浏览代码

Merge branch 'patch-fix-mmap-revert' into patch-add-file-mapping

MemoryShore 11 月之前
父节点
当前提交
c4149d806f
共有 100 个文件被更改,包括 3235 次插入682 次删除
  1. 1062 0
      docs/community/ChangeLog/V0.1.x/V0.1.10.md
  2. 1 0
      docs/community/ChangeLog/index.rst
  3. 1 0
      docs/introduction/build_system.md
  4. 2 2
      docs/kernel/locking/mutex.md
  5. 2 2
      docs/kernel/locking/spinlock.md
  6. 1 1
      kernel/Cargo.toml
  7. 1 1
      kernel/crates/unified-init/src/lib.rs
  8. 2 2
      kernel/src/arch/riscv64/driver/of.rs
  9. 5 6
      kernel/src/arch/riscv64/init/mod.rs
  10. 18 22
      kernel/src/arch/riscv64/interrupt/handle.rs
  11. 7 6
      kernel/src/arch/riscv64/ipc/signal.rs
  12. 12 12
      kernel/src/arch/riscv64/mm/init.rs
  13. 4 5
      kernel/src/arch/riscv64/pci/pci_host_ecam.rs
  14. 5 3
      kernel/src/arch/riscv64/process/idle.rs
  15. 5 5
      kernel/src/arch/riscv64/process/mod.rs
  16. 6 6
      kernel/src/arch/riscv64/process/syscall.rs
  17. 6 8
      kernel/src/arch/riscv64/smp/mod.rs
  18. 2 2
      kernel/src/arch/riscv64/syscall/mod.rs
  19. 5 4
      kernel/src/arch/riscv64/time.rs
  20. 3 2
      kernel/src/arch/x86_64/acpi.rs
  21. 10 11
      kernel/src/arch/x86_64/driver/apic/apic_timer.rs
  22. 7 7
      kernel/src/arch/x86_64/driver/apic/ioapic.rs
  23. 3 3
      kernel/src/arch/x86_64/driver/apic/lapic_vector.rs
  24. 7 7
      kernel/src/arch/x86_64/driver/apic/mod.rs
  25. 5 6
      kernel/src/arch/x86_64/driver/apic/x2apic.rs
  26. 7 6
      kernel/src/arch/x86_64/driver/apic/xapic.rs
  27. 7 7
      kernel/src/arch/x86_64/driver/hpet.rs
  28. 2 2
      kernel/src/arch/x86_64/driver/rtc.rs
  29. 19 19
      kernel/src/arch/x86_64/driver/tsc.rs
  30. 5 6
      kernel/src/arch/x86_64/init/mod.rs
  31. 5 5
      kernel/src/arch/x86_64/interrupt/ipi.rs
  32. 2 2
      kernel/src/arch/x86_64/interrupt/mod.rs
  33. 23 23
      kernel/src/arch/x86_64/interrupt/trap.rs
  34. 20 20
      kernel/src/arch/x86_64/ipc/signal.rs
  35. 6 9
      kernel/src/arch/x86_64/kvm/mod.rs
  36. 3 3
      kernel/src/arch/x86_64/kvm/vmx/mmu.rs
  37. 26 25
      kernel/src/arch/x86_64/kvm/vmx/vcpu.rs
  38. 16 15
      kernel/src/arch/x86_64/kvm/vmx/vmexit.rs
  39. 7 6
      kernel/src/arch/x86_64/kvm/vmx/vmx_asm_wrapper.rs
  40. 7 7
      kernel/src/arch/x86_64/mm/fault.rs
  41. 21 22
      kernel/src/arch/x86_64/mm/mod.rs
  42. 37 5
      kernel/src/arch/x86_64/pci/pci.rs
  43. 3 2
      kernel/src/arch/x86_64/process/idle.rs
  44. 5 5
      kernel/src/arch/x86_64/process/mod.rs
  45. 8 8
      kernel/src/arch/x86_64/process/syscall.rs
  46. 3 3
      kernel/src/arch/x86_64/smp/mod.rs
  47. 4 3
      kernel/src/arch/x86_64/syscall/mod.rs
  48. 11 16
      kernel/src/debug/klog/mm.rs
  49. 5 5
      kernel/src/driver/acpi/mod.rs
  50. 1 1
      kernel/src/driver/acpi/pmtmr.rs
  51. 6 6
      kernel/src/driver/acpi/sysfs.rs
  52. 14 16
      kernel/src/driver/base/block/block_device.rs
  53. 4 4
      kernel/src/driver/base/char/mod.rs
  54. 7 6
      kernel/src/driver/base/device/bus.rs
  55. 18 17
      kernel/src/driver/base/device/dd.rs
  56. 3 2
      kernel/src/driver/base/device/driver.rs
  57. 10 13
      kernel/src/driver/base/device/init.rs
  58. 12 10
      kernel/src/driver/base/device/mod.rs
  59. 3 3
      kernel/src/driver/base/kobject.rs
  60. 3 2
      kernel/src/driver/base/platform/subsys.rs
  61. 2 1
      kernel/src/driver/block/cache/cached_block_device.rs
  62. 6 6
      kernel/src/driver/block/virtio_blk.rs
  63. 27 24
      kernel/src/driver/clocksource/acpi_pm.rs
  64. 1 1
      kernel/src/driver/clocksource/timer_riscv.rs
  65. 11 13
      kernel/src/driver/disk/ahci/ahcidisk.rs
  66. 12 14
      kernel/src/driver/disk/ahci/mod.rs
  67. 3 2
      kernel/src/driver/firmware/efi/fdt.rs
  68. 16 15
      kernel/src/driver/firmware/efi/init.rs
  69. 3 2
      kernel/src/driver/firmware/efi/memmap.rs
  70. 4 4
      kernel/src/driver/firmware/efi/mod.rs
  71. 11 10
      kernel/src/driver/firmware/efi/tables.rs
  72. 5 4
      kernel/src/driver/input/ps2_mouse/ps_mouse_device.rs
  73. 3 2
      kernel/src/driver/input/ps2_mouse/ps_mouse_driver.rs
  74. 2 1
      kernel/src/driver/input/serio/i8042/mod.rs
  75. 3 2
      kernel/src/driver/input/serio/subsys.rs
  76. 3 2
      kernel/src/driver/irqchip/riscv_intc.rs
  77. 18 17
      kernel/src/driver/irqchip/riscv_sifive_plic.rs
  78. 7 8
      kernel/src/driver/net/e1000e/e1000e.rs
  79. 2 2
      kernel/src/driver/net/e1000e/e1000e_driver.rs
  80. 8 8
      kernel/src/driver/net/virtio_net.rs
  81. 19 22
      kernel/src/driver/open_firmware/fdt.rs
  82. 160 0
      kernel/src/driver/pci/attr.rs
  83. 109 0
      kernel/src/driver/pci/dev_id.rs
  84. 219 0
      kernel/src/driver/pci/device.rs
  85. 83 0
      kernel/src/driver/pci/driver.rs
  86. 18 12
      kernel/src/driver/pci/ecam.rs
  87. 7 0
      kernel/src/driver/pci/mod.rs
  88. 57 33
      kernel/src/driver/pci/pci.rs
  89. 3 2
      kernel/src/driver/pci/pci_irq.rs
  90. 194 0
      kernel/src/driver/pci/raw_device.rs
  91. 65 42
      kernel/src/driver/pci/root.rs
  92. 191 0
      kernel/src/driver/pci/subsys.rs
  93. 30 0
      kernel/src/driver/pci/test/mod.rs
  94. 236 0
      kernel/src/driver/pci/test/pt_device.rs
  95. 171 0
      kernel/src/driver/pci/test/pt_driver.rs
  96. 2 1
      kernel/src/driver/rtc/class.rs
  97. 2 1
      kernel/src/driver/serial/serial8250/mod.rs
  98. 2 1
      kernel/src/driver/tty/tty_driver.rs
  99. 3 2
      kernel/src/driver/tty/virtual_terminal/virtual_console.rs
  100. 2 1
      kernel/src/driver/video/fbdev/base/fbcon/framebuffer_console.rs

+ 1062 - 0
docs/community/ChangeLog/V0.1.x/V0.1.10.md

@@ -0,0 +1,1062 @@
+# V0.1.10
+
+:::{note}
+本文作者:龙进 <longjin@DragonOS.org>
+
+DragonOS官方论坛:[bbs.dragonos.org.cn](https://bbs.dragonos.org.cn)
+
+2024年5月13日
+:::
+
+## 简介
+
+&emsp;&emsp;本次版本更新,引入了42个feature类型的PR,24个bug修复,5个文档更新,以及一些软件移植、ci相关的内容。
+
+&emsp;&emsp;当前版本核心看点:
+
+- 对调度子系统进行了重构
+- 能在riscv64下运行到hello world应用程序
+- 内存管理子系统引入了匿名页反向映射、写时拷贝以及延迟分配的特性
+- 文件系统引入了大量的新的系统接口
+- 实现了pty,并能运行简单的ssh服务端
+
+
+## 赞助商列表
+
+- **[中国雅云](https://yacloud.net)** 雅安大数据产业园为DragonOS提供了云服务器支持。
+
+## 更新内容-内核
+
+- feat(fs): 实现了sys_rename (#578)
+- feat(fs): 实现get_pathname (#615)
+- feat(kernel): 实现uname系统调用 (#614)
+- feat(fs): 添加mount系统调用 (#561)
+- feat(smp): 重写SMP模块 (#633)
+- feat(fs): 添加Statx系统调用 (#632)
+- feat(riscv64): 添加flush tlb的ipi (#636)
+- feat(fs): 实现SYS_LINK和SYS_LINKAT (#611)
+- fix(fs): mkdir输出错误信息; 
+- fix(clippy): 修复内核的clippy检查报错 (#637)
+- feat(net): 实现socketpair (#576)
+- feat(process/riscv): 进程管理初始化 (#654)
+- fix(time): 修复clock_gettime返回类型错误,修复小时间间隔duration返回0问题 (#664)
+- fix(driver/base): 把Device trait的set_class改为设置Weak指针,以避免循环引用问题。 (#666)
+- feat(textui): 支持绘制24位深和16位深显示缓冲区 (#640)
+- fix(driver/tty): 修复tty设备显示在/sys目录下的bug (#668)
+- feat(fs): 新加结构体POSIXSTATFS与SuperBlock用于处理statfs系统调用 (#667)
+- feat(driver/rtc):实现了rtc的抽象,并且把x86的cmos rtc接入到设备驱动模型 (#674)
+- fix(net): 修复udp bind的时候,对port0处理不正确的问题(#676)
+- fix(fs/ramfs): 修复了ramfs中move_to未更新parent字段的bug (#673)
+- feat(mm): 实现页面反向映射 (#670)
+- fix(misc): 修复get_ramdom的长度错误问题() (#677)
+- feat(process/riscv): riscv64: switch process (#678)
+- fix(misc): 使nproc可以正确获取到cpu核心数 (#689)
+- fix(time): 修复jiffy时钟过快问题,启用gettimeofday测试,修改mount测试 (#680)
+- feat(driver/pty): 实现pty,附带测试程序 (#685)
+- feat(process/riscv): 实现copy-thread (#696)
+- feat(sched): 重写调度模块 (#679)
+- fix(riscv): 把内核编译target改为riscv64gc & 获取time csr的频率 & 修正浮点保存与恢复的汇编的问题 (#699)
+- feat(lock): 实现robust futex (#682)
+- feat(fs): BlockCache-read cache支持 (#521)
+- feat(mm): 实现SystemV共享内存 (#690)
+- chore(tools): add bootstrap support for Centos/RHEL8/fedora (#713)
+- feat(driver/pty): 完善pty,目前pty能够支持ssh (#708)
+- fix(smp): 修复smp启动的时候,损坏0号核心的idle进程的内核栈的问题 (#711)
+- feat(driver/riscv): 初始化riscv-sbi-timer (#716)
+- doc: Update DragonOS description and introduction (#717)
+- feat(riscv): 让riscv64能正常切换进程,并运行完所有的initcall (#721)
+- feat(net): 实现tcp backlog功能 (#714)
+- feat(mm): 添加slab内存分配器 (#683)
+- feat(fs): 引入Umount系统调用 (#719)
+- doc: Update build instructions for riscv64 architecture (#725)
+- fix(fs): socket统一改用`GlobalSocketHandle`,并且修复fcntl SETFD的错误 (#730)
+- feat: alarm系统调用实现 (#710)
+- feat(tty): add dummy console (#735)
+- fix(driver/pci): pci: 统一使用ecam root (#744)
+- feat(driver/pci): pci: 添加pci root manager来管理pci root,并使得riscv能够正常扫描pci设备. (#745)
+- build: 将smoltcp升级到0.11.0版本 (#740)
+- fix(unified-init): 修复unified-init导致cargo check失败的问题 (#747)
+- chore: Update virtio-drivers to commit 61ece509c4 and modify max_queue_size implementation (#748)
+- feat(net): 实现raw socket的poll (#739)
+- feat(mm): 实现缺页中断处理,支持页面延迟分配和写时拷贝,以及用户栈自动拓展 (#715)
+- feat(driver): 把virtio添加到sysfs (#752)
+- fix(dog): 添加CC环境变量,解决编译时找不到musl-gcc的问题 (#753)
+- doc(community): add description of conventional commit standard (#754)
+- feat(driver/virtio): riscv: 添加virtio-blk driver,并在riscv下能够正确挂载FAT32 (#761)
+- feat(fs): add sys_dup3 (#755)
+- feat(riscv): riscv下能够运行hello world用户程序 (#770)
+- feat(sched): add sched_yield (#766)
+- refactor(process): 调整arch_switch_to_user函数,把riscv和x86_64的共用逻辑抽取出来。 (#773)
+- feat(driver/acpi_pm): Implement ACPI PM Timer (#772)
+- chore: 适配dadk 0.1.11 (#777)
+- fix(libs/lib_ui): fix the display errors when system initialize (#779)
+- fix(riscv/process): 把riscv的调度时钟节拍率与HZ同步,并且修复切换到用户态的时候忘了在内核态关中断的bug (#780)
+- fix: (riscv/timer): 修复riscv下没有更新墙上时钟以及没有处理软中断的bug (#783)
+- feat(mm): add slab usage calculation (#768)
+- feat(bitmap): Add bit and for AllocBitMap (#793)
+- fix(mm): 修复vma映射标志错误 (#801)
+- feat:(riscv/intr) 实现riscv plic驱动,能处理外部中断 (#799)
+- doc(sched):调度子系统文档即cfs文档 (#807)
+- fix(net): Fix TCP Unresponsiveness and Inability to Close Connections (#791)
+- fix: disable mm debug log to prevent system lockup due to thingbuf issue (#808)
+- feat(driver/pci): add pci bus into sysfs (#792)
+- doc: Add Gentoo Linux In build_system.md (#810)
+
+## 更新内容-用户环境
+
+### 新特性/新应用移植
+
+- 添加core utils到系统 (#624)
+- 移植dns查询工具dog的--tcp功能 (#652)
+
+
+## 更新内容-CI
+
+- 引入triagebot对issue和PR进行分类
+- 添加clippy检测的自动化工作流 (#649)
+- ci: import issue checker (#750)
+- ci: update the match regex of issue checker (#784)
+- ci: 添加支持gentoo系统的一键安装脚本 (#809)
+
+## 源码、发布版镜像下载
+
+&emsp;&emsp;您可以通过以下方式获得源代码:
+
+### 通过Git获取
+
+- 您可以访问DragonOS的仓库获取源代码:[https://github.com/DragonOS-Community/DragonOS](https://github.com/DragonOS-Community/DragonOS)
+- 您可以访问[https://github.com/DragonOS-Community/DragonOS/releases](https://github.com/DragonOS-Community/DragonOS/releases)下载发布版的代码。
+
+### 通过DragonOS软件镜像站获取
+
+&emsp;&emsp;为解决国内访问GitHub慢、不稳定的问题,同时为了方便开发者们下载DragonOS的每个版本的代码,我们特意搭建了镜像站,您可以通过以下地址访问镜像站:
+
+&emsp;&emsp;您可以通过镜像站获取到DragonOS的代码压缩包,以及编译好的可运行的磁盘镜像。
+
+- [https://mirrors.DragonOS.org.cn](https://mirrors.DragonOS.org.cn)
+- [https://git.mirrors.DragonOS.org.cn](https://git.mirrors.DragonOS.org.cn)
+
+## 开放源代码声明
+
+:::{note}
+为促进DragonOS项目的健康发展,DragonOS以GPLv2开源协议进行发布。所有能获得到DragonOS源代码以及相应的软件制品(包括但不限于二进制副本、文档)的人,都能享有我们通过GPLv2协议授予您的权利,同时您也需要遵守协议中规定的义务。
+
+这是一个相当严格的,保护开源软件健康发展,不被侵占的协议。
+
+对于大部分的善意的人们而言,您不会违反我们的开源协议。
+
+我们鼓励DragonOS的自由传播、推广,但是请确保所有行为没有侵犯他人的合法权益,也没有违反GPLv2协议。
+
+请特别注意,对于违反开源协议的,尤其是**商业闭源使用以及任何剽窃、学术不端行为将会受到严肃的追责**。(这是最容易违反我们的开源协议的场景)。
+
+并且,请注意,按照GPLv2协议的要求,基于DragonOS修改或二次开发的软件,必须同样采用GPLv2协议开源,并标明其基于DragonOS进行了修改。亦需保证这些修改版本的用户能方便的获取到DragonOS的原始版本。
+
+您必须使得DragonOS的开发者们,能够以同样的方式,从公开渠道获取到您二次开发的版本的源代码,否则您将违反GPLv2协议。
+
+关于协议详细内容,还敬请您请阅读项目根目录下的**LICENSE**文件。请注意,按照GPLv2协议的要求,**只有英文原版才具有法律效力**。任何翻译版本都仅供参考。
+:::
+
+### 开源软件使用情况
+
+&emsp;&emsp;DragonOS在开发的过程中,参考了Linux社区的一些设计,或者引入了他们的部分思想,亦或是受到了他们的启发。我们在这里对Linux社区以及Linux社区的贡献者们致以最衷心的感谢!
+
+## 当前版本的所有提交记录
+
+```text
+commit 9a0802fd2ddda39e96342997abbfc30bf65f1f0e
+Author: donjuanplatinum <113148619+donjuanplatinum@users.noreply.github.com>
+Date:   Mon May 13 15:36:23 2024 +0800
+
+    doc: Add Gentoo Linux In build_system.md (#810)
+    
+    * 增加安装文档中的Gentoo Linux提示
+
+commit 1f4877a4c512eb5ad232436128a0c52287b39aaa
+Author: 曾俊 <110876916+ZZJJWarth@users.noreply.github.com>
+Date:   Mon May 13 15:27:08 2024 +0800
+
+    feat(driver/pci): add pci bus into sysfs (#792)
+    
+    把pci设备加入sysfs
+
+commit 1df85daf8f1b4426fe09d489d815997cdf989a87
+Author: donjuanplatinum <113148619+donjuanplatinum@users.noreply.github.com>
+Date:   Sun May 12 22:58:59 2024 +0800
+
+    添加支持gentoo系统的一键安装脚本 (#809)
+
+commit 352ee04918f4585ad4f8a896ca6e18b1ef7d7934
+Author: LoGin <longjin@DragonOS.org>
+Date:   Sat May 11 18:02:13 2024 +0800
+
+    fix: disable mm debug log to prevent system lockup due to thingbuf issue (#808)
+
+commit 37cef00bb404c9cc01509c12df57548029967dc2
+Author: Samuel Dai <samuka007@qq.com>
+Date:   Sat May 11 17:17:43 2024 +0800
+
+    fix(net): Fix TCP Unresponsiveness and Inability to Close Connections (#791)
+    
+    * fix(net): Improve stability. 为RawSocket与UdpSocket实现close时调用close方法,符合smoltcp的行为。为SocketInode实现drop,保证程序任何情况下退出时都能正确close对应socket, 释放被占用的端口。
+    
+    * fix(net): Correct socket close behavior.
+
+commit b941261d943fac38d3154495e19ec99c90ebea8d
+Author: GnoCiYeH <heyicong@dragonos.org>
+Date:   Tue May 7 22:01:01 2024 +0800
+
+    docs(sched):调度子系统文档即cfs文档 (#807)
+    
+    * 调度子系统文档以及cfs文档
+
+commit 0102d69fdd231e472d7bb3d609a41ae56a3799ee
+Author: LoGin <longjin@DragonOS.org>
+Date:   Wed May 1 21:11:32 2024 +0800
+
+    feat:(riscv/intr) 实现riscv plic驱动,能处理外部中断 (#799)
+    
+    * feat:(riscv/intr) 实现riscv plic驱动,能处理外部中断
+    
+    - 实现riscv plic驱动,能处理外部中断
+    - 能收到virtio-blk的中断
+    - 实现fasteoi interrupt handler
+
+commit 17dc558977663433bd0181aa73ad131a1a265c1f
+Author: MemoryShore <105195940+MemoryShore@users.noreply.github.com>
+Date:   Wed May 1 21:09:51 2024 +0800
+
+    修复vma映射标志错误 (#801)
+
+commit 7db6e06354328ea7c6164723f504e8ba58d0c4a4
+Author: LoGin <longjin@DragonOS.org>
+Date:   Tue Apr 30 18:45:01 2024 +0800
+
+    feat(bitmap): Add bit and for AllocBitMap (#793)
+
+commit 7401bec5e3c42015399a46e29c370abe7c7388b5
+Author: laokengwt <143977175+laokengwt@users.noreply.github.com>
+Date:   Mon Apr 29 23:03:33 2024 +0800
+
+    feat(mm): add slab usage calculation (#768)
+    
+    * Add slab free space calculation and add it to freeram of sysinfo
+
+commit bde4a334c1ff2ae27989de4f6f8b45f5154b684d
+Author: 曾俊 <110876916+ZZJJWarth@users.noreply.github.com>
+Date:   Mon Apr 29 18:55:17 2024 +0800
+
+    修复了未初始化时ui显示模块内存越界的问题,优化了代码结构 (#789)
+
+commit 0722a06a09ed52cb980a6147123453f86d0ea267
+Author: LoGin <longjin@DragonOS.org>
+Date:   Sun Apr 28 19:40:09 2024 +0800
+
+    fix: (riscv/timer): 修复riscv下没有更新墙上时钟以及没有处理软中断的bug (#783)
+
+commit ab53b2eb75fe79167aa100e655b3589ee306f793
+Author: Chiichen <chiichen@qq.com>
+Date:   Sun Apr 28 19:37:58 2024 +0800
+
+    ci: update the match regex of issue checker (#784)
+    
+    The previous regex can not successfully match the pattern like `feat(driver/pci)`, which has a slash in the scope
+
+commit 942cf26b48c8b024a6fa7867bb0c8ae39bb1ae09
+Author: LoGin <longjin@DragonOS.org>
+Date:   Sun Apr 28 16:49:40 2024 +0800
+
+    fix(riscv/process): 把riscv的调度时钟节拍率与HZ同步,并且修复切换到用户态的时候忘了在内核态关中断的bug (#780)
+
+commit 13b057cc0fda0cf9630c98d246937b85fa01a7c9
+Author: 曾俊 <110876916+ZZJJWarth@users.noreply.github.com>
+Date:   Sun Apr 28 16:49:19 2024 +0800
+
+    fix(libs/lib_ui): fix the display errors when system initialize (#779)
+    
+    * 修复了系统初启动时会花屏的bug
+
+commit 182b778a3ca8c633b605ae7dd90a5e9f1131cc6d
+Author: LoGin <longjin@DragonOS.org>
+Date:   Sun Apr 28 13:39:51 2024 +0800
+
+    chore: 适配dadk 0.1.11 (#777)
+    
+    * chore: 适配dadk 0.1.11
+
+commit dd8e74ef0d7f91a141bd217736bef4fe7dc6df3d
+Author: Mingtao Huang <114841534+1037827920@users.noreply.github.com>
+Date:   Sun Apr 28 13:25:12 2024 +0800
+
+    feat(driver/acpi_pm): Implement ACPI PM Timer (#772)
+    
+    * feat: Implement ACPI PM Timer
+
+commit f75cb0f8ed754d94c3b2924519b785db3321c1d9
+Author: LoGin <longjin@DragonOS.org>
+Date:   Sat Apr 27 15:35:24 2024 +0800
+
+    refactor(process): 调整arch_switch_to_user函数,把riscv和x86_64的共用逻辑抽取出来。 (#773)
+    
+    * refactor(process): Extract common logic for riscv and x86_64 in arch_switch_to_user to run_init_process
+    
+    调整arch_switch_to_user函数,把riscv和x86_64的共用逻辑抽取出来。写成run_init_process函数,并且能够尝试运行多个不同的init程序,直到某个运行成功
+
+commit 173c4567cf4fb2276ef3f4614b69da7913fc8381
+Author: zwb0x00 <163394849+zwb0x00@users.noreply.github.com>
+Date:   Fri Apr 26 15:33:29 2024 +0800
+
+    feat(sched): add sched_yield (#766)
+    
+    * 实现sched_yield系统调用
+
+commit 471d65cf158c9bf741c21f5d0ab92efe7bf1c3d4
+Author: LoGin <longjin@DragonOS.org>
+Date:   Fri Apr 26 11:59:47 2024 +0800
+
+    feat(riscv): riscv下能够运行hello world用户程序 (#770)
+    
+    * feat(riscv): riscv下能够运行hello world用户程序
+
+commit 40348dd8d5a008ecc9eb3aab931933e4eba0e6da
+Author: zwb0x00 <163394849+zwb0x00@users.noreply.github.com>
+Date:   Tue Apr 23 19:35:02 2024 +0800
+
+    feat(fs): add sys_dup3 (#755)
+    
+    * feat(fs): add sys_dup3
+
+commit 3b799d13beeb80900d728937308e47f8011835e1
+Author: LoGin <longjin@DragonOS.org>
+Date:   Tue Apr 23 19:14:41 2024 +0800
+
+    Create FUNDING.yml (#763)
+
+commit 731bc2b32d7b37298883d7a15b6dca659b436ee4
+Author: LoGin <longjin@DragonOS.org>
+Date:   Tue Apr 23 17:19:54 2024 +0800
+
+    feat(virtio): riscv: 添加virtio-blk driver,并在riscv下能够正确挂载FAT32 (#761)
+
+commit 0c1ef30087d10035c256fed08097f5897041979d
+Author: Chiichen <chiichen@qq.com>
+Date:   Tue Apr 23 00:27:05 2024 +0800
+
+    docs(community): add description of conventional commit standard (#754)
+    
+    * docs(community): add description of conventional commit standard
+    
+    * docs: add index
+
+commit 70c991af204167db26ec1d9494efcff010893482
+Author: laokengwt <143977175+laokengwt@users.noreply.github.com>
+Date:   Mon Apr 22 17:40:03 2024 +0800
+
+    fix(dog): 添加CC环境变量,解决编译时找不到musl-gcc的问题 (#753)
+
+commit e32effb1507773d32c216d9e77b963786e275c06
+Author: LoGin <longjin@DragonOS.org>
+Date:   Mon Apr 22 15:11:47 2024 +0800
+
+    feat(driver): 把virtio添加到sysfs (#752)
+
+commit a17651b14b86dd70655090381db4a2f710853aa1
+Author: MemoryShore <105195940+MemoryShore@users.noreply.github.com>
+Date:   Mon Apr 22 15:10:47 2024 +0800
+
+    feat(mm): 实现缺页中断处理,支持页面延迟分配和写时拷贝,以及用户栈自动拓展 (#715)
+    
+    * 实现缺页中断处理
+    
+    * 完善页表拷贝逻辑
+    
+    * 优化代码结构
+    
+    * 完善缺页异常信息
+    
+    * 修改大页映射逻辑
+    
+    * 修正大页映射错误
+    
+    * 添加缺页中断支持标志
+    
+    * 实现用户栈自动拓展功能
+
+commit cb02d0bbc213867ac845b7e8a0fb337f723d396a
+Author: Chiichen <chiichen@qq.com>
+Date:   Sun Apr 21 23:23:21 2024 +0800
+
+    ci: import issue checker (#750)
+    
+    * ci: supprot auto tag on pull request
+    
+    * ci: update issue checker config
+    
+    * ci: update issue checker & block merge while
+
+commit 93c379703e3be210799953bc0686d02f97119b39
+Author: sun5etop <146408999+sun5etop@users.noreply.github.com>
+Date:   Sun Apr 21 13:36:44 2024 +0800
+
+    feat(net): 实现raw socket的poll (#739)
+    
+    feat(net): 实现raw socket的poll
+
+commit b502fbf0b9c575a4c04e103d0fb708c4e383ab06
+Author: LoGin <longjin@DragonOS.org>
+Date:   Sun Apr 21 13:30:29 2024 +0800
+
+    chore: Update virtio-drivers to commit 61ece509c4 and modify max_queue_size implementation (#748)
+
+commit d770de5d53ce9b598fb0024800a347b081f92a73
+Author: LoGin <longjin@DragonOS.org>
+Date:   Sun Apr 21 13:12:31 2024 +0800
+
+    fix: 修复unified-init导致cargo check失败的问题 (#747)
+
+commit 881ff6f95e4addc373d815d66cb912bf721c20e6
+Author: yuyi2439 <68320855+yuyi2439@users.noreply.github.com>
+Date:   Sun Apr 21 11:39:00 2024 +0800
+
+    将smoltcp升级到0.11.0版本 (#740)
+
+commit 370472f7288b568c7b80815f5b150daf4496446c
+Author: LoGin <longjin@DragonOS.org>
+Date:   Sun Apr 21 11:27:36 2024 +0800
+
+    pci: 添加pci root manager来管理pci root,并使得riscv能够正常扫描pci设备. (#745)
+    
+    * pci: 添加pci root manager来管理pci root.
+    pci: 使得riscv能够正常扫描pci设备.
+    
+    * doc: 添加注释
+
+commit 2709e017d0d216d61b2caed3c7286459de7794c7
+Author: LoGin <longjin@DragonOS.org>
+Date:   Sat Apr 20 18:31:56 2024 +0800
+
+    pci: 统一使用ecam root (#744)
+
+commit 418ad41fd84c15ed7e132e56970150ac38fc24a9
+Author: LoGin <longjin@DragonOS.org>
+Date:   Wed Apr 17 10:03:22 2024 +0800
+
+    Feat(tty): add dummy console (#735)
+    
+    使得riscv能暂时完成stdio_init(将来需要实现riscv的串口console)
+
+commit 1012552dea71bf04cf1d329d570c4c9ca9b2a2f8
+Author: Saga1718 <161323888+Saga1718@users.noreply.github.com>
+Date:   Tue Apr 16 21:37:42 2024 +0800
+
+    删除无用的hid代码 (#734)
+
+commit fbd63a301c5648f906eeb802f10ac03518ba1264
+Author: SMALLC <121806694+SMALLC04@users.noreply.github.com>
+Date:   Tue Apr 16 21:34:36 2024 +0800
+
+    feat: alarm系统调用实现 (#710)
+    
+    * alarm系统调用实现
+
+commit d623e90231ef6a31d091c3f611c0af3a83d3343b
+Author: GnoCiYeH <heyicong@dragonos.org>
+Date:   Mon Apr 15 22:01:32 2024 +0800
+
+    socket统一改用`GlobalSocketHandle`,并且修复fcntl SETFD的错误 (#730)
+    
+    * socket统一改用`GlobalSocketHandle`,并且修复fcntl SETFD的错误
+    
+    ---------
+    
+    Co-authored-by: longjin <longjin@DragonOS.org>
+
+commit 7162a8358d94c7799dd2b5300192b6a794b23d79
+Author: LoGin <longjin@DragonOS.org>
+Date:   Mon Apr 15 13:20:46 2024 +0800
+
+    doc: Update build instructions for riscv64 architecture (#725)
+
+commit 1074eb34e784aa2adfc5b9e0d89fa4b7e6ea03ef
+Author: Samuel Dai <samuka007@qq.com>
+Date:   Mon Apr 15 13:02:04 2024 +0800
+
+    feat(filesystem): 引入Umount系统调用 (#719)
+    
+    * feat(filesystem): 引入Umount系统调用
+    
+    * 将所有ENOSYS误用更正
+    
+    * 修复了一个使同一个挂载点可以挂载2个文件系统的bug
+    
+    * 统一注释,增强程序稳定性,统一接口。注意:Umount时在fatfs的路径要使用大写,此受限于当前文件系统设计。
+
+commit ceeb2e943ca7645609920ec7ad8bfceea2b13de6
+Author: laokengwt <143977175+laokengwt@users.noreply.github.com>
+Date:   Mon Apr 15 12:51:14 2024 +0800
+
+    feat(mm): 添加slab内存分配器 (#683)
+    
+    feat(mm): 添加slab内存分配器
+    ---------
+    
+    Co-authored-by: longjin <longjin@DragonOS.org>
+
+commit c719ddc6312acd7976e0f6fd449a94ff9abad5a6
+Author: Saga1718 <161323888+Saga1718@users.noreply.github.com>
+Date:   Sun Apr 14 23:51:47 2024 +0800
+
+    feat(net): 实现tcp backlog功能 (#714)
+    
+    * feat:实现tcp的backlog功能
+
+commit 9621ab16ef27bc94f223e6254fafb9bb07d46d57
+Author: LoGin <longjin@DragonOS.org>
+Date:   Sun Apr 14 20:39:20 2024 +0800
+
+    让riscv64能正常切换进程,并运行完所有的initcall (#721)
+
+commit 9fab312ea9921618629924ab15c28c2d255b21c6
+Author: LoGin <longjin@DragonOS.org>
+Date:   Fri Apr 12 15:27:44 2024 +0800
+
+    Update DragonOS description and introduction (#717)
+
+commit f049d1af01da7b92f312245ed411b22475b76065
+Author: LoGin <longjin@DragonOS.org>
+Date:   Fri Apr 12 14:46:47 2024 +0800
+
+    初始化riscv-sbi-timer (#716)
+
+commit 3959e94df38073fdb80b199777015f95611ba05f
+Author: 曾俊 <110876916+ZZJJWarth@users.noreply.github.com>
+Date:   Wed Apr 10 19:00:32 2024 +0800
+
+    bugfix: 修复smp启动的时候,损坏0号核心的idle进程的内核栈的问题 (#711)
+    
+    ---------
+    
+    Co-authored-by: longjin <longjin@DragonOS.org>
+    Co-authored-by: heyicong <heyicong@dragonos.org>
+
+commit 9365e8017b39582eca620ba93c64f1b3c87c73d4
+Author: GnoCiYeH <heyicong@dragonos.org>
+Date:   Wed Apr 10 19:00:12 2024 +0800
+
+    完善pty,目前pty能够支持ssh (#708)
+
+commit 4b0170bd6bb374d0e9699a0076cc23b976ad6db7
+Author: Chiichen <chiichen@qq.com>
+Date:   Wed Apr 10 18:58:54 2024 +0800
+
+    chore(tools): add bootstrap support for Centos/RHEL8/fedora (#713)
+    
+    Co-authored-by: kejianchi <kejianchi@tencent.com>
+
+commit 15b94df01adc7e8931961b9b9a89db4e7c014b64
+Author: Jomo <xuzihao@dragonos.org>
+Date:   Wed Apr 10 10:58:07 2024 +0800
+
+    add xuzihao (#712)
+
+commit 6fc066ac11d2f9a3ac629d57487a6144fda1ac63
+Author: Jomo <2512364506@qq.com>
+Date:   Sun Apr 7 14:04:19 2024 +0800
+
+    实现SystemV共享内存 (#690)
+    
+    * 实现SystemV共享内存
+    
+    * 测试shm
+    
+    * 添加测试程序
+    
+    * 完善细节
+    
+    * 修正shm的时间数据错误的问题
+    
+    * fix: devfs的metadata权限为0x777的错误
+    
+    ---------
+    
+    Co-authored-by: longjin <longjin@DragonOS.org>
+
+commit eb49bb993a39964f92494ec3effafed3fb9adfd8
+Author: 曾俊 <110876916+ZZJJWarth@users.noreply.github.com>
+Date:   Sun Apr 7 14:03:51 2024 +0800
+
+    BlockCache-read cache支持 (#521)
+    
+    支持block cache的读缓存
+
+commit 06560afa2aa4db352526f4be8b6262719b8b3eac
+Author: hmt <114841534+1037827920@users.noreply.github.com>
+Date:   Sat Apr 6 22:26:34 2024 +0800
+
+    Patch feat robust futex (#682)
+    
+    * feat: 实现robust lock机制
+    
+    * 前面更改vscode,修改回来
+    
+    * 修改dadk的路径
+    
+    * 提交.gitnore和.cargo,删除LICENSE,修改README
+    
+    * 修改一个warn
+    
+    * 删除.rustc_info.json
+    
+    * 删除target文件夹
+    
+    * 恢复DragonOS的LICENSE,删除Cargo.lock
+    
+    * 将校验用户空间地址的代码写入函数内;将部分match分支用ok_or代替
+    
+    * 修改wakeup函数获取running queue时unwrap一个None值发生panic
+    
+    * 测试程序使用syscalls库进行系统调用
+
+commit 23ef2b33d1e3cfd2506eb7449a33df4ec42f11d3
+Author: LoGin <longjin@DragonOS.org>
+Date:   Sat Apr 6 22:13:26 2024 +0800
+
+    riscv: 把内核编译target改为riscv64gc & 获取time csr的频率 & 修正浮点保存与恢复的汇编的问题 (#699)
+    
+    * 1. 把内核编译target改为riscv64gc
+    2. fix: 修正浮点保存与恢复的汇编的问题
+    
+    * riscv: 获取time csr的频率
+
+commit f0c87a897fe813b7f06bf5a9e93c43ad9519dafd
+Author: GnoCiYeH <heyicong@dragonos.org>
+Date:   Fri Apr 5 17:54:48 2024 +0800
+
+    重写调度模块 (#679)
+    
+    ## PR:重写调度模块
+    ---
+    ### 完成的部分
+    - 实现cfs调度策略
+    - 搭建框架,后续功能可以迭代开发
+    - 目前能跑,未测试性能
+    
+    ### 需要后续接力的部分
+    - 实现组内调度(task_group)
+    - 实现跨核负载均衡(pelt算法)
+    - 接入sysfs,实现参数动态调节(sched_stat等)
+    - nice值以及priority等参数的设置及调优
+
+commit e8eab1ac824e1b1e638e50debb8326dfed4f05e5
+Author: LoGin <longjin@DragonOS.org>
+Date:   Fri Apr 5 16:37:08 2024 +0800
+
+    riscv: copy-thread (#696)
+
+commit dfe53cf087ef4c7b6db63d992906b062dc63e93f
+Author: GnoCiYeH <heyicong@dragonos.org>
+Date:   Fri Apr 5 00:21:55 2024 +0800
+
+    实现pty,附带测试程序 (#685)
+    
+    * 实现pty,附带测试程序
+    
+    * fmt ** clippy
+    
+    * 将file层的锁粒度缩小,从而不使用no_preempt。更改pipe在sleep部分的bug
+    
+    * 修复拼写错误
+
+commit b8ed38251dc255b0c525801b5dbf37d3b0d0d61e
+Author: Donkey Kane <109840258+xiaolin2004@users.noreply.github.com>
+Date:   Fri Apr 5 00:06:26 2024 +0800
+
+    修复jiffy时钟过快问题,启用gettimeofday测试,修改mount测试 (#680)
+    
+    1. 把clock tick rate与hpet频率关联起来
+    2. 修复墙上时间同步错误的问题
+    3. 启用时间watch dog.
+    4. 修复时间流逝速度异常
+    
+    ---------
+    
+    Co-authored-by: longjin <longjin@DragonOS.org>
+
+commit 9430523b465b19db4dd476e9fd3038bdc2aa0c8d
+Author: yuyi2439 <68320855+yuyi2439@users.noreply.github.com>
+Date:   Thu Apr 4 12:41:19 2024 +0800
+
+    使nproc可以正确获取到cpu核心数 (#689)
+
+commit 9b96c5b547c337502db7ec820312f119f95eece1
+Author: LoGin <longjin@DragonOS.org>
+Date:   Sun Mar 31 22:53:01 2024 +0800
+
+    riscv64: switch process (#678)
+    
+    * riscv64: switch process
+    
+    * fixname
+
+commit 7d580ef99d2a52250b384afd49c7f87ab66a8c84
+Author: Val213 <112376067+val213@users.noreply.github.com>
+Date:   Sun Mar 31 18:01:32 2024 +0800
+
+    修复get_ramdom的长度错误问题() (#677)
+
+commit 56cc4dbe27e132aac5c61b8bd4f4ec9a223b49ee
+Author: Jomo <2512364506@qq.com>
+Date:   Sun Mar 31 16:33:49 2024 +0800
+
+    实现页面反向映射 (#670)
+    
+    * 实现页面反向映射
+    
+    * 完善PAGE_MANAGER初始化时机 && 封装lock函数 && 删掉过时注释
+
+commit 924d64de8def99488f57dc618de763f7aca4a68b
+Author: BrahmaMantra <140599389+BrahmaMantra@users.noreply.github.com>
+Date:   Sun Mar 31 15:19:12 2024 +0800
+
+    修复了ramfs中move_to未更新parent字段的bug (#673)
+    
+    修复了ramfs中move_to未更新parent字段的bug
+    
+    ---------
+    
+    Co-authored-by: Samuel Dai <samuka007@qq.com>
+
+commit 9d9a09841ce2d650a41fed776916c0a11d52f92e
+Author: sun5etop <146408999+sun5etop@users.noreply.github.com>
+Date:   Sun Mar 31 15:11:10 2024 +0800
+
+    修复udp bind的时候,对port0处理不正确的问题(#676)
+
+commit da152319797436368304cbc3f85a3b9ec049134b
+Author: LoGin <longjin@DragonOS.org>
+Date:   Thu Mar 28 00:28:13 2024 +0800
+
+    实现了rtc的抽象,并且把x86的cmos rtc接入到设备驱动模型 (#674)
+    
+    * 实现了rtc的抽象,并且把x86的cmos rtc接入到设备驱动模型。
+
+commit 597ecc08c2444dcc8f527eb021932718b69c9cc5
+Author: TTaq <103996388+TTaq@users.noreply.github.com>
+Date:   Tue Mar 26 18:28:26 2024 +0800
+
+    新加结构体POSIXSTATFS与SuperBlock用于处理statfs系统调用 (#667)
+    
+    * 新加结构体POSIXSTATFS与SuperBlock用于处理statfs系统调用
+
+commit 0cb807346cb3c47924538585087d9fc846cf5e6f
+Author: LoGin <longjin@DragonOS.org>
+Date:   Tue Mar 26 18:26:02 2024 +0800
+
+    修复tty设备显示在/sys目录下的bug (#668)
+
+commit 2755467c790d6510fa97cbf052ce8e91ad1372c6
+Author: 曾俊 <110876916+ZZJJWarth@users.noreply.github.com>
+Date:   Mon Mar 25 16:39:36 2024 +0800
+
+    支持绘制24位深和16位深显示缓冲区 (#640)
+    
+    * 修复了初始化时显示,边界条件的一个bug
+    
+    * 解决了内存未初始前字体显示的兼容性问题
+    * 支持绘制24位深和16位深显示缓冲区
+
+commit 4256da7fb6ad25a3caab6f656607aaf047cb6446
+Author: LoGin <longjin@DragonOS.org>
+Date:   Mon Mar 25 15:47:05 2024 +0800
+
+    把Device trait的set_class改为设置Weak指针,以避免循环引用问题。 (#666)
+
+commit 5c20e05a2eb82da6dd73104fcf51d538500c2856
+Author: LoGin <longjin@DragonOS.org>
+Date:   Mon Mar 25 13:59:00 2024 +0800
+
+    修改bug report模版label (#665)
+
+commit 7c958c9ef0cd25eb15abb21d0d3420aac1c67c88
+Author: Val213 <112376067+val213@users.noreply.github.com>
+Date:   Mon Mar 25 13:04:53 2024 +0800
+
+    移植dns查询工具dog的--tcp功能 (#652)
+    
+    * add dog, modify user/Makefile and user.sysconfig
+    
+    * add dog, modify user/Makefile and user.sysconfig
+    
+    * fix tty unicode
+    
+    * 修正无法正确编译dog的问题
+    
+    ---------
+    
+    Co-authored-by: val213 <val213666@gmail.com>
+    Co-authored-by: GnoCiYeH <heyicong@dragonos.org>
+    Co-authored-by: longjin <longjin@DragonOS.org>
+
+commit 911132c4b8ea0e9c49a4e84b9fa1db114102acbb
+Author: Donkey Kane <109840258+xiaolin2004@users.noreply.github.com>
+Date:   Mon Mar 25 13:04:32 2024 +0800
+
+    修复clock_gettime返回类型错误,修复小时间间隔duration返回0问题 (#664)
+    
+    * 修复clock_gettime返回类型错误,修正wtm初始化逻辑
+    
+    * 修复duration在小时间间隔下为0的问题
+    
+    * 临时修复时间流逝速度异常,在test-mount中加入运行时间检测
+
+commit 401699735b5ec29768c3c0c47df6c529991f108f
+Author: LoGin <longjin@DragonOS.org>
+Date:   Sat Mar 23 16:25:56 2024 +0800
+
+    riscv: 进程管理初始化 (#654)
+
+commit 6046f77591cf23dc9cc53b68b25c0d74f94fa493
+Author: 裕依 <68320855+yuyi2439@users.noreply.github.com>
+Date:   Sat Mar 23 15:56:49 2024 +0800
+
+    Patch socketpair (#576)
+    
+    * 将sockets分成inet和unix域
+    - 添加File端点
+    - 添加SocketPair trait并将Socket trait中的pair相关方法移动
+    - 添加对SockAddrUn的处理
+    
+    * 精简SocketHandleItem
+    
+    * 重构socketpair相关逻辑
+    - 将File端点换成Inode端点
+    - 尝试使用SocketInode进行socketpair(未成功)
+    
+    
+    * 将SocketPair trait合并到Socket trait中,去除downcast
+
+commit 3660256a9ee94abc30b5b22508cbd48c44c86089
+Author: LoGin <longjin@DragonOS.org>
+Date:   Sat Mar 23 11:51:30 2024 +0800
+
+    只对x86_64进行clippy check (#651)
+
+commit 4e4c8c41e90989c1f732995511e0f9a77a33f650
+Author: LoGin <longjin@DragonOS.org>
+Date:   Fri Mar 22 23:56:30 2024 +0800
+
+    添加clippy检测的自动化工作流 (#649)
+    
+    * 添加clippy检测的自动化工作流
+    
+    * fmt
+    
+    * 1
+
+commit b5b571e02693d91eb6918d3b7561e088c3e7ee81
+Author: LoGin <longjin@DragonOS.org>
+Date:   Fri Mar 22 23:26:39 2024 +0800
+
+    修复内核的clippy检查报错 (#637)
+    
+    修复内核的clippy检查报错
+    ---------
+    
+    Co-authored-by: Samuel Dai <947309196@qq.com>
+    Co-authored-by: Donkey Kane <109840258+xiaolin2004@users.noreply.github.com>
+    Co-authored-by: themildwind <107623059+themildwind@users.noreply.github.com>
+    Co-authored-by: GnoCiYeH <heyicong@dragonos.org>
+    Co-authored-by: MemoryShore <105195940+MemoryShore@users.noreply.github.com>
+    Co-authored-by: 曾俊 <110876916+ZZJJWarth@users.noreply.github.com>
+    Co-authored-by: sun5etop <146408999+sun5etop@users.noreply.github.com>
+    Co-authored-by: hmt <114841534+1037827920@users.noreply.github.com>
+    Co-authored-by: laokengwt <143977175+laokengwt@users.noreply.github.com>
+    Co-authored-by: TTaq <103996388+TTaq@users.noreply.github.com>
+    Co-authored-by: Jomo <2512364506@qq.com>
+    Co-authored-by: Samuel Dai <samuka007@qq.com>
+    Co-authored-by: sspphh <112558065+sspphh@users.noreply.github.com>
+
+commit 4695947e1b601c83641676485571d42c692a2bbd
+Author: Chenzx <109664121+schulice@users.noreply.github.com>
+Date:   Fri Mar 22 18:27:07 2024 +0800
+
+    实现SYS_LINK和SYS_LINKAT (#611)
+    
+    * 实现do_linkat及SYS_LINK和SYS_LINKAT
+    
+    * 未在riscv上测试,添加target_arch
+    
+    * 将c字符串检查移动到vfs/syscall.rs,修改do_linkat()逻辑
+    
+    * 修改部分注释
+
+commit 70f159a3988eab656ea1d2b204fde87948526ecf
+Author: LoGin <longjin@DragonOS.org>
+Date:   Thu Mar 21 21:35:39 2024 +0800
+
+    riscv64: 添加flush tlb的ipi (#636)
+    
+    * riscv64: 添加flush tlb的ipi
+    
+    * update triagebot
+
+commit b4eb05a17f0f65668f69e7979660874ef8e01a2e
+Author: TTaq <103996388+TTaq@users.noreply.github.com>
+Date:   Thu Mar 21 19:59:10 2024 +0800
+
+    Statx (#632)
+    
+    
+    * 实现statx及测试的应用程序
+
+commit 8cb2e9b344230227fe5f3ab3ebeb2522f1c5e289
+Author: LoGin <longjin@DragonOS.org>
+Date:   Thu Mar 21 19:19:32 2024 +0800
+
+    重写SMP模块 (#633)
+    
+    * 修复cpumask的迭代器的错误。
+    
+    * 能进系统(AP核心还没有初始化自身)
+    
+    * 初始化ap core
+    
+    * 修改percpu
+    
+    * 删除无用的cpu.c
+    
+    * riscv64编译通过
+
+commit 1d37ca6d172e01a98fa6785d2b3e07fb8202a4a9
+Author: Donkey Kane <109840258+xiaolin2004@users.noreply.github.com>
+Date:   Wed Mar 20 15:31:20 2024 +0800
+
+    添加mount系统调用 (#561)
+    
+    * Modify dadk config to switch NovaShell revision
+    
+    * finish primary build of mount(2), usable now
+    
+    * 使用read_from_cstr函数优化代码可读性 , 针对文件系统新增错误EUNSUPFS
+    
+    * small changes
+    
+    * 添加系统调用文档
+    
+    * cargo fmt
+    
+    * Revert "small changes"
+    
+    This reverts commit e1991314ce687faa2d652479e8ef64f5bea25fa1.
+    
+    * 修复用户程序参数传入错误
+    
+    * Revert "small changes"
+    
+    This reverts commit e1991314ce687faa2d652479e8ef64f5bea25fa1.
+    
+    * 解决合并冲突,最终提交
+    
+    * 将dadk_config切换为相对路径以修复依赖问题
+    
+    * Update settings.json
+    
+    * Delete user/apps/test-mount/LICENSE
+    
+    * 换用更好的c字符串读取函数,优化系统调用函数注释,修复错误处理bug,删除无用文件,修改测试程序readme
+    
+    * 修改用户程序readme
+    
+    * 代码格式化,初级版本
+    
+    * 初级版本,未实现文件系统管理器,未支持设备挂载
+    
+    * 为文件系统添加name方法,返回文件系统名字字符串,为挂载查询服务
+    
+    * mount系统调用:添加统一文件系统初始化管理器
+    
+    * null
+    
+    * 解除冲突
+    
+    * 删除无用kdebug
+
+commit 1cd9bb43f0256aecf19a090dd71e4ac2b86a5e29
+Author: LoGin <longjin@DragonOS.org>
+Date:   Tue Mar 19 21:31:02 2024 +0800
+
+    添加core utils到系统 (#624)
+
+commit 8c6f21840f820a161d4386000aea1d79e3bc8d13
+Author: sspphh <112558065+sspphh@users.noreply.github.com>
+Date:   Tue Mar 19 17:01:20 2024 +0800
+
+    实现uname系统调用 (#614)
+    
+    * 实现uname系统调用
+    
+    Co-authored-by: longjin <longjin@DragonOS.org>
+
+commit 82df0a13109e400602ddaec049d04ae230eb485b
+Author: hmt <114841534+1037827920@users.noreply.github.com>
+Date:   Tue Mar 19 16:45:44 2024 +0800
+
+    fix: mkdir输出错误信息; feat: 实现get_pathname (#615)
+    
+    * fix: mkdir输出错误信息; feat: 实现get_pathname
+    
+    * fix: 将处理路径的操作放入vfs而不是在syscall/mod.rs中
+    
+    * 调整入参类型
+    
+    ---------
+    
+    Co-authored-by: longjin <longjin@DragonOS.org>
+
+commit 9e481b3bfe303e0b104694da9750ae978dfeecae
+Author: TTaq <103996388+TTaq@users.noreply.github.com>
+Date:   Mon Mar 18 14:47:59 2024 +0800
+
+    实现了sys_rename (#578)
+    
+    * 基本实现了rename的系统调用
+    
+    * 实现相对路径的mv
+    
+    * confilct resolve
+    
+    * make fmt
+    
+    * 更改校验位置,
+     增加了SYS_RENAMEAT与SYS_RENAMEAT2两个系统调用,其实现与SYS_RENAME基本一致
+    
+    * 删除了fat中的link
+    
+    * fix
+    
+    * 修改注释格式,删除管道文件判断
+    
+    * 1
+
+commit c3c73444516b7b47b6327cd66f5453133f47998d
+Author: LoGin <longjin@DragonOS.org>
+Date:   Sat Mar 16 22:28:59 2024 +0800
+
+    更新triagebot配置 (#616)
+    
+    * 更新triagebot配置
+
+commit 4fd916113e576a1c5d8ca9faae7a9d6b25afb9ae
+Author: LoGin <longjin@DragonOS.org>
+Date:   Sat Mar 16 18:09:32 2024 +0800
+
+    triagebot-add-shortcut (#612)
+
+commit fbc174499f5200924c732263e461c79b4a936c5b
+Author: LoGin <longjin@DragonOS.org>
+Date:   Fri Mar 15 20:06:24 2024 +0800
+
+    添加triagebot文件 (#608)
+    
+    * 添加triagebot文件
+
+```

+ 1 - 0
docs/community/ChangeLog/index.rst

@@ -6,6 +6,7 @@
 ..  toctree::
     :maxdepth: 1
 
+    V0.1.x/V0.1.10
     V0.1.x/V0.1.9
     V0.1.x/V0.1.8
     V0.1.x/V0.1.7

+ 1 - 0
docs/introduction/build_system.md

@@ -48,6 +48,7 @@ bash bootstrap.sh  # 这里请不要加上sudo, 因为需要安装的开发依
 一键配置脚本目前只支持以下系统:
 
 - Ubuntu/Debian/Deepin/UOS 等基于Debian的衍生版本
+- Gentoo 由于Gentoo系统的特性 当gentoo出现USE或循环依赖问题时 请根据emerge提示信息进行对应的处理 官方的依赖处理实例[GentooWiki](https://wiki.gentoo.org/wiki/Handbook:AMD64/Full/Working/zh-cn#.E5.BD.93_Portage_.E6.8A.A5.E9.94.99.E7.9A.84.E6.97.B6.E5.80.99)
 
 欢迎您为其他的系统完善构建脚本!
 :::

+ 2 - 2
docs/kernel/locking/mutex.md

@@ -59,10 +59,10 @@ let x :Mutex<Vec<i32>>= 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);
 ```
 
 &emsp;&emsp;对于结构体内部的变量,我们可以使用Mutex进行细粒度的加锁,也就是使用Mutex包裹需要细致加锁的成员变量,比如这样:

+ 2 - 2
docs/kernel/locking/spinlock.md

@@ -65,10 +65,10 @@ let x :SpinLock<Vec<i32>>= 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);
 ```
 
 &emsp;&emsp;对于结构体内部的变量,我们可以使用SpinLock进行细粒度的加锁,也就是使用SpinLock包裹需要细致加锁的成员变量,比如这样:

+ 1 - 1
kernel/Cargo.toml

@@ -1,6 +1,6 @@
 [package]
 name = "dragonos_kernel"
-version = "0.1.9"
+version = "0.1.10"
 edition = "2021"
 
 # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

+ 1 - 1
kernel/crates/unified-init/src/lib.rs

@@ -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);
             });
         }
     };

+ 2 - 2
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;

+ 5 - 6
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();

+ 18 - 22
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();

+ 7 - 6
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<usize> 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<usize> for Signal {
 impl From<i32> 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

+ 12 - 12
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<MMArch, &mut BumpAllocator<MMArch>> =
             crate::mm::page::PageMapper::<MMArch, _>::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::<MMArch>::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::<MMArch, _>::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(());
 }

+ 4 - 5
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
             );
         }
     }

+ 5 - 3
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");
         }
     }
 }

+ 5 - 5
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<ProcessControlBlock>, next: Arc<ProcessControlBlock>) {
         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 {

+ 6 - 6
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();

+ 6 - 8
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(())
     }
 }

+ 2 - 2
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();
     }

+ 5 - 4
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;
     }

+ 3 - 2
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()
     );

+ 10 - 11
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,19 +221,18 @@ 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);
-        self.set_initial_cnt(initial_count);
         self.setup_lvt(
             APIC_TIMER_IRQ_NUM.data() as u8,
             true,
             LocalApicTimerMode::Periodic,
         );
+        self.set_initial_cnt(initial_count);
     }
 
     fn setup_lvt(&mut self, vector: u8, mask: bool, mode: LocalApicTimerMode) {

+ 7 - 7
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<IoApic> = 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<IrqDesc>, level_triggered: bool) {

+ 3 - 3
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();

+ 7 - 7
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;
     }
 

+ 5 - 6
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
     }

+ 7 - 6
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();

+ 7 - 7
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;

+ 2 - 2
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<dyn RtcDevice>, _time: &RtcTime) -> Result<(), SystemError> {
-        kerror!("set_time is not implemented for CmosRtcClassOps");
+        error!("set_time is not implemented for CmosRtcClassOps");
         Err(SystemError::ENOSYS)
     }
 }

+ 19 - 19
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<u64, SystemError> {
         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);
     }
 

+ 5 - 6
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);

+ 5 - 5
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<ArchIpiTarget> 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();
             }
         }

+ 2 - 2
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();
     }
 

+ 23 - 23
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!(
+    // log::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.");
 }

+ 20 - 20
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<usize> 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<Signal> for usize {
 impl From<i32> 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<i32, SystemError> =
             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::<SigFrame>(), 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::<SigFrame>());
-    // kdebug!("frame=0x{:016x}", frame as usize);
+    // debug!("frame=0x{:016x}", frame as usize);
     // 要求这个frame的地址位于用户空间,因此进行校验
     let r: Result<UserBufferWriter<'_>, SystemError> =
         UserBufferWriter::new(frame, size_of::<SigFrame>(), 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

+ 6 - 9
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<usize, SystemError> {
-        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");
     }
 }

+ 3 - 3
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::EntryFlags, 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<u32, SystemError> {
-    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);

+ 26 - 25
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<Self, SystemError> {
-        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<X86_64MMArch, LockedFrameAllocator> = 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(())
 }

+ 16 - 15
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!();

+ 7 - 6
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<u64, SystemError> {
     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)
     //     },
     // }

+ 7 - 7
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) {

+ 21 - 22
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::{EntryFlags, PageEntry, 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::<X86_64MMArch>::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::<X86_64MMArch>::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::<MMArch, _>::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}");
     }
 }
 

+ 37 - 5
kernel/src/arch/x86_64/pci/pci.rs

@@ -2,18 +2,40 @@ use crate::arch::TraitPciArch;
 use crate::driver::acpi::acpi_manager;
 use crate::driver::pci::ecam::{pci_ecam_root_info_manager, EcamRootInfo};
 use crate::driver::pci::pci::{
-    pci_init, BusDeviceFunction, PciAddr, PciError, PORT_PCI_CONFIG_ADDRESS, PORT_PCI_CONFIG_DATA,
+    pci_init, BusDeviceFunction, PciAddr, PciCam, PciError, PORT_PCI_CONFIG_ADDRESS,
+    PORT_PCI_CONFIG_DATA,
 };
-use crate::include::bindings::bindings::{io_in32, io_out32};
+use crate::driver::pci::root::{pci_root_manager, PciRoot};
+use crate::include::bindings::bindings::{io_in32, io_in8, io_out32};
 use crate::init::initcall::INITCALL_SUBSYS;
-use crate::kerror;
 use crate::mm::PhysAddr;
 
 use acpi::mcfg::Mcfg;
+use log::{error, warn};
 use system_error::SystemError;
 use unified_init::macros::unified_init;
 
 pub struct X86_64PciArch;
+
+impl X86_64PciArch {
+    /// # 在早期引导阶段直接访问PCI配置空间的函数
+    /// 参考:https://code.dragonos.org.cn/xref/linux-6.6.21/arch/x86/pci/early.c?fi=read_pci_config_byte#19
+    fn read_config_early(bus: u8, slot: u8, func: u8, offset: u8) -> u8 {
+        unsafe {
+            io_out32(
+                PORT_PCI_CONFIG_ADDRESS,
+                0x80000000
+                    | ((bus as u32) << 16)
+                    | ((slot as u32) << 11)
+                    | ((func as u32) << 8)
+                    | offset as u32,
+            );
+        }
+        let value = unsafe { io_in8(PORT_PCI_CONFIG_DATA + (offset & 3) as u16) };
+        return value;
+    }
+}
+
 impl TraitPciArch for X86_64PciArch {
     fn read_config(bus_device_function: &BusDeviceFunction, offset: u8) -> u32 {
         // 构造pci配置空间地址
@@ -50,8 +72,18 @@ 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);
+    if discover_ecam_root().is_err() {
+        // ecam初始化失败,使用portio访问pci配置空间
+        // 参考:https://code.dragonos.org.cn/xref/linux-6.6.21/arch/x86/pci/broadcom_bus.c#27
+        let bus_begin = X86_64PciArch::read_config_early(0, 0, 0, 0x44);
+        let bus_end = X86_64PciArch::read_config_early(0, 0, 0, 0x45);
+
+        if !pci_root_manager().has_root(bus_begin as u16) {
+            let root = PciRoot::new(None, PciCam::Portiocam, bus_begin, bus_end);
+            pci_root_manager().add_pci_root(root.unwrap());
+        } else {
+            warn!("x86_64_pci_init(): pci_root_manager {}", bus_begin);
+        }
     }
     pci_init();
 

+ 3 - 2
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();
             }
         }

+ 5 - 5
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::<TrapFrame>(),
     );
-    // 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(),

+ 8 - 8
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()
         // );

+ 3 - 3
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;

+ 4 - 3
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(());

+ 11 - 16
kernel/src/debug/klog/mm.rs

@@ -1,17 +1,10 @@
 extern crate klog_types;
 
-use core::{
-    intrinsics::unlikely,
-    sync::atomic::{compiler_fence, Ordering},
-};
+use core::sync::atomic::{compiler_fence, Ordering};
 
 use klog_types::{AllocatorLog, AllocatorLogType, LogSource, MMLogChannel};
 
-use crate::{
-    arch::CurrentTimeArch,
-    process::{Pid, ProcessManager},
-    time::TimeArch,
-};
+use crate::{arch::CurrentTimeArch, process::Pid, time::TimeArch};
 
 /// 全局的内存分配器日志通道
 ///
@@ -31,13 +24,14 @@ static __MM_DEBUG_LOG_IDA: ida::IdAllocator = ida::IdAllocator::new(1, usize::MA
 ///
 /// - `log_type`:日志类型
 /// - `source`:日志来源
-pub fn mm_debug_log(log_type: AllocatorLogType, source: LogSource) {
-    let pid = if unlikely(!ProcessManager::initialized()) {
-        Some(Pid::new(0))
-    } else {
-        Some(ProcessManager::current_pcb().pid())
-    };
-    MMDebugLogManager::log(log_type, source, pid);
+pub fn mm_debug_log(_log_type: AllocatorLogType, _source: LogSource) {
+    // todo: 由于目前底层的thingbuf存在卡死的问题,因此这里暂时注释掉。
+    // let pid = if unlikely(!ProcessManager::initialized()) {
+    //     Some(Pid::new(0))
+    // } else {
+    //     Some(ProcessManager::current_pcb().pid())
+    // };
+    // MMDebugLogManager::log(log_type, source, pid);
 }
 
 #[derive(Debug)]
@@ -54,6 +48,7 @@ impl MMDebugLogManager {
     /// - `log_type`:日志类型
     /// - `source`:日志来源
     /// - `pid`:日志来源的pid
+    #[allow(dead_code)]
     pub fn log(log_type: AllocatorLogType, source: LogSource, pid: Option<Pid>) {
         let id = __MM_DEBUG_LOG_IDA.alloc().unwrap();
         let log = AllocatorLog::new(

+ 5 - 5
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<PlatformInfo<'_, alloc::alloc::Global>> {
         let r = self.tables()?.platform_info();
         if let Err(ref e) = r {
-            kerror!(
+            error!(
                 "AcpiManager::platform_info(): failed to get platform info, error: {:?}",
                 e
             );

+ 1 - 1
kernel/src/driver/acpi/pmtmr.rs

@@ -12,7 +12,7 @@ pub const ACPI_PM_MASK: u64 = 0xffffff;
 pub fn acpi_pm_read_early() -> u32 {
     use crate::driver::clocksource::acpi_pm::{acpi_pm_read_verified, PMTMR_IO_PORT};
     use core::sync::atomic::Ordering;
-    let port = unsafe { PMTMR_IO_PORT.load(Ordering::SeqCst) };
+    let port = PMTMR_IO_PORT.load(Ordering::SeqCst);
 
     // 如果端口为零直接返回
     if port == 0 {

+ 6 - 6
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);
             }
         };

+ 14 - 16
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<dyn BlockDevice>, 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());

+ 4 - 4
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(

+ 7 - 6
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<dyn KObject>;
@@ -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<dyn Device>) -> 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<dyn Device>) {
-    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<dyn KObject>, buf: &[u8]) -> Result<usize, SystemError> {
         let driver = kobj.cast::<dyn Driver>().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<dyn KObject>, buf: &[u8]) -> Result<usize, SystemError> {
         let driver = kobj.cast::<dyn Driver>().map_err(|kobj| {
-            kerror!(
+            error!(
                 "Intertrait casting not implemented for kobj: {}",
                 kobj.name()
             );

+ 18 - 17
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<bool, SystemError> {
         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<dyn Device>) {
         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<dyn KObject>, buf: &mut [u8]) -> Result<usize, SystemError> {
         let dev = kobj.cast::<dyn Device>().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<dyn KObject>, buf: &[u8]) -> Result<usize, SystemError> {
         let dev = kobj.cast::<dyn Device>().map_err(|kobj| {
-            kerror!(
+            error!(
                 "Intertrait casting not implemented for kobj: {}",
                 kobj.name()
             );

+ 3 - 2
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<dyn Driver>) -> 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
             );

+ 10 - 13
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<dyn KObject>;
@@ -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<dyn KObject>;
@@ -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(());
 }

+ 12 - 10
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::{
@@ -75,7 +76,7 @@ static mut DEVICES_VIRTUAL_KSET_INSTANCE: Option<Arc<KSet>> = None;
 
 /// 获取`/sys/devices`的kset实例
 #[inline(always)]
-pub(super) fn sys_devices_kset() -> Arc<KSet> {
+pub fn sys_devices_kset() -> Arc<KSet> {
     unsafe { DEVICES_KSET_INSTANCE.as_ref().unwrap().clone() }
 }
 
@@ -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
         );
@@ -287,6 +288,7 @@ pub enum DeviceType {
     Intc,
     PlatformDev,
     Char,
+    Pci,
 }
 
 /// @brief: 设备标识符类型
@@ -481,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(),
@@ -491,7 +493,7 @@ impl DeviceManager {
         }
 
         KObjectManager::add_kobj(device.clone() as Arc<dyn KObject>, None).map_err(|e| {
-            kerror!("add device '{:?}' failed: {:?}", device.name(), e);
+            error!("add device '{:?}' failed: {:?}", device.name(), e);
             e
         })?;
 
@@ -551,10 +553,10 @@ impl DeviceManager {
         device: &Arc<dyn Device>,
         current_parent: Option<Arc<dyn Device>>,
     ) -> Result<Option<Arc<dyn KObject>>, SystemError> {
-        // kdebug!("get_device_parent() device:{:?}", device.name());
+        // debug!("get_device_parent() device:{:?}", device.name());
         if device.class().is_some() {
             let parent_kobj: Arc<dyn KObject>;
-            // 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<dyn KObject>));
@@ -755,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()
             );
@@ -764,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()
             );
@@ -806,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<dyn Device>) {
-        kwarn!("device_links_force_bind not implemented");
+        warn!("device_links_force_bind not implemented");
     }
 
     /// 把device对象的一些结构进行默认初始化
@@ -871,7 +873,7 @@ impl Attribute for DeviceAttrDev {
 
     fn show(&self, kobj: Arc<dyn KObject>, buf: &mut [u8]) -> Result<usize, SystemError> {
         let dev = kobj.cast::<dyn Device>().map_err(|kobj| {
-            kerror!(
+            error!(
                 "Intertrait casting not implemented for kobj: {}",
                 kobj.name()
             );

+ 3 - 3
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<dyn KObject>) {
-        kdebug!("DynamicKObjKType::release() kobj:{:?}", kobj.name());
+        debug!("DynamicKObjKType::release() kobj:{:?}", kobj.name());
     }
 
     fn sysfs_ops(&self) -> Option<&dyn SysFSOps> {

+ 3 - 2
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<dyn Device>) -> Result<(), SystemError> {
         let drv = device.driver().ok_or(SystemError::EINVAL)?;
         let pdrv = drv.cast::<dyn PlatformDriver>().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::<dyn PlatformDevice>().map_err(|_| {
-            kerror!(
+            error!(
                 "PlatformBus::probe() failed: device is not a PlatformDevice. Device: '{:?}'",
                 device.name()
             );

+ 2 - 1
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进行对块设备进行连续块的读操作

+ 6 - 6
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<Arc<VirtIOBlkDevice>> {
 pub fn virtio_blk(transport: VirtIOTransport, dev_id: Arc<DeviceId>) {
     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<dyn VirtIODevice>)
             .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::<HalImpl, VirtIOTransport>::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::<VirtIOBlkDevice>()
             .map_err(|_| {
-                kerror!(
+                error!(
                 "VirtIOBlkDriver::probe() failed: device is not a VirtIO block device. Device: '{:?}'",
                 device.name()
             );

+ 27 - 24
kernel/src/driver/clocksource/acpi_pm.rs

@@ -15,12 +15,13 @@ 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
 
 /// acpi_pmtmr所在的I/O端口
-pub static mut PMTMR_IO_PORT: AtomicU32 = AtomicU32::new(0);
+pub static PMTMR_IO_PORT: AtomicU32 = AtomicU32::new(0);
 
 /// # 读取acpi_pmtmr当前值,并对齐进行掩码操作
 #[inline(always)]
@@ -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
         );
@@ -206,12 +209,13 @@ fn find_acpi_pm_clock() -> Result<(), SystemError> {
     let pm_timer_block = fadt.pm_timer_block().map_err(|_| SystemError::ENODEV)?;
     let pm_timer_block = pm_timer_block.ok_or(SystemError::ENODEV)?;
     let pmtmr_addr = pm_timer_block.address;
-    unsafe {
-        PMTMR_IO_PORT.store(pmtmr_addr as u32, Ordering::SeqCst);
-    }
-    kinfo!("apic_pmtmr I/O port: {}", unsafe {
+
+    PMTMR_IO_PORT.store(pmtmr_addr as u32, Ordering::SeqCst);
+
+    info!(
+        "apic_pmtmr I/O port: {}",
         PMTMR_IO_PORT.load(Ordering::SeqCst)
-    });
+    );
 
     return Ok(());
 }
@@ -222,18 +226,19 @@ fn find_acpi_pm_clock() -> Result<(), SystemError> {
 #[allow(dead_code)]
 pub fn init_acpi_pm_clocksource() -> Result<(), SystemError> {
     let acpi_pm = Acpipm::new();
-    unsafe {
-        CLOCKSOURCE_ACPI_PM = Some(acpi_pm);
-    }
 
     // 解析fadt
     find_acpi_pm_clock()?;
 
     // 检查pmtmr_io_port是否被设置
-    if unsafe { PMTMR_IO_PORT.load(Ordering::SeqCst) } == 0 {
+    if PMTMR_IO_PORT.load(Ordering::SeqCst) == 0 {
         return Err(SystemError::ENODEV);
     }
 
+    unsafe {
+        CLOCKSOURCE_ACPI_PM = Some(acpi_pm);
+    }
+
     // 验证ACPI PM Timer作为时钟源的稳定性和一致性
     for j in 0..ACPI_PM_MONOTONIC_CHECKS {
         let mut cnt = 100 * j;
@@ -255,26 +260,24 @@ pub fn init_acpi_pm_clocksource() -> Result<(), SystemError> {
             if (value2 < value1) && (value2 < 0xfff) {
                 break;
             }
-            kinfo!("PM Timer had inconsistens results: {} {}", value1, value2);
-            unsafe {
-                PMTMR_IO_PORT.store(0, Ordering::SeqCst);
-            }
+            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);
-            unsafe {
-                PMTMR_IO_PORT.store(0, Ordering::SeqCst);
-            }
+            info!("PM Timer failed consistency check: {}", value1);
+
+            PMTMR_IO_PORT.store(0, Ordering::SeqCst);
+
             return Err(SystemError::EINVAL);
         }
     }
 
     // 检查ACPI PM Timer的频率是否正确
     if !verify_pmtmr_rate() {
-        unsafe {
-            PMTMR_IO_PORT.store(0, Ordering::SeqCst);
-        }
+        PMTMR_IO_PORT.store(0, Ordering::SeqCst);
     }
 
     // 检查TSC时钟源的监视器是否被禁用,如果被禁用则将时钟源的标志设置为CLOCK_SOURCE_MUST_VERIFY
@@ -289,11 +292,11 @@ pub fn init_acpi_pm_clocksource() -> Result<(), SystemError> {
     let acpi_pmtmr = clocksource_acpi_pm() as Arc<dyn Clocksource>;
     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);
         }
     };

+ 1 - 1
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

+ 11 - 13
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);
             }
         }

+ 12 - 14
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!("<ahci_rust_init> Find a None type Disk.");
+                        debug!("<ahci_rust_init> Find a None type Disk.");
                     }
                     HbaPortType::Unknown(err) => {
-                        kdebug!("<ahci_rust_init> Find a Unknown({:?}) type Disk.", err);
+                        debug!("<ahci_rust_init> Find a Unknown({:?}) type Disk.", err);
                     }
                     _ => {
-                        kdebug!("<ahci_rust_init> Find a {:?} type Disk.", tp);
+                        debug!("<ahci_rust_init> 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,

+ 3 - 2
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:?}");
                     })
             }
         }

+ 16 - 15
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::<uefi_raw::table::system::SystemTable>();
 
     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

+ 3 - 2
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);
         }
 

+ 4 - 4
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
             );
         }
 

+ 11 - 10
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::<LinuxEFIMemReserveEntry>() * 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(());
     }
 }

+ 5 - 4
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<dyn KObject>) -> 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<dyn Device>));
@@ -672,7 +673,7 @@ pub fn rs_ps2_mouse_device_init(parent: Arc<dyn KObject>) -> Result<(), SystemEr
     serio_device_manager().register_port(psmouse.clone() as Arc<dyn SerioDevice>)?;
 
     devfs_register(&psmouse.name(), psmouse.clone()).map_err(|e| {
-        kerror!(
+        error!(
             "register psmouse device '{}' to devfs failed: {:?}",
             psmouse.name(),
             e

+ 3 - 2
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(());
 }

+ 2 - 1
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<I8042PlatformDevice> {
 // 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<dyn Device>));
     platform_device_manager().device_add(i8042_device.clone() as Arc<dyn PlatformDevice>)?;

+ 3 - 2
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<dyn Device>) -> Result<(), SystemError> {
         let drv = device.driver().ok_or(SystemError::EINVAL)?;
         let pdrv = drv.cast::<dyn SerioDriver>().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::<dyn SerioDevice>().map_err(|_| {
-            kerror!(
+            error!(
                 "SerioBus::probe() failed: device is not a SerioDevice. Device: '{:?}'",
                 device.name()
             );

+ 3 - 2
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<IrqNumber> {
     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,

+ 18 - 17
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<IrqData>, 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<IrqData>) -> 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<IrqData>) -> 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<IrqData>) {
-        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<IrqData>,
         _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:?}");
         }
     }
 }

+ 7 - 8
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::<E1000ERecvDesc>();
         let trans_ring_length = PAGE_SIZE / size_of::<E1000ETransDesc>();
         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<u64, E1000EPciError> {
         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
                 );

+ 2 - 2
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);
 }

+ 8 - 8
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<Self::TxToken<'_>> {
-        // 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<DeviceId>) {
         match VirtIONet::<HalImpl, VirtIOTransport, 2>::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<dyn VirtIODevice>)
         .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::<VirtioInterface>()
             .map_err(|_| {
-                kerror!(
+                error!(
                 "VirtIONetDriver::probe() failed: device is not a VirtioInterface. Device: '{:?}'",
                 device.name()
             );

+ 19 - 22
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
             );
         }
 

+ 160 - 0
kernel/src/driver/pci/attr.rs

@@ -0,0 +1,160 @@
+use alloc::sync::Arc;
+use intertrait::cast::CastArc;
+use log::warn;
+use system_error::SystemError;
+
+use crate::{
+    driver::base::kobject::KObject,
+    filesystem::{
+        sysfs::{
+            file::sysfs_emit_str, Attribute, AttributeGroup, SysFSOpsSupport, SYSFS_ATTR_MODE_RO,
+        },
+        vfs::syscall::ModeType,
+    },
+};
+
+use super::device::PciDevice;
+#[derive(Debug)]
+pub struct BasicPciReadOnlyAttrs;
+
+impl AttributeGroup for BasicPciReadOnlyAttrs {
+    fn name(&self) -> Option<&str> {
+        None
+    }
+
+    fn attrs(&self) -> &[&'static dyn Attribute] {
+        &[&Vendor, &DeviceID, &SubsystemVendor, &SubsystemDevice]
+    }
+
+    fn is_visible(
+        &self,
+        _kobj: Arc<dyn KObject>,
+        attr: &'static dyn Attribute,
+    ) -> Option<ModeType> {
+        return Some(attr.mode());
+    }
+}
+
+#[derive(Debug)]
+pub struct Vendor;
+
+impl Attribute for Vendor {
+    fn mode(&self) -> ModeType {
+        SYSFS_ATTR_MODE_RO
+    }
+
+    fn name(&self) -> &str {
+        "vendor"
+    }
+
+    fn show(&self, _kobj: Arc<dyn KObject>, _buf: &mut [u8]) -> Result<usize, SystemError> {
+        let dev = _kobj
+            .cast::<dyn PciDevice>()
+            .map_err(|e: Arc<dyn KObject>| {
+                warn!("device:{:?} is not a pci device!", e);
+                SystemError::EINVAL
+            })?;
+        return sysfs_emit_str(_buf, &format!("0x{:04x}", dev.vendor()));
+    }
+
+    fn store(&self, _kobj: Arc<dyn KObject>, _buf: &[u8]) -> Result<usize, SystemError> {
+        todo!()
+    }
+
+    fn support(&self) -> SysFSOpsSupport {
+        SysFSOpsSupport::ATTR_SHOW
+    }
+}
+
+#[derive(Debug)]
+pub struct DeviceID;
+
+impl Attribute for DeviceID {
+    fn mode(&self) -> ModeType {
+        SYSFS_ATTR_MODE_RO
+    }
+
+    fn name(&self) -> &str {
+        "device"
+    }
+
+    fn show(&self, _kobj: Arc<dyn KObject>, _buf: &mut [u8]) -> Result<usize, SystemError> {
+        let dev = _kobj
+            .cast::<dyn PciDevice>()
+            .map_err(|e: Arc<dyn KObject>| {
+                warn!("device:{:?} is not a pci device!", e);
+                SystemError::EINVAL
+            })?;
+        return sysfs_emit_str(_buf, &format!("0x{:04x}", dev.device_id()));
+    }
+
+    fn store(&self, _kobj: Arc<dyn KObject>, _buf: &[u8]) -> Result<usize, SystemError> {
+        todo!()
+    }
+
+    fn support(&self) -> SysFSOpsSupport {
+        SysFSOpsSupport::ATTR_SHOW
+    }
+}
+
+#[derive(Debug)]
+pub struct SubsystemVendor;
+
+impl Attribute for SubsystemVendor {
+    fn mode(&self) -> ModeType {
+        SYSFS_ATTR_MODE_RO
+    }
+
+    fn name(&self) -> &str {
+        "subsystem_vendor"
+    }
+
+    fn show(&self, _kobj: Arc<dyn KObject>, _buf: &mut [u8]) -> Result<usize, SystemError> {
+        let dev = _kobj
+            .cast::<dyn PciDevice>()
+            .map_err(|e: Arc<dyn KObject>| {
+                warn!("device:{:?} is not a pci device!", e);
+                SystemError::EINVAL
+            })?;
+        return sysfs_emit_str(_buf, &format!("0x{:04x}", dev.subsystem_vendor()));
+    }
+
+    fn store(&self, _kobj: Arc<dyn KObject>, _buf: &[u8]) -> Result<usize, SystemError> {
+        todo!()
+    }
+
+    fn support(&self) -> SysFSOpsSupport {
+        SysFSOpsSupport::ATTR_SHOW
+    }
+}
+
+#[derive(Debug)]
+pub struct SubsystemDevice;
+
+impl Attribute for SubsystemDevice {
+    fn mode(&self) -> ModeType {
+        SYSFS_ATTR_MODE_RO
+    }
+
+    fn name(&self) -> &str {
+        "subsystem_device"
+    }
+
+    fn show(&self, _kobj: Arc<dyn KObject>, _buf: &mut [u8]) -> Result<usize, SystemError> {
+        let dev = _kobj
+            .cast::<dyn PciDevice>()
+            .map_err(|e: Arc<dyn KObject>| {
+                warn!("device:{:?} is not a pci device!", e);
+                SystemError::EINVAL
+            })?;
+        return sysfs_emit_str(_buf, &format!("0x{:04x}", dev.subsystem_device()));
+    }
+
+    fn store(&self, _kobj: Arc<dyn KObject>, _buf: &[u8]) -> Result<usize, SystemError> {
+        todo!()
+    }
+
+    fn support(&self) -> SysFSOpsSupport {
+        SysFSOpsSupport::ATTR_SHOW
+    }
+}

+ 109 - 0
kernel/src/driver/pci/dev_id.rs

@@ -0,0 +1,109 @@
+use alloc::sync::Arc;
+
+use super::device::PciDevice;
+const PCI_ANY_ID: u32 = 0xffff_ffff;
+
+/// # 结构功能
+/// 该结构用于驱动和设备之间的识别,驱动会有一个支持的设备ID列表,而设备会自带一个ID,如果设备的ID在驱动的支持列表中,则驱动和设备就可以识别了
+/// 见https://code.dragonos.org.cn/xref/linux-6.1.9/include/linux/mod_devicetable.h#43
+#[derive(Debug, Copy, Clone)]
+pub struct PciDeviceID {
+    vendor: u32,
+    device_id: u32,
+    subvendor: u32,
+    subdevice: u32,
+    class: u32,
+    class_mask: u32,
+    _driver_data: u64,
+    _override_only: u32,
+    /// 可能有些设备的识别方式比较特殊,那么可以通过设置该字段进行自定义的识别方式,只需要在PciSpecifiedData枚举中加入一个类型即可
+    /// 若该字段不为None,则优先使用special_data进行识别;
+    /// 该字段是为了增加灵活性
+    special_data: Option<PciSpecifiedData>,
+}
+
+impl PciDeviceID {
+    #[allow(dead_code)]
+    pub fn set_special(&mut self, data: PciSpecifiedData) {
+        self.special_data = Some(data);
+    }
+
+    pub fn dummpy() -> Self {
+        return Self {
+            vendor: PCI_ANY_ID,
+            device_id: PCI_ANY_ID,
+            subvendor: PCI_ANY_ID,
+            subdevice: PCI_ANY_ID,
+            class: PCI_ANY_ID,
+            class_mask: PCI_ANY_ID,
+            _driver_data: 0,
+            _override_only: PCI_ANY_ID,
+            special_data: None,
+        };
+    }
+    pub fn match_dev(&self, dev: &Arc<dyn PciDevice>) -> bool {
+        if let Some(d_data) = &dev.dynid().special_data {
+            return d_data.match_dev(self.special_data);
+        }
+        if let Some(s_data) = &self.special_data {
+            return s_data.match_dev(dev.dynid().special_data);
+        } else {
+            let d_id = dev.dynid();
+            return self.general_match(d_id);
+        }
+    }
+
+    /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/pci/pci.h?fi=pci_match_one_device#195
+    pub fn general_match(&self, id: PciDeviceID) -> bool {
+        if (self.vendor == id.vendor() || self.vendor == PCI_ANY_ID)
+            && (self.device_id == id.device_id() || self.device_id == PCI_ANY_ID)
+            && (self.subvendor == id.subvendor() || self.subvendor == PCI_ANY_ID)
+            && (self.subdevice == id.subdevice() || self.subdevice == PCI_ANY_ID)
+            && self.class_check(&id)
+        {
+            return true;
+        }
+        return false;
+    }
+
+    pub fn class_check(&self, id: &Self) -> bool {
+        return (self.class ^ id.class()) & self.class_mask == 0;
+    }
+
+    pub fn vendor(&self) -> u32 {
+        self.vendor
+    }
+
+    pub fn device_id(&self) -> u32 {
+        self.device_id
+    }
+
+    pub fn subvendor(&self) -> u32 {
+        self.subvendor
+    }
+
+    pub fn subdevice(&self) -> u32 {
+        self.subdevice
+    }
+
+    pub fn class(&self) -> u32 {
+        self.class
+    }
+
+    pub fn _class_mask(&self) -> u32 {
+        self.class_mask
+    }
+}
+
+#[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Copy, Clone)]
+pub enum PciSpecifiedData {}
+
+impl PciSpecifiedData {
+    pub fn match_dev(&self, data: Option<Self>) -> bool {
+        if let Some(data) = data {
+            return *self == data;
+        } else {
+            return false;
+        }
+    }
+}

+ 219 - 0
kernel/src/driver/pci/device.rs

@@ -0,0 +1,219 @@
+use alloc::{
+    string::{String, ToString},
+    sync::{Arc, Weak},
+};
+use system_error::SystemError;
+
+use crate::{
+    driver::base::{
+        device::{
+            bus::Bus, device_manager, driver::Driver, Device, DeviceCommonData, DeviceType, IdTable,
+        },
+        kobject::{KObjType, KObject, KObjectCommonData, KObjectState, LockedKObjectState},
+        kset::KSet,
+    },
+    filesystem::kernfs::KernFSInode,
+    libs::{rwlock::RwLockWriteGuard, spinlock::SpinLock},
+};
+
+use super::{
+    dev_id::PciDeviceID,
+    subsys::{pci_bus, pci_bus_device},
+};
+
+/// # 结构功能
+/// 该结构为Pci设备的管理器,使用该结构可以将pci设备添加到sysfs中
+pub struct PciDeviceManager;
+
+pub fn pci_device_manager() -> &'static PciDeviceManager {
+    &PciDeviceManager
+}
+
+impl PciDeviceManager {
+    /// #函数的功能
+    /// 将pci设备注册到sysfs中
+    ///
+    /// ## 参数:
+    /// - 'pci_dev':需要添加的pci设备
+    ///
+    /// ## 返回值:
+    /// - OK(()) :表示成功
+    /// - Err(e) :失败原因
+    pub fn device_add(&self, pci_dev: Arc<dyn PciDevice>) -> Result<(), SystemError> {
+        // pci设备一般放置在/sys/device/pci:xxxx下
+        if pci_dev.parent().is_none() {
+            pci_dev.set_parent(Some(Arc::downgrade(
+                &(pci_bus_device() as Arc<dyn KObject>),
+            )));
+        }
+        // 设置设备的总线
+        pci_dev.set_bus(Some(Arc::downgrade(&(pci_bus() as Arc<dyn Bus>))));
+        // 对设备进行默认的初始化
+        device_manager().device_default_initialize(&(pci_dev.clone() as Arc<dyn Device>));
+        // 使用设备管理器注册设备,当设备被注册后,会根据它的总线字段,在对应的总线上扫描驱动,并尝试进行匹配
+        let r = device_manager().add_device(pci_dev.clone() as Arc<dyn Device>);
+
+        if r.is_ok() {
+            //todo:这里可能还要处理一些设置成功后设备状态的变化
+            return Ok(());
+        } else {
+            //todo:这里可能有一些添加失败的处理
+            return r;
+        }
+    }
+}
+
+/// #trait功能
+/// 要进入sysfs的Pci设备应当实现的trait
+pub trait PciDevice: Device {
+    /// # 函数的功能
+    /// 返回本设备的PciDeviceID,该ID用于driver和device之间的匹配
+    ///
+    /// ## 返回值
+    /// - 'PciDeviceID' :本设备的PciDeviceID
+    fn dynid(&self) -> PciDeviceID;
+
+    /// # 函数的功能
+    /// 返回本设备的供应商(vendor)ID
+    ///
+    /// ## 返回值
+    /// - u16 :表示供应商ID
+    fn vendor(&self) -> u16;
+    fn device_id(&self) -> u16;
+    fn subsystem_vendor(&self) -> u16;
+    fn subsystem_device(&self) -> u16;
+}
+
+/// #结构功能
+/// 由于Pci总线本身就属于一个设备,故该结构代表Pci总线(控制器)本身
+/// 它对应/sys/device/pci
+#[derive(Debug)]
+#[cast_to([sync] Device)]
+pub struct PciBusDevice {
+    // inner: SpinLock<InnerPciBusDevice>,
+    device_data: SpinLock<DeviceCommonData>,
+    kobj_data: SpinLock<KObjectCommonData>,
+    kobj_state: LockedKObjectState,
+    name: String,
+}
+
+impl PciBusDevice {
+    pub fn new(parent: Option<Weak<dyn KObject>>) -> Arc<Self> {
+        let common_device = DeviceCommonData::default();
+        let common_kobj = KObjectCommonData::default();
+        let bus_device = Self {
+            device_data: SpinLock::new(common_device),
+            kobj_data: SpinLock::new(common_kobj),
+            kobj_state: LockedKObjectState::new(None),
+            name: "pci".to_string(),
+        };
+        bus_device.set_parent(parent);
+        return Arc::new(bus_device);
+    }
+}
+
+impl KObject for PciBusDevice {
+    fn as_any_ref(&self) -> &dyn core::any::Any {
+        self
+    }
+
+    fn parent(&self) -> Option<alloc::sync::Weak<dyn KObject>> {
+        self.kobj_data.lock().parent.clone()
+    }
+
+    fn inode(&self) -> Option<Arc<KernFSInode>> {
+        self.kobj_data.lock().kern_inode.clone()
+    }
+
+    fn set_inode(&self, inode: Option<Arc<KernFSInode>>) {
+        self.kobj_data.lock().kern_inode = inode;
+    }
+
+    fn kobj_type(&self) -> Option<&'static dyn KObjType> {
+        self.kobj_data.lock().kobj_type
+    }
+
+    fn set_kobj_type(&self, ktype: Option<&'static dyn KObjType>) {
+        self.kobj_data.lock().kobj_type = ktype
+    }
+
+    fn kset(&self) -> Option<Arc<KSet>> {
+        self.kobj_data.lock().kset.clone()
+    }
+
+    fn kobj_state(
+        &self,
+    ) -> crate::libs::rwlock::RwLockReadGuard<crate::driver::base::kobject::KObjectState> {
+        self.kobj_state.read()
+    }
+
+    fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> {
+        self.kobj_state.write()
+    }
+
+    fn set_kobj_state(&self, state: KObjectState) {
+        *self.kobj_state.write() = state;
+    }
+
+    fn name(&self) -> String {
+        self.name.clone()
+    }
+
+    fn set_name(&self, _name: String) {
+        //do nothing; it's not supposed to change this struct's name
+    }
+
+    fn set_kset(&self, kset: Option<Arc<KSet>>) {
+        self.kobj_data.lock().kset = kset;
+    }
+
+    fn set_parent(&self, parent: Option<Weak<dyn KObject>>) {
+        self.kobj_data.lock().parent = parent;
+    }
+}
+
+impl Device for PciBusDevice {
+    fn dev_type(&self) -> DeviceType {
+        return DeviceType::Bus;
+    }
+
+    fn id_table(&self) -> IdTable {
+        IdTable::new("pci".to_string(), None)
+    }
+
+    fn bus(&self) -> Option<Weak<dyn Bus>> {
+        self.device_data.lock().bus.clone()
+    }
+
+    fn set_bus(&self, bus: Option<alloc::sync::Weak<dyn Bus>>) {
+        self.device_data.lock().bus = bus
+    }
+
+    fn driver(&self) -> Option<Arc<dyn Driver>> {
+        self.device_data.lock().driver.clone()?.upgrade()
+    }
+
+    fn is_dead(&self) -> bool {
+        false
+    }
+
+    fn set_driver(&self, driver: Option<alloc::sync::Weak<dyn Driver>>) {
+        self.device_data.lock().driver = driver;
+    }
+
+    fn can_match(&self) -> bool {
+        todo!()
+    }
+
+    fn set_can_match(&self, _can_match: bool) {
+        todo!()
+    }
+
+    fn set_class(&self, _class: Option<alloc::sync::Weak<dyn crate::driver::base::class::Class>>) {
+        todo!()
+    }
+
+    fn state_synced(&self) -> bool {
+        todo!()
+    }
+}

+ 83 - 0
kernel/src/driver/pci/driver.rs

@@ -0,0 +1,83 @@
+use alloc::{sync::Arc, vec::Vec};
+use system_error::SystemError;
+
+use crate::driver::base::device::{
+    bus::Bus,
+    driver::{driver_manager, Driver},
+};
+
+use super::{dev_id::PciDeviceID, device::PciDevice, subsys::pci_bus};
+
+/// # trait功能
+/// Pci驱动应该实现的trait
+///
+/// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/include/linux/pci.h#907
+pub trait PciDriver: Driver {
+    /// # 函数的功能
+    /// 对设备进行probe操作
+    ///
+    /// ## 参数:
+    /// - 'device' :要进行probe的设备
+    /// - 'id' :设备的ID(暂时不清楚为什么需要这个,依Linux实现是有ID的)
+    ///
+    /// ## 返回值:
+    /// - Ok:probe成功
+    /// - Err:probe失败
+    fn probe(&self, device: &Arc<dyn PciDevice>, id: &PciDeviceID) -> Result<(), SystemError>;
+    fn remove(&self, device: &Arc<dyn PciDevice>) -> Result<(), SystemError>;
+    fn shutdown(&self, device: &Arc<dyn PciDevice>) -> Result<(), SystemError>;
+    fn suspend(&self, device: &Arc<dyn PciDevice>) -> Result<(), SystemError>;
+    fn resume(&self, device: &Arc<dyn PciDevice>) -> Result<(), SystemError>;
+    /// # 函数的功能
+    /// 向驱动中加入一个PciDeviceID,表示该驱动可以支持该ID的设备
+    ///
+    /// ## 参数:
+    /// - 'id' :要添加的ID
+    ///
+    /// ## 返回值:
+    /// - 'Ok':添加成功
+    /// - 'Err':添加失败
+    fn add_dynid(&mut self, id: PciDeviceID) -> Result<(), SystemError>;
+    /// # 函数的功能
+    /// 每个Pci驱动都应该持有一个支持ID的列表,并通过该函数进行访问
+    ///
+    /// ## 返回值:
+    /// - 'Some(Vec)': 支持ID的列表
+    /// - 'None':未能获取列表
+    fn locked_dynid_list(&self) -> Option<Vec<Arc<PciDeviceID>>>;
+    /// # 函数的功能
+    /// 检测当前驱动是否支持目标设备
+    ///
+    /// ## 参数:
+    /// - 'dev' :要检测的设备
+    ///
+    /// ## 返回值:
+    /// - 'Some(Arc<PciDeviceID>)': 如果支持,则返回支持的ID
+    /// - 'None': 不支持的设备
+    fn match_dev(&self, dev: &Arc<dyn PciDevice>) -> Option<Arc<PciDeviceID>> {
+        for i in self.locked_dynid_list()?.iter() {
+            if i.match_dev(dev) {
+                return Some(i.clone());
+            }
+        }
+        return None;
+    }
+}
+
+pub struct PciDriverManager;
+
+pub fn pci_driver_manager() -> &'static PciDriverManager {
+    &PciDriverManager
+}
+
+impl PciDriverManager {
+    pub fn register(&self, driver: Arc<dyn PciDriver>) -> Result<(), SystemError> {
+        driver.set_bus(Some(Arc::downgrade(&(pci_bus() as Arc<dyn Bus>))));
+        return driver_manager().register(driver as Arc<dyn Driver>);
+    }
+
+    #[allow(dead_code)]
+    pub fn unregister(&self, driver: &Arc<dyn PciDriver>) {
+        driver_manager().unregister(&(driver.clone() as Arc<dyn Driver>));
+    }
+}

+ 18 - 12
kernel/src/driver/pci/ecam.rs

@@ -1,3 +1,5 @@
+use log::{error, warn};
+
 use crate::mm::PhysAddr;
 
 use super::{
@@ -11,27 +13,32 @@ pub fn pci_ecam_root_info_manager() -> &'static EcamRootInfoManager {
 }
 
 /// Ecam pci root info
-#[derive(Clone, Copy)]
+#[derive(Clone, Debug, Copy)]
 pub struct EcamRootInfo {
-    pub segement_group_number: SegmentGroupNumber,
+    /// 段组号
+    pub segment_group_number: SegmentGroupNumber,
+    /// 该分组中的最小bus
     pub bus_begin: u8,
+    /// 该分组中的最大bus
     pub bus_end: u8,
+    /// 物理基地址       
     pub physical_address_base: PhysAddr,
 }
 
 impl EcamRootInfo {
     pub fn new(
-        segement_group_number: SegmentGroupNumber,
+        segment_group_number: SegmentGroupNumber,
         bus_begin: u8,
         bus_end: u8,
         physical_address_base: PhysAddr,
     ) -> Self {
-        Self {
-            segement_group_number,
+        let ecam_root_info = Self {
+            segment_group_number,
             bus_begin,
             bus_end,
             physical_address_base,
-        }
+        };
+        return ecam_root_info;
     }
 }
 
@@ -46,25 +53,24 @@ impl EcamRootInfoManager {
     ///
     /// - `ecam_root_info`: EcamRootInfo - 要添加的EcamRootInfo实例
     pub fn add_ecam_root_info(&self, ecam_root_info: EcamRootInfo) {
-        if !pci_root_manager().has_root(ecam_root_info.segement_group_number) {
+        if !pci_root_manager().has_root(ecam_root_info.segment_group_number) {
             let root = PciRoot::new(
-                ecam_root_info.segement_group_number,
+                Some(ecam_root_info),
                 PciCam::Ecam,
-                ecam_root_info.physical_address_base,
                 ecam_root_info.bus_begin,
                 ecam_root_info.bus_end,
             );
 
             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
+                ecam_root_info.segment_group_number
             );
         }
     }

+ 7 - 0
kernel/src/driver/pci/mod.rs

@@ -1,5 +1,12 @@
+pub mod attr;
+pub mod dev_id;
+pub mod device;
+pub mod driver;
 pub mod ecam;
 #[allow(clippy::module_inception)]
 pub mod pci;
 pub mod pci_irq;
+pub mod raw_device;
 pub mod root;
+pub mod subsys;
+pub mod test;

+ 57 - 33
kernel/src/driver/pci/pci.rs

@@ -1,20 +1,26 @@
 #![allow(dead_code)]
 // 目前仅支持单主桥单Segment
 
+use super::device::pci_device_manager;
 use super::pci_irq::{IrqType, PciIrqError};
+use super::raw_device::PciGeneralDevice;
 use super::root::{pci_root_0, PciRoot};
+
 use crate::arch::{PciArch, TraitPciArch};
+use crate::driver::pci::subsys::pci_bus_subsys_init;
 use crate::exception::IrqNumber;
 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,
@@ -633,6 +639,8 @@ impl PciDeviceStructure for PciDeviceStructurePciToCardbusBridge {
 /// 用于访问PCI设备的功能配置空间的一组机制。
 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
 pub enum PciCam {
+    /// PortIO配置访问机制
+    Portiocam,
     /// PCI内存映射配置访问机制
     ///
     /// 为每个设备功能提供256字节的配置空间访问。
@@ -647,6 +655,7 @@ impl PciCam {
     /// Returns the total size in bytes of the memory-mapped region.
     pub const fn size(self) -> u32 {
         match self {
+            Self::Portiocam => 0x100000,
             Self::MmioCam => 0x1000000,
             Self::Ecam => 0x10000000,
         }
@@ -716,11 +725,18 @@ fn pci_read_header(
     };
     match HeaderType::from(header_type & 0x7f) {
         HeaderType::Standard => {
-            let general_device = pci_read_general_device_header(header, &bus_device_function);
-            let box_general_device = Box::new(general_device);
+            let general_device: PciDeviceStructureGeneralDevice =
+                pci_read_general_device_header(header, &bus_device_function);
+            let box_general_device = Box::new(general_device.clone());
             let box_general_device_clone = box_general_device.clone();
             if add_to_list {
                 PCI_DEVICE_LINKEDLIST.add(box_general_device);
+                //这里实际上不应该使用clone,因为raw是用于sysfs的结构,但是实际上pci设备是在PCI_DEVICE_LINKEDLIST链表上的,
+                //这就导致sysfs呈现的对pci设备的操控接口实际上操控的是pci设备描述符是一个副本
+                //但是无奈这里没有使用Arc
+                //todo:修改pci设备描述符在静态链表中存在的方式,并修改这里的clone操作
+                let raw = PciGeneralDevice::from(&general_device);
+                let _ = pci_device_manager().device_add(Arc::new(raw));
             }
             Ok(box_general_device_clone)
         }
@@ -950,7 +966,7 @@ fn pci_read_pci_to_cardbus_bridge_header(
 /// @brief 检查所有bus上的设备并将其加入链表
 /// @return 成功返回ok(),失败返回失败原因
 fn pci_check_all_buses() -> Result<u8, PciError> {
-    kinfo!("Checking all devices in PCI bus...");
+    info!("Checking all devices in PCI bus...");
     let busdevicefunction = BusDeviceFunction {
         bus: 0,
         device: 0,
@@ -969,7 +985,7 @@ fn pci_check_all_buses() -> Result<u8, PciError> {
 /// @brief 检查特定设备并将其加入链表
 /// @return 成功返回ok(),失败返回失败原因
 fn pci_check_function(busdevicefunction: BusDeviceFunction) -> Result<u8, PciError> {
-    //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) => {
@@ -995,7 +1011,7 @@ fn pci_check_function(busdevicefunction: BusDeviceFunction) -> Result<u8, PciErr
 /// @brief 检查device上的设备并将其加入链表
 /// @return 成功返回ok(),失败返回失败原因
 fn pci_check_device(bus: u8, device: u8) -> Result<u8, PciError> {
-    //kdebug!("PCI check device {}", device);
+    //debug!("PCI check device {}", device);
     let busdevicefunction = BusDeviceFunction {
         bus,
         device,
@@ -1014,10 +1030,9 @@ fn pci_check_device(bus: u8, device: u8) -> Result<u8, PciError> {
     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 {
@@ -1034,7 +1049,7 @@ fn pci_check_device(bus: u8, device: u8) -> Result<u8, PciError> {
 /// @brief 检查该bus上的设备并将其加入链表
 /// @return 成功返回ok(),失败返回失败原因
 fn pci_check_bus(bus: u8) -> Result<u8, PciError> {
-    //kdebug!("PCI check bus {}", bus);
+    //debug!("PCI check bus {}", bus);
     for device in 0..32 {
         pci_check_device(bus, device)?;
     }
@@ -1044,12 +1059,13 @@ fn pci_check_bus(bus: u8) -> Result<u8, PciError> {
 /// 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()
     );
@@ -1058,39 +1074,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.
@@ -1114,6 +1125,19 @@ impl BusDeviceFunction {
         self.device < 32 && self.function < 8
     }
 }
+
+impl From<BusDeviceFunction> for String {
+    /// # 函数的功能
+    /// 这里提供一个由BusDeviceFunction到dddd:bb:vv.f字符串的转换函数,主要用于转换成设备的名称(pci设备的名称一般是诸如0000:00:00.1这种)
+    fn from(value: BusDeviceFunction) -> Self {
+        //需要注意,这里的0000应该是所谓的“域号”(Domain ID),但是尚不知道是如何获得的,故硬编码在这里
+        //todo:实现域号的获取
+        format!(
+            "0000:{:02x}:{:02x}.{}",
+            value.bus, value.device, value.function
+        )
+    }
+}
 ///实现BusDeviceFunction的Display trait,使其可以直接输出
 impl Display for BusDeviceFunction {
     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
@@ -1313,7 +1337,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,
@@ -1353,7 +1377,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"
@@ -1389,7 +1413,7 @@ pub fn pci_bar_init(
             _ => {}
         }
     }
-    //kdebug!("pci_device_bar:{}", device_bar);
+    //debug!("pci_device_bar:{}", device_bar);
     return Ok(device_bar);
 }
 
@@ -1427,7 +1451,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)
@@ -1475,7 +1499,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)

+ 3 - 2
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

+ 194 - 0
kernel/src/driver/pci/raw_device.rs

@@ -0,0 +1,194 @@
+use core::any::Any;
+
+use alloc::{
+    string::{String, ToString},
+    sync::{Arc, Weak},
+};
+
+use crate::{
+    driver::base::{
+        class::Class,
+        device::{bus::Bus, driver::Driver, Device, DeviceCommonData, DeviceType, IdTable},
+        kobject::{KObjType, KObject, KObjectCommonData, KObjectState, LockedKObjectState},
+        kset::KSet,
+    },
+    filesystem::{kernfs::KernFSInode, sysfs::AttributeGroup},
+    libs::rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard},
+};
+
+use super::{
+    attr::BasicPciReadOnlyAttrs, dev_id::PciDeviceID, device::PciDevice,
+    pci::PciDeviceStructureGeneralDevice,
+};
+#[derive(Debug)]
+#[cast_to([sync] Device)]
+#[cast_to([sync] PciDevice)]
+pub struct PciGeneralDevice {
+    device_data: RwLock<DeviceCommonData>,
+    kobj_data: RwLock<KObjectCommonData>,
+    name: RwLock<Option<String>>,
+    kobj_state: LockedKObjectState,
+    dev_id: PciDeviceID,
+    header: Arc<PciDeviceStructureGeneralDevice>,
+}
+
+impl From<&PciDeviceStructureGeneralDevice> for PciGeneralDevice {
+    fn from(value: &PciDeviceStructureGeneralDevice) -> Self {
+        let value = Arc::new(value.clone());
+        let name: String = value.common_header.bus_device_function.into();
+        let kobj_state = LockedKObjectState::new(None);
+        let common_dev = RwLock::new(DeviceCommonData::default());
+        let common_kobj = RwLock::new(KObjectCommonData::default());
+        let dev_id = PciDeviceID::dummpy();
+
+        // dev_id.set_special(PciSpecifiedData::Virtio());
+        let res = Self {
+            device_data: common_dev,
+            kobj_data: common_kobj,
+            kobj_state,
+            dev_id,
+            header: value,
+            name: RwLock::new(None),
+        };
+        res.set_name(name);
+        res
+    }
+}
+
+impl PciDevice for PciGeneralDevice {
+    fn dynid(&self) -> PciDeviceID {
+        self.dev_id
+    }
+
+    fn vendor(&self) -> u16 {
+        self.header.common_header.vendor_id
+    }
+
+    fn device_id(&self) -> u16 {
+        self.header.common_header.device_id
+    }
+
+    fn subsystem_vendor(&self) -> u16 {
+        self.header.subsystem_vendor_id
+    }
+
+    fn subsystem_device(&self) -> u16 {
+        self.header.subsystem_id
+    }
+}
+
+impl Device for PciGeneralDevice {
+    fn attribute_groups(&self) -> Option<&'static [&'static dyn AttributeGroup]> {
+        Some(&[&BasicPciReadOnlyAttrs])
+    }
+
+    fn bus(&self) -> Option<Weak<dyn Bus>> {
+        self.device_data.read().bus.clone()
+    }
+
+    fn class(&self) -> Option<Arc<dyn Class>> {
+        let mut guard = self.device_data.write();
+        let r = guard.class.clone()?.upgrade();
+        if r.is_none() {
+            guard.class = None;
+        }
+
+        return r;
+    }
+
+    fn driver(&self) -> Option<Arc<dyn Driver>> {
+        self.device_data.read().driver.clone()?.upgrade()
+    }
+
+    fn dev_type(&self) -> DeviceType {
+        DeviceType::Pci
+    }
+
+    fn id_table(&self) -> IdTable {
+        IdTable::new("testPci".to_string(), None)
+    }
+
+    fn can_match(&self) -> bool {
+        true
+    }
+
+    fn is_dead(&self) -> bool {
+        false
+    }
+
+    fn set_bus(&self, bus: Option<Weak<dyn Bus>>) {
+        self.device_data.write().bus = bus;
+    }
+
+    fn set_can_match(&self, _can_match: bool) {}
+
+    fn set_class(&self, class: Option<Weak<dyn Class>>) {
+        self.device_data.write().class = class;
+    }
+
+    fn set_driver(&self, driver: Option<Weak<dyn Driver>>) {
+        self.device_data.write().driver = driver
+    }
+
+    fn state_synced(&self) -> bool {
+        true
+    }
+}
+
+impl KObject for PciGeneralDevice {
+    fn as_any_ref(&self) -> &dyn Any {
+        self
+    }
+
+    fn set_inode(&self, inode: Option<Arc<KernFSInode>>) {
+        self.kobj_data.write().kern_inode = inode;
+    }
+
+    fn inode(&self) -> Option<Arc<KernFSInode>> {
+        self.kobj_data.read().kern_inode.clone()
+    }
+
+    fn parent(&self) -> Option<Weak<dyn KObject>> {
+        self.kobj_data.read().parent.clone()
+    }
+
+    fn set_parent(&self, parent: Option<Weak<dyn KObject>>) {
+        self.kobj_data.write().parent = parent;
+    }
+
+    fn kset(&self) -> Option<Arc<KSet>> {
+        self.kobj_data.read().kset.clone()
+    }
+
+    fn set_kset(&self, kset: Option<Arc<KSet>>) {
+        self.kobj_data.write().kset = kset;
+    }
+
+    fn kobj_type(&self) -> Option<&'static dyn KObjType> {
+        self.kobj_data.read().kobj_type
+    }
+
+    fn set_kobj_type(&self, ktype: Option<&'static dyn KObjType>) {
+        self.kobj_data.write().kobj_type = ktype;
+    }
+
+    fn name(&self) -> String {
+        self.name.read().clone().unwrap()
+    }
+
+    fn set_name(&self, name: String) {
+        *self.name.write() = Some(name);
+    }
+
+    fn kobj_state(&self) -> RwLockReadGuard<KObjectState> {
+        self.kobj_state.read()
+    }
+
+    fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> {
+        self.kobj_state.write()
+    }
+
+    fn set_kobj_state(&self, state: KObjectState) {
+        *self.kobj_state.write() = state;
+    }
+}

+ 65 - 42
kernel/src/driver/pci/root.rs

@@ -4,16 +4,17 @@ use alloc::sync::Arc;
 use hashbrown::HashMap;
 
 use crate::{
+    arch::{PciArch, TraitPciArch},
     libs::spinlock::{SpinLock, SpinLockGuard},
     mm::{
         mmio_buddy::{mmio_pool, MMIOSpaceGuard},
         page::PAGE_2M_SIZE,
-        PhysAddr,
     },
 };
 
-use super::pci::{
-    BusDeviceFunction, ExternalCapabilityIterator, PciCam, PciError, SegmentGroupNumber,
+use super::{
+    ecam::EcamRootInfo,
+    pci::{BusDeviceFunction, ExternalCapabilityIterator, PciCam, PciError, SegmentGroupNumber},
 };
 
 lazy_static! {
@@ -28,13 +29,14 @@ pub fn pci_root_manager() -> &'static PciRootManager {
 /// 代表一个PCI segement greoup.
 #[derive(Clone, Debug)]
 pub struct PciRoot {
-    pub physical_address_base: PhysAddr,          //物理地址,acpi获取
-    pub mmio_guard: Option<Arc<MMIOSpaceGuard>>,  //映射后的虚拟地址,为方便访问数据这里转化成指针
-    pub segment_group_number: SegmentGroupNumber, //segement greoup的id
-    pub bus_begin: u8,                            //该分组中的最小bus
-    pub bus_end: u8,                              //该分组中的最大bus
+    pub ecam_root_info: Option<EcamRootInfo>,
+    pub mmio_guard: Option<Arc<MMIOSpaceGuard>>, //映射后的虚拟地址,为方便访问数据这里转化成指针
     /// 配置空间访问机制
     pub cam: PciCam,
+    /// bus起始位置
+    pub bus_begin: u8,
+    /// bus结束位置
+    pub bus_end: u8,
 }
 
 ///线程间共享需要,该结构体只需要在初始化时写入数据,无需读写锁保证线程安全
@@ -43,11 +45,15 @@ unsafe impl Sync for PciRoot {}
 ///实现PciRoot的Display trait,自定义输出
 impl core::fmt::Display for PciRoot {
     fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
-        write!(
-                f,
-                "PCI Root with segement:{}, bus begin at {}, bus end at {}, physical address at {:?},mapped at {:?}",
-                self.segment_group_number, self.bus_begin, self.bus_end, self.physical_address_base, self.mmio_guard
-            )
+        if let Some(ecam_root_info) = &self.ecam_root_info {
+            write!(
+                    f,
+                    "PCI Eacm Root with segment:{}, bus begin at {}, bus end at {}, physical address at {:?},mapped at {:?}",
+                    ecam_root_info.segment_group_number, ecam_root_info.bus_begin, ecam_root_info.bus_end, ecam_root_info.physical_address_base, self.mmio_guard
+                )
+        } else {
+            write!(f, "PCI Root cam is {:?}", self.cam,)
+        }
     }
 }
 
@@ -69,29 +75,30 @@ impl PciRoot {
     ///
     /// - 成功执行后,结构体的内部状态将被初始化为包含映射后的虚拟地址。
     pub fn new(
-        segment_group_number: SegmentGroupNumber,
+        ecam_root_info: Option<EcamRootInfo>,
         cam: PciCam,
-        phys_base: PhysAddr,
         bus_begin: u8,
         bus_end: u8,
     ) -> Result<Arc<Self>, PciError> {
-        assert_eq!(cam, PciCam::Ecam);
         let mut pci_root = Self {
-            physical_address_base: phys_base,
+            ecam_root_info,
             mmio_guard: None,
-            segment_group_number,
+            cam,
             bus_begin,
             bus_end,
-            cam,
         };
-        pci_root.map()?;
+
+        if ecam_root_info.is_some() {
+            pci_root.map()?;
+        }
 
         Ok(Arc::new(pci_root))
     }
-    /// @brief  完成物理地址到虚拟地址的映射,并将虚拟地址加入mmio_base变量
-    /// @return 返回错误或Ok(0)
+
+    /// # 完成物理地址到虚拟地址的映射,并将虚拟地址加入mmio_base变量
+    /// ## return 返回错误或Ok(0)
     fn map(&mut self) -> Result<u8, PciError> {
-        //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空间的个数
 
@@ -104,7 +111,7 @@ impl PciRoot {
             self.mmio_guard = Some(space_guard.clone());
 
             assert!(space_guard
-                .map_phys(self.physical_address_base, size)
+                .map_phys(self.ecam_root_info.unwrap().physical_address_base, size)
                 .is_ok());
         }
         return Ok(0);
@@ -129,11 +136,12 @@ impl PciRoot {
     /// - 此函数计算出的地址需要是字对齐的(即地址与0x3对齐)。如果不是,将panic。
     fn cam_offset(&self, bus_device_function: BusDeviceFunction, register_offset: u16) -> u32 {
         assert!(bus_device_function.valid());
-        let bdf = ((bus_device_function.bus - self.bus_begin) as u32) << 8
+        let bdf = ((bus_device_function.bus - self.ecam_root_info.unwrap().bus_begin) as u32) << 8
             | (bus_device_function.device as u32) << 3
             | bus_device_function.function as u32;
         let address =
             bdf << match self.cam {
+                PciCam::Portiocam => 4,
                 PciCam::MmioCam => 8,
                 PciCam::Ecam => 12,
             } | register_offset as u32;
@@ -141,6 +149,7 @@ impl PciRoot {
         assert!(address & 0x3 == 0);
         address
     }
+
     /// # read_config - 通过bus_device_function和offset读取相应位置寄存器的值(32位)
     ///
     /// 此函数用于通过指定的bus_device_function和register_offset读取PCI设备中相应位置的寄存器值。
@@ -154,12 +163,16 @@ impl PciRoot {
     ///
     /// - `u32`: 寄存器读值结果
     pub fn read_config(&self, bus_device_function: BusDeviceFunction, register_offset: u16) -> u32 {
-        let address = self.cam_offset(bus_device_function, register_offset);
-        unsafe {
-            // Right shift to convert from byte offset to word offset.
-            ((self.mmio_guard.as_ref().unwrap().vaddr().data() as *mut u32)
-                .add((address >> 2) as usize))
-            .read_volatile()
+        if self.ecam_root_info.is_some() {
+            let address = self.cam_offset(bus_device_function, register_offset);
+            unsafe {
+                // Right shift to convert from byte offset to word offset.
+                ((self.mmio_guard.as_ref().unwrap().vaddr().data() as *mut u32)
+                    .add((address >> 2) as usize))
+                .read_volatile()
+            }
+        } else {
+            PciArch::read_config(&bus_device_function, register_offset as u8)
         }
     }
 
@@ -178,16 +191,21 @@ impl PciRoot {
         register_offset: u16,
         data: u32,
     ) {
-        let address = self.cam_offset(bus_device_function, register_offset);
-        // Safe because both the `mmio_base` and the address offset are properly aligned, and the
-        // resulting pointer is within the MMIO range of the CAM.
-        unsafe {
-            // Right shift to convert from byte offset to word offset.
-            ((self.mmio_guard.as_ref().unwrap().vaddr().data() as *mut u32)
-                .add((address >> 2) as usize))
-            .write_volatile(data)
+        if self.ecam_root_info.is_some() {
+            let address = self.cam_offset(bus_device_function, register_offset);
+            // Safe because both the `mmio_base` and the address offset are properly aligned, and the
+            // resulting pointer is within the MMIO range of the CAM.
+            unsafe {
+                // Right shift to convert from byte offset to word offset.
+                ((self.mmio_guard.as_ref().unwrap().vaddr().data() as *mut u32)
+                    .add((address >> 2) as usize))
+                .write_volatile(data)
+            }
+        } else {
+            PciArch::write_config(&bus_device_function, register_offset as u8, data);
         }
     }
+
     /// 返回迭代器,遍历pcie设备的external_capabilities
     #[allow(dead_code)]
     pub fn external_capabilities(
@@ -233,9 +251,14 @@ impl PciRootManager {
     /// - `pci_root`: Arc<PciRoot>,要添加的PciRoot的Arc指针
     pub fn add_pci_root(&self, pci_root: Arc<PciRoot>) {
         let mut inner = self.inner.lock();
-        inner
-            .pci_root
-            .insert(pci_root.segment_group_number, pci_root);
+
+        if let Some(ecam_root_info) = pci_root.ecam_root_info {
+            inner
+                .pci_root
+                .insert(ecam_root_info.segment_group_number, pci_root);
+        } else {
+            inner.pci_root.insert(pci_root.bus_begin as u16, pci_root);
+        }
     }
 
     /// # 检查是否存在PciRoot - 检查PciRootManager中是否存在指定segment_group_number的PciRoot

+ 191 - 0
kernel/src/driver/pci/subsys.rs

@@ -0,0 +1,191 @@
+use alloc::{
+    string::{String, ToString},
+    sync::{Arc, Weak},
+};
+use intertrait::cast::CastArc;
+use log::error;
+use system_error::SystemError;
+
+use crate::{
+    driver::base::{
+        device::{
+            bus::{bus_register, Bus},
+            device_register,
+            driver::Driver,
+            sys_devices_kset, Device,
+        },
+        kobject::KObject,
+        subsys::SubSysPrivate,
+    },
+    filesystem::sysfs::AttributeGroup,
+};
+
+use super::{
+    device::{PciBusDevice, PciDevice},
+    driver::PciDriver,
+    test::pt_init,
+};
+
+static mut PCI_BUS_DEVICE: Option<Arc<PciBusDevice>> = None;
+static mut PCI_BUS: Option<Arc<PciBus>> = None;
+
+pub(super) fn set_pci_bus_device(device: Arc<PciBusDevice>) {
+    unsafe {
+        PCI_BUS_DEVICE = Some(device);
+    }
+}
+
+pub(super) fn set_pci_bus(bus: Arc<PciBus>) {
+    unsafe {
+        PCI_BUS = Some(bus);
+    }
+}
+
+pub fn pci_bus_device() -> Arc<PciBusDevice> {
+    unsafe {
+        return PCI_BUS_DEVICE.clone().unwrap();
+    }
+}
+
+pub fn pci_bus() -> Arc<PciBus> {
+    unsafe {
+        return PCI_BUS.clone().unwrap();
+    }
+}
+
+/// # 结构功能
+/// 该结构为Pci总线,由于总线也属于设备,故设此结构;
+/// 此结构对应/sys/bus/pci
+#[derive(Debug)]
+pub struct PciBus {
+    private: SubSysPrivate,
+}
+
+impl PciBus {
+    pub fn new() -> Arc<Self> {
+        let w: Weak<Self> = Weak::new();
+        let private = SubSysPrivate::new("pci".to_string(), Some(w), None, &[]);
+        let bus = Arc::new(Self { private });
+        bus
+    }
+}
+
+impl Bus for PciBus {
+    fn name(&self) -> String {
+        return "pci".to_string();
+    }
+
+    fn dev_name(&self) -> String {
+        return self.name();
+    }
+
+    fn dev_groups(&self) -> &'static [&'static dyn AttributeGroup] {
+        return &[&PciDeviceAttrGroup];
+    }
+
+    fn subsystem(&self) -> &SubSysPrivate {
+        return &self.private;
+    }
+
+    fn probe(&self, device: &Arc<dyn Device>) -> Result<(), SystemError> {
+        let drv = device.driver().ok_or(SystemError::EINVAL)?;
+        let pci_drv = drv.cast::<dyn PciDriver>().map_err(|_| {
+            error!(
+                "PciBus::probe() failed: device.driver() is not a PciDriver. Device: '{:?}'",
+                device.name()
+            );
+            SystemError::EINVAL
+        })?;
+        let pci_dev = device.clone().cast::<dyn PciDevice>().map_err(|_| {
+            error!(
+                "PciBus::probe() failed: device is not a PciDevice. Device: '{:?}'",
+                device.name()
+            );
+            SystemError::EINVAL
+        })?;
+        //见https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/pci/pci-driver.c#324
+        let id = pci_drv.match_dev(&pci_dev).ok_or(SystemError::EINVAL)?;
+        pci_drv.probe(&pci_dev, &id)
+    }
+
+    fn remove(&self, _device: &Arc<dyn Device>) -> Result<(), SystemError> {
+        todo!()
+    }
+
+    fn sync_state(&self, _device: &Arc<dyn Device>) {
+        todo!()
+    }
+
+    fn shutdown(&self, _device: &Arc<dyn Device>) {
+        todo!()
+    }
+
+    fn resume(&self, _device: &Arc<dyn Device>) -> Result<(), SystemError> {
+        todo!()
+    }
+
+    fn match_device(
+        &self,
+        device: &Arc<dyn Device>,
+        driver: &Arc<dyn Driver>,
+    ) -> Result<bool, SystemError> {
+        //首先将设备和驱动映射为pci设备和pci驱动
+        let pci_driver = driver.clone().cast::<dyn PciDriver>().map_err(|_| {
+            return SystemError::EINVAL;
+        })?;
+        let pci_dev = device.clone().cast::<dyn PciDevice>().map_err(|_| {
+            return SystemError::EINVAL;
+        })?;
+        //pci_driver需要实现一个match_dev函数,即driver需要识别是否支持给定的pci设备
+        //这是主要的match方式
+        if pci_driver.match_dev(&pci_dev).is_some() {
+            return Ok(true);
+        }
+
+        //todo:这里似乎需要一个driver_override_only的支持,但是目前不清楚driver_override_only 的用途,故暂时参考platform总线的match方法
+        //override_only相关代码在 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/pci/pci-driver.c#159
+        if let Some(driver_id_table) = driver.id_table() {
+            if driver_id_table.name().eq(&pci_dev.name()) {
+                return Ok(true);
+            }
+        };
+        return Ok(pci_dev.name().eq(&pci_driver.name()));
+    }
+}
+
+#[derive(Debug)]
+pub struct PciDeviceAttrGroup;
+
+impl AttributeGroup for PciDeviceAttrGroup {
+    fn name(&self) -> Option<&str> {
+        return None;
+    }
+
+    fn attrs(&self) -> &[&'static dyn crate::filesystem::sysfs::Attribute] {
+        return &[];
+    }
+
+    fn is_visible(
+        &self,
+        _kobj: Arc<dyn crate::driver::base::kobject::KObject>,
+        attr: &'static dyn crate::filesystem::sysfs::Attribute,
+    ) -> Option<crate::filesystem::vfs::syscall::ModeType> {
+        return Some(attr.mode());
+    }
+}
+
+pub(super) fn pci_bus_subsys_init() -> Result<(), SystemError> {
+    let pci_bus_device: Arc<PciBusDevice> = PciBusDevice::new(Some(Arc::downgrade(
+        &(sys_devices_kset() as Arc<dyn KObject>),
+    )));
+
+    set_pci_bus_device(pci_bus_device.clone());
+
+    device_register(pci_bus_device.clone())?;
+    let pci_bus = PciBus::new();
+
+    set_pci_bus(pci_bus.clone());
+    let r = bus_register(pci_bus.clone() as Arc<dyn Bus>);
+    pt_init()?;
+    return r;
+}

+ 30 - 0
kernel/src/driver/pci/test/mod.rs

@@ -0,0 +1,30 @@
+use alloc::sync::Arc;
+use system_error::SystemError;
+
+use self::{pt_device::TestDevice, pt_driver::TestDriver};
+
+use super::{
+    dev_id::PciDeviceID,
+    device::pci_device_manager,
+    driver::{pci_driver_manager, PciDriver},
+};
+
+pub mod pt_device;
+pub mod pt_driver;
+
+static mut TEST_DRIVER: Option<Arc<TestDriver>> = None;
+static mut TEST_DEVICE: Option<Arc<TestDevice>> = None;
+pub fn pt_init() -> Result<(), SystemError> {
+    let tdev = Arc::new(TestDevice::new());
+    let mut drv = TestDriver::new();
+    drv.add_dynid(PciDeviceID::dummpy())?;
+    let tdrv = Arc::new(drv);
+
+    let _ = pci_device_manager().device_add(tdev.clone());
+    let _ = pci_driver_manager().register(tdrv.clone());
+    unsafe {
+        TEST_DEVICE = Some(tdev);
+        TEST_DRIVER = Some(tdrv);
+    }
+    Ok(())
+}

+ 236 - 0
kernel/src/driver/pci/test/pt_device.rs

@@ -0,0 +1,236 @@
+use core::any::Any;
+
+use alloc::{
+    string::{String, ToString},
+    sync::{Arc, Weak},
+};
+use system_error::SystemError;
+
+use crate::{
+    driver::{
+        base::{
+            class::Class,
+            device::{bus::Bus, driver::Driver, Device, DeviceCommonData, DeviceType, IdTable},
+            kobject::{KObjType, KObject, KObjectCommonData, KObjectState, LockedKObjectState},
+            kset::KSet,
+        },
+        pci::{dev_id::PciDeviceID, device::PciDevice},
+    },
+    filesystem::{
+        kernfs::KernFSInode,
+        sysfs::{
+            file::sysfs_emit_str, Attribute, AttributeGroup, SysFSOpsSupport, SYSFS_ATTR_MODE_RO,
+        },
+        vfs::syscall::ModeType,
+    },
+    libs::rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard},
+};
+#[derive(Debug)]
+#[cast_to([sync] Device)]
+#[cast_to([sync] PciDevice)]
+/// # 结构功能
+/// 这是一个测试用的PciDevice,也可以作为新PciDevice的参考
+/// 它需要实现KObject PciDevice Device这些接口
+/// 并通过函数pci_device_manager().device_add()来将设备进行接入
+pub struct TestDevice {
+    device_data: RwLock<DeviceCommonData>,
+    kobj_data: RwLock<KObjectCommonData>,
+    kobj_state: LockedKObjectState,
+}
+
+impl TestDevice {
+    pub fn new() -> Self {
+        let common_dev = RwLock::new(DeviceCommonData::default());
+        let common_kobj = RwLock::new(KObjectCommonData::default());
+        Self {
+            device_data: common_dev,
+            kobj_data: common_kobj,
+            kobj_state: LockedKObjectState::new(None),
+        }
+    }
+}
+
+impl PciDevice for TestDevice {
+    fn dynid(&self) -> PciDeviceID {
+        PciDeviceID::dummpy()
+    }
+
+    fn vendor(&self) -> u16 {
+        return 0xffff;
+    }
+
+    fn device_id(&self) -> u16 {
+        return 0xffff;
+    }
+
+    fn subsystem_vendor(&self) -> u16 {
+        return 0xffff;
+    }
+
+    fn subsystem_device(&self) -> u16 {
+        return 0xffff;
+    }
+}
+
+impl Device for TestDevice {
+    fn attribute_groups(&self) -> Option<&'static [&'static dyn AttributeGroup]> {
+        Some(&[&HelloAttr])
+    }
+
+    fn bus(&self) -> Option<Weak<dyn Bus>> {
+        self.device_data.read().bus.clone()
+    }
+
+    fn class(&self) -> Option<Arc<dyn Class>> {
+        let mut guard = self.device_data.write();
+        let r = guard.class.clone()?.upgrade();
+        if r.is_none() {
+            guard.class = None;
+        }
+
+        return r;
+    }
+
+    fn driver(&self) -> Option<Arc<dyn Driver>> {
+        self.device_data.read().driver.clone()?.upgrade()
+    }
+
+    fn dev_type(&self) -> DeviceType {
+        DeviceType::Pci
+    }
+
+    fn id_table(&self) -> IdTable {
+        IdTable::new("testPci".to_string(), None)
+    }
+
+    fn can_match(&self) -> bool {
+        true
+    }
+
+    fn is_dead(&self) -> bool {
+        false
+    }
+
+    fn set_bus(&self, bus: Option<Weak<dyn Bus>>) {
+        self.device_data.write().bus = bus
+    }
+
+    fn set_can_match(&self, _can_match: bool) {
+        //todo
+    }
+
+    fn set_class(&self, class: Option<Weak<dyn Class>>) {
+        self.device_data.write().class = class
+    }
+
+    fn set_driver(&self, driver: Option<Weak<dyn Driver>>) {
+        self.device_data.write().driver = driver
+    }
+
+    fn state_synced(&self) -> bool {
+        true
+    }
+}
+
+impl KObject for TestDevice {
+    fn as_any_ref(&self) -> &dyn Any {
+        self
+    }
+
+    fn set_inode(&self, inode: Option<Arc<KernFSInode>>) {
+        self.kobj_data.write().kern_inode = inode;
+    }
+
+    fn inode(&self) -> Option<Arc<KernFSInode>> {
+        self.kobj_data.read().kern_inode.clone()
+    }
+
+    fn parent(&self) -> Option<Weak<dyn KObject>> {
+        self.kobj_data.read().parent.clone()
+    }
+
+    fn set_parent(&self, parent: Option<Weak<dyn KObject>>) {
+        self.kobj_data.write().parent = parent;
+    }
+
+    fn kset(&self) -> Option<Arc<KSet>> {
+        self.kobj_data.read().kset.clone()
+    }
+
+    fn set_kset(&self, kset: Option<Arc<KSet>>) {
+        self.kobj_data.write().kset = kset;
+    }
+
+    fn kobj_type(&self) -> Option<&'static dyn KObjType> {
+        self.kobj_data.read().kobj_type
+    }
+
+    fn set_kobj_type(&self, ktype: Option<&'static dyn KObjType>) {
+        self.kobj_data.write().kobj_type = ktype;
+    }
+
+    fn name(&self) -> String {
+        "PciTest".to_string()
+    }
+
+    fn set_name(&self, _name: String) {
+        // do nothing
+    }
+
+    fn kobj_state(&self) -> RwLockReadGuard<KObjectState> {
+        self.kobj_state.read()
+    }
+
+    fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> {
+        self.kobj_state.write()
+    }
+
+    fn set_kobj_state(&self, state: KObjectState) {
+        *self.kobj_state.write() = state;
+    }
+}
+
+#[derive(Debug)]
+pub struct HelloAttr;
+
+impl AttributeGroup for HelloAttr {
+    fn name(&self) -> Option<&str> {
+        return Some("TestAttr");
+    }
+
+    fn attrs(&self) -> &[&'static dyn Attribute] {
+        &[&Hello]
+    }
+
+    fn is_visible(
+        &self,
+        _kobj: Arc<dyn KObject>,
+        attr: &'static dyn Attribute,
+    ) -> Option<ModeType> {
+        return Some(attr.mode());
+    }
+}
+#[derive(Debug)]
+pub struct Hello;
+
+impl Attribute for Hello {
+    fn mode(&self) -> ModeType {
+        SYSFS_ATTR_MODE_RO
+    }
+
+    fn name(&self) -> &str {
+        "Hello"
+    }
+
+    fn show(&self, _kobj: Arc<dyn KObject>, _buf: &mut [u8]) -> Result<usize, SystemError> {
+        return sysfs_emit_str(_buf, "Hello Pci");
+    }
+
+    fn store(&self, _kobj: Arc<dyn KObject>, _buf: &[u8]) -> Result<usize, SystemError> {
+        todo!()
+    }
+
+    fn support(&self) -> SysFSOpsSupport {
+        SysFSOpsSupport::ATTR_SHOW
+    }
+}

+ 171 - 0
kernel/src/driver/pci/test/pt_driver.rs

@@ -0,0 +1,171 @@
+use alloc::{
+    string::{String, ToString},
+    sync::{Arc, Weak},
+    vec::Vec,
+};
+
+use crate::{
+    driver::{
+        base::{
+            device::{
+                bus::Bus,
+                driver::{Driver, DriverCommonData},
+                Device, IdTable,
+            },
+            kobject::{KObjType, KObject, KObjectCommonData, KObjectState, LockedKObjectState},
+            kset::KSet,
+        },
+        pci::{dev_id::PciDeviceID, device::PciDevice, driver::PciDriver},
+    },
+    filesystem::kernfs::KernFSInode,
+    libs::rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard},
+};
+#[derive(Debug)]
+#[cast_to([sync] PciDriver)]
+pub struct TestDriver {
+    driver_data: RwLock<DriverCommonData>,
+    kobj_data: RwLock<KObjectCommonData>,
+    kobj_state: LockedKObjectState,
+    pub locked_dynid_list: RwLock<Vec<Arc<PciDeviceID>>>,
+}
+
+/// # 结构功能
+/// 本结构体是测试用的驱动,目前暂时保留,否则将出现大量dead code
+/// 在编写了实际的pci驱动后,可将该驱动删除
+impl TestDriver {
+    pub fn new() -> Self {
+        Self {
+            driver_data: RwLock::new(DriverCommonData::default()),
+            kobj_data: RwLock::new(KObjectCommonData::default()),
+            kobj_state: LockedKObjectState::new(None),
+            locked_dynid_list: RwLock::new(vec![]),
+        }
+    }
+}
+
+impl PciDriver for TestDriver {
+    fn add_dynid(&mut self, id: PciDeviceID) -> Result<(), system_error::SystemError> {
+        let id = Arc::new(id);
+        self.locked_dynid_list.write().push(id);
+        Ok(())
+    }
+
+    fn locked_dynid_list(&self) -> Option<Vec<Arc<PciDeviceID>>> {
+        Some(self.locked_dynid_list.read().clone())
+    }
+
+    fn probe(
+        &self,
+        _device: &Arc<dyn PciDevice>,
+        _id: &PciDeviceID,
+    ) -> Result<(), system_error::SystemError> {
+        Ok(())
+    }
+
+    fn remove(&self, _device: &Arc<dyn PciDevice>) -> Result<(), system_error::SystemError> {
+        Ok(())
+    }
+
+    fn resume(&self, _device: &Arc<dyn PciDevice>) -> Result<(), system_error::SystemError> {
+        Ok(())
+    }
+
+    fn shutdown(&self, _device: &Arc<dyn PciDevice>) -> Result<(), system_error::SystemError> {
+        Ok(())
+    }
+
+    fn suspend(&self, _device: &Arc<dyn PciDevice>) -> Result<(), system_error::SystemError> {
+        Ok(())
+    }
+}
+
+impl Driver for TestDriver {
+    fn id_table(&self) -> Option<IdTable> {
+        Some(IdTable::new("PciTestDriver".to_string(), None))
+    }
+
+    fn devices(&self) -> Vec<Arc<dyn Device>> {
+        self.driver_data.read().devices.clone()
+    }
+
+    fn add_device(&self, device: Arc<dyn Device>) {
+        let mut guard = self.driver_data.write();
+        // check if the device is already in the list
+        if guard.devices.iter().any(|dev| Arc::ptr_eq(dev, &device)) {
+            return;
+        }
+
+        guard.devices.push(device);
+    }
+
+    fn delete_device(&self, device: &Arc<dyn Device>) {
+        let mut guard = self.driver_data.write();
+        guard.devices.retain(|dev| !Arc::ptr_eq(dev, device));
+    }
+
+    fn set_bus(&self, bus: Option<Weak<dyn Bus>>) {
+        self.driver_data.write().bus = bus;
+    }
+
+    fn bus(&self) -> Option<Weak<dyn Bus>> {
+        self.driver_data.read().bus.clone()
+    }
+}
+
+impl KObject for TestDriver {
+    fn as_any_ref(&self) -> &dyn core::any::Any {
+        self
+    }
+
+    fn set_inode(&self, inode: Option<Arc<KernFSInode>>) {
+        self.kobj_data.write().kern_inode = inode;
+    }
+
+    fn inode(&self) -> Option<Arc<KernFSInode>> {
+        self.kobj_data.read().kern_inode.clone()
+    }
+
+    fn parent(&self) -> Option<Weak<dyn KObject>> {
+        self.kobj_data.read().parent.clone()
+    }
+
+    fn set_parent(&self, parent: Option<Weak<dyn KObject>>) {
+        self.kobj_data.write().parent = parent;
+    }
+
+    fn kset(&self) -> Option<Arc<KSet>> {
+        self.kobj_data.read().kset.clone()
+    }
+
+    fn set_kset(&self, kset: Option<Arc<KSet>>) {
+        self.kobj_data.write().kset = kset;
+    }
+
+    fn kobj_type(&self) -> Option<&'static dyn KObjType> {
+        self.kobj_data.read().kobj_type
+    }
+
+    fn set_kobj_type(&self, ktype: Option<&'static dyn KObjType>) {
+        self.kobj_data.write().kobj_type = ktype;
+    }
+
+    fn name(&self) -> String {
+        "PciTestDriver".to_string()
+    }
+
+    fn set_name(&self, _name: String) {
+        // do nothing
+    }
+
+    fn kobj_state(&self) -> RwLockReadGuard<KObjectState> {
+        self.kobj_state.read()
+    }
+
+    fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> {
+        self.kobj_state.write()
+    }
+
+    fn set_kobj_state(&self, state: KObjectState) {
+        *self.kobj_state.write() = state;
+    }
+}

+ 2 - 1
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<RtcGeneralDevice>) {
     let r = do_settimeofday64(timespec64);
     dev.set_hc2sys_result(r);
 
-    kinfo!(
+    info!(
         "Setting system clock to {} {} UTC ({})",
         time.date_string(),
         time.time_string(),

+ 2 - 1
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::<Serial8250ISADevices>()
             .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()));

+ 2 - 1
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);
                 }

+ 3 - 2
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,

+ 2 - 1
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;

部分文件因为文件数量过多而无法显示