Browse Source

Revert "feat: 初步支持动态链接程序运行 (#908)" (#966)

This reverts commit c966d612d2af506ae5ae29cf90411050afa2a35e.
Chiichen 5 months ago
parent
commit
9ee2f64323
100 changed files with 704 additions and 2025 deletions
  1. 9 12
      .github/workflows/cache-toolchain.yml
  2. 2 2
      .github/workflows/makefile.yml
  3. 2 2
      Makefile
  4. 56 20
      README.md
  5. 59 21
      README_EN.md
  6. 1 1
      build-scripts/.gitignore
  7. 0 2
      build-scripts/Makefile
  8. 2 0
      build-scripts/kernel_build/src/lib.rs
  9. 0 1062
      docs/community/ChangeLog/V0.1.x/V0.1.10.md
  10. 0 1
      docs/community/ChangeLog/index.rst
  11. 4 11
      docs/conf.py
  12. 0 1
      docs/introduction/build_system.md
  13. 2 2
      docs/kernel/locking/mutex.md
  14. 2 2
      docs/kernel/locking/spinlock.md
  15. 13 17
      docs/kernel/sched/cfs.md
  16. 8 59
      docs/kernel/sched/core.md
  17. 0 4
      kernel/.cargo/config.toml
  18. 10 14
      kernel/Cargo.toml
  19. 5 5
      kernel/Makefile
  20. 0 1
      kernel/crates/bitmap/src/lib.rs
  21. 0 9
      kernel/crates/bitmap/src/static_bitmap.rs
  22. 5 0
      kernel/crates/bitmap/src/traits.rs
  23. 0 6
      kernel/crates/klog_types/src/lib.rs
  24. 3 5
      kernel/crates/rust-slabmalloc/src/pages.rs
  25. 1 1
      kernel/crates/unified-init/Cargo.toml
  26. 1 1
      kernel/crates/unified-init/macros/Cargo.toml
  27. 1 1
      kernel/crates/unified-init/src/lib.rs
  28. 0 7
      kernel/crates/wait_queue_macros/Cargo.toml
  29. 0 60
      kernel/crates/wait_queue_macros/src/lib.rs
  30. 0 3
      kernel/env.mk
  31. 1 1
      kernel/rust-toolchain.toml
  32. 2 2
      kernel/src/Makefile
  33. 0 1
      kernel/src/arch/io.rs
  34. 2 2
      kernel/src/arch/riscv64/driver/of.rs
  35. 6 5
      kernel/src/arch/riscv64/init/mod.rs
  36. 22 18
      kernel/src/arch/riscv64/interrupt/handle.rs
  37. 6 7
      kernel/src/arch/riscv64/ipc/signal.rs
  38. 12 12
      kernel/src/arch/riscv64/mm/init.rs
  39. 4 70
      kernel/src/arch/riscv64/mm/mod.rs
  40. 5 4
      kernel/src/arch/riscv64/pci/pci_host_ecam.rs
  41. 3 5
      kernel/src/arch/riscv64/process/idle.rs
  42. 5 5
      kernel/src/arch/riscv64/process/mod.rs
  43. 17 11
      kernel/src/arch/riscv64/process/syscall.rs
  44. 8 6
      kernel/src/arch/riscv64/smp/mod.rs
  45. 2 2
      kernel/src/arch/riscv64/syscall/mod.rs
  46. 4 5
      kernel/src/arch/riscv64/time.rs
  47. 2 3
      kernel/src/arch/x86_64/acpi.rs
  48. 13 13
      kernel/src/arch/x86_64/driver/apic/apic_timer.rs
  49. 7 7
      kernel/src/arch/x86_64/driver/apic/ioapic.rs
  50. 3 4
      kernel/src/arch/x86_64/driver/apic/lapic_vector.rs
  51. 7 7
      kernel/src/arch/x86_64/driver/apic/mod.rs
  52. 6 5
      kernel/src/arch/x86_64/driver/apic/x2apic.rs
  53. 6 7
      kernel/src/arch/x86_64/driver/apic/xapic.rs
  54. 14 8
      kernel/src/arch/x86_64/driver/hpet.rs
  55. 2 2
      kernel/src/arch/x86_64/driver/rtc.rs
  56. 19 19
      kernel/src/arch/x86_64/driver/tsc.rs
  57. 6 7
      kernel/src/arch/x86_64/init/mod.rs
  58. 0 1
      kernel/src/arch/x86_64/interrupt/entry.rs
  59. 5 5
      kernel/src/arch/x86_64/interrupt/ipi.rs
  60. 2 8
      kernel/src/arch/x86_64/interrupt/mod.rs
  61. 0 1
      kernel/src/arch/x86_64/interrupt/msi.rs
  62. 23 23
      kernel/src/arch/x86_64/interrupt/trap.rs
  63. 20 21
      kernel/src/arch/x86_64/ipc/signal.rs
  64. 9 6
      kernel/src/arch/x86_64/kvm/mod.rs
  65. 2 2
      kernel/src/arch/x86_64/kvm/vmx/ept.rs
  66. 5 5
      kernel/src/arch/x86_64/kvm/vmx/mmu.rs
  67. 35 33
      kernel/src/arch/x86_64/kvm/vmx/vcpu.rs
  68. 15 16
      kernel/src/arch/x86_64/kvm/vmx/vmexit.rs
  69. 8 9
      kernel/src/arch/x86_64/kvm/vmx/vmx_asm_wrapper.rs
  70. 14 12
      kernel/src/arch/x86_64/mm/fault.rs
  71. 28 114
      kernel/src/arch/x86_64/mm/mod.rs
  72. 2 2
      kernel/src/arch/x86_64/mm/pkru.rs
  73. 0 1
      kernel/src/arch/x86_64/mod.rs
  74. 5 37
      kernel/src/arch/x86_64/pci/pci.rs
  75. 2 3
      kernel/src/arch/x86_64/process/idle.rs
  76. 2 1
      kernel/src/arch/x86_64/process/kthread.rs
  77. 5 5
      kernel/src/arch/x86_64/process/mod.rs
  78. 19 17
      kernel/src/arch/x86_64/process/syscall.rs
  79. 0 1
      kernel/src/arch/x86_64/process/table.rs
  80. 3 4
      kernel/src/arch/x86_64/smp/mod.rs
  81. 3 4
      kernel/src/arch/x86_64/syscall/mod.rs
  82. 1 1
      kernel/src/arch/x86_64/x86_64-unknown-none.json
  83. 16 11
      kernel/src/debug/klog/mm.rs
  84. 0 2
      kernel/src/driver/acpi/bus.rs
  85. 5 5
      kernel/src/driver/acpi/mod.rs
  86. 1 1
      kernel/src/driver/acpi/pmtmr.rs
  87. 6 6
      kernel/src/driver/acpi/sysfs.rs
  88. 16 14
      kernel/src/driver/base/block/block_device.rs
  89. 4 4
      kernel/src/driver/base/char/mod.rs
  90. 8 8
      kernel/src/driver/base/device/bus.rs
  91. 21 21
      kernel/src/driver/base/device/dd.rs
  92. 6 7
      kernel/src/driver/base/device/driver.rs
  93. 13 10
      kernel/src/driver/base/device/init.rs
  94. 18 16
      kernel/src/driver/base/device/mod.rs
  95. 3 3
      kernel/src/driver/base/kobject.rs
  96. 0 1
      kernel/src/driver/base/platform/platform_device.rs
  97. 0 1
      kernel/src/driver/base/platform/platform_driver.rs
  98. 2 3
      kernel/src/driver/base/platform/subsys.rs
  99. 1 4
      kernel/src/driver/block/cache/cached_block_device.rs
  100. 6 6
      kernel/src/driver/block/virtio_blk.rs

+ 9 - 12
.github/workflows/cache-toolchain.yml

@@ -51,17 +51,17 @@ jobs:
 
             cargo install cargo-binutils
             rustup toolchain install nightly-x86_64-unknown-linux-gnu
-            rustup toolchain install nightly-2024-07-23-x86_64-unknown-linux-gnu
+            rustup toolchain install nightly-2023-01-21-x86_64-unknown-linux-gnu
             rustup toolchain install nightly-2023-08-15-x86_64-unknown-linux-gnu
-            rustup component add rust-src --toolchain nightly-2024-07-23-x86_64-unknown-linux-gnu
+            rustup component add rust-src --toolchain nightly-2023-01-21-x86_64-unknown-linux-gnu
             rustup component add rust-src --toolchain nightly-2023-08-15-x86_64-unknown-linux-gnu
-            rustup target add x86_64-unknown-none --toolchain nightly-2024-07-23-x86_64-unknown-linux-gnu
+            rustup target add x86_64-unknown-none --toolchain nightly-2023-01-21-x86_64-unknown-linux-gnu
             rustup target add x86_64-unknown-none --toolchain nightly-2023-08-15-x86_64-unknown-linux-gnu
 
-            rustup toolchain install nightly-2024-07-23-riscv64gc-unknown-linux-gnu --force-non-host
+            rustup toolchain install nightly-2023-01-21-riscv64gc-unknown-linux-gnu --force-non-host
             rustup toolchain install nightly-2023-08-15-riscv64gc-unknown-linux-gnu --force-non-host
-            rustup target add riscv64gc-unknown-none-elf --toolchain nightly-2024-07-23-riscv64gc-unknown-linux-gnu
-            rustup target add riscv64imac-unknown-none-elf --toolchain nightly-2024-07-23-riscv64gc-unknown-linux-gnu
+            rustup target add riscv64gc-unknown-none-elf --toolchain nightly-2023-01-21-riscv64gc-unknown-linux-gnu
+            rustup target add riscv64imac-unknown-none-elf --toolchain nightly-2023-01-21-riscv64gc-unknown-linux-gnu
             rustup target add riscv64gc-unknown-none-elf --toolchain nightly-2023-08-15-riscv64gc-unknown-linux-gnu
             rustup target add riscv64imac-unknown-none-elf --toolchain nightly-2023-08-15-riscv64gc-unknown-linux-gnu
                 
@@ -71,12 +71,12 @@ jobs:
 
             rustup component add rustfmt
             rustup component add rustfmt --toolchain nightly-x86_64-unknown-linux-gnu
-            rustup component add rustfmt --toolchain nightly-2024-07-23-x86_64-unknown-linux-gnu
+            rustup component add rustfmt --toolchain nightly-2023-01-21-x86_64-unknown-linux-gnu
             rustup component add rustfmt --toolchain nightly-2023-08-15-x86_64-unknown-linux-gnu
-            rustup component add rustfmt --toolchain nightly-2024-07-23-riscv64gc-unknown-linux-gnu
+            rustup component add rustfmt --toolchain nightly-2023-01-21-riscv64gc-unknown-linux-gnu
             rustup component add rustfmt --toolchain nightly-2023-08-15-riscv64gc-unknown-linux-gnu
 
-            rustup default nightly-2024-07-23
+            rustup default nightly
 
             cargo install dadk --version 0.1.11
           
@@ -86,9 +86,6 @@ jobs:
             rustup toolchain install ${userapp_musl_toolchain}
             rustup component add --toolchain ${userapp_musl_toolchain} rust-src
             rustup target add --toolchain ${userapp_musl_toolchain} x86_64-unknown-linux-musl
-
-            rustup target add x86_64-unknown-linux-musl --toolchain nightly-2024-07-23-x86_64-unknown-linux-gnu
-            rustup component add rust-src --toolchain nightly-2024-07-23-x86_64-unknown-linux-gnu
            
 
 

+ 2 - 2
.github/workflows/makefile.yml

@@ -2,9 +2,9 @@ name: Build Check
 
 on:
   push:
-    branches: [ "master", "feat-*", "fix-*"]
+    branches: [ "master" ]
   pull_request:
-    branches: [ "master", "feat-*", "fix-*"]
+    branches: [ "master" ]
 
 jobs:
   # ensure the toolchain is cached

+ 2 - 2
Makefile

@@ -156,14 +156,14 @@ log-monitor:
 .PHONY: update-submodules
 update-submodules:
 	@echo "更新子模块"
-	@git submodule update --recursive --init
+	@git submodule update --recursive
 	@git submodule foreach git pull origin master
 
 .PHONY: update-submodules-by-mirror
 update-submodules-by-mirror:
 	@echo "从镜像更新子模块"
 	@git config --global url."https://git.mirrors.dragonos.org.cn/DragonOS-Community/".insteadOf https://github.com/DragonOS-Community/
-	@$(MAKE) update-submodules --init
+	@$(MAKE) update-submodules
 	@git config --global --unset url."https://git.mirrors.dragonos.org.cn/DragonOS-Community/".insteadOf
 
 help:

+ 56 - 20
README.md

@@ -26,25 +26,25 @@
   DragonOS目前在社区驱动下正在快速发展中,目前DragonOS已经实现了约1/4的Linux接口,在未来我们将提供对Linux的100%兼容性,并且提供新特性。
 
 
-## 参与开发?
-
-仔细阅读 [DragonOS社区介绍文档] ,能够帮助你了解社区的运作方式,以及如何参与贡献!
-
-- **了解开发动态、开发任务,请访问DragonOS社区论坛**: [https://bbs.dragonos.org.cn](https://bbs.dragonos.org.cn)
-- 您也可以从项目的issue里面了解相关的开发内容。
+[关于DragonOS,你想了解的都在这儿 - DragonOS](https://dragonos.org/?p=46)
 
+## 网站
 
-  如果你愿意加入我们,你可以查看issue,并在issue下发表讨论、想法,或者访问DragonOS的论坛,了解开发动态、开发任务: [https://bbs.dragonos.org.cn](https://bbs.dragonos.org.cn)
+- 项目官网  **[DragonOS.org](https://dragonos.org)**
 
-  你也可以带着你的创意与想法,和社区的小伙伴一起讨论,为DragonOS创造一些新的功能。
+- 项目文档  **[docs.DragonOS.org](https://docs.dragonos.org)**
 
-## 网站
+- **了解开发动态、开发任务,请访问DragonOS社区论坛**: [https://bbs.dragonos.org.cn](https://bbs.dragonos.org.cn)
 
+- 软件镜像站 **[mirrors.DragonOS.org](https://mirrors.DragonOS.org)**
+- Git镜像站 **[git.mirrors.DragonOS.org](https://git.mirrors.DragonOS.org)**
+- 国内镜像站 **[mirrors.DragonOS.org.cn](https://mirrors.DragonOS.org.cn)**
 
-- 项目官网  **[DragonOS.org](https://dragonos.org)**
-- 文档:**[docs.dragonos.org](https://docs.dragonos.org)**
-- 社区介绍文档: **[community.dragonos.org](https://community.dragonos.org)**
+- 开发交流QQ群 **115763565**
 
+- 代码搜索引擎 [code.DragonOS.org](http://code.dragonos.org)
+  
+   
 
 ## 如何运行?
 
@@ -52,20 +52,34 @@
 
 - [构建DragonOS — DragonOS dev 文档](https://docs.dragonos.org/zh_CN/latest/introduction/build_system.html)
 
+## 系统特性
+
+  请参见文档:[系统特性](https://docs.dragonos.org/zh_CN/latest/introduction/features.html)
+
+## 如何加入?
 
+  如果你愿意加入我们,你可以查看issue,并在issue下发表讨论、想法,或者访问DragonOS的论坛,了解开发动态、开发任务: [https://bbs.dragonos.org.cn](https://bbs.dragonos.org.cn)
+
+  你也可以带着你的创意与想法,和社区的小伙伴一起讨论,为DragonOS创造一些新的功能。
 
 ## 如何与社区建立联系?
 
-请阅读[贡献者指南](https://community.dragonos.org/contributors/#%E7%A4%BE%E5%8C%BA)~
+  你可以发邮件给Maintainer: longjin,邮件地址是 [[email protected]](mailto:[email protected]) 。
+
+  或者是加入我们的开发交流QQ群:**115763565**
+
+  对于正式问题的讨论,请在 **[https://bbs.dragonos.org.cn](https://bbs.dragonos.org.cn)** 上的对应板块,使用正式的语言发帖讨论。亦或者是在本仓库的issue下提出问题。
 
-- 您可以通过[社区管理团队]信息,与各委员会的成员们建立联系~
-- 同时,您可以通过[SIGs]和[WGs]页面,找到对应的社区团体负责人的联系方式~
 
 ## 贡献者名单
 
 [Contributors to DragonOS-Community/DragonOS · GitHub](https://github.com/DragonOS-Community/DragonOS/graphs/contributors)
 
+## 联系我们
 
+社区对外联系邮箱:[email protected]
+
+社区负责人邮箱:[email protected]
 
 ## 赞助
 
@@ -120,10 +134,32 @@
 
 **我们谴责**:任何不遵守开源协议的行为。包括但不限于:剽窃该项目的代码作为你的毕业设计等学术不端行为以及商业闭源使用而不付费。
 
-若您发现了任何违背开源协议的使用行为,我们欢迎您发邮件到 [email protected] 反馈!让我们共同建设诚信的开源社区。
+若您发现了任何违背开源协议的使用行为,我们欢迎您发邮件反馈!让我们共同建设诚信的开源社区。
+
+## 参考资料
+
+  本项目参考了以下资料,我对这些项目、书籍、文档的作者表示感谢!
+
+- 《一个64位操作系统的实现》田宇(人民邮电出版社)
+
+- 《现代操作系统 原理与实现》陈海波、夏虞斌(机械工业出版社)
+
+- [SimpleKernel](https://github.com/Simple-XX/SimpleKernel)
+
+- [osdev.org](https://wiki.osdev.org/Main_Page)
+
+- ACPI_6_3_final_Jan30
+
+- the GNU GRUB manual
+
+- Intel® 64 and IA-32 Architectures Software Developer’s Manual
+
+- IA-PC HPET (High Precision Event Timers) Specification
+
+- [skiftOS]([GitHub - skiftOS/skift: 🥑 A hobby operating system built from scratch in modern C++. Featuring a reactive UI library and a strong emphasis on user experience.](https://github.com/skiftOS/skift))
+
+- [GuideOS](https://github.com/Codetector1374/GuideOS)
 
+- [redox-os](https://gitlab.redox-os.org/redox-os/redox)
 
-[DragonOS社区介绍文档]: https://community.dragonos.org/
-[社区管理团队]: https://community.dragonos.org/governance/staff-info.html
-[SIGs]: https://community.dragonos.org/sigs/
-[WGs]: https://community.dragonos.org/wgs/
+- [rcore](https://github.com/rcore-os/rCore)

+ 59 - 21
README_EN.md

@@ -25,37 +25,52 @@
 
   Driven by the community, DragonOS is currently evolving rapidly. DragonOS has already implemented about 1/4 of Linux interfaces, and in the future, we will strive to provide 100% compatibility with Linux, along with new features.
 
+[All you want to know about DragonOS is here - DragonOS](https://dragonos.org/?p=46)
 
-## Get Involved in Development?
+## Websites
 
-Carefully read the [DragonOS Community Introduction Document] to understand how the community operates and how you can contribute!
+- Home Page  **[DragonOS.org](https://dragonos.org)**
+- Documentation  **[docs.DragonOS.org](https://docs.dragonos.org)**
+- **To learn about development dynamics and development tasks, please visit DragonOS's BBS:** [https://bbs.dragonos.org.cn](https://bbs.dragonos.org.cn)
+- Software mirror website **[mirrors.DragonOS.org](https://mirrors.DragonOS.org)**
+- Git mirror website **[git.mirrors.DragonOS.org](https://git.mirrors.DragonOS.org)**
+- QQ group **115763565**
+- Code search engine [code.DragonOS.org](http://code.dragonos.org) 
 
-- **To stay updated on development news and tasks, visit the DragonOS Community Forum**: [https://bbs.dragonos.org.cn](https://bbs.dragonos.org.cn)
-- You can also learn about the development progress by checking the project's issues.
+## How to run?
 
-  If you're interested in joining us, you can check out the issues and post your discussions or ideas under them, or visit the DragonOS forum to learn about development updates and tasks: [https://bbs.dragonos.org.cn](https://bbs.dragonos.org.cn)
+  The steps to run DragonOS are very simple. You can refer to the following information to run DragonOS within 15 minutes at the fastest!
 
-  You're also welcome to bring your creative ideas and discuss them with the community members, working together to create new features for DragonOS.
+- [Building DragonOS - DragonOS dev document](https://docs.dragonos.org/zh_CN/latest/introduction/build_system.html)
 
+## DragonOS' Features
 
-## Website
+  See documentation:[Features](https://docs.dragonos.org/zh_CN/latest/introduction/features.html)
 
-- **Project's Website**: [DragonOS.org](https://dragonos.org)
-- Documentation: [docs.dragonos.org](https://docs.dragonos.org)
-- Community Introduction Document: [community.dragonos.org](https://community.dragonos.org)
+## How to join DragonOS ?
 
-## How to Run?
+  If you are willing to join us, you can visit DragonOS's BBS , learn about development dynamics and development tasks: [https://bbs.dragonos.org.cn](https://bbs.dragonos.org.cn)
 
-  Running DragonOS is quite straightforward. You can refer to the following resources and get DragonOS up and running in as little as 15 minutes!
+  Or, you can also bring your ideas, discuss with community members, and create some new functions for DragonOS.
 
-- [Building DragonOS — DragonOS Development Documentation](https://docs.dragonos.org/zh_CN/latest/introduction/build_system.html)
+## How to contact the community?
 
-## How to Connect with the Community?
+  You can send an email to the project's maintainer: longjin. His email address is [[email protected]](mailto: [email protected]) .
 
-Please read the [Contributor Guide](https://community.dragonos.org/contributors/#%E7%A4%BE%E5%8C%BA)~
+  Or join our development exchange QQ group: **115763565**
 
-- You can establish contact with the members of various committees through the [Community Management Team] information.
-- Additionally, you can find the contact information of the respective community group leaders via the [SIGs] and [WGs] pages.
+  For the discussion of formal issues, we recommend that you use the official language to post on the corresponding section of **[https://bbs.dragonos.org.cn](https://bbs.dragonos.org.cn)**. Or you can post questions under the issue of this repository.
+
+
+## List of contributors
+
+[Contributors to DragonOS-Community/DragonOS · GitHub](https://github.com/DragonOS-Community/DragonOS/graphs/contributors)
+
+## Get contact with us
+
+Community Contact Email: [email protected]
+
+Maintainer longjin's Email:[email protected]
 
 
 ## Reward
@@ -113,7 +128,30 @@ We guarantee that all sponsorship funds and items will be used for:
 
 If you find any violation of the open source license, we welcome you to send email feedback! Let's build an honest open source community together!
 
-[DragonOS Community Introduction Document]: https://community.dragonos.org/
-[Community Management Team]: https://community.dragonos.org/governance/staff-info.html
-[SIGs]: https://community.dragonos.org/sigs/
-[WGs]: https://community.dragonos.org/wgs/
+## References
+
+  This project refers to the following materials. I sincerely give my thanks to the authors of these projects, books and documents!
+
+- Implementation of a 64 bit operating system, Tian Yu (POSTS&TELECOM  PRESS)
+
+- Principle and implementation of modern operating system, Chen Haibo, Xia Yubin (China Machine Press)
+
+- [SimpleKernel](https://github.com/Simple-XX/SimpleKernel)
+
+- [osdev.org](https://wiki.osdev.org/Main_Page)
+
+- ACPI_6_3_final_Jan30
+
+- the GNU GRUB manual
+
+- Intel® 64 and IA-32 Architectures Software Developer’s Manual
+
+- IA-PC HPET (High Precision Event Timers) Specification
+
+- [skiftOS]([GitHub - skiftOS/skift: 🥑 A hobby operating system built from scratch in modern C++. Featuring a reactive UI library and a strong emphasis on user experience.](https://github.com/skiftOS/skift))
+
+- [GuideOS](https://github.com/Codetector1374/GuideOS)
+
+- [redox-os](https://gitlab.redox-os.org/redox-os/redox)
+
+- [rcore](https://github.com/rcore-os/rCore)

+ 1 - 1
build-scripts/.gitignore

@@ -1 +1 @@
-/target/
+target

+ 0 - 2
build-scripts/Makefile

@@ -4,5 +4,3 @@ fmt:
 
 clean:
 	@cargo clean
-check:
-	@cargo +nightly-2024-07-23 check --workspace $(CARGO_ZBUILD) --message-format=json

+ 2 - 0
build-scripts/kernel_build/src/lib.rs

@@ -1,3 +1,5 @@
+#![feature(cfg_target_abi)]
+
 #[macro_use]
 extern crate lazy_static;
 extern crate cc;

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

@@ -1,1062 +0,0 @@
-# V0.1.10
-
-:::{note}
-本文作者:龙进 <[email protected]>
-
-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 <[email protected]>
-Date:   Mon May 13 15:36:23 2024 +0800
-
-    doc: Add Gentoo Linux In build_system.md (#810)
-    
-    * 增加安装文档中的Gentoo Linux提示
-
-commit 1f4877a4c512eb5ad232436128a0c52287b39aaa
-Author: 曾俊 <[email protected]>
-Date:   Mon May 13 15:27:08 2024 +0800
-
-    feat(driver/pci): add pci bus into sysfs (#792)
-    
-    把pci设备加入sysfs
-
-commit 1df85daf8f1b4426fe09d489d815997cdf989a87
-Author: donjuanplatinum <[email protected]>
-Date:   Sun May 12 22:58:59 2024 +0800
-
-    添加支持gentoo系统的一键安装脚本 (#809)
-
-commit 352ee04918f4585ad4f8a896ca6e18b1ef7d7934
-Author: LoGin <[email protected]>
-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 <[email protected]>
-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 <[email protected]>
-Date:   Tue May 7 22:01:01 2024 +0800
-
-    docs(sched):调度子系统文档即cfs文档 (#807)
-    
-    * 调度子系统文档以及cfs文档
-
-commit 0102d69fdd231e472d7bb3d609a41ae56a3799ee
-Author: LoGin <[email protected]>
-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 <[email protected]>
-Date:   Wed May 1 21:09:51 2024 +0800
-
-    修复vma映射标志错误 (#801)
-
-commit 7db6e06354328ea7c6164723f504e8ba58d0c4a4
-Author: LoGin <[email protected]>
-Date:   Tue Apr 30 18:45:01 2024 +0800
-
-    feat(bitmap): Add bit and for AllocBitMap (#793)
-
-commit 7401bec5e3c42015399a46e29c370abe7c7388b5
-Author: laokengwt <[email protected]>
-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: 曾俊 <[email protected]>
-Date:   Mon Apr 29 18:55:17 2024 +0800
-
-    修复了未初始化时ui显示模块内存越界的问题,优化了代码结构 (#789)
-
-commit 0722a06a09ed52cb980a6147123453f86d0ea267
-Author: LoGin <[email protected]>
-Date:   Sun Apr 28 19:40:09 2024 +0800
-
-    fix: (riscv/timer): 修复riscv下没有更新墙上时钟以及没有处理软中断的bug (#783)
-
-commit ab53b2eb75fe79167aa100e655b3589ee306f793
-Author: Chiichen <[email protected]>
-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 <[email protected]>
-Date:   Sun Apr 28 16:49:40 2024 +0800
-
-    fix(riscv/process): 把riscv的调度时钟节拍率与HZ同步,并且修复切换到用户态的时候忘了在内核态关中断的bug (#780)
-
-commit 13b057cc0fda0cf9630c98d246937b85fa01a7c9
-Author: 曾俊 <[email protected]>
-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 <[email protected]>
-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 <[email protected]>
-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 <[email protected]>
-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 <[email protected]>
-Date:   Fri Apr 26 15:33:29 2024 +0800
-
-    feat(sched): add sched_yield (#766)
-    
-    * 实现sched_yield系统调用
-
-commit 471d65cf158c9bf741c21f5d0ab92efe7bf1c3d4
-Author: LoGin <[email protected]>
-Date:   Fri Apr 26 11:59:47 2024 +0800
-
-    feat(riscv): riscv下能够运行hello world用户程序 (#770)
-    
-    * feat(riscv): riscv下能够运行hello world用户程序
-
-commit 40348dd8d5a008ecc9eb3aab931933e4eba0e6da
-Author: zwb0x00 <[email protected]>
-Date:   Tue Apr 23 19:35:02 2024 +0800
-
-    feat(fs): add sys_dup3 (#755)
-    
-    * feat(fs): add sys_dup3
-
-commit 3b799d13beeb80900d728937308e47f8011835e1
-Author: LoGin <[email protected]>
-Date:   Tue Apr 23 19:14:41 2024 +0800
-
-    Create FUNDING.yml (#763)
-
-commit 731bc2b32d7b37298883d7a15b6dca659b436ee4
-Author: LoGin <[email protected]>
-Date:   Tue Apr 23 17:19:54 2024 +0800
-
-    feat(virtio): riscv: 添加virtio-blk driver,并在riscv下能够正确挂载FAT32 (#761)
-
-commit 0c1ef30087d10035c256fed08097f5897041979d
-Author: Chiichen <[email protected]>
-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 <[email protected]>
-Date:   Mon Apr 22 17:40:03 2024 +0800
-
-    fix(dog): 添加CC环境变量,解决编译时找不到musl-gcc的问题 (#753)
-
-commit e32effb1507773d32c216d9e77b963786e275c06
-Author: LoGin <[email protected]>
-Date:   Mon Apr 22 15:11:47 2024 +0800
-
-    feat(driver): 把virtio添加到sysfs (#752)
-
-commit a17651b14b86dd70655090381db4a2f710853aa1
-Author: MemoryShore <[email protected]>
-Date:   Mon Apr 22 15:10:47 2024 +0800
-
-    feat(mm): 实现缺页中断处理,支持页面延迟分配和写时拷贝,以及用户栈自动拓展 (#715)
-    
-    * 实现缺页中断处理
-    
-    * 完善页表拷贝逻辑
-    
-    * 优化代码结构
-    
-    * 完善缺页异常信息
-    
-    * 修改大页映射逻辑
-    
-    * 修正大页映射错误
-    
-    * 添加缺页中断支持标志
-    
-    * 实现用户栈自动拓展功能
-
-commit cb02d0bbc213867ac845b7e8a0fb337f723d396a
-Author: Chiichen <[email protected]>
-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 <[email protected]>
-Date:   Sun Apr 21 13:36:44 2024 +0800
-
-    feat(net): 实现raw socket的poll (#739)
-    
-    feat(net): 实现raw socket的poll
-
-commit b502fbf0b9c575a4c04e103d0fb708c4e383ab06
-Author: LoGin <[email protected]>
-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 <[email protected]>
-Date:   Sun Apr 21 13:12:31 2024 +0800
-
-    fix: 修复unified-init导致cargo check失败的问题 (#747)
-
-commit 881ff6f95e4addc373d815d66cb912bf721c20e6
-Author: yuyi2439 <[email protected]>
-Date:   Sun Apr 21 11:39:00 2024 +0800
-
-    将smoltcp升级到0.11.0版本 (#740)
-
-commit 370472f7288b568c7b80815f5b150daf4496446c
-Author: LoGin <[email protected]>
-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 <[email protected]>
-Date:   Sat Apr 20 18:31:56 2024 +0800
-
-    pci: 统一使用ecam root (#744)
-
-commit 418ad41fd84c15ed7e132e56970150ac38fc24a9
-Author: LoGin <[email protected]>
-Date:   Wed Apr 17 10:03:22 2024 +0800
-
-    Feat(tty): add dummy console (#735)
-    
-    使得riscv能暂时完成stdio_init(将来需要实现riscv的串口console)
-
-commit 1012552dea71bf04cf1d329d570c4c9ca9b2a2f8
-Author: Saga1718 <[email protected]>
-Date:   Tue Apr 16 21:37:42 2024 +0800
-
-    删除无用的hid代码 (#734)
-
-commit fbd63a301c5648f906eeb802f10ac03518ba1264
-Author: SMALLC <[email protected]>
-Date:   Tue Apr 16 21:34:36 2024 +0800
-
-    feat: alarm系统调用实现 (#710)
-    
-    * alarm系统调用实现
-
-commit d623e90231ef6a31d091c3f611c0af3a83d3343b
-Author: GnoCiYeH <[email protected]>
-Date:   Mon Apr 15 22:01:32 2024 +0800
-
-    socket统一改用`GlobalSocketHandle`,并且修复fcntl SETFD的错误 (#730)
-    
-    * socket统一改用`GlobalSocketHandle`,并且修复fcntl SETFD的错误
-    
-    ---------
-    
-    Co-authored-by: longjin <[email protected]>
-
-commit 7162a8358d94c7799dd2b5300192b6a794b23d79
-Author: LoGin <[email protected]>
-Date:   Mon Apr 15 13:20:46 2024 +0800
-
-    doc: Update build instructions for riscv64 architecture (#725)
-
-commit 1074eb34e784aa2adfc5b9e0d89fa4b7e6ea03ef
-Author: Samuel Dai <[email protected]>
-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 <[email protected]>
-Date:   Mon Apr 15 12:51:14 2024 +0800
-
-    feat(mm): 添加slab内存分配器 (#683)
-    
-    feat(mm): 添加slab内存分配器
-    ---------
-    
-    Co-authored-by: longjin <[email protected]>
-
-commit c719ddc6312acd7976e0f6fd449a94ff9abad5a6
-Author: Saga1718 <[email protected]>
-Date:   Sun Apr 14 23:51:47 2024 +0800
-
-    feat(net): 实现tcp backlog功能 (#714)
-    
-    * feat:实现tcp的backlog功能
-
-commit 9621ab16ef27bc94f223e6254fafb9bb07d46d57
-Author: LoGin <[email protected]>
-Date:   Sun Apr 14 20:39:20 2024 +0800
-
-    让riscv64能正常切换进程,并运行完所有的initcall (#721)
-
-commit 9fab312ea9921618629924ab15c28c2d255b21c6
-Author: LoGin <[email protected]>
-Date:   Fri Apr 12 15:27:44 2024 +0800
-
-    Update DragonOS description and introduction (#717)
-
-commit f049d1af01da7b92f312245ed411b22475b76065
-Author: LoGin <[email protected]>
-Date:   Fri Apr 12 14:46:47 2024 +0800
-
-    初始化riscv-sbi-timer (#716)
-
-commit 3959e94df38073fdb80b199777015f95611ba05f
-Author: 曾俊 <[email protected]>
-Date:   Wed Apr 10 19:00:32 2024 +0800
-
-    bugfix: 修复smp启动的时候,损坏0号核心的idle进程的内核栈的问题 (#711)
-    
-    ---------
-    
-    Co-authored-by: longjin <[email protected]>
-    Co-authored-by: heyicong <[email protected]>
-
-commit 9365e8017b39582eca620ba93c64f1b3c87c73d4
-Author: GnoCiYeH <[email protected]>
-Date:   Wed Apr 10 19:00:12 2024 +0800
-
-    完善pty,目前pty能够支持ssh (#708)
-
-commit 4b0170bd6bb374d0e9699a0076cc23b976ad6db7
-Author: Chiichen <[email protected]>
-Date:   Wed Apr 10 18:58:54 2024 +0800
-
-    chore(tools): add bootstrap support for Centos/RHEL8/fedora (#713)
-    
-    Co-authored-by: kejianchi <[email protected]>
-
-commit 15b94df01adc7e8931961b9b9a89db4e7c014b64
-Author: Jomo <[email protected]>
-Date:   Wed Apr 10 10:58:07 2024 +0800
-
-    add xuzihao (#712)
-
-commit 6fc066ac11d2f9a3ac629d57487a6144fda1ac63
-Author: Jomo <[email protected]>
-Date:   Sun Apr 7 14:04:19 2024 +0800
-
-    实现SystemV共享内存 (#690)
-    
-    * 实现SystemV共享内存
-    
-    * 测试shm
-    
-    * 添加测试程序
-    
-    * 完善细节
-    
-    * 修正shm的时间数据错误的问题
-    
-    * fix: devfs的metadata权限为0x777的错误
-    
-    ---------
-    
-    Co-authored-by: longjin <[email protected]>
-
-commit eb49bb993a39964f92494ec3effafed3fb9adfd8
-Author: 曾俊 <[email protected]>
-Date:   Sun Apr 7 14:03:51 2024 +0800
-
-    BlockCache-read cache支持 (#521)
-    
-    支持block cache的读缓存
-
-commit 06560afa2aa4db352526f4be8b6262719b8b3eac
-Author: hmt <[email protected]>
-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 <[email protected]>
-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 <[email protected]>
-Date:   Fri Apr 5 17:54:48 2024 +0800
-
-    重写调度模块 (#679)
-    
-    ## PR:重写调度模块
-    ---
-    ### 完成的部分
-    - 实现cfs调度策略
-    - 搭建框架,后续功能可以迭代开发
-    - 目前能跑,未测试性能
-    
-    ### 需要后续接力的部分
-    - 实现组内调度(task_group)
-    - 实现跨核负载均衡(pelt算法)
-    - 接入sysfs,实现参数动态调节(sched_stat等)
-    - nice值以及priority等参数的设置及调优
-
-commit e8eab1ac824e1b1e638e50debb8326dfed4f05e5
-Author: LoGin <[email protected]>
-Date:   Fri Apr 5 16:37:08 2024 +0800
-
-    riscv: copy-thread (#696)
-
-commit dfe53cf087ef4c7b6db63d992906b062dc63e93f
-Author: GnoCiYeH <[email protected]>
-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 <[email protected]>
-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 <[email protected]>
-
-commit 9430523b465b19db4dd476e9fd3038bdc2aa0c8d
-Author: yuyi2439 <[email protected]>
-Date:   Thu Apr 4 12:41:19 2024 +0800
-
-    使nproc可以正确获取到cpu核心数 (#689)
-
-commit 9b96c5b547c337502db7ec820312f119f95eece1
-Author: LoGin <[email protected]>
-Date:   Sun Mar 31 22:53:01 2024 +0800
-
-    riscv64: switch process (#678)
-    
-    * riscv64: switch process
-    
-    * fixname
-
-commit 7d580ef99d2a52250b384afd49c7f87ab66a8c84
-Author: Val213 <[email protected]>
-Date:   Sun Mar 31 18:01:32 2024 +0800
-
-    修复get_ramdom的长度错误问题() (#677)
-
-commit 56cc4dbe27e132aac5c61b8bd4f4ec9a223b49ee
-Author: Jomo <[email protected]>
-Date:   Sun Mar 31 16:33:49 2024 +0800
-
-    实现页面反向映射 (#670)
-    
-    * 实现页面反向映射
-    
-    * 完善PAGE_MANAGER初始化时机 && 封装lock函数 && 删掉过时注释
-
-commit 924d64de8def99488f57dc618de763f7aca4a68b
-Author: BrahmaMantra <[email protected]>
-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 <[email protected]>
-
-commit 9d9a09841ce2d650a41fed776916c0a11d52f92e
-Author: sun5etop <[email protected]>
-Date:   Sun Mar 31 15:11:10 2024 +0800
-
-    修复udp bind的时候,对port0处理不正确的问题(#676)
-
-commit da152319797436368304cbc3f85a3b9ec049134b
-Author: LoGin <[email protected]>
-Date:   Thu Mar 28 00:28:13 2024 +0800
-
-    实现了rtc的抽象,并且把x86的cmos rtc接入到设备驱动模型 (#674)
-    
-    * 实现了rtc的抽象,并且把x86的cmos rtc接入到设备驱动模型。
-
-commit 597ecc08c2444dcc8f527eb021932718b69c9cc5
-Author: TTaq <[email protected]>
-Date:   Tue Mar 26 18:28:26 2024 +0800
-
-    新加结构体POSIXSTATFS与SuperBlock用于处理statfs系统调用 (#667)
-    
-    * 新加结构体POSIXSTATFS与SuperBlock用于处理statfs系统调用
-
-commit 0cb807346cb3c47924538585087d9fc846cf5e6f
-Author: LoGin <[email protected]>
-Date:   Tue Mar 26 18:26:02 2024 +0800
-
-    修复tty设备显示在/sys目录下的bug (#668)
-
-commit 2755467c790d6510fa97cbf052ce8e91ad1372c6
-Author: 曾俊 <[email protected]>
-Date:   Mon Mar 25 16:39:36 2024 +0800
-
-    支持绘制24位深和16位深显示缓冲区 (#640)
-    
-    * 修复了初始化时显示,边界条件的一个bug
-    
-    * 解决了内存未初始前字体显示的兼容性问题
-    * 支持绘制24位深和16位深显示缓冲区
-
-commit 4256da7fb6ad25a3caab6f656607aaf047cb6446
-Author: LoGin <[email protected]>
-Date:   Mon Mar 25 15:47:05 2024 +0800
-
-    把Device trait的set_class改为设置Weak指针,以避免循环引用问题。 (#666)
-
-commit 5c20e05a2eb82da6dd73104fcf51d538500c2856
-Author: LoGin <[email protected]>
-Date:   Mon Mar 25 13:59:00 2024 +0800
-
-    修改bug report模版label (#665)
-
-commit 7c958c9ef0cd25eb15abb21d0d3420aac1c67c88
-Author: Val213 <[email protected]>
-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 <[email protected]>
-    Co-authored-by: GnoCiYeH <[email protected]>
-    Co-authored-by: longjin <[email protected]>
-
-commit 911132c4b8ea0e9c49a4e84b9fa1db114102acbb
-Author: Donkey Kane <[email protected]>
-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 <[email protected]>
-Date:   Sat Mar 23 16:25:56 2024 +0800
-
-    riscv: 进程管理初始化 (#654)
-
-commit 6046f77591cf23dc9cc53b68b25c0d74f94fa493
-Author: 裕依 <[email protected]>
-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 <[email protected]>
-Date:   Sat Mar 23 11:51:30 2024 +0800
-
-    只对x86_64进行clippy check (#651)
-
-commit 4e4c8c41e90989c1f732995511e0f9a77a33f650
-Author: LoGin <[email protected]>
-Date:   Fri Mar 22 23:56:30 2024 +0800
-
-    添加clippy检测的自动化工作流 (#649)
-    
-    * 添加clippy检测的自动化工作流
-    
-    * fmt
-    
-    * 1
-
-commit b5b571e02693d91eb6918d3b7561e088c3e7ee81
-Author: LoGin <[email protected]>
-Date:   Fri Mar 22 23:26:39 2024 +0800
-
-    修复内核的clippy检查报错 (#637)
-    
-    修复内核的clippy检查报错
-    ---------
-    
-    Co-authored-by: Samuel Dai <[email protected]>
-    Co-authored-by: Donkey Kane <[email protected]>
-    Co-authored-by: themildwind <[email protected]>
-    Co-authored-by: GnoCiYeH <[email protected]>
-    Co-authored-by: MemoryShore <[email protected]>
-    Co-authored-by: 曾俊 <[email protected]>
-    Co-authored-by: sun5etop <[email protected]>
-    Co-authored-by: hmt <[email protected]>
-    Co-authored-by: laokengwt <[email protected]>
-    Co-authored-by: TTaq <[email protected]>
-    Co-authored-by: Jomo <[email protected]>
-    Co-authored-by: Samuel Dai <[email protected]>
-    Co-authored-by: sspphh <[email protected]>
-
-commit 4695947e1b601c83641676485571d42c692a2bbd
-Author: Chenzx <[email protected]>
-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 <[email protected]>
-Date:   Thu Mar 21 21:35:39 2024 +0800
-
-    riscv64: 添加flush tlb的ipi (#636)
-    
-    * riscv64: 添加flush tlb的ipi
-    
-    * update triagebot
-
-commit b4eb05a17f0f65668f69e7979660874ef8e01a2e
-Author: TTaq <[email protected]>
-Date:   Thu Mar 21 19:59:10 2024 +0800
-
-    Statx (#632)
-    
-    
-    * 实现statx及测试的应用程序
-
-commit 8cb2e9b344230227fe5f3ab3ebeb2522f1c5e289
-Author: LoGin <[email protected]>
-Date:   Thu Mar 21 19:19:32 2024 +0800
-
-    重写SMP模块 (#633)
-    
-    * 修复cpumask的迭代器的错误。
-    
-    * 能进系统(AP核心还没有初始化自身)
-    
-    * 初始化ap core
-    
-    * 修改percpu
-    
-    * 删除无用的cpu.c
-    
-    * riscv64编译通过
-
-commit 1d37ca6d172e01a98fa6785d2b3e07fb8202a4a9
-Author: Donkey Kane <[email protected]>
-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 <[email protected]>
-Date:   Tue Mar 19 21:31:02 2024 +0800
-
-    添加core utils到系统 (#624)
-
-commit 8c6f21840f820a161d4386000aea1d79e3bc8d13
-Author: sspphh <[email protected]>
-Date:   Tue Mar 19 17:01:20 2024 +0800
-
-    实现uname系统调用 (#614)
-    
-    * 实现uname系统调用
-    
-    Co-authored-by: longjin <[email protected]>
-
-commit 82df0a13109e400602ddaec049d04ae230eb485b
-Author: hmt <[email protected]>
-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 <[email protected]>
-
-commit 9e481b3bfe303e0b104694da9750ae978dfeecae
-Author: TTaq <[email protected]>
-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 <[email protected]>
-Date:   Sat Mar 16 22:28:59 2024 +0800
-
-    更新triagebot配置 (#616)
-    
-    * 更新triagebot配置
-
-commit 4fd916113e576a1c5d8ca9faae7a9d6b25afb9ae
-Author: LoGin <[email protected]>
-Date:   Sat Mar 16 18:09:32 2024 +0800
-
-    triagebot-add-shortcut (#612)
-
-commit fbc174499f5200924c732263e461c79b4a936c5b
-Author: LoGin <[email protected]>
-Date:   Fri Mar 15 20:06:24 2024 +0800
-
-    添加triagebot文件 (#608)
-    
-    * 添加triagebot文件
-
-```

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

@@ -6,7 +6,6 @@
 ..  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

+ 4 - 11
docs/conf.py

@@ -10,14 +10,15 @@
 # add these directories to sys.path here. If the directory is relative to the
 # documentation root, use os.path.abspath to make it absolute, like shown here.
 #
-import os
+# import os
 # import sys
 # sys.path.insert(0, os.path.abspath('.'))
 
+
 # -- Project information -----------------------------------------------------
 
 project = 'DragonOS'
-copyright = '2022-2024, DragonOS Community'
+copyright = '2022-2023, DragonOS Community'
 author = 'longjin'
 
 # The full version, including alpha/beta/rc tags
@@ -72,12 +73,4 @@ myst_enable_extensions = [
     "strikethrough",
     "substitution",
     "tasklist",
-]
-
-
-# Define the canonical URL if you are using a custom domain on Read the Docs
-html_baseurl = os.environ.get("READTHEDOCS_CANONICAL_URL", "")
-
-# Tell Jinja2 templates the build is running on Read the Docs
-if os.environ.get("READTHEDOCS", "") == "True":
-    html_context["READTHEDOCS"] = True
+]

+ 0 - 1
docs/introduction/build_system.md

@@ -48,7 +48,6 @@ 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是加锁的状态
-        debug!("x={:?}", x);
+        kdebug!("x={:?}", x);
     }
     // 由于上方的变量`g`,也就是Mutex守卫的生命周期结束,自动释放了Mutex。因此,在此处,Mutex是放锁的状态
-    debug!("x={:?}", x);
+    kdebug!("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是加锁的状态
-        debug!("x={:?}", x);
+        kdebug!("x={:?}", x);
     }
     // 由于上方的变量`g`,也就是SpinLock守卫的生命周期结束,自动释放了SpinLock。因此,在此处,SpinLock是放锁的状态
-    debug!("x={:?}", x);
+    kdebug!("x={:?}", x);
 ```
 
 &emsp;&emsp;对于结构体内部的变量,我们可以使用SpinLock进行细粒度的加锁,也就是使用SpinLock包裹需要细致加锁的成员变量,比如这样:

+ 13 - 17
docs/kernel/sched/cfs.md

@@ -2,27 +2,23 @@
 
 &emsp;&emsp; CFS(Completely Fair Scheduler),顾名思义,完全公平调度器。CFS作为主线调度器之一,也是最典型的O(1)调度器之一
 
-## 结构体介绍
+## 1. CFSQueue 介绍
 
-- ``CompletelyFairScheduler``
-&emsp;&emsp; ``CompletelyFairScheduler``实现了``Scheduler``trait,他是完全调度算法逻辑的主要实施者。
+&emsp;&emsp; CFSQueue是用来存放普通进程的调度队列,每个CPU维护一个CFSQueue,主要使用Vec作为主要存储结构来实现。
 
-- ``FairSchedEntity``
-	- **重要字段**
-		- ``cfs_rq``: 它指向了自己所在的完全公平调度队列。
-		- ``my_cfs_rq``: 为一个``Option``变量,当该实体作为一个单独进程时,这个值为``None``,但是若这个实体为一个组,那这个变量必需为这个组内的私有调度队列。这个``cfs_rq``还可以继续往下深入,就构成了上述的树型结构。
-		- ``pcb``: 它指向了当前实体对应的``PCB``,同样,若当前实体为一个组,则这个``Weak``指针不指向任何值。
+### 1.1 主要函数
+1. enqueue(): 将pcb入队列
+2. dequeue(): 将pcb从调度队列中弹出,若队列为空,则返回IDLE进程的pcb
+3. sort(): 将进程按照虚拟运行时间的升序进行排列
 
-&emsp;&emsp;``FairSchedEntity``是完全公平调度器中最重要的结构体,他代表一个实体单位,它不止表示一个进程,它还可以是一个组或者一个用户,但是它在cfs队列中所表示的就单单是一个调度实体。这样的设计可以为上层提供更多的思路,比如上层可以把不同的进程归纳到一个调度实体从而实现组调度等功能而不需要改变调度算法。
+## 2. SchedulerCFS 介绍
 
-&emsp;&emsp;在cfs中,整体的结构是**一棵树**,每一个调度实体作为``cfs_rq``中的一个节点,若该调度实体不是单个进程(它可能是一个进程组),则在该调度实体中还需要维护一个自己的``cfs_rq``,这样的嵌套展开后,每一个叶子节点就是一个单独的进程。需要理解这样一棵树,**在后续文档中会以这棵树为核心讲解**。
-&emsp;&emsp;该结构体具体的字段意义请查阅源代码。这里提及几个重要的字段:
+&emsp;&emsp; CFS调度器类,主要实现了CFS调度器类的初始化以及调度功能函数。
 
+### 2.1 主要函数
 
-- ``CfsRunQueue``
-&emsp;&emsp;``CfsRunQueue``完全公平调度算法中管理``FairSchedEntity``的队列,它可以挂在总的``CpuRunQueue``下,也可以作为子节点挂在``FairSchedEntity``上,详见上文``FairSchedEntity``。
-
-	- **重要字段**
-		- ``entities``: 存储调度实体的红黑树
-		- ``current``: 当前正在运行的实体
+1. sched(): 是对于Scheduler trait的sched()实现,是普通进程进行调度时的逻辑处理,该函数会返回接下来要执行的pcb,若没有符合要求的pcb,返回None
+2. enqueue(): 同样是对于Scheduler trait的sched()实现,将一个pcb加入调度器的调度队列
+3. update_cpu_exec_proc_jiffies(): 更新这个cpu上,这个进程的可执行时间。
+4. timer_update_jiffies(): 时钟中断到来时,由sched的core模块中的函数,调用本函数,更新CFS进程的可执行时间
 

+ 8 - 59
docs/kernel/sched/core.md

@@ -1,65 +1,14 @@
 # 进程调度器相关的api
 
-&emsp;&emsp; 定义了DragonOS的进程调度相关的api,是系统进行进程调度的接口。同时也抽象出了Scheduler的trait,以供具体的调度器实现
+&emsp;&emsp; 定义了DragonOS的进程调度相关的api,是系统进行进程调度的接口。同时也抽象出了Scheduler的trait,以供具体的调度器实现 
 
-## 调度器介绍
+## 1. 调度器介绍
 
 &emsp;&emsp; 一般来说,一个系统会同时处理多个请求,但是其资源是优先的,调度就是用来协调每个请求对资源的使用的方法。
 
-## 整体架构
-&emsp;&emsp;整个调度子系统以**树形结构**来组织,每个CPU都会管理这样一棵树,每个CPU的``CpuRunQueue``即可以理解为树的根节点。每个``CpuRunQueue``下会管理着不同调度策略的子树,根据不同的调度策略深入到对应子树中实施调度。大体结构如下:
-
-- CpuRunQueue
-	- Cfs
-		- CfsRunQueue
-			- FairSchedEntity
-				- CfsRunQueue
-					- ...(嵌套)
-	- Rt
-		- ...
-	- Idle
-		- ...
-	- RR
-		- ...
-	- ...
-
-&emsp;&emsp;基于这个结构,调度子系统能够更轻松地解耦以及添加其他调度策略。
-&emsp;&emsp;
-
-## 重要结构
-- ``Scheduler:``
-&emsp;&emsp;``Scheduler``是各个调度算法提供给上层的接口,实现不同的调度算法,只需要向外提供这样一组接口即可。
-
-- ``CpuRunQueue:``
-&emsp;&emsp;``CpuRunQueue``为总的CPU运行队列,他会根据不同的调度策略来进行调度。他作为调度子系统的根节点来组织调度。
-	- **重要字段**
-		- ``lock``: 过程锁,因为在深入到具体调度策略后的调度过程中还会需要访问``CpuRunQueue``中的信息,在cfs中保存了``CpuRunQueue``对象,我们需要确保在整体过程上锁后,子对象中不需要二次加锁即可访问,所以过程锁比较适合这个场景,若使用对象锁,则在对应调度策略中想要访问``CpuRunQueue``中的信息时需要加锁,但是最外层已经将``CpuRunQueue``对象上锁,会导致内层永远拿不到锁。对于该字段,详见[CpuRunQueue的self_lock方法及其注释](https://code.dragonos.org.cn/xref/DragonOS/kernel/src/sched/mod.rs?r=dd8e74ef0d7f91a141bd217736bef4fe7dc6df3d#360)。
-		- ``cfs``: Cfs调度器的根节点,往下伸展为一棵子树,详见完全公平调度文档。
-		- ``current``: 当前在CPU上运行的进程。
-		- ``idle``: 当前CPU的Idle进程。
-
-
-## 调度流程
-&emsp;&emsp;一次有效的调度分两种情况,第一是主动调用``__schedule``或者``schedule``函数进行调度,第二是通过时钟中断,判断当前运行的任务时间是否到期。
-
-- **主动调度**
-	- ``__schedule``和``schedule``函数:
-		- ``__schedule``:真正执行调度。会按照当前调度策略来选择下一个任务执行。
-		- ``schedule``: ``__schedule``的上层封装,它需要该任务在内核中的所有资源释放干净才能进行调度,即判断当前进程的``preempt_count``是否为0,若不为0则会**panic**。
-		- 参数:这两个函数都需要提供一个参数:``SchedMode``。用于控制此次调度的行为,可选参数主要有以下两个:
-			- ``SchedMode::SM_NONE``: 标志当前进程没有被抢占而是主动让出,他**不会**被再次加入队列,直到有其他进程主动唤醒它,这个标志位主要用于信号量、等待队列以及一些主动唤醒场景的实现。
-			- ``SchedMode::SM_PREEMPT``:标志当前是被**抢占**运行的,他**会**再次被加入调度队列等待下次调度,通俗来说:它是被别的进程抢占了运行时间,有机会运行时他会继续执行。
-
-- **时钟调度**
-&emsp;&emsp;时钟中断到来的时候,调度系统会进行更新,包括判断是否需要下一次调度。以下为主要的函数调用栈:
-	- ``LocalApicTimer::handle_irq``: 中断处理函数
-		- ``ProcessManager::update_process_times``: 更新当前进程的时钟信息(统计运行时等)
-		 - ``scheduler_tick``: 调度子系统tick入口
-		 	- ``CompletelyFairScheduler::tick``: 以cfs为例,此为cfs调度算法的tick入口
-		 		- ``CfsRunQueue::entity_tick``: 对所有调度实体进行tick
-		 		 - ``CfsRunQueue::update_current``: 更新当前运行任务的运行时间及判断是否到期
-		 		 	- ``CfsRunQueue::account_cfs_rq_runtime``: 计算当前队列的运行时间
-		 		 	 - ``CpuRunQueue::resched_current``: 若上一步计算的时间超时则到这一步,这里会设置进程标志为``NEED_SCHEDULE``.
-
-	- 退出中断:退出中断时检查当前进程是否存在标志位``NEED_SCHEDULE``,若存在则调用``__schedule``进行调度。
-
+### 1.1 主要函数
+1. cpu_executing(): 获取指定的cpu上正在执行的进程的pcb
+2. sched_enqueue(): 将进程加入调度队列
+3. sched_init(): 初始化进程调度器模块
+4. sched_update_jiffies(): 当时钟中断到达时,更新时间片。*请注意,该函数只能被时钟中断处理程序调用*
+5. sys_sched(): 让系统立即运行调度器的系统调用。*请注意,该系统调用不能由ring3的程序发起*

+ 0 - 4
kernel/.cargo/config.toml

@@ -5,8 +5,4 @@
 [target.'cfg(target_os = "none")']
 runner = "bootimage runner"
 
-[build]
-rustflags = ["-Clink-args=-znostart-stop-gc"]
-rustdocflags = ["-Clink-args=-znostart-stop-gc"]
-
 [env]

+ 10 - 14
kernel/Cargo.toml

@@ -1,6 +1,6 @@
 [package]
 name = "dragonos_kernel"
-version = "0.1.10"
+version = "0.1.9"
 edition = "2021"
 
 # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -12,18 +12,16 @@ crate-type = ["staticlib"]
 [workspace]
 members = [ 
     "crates/*",
+    "src/libs/intertrait"
 ]
 
 [features]
-default = ["backtrace", "kvm", "fatfs", "fatfs-secure"]
+default = ["backtrace", "kvm"]
 # 内核栈回溯
 backtrace = []
 # kvm
 kvm = []
 
-fatfs = []
-fatfs-secure = ["fatfs"]
-
 
 # 运行时依赖项
 [dependencies]
@@ -37,28 +35,26 @@ bitmap = { path = "crates/bitmap" }
 driver_base_macros = { "path" = "crates/driver_base_macros" }
 # 一个no_std的hashmap、hashset
 elf = { version = "=0.7.2", default-features = false }
-fdt = { git = "https://git.mirrors.dragonos.org.cn/DragonOS-Community/fdt", rev = "9862813020" }
 hashbrown = "=0.13.2"
 ida = { path = "src/libs/ida" }
-intertrait = { path = "crates/intertrait" }
+intertrait = { path = "src/libs/intertrait" }
 kdepends = { path = "crates/kdepends" }
 klog_types = { path = "crates/klog_types" }
-linkme = "=0.3.27"
+linkme = "=0.2"
 num = { version = "=0.4.0", default-features = false }
 num-derive = "=0.3"
 num-traits = { git = "https://git.mirrors.dragonos.org.cn/DragonOS-Community/num-traits.git", rev="1597c1c", default-features = false }
 smoltcp = { version = "=0.11.0", default-features = false, features = ["log", "alloc",  "socket-raw", "socket-udp", "socket-tcp", "socket-icmp", "socket-dhcpv4", "socket-dns", "proto-ipv4", "proto-ipv6"]}
 system_error = { path = "crates/system_error" }
-uefi = { version = "=0.26.0", features = ["alloc"] }
-uefi-raw = "=0.5.0"
 unified-init = { path = "crates/unified-init" }
 virtio-drivers = { git = "https://git.mirrors.dragonos.org.cn/DragonOS-Community/virtio-drivers", rev = "f91c807965" }
-wait_queue_macros = { path = "crates/wait_queue_macros" }
+fdt = { git = "https://git.mirrors.dragonos.org.cn/DragonOS-Community/fdt", rev = "9862813020" }
+uefi = { version = "=0.26.0", features = ["alloc"] }
+uefi-raw = "=0.5.0"
 paste = "=1.0.14"
 slabmalloc = { path = "crates/rust-slabmalloc" }
 log = "0.4.21"
-xarray = "0.1.0"
-lru = "0.12.3"
+
 
 # target为x86_64时,使用下面的依赖
 [target.'cfg(target_arch = "x86_64")'.dependencies]
@@ -89,4 +85,4 @@ debug = true   # Controls whether the compiler passes `-g`
 
 # The release profile, used for `cargo build --release`
 [profile.release]
-debug = true
+debug = false

+ 5 - 5
kernel/Makefile

@@ -25,9 +25,9 @@ clean:
 
 .PHONY: fmt
 fmt:
-	RUSTFLAGS="$(RUSTFLAGS)" cargo fmt --all $(FMT_CHECK)
+	@cargo fmt --all $(FMT_CHECK)
 ifeq ($(ARCH), x86_64)
-	RUSTFLAGS="$(RUSTFLAGS)" cargo clippy --all-features
+	@cargo clippy --all-features
 endif
 
 
@@ -36,12 +36,12 @@ check: ECHO
 # @echo "Checking kernel... ARCH=$(ARCH)"
 # @exit 1
 ifeq ($(ARCH), x86_64)
-	RUSTFLAGS="$(RUSTFLAGS)" cargo +nightly-2024-07-23 check --workspace $(CARGO_ZBUILD) --message-format=json --target ./src/$(TARGET_JSON)
+	@cargo +nightly-2023-08-15 check --workspace $(CARGO_ZBUILD) --message-format=json --target ./src/$(TARGET_JSON)
 else ifeq ($(ARCH), riscv64)
-	RUSTFLAGS="$(RUSTFLAGS)" cargo +nightly-2024-07-23 check --workspace $(CARGO_ZBUILD) --message-format=json --target $(TARGET_JSON)
+	@cargo +nightly-2023-08-15 check --workspace $(CARGO_ZBUILD) --message-format=json --target $(TARGET_JSON)
 endif
 
 test:
 # 测试内核库
-	RUSTFLAGS="$(RUSTFLAGS)" cargo +nightly-2024-07-23 test --workspace --exclude dragonos_kernel
+	@cargo +nightly-2023-08-15 test --workspace --exclude dragonos_kernel
 

+ 0 - 1
kernel/crates/bitmap/src/lib.rs

@@ -2,7 +2,6 @@
 #![feature(core_intrinsics)]
 #![allow(incomplete_features)] // for const generics
 #![feature(generic_const_exprs)]
-#![allow(internal_features)]
 #![allow(clippy::needless_return)]
 
 #[macro_use]

+ 0 - 9
kernel/crates/bitmap/src/static_bitmap.rs

@@ -14,15 +14,6 @@ where
     core: BitMapCore<usize>,
 }
 
-impl<const N: usize> Default for StaticBitmap<N>
-where
-    [(); (N + usize::BITS as usize - 1) / (usize::BITS as usize)]:,
-{
-    fn default() -> Self {
-        Self::new()
-    }
-}
-
 impl<const N: usize> StaticBitmap<N>
 where
     [(); (N + usize::BITS as usize - 1) / (usize::BITS as usize)]:,

+ 5 - 0
kernel/crates/bitmap/src/traits.rs

@@ -182,6 +182,11 @@ macro_rules! bitops_for {
                 }
             }
 
+            #[cfg(feature = "std")]
+            fn to_hex(bits: &Self) -> String {
+                format!("{:x}", bits)
+            }
+
             #[inline]
             fn bit_size() -> usize {
                 <$target>::BITS as usize

+ 0 - 6
kernel/crates/klog_types/src/lib.rs

@@ -175,12 +175,6 @@ impl MMLogCycle {
     }
 }
 
-impl Default for MMLogCycle {
-    fn default() -> Self {
-        Self::new()
-    }
-}
-
 impl kdepends::thingbuf::Recycle<AllocatorLog> for MMLogCycle {
     fn new_element(&self) -> AllocatorLog {
         AllocatorLog::zeroed()

+ 3 - 5
kernel/crates/rust-slabmalloc/src/pages.rs

@@ -38,7 +38,7 @@ impl Bitfield for [AtomicU64] {
     fn initialize(&mut self, for_size: usize, capacity: usize) {
         // Set everything to allocated
         for bitmap in self.iter_mut() {
-            *bitmap = AtomicU64::new(u64::MAX);
+            *bitmap = AtomicU64::new(u64::max_value());
         }
 
         // Mark actual slots as free
@@ -64,7 +64,7 @@ impl Bitfield for [AtomicU64] {
 
         for (base_idx, b) in self.iter().enumerate() {
             let bitval = b.load(Ordering::Relaxed);
-            if bitval == u64::MAX {
+            if bitval == u64::max_value() {
                 continue;
             } else {
                 let negated = !bitval;
@@ -125,7 +125,7 @@ impl Bitfield for [AtomicU64] {
     #[inline(always)]
     fn is_full(&self) -> bool {
         self.iter()
-            .filter(|&x| x.load(Ordering::Relaxed) != u64::MAX)
+            .filter(|&x| x.load(Ordering::Relaxed) != u64::max_value())
             .count()
             == 0
     }
@@ -410,7 +410,6 @@ impl<'a, T: AllocablePage> PageList<'a, T> {
     }
 
     /// Removes `slab_page` from the list.
-    #[allow(clippy::manual_inspect)]
     pub(crate) fn pop<'b>(&'b mut self) -> Option<&'a mut T> {
         match self.head {
             None => None,
@@ -454,7 +453,6 @@ impl<'a, P: AllocablePage + 'a> Iterator for ObjectPageIterMut<'a, P> {
     type Item = &'a mut P;
 
     #[inline]
-    #[allow(clippy::manual_inspect)]
     fn next(&mut self) -> Option<&'a mut P> {
         unsafe {
             self.head.resolve_mut().map(|next| {

+ 1 - 1
kernel/crates/unified-init/Cargo.toml

@@ -10,5 +10,5 @@ path = "src/main.rs"
 
 [dependencies]
 unified-init-macros = { path = "macros" }
-linkme = "=0.3.27"
+linkme = "0.2"
 system_error = { path = "../system_error" }

+ 1 - 1
kernel/crates/unified-init/macros/Cargo.toml

@@ -16,5 +16,5 @@ uuid = { version = "0.8", features = ["v4"] }
 
 [dev-dependencies]
 unified-init = { path = ".." }
-linkme = "=0.3.27"
+linkme = "0.2"
 system_error = { path = "../../system_error" }

+ 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| {
-                log::error!("Failed to call initializer {}: {:?}", initializer.name(), e);
+                kerror!("Failed to call initializer {}: {:?}", initializer.name(), e);
             });
         }
     };

+ 0 - 7
kernel/crates/wait_queue_macros/Cargo.toml

@@ -1,7 +0,0 @@
-[package]
-name = "wait_queue_macros"
-version = "0.1.0"
-edition = "2021"
-authors = ["longjin <[email protected]>"]
-
-[dependencies]

+ 0 - 60
kernel/crates/wait_queue_macros/src/lib.rs

@@ -1,60 +0,0 @@
-#![no_std]
-
-/// Wait for a condition to become true.
-///
-/// This macro will wait for a condition to become true.
-///
-/// ## Parameters
-///
-/// - `$wq`: The wait queue to wait on.
-/// - `$condition`: The condition to wait for. (you can pass a function or a boolean expression)
-/// - `$cmd`: The command to execute while waiting.
-#[macro_export]
-macro_rules! wq_wait_event_interruptible {
-    ($wq:expr, $condition: expr, $cmd: expr) => {{
-        let mut retval = Ok(());
-        if !$condition {
-            retval = wait_queue_macros::_wq_wait_event_interruptible!($wq, $condition, $cmd);
-        }
-
-        retval
-    }};
-}
-
-#[macro_export]
-#[allow(clippy::crate_in_macro_def)]
-macro_rules! _wq_wait_event_interruptible {
-    ($wq:expr, $condition: expr, $cmd: expr) => {{
-        wait_queue_macros::__wq_wait_event!($wq, $condition, true, Ok(()), {
-            $cmd;
-            crate::sched::schedule(SchedMode::SM_NONE)
-        })
-    }};
-}
-
-#[macro_export]
-macro_rules! __wq_wait_event(
-    ($wq:expr, $condition: expr, $interruptible: expr, $ret: expr, $cmd:expr) => {{
-        let mut retval = $ret;
-        let mut exec_finish_wait = true;
-        loop {
-            let x = $wq.prepare_to_wait_event($interruptible);
-            if $condition {
-                break;
-            }
-
-            if $interruptible && !x.is_ok() {
-                retval = x;
-                exec_finish_wait = false;
-                break;
-            }
-
-            $cmd;
-        }
-        if exec_finish_wait {
-            $wq.finish_wait();
-        }
-
-        retval
-    }};
-);

+ 0 - 3
kernel/env.mk

@@ -42,6 +42,3 @@ endif
 ifeq ($(DEBUG), DEBUG)
 GLOBAL_CFLAGS += -g 
 endif
-
-export RUSTFLAGS := -C link-args=-znostart-stop-gc
-export RUSTDOCFLAGS := -C link-args=-znostart-stop-gc

+ 1 - 1
kernel/rust-toolchain.toml

@@ -1,3 +1,3 @@
 [toolchain]
-channel = "nightly-2024-07-23"
+channel = "nightly-2023-08-15"
 components = ["rust-src", "clippy"]

+ 2 - 2
kernel/src/Makefile

@@ -21,7 +21,7 @@ ifeq ($(ARCH), x86_64)
 endif
 endif
 
-RUSTFLAGS += $(RUSTFLAGS_UNWIND)
+RUSTFLAGS = $(RUSTFLAGS_UNWIND)
 
 CFLAGS = $(GLOBAL_CFLAGS) -fno-pie $(CFLAGS_UNWIND) -I $(shell pwd) -I $(shell pwd)/include
 
@@ -40,7 +40,7 @@ kernel_subdirs := common driver debug syscall libs
 
 
 kernel_rust:
-	RUSTFLAGS="$(RUSTFLAGS)" cargo +nightly-2024-07-23 $(CARGO_ZBUILD) build --release --target $(TARGET_JSON)
+	RUSTFLAGS="$(RUSTFLAGS)" cargo +nightly-2023-08-15 $(CARGO_ZBUILD) build --release --target $(TARGET_JSON)
 
 
 all: kernel

+ 0 - 1
kernel/src/arch/io.rs

@@ -1,5 +1,4 @@
 /// 每个架构都需要实现的IO接口
-#[allow(unused)]
 pub trait PortIOArch {
     unsafe fn in8(port: u16) -> u8;
     unsafe fn in16(port: u16) -> u16;

+ 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);
-        // debug!(
+        // kdebug!(
         //     "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);
-        // debug!("map_fdt: map fdt to {:?}, size: {}", map_paddr, map_size);
+        // kdebug!("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;

+ 6 - 5
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,12 +112,13 @@ 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);
-    // debug!("fdt_paddr: {:?}, fdt_size: {}", fdt_paddr, fdt.total_size());
+    // kdebug!("fdt_paddr: {:?}, fdt_size: {}", fdt_paddr, fdt.total_size());
     drop(arch_boot_params_guard);
 
-    info!(
+    kinfo!(
         "DragonOS kernel is running on hart {}, fdt address:{:?}",
-        hartid, fdt_paddr
+        hartid,
+        fdt_paddr
     );
     mm_early_init();
 
@@ -126,7 +127,7 @@ pub fn early_setup_arch() -> Result<(), SystemError> {
     unsafe { parse_dtb() };
 
     for x in mem_block_manager().to_iter() {
-        debug!("before efi: {x:?}");
+        kdebug!("before efi: {x:?}");
     }
 
     efi_init();

+ 22 - 18
kernel/src/arch/riscv64/interrupt/handle.rs

@@ -3,10 +3,9 @@
 //! 架构相关的处理逻辑参考: 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};
+use crate::{arch::syscall::syscall_handler, driver::irqchip::riscv_intc::riscv_intc_irq, kerror};
 
 use super::TrapFrame;
 
@@ -53,7 +52,7 @@ fn riscv64_do_exception(trap_frame: &mut TrapFrame) {
         let handler = EXCEPTION_HANDLERS[code];
         handler(trap_frame).ok();
     } else {
-        error!("riscv64_do_irq: exception code out of range");
+        kerror!("riscv64_do_irq: exception code out of range");
         loop {
             // kernel die
             spin_loop();
@@ -62,7 +61,7 @@ fn riscv64_do_exception(trap_frame: &mut TrapFrame) {
 }
 
 fn default_handler(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> {
-    error!("riscv64_do_irq: handler not found");
+    kerror!("riscv64_do_irq: handler not found");
     loop {
         spin_loop();
     }
@@ -70,7 +69,7 @@ fn default_handler(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> {
 
 /// 处理指令地址不对齐异常 #0
 fn do_trap_insn_misaligned(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> {
-    error!("riscv64_do_irq: do_trap_insn_misaligned");
+    kerror!("riscv64_do_irq: do_trap_insn_misaligned");
     loop {
         spin_loop();
     }
@@ -78,7 +77,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> {
-    error!("riscv64_do_irq: do_trap_insn_access_fault");
+    kerror!("riscv64_do_irq: do_trap_insn_access_fault");
     loop {
         spin_loop();
     }
@@ -86,7 +85,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> {
-    error!("riscv64_do_irq: do_trap_insn_illegal");
+    kerror!("riscv64_do_irq: do_trap_insn_illegal");
     loop {
         spin_loop();
     }
@@ -94,7 +93,7 @@ fn do_trap_insn_illegal(_trap_frame: &mut TrapFrame) -> Result<(), SystemError>
 
 /// 处理断点异常 #3
 fn do_trap_break(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> {
-    error!("riscv64_do_irq: do_trap_break");
+    kerror!("riscv64_do_irq: do_trap_break");
     loop {
         spin_loop();
     }
@@ -102,7 +101,7 @@ fn do_trap_break(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> {
 
 /// 处理加载地址不对齐异常 #4
 fn do_trap_load_misaligned(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> {
-    error!("riscv64_do_irq: do_trap_load_misaligned");
+    kerror!("riscv64_do_irq: do_trap_load_misaligned");
     loop {
         spin_loop();
     }
@@ -110,7 +109,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> {
-    error!("riscv64_do_irq: do_trap_load_access_fault");
+    kerror!("riscv64_do_irq: do_trap_load_access_fault");
     loop {
         spin_loop();
     }
@@ -118,7 +117,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> {
-    error!("riscv64_do_irq: do_trap_store_misaligned");
+    kerror!("riscv64_do_irq: do_trap_store_misaligned");
     loop {
         spin_loop();
     }
@@ -126,7 +125,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> {
-    error!("riscv64_do_irq: do_trap_store_access_fault");
+    kerror!("riscv64_do_irq: do_trap_store_access_fault");
     loop {
         spin_loop();
     }
@@ -152,9 +151,11 @@ 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;
-    error!(
+    kerror!(
         "riscv64_do_irq: do_insn_page_fault vaddr: {:#x}, cause: {:?} epc: {:#x}",
-        vaddr, cause, epc
+        vaddr,
+        cause,
+        epc
     );
     loop {
         spin_loop();
@@ -166,9 +167,10 @@ 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;
-    error!(
+    kerror!(
         "riscv64_do_irq: do_trap_load_page_fault: epc: {epc:#x}, vaddr={:#x}, cause={:?}",
-        vaddr, cause
+        vaddr,
+        cause
     );
 
     loop {
@@ -180,9 +182,11 @@ 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> {
-    error!(
+    kerror!(
         "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();

+ 6 - 7
kernel/src/arch/riscv64/ipc/signal.rs

@@ -1,8 +1,7 @@
-use log::error;
-
 use crate::{
     arch::{sched::sched, CurrentIrqArch},
     exception::InterruptArch,
+    kerror,
     process::ProcessManager,
 };
 
@@ -69,7 +68,7 @@ impl From<usize> for Signal {
             let ret: Signal = unsafe { core::mem::transmute(value) };
             return ret;
         } else {
-            error!("Try to convert an invalid number to Signal");
+            kerror!("Try to convert an invalid number to Signal");
             return Signal::INVALID;
         }
     }
@@ -84,7 +83,7 @@ impl Into<usize> for Signal {
 impl From<i32> for Signal {
     fn from(value: i32) -> Self {
         if value < 0 {
-            error!("Try to convert an invalid number to Signal");
+            kerror!("Try to convert an invalid number to Signal");
             return Signal::INVALID;
         } else {
             return Self::from(value as usize);
@@ -128,7 +127,7 @@ impl Signal {
     pub fn handle_default(&self) {
         match self {
             Signal::INVALID => {
-                error!("attempting to handler an Invalid");
+                kerror!("attempting to handler an Invalid");
             }
             Signal::SIGHUP => sig_terminate(self.clone()),
             Signal::SIGINT => sig_terminate(self.clone()),
@@ -313,7 +312,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| {
-        error!(
+        kerror!(
             "sleep error :{:?},failed to sleep process :{:?}, with signal :{:?}",
             e,
             ProcessManager::current_pcb(),
@@ -328,7 +327,7 @@ fn sig_stop(sig: Signal) {
 /// 信号默认处理函数——继续进程
 fn sig_continue(sig: Signal) {
     ProcessManager::wakeup_stop(&ProcessManager::current_pcb()).unwrap_or_else(|_| {
-        error!(
+        kerror!(
             "Failed to wake up process pid = {:?} with signal :{:?}",
             ProcessManager::current_pcb().pid(),
             sig

+ 12 - 12
kernel/src/arch/riscv64/mm/init.rs

@@ -1,6 +1,5 @@
 use core::sync::atomic::{compiler_fence, AtomicBool, Ordering};
 
-use log::{debug, info};
 use system_error::SystemError;
 
 use crate::{
@@ -12,6 +11,7 @@ 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);
 
-    debug!(
+    kdebug!(
         "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分配器,把所有的内存页都映射到页表
     {
-        // debug!("to create new page table");
+        // kdebug!("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();
-        // debug!("PageMapper created");
+        // kdebug!("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");
             }
         }
-        debug!("Successfully emptied page table");
+        kdebug!("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();
-            // debug!("area: base={:?}, size={:#x}, end={:?}", area.base, area.size, area.base + area.size);
+            // kdebug!("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;
     }
-    debug!(
+    kdebug!(
         "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) };
-    info!("Successfully initialized buddy allocator");
+    kinfo!("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();
-        debug!("To enable new page table.");
+        kdebug!("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);
-        // debug!("New page table enabled");
+        // kdebug!("New page table enabled");
     }
-    debug!("Successfully enabled new page table");
-    info!("riscv mm init done");
+    kdebug!("Successfully enabled new page table");
+    kinfo!("riscv mm init done");
 
     return Ok(());
 }

+ 4 - 70
kernel/src/arch/riscv64/mm/mod.rs

@@ -12,9 +12,9 @@ use crate::{
             page_frame::{FrameAllocator, PageFrameCount, PageFrameUsage, PhysPageFrame},
         },
         kernel_mapper::KernelMapper,
-        page::{EntryFlags, PageEntry, PAGE_1G_SHIFT},
+        page::{PageEntry, PageFlags, PAGE_1G_SHIFT},
         ucontext::UserMapper,
-        MemoryManagementArch, PageTableKind, PhysAddr, VirtAddr, VmFlags,
+        MemoryManagementArch, PageTableKind, PhysAddr, VirtAddr,
     },
     smp::cpu::ProcessorId,
 };
@@ -256,74 +256,8 @@ impl MemoryManagementArch for RiscV64MMArch {
     ) -> bool {
         true
     }
-
-    const PAGE_NONE: usize = Self::ENTRY_FLAG_GLOBAL | Self::ENTRY_FLAG_READONLY;
-
-    const PAGE_READ: usize = PAGE_ENTRY_BASE | Self::ENTRY_FLAG_READONLY;
-
-    const PAGE_WRITE: usize =
-        PAGE_ENTRY_BASE | Self::ENTRY_FLAG_READONLY | Self::ENTRY_FLAG_WRITEABLE;
-
-    const PAGE_EXEC: usize = PAGE_ENTRY_BASE | Self::ENTRY_FLAG_EXEC;
-
-    const PAGE_READ_EXEC: usize =
-        PAGE_ENTRY_BASE | Self::ENTRY_FLAG_READONLY | Self::ENTRY_FLAG_EXEC;
-
-    const PAGE_WRITE_EXEC: usize = PAGE_ENTRY_BASE
-        | Self::ENTRY_FLAG_READONLY
-        | Self::ENTRY_FLAG_EXEC
-        | Self::ENTRY_FLAG_WRITEABLE;
-
-    const PAGE_COPY: usize = Self::PAGE_READ;
-    const PAGE_COPY_EXEC: usize = Self::PAGE_READ_EXEC;
-    const PAGE_SHARED: usize = Self::PAGE_WRITE;
-    const PAGE_SHARED_EXEC: usize = Self::PAGE_WRITE_EXEC;
-
-    const PAGE_COPY_NOEXEC: usize = 0;
-    const PAGE_READONLY: usize = 0;
-    const PAGE_READONLY_EXEC: usize = 0;
-
-    const PROTECTION_MAP: [EntryFlags<MMArch>; 16] = protection_map();
-}
-
-const fn protection_map() -> [EntryFlags<MMArch>; 16] {
-    let mut map = [0; 16];
-    map[VmFlags::VM_NONE.bits()] = MMArch::PAGE_NONE;
-    map[VmFlags::VM_READ.bits()] = MMArch::PAGE_READONLY;
-    map[VmFlags::VM_WRITE.bits()] = MMArch::PAGE_COPY;
-    map[VmFlags::VM_WRITE.bits() | VmFlags::VM_READ.bits()] = MMArch::PAGE_COPY;
-    map[VmFlags::VM_EXEC.bits()] = MMArch::PAGE_READONLY_EXEC;
-    map[VmFlags::VM_EXEC.bits() | VmFlags::VM_READ.bits()] = MMArch::PAGE_READONLY_EXEC;
-    map[VmFlags::VM_EXEC.bits() | VmFlags::VM_WRITE.bits()] = MMArch::PAGE_COPY_EXEC;
-    map[VmFlags::VM_EXEC.bits() | VmFlags::VM_WRITE.bits() | VmFlags::VM_READ.bits()] =
-        MMArch::PAGE_COPY_EXEC;
-    map[VmFlags::VM_SHARED.bits()] = MMArch::PAGE_NONE;
-    map[VmFlags::VM_SHARED.bits() | VmFlags::VM_READ.bits()] = MMArch::PAGE_READONLY;
-    map[VmFlags::VM_SHARED.bits() | VmFlags::VM_WRITE.bits()] = MMArch::PAGE_SHARED;
-    map[VmFlags::VM_SHARED.bits() | VmFlags::VM_WRITE.bits() | VmFlags::VM_READ.bits()] =
-        MMArch::PAGE_SHARED;
-    map[VmFlags::VM_SHARED.bits() | VmFlags::VM_EXEC.bits()] = MMArch::PAGE_READONLY_EXEC;
-    map[VmFlags::VM_SHARED.bits() | VmFlags::VM_EXEC.bits() | VmFlags::VM_READ.bits()] =
-        MMArch::PAGE_READONLY_EXEC;
-    map[VmFlags::VM_SHARED.bits() | VmFlags::VM_EXEC.bits() | VmFlags::VM_WRITE.bits()] =
-        MMArch::PAGE_SHARED_EXEC;
-    map[VmFlags::VM_SHARED.bits()
-        | VmFlags::VM_EXEC.bits()
-        | VmFlags::VM_WRITE.bits()
-        | VmFlags::VM_READ.bits()] = MMArch::PAGE_SHARED_EXEC;
-    let mut ret = [unsafe { EntryFlags::from_data(0) }; 16];
-    let mut index = 0;
-    while index < 16 {
-        ret[index] = unsafe { EntryFlags::from_data(map[index]) };
-        index += 1;
-    }
-    ret
 }
 
-const PAGE_ENTRY_BASE: usize = RiscV64MMArch::ENTRY_FLAG_PRESENT
-    | RiscV64MMArch::ENTRY_FLAG_ACCESSED
-    | RiscV64MMArch::ENTRY_FLAG_USER;
-
 impl VirtAddr {
     /// 判断虚拟地址是否合法
     #[inline(always)]
@@ -336,8 +270,8 @@ impl VirtAddr {
 }
 
 /// 获取内核地址默认的页面标志
-pub unsafe fn kernel_page_flags<A: MemoryManagementArch>(_virt: VirtAddr) -> EntryFlags<A> {
-    EntryFlags::from_data(RiscV64MMArch::ENTRY_FLAG_DEFAULT_PAGE)
+pub unsafe fn kernel_page_flags<A: MemoryManagementArch>(_virt: VirtAddr) -> PageFlags<A> {
+    PageFlags::from_data(RiscV64MMArch::ENTRY_FLAG_DEFAULT_PAGE)
         .set_user(false)
         .set_execute(true)
 }

+ 5 - 4
kernel/src/arch/riscv64/pci/pci_host_ecam.rs

@@ -1,5 +1,4 @@
 use fdt::{node::FdtNode, Fdt};
-use log::debug;
 use system_error::SystemError;
 
 use crate::{
@@ -7,6 +6,7 @@ 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"),
         };
 
-        debug!(
+        kdebug!(
             "pci_host_ecam_driver_init(): {} paddr: {:#x} size: {:#x} bus-range: {}-{} segement_group_number: {}",
             node.name,
             paddr,
@@ -61,9 +61,10 @@ 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) {
-            debug!(
+            kdebug!(
                 "pci_host_ecam_driver_init(): check {} error: {:?}",
-                node.name, err
+                node.name,
+                err
             );
         }
     }

+ 3 - 5
kernel/src/arch/riscv64/process/idle.rs

@@ -1,8 +1,6 @@
 use core::hint::spin_loop;
 
-use log::error;
-
-use crate::{arch::CurrentIrqArch, exception::InterruptArch, process::ProcessManager};
+use crate::{arch::CurrentIrqArch, exception::InterruptArch, kBUG, process::ProcessManager};
 
 impl ProcessManager {
     /// 每个核的idle进程
@@ -11,11 +9,11 @@ impl ProcessManager {
             if CurrentIrqArch::is_irq_enabled() {
                 riscv::asm::wfi();
             } else {
-                error!("Idle process should not be scheduled with IRQs disabled.");
+                kBUG!("Idle process should not be scheduled with IRQs disabled.");
                 spin_loop();
             }
 
-            // debug!("idle loop");
+            // kdebug!("idle loop");
         }
     }
 }

+ 5 - 5
kernel/src/arch/riscv64/process/mod.rs

@@ -6,7 +6,6 @@ use core::{
     sync::atomic::{compiler_fence, Ordering},
 };
 use kdepends::memoffset::offset_of;
-use log::error;
 use riscv::register::sstatus::Sstatus;
 use system_error::SystemError;
 
@@ -16,6 +15,7 @@ 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());
-        // debug!(
+        // kdebug!(
         //     "riscv switch process: prev: {:?}, next: {:?}",
         //     prev.pid(),
         //     next.pid()
@@ -182,7 +182,7 @@ impl ProcessManager {
         drop(next_addr_space);
         compiler_fence(Ordering::SeqCst);
 
-        // debug!("current sum={}, prev sum={}, next_sum={}", riscv::register::sstatus::read().sum(), prev.arch_info_irqsave().sstatus.sum(), next.arch_info_irqsave().sstatus.sum());
+        // kdebug!("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);
-        // debug!("riscv switch process: before to inner");
+        // kdebug!("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()) {
-            error!("p={:p}", p);
+            kerror!("p={:p}", p);
             panic!("current_pcb is null");
         }
         unsafe {

+ 17 - 11
kernel/src/arch/riscv64/process/syscall.rs

@@ -1,4 +1,4 @@
-use alloc::{ffi::CString, string::String, vec::Vec};
+use alloc::{string::String, vec::Vec};
 use riscv::register::sstatus::{FS, SPP};
 use system_error::SystemError;
 
@@ -16,14 +16,14 @@ use crate::{
 impl Syscall {
     pub fn do_execve(
         path: String,
-        argv: Vec<CString>,
-        envp: Vec<CString>,
+        argv: Vec<String>,
+        envp: Vec<String>,
         regs: &mut TrapFrame,
     ) -> Result<(), SystemError> {
         // 关中断,防止在设置地址空间的时候,发生中断,然后进调度器,出现错误。
         let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
         let pcb = ProcessManager::current_pcb();
-        // crate::debug!(
+        // crate::kdebug!(
         //     "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"
         );
-        // debug!("Switch to new address space");
+        // kdebug!("Switch to new address space");
 
         // 切换到新的用户地址空间
         unsafe { address_space.read().user_mapper.utable.make_current() };
 
         drop(old_address_space);
         drop(irq_guard);
-        // debug!("to load binary file");
+        // kdebug!("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)?;
-        // debug!("load binary file done");
-        // debug!("argv: {:?}, envp: {:?}", argv, envp);
+        // kdebug!("load binary file done");
+        // kdebug!("argv: {:?}, envp: {:?}", argv, envp);
         param.init_info_mut().args = argv;
         param.init_info_mut().envs = envp;
 
@@ -79,13 +79,19 @@ impl Syscall {
         };
         let (user_sp, argv_ptr) = unsafe {
             param
-                .init_info_mut()
-                .push_at(&mut ustack_message)
+                .init_info()
+                .push_at(
+                    // address_space
+                    //     .write()
+                    //     .user_stack_mut()
+                    //     .expect("No user stack found"),
+                    &mut ustack_message,
+                )
                 .expect("Failed to push proc_init_info to user stack")
         };
         address_space.write().user_stack = Some(ustack_message);
 
-        // debug!("write proc_init_info to user stack done");
+        // kdebug!("write proc_init_info to user stack done");
 
         regs.a0 = param.init_info().args.len();
         regs.a1 = argv_ptr.data();

+ 8 - 6
kernel/src/arch/riscv64/smp/mod.rs

@@ -1,9 +1,11 @@
-use log::warn;
 use system_error::SystemError;
 
-use crate::smp::{
-    cpu::{CpuHpCpuState, ProcessorId},
-    SMPArch,
+use crate::{
+    kwarn,
+    smp::{
+        cpu::{CpuHpCpuState, ProcessorId},
+        SMPArch,
+    },
 };
 
 pub struct RiscV64SMPArch;
@@ -11,12 +13,12 @@ pub struct RiscV64SMPArch;
 impl SMPArch for RiscV64SMPArch {
     #[inline(never)]
     fn prepare_cpus() -> Result<(), SystemError> {
-        warn!("RiscV64SMPArch::prepare_cpus() is not implemented");
+        kwarn!("RiscV64SMPArch::prepare_cpus() is not implemented");
         Ok(())
     }
 
     fn start_cpu(_cpu_id: ProcessorId, _hp_state: &CpuHpCpuState) -> Result<(), SystemError> {
-        warn!("RiscV64SMPArch::start_cpu() is not implemented");
+        kwarn!("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();
-            log::debug!("syscall return:pid={:?},ret= {:?}\n", pid, ret as isize);
+            crate::kdebug!("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) -> () {
-    // debug!("syscall_handler: syscall_num: {}", syscall_num);
+    // kdebug!("syscall_handler: syscall_num: {}", syscall_num);
     unsafe {
         CurrentIrqArch::interrupt_enable();
     }

+ 4 - 5
kernel/src/arch/riscv64/time.rs

@@ -1,7 +1,6 @@
-use log::{debug, info};
-
 use crate::{
     driver::open_firmware::fdt::open_firmware_fdt_driver,
+    kdebug, kinfo,
     time::{clocksource::HZ, TimeArch},
 };
 pub struct RiscV64TimeArch;
@@ -15,12 +14,12 @@ static mut TIME_FREQ: usize = 0;
 ///
 /// todo: 支持从acpi中获取
 fn init_time_freq() {
-    debug!("init_time_freq: init");
+    kdebug!("init_time_freq: init");
     let fdt = open_firmware_fdt_driver().fdt_ref();
     if fdt.is_err() {
         panic!("init_time_freq: failed to get fdt");
     }
-    debug!("init_time_freq: get fdt");
+    kdebug!("init_time_freq: get fdt");
     let fdt = fdt.unwrap();
     let cpu_node = fdt.find_node("/cpus");
     if cpu_node.is_none() {
@@ -37,7 +36,7 @@ fn init_time_freq() {
     }
 
     let time_freq: usize = time_freq.unwrap();
-    info!("init_time_freq: timebase-frequency: {}", time_freq);
+    kinfo!("init_time_freq: timebase-frequency: {}", time_freq);
     unsafe {
         TIME_FREQ = time_freq;
     }

+ 2 - 3
kernel/src/arch/x86_64/acpi.rs

@@ -1,6 +1,5 @@
 use super::smp::SMP_BOOT_DATA;
-use crate::{driver::acpi::acpi_manager, mm::percpu::PerCpu, smp::cpu::ProcessorId};
-use log::info;
+use crate::{driver::acpi::acpi_manager, kinfo, mm::percpu::PerCpu, smp::cpu::ProcessorId};
 use system_error::SystemError;
 
 pub(super) fn early_acpi_boot_init() -> Result<(), SystemError> {
@@ -25,7 +24,7 @@ pub(super) fn early_acpi_boot_init() -> Result<(), SystemError> {
         SMP_BOOT_DATA.set_cpu_count(cnt.data());
         SMP_BOOT_DATA.mark_initialized();
     }
-    info!(
+    kinfo!(
         "early_acpi_boot_init: cpu_count: {}\n",
         SMP_BOOT_DATA.cpu_count()
     );

+ 13 - 13
kernel/src/arch/x86_64/driver/apic/apic_timer.rs

@@ -11,15 +11,15 @@ 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;
 use crate::smp::cpu::ProcessorId;
 use crate::time::clocksource::HZ;
-use crate::time::tick_common::tick_handle_periodic;
 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() {
-    debug!("init_bsp_apic_timer");
+    kdebug!("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,
     );
-    debug!("init_bsp_apic_timer done");
+    kdebug!("init_bsp_apic_timer done");
 }
 
 fn init_ap_apic_timer() {
-    debug!("init_ap_apic_timer");
+    kdebug!("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,
     );
-    debug!("init_ap_apic_timer done");
+    kdebug!("init_ap_apic_timer done");
 }
 
 pub(super) struct LocalApicTimerIntrController;
 
 impl LocalApicTimerIntrController {
     pub(super) fn install(&self) {
-        debug!("LocalApicTimerIntrController::install");
+        kdebug!("LocalApicTimerIntrController::install");
         if smp_get_processor_id().data() == 0 {
             init_bsp_apic_timer();
         } else {
@@ -150,13 +150,12 @@ impl LocalApicTimerIntrController {
     }
 
     pub(super) fn enable(&self) {
-        debug!("LocalApicTimerIntrController::enable");
+        kdebug!("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();
     }
 
-    #[allow(dead_code)]
     pub(super) fn disable(&self) {
         let cpu_id = smp_get_processor_id();
         let local_apic_timer = local_apic_timer_instance_mut(cpu_id);
@@ -222,18 +221,19 @@ impl LocalApicTimer {
     }
 
     fn install_periodic_mode(&mut self, initial_count: u64, divisor: u32) {
-        debug!(
+        kdebug!(
             "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) {
@@ -278,7 +278,7 @@ impl LocalApicTimer {
 
     pub(super) fn handle_irq(trap_frame: &TrapFrame) -> Result<IrqReturn, SystemError> {
         // sched_update_jiffies();
-        tick_handle_periodic(trap_frame);
+        ProcessManager::update_process_times(trap_frame.is_from_user());
         return Ok(IrqReturn::Handled);
     }
 }

+ 7 - 7
kernel/src/arch/x86_64/driver/apic/ioapic.rs

@@ -4,7 +4,6 @@ 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::{
@@ -17,6 +16,7 @@ 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(|| {
-            info!("Initializing ioapic...");
+            kinfo!("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"
             );
-            debug!("Ioapic map ok");
+            kdebug!("Ioapic map ok");
             let reg = mmio_guard.vaddr();
 
             result = Some(IoApic {
@@ -114,13 +114,13 @@ impl IoApic {
                 phys_base,
                 mmio_guard,
             });
-            debug!("IOAPIC: to mask all RTE");
+            kdebug!("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);
             }
-            debug!("Ioapic init done");
+            kdebug!("Ioapic init done");
         });
 
         assert!(
@@ -393,7 +393,7 @@ impl InnerIoApicChipData {
 
 #[inline(never)]
 pub fn ioapic_init(ignore: &'static [IrqNumber]) {
-    info!("Initializing ioapic...");
+    kinfo!("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);
     }
 
-    info!("IO Apic initialized.");
+    kinfo!("IO Apic initialized.");
 }
 
 fn register_handler(desc: &Arc<IrqDesc>, level_triggered: bool) {

+ 3 - 4
kernel/src/arch/x86_64/driver/apic/lapic_vector.rs

@@ -2,7 +2,6 @@ use core::intrinsics::unlikely;
 
 use alloc::{string::ToString, sync::Arc};
 use intertrait::CastFrom;
-use log::warn;
 use system_error::SystemError;
 
 use crate::{
@@ -26,6 +25,7 @@ use crate::{
         msi::MsiMsg,
         HardwareIrqNumber, IrqNumber,
     },
+    kwarn,
     libs::spinlock::{SpinLock, SpinLockGuard},
     smp::{core::smp_get_processor_id, cpu::ProcessorId},
 };
@@ -179,7 +179,6 @@ bitflags! {
     }
 }
 
-#[allow(dead_code)]
 pub(super) fn irq_msi_compose_msg(cfg: &HardwareIrqConfig, msg: &mut MsiMsg, dmar: bool) {
     *msg = MsiMsg::new_zeroed();
 
@@ -207,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) {
-        warn!(
+        kwarn!(
             "irq_msi_compose_msg: Invalid APIC ID: {}",
             cfg.apic_id.data()
         );
@@ -253,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
-    warn!("arch_early_irq_init: todo: add vector matrix");
+    kwarn!("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,7 +1,6 @@
 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};
 
@@ -11,6 +10,7 @@ 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);
 
-        debug!("8259A Masked.");
+        kdebug!("8259A Masked.");
 
         // enable IMCR
         CurrentPortIOArch::out8(0x22, 0x70);
@@ -488,14 +488,14 @@ impl LocalAPIC for CurrentApic {
                 self.mask8259a();
             }
         }
-        info!("Initializing apic for cpu {:?}", cpu_id);
+        kinfo!("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);
             }
-            info!("x2APIC initialized for cpu {:?}", cpu_id);
+            kinfo!("x2APIC initialized for cpu {:?}", cpu_id);
         } else {
-            info!("x2APIC not supported or failed to initialize, fallback to xAPIC.");
+            kinfo!("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();
             }
 
-            info!("xAPIC initialized for cpu {:?}", cpu_id);
+            kinfo!("xAPIC initialized for cpu {:?}", cpu_id);
         }
 
-        info!("Apic initialized.");
+        kinfo!("Apic initialized.");
         return true;
     }
 

+ 6 - 5
kernel/src/arch/x86_64/driver/apic/x2apic.rs

@@ -1,11 +1,12 @@
 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)]
@@ -44,19 +45,19 @@ impl LocalAPIC for X2Apic {
                     (rdmsr(IA32_X2APIC_SIVR) & 0x100) == 0x100,
                     "x2APIC software enable failed."
                 );
-                info!("x2APIC software enabled.");
+                kinfo!("x2APIC software enabled.");
 
                 if self.support_eoi_broadcast_suppression() {
                     assert!(
                         (rdmsr(IA32_X2APIC_SIVR) & 0x1000) == 0x1000,
                         "x2APIC EOI broadcast suppression enable failed."
                     );
-                    info!("x2APIC EOI broadcast suppression enabled.");
+                    kinfo!("x2APIC EOI broadcast suppression enabled.");
                 }
             }
-            // debug!("x2apic: to mask all lvt");
+            // kdebug!("x2apic: to mask all lvt");
             self.mask_all_lvt();
-            // debug!("x2apic: all lvt masked");
+            // kdebug!("x2apic: all lvt masked");
         }
         true
     }

+ 6 - 7
kernel/src/arch/x86_64/driver/apic/xapic.rs

@@ -4,9 +4,8 @@ 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,
@@ -158,7 +157,7 @@ impl XApic {
         g.map_phys(paddr, 4096).expect("Fail to map MMIO for XAPIC");
         let addr = g.vaddr() + offset;
 
-        debug!(
+        kdebug!(
             "XAPIC: {:#x} -> {:#x}, offset={offset}",
             xapic_base.data(),
             addr.data()
@@ -220,7 +219,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 {
-                error!("xAPIC enable failed: APIC_BASE & 0x800 != 0x800");
+                kerror!("xAPIC enable failed: APIC_BASE & 0x800 != 0x800");
                 return false;
             }
             // 设置 Spurious Interrupt Vector Register
@@ -230,15 +229,15 @@ impl LocalAPIC for XApic {
 
             let val = self.read(XApicOffset::LOCAL_APIC_OFFSET_Local_APIC_SVR);
             if val & ENABLE == 0 {
-                error!("xAPIC software enable failed.");
+                kerror!("xAPIC software enable failed.");
 
                 return false;
             } else {
-                info!("xAPIC software enabled.");
+                kinfo!("xAPIC software enabled.");
             }
 
             if val & 0x1000 != 0 {
-                info!("xAPIC EOI broadcast suppression enabled.");
+                kinfo!("xAPIC EOI broadcast suppression enabled.");
             }
 
             self.mask_all_lvt();

+ 14 - 8
kernel/src/arch/x86_64/driver/hpet.rs

@@ -7,7 +7,6 @@ use core::{
 
 use acpi::HpetInfo;
 use alloc::{string::ToString, sync::Arc};
-use log::{debug, error, info};
 use system_error::SystemError;
 
 use crate::{
@@ -22,6 +21,7 @@ use crate::{
         manage::irq_manager,
         InterruptArch, IrqNumber,
     },
+    kdebug, kerror, kinfo,
     libs::{
         rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard},
         volatile::volwrite,
@@ -30,7 +30,10 @@ use crate::{
         mmio_buddy::{mmio_pool, MMIOSpaceGuard},
         PhysAddr,
     },
-    time::jiffies::NSEC_PER_JIFFY,
+    time::{
+        jiffies::NSEC_PER_JIFFY,
+        timer::{try_raise_timer_softirq, update_timer_jiffies},
+    },
 };
 
 static mut HPET_INSTANCE: Option<Hpet> = None;
@@ -77,8 +80,8 @@ impl Hpet {
                 .unwrap()
         };
         let tm_num = hpet.timers_num();
-        debug!("HPET0_INTERVAL_USEC: {}", Self::HPET0_INTERVAL_USEC);
-        info!("HPET has {} timers", tm_num);
+        kdebug!("HPET0_INTERVAL_USEC: {}", Self::HPET0_INTERVAL_USEC);
+        kinfo!("HPET has {} timers", tm_num);
         hpet_info.hpet_number = tm_num as u8;
 
         drop(mmio);
@@ -121,10 +124,10 @@ impl Hpet {
         // !!!这里是临时糊代码的,需要在apic重构的时候修改!!!
         let (inner_guard, regs) = unsafe { self.hpet_regs_mut() };
         let freq = regs.frequency();
-        debug!("HPET frequency: {} Hz", freq);
+        kdebug!("HPET frequency: {} Hz", freq);
         let ticks = Self::HPET0_INTERVAL_USEC * freq / 1000000;
         if ticks == 0 || ticks > freq * 8 {
-            error!("HPET enable: ticks '{ticks}' is invalid");
+            kerror!("HPET enable: ticks '{ticks}' is invalid");
             return Err(SystemError::EINVAL);
         }
         if unlikely(regs.timers_num() == 0) {
@@ -163,7 +166,7 @@ impl Hpet {
 
         drop(inner_guard);
 
-        info!("HPET enabled");
+        kinfo!("HPET enabled");
 
         drop(irq_guard);
         return Ok(());
@@ -236,7 +239,7 @@ impl Hpet {
     pub fn period(&self) -> u64 {
         let (inner_guard, regs) = unsafe { self.hpet_regs() };
         let period = regs.counter_clock_period();
-        debug!("HPET period: {}", period);
+        kdebug!("HPET period: {}", period);
 
         drop(inner_guard);
         return period;
@@ -246,6 +249,9 @@ impl Hpet {
     pub(super) fn handle_irq(&self, timer_num: u32) {
         if timer_num == 0 {
             assert!(!CurrentIrqArch::is_irq_enabled());
+            update_timer_jiffies(1, Self::HPET0_INTERVAL_USEC as i64);
+
+            try_raise_timer_softirq();
         }
     }
 }

+ 2 - 2
kernel/src/arch/x86_64/driver/rtc.rs

@@ -4,7 +4,6 @@ use alloc::{
     string::{String, ToString},
     sync::{Arc, Weak},
 };
-use log::error;
 use system_error::SystemError;
 use unified_init::macros::unified_init;
 
@@ -26,6 +25,7 @@ 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> {
-        error!("set_time is not implemented for CmosRtcClassOps");
+        kerror!("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() {
-            error!("TSC is not available");
+            kerror!("TSC is not available");
             return Err(SystemError::ENODEV);
         }
 
         if unsafe { TSC_KHZ == 0 } {
             if let Err(e) = Self::determine_cpu_tsc_frequency(false) {
-                error!("Failed to determine CPU TSC frequency: {:?}", e);
+                kerror!("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) {
-            warn!("TSC and CPU frequency already determined");
+            kwarn!("TSC and CPU frequency already determined");
         }
 
         if early {
@@ -79,16 +79,16 @@ impl TSCManager {
         }
 
         if Self::cpu_khz() == 0 {
-            error!("Failed to determine CPU frequency");
+            kerror!("Failed to determine CPU frequency");
             return Err(SystemError::ENODEV);
         }
 
-        info!(
+        kinfo!(
             "Detected {}.{} MHz processor",
             Self::cpu_khz() / 1000,
             Self::cpu_khz() % 1000
         );
-        info!(
+        kinfo!(
             "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();
-        debug!(
+        kdebug!(
             "Calibrating TSC with {}",
             if hpet { "HPET" } else { "PMTIMER" }
         );
@@ -143,7 +143,7 @@ impl TSCManager {
 
             // HPET或者PTIMER可能是不可用的
             if ref1 == ref2 {
-                debug!("HPET/PMTIMER not available");
+                kdebug!("HPET/PMTIMER not available");
                 continue;
             }
 
@@ -169,7 +169,7 @@ impl TSCManager {
             // 如果误差在10%以内,那么认为测量成功
             // 返回参考值,因为它是更精确的
             if (90..=110).contains(&delta) {
-                info!(
+                kinfo!(
                     "PIT calibration matches {}. {} loops",
                     if hpet { "HPET" } else { "PMTIMER" },
                     i + 1
@@ -185,20 +185,20 @@ impl TSCManager {
         }
 
         if tsc_pit_min == u64::MAX {
-            warn!("Unable to calibrate against PIT");
+            kwarn!("Unable to calibrate against PIT");
 
             // 如果没有参考值,那么禁用tsc
             if (!hpet) && (global_ref1 == 0) && (global_ref2 == 0) {
-                warn!("No reference (HPET/PMTIMER) available");
+                kwarn!("No reference (HPET/PMTIMER) available");
                 return Err(SystemError::ENODEV);
             }
 
             if tsc_ref_min == u64::MAX {
-                warn!("Unable to calibrate against HPET/PMTIMER");
+                kwarn!("Unable to calibrate against HPET/PMTIMER");
                 return Err(SystemError::ENODEV);
             }
 
-            info!(
+            kinfo!(
                 "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) {
-            info!("Using PIT calibration value");
+            kinfo!("Using PIT calibration value");
             return Ok(tsc_pit_min);
         }
 
         // The alternative source failed, use the PIT calibration value
         if tsc_ref_min == u64::MAX {
-            warn!("Unable to calibrate against HPET/PMTIMER, using PIT calibration value");
+            kwarn!("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:
-        warn!(
+        kwarn!(
             "PIT calibration deviates from {}: tsc_pit_min={}, tsc_ref_min={}",
             if hpet { "HPET" } else { "PMTIMER" },
             tsc_pit_min,
             tsc_ref_min
         );
 
-        info!("Using PIT calibration value");
+        kinfo!("Using PIT calibration value");
         return Ok(tsc_pit_min);
     }
 
@@ -326,7 +326,7 @@ impl TSCManager {
             }
         }
 
-        warn!("TSCManager: Failed to read reference value, tsc delta too high");
+        kwarn!("TSCManager: Failed to read reference value, tsc delta too high");
         return (u64::MAX, ref_ret);
     }
 

+ 6 - 7
kernel/src/arch/x86_64/init/mod.rs

@@ -1,6 +1,5 @@
 use core::sync::atomic::{compiler_fence, Ordering};
 
-use log::debug;
 use system_error::SystemError;
 use x86::dtables::DescriptorTablePointer;
 
@@ -8,6 +7,7 @@ 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},
 };
 
@@ -35,7 +35,6 @@ extern "C" {
 }
 
 #[no_mangle]
-#[allow(static_mut_refs)]
 unsafe extern "C" fn kernel_main(
     mb2_info: u64,
     mb2_magic: u64,
@@ -67,17 +66,16 @@ unsafe extern "C" fn kernel_main(
 
 /// 在内存管理初始化之前的架构相关的早期初始化
 #[inline(never)]
-#[allow(static_mut_refs)]
 pub fn early_setup_arch() -> Result<(), SystemError> {
     let stack_start = unsafe { *(head_stack_start as *const u64) } as usize;
-    debug!("head_stack_start={:#x}\n", stack_start);
+    kdebug!("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();
 
-        debug!("GDT_Table={:?}, IDT_Table={:?}\n", gdt_vaddr, idt_vaddr);
+        kdebug!("GDT_Table={:?}, IDT_Table={:?}\n", gdt_vaddr, idt_vaddr);
     }
 
     set_current_core_tss(stack_start, 0);
@@ -109,9 +107,10 @@ pub fn setup_arch_post() -> Result<(), SystemError> {
 
 fn set_current_core_tss(stack_start: usize, ist0: usize) {
     let current_tss = unsafe { TSSManager::current_tss() };
-    debug!(
+    kdebug!(
         "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);

+ 0 - 1
kernel/src/arch/x86_64/interrupt/entry.rs

@@ -564,7 +564,6 @@ pub unsafe fn set_system_trap_gate(irq: u32, ist: u8, vaddr: VirtAddr) {
     set_gate(idt_entry, 0xEF, ist, vaddr);
 }
 
-#[allow(static_mut_refs)]
 unsafe fn get_idt_entry(irq: u32) -> &'static mut [u64] {
     assert!(irq < 256);
     let mut idt_vaddr =

+ 5 - 5
kernel/src/arch/x86_64/interrupt/ipi.rs

@@ -1,5 +1,4 @@
 use alloc::sync::Arc;
-use log::error;
 use system_error::SystemError;
 use x86::apic::ApicId;
 
@@ -14,6 +13,7 @@ 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) {
-    // debug!("send_ipi: {:?} {:?}", kind, target);
+    // kdebug!("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() {
-        // debug!("send_ipi: x2apic");
+        // kdebug!("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 {
-        // debug!("send_ipi: xapic");
+        // kdebug!("send_ipi: xapic");
         x86::apic::Icr::for_xapic(
             ipi_vec,
             destination,
@@ -257,7 +257,7 @@ impl IrqFlowHandler for X86_64IpiIrqFlowHandler {
                 CurrentApic.send_eoi();
             }
             _ => {
-                error!("Unknown IPI: {}", irq.data());
+                kerror!("Unknown IPI: {}", irq.data());
                 CurrentApic.send_eoi();
             }
         }

+ 2 - 8
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) {
-        error!("Unexpected IRQ trap at vector {}", irq.data());
+        kerror!("Unexpected IRQ trap at vector {}", irq.data());
         CurrentApic.send_eoi();
     }
 
@@ -132,12 +132,6 @@ pub struct TrapFrame {
     pub ss: ::core::ffi::c_ulong,
 }
 
-impl Default for TrapFrame {
-    fn default() -> Self {
-        Self::new()
-    }
-}
-
 impl TrapFrame {
     pub fn new() -> Self {
         Self {

+ 0 - 1
kernel/src/arch/x86_64/interrupt/msi.rs

@@ -26,7 +26,6 @@ pub struct X86MsiDataNormal {
 }
 
 #[derive(Debug)]
-#[allow(dead_code)]
 pub struct X86MsiDataDmar {
     pub dmar_subhandle: u32,
 }

+ 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) {
-    error!(
+    kerror!(
         "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) {
-    error!(
+    kerror!(
         "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) {
-    error!(
+    kerror!(
         "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) {
-    error!(
+    kerror!(
         "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) {
-    error!(
+    kerror!(
         "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) {
-    error!(
+    kerror!(
         "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) {
-    error!(
+    kerror!(
         "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) {
-    error!(
+    kerror!(
         "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) {
-    error!(
+    kerror!(
         "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) {
-    error!(
+    kerror!(
         "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
     };
 
-    error!(
+    kerror!(
         "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) {
-    error!(
+    kerror!(
         "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) {
-    error!(
+    kerror!(
         "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 {
         ""
     };
-    error!(
+    kerror!(
         "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) {
-    // error!(
+    // kerror!(
     //     "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();
-    // log::info!(
+    // crate::kinfo!(
     //     "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) {
-    error!(
+    kerror!(
         "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) {
-    error!(
+    kerror!(
         "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) {
-    error!(
+    kerror!(
         "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) {
-    error!(
+    kerror!(
         "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) {
-    error!(
+    kerror!(
         "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) {
-    warn!("Unknown interrupt.");
+    kwarn!("Unknown interrupt.");
 }

+ 20 - 21
kernel/src/arch/x86_64/ipc/signal.rs

@@ -1,6 +1,5 @@
 use core::{ffi::c_void, intrinsics::unlikely, mem::size_of};
 
-use log::error;
 use system_error::SystemError;
 
 use crate::{
@@ -15,6 +14,7 @@ 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 {
-            error!("Try to convert an invalid number to Signal");
+            kerror!("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 {
-            error!("Try to convert an invalid number to Signal");
+            kerror!("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 => {
-                error!("attempting to handler an Invalid");
+                kerror!("attempting to handler an Invalid");
             }
             Signal::SIGHUP => sig_terminate(*self),
             Signal::SIGINT => sig_terminate(*self),
@@ -396,7 +396,6 @@ impl SigContext {
     }
 }
 /// @brief 信号处理备用栈的信息
-#[allow(dead_code)]
 #[derive(Debug, Clone, Copy)]
 pub struct SigStack {
     pub sp: *mut c_void,
@@ -462,7 +461,7 @@ impl SignalArch for X86_64SignalArch {
             match sigaction.action() {
                 SigactionType::SaHandler(action_type) => match action_type {
                     SaHandlerType::Error => {
-                        error!("Trying to handle a Sigerror on Process:{:?}", pcb.pid());
+                        kerror!("Trying to handle a Sigerror on Process:{:?}", pcb.pid());
                         return;
                     }
                     SaHandlerType::Default => {
@@ -489,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() {
-            error!(
+            kerror!(
                 "Error occurred when handling signal: {}, pid={:?}, errcode={:?}",
                 sig_number as i32,
                 ProcessManager::current_pcb().pid(),
@@ -503,7 +502,7 @@ impl SignalArch for X86_64SignalArch {
 
         // 如果当前的rsp不来自用户态,则认为产生了错误(或被SROP攻击)
         if UserBufferWriter::new(frame, size_of::<SigFrame>(), true).is_err() {
-            error!("rsp doesn't from user level");
+            kerror!("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;
@@ -512,7 +511,7 @@ impl SignalArch for X86_64SignalArch {
         set_current_sig_blocked(&mut sigmask);
         // 从用户栈恢复sigcontext
         if !unsafe { &mut (*frame).context }.restore_sigcontext(trap_frame) {
-            error!("unable to restore sigcontext");
+            kerror!("unable to restore sigcontext");
             let _r = Syscall::kill(ProcessManager::current_pcb().pid(), Signal::SIGSEGV as i32)
                 .map_err(|e| e.to_posix_errno());
             // 如果这里返回 err 值的话会丢失上一个系统调用的返回值
@@ -570,7 +569,7 @@ fn setup_frame(
                         sig.handle_default();
                         return Ok(0);
                     } else {
-                        error!("attempting  to execute a signal handler from kernel");
+                        kerror!("attempting  to execute a signal handler from kernel");
                         sig.handle_default();
                         return Err(SystemError::EINVAL);
                     }
@@ -579,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 {
-                        error!(
+                        kerror!(
                             "pid-{:?} forgot to set SA_FLAG_RESTORER for signal {:?}",
                             ProcessManager::current_pcb().pid(),
                             sig as i32
@@ -589,12 +588,12 @@ fn setup_frame(
                             Signal::SIGSEGV as i32,
                         );
                         if r.is_err() {
-                            error!("In setup_sigcontext: generate SIGSEGV signal failed");
+                            kerror!("In setup_sigcontext: generate SIGSEGV signal failed");
                         }
                         return Err(SystemError::EINVAL);
                     }
                     if sigaction.restorer().is_none() {
-                        error!(
+                        kerror!(
                             "restorer in process:{:?} is not defined",
                             ProcessManager::current_pcb().pid()
                         );
@@ -612,12 +611,12 @@ fn setup_frame(
         },
         SigactionType::SaSigaction(_) => {
             //TODO 这里应该是可以恢复栈的,等后续来做
-            error!("trying to recover from sigaction type instead of handler");
+            kerror!("trying to recover from sigaction type instead of handler");
             return Err(SystemError::EINVAL);
         }
     }
     let frame: *mut SigFrame = get_stack(trap_frame, size_of::<SigFrame>());
-    // debug!("frame=0x{:016x}", frame as usize);
+    // kdebug!("frame=0x{:016x}", frame as usize);
     // 要求这个frame的地址位于用户空间,因此进行校验
     let r: Result<UserBufferWriter<'_>, SystemError> =
         UserBufferWriter::new(frame, size_of::<SigFrame>(), true);
@@ -626,9 +625,9 @@ fn setup_frame(
         // todo: 生成一个sigsegv
         let r = Syscall::kill(ProcessManager::current_pcb().pid(), Signal::SIGSEGV as i32);
         if r.is_err() {
-            error!("In setup frame: generate SIGSEGV signal failed");
+            kerror!("In setup frame: generate SIGSEGV signal failed");
         }
-        error!("In setup frame: access check failed");
+        kerror!("In setup frame: access check failed");
         return Err(SystemError::EFAULT);
     }
 
@@ -637,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() {
-                error!("In copy_siginfo_to_user: generate SIGSEGV signal failed");
+                kerror!("In copy_siginfo_to_user: generate SIGSEGV signal failed");
             }
             return e;
         })?;
@@ -651,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() {
-                    error!("In setup_sigcontext: generate SIGSEGV signal failed");
+                    kerror!("In setup_sigcontext: generate SIGSEGV signal failed");
                 }
                 return e;
             })?
@@ -708,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| {
-        error!(
+        kerror!(
             "sleep error :{:?},failed to sleep process :{:?}, with signal :{:?}",
             e,
             ProcessManager::current_pcb(),
@@ -722,7 +721,7 @@ fn sig_stop(sig: Signal) {
 /// 信号默认处理函数——继续进程
 fn sig_continue(sig: Signal) {
     ProcessManager::wakeup_stop(&ProcessManager::current_pcb()).unwrap_or_else(|_| {
-        error!(
+        kerror!(
             "Failed to wake up process pid = {:?} with signal :{:?}",
             ProcessManager::current_pcb().pid(),
             sig

+ 9 - 6
kernel/src/arch/x86_64/kvm/mod.rs

@@ -2,10 +2,13 @@ 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;
@@ -51,7 +54,7 @@ impl X86_64KVMArch {
 
     #[deny(clippy::match_single_binding)]
     pub fn kvm_arch_dev_ioctl(cmd: u32, _arg: usize) -> Result<usize, SystemError> {
-        error!("unknown kvm ioctl cmd: {}", cmd);
+        kerror!("unknown kvm ioctl cmd: {}", cmd);
         return Err(SystemError::EINVAL);
     }
 
@@ -71,7 +74,7 @@ impl X86_64KVMArch {
             Ok(_) => {}
             Err(e) => {
                 let vmx_err = vmx_vmread(VmcsFields::VMEXIT_INSTR_ERR as u32).unwrap();
-                debug!("vmlaunch failed: {:?}", vmx_err);
+                kdebug!("vmlaunch failed: {:?}", vmx_err);
                 return Err(e);
             }
         }
@@ -100,12 +103,12 @@ impl X86_64KVMArch {
 
 #[no_mangle]
 pub extern "C" fn guest_code() {
-    debug!("guest_code");
+    kdebug!("guest_code");
     loop {
         unsafe {
             asm!("mov rax, 0", "mov rcx, 0", "cpuid");
         }
         unsafe { asm!("nop") };
-        debug!("guest_code");
+        kdebug!("guest_code");
     }
 }

+ 2 - 2
kernel/src/arch/x86_64/kvm/vmx/ept.rs

@@ -1,7 +1,7 @@
 use crate::arch::mm::LockedFrameAllocator;
 use crate::arch::mm::PageMapper;
 use crate::arch::MMArch;
-use crate::mm::page::EntryFlags;
+use crate::mm::page::PageFlags;
 use crate::mm::{PageTableKind, PhysAddr, VirtAddr};
 use crate::smp::core::smp_get_processor_id;
 use crate::smp::cpu::AtomicProcessorId;
@@ -92,7 +92,7 @@ impl EptMapper {
         &mut self,
         gpa: u64,
         hpa: u64,
-        flags: EntryFlags<MMArch>,
+        flags: PageFlags<MMArch>,
     ) -> Result<(), SystemError> {
         if self.readonly {
             return Err(SystemError::EAGAIN_OR_EWOULDBLOCK);

+ 5 - 5
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},
+    mm::{page::PageFlags, syscall::ProtFlags},
     virt::kvm::host_mem::{__gfn_to_pfn, kvm_vcpu_gfn_to_memslot, PAGE_MASK, PAGE_SHIFT},
 };
 use bitfield_struct::bitfield;
-use log::debug;
 use system_error::SystemError;
 
 use super::{
@@ -105,7 +105,7 @@ fn tdp_page_fault(
     error_code: u32,
     prefault: bool,
 ) -> Result<(), SystemError> {
-    debug!("tdp_page_fault");
+    kdebug!("tdp_page_fault");
     let gfn = gpa >> PAGE_SHIFT; // 物理地址右移12位得到物理页框号(相对于虚拟机而言)
                                  // 分配缓存池,为了避免在运行时分配空间失败,这里提前分配/填充足额的空间
     mmu_topup_memory_caches(vcpu)?;
@@ -211,14 +211,14 @@ pub fn __direct_map(
     pfn: u64,
     _prefault: bool,
 ) -> Result<u32, SystemError> {
-    debug!("gpa={}, pfn={}, root_hpa={:x}", gpa, pfn, vcpu.mmu.root_hpa);
+    kdebug!("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);
     }
     // 把gpa映射到hpa
     let mut ept_mapper = EptMapper::lock();
-    let page_flags = EntryFlags::from_prot_flags(ProtFlags::from_bits_truncate(0x7_u64), false);
+    let page_flags = PageFlags::from_prot_flags(ProtFlags::from_bits_truncate(0x7_u64), false);
     unsafe {
         assert!(ept_mapper.walk(gpa, pfn << PAGE_SHIFT, page_flags).is_ok());
     }

+ 35 - 33
kernel/src/arch/x86_64/kvm/vmx/vcpu.rs

@@ -9,15 +9,14 @@ 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::mm::{PhysAddr, VirtAddr};
 use crate::virt::kvm::vcpu::Vcpu;
 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;
@@ -42,7 +41,6 @@ pub struct MSRBitmap {
     pub data: [u8; PAGE_SIZE],
 }
 
-#[allow(dead_code)]
 #[derive(Debug)]
 pub struct VcpuData {
     /// The virtual and physical address of the Vmxon naturally aligned 4-KByte region of memory
@@ -74,7 +72,6 @@ pub enum VcpuState {
     Act = 2,
 }
 
-#[allow(dead_code)]
 #[derive(Debug)]
 pub struct VmxVcpu {
     pub vcpu_id: u32,
@@ -135,13 +132,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 };
-        debug!("[+] VMXON Region Virtual Address: {:p}", self.vmxon_region);
-        debug!(
+        kdebug!("[+] VMXON Region Virtual Address: {:p}", self.vmxon_region);
+        kdebug!(
             "[+] VMXON Region Physical Addresss: 0x{:x}",
             self.vmxon_region_physical_address
         );
-        debug!("[+] VMCS Region Virtual Address: {:p}", self.vmcs_region);
-        debug!(
+        kdebug!("[+] VMCS Region Virtual Address: {:p}", self.vmcs_region);
+        kdebug!(
             "[+] VMCS Region Physical Address1: 0x{:x}",
             self.vmcs_region_physical_address
         );
@@ -153,7 +150,7 @@ impl VcpuData {
 
 impl VmxVcpu {
     pub fn new(vcpu_id: u32, parent_vm: Vm) -> Result<Self, SystemError> {
-        debug!("Creating processor {}", vcpu_id);
+        kdebug!("Creating processor {}", vcpu_id);
         let instance = Self {
             vcpu_id,
             vcpu_ctx: VcpuContextFrame {
@@ -254,8 +251,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)?;
-        debug!("vmcs init guest rip: {:#x}", self.vcpu_ctx.rip as u64);
-        debug!(
+        kdebug!("vmcs init guest rip: {:#x}", self.vcpu_ctx.rip as u64);
+        kdebug!(
             "vmcs init guest rsp: {:#x}",
             self.vcpu_ctx.regs[VcpuRegIndex::Rsp as usize] as u64
         );
@@ -320,13 +317,13 @@ impl VmxVcpu {
         )?;
         vmx_vmwrite(
             VmcsFields::HOST_GDTR_BASE as u32,
-            pseudo_descriptpr.base as usize as u64,
+            pseudo_descriptpr.base.to_bits() as u64,
         )?;
         vmx_vmwrite(VmcsFields::HOST_IDTR_BASE as u32, unsafe {
             let mut pseudo_descriptpr: x86::dtables::DescriptorTablePointer<u64> =
                 Default::default();
             x86::dtables::sidt(&mut pseudo_descriptpr);
-            pseudo_descriptpr.base as usize as u64
+            pseudo_descriptpr.base.to_bits() as u64
         })?;
 
         // fast entry into the kernel
@@ -341,7 +338,7 @@ impl VmxVcpu {
         })?;
 
         // vmx_vmwrite(VmcsFields::HOST_RIP as u32, vmx_return as *const () as u64)?;
-        // debug!("vmcs init host rip: {:#x}", vmx_return as *const () as u64);
+        // kdebug!("vmcs init host rip: {:#x}", vmx_return as *const () as u64);
 
         Ok(())
     }
@@ -391,7 +388,7 @@ impl VmxVcpu {
     }
 
     fn kvm_mmu_load(&mut self) -> Result<(), SystemError> {
-        debug!("kvm_mmu_load!");
+        kdebug!("kvm_mmu_load!");
         // 申请并创建新的页表
         let mapper: crate::mm::page::PageMapper<X86_64MMArch, LockedFrameAllocator> = unsafe {
             PageMapper::create(PageTableKind::EPT, LockedFrameAllocator)
@@ -402,7 +399,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;
-        debug!("ept_root_hpa:{:x}!", ept_root_hpa.data() as u64);
+        kdebug!("ept_root_hpa:{:x}!", ept_root_hpa.data() as u64);
 
         return Ok(());
     }
@@ -418,33 +415,33 @@ impl Vcpu for VmxVcpu {
     fn virtualize_cpu(&mut self) -> Result<(), SystemError> {
         match has_intel_vmx_support() {
             Ok(_) => {
-                debug!("[+] CPU supports Intel VMX");
+                kdebug!("[+] CPU supports Intel VMX");
             }
             Err(e) => {
-                debug!("[-] CPU does not support Intel VMX: {:?}", e);
+                kdebug!("[-] CPU does not support Intel VMX: {:?}", e);
                 return Err(SystemError::ENOSYS);
             }
         };
 
         match enable_vmx_operation() {
             Ok(_) => {
-                debug!("[+] Enabling Virtual Machine Extensions (VMX)");
+                kdebug!("[+] Enabling Virtual Machine Extensions (VMX)");
             }
             Err(_) => {
-                debug!("[-] VMX operation is not supported on this processor.");
+                kdebug!("[-] VMX operation is not supported on this processor.");
                 return Err(SystemError::ENOSYS);
             }
         }
 
         vmxon(self.data.vmxon_region_physical_address)?;
-        debug!("[+] VMXON successful!");
+        kdebug!("[+] VMXON successful!");
         vmx_vmclear(self.data.vmcs_region_physical_address)?;
         vmx_vmptrld(self.data.vmcs_region_physical_address)?;
-        debug!("[+] VMPTRLD successful!");
+        kdebug!("[+] VMPTRLD successful!");
         self.vmcs_init().expect("vncs_init fail");
-        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());
+        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());
         // 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,9 +473,14 @@ pub fn get_segment_base(gdt_base: *const u64, gdt_size: u16, segment_selector: u
     let base_mid = (descriptor & 0x0000_00FF_0000_0000) >> 16;
     let base_low = (descriptor & 0x0000_0000_FFFF_0000) >> 16;
     let segment_base = (base_high | base_mid | base_low) & 0xFFFFFFFF;
-    let virtaddr = unsafe { MMArch::phys_2_virt(PhysAddr::new(segment_base as usize)).unwrap() };
-
-    return virtaddr.data() as u64;
+    let virtaddr = phys_2_virt(segment_base.try_into().unwrap())
+        .try_into()
+        .unwrap();
+    kdebug!(
+        "segment_base={:x}",
+        phys_2_virt(segment_base.try_into().unwrap())
+    );
+    return virtaddr;
 }
 
 // FIXME: may have bug
@@ -534,7 +536,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);
-    // debug!("adjust_vmx_pinbased_controls: {:x}", controls);
+    // kdebug!("adjust_vmx_pinbased_controls: {:x}", controls);
     return controls;
 }
 
@@ -591,11 +593,11 @@ pub fn enable_vmx_operation() -> Result<(), SystemError> {
     unsafe { controlregs::cr4_write(cr4) };
 
     set_lock_bit()?;
-    debug!("[+] Lock bit set via IA32_FEATURE_CONTROL");
+    kdebug!("[+] Lock bit set via IA32_FEATURE_CONTROL");
     set_cr0_bits();
-    debug!("[+] Mandatory bits in CR0 set/cleared");
+    kdebug!("[+] Mandatory bits in CR0 set/cleared");
     set_cr4_bits();
-    debug!("[+] Mandatory bits in CR4 set/cleared");
+    kdebug!("[+] Mandatory bits in CR4 set/cleared");
 
     Ok(())
 }

+ 15 - 16
kernel/src/arch/x86_64/kvm/vmx/vmexit.rs

@@ -1,9 +1,8 @@
 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;
 
@@ -148,7 +147,7 @@ pub struct GuestCpuContext {
 
 #[no_mangle]
 pub extern "C" fn vmx_return() {
-    debug!("vmx_return!");
+    kdebug!("vmx_return!");
     unsafe { save_rpg() };
     vmexit_handler();
     // XMM registers are vector registers. They're renamed onto the FP/SIMD register file
@@ -182,14 +181,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() };
-    // debug!("guest_cpu_context_ptr={:p}",guest_cpu_context_ptr);
-    debug!("vmexit handler!");
+    // kdebug!("guest_cpu_context_ptr={:p}",guest_cpu_context_ptr);
+    kdebug!("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();
-    debug!("guest_rip={:x}", guest_rip);
+    kdebug!("guest_rip={:x}", guest_rip);
     let _guest_rflags = vmx_vmread(VmcsFields::GUEST_RFLAGS as u32).unwrap();
 
     match VmxExitReason::from(exit_basic_reason as i32) {
@@ -206,28 +205,28 @@ extern "C" fn vmexit_handler() {
         | VmxExitReason::VMFUNC
         | VmxExitReason::INVEPT
         | VmxExitReason::INVVPID => {
-            debug!("vmexit handler: vmx instruction!");
+            kdebug!("vmexit handler: vmx instruction!");
             vmexit_vmx_instruction_executed().expect("previledge instruction handle error");
         }
         VmxExitReason::CPUID => {
-            debug!("vmexit handler: cpuid instruction!");
+            kdebug!("vmexit handler: cpuid instruction!");
             // vmexit_cpuid_handler(guest_cpu_context);
             adjust_rip(guest_rip).unwrap();
         }
         VmxExitReason::RDMSR => {
-            debug!("vmexit handler: rdmsr instruction!");
+            kdebug!("vmexit handler: rdmsr instruction!");
             adjust_rip(guest_rip).unwrap();
         }
         VmxExitReason::WRMSR => {
-            debug!("vmexit handler: wrmsr instruction!");
+            kdebug!("vmexit handler: wrmsr instruction!");
             adjust_rip(guest_rip).unwrap();
         }
         VmxExitReason::TRIPLE_FAULT => {
-            debug!("vmexit handler: triple fault!");
+            kdebug!("vmexit handler: triple fault!");
             adjust_rip(guest_rip).unwrap();
         }
         VmxExitReason::EPT_VIOLATION => {
-            debug!("vmexit handler: ept violation!");
+            kdebug!("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? */
@@ -245,17 +244,17 @@ extern "C" fn vmexit_handler() {
                 .expect("ept page fault error");
         }
         _ => {
-            debug!(
+            kdebug!(
                 "vmexit handler: unhandled vmexit reason: {}!",
                 exit_basic_reason
             );
 
             let info = vmx_vmread(VmcsFields::VMEXIT_INSTR_LEN as u32).unwrap() as u32;
-            debug!("vmexit handler: VMEXIT_INSTR_LEN: {}!", info);
+            kdebug!("vmexit handler: VMEXIT_INSTR_LEN: {}!", info);
             let info = vmx_vmread(VmcsFields::VMEXIT_INSTR_INFO as u32).unwrap() as u32;
-            debug!("vmexit handler: VMEXIT_INSTR_INFO: {}!", info);
+            kdebug!("vmexit handler: VMEXIT_INSTR_INFO: {}!", info);
             let info = vmx_vmread(VmcsFields::CTRL_EXPECTION_BITMAP as u32).unwrap() as u32;
-            debug!("vmexit handler: CTRL_EXPECTION_BITMAP: {}!", info);
+            kdebug!("vmexit handler: CTRL_EXPECTION_BITMAP: {}!", info);
 
             adjust_rip(guest_rip).unwrap();
             // panic!();

+ 8 - 9
kernel/src/arch/x86_64/kvm/vmx/vmx_asm_wrapper.rs

@@ -1,7 +1,6 @@
 use super::vmcs::VmcsFields;
-
+use crate::kdebug;
 use core::arch::asm;
-use log::debug;
 use system_error::SystemError;
 use x86;
 /// Enable VMX operation.
@@ -9,7 +8,7 @@ pub fn vmxon(vmxon_pa: u64) -> Result<(), SystemError> {
     match unsafe { x86::bits64::vmx::vmxon(vmxon_pa) } {
         Ok(_) => Ok(()),
         Err(e) => {
-            debug!("vmxon fail: {:?}", e);
+            kdebug!("vmxon fail: {:?}", e);
             Err(SystemError::EVMXONFailed)
         }
     }
@@ -28,8 +27,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) => {
-            debug!("vmx_write fail: {:?}", e);
-            debug!("vmcs_field: {:x}", vmcs_field);
+            kdebug!("vmx_write fail: {:?}", e);
+            kdebug!("vmcs_field: {:x}", vmcs_field);
             Err(SystemError::EVMWRITEFailed)
         }
     }
@@ -40,7 +39,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) => {
-            debug!("vmx_read fail: {:?}", e);
+            kdebug!("vmx_read fail: {:?}", e);
             Err(SystemError::EVMREADFailed)
         }
     }
@@ -64,10 +63,10 @@ pub fn vmx_vmlaunch() -> Result<(), SystemError> {
             "push    rsi",
             "push    rdi",
             "vmwrite {0:r}, rsp",
-            "lea rax, 2f[rip]",
+            "lea rax, 1f[rip]",
             "vmwrite {1:r}, rax",
             "vmlaunch",
-            "2:",
+            "1:",
             "pop    rdi",
             "pop    rsi",
             "pop    rdx",
@@ -83,7 +82,7 @@ pub fn vmx_vmlaunch() -> Result<(), SystemError> {
     // match unsafe { x86::bits64::vmx::vmlaunch() } {
     //     Ok(_) => Ok(()),
     //     Err(e) => {
-    //         debug!("vmx_launch fail: {:?}", e);
+    //         kdebug!("vmx_launch fail: {:?}", e);
     //         Err(SystemError::EVMLAUNCHFailed)
     //     },
     // }

+ 14 - 12
kernel/src/arch/x86_64/mm/fault.rs

@@ -4,7 +4,6 @@ use core::{
 };
 
 use alloc::sync::Arc;
-use log::error;
 use x86::{bits64::rflags::RFlags, controlregs::Cr4};
 
 use crate::{
@@ -14,6 +13,7 @@ use crate::{
         CurrentIrqArch, MMArch,
     },
     exception::InterruptArch,
+    kerror,
     mm::{
         fault::{FaultFlags, PageFaultHandler, PageFaultMessage},
         ucontext::{AddressSpace, LockedVMA},
@@ -28,7 +28,7 @@ pub type PageMapper =
 
 impl X86_64MMArch {
     pub fn vma_access_error(vma: Arc<LockedVMA>, error_code: X86PfErrorCode) -> bool {
-        let vm_flags = *vma.lock_irqsave().vm_flags();
+        let vm_flags = *vma.lock().vm_flags();
         let foreign = false;
         if error_code.contains(X86PfErrorCode::X86_PF_PK) {
             return true;
@@ -74,27 +74,27 @@ impl X86_64MMArch {
         if let Some(entry) = mapper.get_entry(address, 0) {
             if entry.present() {
                 if !entry.flags().has_execute() {
-                    error!("kernel tried to execute NX-protected page - exploit attempt?");
+                    kerror!("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) }
                 {
-                    error!("unable to execute userspace code (SMEP?)");
+                    kerror!("unable to execute userspace code (SMEP?)");
                 }
             }
         }
         if address.data() < X86_64MMArch::PAGE_SIZE && !regs.is_from_user() {
-            error!(
+            kerror!(
                 "BUG: kernel NULL pointer dereference, address: {:#x}",
                 address.data()
             );
         } else {
-            error!(
+            kerror!(
                 "BUG: unable to handle page fault for address: {:#x}",
                 address.data()
             );
         }
 
-        error!(
+        kerror!(
             "#PF: {} {} in {} mode\n",
             if error_code.contains(X86PfErrorCode::X86_PF_USER) {
                 "user"
@@ -114,7 +114,7 @@ impl X86_64MMArch {
                 "kernel"
             }
         );
-        error!(
+        kerror!(
             "#PF: error_code({:#04x}) - {}\n",
             error_code,
             if !error_code.contains(X86PfErrorCode::X86_PF_PROT) {
@@ -223,7 +223,7 @@ impl X86_64MMArch {
         }
 
         let current_address_space: Arc<AddressSpace> = AddressSpace::current().unwrap();
-        let mut space_guard = current_address_space.write_irqsave();
+        let mut space_guard = current_address_space.write();
         let mut fault;
         loop {
             let vma = space_guard.mappings.find_nearest(address);
@@ -236,7 +236,7 @@ impl X86_64MMArch {
                     address.data(),
                 )
             });
-            let guard = vma.lock_irqsave();
+            let guard = vma.lock();
             let region = *guard.region();
             let vm_flags = *guard.vm_flags();
             drop(guard);
@@ -269,9 +269,11 @@ impl X86_64MMArch {
                 );
             }
             let mapper = &mut space_guard.user_mapper.utable;
-            let message = PageFaultMessage::new(vma.clone(), address, flags, mapper);
 
-            fault = PageFaultHandler::handle_mm_fault(message);
+            fault = PageFaultHandler::handle_mm_fault(
+                PageFaultMessage::new(vma.clone(), address, flags),
+                mapper,
+            );
 
             if fault.contains(VmFaultReason::VM_FAULT_COMPLETED) {
                 return;

+ 28 - 114
kernel/src/arch/x86_64/mm/mod.rs

@@ -6,7 +6,6 @@ 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;
 
@@ -28,9 +27,9 @@ use crate::{
 };
 
 use crate::mm::kernel_mapper::KernelMapper;
-use crate::mm::page::{EntryFlags, PageEntry, PAGE_1G_SHIFT};
-use crate::mm::{MemoryManagementArch, PageTableKind, PhysAddr, VirtAddr, VmFlags};
-
+use crate::mm::page::{PageEntry, PageFlags, PAGE_1G_SHIFT};
+use crate::mm::{MemoryManagementArch, PageTableKind, PhysAddr, VirtAddr};
+use crate::{kdebug, kinfo, kwarn};
 use system_error::SystemError;
 
 use core::arch::asm;
@@ -160,8 +159,8 @@ impl MemoryManagementArch for X86_64MMArch {
         // 初始化物理内存区域(从multiboot2中获取)
         Self::init_memory_area_from_multiboot2().expect("init memory area failed");
 
-        debug!("bootstrap info: {:?}", unsafe { BOOTSTRAP_MM_INFO });
-        debug!("phys[0]=virt[0x{:x}]", unsafe {
+        kdebug!("bootstrap info: {:?}", unsafe { BOOTSTRAP_MM_INFO });
+        kdebug!("phys[0]=virt[0x{:x}]", unsafe {
             MMArch::phys_2_virt(PhysAddr::new(0)).unwrap().data()
         });
 
@@ -326,93 +325,6 @@ impl MemoryManagementArch for X86_64MMArch {
         }
         pkru::pkru_allows_pkey(pkru::vma_pkey(vma), write)
     }
-
-    const PROTECTION_MAP: [EntryFlags<MMArch>; 16] = protection_map();
-
-    const PAGE_NONE: usize =
-        Self::ENTRY_FLAG_PRESENT | Self::ENTRY_FLAG_ACCESSED | Self::ENTRY_FLAG_GLOBAL;
-
-    const PAGE_SHARED: usize = Self::ENTRY_FLAG_PRESENT
-        | Self::ENTRY_FLAG_READWRITE
-        | Self::ENTRY_FLAG_USER
-        | Self::ENTRY_FLAG_ACCESSED
-        | Self::ENTRY_FLAG_NO_EXEC;
-
-    const PAGE_SHARED_EXEC: usize = Self::ENTRY_FLAG_PRESENT
-        | Self::ENTRY_FLAG_READWRITE
-        | Self::ENTRY_FLAG_USER
-        | Self::ENTRY_FLAG_ACCESSED;
-
-    const PAGE_COPY_NOEXEC: usize = Self::ENTRY_FLAG_PRESENT
-        | Self::ENTRY_FLAG_USER
-        | Self::ENTRY_FLAG_ACCESSED
-        | Self::ENTRY_FLAG_NO_EXEC;
-
-    const PAGE_COPY_EXEC: usize =
-        Self::ENTRY_FLAG_PRESENT | Self::ENTRY_FLAG_USER | Self::ENTRY_FLAG_ACCESSED;
-
-    const PAGE_COPY: usize = Self::ENTRY_FLAG_PRESENT
-        | Self::ENTRY_FLAG_USER
-        | Self::ENTRY_FLAG_ACCESSED
-        | Self::ENTRY_FLAG_NO_EXEC;
-
-    const PAGE_READONLY: usize = Self::ENTRY_FLAG_PRESENT
-        | Self::ENTRY_FLAG_USER
-        | Self::ENTRY_FLAG_ACCESSED
-        | Self::ENTRY_FLAG_NO_EXEC;
-
-    const PAGE_READONLY_EXEC: usize =
-        Self::ENTRY_FLAG_PRESENT | Self::ENTRY_FLAG_USER | Self::ENTRY_FLAG_ACCESSED;
-
-    const PAGE_READ: usize = 0;
-    const PAGE_READ_EXEC: usize = 0;
-    const PAGE_WRITE: usize = 0;
-    const PAGE_WRITE_EXEC: usize = 0;
-    const PAGE_EXEC: usize = 0;
-}
-
-/// 获取保护标志的映射表
-///
-///
-/// ## 返回值
-/// - `[usize; 16]`: 长度为16的映射表
-const fn protection_map() -> [EntryFlags<MMArch>; 16] {
-    let mut map = [unsafe { EntryFlags::from_data(0) }; 16];
-    unsafe {
-        map[VmFlags::VM_NONE.bits()] = EntryFlags::from_data(MMArch::PAGE_NONE);
-        map[VmFlags::VM_READ.bits()] = EntryFlags::from_data(MMArch::PAGE_READONLY);
-        map[VmFlags::VM_WRITE.bits()] = EntryFlags::from_data(MMArch::PAGE_COPY);
-        map[VmFlags::VM_WRITE.bits() | VmFlags::VM_READ.bits()] =
-            EntryFlags::from_data(MMArch::PAGE_COPY);
-        map[VmFlags::VM_EXEC.bits()] = EntryFlags::from_data(MMArch::PAGE_READONLY_EXEC);
-        map[VmFlags::VM_EXEC.bits() | VmFlags::VM_READ.bits()] =
-            EntryFlags::from_data(MMArch::PAGE_READONLY_EXEC);
-        map[VmFlags::VM_EXEC.bits() | VmFlags::VM_WRITE.bits()] =
-            EntryFlags::from_data(MMArch::PAGE_COPY_EXEC);
-        map[VmFlags::VM_EXEC.bits() | VmFlags::VM_WRITE.bits() | VmFlags::VM_READ.bits()] =
-            EntryFlags::from_data(MMArch::PAGE_COPY_EXEC);
-        map[VmFlags::VM_SHARED.bits()] = EntryFlags::from_data(MMArch::PAGE_NONE);
-        map[VmFlags::VM_SHARED.bits() | VmFlags::VM_READ.bits()] =
-            EntryFlags::from_data(MMArch::PAGE_READONLY);
-        map[VmFlags::VM_SHARED.bits() | VmFlags::VM_WRITE.bits()] =
-            EntryFlags::from_data(MMArch::PAGE_SHARED);
-        map[VmFlags::VM_SHARED.bits() | VmFlags::VM_WRITE.bits() | VmFlags::VM_READ.bits()] =
-            EntryFlags::from_data(MMArch::PAGE_SHARED);
-        map[VmFlags::VM_SHARED.bits() | VmFlags::VM_EXEC.bits()] =
-            EntryFlags::from_data(MMArch::PAGE_READONLY_EXEC);
-        map[VmFlags::VM_SHARED.bits() | VmFlags::VM_EXEC.bits() | VmFlags::VM_READ.bits()] =
-            EntryFlags::from_data(MMArch::PAGE_READONLY_EXEC);
-        map[VmFlags::VM_SHARED.bits() | VmFlags::VM_EXEC.bits() | VmFlags::VM_WRITE.bits()] =
-            EntryFlags::from_data(MMArch::PAGE_SHARED_EXEC);
-        map[VmFlags::VM_SHARED.bits()
-            | VmFlags::VM_EXEC.bits()
-            | VmFlags::VM_WRITE.bits()
-            | VmFlags::VM_READ.bits()] = EntryFlags::from_data(MMArch::PAGE_SHARED_EXEC);
-    }
-    // if X86_64MMArch::is_xd_reserved() {
-    //     map.iter_mut().for_each(|x| *x &= !Self::ENTRY_FLAG_NO_EXEC)
-    // }
-    map
 }
 
 impl X86_64MMArch {
@@ -470,16 +382,18 @@ impl X86_64MMArch {
                         info_entry.len as usize,
                     )
                     .unwrap_or_else(|e| {
-                        warn!(
+                        kwarn!(
                             "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());
-        info!("Total memory size: {} MB, total areas from multiboot2: {mb2_count}, valid areas: {areas_count}", total_mem_size / 1024 / 1024);
+        kinfo!("Total memory size: {} MB, total areas from multiboot2: {mb2_count}, valid areas: {areas_count}", total_mem_size / 1024 / 1024);
         return Ok(areas_count);
     }
 
@@ -488,7 +402,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
-            debug!("NO_EXECUTE_ENABLE is false, set XD_RESERVED to true");
+            kdebug!("NO_EXECUTE_ENABLE is false, set XD_RESERVED to true");
             XD_RESERVED.store(true, Ordering::Relaxed);
         }
         compiler_fence(Ordering::SeqCst);
@@ -524,7 +438,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());
-    debug!(
+    kdebug!(
         "BumpAllocator created, offset={:?}",
         bump_allocator.offset()
     );
@@ -545,7 +459,7 @@ unsafe fn allocator_init() {
             )
             .expect("Failed to create page mapper");
         new_page_table = mapper.table().phys();
-        debug!("PageMapper created");
+        kdebug!("PageMapper created");
 
         // 取消最开始时候,在head.S中指定的映射(暂时不刷新TLB)
         {
@@ -557,12 +471,12 @@ unsafe fn allocator_init() {
                     .expect("Failed to empty page table entry");
             }
         }
-        debug!("Successfully emptied page table");
+        kdebug!("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();
-            // debug!("area: base={:?}, size={:#x}, end={:?}", area.base, area.size, area.base + area.size);
+            // kdebug!("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();
@@ -580,7 +494,7 @@ unsafe fn allocator_init() {
     unsafe {
         INITIAL_CR3_VALUE = new_page_table;
     }
-    debug!(
+    kdebug!(
         "After mapping all physical memory, DragonOS used: {} KB",
         bump_allocator.offset() / 1024
     );
@@ -589,7 +503,7 @@ unsafe fn allocator_init() {
     let buddy_allocator = unsafe { BuddyAllocator::<X86_64MMArch>::new(bump_allocator).unwrap() };
     // 设置全局的页帧分配器
     unsafe { set_inner_allocator(buddy_allocator) };
-    info!("Successfully initialized buddy allocator");
+    kinfo!("Successfully initialized buddy allocator");
     // 关闭显示输出
     scm_disable_put_to_window();
 
@@ -597,7 +511,7 @@ unsafe fn allocator_init() {
     {
         let mut binding = INNER_ALLOCATOR.lock();
         let mut allocator_guard = binding.as_mut().unwrap();
-        debug!("To enable new page table.");
+        kdebug!("To enable new page table.");
         compiler_fence(Ordering::SeqCst);
         let mapper = crate::mm::page::PageMapper::<MMArch, _>::new(
             PageTableKind::Kernel,
@@ -607,9 +521,9 @@ unsafe fn allocator_init() {
         compiler_fence(Ordering::SeqCst);
         mapper.make_current();
         compiler_fence(Ordering::SeqCst);
-        debug!("New page table enabled");
+        kdebug!("New page table enabled");
     }
-    debug!("Successfully enabled new page table");
+    kdebug!("Successfully enabled new page table");
 }
 
 #[no_mangle]
@@ -622,7 +536,7 @@ pub fn test_buddy() {
     const TOTAL_SIZE: usize = 200 * 1024 * 1024;
 
     for i in 0..10 {
-        debug!("Test buddy, round: {i}");
+        kdebug!("Test buddy, round: {i}");
         // 存放申请的内存块
         let mut v: Vec<(PhysAddr, PageFrameCount)> = Vec::with_capacity(60 * 1024);
         // 存放已经申请的内存块的地址(用于检查重复)
@@ -687,14 +601,14 @@ pub fn test_buddy() {
             }
         }
 
-        debug!(
+        kdebug!(
             "Allocated {} MB memory, release: {} MB, no release: {} bytes",
             allocated / 1024 / 1024,
             free_count / 1024 / 1024,
             (allocated - free_count)
         );
 
-        debug!("Now, to release buddy memory");
+        kdebug!("Now, to release buddy memory");
         // 释放所有的内存
         for (paddr, allocated_frame_count) in v {
             unsafe { LockedFrameAllocator.free(paddr, allocated_frame_count) };
@@ -702,7 +616,7 @@ pub fn test_buddy() {
             free_count += allocated_frame_count.data() * MMArch::PAGE_SIZE;
         }
 
-        debug!("release done!, allocated: {allocated}, free_count: {free_count}");
+        kdebug!("release done!, allocated: {allocated}, free_count: {free_count}");
     }
 }
 
@@ -737,17 +651,17 @@ impl FrameAllocator for LockedFrameAllocator {
 }
 
 /// 获取内核地址默认的页面标志
-pub unsafe fn kernel_page_flags<A: MemoryManagementArch>(virt: VirtAddr) -> EntryFlags<A> {
+pub unsafe fn kernel_page_flags<A: MemoryManagementArch>(virt: VirtAddr) -> PageFlags<A> {
     let info: X86_64MMBootstrapInfo = BOOTSTRAP_MM_INFO.unwrap();
 
     if virt.data() >= info.kernel_code_start && virt.data() < info.kernel_code_end {
         // Remap kernel code  execute
-        return EntryFlags::new().set_execute(true).set_write(true);
+        return PageFlags::new().set_execute(true).set_write(true);
     } else if virt.data() >= info.kernel_data_end && virt.data() < info.kernel_rodata_end {
         // Remap kernel rodata read only
-        return EntryFlags::new().set_execute(true);
+        return PageFlags::new().set_execute(true);
     } else {
-        return EntryFlags::new().set_write(true).set_execute(true);
+        return PageFlags::new().set_write(true).set_execute(true);
     }
 }
 

+ 2 - 2
kernel/src/arch/x86_64/mm/pkru.rs

@@ -16,8 +16,8 @@ const PKEY_MASK: usize = 1 << 32 | 1 << 33 | 1 << 34 | 1 << 35;
 /// ## 返回值
 /// - `u16`: vma的protection_key
 pub fn vma_pkey(vma: Arc<LockedVMA>) -> u16 {
-    let guard = vma.lock_irqsave();
-    ((guard.vm_flags().bits() & PKEY_MASK) >> VM_PKEY_SHIFT) as u16
+    let guard = vma.lock();
+    ((guard.vm_flags().bits() & PKEY_MASK as u64) >> VM_PKEY_SHIFT) as u16
 }
 
 // TODO pkru实现参考:https://code.dragonos.org.cn/xref/linux-6.6.21/arch/x86/include/asm/pkru.h

+ 0 - 1
kernel/src/arch/x86_64/mod.rs

@@ -30,7 +30,6 @@ pub use interrupt::X86_64InterruptArch as CurrentIrqArch;
 pub use crate::arch::asm::pio::X86_64PortIOArch as CurrentPortIOArch;
 pub use kvm::X86_64KVMArch as KVMArch;
 
-#[allow(unused_imports)]
 pub use crate::arch::ipc::signal::X86_64SignalArch as CurrentSignalArch;
 pub use crate::arch::time::X86_64TimeArch as CurrentTimeArch;
 

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

@@ -2,40 +2,18 @@ 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, PciCam, PciError, PORT_PCI_CONFIG_ADDRESS,
-    PORT_PCI_CONFIG_DATA,
+    pci_init, BusDeviceFunction, PciAddr, PciError, PORT_PCI_CONFIG_ADDRESS, PORT_PCI_CONFIG_DATA,
 };
-use crate::driver::pci::root::{pci_root_manager, PciRoot};
-use crate::include::bindings::bindings::{io_in32, io_in8, io_out32};
+use crate::include::bindings::bindings::{io_in32, io_out32};
 use crate::init::initcall::INITCALL_SUBSYS;
+use crate::kerror;
 use crate::mm::PhysAddr;
 
 use acpi::mcfg::Mcfg;
-use log::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配置空间地址
@@ -72,18 +50,8 @@ impl TraitPciArch for X86_64PciArch {
 
 #[unified_init(INITCALL_SUBSYS)]
 fn x86_64_pci_init() -> Result<(), SystemError> {
-    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);
-        }
+    if let Err(e) = discover_ecam_root() {
+        kerror!("x86_64_pci_init(): discover_ecam_root error: {:?}", e);
     }
     pci_init();
 

+ 2 - 3
kernel/src/arch/x86_64/process/idle.rs

@@ -1,10 +1,9 @@
 use core::hint::spin_loop;
 
-use log::error;
-
 use crate::{
     arch::CurrentIrqArch,
     exception::InterruptArch,
+    kBUG,
     process::{ProcessFlags, ProcessManager},
     sched::{SchedMode, __schedule},
 };
@@ -22,7 +21,7 @@ impl ProcessManager {
                     x86::halt();
                 }
             } else {
-                error!("Idle process should not be scheduled with IRQs disabled.");
+                kBUG!("Idle process should not be scheduled with IRQs disabled.");
                 spin_loop();
             }
         }

+ 2 - 1
kernel/src/arch/x86_64/process/kthread.rs

@@ -42,8 +42,9 @@ impl KernelThreadMechanism {
         frame.rip = kernel_thread_bootstrap_stage1 as usize as u64;
 
         // fork失败的话,子线程不会执行。否则将导致内存安全问题。
-        let pid = ProcessManager::fork(&frame, clone_flags).inspect_err(|_e| {
+        let pid = ProcessManager::fork(&frame, clone_flags).map_err(|e| {
             unsafe { KernelThreadCreateInfo::parse_unsafe_arc_ptr(create_info) };
+            e
         })?;
 
         ProcessManager::find(pid)

+ 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()) {
-            warn!("fp_state is none");
+            kwarn!("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()) {
-            error!("p={:p}", p);
+            kerror!("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);
-        // debug!("switch tss ok");
+        // kdebug!("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>(),
     );
-    // debug!("trap_frame_vaddr: {:?}", trap_frame_vaddr);
+    // kdebug!("trap_frame_vaddr: {:?}", trap_frame_vaddr);
 
     assert!(
         (x86::current::registers::rsp() as usize) < trap_frame_vaddr.data(),

+ 19 - 17
kernel/src/arch/x86_64/process/syscall.rs

@@ -1,4 +1,4 @@
-use alloc::{ffi::CString, string::String, sync::Arc, vec::Vec};
+use alloc::{string::String, sync::Arc, vec::Vec};
 use system_error::SystemError;
 
 use crate::{
@@ -19,14 +19,14 @@ use crate::{
 impl Syscall {
     pub fn do_execve(
         path: String,
-        argv: Vec<CString>,
-        envp: Vec<CString>,
+        argv: Vec<String>,
+        envp: Vec<String>,
         regs: &mut TrapFrame,
     ) -> Result<(), SystemError> {
         // 关中断,防止在设置地址空间的时候,发生中断,然后进调度器,出现错误。
         let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
         let pcb = ProcessManager::current_pcb();
-        // log::debug!(
+        // crate::kdebug!(
         //     "pid: {:?}  do_execve: path: {:?}, argv: {:?}, envp: {:?}\n",
         //     pcb.pid(),
         //     path,
@@ -55,27 +55,23 @@ impl Syscall {
             AddressSpace::is_current(&address_space),
             "Failed to set address space"
         );
-        // debug!("Switch to new address space");
+        // kdebug!("Switch to new address space");
 
         // 切换到新的用户地址空间
         unsafe { address_space.read().user_mapper.utable.make_current() };
 
         drop(old_address_space);
         drop(irq_guard);
-        // debug!("to load binary file");
+        // kdebug!("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)?;
-        // debug!("load binary file done");
-        // debug!("argv: {:?}, envp: {:?}", argv, envp);
+        // kdebug!("load binary file done");
+        // kdebug!("argv: {:?}, envp: {:?}", argv, envp);
         param.init_info_mut().args = argv;
         param.init_info_mut().envs = envp;
 
-        // 生成16字节随机数
-        // TODO 暂时设为0
-        param.init_info_mut().rand_num = [0u8; 16];
-
         // 把proc_init_info写到用户栈上
         let mut ustack_message = unsafe {
             address_space
@@ -86,13 +82,19 @@ impl Syscall {
         };
         let (user_sp, argv_ptr) = unsafe {
             param
-                .init_info_mut()
-                .push_at(&mut ustack_message)
+                .init_info()
+                .push_at(
+                    // address_space
+                    //     .write()
+                    //     .user_stack_mut()
+                    //     .expect("No user stack found"),
+                    &mut ustack_message,
+                )
                 .expect("Failed to push proc_init_info to user stack")
         };
         address_space.write().user_stack = Some(ustack_message);
 
-        // debug!("write proc_init_info to user stack done");
+        // kdebug!("write proc_init_info to user stack done");
 
         // (兼容旧版libc)把argv的指针写到寄存器内
         // TODO: 改写旧版libc,不再需要这个兼容
@@ -114,9 +116,9 @@ impl Syscall {
 
         drop(param);
 
-        // debug!("regs: {:?}\n", regs);
+        // kdebug!("regs: {:?}\n", regs);
 
-        // crate::debug!(
+        // crate::kdebug!(
         //     "tmp_rs_execve: done, load_result.entry_point()={:?}",
         //     load_result.entry_point()
         // );

+ 0 - 1
kernel/src/arch/x86_64/process/table.rs

@@ -59,7 +59,6 @@ impl TSSManager {
         x86::task::load_tr(selector);
     }
 
-    #[allow(static_mut_refs)]
     unsafe fn set_tss_descriptor(index: u16, vaddr: VirtAddr) {
         const LIMIT: u64 = 103;
         let gdt_vaddr = VirtAddr::new(&GDT_Table as *const _ as usize);

+ 3 - 4
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();
-    debug!("smp_ap_start_stage1: id: {}\n", id.data());
+    kdebug!("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());
     }
 
-    debug!("{s}: cpus: {v:?}\n");
+    kdebug!("{s}: cpus: {v:?}\n");
 }
 
 pub struct X86_64SMPArch;
@@ -259,7 +259,6 @@ impl X86_64SMPArch {
 }
 
 impl SmpCpuManager {
-    #[allow(static_mut_refs)]
     pub fn arch_init(_boot_cpu: ProcessorId) {
         assert!(smp_get_processor_id().data() == 0);
         // 写入APU_START_CR3,这个值会在AP处理器启动时设置到CR3寄存器

+ 3 - 4
kernel/src/arch/x86_64/syscall/mod.rs

@@ -11,7 +11,6 @@ use crate::{
     process::ProcessManager,
     syscall::{Syscall, SYS_SCHED},
 };
-use log::debug;
 use system_error::SystemError;
 
 use super::{
@@ -53,7 +52,7 @@ macro_rules! syscall_return {
 
         if $show {
             let pid = ProcessManager::current_pcb().pid();
-            debug!("syscall return:pid={:?},ret= {:?}\n", pid, ret as isize);
+            crate::kdebug!("syscall return:pid={:?},ret= {:?}\n", pid, ret as isize);
         }
 
         unsafe {
@@ -95,7 +94,7 @@ pub extern "sysv64" fn syscall_handler(frame: &mut TrapFrame) {
     // };
 
     if show {
-        debug!("syscall: pid: {:?}, num={:?}\n", pid, syscall_num);
+        crate::kdebug!("syscall: pid: {:?}, num={:?}\n", pid, syscall_num);
     }
 
     // Arch specific syscall
@@ -127,7 +126,7 @@ pub extern "sysv64" fn syscall_handler(frame: &mut TrapFrame) {
 
 /// 系统调用初始化
 pub fn arch_syscall_init() -> Result<(), SystemError> {
-    // info!("arch_syscall_init\n");
+    // kinfo!("arch_syscall_init\n");
     unsafe { set_system_trap_gate(0x80, 0, VirtAddr::new(syscall_int as usize)) }; // 系统调用门
     unsafe { init_syscall_64() };
     return Ok(());

+ 1 - 1
kernel/src/arch/x86_64/x86_64-unknown-none.json

@@ -1,6 +1,6 @@
 {
   "llvm-target": "x86_64-unknown-none",
-  "data-layout": "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128",
+  "data-layout": "e-m:e-i64:64-f80:128-n8:16:32:64-S128",
   "arch": "x86_64",
   "target-endian": "little",
   "target-pointer-width": "64",

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

@@ -1,10 +1,17 @@
 extern crate klog_types;
 
-use core::sync::atomic::{compiler_fence, Ordering};
+use core::{
+    intrinsics::unlikely,
+    sync::atomic::{compiler_fence, Ordering},
+};
 
 use klog_types::{AllocatorLog, AllocatorLogType, LogSource, MMLogChannel};
 
-use crate::{arch::CurrentTimeArch, process::Pid, time::TimeArch};
+use crate::{
+    arch::CurrentTimeArch,
+    process::{Pid, ProcessManager},
+    time::TimeArch,
+};
 
 /// 全局的内存分配器日志通道
 ///
@@ -24,14 +31,13 @@ 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) {
-    // todo: 由于目前底层的thingbuf存在卡死的问题,因此这里暂时注释掉。
-    // 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) {
+    let pid = if unlikely(!ProcessManager::initialized()) {
+        Some(Pid::new(0))
+    } else {
+        Some(ProcessManager::current_pcb().pid())
+    };
+    MMDebugLogManager::log(log_type, source, pid);
 }
 
 #[derive(Debug)]
@@ -48,7 +54,6 @@ 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(

+ 0 - 2
kernel/src/driver/acpi/bus.rs

@@ -111,7 +111,6 @@ impl Bus for AcpiBus {
 ///
 ///
 /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/include/acpi/acpi_bus.h#364
-#[allow(unused)]
 pub trait AcpiDevice: Device {}
 
 /// Acpi驱动应当实现的trait
@@ -121,5 +120,4 @@ pub trait AcpiDevice: Device {}
 /// todo: 仿照linux的acpi_driver去设计这个trait
 ///
 /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/include/acpi/acpi_bus.h#163
-#[allow(unused)]
 pub trait AcpiDriver: Driver {}

+ 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> {
-        info!("Initializing Acpi Manager...");
+        kinfo!("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()?;
-        info!("Acpi Manager initialized.");
+        kinfo!("Acpi Manager initialized.");
         return Ok(());
     }
 
@@ -95,7 +95,7 @@ impl AcpiManager {
             }
             // 如果rsdpv1和rsdpv2都无法获取到acpi_table,说明有问题,打印报错信息后进入死循环
             Err(e2) => {
-                error!("acpi_init(): failed to parse acpi tables, error: (rsdpv1: {:?}) or (rsdpv2: {:?})", e1, e2);
+                kerror!("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 {
-            error!(
+            kerror!(
                 "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 = PMTMR_IO_PORT.load(Ordering::SeqCst);
+    let port = unsafe { PMTMR_IO_PORT.load(Ordering::SeqCst) };
 
     // 如果端口为零直接返回
     if port == 0 {

+ 6 - 6
kernel/src/driver/acpi/sysfs.rs

@@ -18,7 +18,6 @@ use alloc::{
     sync::Arc,
     vec::Vec,
 };
-use log::{debug, error, warn};
 use system_error::SystemError;
 
 use super::{acpi_kset, AcpiManager};
@@ -110,7 +109,7 @@ impl AcpiManager {
         let tables = self.tables().unwrap();
         let headers = tables.headers();
         for header in headers {
-            debug!("ACPI header: {:?}", header);
+            kdebug!("ACPI header: {:?}", header);
             let attr = AttrAcpiTable::new(&header)?;
             acpi_table_attr_list().write().push(attr);
             self.acpi_table_data_init(&header)?;
@@ -173,7 +172,7 @@ impl AttrAcpiTable {
         // 将当前实例的序号加1
         r.instance += 1;
         if r.instance > ACPI_MAX_TABLE_INSTANCES as isize {
-            warn!("too many table instances. name: {}", r.name);
+            kwarn!("too many table instances. name: {}", r.name);
             return Err(SystemError::ERANGE);
         }
 
@@ -290,9 +289,10 @@ impl BinAttribute for AttrAcpiTable {
             ($name: ident, $tables: expr) => {
                 define_struct!($name);
                 let table = $tables.find_entire_table::<$name>().map_err(|e| {
-                    warn!(
+                    kwarn!(
                         "AttrAcpiTable::read(): failed to find table. name: {}, error: {:?}",
-                        self.name, e
+                        self.name,
+                        e
                     );
                     SystemError::ENODEV
                 })?;
@@ -500,7 +500,7 @@ impl BinAttribute for AttrAcpiTable {
             }
 
             _ => {
-                error!("AttrAcpiTable::read(): unknown table. name: {}", self.name);
+                kerror!("AttrAcpiTable::read(): unknown table. name: {}", self.name);
                 return Err(SystemError::ENODEV);
             }
         };

+ 16 - 14
kernel/src/driver/base/block/block_device.rs

@@ -1,21 +1,23 @@
 /// 引入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},
     },
-    block::cache::{cached_block_device::BlockCache, BlockCacheError, BLOCK_SIZE},
+    kerror,
 };
 
 use alloc::{sync::Arc, vec::Vec};
 use core::any::Any;
-use log::error;
 use system_error::SystemError;
 
 use super::disk_info::Partition;
@@ -473,7 +475,7 @@ impl BlockDeviceOps {
         let mut major = device_number.major();
         let baseminor = device_number.minor();
         if major >= DEV_MAJOR_MAX {
-            error!(
+            kerror!(
                 "DEV {} major requested {:?} is greater than the maximum {}\n",
                 name,
                 major,
@@ -481,7 +483,7 @@ impl BlockDeviceOps {
             );
         }
         if minorct > DeviceNumber::MINOR_MASK + 1 - baseminor {
-            error!("DEV {} minor range requested ({}-{}) is out of range of maximum range ({}-{}) for a single major\n",
+            kerror!("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);
@@ -547,7 +549,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 {
-            error!("Device number can't be 0!\n");
+            kerror!("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 {
-            error!(
+            kerror!(
                 "DEV {} major requested {:?} is greater than the maximum {}\n",
                 name,
                 major,
@@ -137,7 +137,7 @@ impl CharDevOps {
             );
         }
         if minorct > DeviceNumber::MINOR_MASK + 1 - baseminor {
-            error!("DEV {} minor range requested ({}-{}) is out of range of maximum range ({}-{}) for a single major\n",
+            kerror!("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 {
-            error!("Device number can't be 0!\n");
+            kerror!("Device number can't be 0!\n");
         }
         device_manager().add_device(cdev.clone())?;
         kobj_map(

+ 8 - 8
kernel/src/driver/base/device/bus.rs

@@ -25,7 +25,6 @@ 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
@@ -297,7 +296,7 @@ impl BusManager {
             .bus()
             .and_then(|bus| bus.upgrade())
             .ok_or(SystemError::EINVAL)?;
-        debug!("bus '{}' add driver '{}'", bus.name(), driver.name());
+        kdebug!("bus '{}' add driver '{}'", bus.name(), driver.name());
 
         driver.set_kobj_type(Some(&BusDriverKType));
         let kobj = driver.clone() as Arc<dyn KObject>;
@@ -315,7 +314,7 @@ impl BusManager {
         driver_manager()
             .add_groups(driver, bus.drv_groups())
             .map_err(|e| {
-                error!(
+                kerror!(
                     "BusManager::add_driver: driver '{:?}' add_groups failed, err: '{:?}",
                     driver.name(),
                     e
@@ -327,7 +326,7 @@ impl BusManager {
         if !driver.suppress_bind_attrs() {
             self.add_bind_files(driver)
                 .map_err(|e| {
-                    error!(
+                    kerror!(
                         "BusManager::add_driver: driver '{:?}' add_bind_files failed, err: '{:?}",
                         driver.name(),
                         e
@@ -478,8 +477,9 @@ impl BusManager {
 
         driver_manager()
             .create_attr_file(driver, &DriverAttrBind)
-            .inspect_err(|_e| {
+            .map_err(|e| {
                 driver_manager().remove_attr_file(driver, &DriverAttrUnbind);
+                e
             })?;
 
         return Ok(());
@@ -580,7 +580,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>) {
-    info!("bus_probe_device: dev: {:?}", dev.name());
+    kinfo!("bus_probe_device: dev: {:?}", dev.name());
     bus_manager().probe_device(dev);
 }
 
@@ -746,7 +746,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| {
-            error!(
+            kerror!(
                 "Intertrait casting not implemented for kobj: {}",
                 kobj.name()
             );
@@ -795,7 +795,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| {
-            error!(
+            kerror!(
                 "Intertrait casting not implemented for kobj: {}",
                 kobj.name()
             );

+ 21 - 21
kernel/src/driver/base/device/dd.rs

@@ -2,7 +2,6 @@ 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,
@@ -60,20 +59,20 @@ impl DeviceManager {
     ) -> Result<bool, SystemError> {
         if unlikely(allow_async) {
             // todo!("do_device_attach: allow_async")
-            warn!("do_device_attach: allow_async is true, but currently not supported");
+            kwarn!("do_device_attach: allow_async is true, but currently not supported");
         }
         if dev.is_dead() {
             return Ok(false);
         }
 
-        warn!("do_device_attach: dev: '{}'", dev.name());
+        kwarn!("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) {
-                debug!(
+                kdebug!(
                     "do_device_attach: device '{}' is already bound.",
                     dev.name()
                 );
@@ -87,7 +86,7 @@ impl DeviceManager {
                 return Ok(false);
             }
         } else {
-            debug!("do_device_attach: device '{}' is not bound.", dev.name());
+            kdebug!("do_device_attach: device '{}' is not bound.", dev.name());
             let bus = dev
                 .bus()
                 .and_then(|bus| bus.upgrade())
@@ -117,7 +116,7 @@ impl DeviceManager {
                 // try them.
 
                 do_async = true;
-                debug!(
+                kdebug!(
                     "do_device_attach: try scheduling asynchronous probe for device: {}",
                     dev.name()
                 );
@@ -142,7 +141,6 @@ impl DeviceManager {
     /// - Ok(true): 匹配成功
     /// - Ok(false): 没有匹配成功
     /// - Err(SystemError): 匹配过程中出现意外错误,没有匹配成功
-    ///
     /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/base/dd.c#899
     fn do_device_attach_driver(
         &self,
@@ -155,7 +153,7 @@ impl DeviceManager {
             if let Err(e) = r {
                 // 如果不是ENOSYS,则总线出错
                 if e != SystemError::ENOSYS {
-                    debug!(
+                    kdebug!(
                         "do_device_attach_driver: bus.match_device() failed, dev: '{}', err: {:?}",
                         data.dev.name(),
                         e
@@ -217,7 +215,7 @@ impl DeviceManager {
         }
 
         if let Err(e) = r.as_ref() {
-            error!(
+            kerror!(
                 "device_bind_driver: driver_sysfs_add failed, dev: '{}', err: {:?}",
                 dev.name(),
                 e
@@ -403,7 +401,7 @@ impl DriverManager {
         device.set_driver(Some(Arc::downgrade(driver)));
 
         self.add_to_sysfs(device).map_err(|e| {
-            error!(
+            kerror!(
                 "really_probe: add_to_sysfs failed, dev: '{}', err: {:?}",
                 device.name(),
                 e
@@ -414,7 +412,7 @@ impl DriverManager {
         })?;
 
         self.call_driver_probe(device, driver).map_err(|e| {
-            error!(
+            kerror!(
                 "really_probe: call_driver_probe failed, dev: '{}', err: {:?}",
                 device.name(),
                 e
@@ -429,7 +427,7 @@ impl DriverManager {
         device_manager()
             .add_groups(device, driver.dev_groups())
             .map_err(|e| {
-                error!(
+                kerror!(
                     "really_probe: add_groups failed, dev: '{}', err: {:?}",
                     device.name(),
                     e
@@ -445,7 +443,7 @@ impl DriverManager {
         device_manager()
             .create_file(device, &DeviceAttrStateSynced)
             .map_err(|e| {
-                error!(
+                kerror!(
                     "really_probe: create_file failed, dev: '{}', err: {:?}",
                     device.name(),
                     e
@@ -485,15 +483,17 @@ impl DriverManager {
 
         sysfs_instance()
             .create_link(Some(&device_kobj), &driver_kobj, "driver".to_string())
-            .inspect_err(|_e| {
+            .map_err(|e| {
                 fail_rm_dev_link();
+                e
             })?;
 
         device_manager()
             .create_file(device, &DeviceAttrCoredump)
-            .inspect_err(|_e| {
+            .map_err(|e| {
                 sysfs_instance().remove_link(&device_kobj, "driver".to_string());
                 fail_rm_dev_link();
+                e
             })?;
 
         return Ok(());
@@ -515,7 +515,7 @@ impl DriverManager {
             .ok_or(SystemError::EINVAL)?;
         let r = bus.probe(device);
         if r == Err(SystemError::ENOSYS) {
-            error!(
+            kerror!(
                 "call_driver_probe: bus.probe() failed, dev: '{}', err: {:?}",
                 device.name(),
                 r
@@ -530,7 +530,7 @@ impl DriverManager {
         let err = r.unwrap_err();
         match err {
             SystemError::ENODEV | SystemError::ENXIO => {
-                debug!(
+                kdebug!(
                     "driver'{}': probe of {} rejects match {:?}",
                     driver.name(),
                     device.name(),
@@ -539,7 +539,7 @@ impl DriverManager {
             }
 
             _ => {
-                warn!(
+                kwarn!(
                     "driver'{}': probe of {} failed with error {:?}",
                     driver.name(),
                     device.name(),
@@ -555,7 +555,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) {
-            warn!("driver_bound: device '{}' is already bound.", device.name());
+            kwarn!("driver_bound: device '{}' is already bound.", device.name());
             return;
         }
 
@@ -600,7 +600,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| {
-            error!(
+            kerror!(
                 "Intertrait casting not implemented for kobj: {}",
                 kobj.name()
             );
@@ -635,7 +635,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| {
-            error!(
+            kerror!(
                 "Intertrait casting not implemented for kobj: {}",
                 kobj.name()
             );

+ 6 - 7
kernel/src/driver/base/device/driver.rs

@@ -15,7 +15,6 @@ use alloc::{
     vec::Vec,
 };
 use core::fmt::Debug;
-use log::error;
 use system_error::SystemError;
 
 /// @brief: Driver error
@@ -194,7 +193,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(|| {
-            error!(
+            kerror!(
                 "DriverManager::register() failed: driver.bus() is None. Driver: '{:?}'",
                 driver.name()
             );
@@ -204,7 +203,7 @@ impl DriverManager {
         let drv_name = driver.name();
         let other = bus.find_driver_by_name(&drv_name);
         if other.is_some() {
-            error!(
+            kerror!(
                 "DriverManager::register() failed: driver '{}' already registered",
                 drv_name
             );
@@ -213,10 +212,10 @@ impl DriverManager {
 
         bus_manager().add_driver(&driver)?;
 
-        self.add_groups(&driver, driver.groups())
-            .inspect_err(|_e| {
-                bus_manager().remove_driver(&driver);
-            })?;
+        self.add_groups(&driver, driver.groups()).map_err(|e| {
+            bus_manager().remove_driver(&driver);
+            e
+        })?;
 
         // todo: 发送uevent
 

+ 13 - 10
kernel/src/driver/base/device/init.rs

@@ -1,13 +1,16 @@
 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,
+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,
     },
-    kobject::KObject,
-    kset::KSet,
+    kinfo,
 };
 
 use system_error::SystemError;
@@ -51,7 +54,7 @@ pub fn devices_init() -> Result<(), SystemError> {
 
     // 创建 `/sys/dev/block` 目录
     {
-        // debug!("create /sys/dev/block");
+        // kdebug!("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>;
@@ -66,7 +69,7 @@ pub fn devices_init() -> Result<(), SystemError> {
 
     // 创建 `/sys/dev/char` 目录
     {
-        // debug!("create /sys/dev/char");
+        // kdebug!("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>;
@@ -79,7 +82,7 @@ pub fn devices_init() -> Result<(), SystemError> {
         unsafe { set_sys_dev_char_kset(dev_char_kset) };
     }
 
-    info!("devices init success");
+    kinfo!("devices init success");
 
     return Ok(());
 }

+ 18 - 16
kernel/src/driver/base/device/mod.rs

@@ -3,7 +3,6 @@ use alloc::{
     sync::{Arc, Weak},
 };
 use intertrait::cast::CastArc;
-use log::{error, warn};
 
 use crate::{
     driver::{
@@ -76,7 +75,7 @@ static mut DEVICES_VIRTUAL_KSET_INSTANCE: Option<Arc<KSet>> = None;
 
 /// 获取`/sys/devices`的kset实例
 #[inline(always)]
-pub fn sys_devices_kset() -> Arc<KSet> {
+pub(super) fn sys_devices_kset() -> Arc<KSet> {
     unsafe { DEVICES_KSET_INSTANCE.as_ref().unwrap().clone() }
 }
 
@@ -140,7 +139,7 @@ pub trait Device: KObject {
     /// 设备释放时的回调函数
     fn release(&self) {
         let name = self.name();
-        warn!(
+        kwarn!(
             "device {} does not have a release() function, it is broken and must be fixed.",
             name
         );
@@ -288,7 +287,6 @@ pub enum DeviceType {
     Intc,
     PlatformDev,
     Char,
-    Pci,
 }
 
 /// @brief: 设备标识符类型
@@ -483,7 +481,7 @@ impl DeviceManager {
 
         let actual_parent = self.get_device_parent(&device, current_parent)?;
         if let Some(actual_parent) = actual_parent {
-            // debug!(
+            // kdebug!(
             //     "device '{}' parent is '{}', strong_count: {}",
             //     device.name().to_string(),
             //     actual_parent.name(),
@@ -493,7 +491,7 @@ impl DeviceManager {
         }
 
         KObjectManager::add_kobj(device.clone() as Arc<dyn KObject>, None).map_err(|e| {
-            error!("add device '{:?}' failed: {:?}", device.name(), e);
+            kerror!("add device '{:?}' failed: {:?}", device.name(), e);
             e
         })?;
 
@@ -553,10 +551,10 @@ impl DeviceManager {
         device: &Arc<dyn Device>,
         current_parent: Option<Arc<dyn Device>>,
     ) -> Result<Option<Arc<dyn KObject>>, SystemError> {
-        // debug!("get_device_parent() device:{:?}", device.name());
+        // kdebug!("get_device_parent() device:{:?}", device.name());
         if device.class().is_some() {
             let parent_kobj: Arc<dyn KObject>;
-            // debug!("current_parent:{:?}", current_parent);
+            // kdebug!("current_parent:{:?}", current_parent);
             if let Some(cp) = current_parent {
                 if cp.class().is_some() {
                     return Ok(Some(cp.clone() as Arc<dyn KObject>));
@@ -646,16 +644,18 @@ impl DeviceManager {
             let parent_kobj = parent.clone() as Arc<dyn KObject>;
             sysfs_instance()
                 .create_link(Some(&dev_kobj), &parent_kobj, "device".to_string())
-                .inspect_err(|_e| {
+                .map_err(|e| {
                     err_remove_subsystem(&dev_kobj);
+                    e
                 })?;
         }
 
         sysfs_instance()
             .create_link(Some(&subsys_kobj), &dev_kobj, dev.name())
-            .inspect_err(|_e| {
+            .map_err(|e| {
                 err_remove_device(&dev_kobj);
                 err_remove_subsystem(&dev_kobj);
+                e
             })?;
 
         return Ok(());
@@ -693,16 +693,18 @@ impl DeviceManager {
         // 添加kobj_type的属性文件
         if let Some(kobj_type) = dev.kobj_type() {
             self.add_groups(dev, kobj_type.attribute_groups().unwrap_or(&[]))
-                .inspect_err(|_e| {
+                .map_err(|e| {
                     err_remove_class_groups(dev);
+                    e
                 })?;
         }
 
         // 添加设备本身的属性文件
         self.add_groups(dev, dev.attribute_groups().unwrap_or(&[]))
-            .inspect_err(|_e| {
+            .map_err(|e| {
                 err_remove_kobj_type_groups(dev);
                 err_remove_class_groups(dev);
+                e
             })?;
 
         return Ok(());
@@ -753,7 +755,7 @@ impl DeviceManager {
             attr.mode().contains(ModeType::S_IRUGO)
                 && (!attr.support().contains(SysFSOpsSupport::ATTR_SHOW)),
         ) {
-            warn!(
+            kwarn!(
                 "Attribute '{}': read permission without 'show'",
                 attr.name()
             );
@@ -762,7 +764,7 @@ impl DeviceManager {
             attr.mode().contains(ModeType::S_IWUGO)
                 && (!attr.support().contains(SysFSOpsSupport::ATTR_STORE)),
         ) {
-            warn!(
+            kwarn!(
                 "Attribute '{}': write permission without 'store'",
                 attr.name()
             );
@@ -804,7 +806,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>) {
-        warn!("device_links_force_bind not implemented");
+        kwarn!("device_links_force_bind not implemented");
     }
 
     /// 把device对象的一些结构进行默认初始化
@@ -869,7 +871,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| {
-            error!(
+            kerror!(
                 "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 {
-                error!("KObjectManager::add_kobj() failed with error: {e:?}, kobj:{kobj:?}");
+                kerror!("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>) {
-        debug!("DynamicKObjKType::release() kobj:{:?}", kobj.name());
+        kdebug!("DynamicKObjKType::release() kobj:{:?}", kobj.name());
     }
 
     fn sysfs_ops(&self) -> Option<&dyn SysFSOps> {

+ 0 - 1
kernel/src/driver/base/platform/platform_device.rs

@@ -64,7 +64,6 @@ pub trait PlatformDevice: Device {
     /// @brief: 判断设备是否初始化
     /// @parameter: None
     /// @return: 如果已经初始化,返回true,否则,返回false
-    #[allow(dead_code)]
     fn is_initialized(&self) -> bool;
 
     /// @brief: 设置设备状态

+ 0 - 1
kernel/src/driver/base/platform/platform_driver.rs

@@ -16,7 +16,6 @@ use super::{platform_bus, platform_device::PlatformDevice};
 ///
 /// 应当在所有实现这个trait的结构体上方,添加 `#[cast_to([sync] PlatformDriver)]`,
 /// 否则运行时将报错“该对象不是PlatformDriver”
-#[allow(dead_code)]
 pub trait PlatformDriver: Driver {
     /// 检测设备是否能绑定到这个驱动
     ///

+ 2 - 3
kernel/src/driver/base/platform/subsys.rs

@@ -3,7 +3,6 @@ use alloc::{
     sync::{Arc, Weak},
 };
 use intertrait::cast::CastArc;
-use log::error;
 
 use super::{platform_device::PlatformDevice, platform_driver::PlatformDriver};
 use crate::{
@@ -59,12 +58,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(|_|{
-            error!("PlatformBus::probe() failed: device.driver() is not a PlatformDriver. Device: '{:?}'", device.name());
+            kerror!("PlatformBus::probe() failed: device.driver() is not a PlatformDriver. Device: '{:?}'", device.name());
             SystemError::EINVAL
         })?;
 
         let pdev = device.clone().cast::<dyn PlatformDevice>().map_err(|_| {
-            error!(
+            kerror!(
                 "PlatformBus::probe() failed: device is not a PlatformDevice. Device: '{:?}'",
                 device.name()
             );

+ 1 - 4
kernel/src/driver/block/cache/cached_block_device.rs

@@ -1,6 +1,5 @@
 use alloc::{boxed::Box, vec::Vec};
 use hashbrown::HashMap;
-use log::debug;
 
 use crate::{driver::base::block::block_device::BlockId, libs::rwlock::RwLock};
 
@@ -16,7 +15,6 @@ static mut CMAPPER: Option<LockedCacheMapper> = None;
 /// 该结构体向外提供BlockCache服务
 pub struct BlockCache;
 
-#[allow(static_mut_refs)]
 unsafe fn mapper() -> Result<&'static mut LockedCacheMapper, BlockCacheError> {
     unsafe {
         match &mut CMAPPER {
@@ -26,7 +24,6 @@ unsafe fn mapper() -> Result<&'static mut LockedCacheMapper, BlockCacheError> {
     };
 }
 
-#[allow(static_mut_refs)]
 unsafe fn space() -> Result<&'static mut LockedCacheSpace, BlockCacheError> {
     unsafe {
         match &mut CSPACE {
@@ -44,7 +41,7 @@ impl BlockCache {
             CSPACE = Some(LockedCacheSpace::new(CacheSpace::new()));
             CMAPPER = Some(LockedCacheMapper::new(CacheMapper::new()));
         }
-        debug!("BlockCache Initialized!");
+        kdebug!("BlockCache Initialized!");
     }
     /// # 函数的功能
     /// 使用blockcache进行对块设备进行连续块的读操作

+ 6 - 6
kernel/src/driver/block/virtio_blk.rs

@@ -5,7 +5,6 @@ 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;
@@ -64,7 +63,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 {
-        debug!("VirtIOBlkDevice '{:?}' created", device.dev_id);
+        kdebug!("VirtIOBlkDevice '{:?}' created", device.dev_id);
         virtio_device_manager()
             .device_add(device.clone() as Arc<dyn VirtIODevice>)
             .expect("Add virtio blk failed");
@@ -90,7 +89,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 {
-            error!("VirtIOBlkDevice '{dev_id:?}' create failed: {:?}", e);
+            kerror!("VirtIOBlkDevice '{dev_id:?}' create failed: {:?}", e);
             return None;
         }
 
@@ -135,9 +134,10 @@ impl BlockDevice for VirtIOBlkDevice {
             .device_inner
             .read_blocks(lba_id_start, &mut buf[..count * LBA_SIZE])
             .map_err(|e| {
-                error!(
+                kerror!(
                     "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(|_| {
-                error!(
+                kerror!(
                 "VirtIOBlkDriver::probe() failed: device is not a VirtIO block device. Device: '{:?}'",
                 device.name()
             );

Some files were not shown because too many files changed in this diff