Browse Source

Merge pull request #965 from MemoryShore/feat-dynamic-link

feat: 初步支持动态链接程序运行
Chiichen 5 months ago
parent
commit
5b912a43b8
100 changed files with 1632 additions and 423 deletions
  1. 12 9
      .github/workflows/cache-toolchain.yml
  2. 2 2
      .github/workflows/makefile.yml
  3. 2 2
      Makefile
  4. 20 56
      README.md
  5. 21 59
      README_EN.md
  6. 1 1
      build-scripts/.gitignore
  7. 2 0
      build-scripts/Makefile
  8. 0 2
      build-scripts/kernel_build/src/lib.rs
  9. 1062 0
      docs/community/ChangeLog/V0.1.x/V0.1.10.md
  10. 1 0
      docs/community/ChangeLog/index.rst
  11. 11 4
      docs/conf.py
  12. 1 0
      docs/introduction/build_system.md
  13. 2 2
      docs/kernel/locking/mutex.md
  14. 2 2
      docs/kernel/locking/spinlock.md
  15. 17 13
      docs/kernel/sched/cfs.md
  16. 59 8
      docs/kernel/sched/core.md
  17. 4 0
      kernel/.cargo/config.toml
  18. 14 10
      kernel/Cargo.toml
  19. 5 5
      kernel/Makefile
  20. 1 0
      kernel/crates/bitmap/src/lib.rs
  21. 9 0
      kernel/crates/bitmap/src/static_bitmap.rs
  22. 0 5
      kernel/crates/bitmap/src/traits.rs
  23. 0 0
      kernel/crates/intertrait/.gitignore
  24. 1 1
      kernel/crates/intertrait/Cargo.toml
  25. 0 0
      kernel/crates/intertrait/LICENSE-MIT
  26. 1 1
      kernel/crates/intertrait/README.md
  27. 1 1
      kernel/crates/intertrait/macros/Cargo.toml
  28. 0 0
      kernel/crates/intertrait/macros/LICENSE-APACHE
  29. 0 0
      kernel/crates/intertrait/macros/LICENSE-MIT
  30. 0 0
      kernel/crates/intertrait/macros/src/args.rs
  31. 0 0
      kernel/crates/intertrait/macros/src/gen_caster.rs
  32. 0 0
      kernel/crates/intertrait/macros/src/item_impl.rs
  33. 0 0
      kernel/crates/intertrait/macros/src/item_type.rs
  34. 0 0
      kernel/crates/intertrait/macros/src/lib.rs
  35. 0 0
      kernel/crates/intertrait/src/cast.rs
  36. 0 0
      kernel/crates/intertrait/src/cast/cast_arc.rs
  37. 0 0
      kernel/crates/intertrait/src/cast/cast_box.rs
  38. 0 0
      kernel/crates/intertrait/src/cast/cast_mut.rs
  39. 0 0
      kernel/crates/intertrait/src/cast/cast_rc.rs
  40. 0 0
      kernel/crates/intertrait/src/cast/cast_ref.rs
  41. 0 0
      kernel/crates/intertrait/src/hasher.rs
  42. 0 0
      kernel/crates/intertrait/src/lib.rs
  43. 0 0
      kernel/crates/intertrait/tests/castable_to.rs
  44. 0 0
      kernel/crates/intertrait/tests/on-enum.rs
  45. 0 0
      kernel/crates/intertrait/tests/on-struct.rs
  46. 0 0
      kernel/crates/intertrait/tests/on-trait-impl-assoc-type1.rs
  47. 0 0
      kernel/crates/intertrait/tests/on-trait-impl-assoc-type2.rs
  48. 0 0
      kernel/crates/intertrait/tests/on-trait-impl-assoc-type3.rs
  49. 0 0
      kernel/crates/intertrait/tests/on-trait-impl.rs
  50. 0 0
      kernel/crates/intertrait/tests/on-type-multi-traits.rs
  51. 0 0
      kernel/crates/intertrait/tests/run.rs
  52. 0 0
      kernel/crates/intertrait/tests/ui/duplicate-flags.rs
  53. 0 0
      kernel/crates/intertrait/tests/ui/duplicate-flags.stderr
  54. 0 0
      kernel/crates/intertrait/tests/ui/on-generic-type.rs
  55. 0 0
      kernel/crates/intertrait/tests/ui/on-generic-type.stderr
  56. 0 0
      kernel/crates/intertrait/tests/ui/on-type-impl.rs
  57. 0 0
      kernel/crates/intertrait/tests/ui/on-type-impl.stderr
  58. 0 0
      kernel/crates/intertrait/tests/ui/unknown-flag.rs
  59. 0 0
      kernel/crates/intertrait/tests/ui/unknown-flag.stderr
  60. 6 0
      kernel/crates/klog_types/src/lib.rs
  61. 5 3
      kernel/crates/rust-slabmalloc/src/pages.rs
  62. 1 1
      kernel/crates/unified-init/Cargo.toml
  63. 1 1
      kernel/crates/unified-init/macros/Cargo.toml
  64. 1 1
      kernel/crates/unified-init/src/lib.rs
  65. 7 0
      kernel/crates/wait_queue_macros/Cargo.toml
  66. 60 0
      kernel/crates/wait_queue_macros/src/lib.rs
  67. 3 0
      kernel/env.mk
  68. 1 1
      kernel/rust-toolchain.toml
  69. 2 2
      kernel/src/Makefile
  70. 1 0
      kernel/src/arch/io.rs
  71. 2 2
      kernel/src/arch/riscv64/driver/of.rs
  72. 5 6
      kernel/src/arch/riscv64/init/mod.rs
  73. 18 22
      kernel/src/arch/riscv64/interrupt/handle.rs
  74. 7 6
      kernel/src/arch/riscv64/ipc/signal.rs
  75. 12 12
      kernel/src/arch/riscv64/mm/init.rs
  76. 70 4
      kernel/src/arch/riscv64/mm/mod.rs
  77. 4 5
      kernel/src/arch/riscv64/pci/pci_host_ecam.rs
  78. 5 3
      kernel/src/arch/riscv64/process/idle.rs
  79. 5 5
      kernel/src/arch/riscv64/process/mod.rs
  80. 11 17
      kernel/src/arch/riscv64/process/syscall.rs
  81. 6 8
      kernel/src/arch/riscv64/smp/mod.rs
  82. 2 2
      kernel/src/arch/riscv64/syscall/mod.rs
  83. 5 4
      kernel/src/arch/riscv64/time.rs
  84. 3 2
      kernel/src/arch/x86_64/acpi.rs
  85. 13 13
      kernel/src/arch/x86_64/driver/apic/apic_timer.rs
  86. 7 7
      kernel/src/arch/x86_64/driver/apic/ioapic.rs
  87. 4 3
      kernel/src/arch/x86_64/driver/apic/lapic_vector.rs
  88. 7 7
      kernel/src/arch/x86_64/driver/apic/mod.rs
  89. 5 6
      kernel/src/arch/x86_64/driver/apic/x2apic.rs
  90. 7 6
      kernel/src/arch/x86_64/driver/apic/xapic.rs
  91. 8 14
      kernel/src/arch/x86_64/driver/hpet.rs
  92. 2 2
      kernel/src/arch/x86_64/driver/rtc.rs
  93. 19 19
      kernel/src/arch/x86_64/driver/tsc.rs
  94. 7 6
      kernel/src/arch/x86_64/init/mod.rs
  95. 1 0
      kernel/src/arch/x86_64/interrupt/entry.rs
  96. 5 5
      kernel/src/arch/x86_64/interrupt/ipi.rs
  97. 8 2
      kernel/src/arch/x86_64/interrupt/mod.rs
  98. 1 0
      kernel/src/arch/x86_64/interrupt/msi.rs
  99. 23 23
      kernel/src/arch/x86_64/interrupt/trap.rs
  100. 21 20
      kernel/src/arch/x86_64/ipc/signal.rs

+ 12 - 9
.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-2023-01-21-x86_64-unknown-linux-gnu
+            rustup toolchain install nightly-2024-07-23-x86_64-unknown-linux-gnu
             rustup toolchain install nightly-2023-08-15-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-2024-07-23-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-2023-01-21-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-08-15-x86_64-unknown-linux-gnu
 
-            rustup toolchain install nightly-2023-01-21-riscv64gc-unknown-linux-gnu --force-non-host
+            rustup toolchain install nightly-2024-07-23-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-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-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-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-2023-01-21-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-08-15-x86_64-unknown-linux-gnu
-            rustup component add rustfmt --toolchain nightly-2023-01-21-riscv64gc-unknown-linux-gnu
+            rustup component add rustfmt --toolchain nightly-2024-07-23-riscv64gc-unknown-linux-gnu
             rustup component add rustfmt --toolchain nightly-2023-08-15-riscv64gc-unknown-linux-gnu
 
-            rustup default nightly
+            rustup default nightly-2024-07-23
 
             cargo install dadk --version 0.1.11
           
@@ -86,6 +86,9 @@ 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" ]
+    branches: [ "master", "feat-*", "fix-*"]
   pull_request:
-    branches: [ "master" ]
+    branches: [ "master", "feat-*", "fix-*"]
 
 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
+	@git submodule update --recursive --init
 	@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
+	@$(MAKE) update-submodules --init
 	@git config --global --unset url."https://git.mirrors.dragonos.org.cn/DragonOS-Community/".insteadOf
 
 help:

+ 20 - 56
README.md

@@ -26,25 +26,25 @@
   DragonOS目前在社区驱动下正在快速发展中,目前DragonOS已经实现了约1/4的Linux接口,在未来我们将提供对Linux的100%兼容性,并且提供新特性。
 
 
-[关于DragonOS,你想了解的都在这儿 - DragonOS](https://dragonos.org/?p=46)
+## 参与开发?
 
-## 网站
+仔细阅读 [DragonOS社区介绍文档] ,能够帮助你了解社区的运作方式,以及如何参与贡献!
 
-- 项目官网  **[DragonOS.org](https://dragonos.org)**
+- **了解开发动态、开发任务,请访问DragonOS社区论坛**: [https://bbs.dragonos.org.cn](https://bbs.dragonos.org.cn)
+- 您也可以从项目的issue里面了解相关的开发内容。
 
-- 项目文档  **[docs.DragonOS.org](https://docs.dragonos.org)**
 
-- **了解开发动态、开发任务,请访问DragonOS社区论坛**: [https://bbs.dragonos.org.cn](https://bbs.dragonos.org.cn)
+  如果你愿意加入我们,你可以查看issue,并在issue下发表讨论、想法,或者访问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创造一些新的功能。
 
-- 开发交流QQ群 **115763565**
+## 网站
+
+
+- 项目官网  **[DragonOS.org](https://dragonos.org)**
+- 文档:**[docs.dragonos.org](https://docs.dragonos.org)**
+- 社区介绍文档: **[community.dragonos.org](https://community.dragonos.org)**
 
-- 代码搜索引擎 [code.DragonOS.org](http://code.dragonos.org)
-  
-   
 
 ## 如何运行?
 
@@ -52,34 +52,20 @@
 
 - [构建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创造一些新的功能。
 
 ## 如何与社区建立联系?
 
-  你可以发邮件给Maintainer: longjin,邮件地址是 [[email protected]](mailto:[email protected]) 。
-
-  或者是加入我们的开发交流QQ群:**115763565**
-
-  对于正式问题的讨论,请在 **[https://bbs.dragonos.org.cn](https://bbs.dragonos.org.cn)** 上的对应板块,使用正式的语言发帖讨论。亦或者是在本仓库的issue下提出问题。
+请阅读[贡献者指南](https://community.dragonos.org/contributors/#%E7%A4%BE%E5%8C%BA)~
 
+- 您可以通过[社区管理团队]信息,与各委员会的成员们建立联系~
+- 同时,您可以通过[SIGs]和[WGs]页面,找到对应的社区团体负责人的联系方式~
 
 ## 贡献者名单
 
 [Contributors to DragonOS-Community/DragonOS · GitHub](https://github.com/DragonOS-Community/DragonOS/graphs/contributors)
 
-## 联系我们
 
-社区对外联系邮箱:[email protected]
-
-社区负责人邮箱:[email protected]
 
 ## 赞助
 
@@ -134,32 +120,10 @@
 
 **我们谴责**:任何不遵守开源协议的行为。包括但不限于:剽窃该项目的代码作为你的毕业设计等学术不端行为以及商业闭源使用而不付费。
 
-若您发现了任何违背开源协议的使用行为,我们欢迎您发邮件反馈!让我们共同建设诚信的开源社区。
-
-## 参考资料
-
-  本项目参考了以下资料,我对这些项目、书籍、文档的作者表示感谢!
-
-- 《一个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)
+若您发现了任何违背开源协议的使用行为,我们欢迎您发邮件到 [email protected] 反馈!让我们共同建设诚信的开源社区。
 
-- [redox-os](https://gitlab.redox-os.org/redox-os/redox)
 
-- [rcore](https://github.com/rcore-os/rCore)
+[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/

+ 21 - 59
README_EN.md

@@ -25,52 +25,37 @@
 
   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)
 
-## Websites
+## Get Involved in Development?
 
-- 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) 
+Carefully read the [DragonOS Community Introduction Document] to understand how the community operates and how you can contribute!
 
-## How to run?
+- **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.
 
-  The steps to run DragonOS are very simple. You can refer to the following information to run DragonOS within 15 minutes at the fastest!
+  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)
 
-- [Building DragonOS - DragonOS dev document](https://docs.dragonos.org/zh_CN/latest/introduction/build_system.html)
+  You're also welcome to bring your creative ideas and discuss them with the community members, working together to create new features for DragonOS.
 
-## DragonOS' Features
 
-  See documentation:[Features](https://docs.dragonos.org/zh_CN/latest/introduction/features.html)
+## Website
 
-## How to join DragonOS ?
+- **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)
 
-  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)
+## How to Run?
 
-  Or, you can also bring your ideas, discuss with community members, and create some new functions for DragonOS.
+  Running DragonOS is quite straightforward. You can refer to the following resources and get DragonOS up and running in as little as 15 minutes!
 
-## How to contact the community?
+- [Building DragonOS — DragonOS Development Documentation](https://docs.dragonos.org/zh_CN/latest/introduction/build_system.html)
 
-  You can send an email to the project's maintainer: longjin. His email address is [[email protected]](mailto: [email protected]) .
+## How to Connect with the Community?
 
-  Or join our development exchange QQ group: **115763565**
+Please read the [Contributor Guide](https://community.dragonos.org/contributors/#%E7%A4%BE%E5%8C%BA)~
 
-  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]
+- 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.
 
 
 ## Reward
@@ -128,30 +113,7 @@ 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!
 
-## 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)
+[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/

+ 1 - 1
build-scripts/.gitignore

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

+ 2 - 0
build-scripts/Makefile

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

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

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

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

@@ -0,0 +1,1062 @@
+# 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文件
+
+```

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

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

+ 11 - 4
docs/conf.py

@@ -10,15 +10,14 @@
 # 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-2023, DragonOS Community'
+copyright = '2022-2024, DragonOS Community'
 author = 'longjin'
 
 # The full version, including alpha/beta/rc tags
@@ -73,4 +72,12 @@ 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

+ 1 - 0
docs/introduction/build_system.md

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

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

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

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

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

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

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

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

@@ -1,14 +1,65 @@
 # 进程调度器相关的api
 
-&emsp;&emsp; 定义了DragonOS的进程调度相关的api,是系统进行进程调度的接口。同时也抽象出了Scheduler的trait,以供具体的调度器实现 
+&emsp;&emsp; 定义了DragonOS的进程调度相关的api,是系统进行进程调度的接口。同时也抽象出了Scheduler的trait,以供具体的调度器实现
 
-## 1. 调度器介绍
+## 调度器介绍
 
 &emsp;&emsp; 一般来说,一个系统会同时处理多个请求,但是其资源是优先的,调度就是用来协调每个请求对资源的使用的方法。
 
-### 1.1 主要函数
-1. cpu_executing(): 获取指定的cpu上正在执行的进程的pcb
-2. sched_enqueue(): 将进程加入调度队列
-3. sched_init(): 初始化进程调度器模块
-4. sched_update_jiffies(): 当时钟中断到达时,更新时间片。*请注意,该函数只能被时钟中断处理程序调用*
-5. sys_sched(): 让系统立即运行调度器的系统调用。*请注意,该系统调用不能由ring3的程序发起*
+## 整体架构
+&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``进行调度。
+

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

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

+ 14 - 10
kernel/Cargo.toml

@@ -1,6 +1,6 @@
 [package]
 name = "dragonos_kernel"
-version = "0.1.9"
+version = "0.1.10"
 edition = "2021"
 
 # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -12,16 +12,18 @@ crate-type = ["staticlib"]
 [workspace]
 members = [ 
     "crates/*",
-    "src/libs/intertrait"
 ]
 
 [features]
-default = ["backtrace", "kvm"]
+default = ["backtrace", "kvm", "fatfs", "fatfs-secure"]
 # 内核栈回溯
 backtrace = []
 # kvm
 kvm = []
 
+fatfs = []
+fatfs-secure = ["fatfs"]
+
 
 # 运行时依赖项
 [dependencies]
@@ -35,26 +37,28 @@ 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 = "src/libs/intertrait" }
+intertrait = { path = "crates/intertrait" }
 kdepends = { path = "crates/kdepends" }
 klog_types = { path = "crates/klog_types" }
-linkme = "=0.2"
+linkme = "=0.3.27"
 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" }
-unified-init = { path = "crates/unified-init" }
-virtio-drivers = { git = "https://git.mirrors.dragonos.org.cn/DragonOS-Community/virtio-drivers", rev = "f91c807965" }
-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"
+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" }
 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]
@@ -85,4 +89,4 @@ debug = true   # Controls whether the compiler passes `-g`
 
 # The release profile, used for `cargo build --release`
 [profile.release]
-debug = false
+debug = true

+ 5 - 5
kernel/Makefile

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

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

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

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

@@ -14,6 +14,15 @@ 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)]:,

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

@@ -182,11 +182,6 @@ 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 - 0
kernel/src/libs/intertrait/.gitignore → kernel/crates/intertrait/.gitignore


+ 1 - 1
kernel/src/libs/intertrait/Cargo.toml → kernel/crates/intertrait/Cargo.toml

@@ -14,7 +14,7 @@ include = ["src/**/*", "Cargo.toml", "LICENSE-*", "README.md"]
 
 
 [dependencies]
-linkme = "0.2"
+linkme = "=0.3.27"
 hashbrown = "0.13.2"
 intertrait-macros = { version = "=0.2.2", path = "macros" }
 

+ 0 - 0
kernel/src/libs/intertrait/LICENSE-MIT → kernel/crates/intertrait/LICENSE-MIT


+ 1 - 1
kernel/src/libs/intertrait/README.md → kernel/crates/intertrait/README.md

@@ -23,7 +23,7 @@ Add the following two dependencies to your `Cargo.toml`:
 ```toml
 [dependencies]
 intertrait = "0.2"
-linkme = "0.2"
+linkme = "=0.3.27"
 ```
 
 The `linkme` dependency is required due to the use of `linkme` macro in the output of `intertrait` macros.

+ 1 - 1
kernel/src/libs/intertrait/macros/Cargo.toml → kernel/crates/intertrait/macros/Cargo.toml

@@ -20,4 +20,4 @@ uuid = { version = "0.8", features = ["v4"] }
 
 [dev-dependencies]
 intertrait = { version = "=0.2.2", path = ".." }
-linkme = "0.2"
+linkme = "=0.3.27"

+ 0 - 0
kernel/src/libs/intertrait/macros/LICENSE-APACHE → kernel/crates/intertrait/macros/LICENSE-APACHE


+ 0 - 0
kernel/src/libs/intertrait/macros/LICENSE-MIT → kernel/crates/intertrait/macros/LICENSE-MIT


+ 0 - 0
kernel/src/libs/intertrait/macros/src/args.rs → kernel/crates/intertrait/macros/src/args.rs


+ 0 - 0
kernel/src/libs/intertrait/macros/src/gen_caster.rs → kernel/crates/intertrait/macros/src/gen_caster.rs


+ 0 - 0
kernel/src/libs/intertrait/macros/src/item_impl.rs → kernel/crates/intertrait/macros/src/item_impl.rs


+ 0 - 0
kernel/src/libs/intertrait/macros/src/item_type.rs → kernel/crates/intertrait/macros/src/item_type.rs


+ 0 - 0
kernel/src/libs/intertrait/macros/src/lib.rs → kernel/crates/intertrait/macros/src/lib.rs


+ 0 - 0
kernel/src/libs/intertrait/src/cast.rs → kernel/crates/intertrait/src/cast.rs


+ 0 - 0
kernel/src/libs/intertrait/src/cast/cast_arc.rs → kernel/crates/intertrait/src/cast/cast_arc.rs


+ 0 - 0
kernel/src/libs/intertrait/src/cast/cast_box.rs → kernel/crates/intertrait/src/cast/cast_box.rs


+ 0 - 0
kernel/src/libs/intertrait/src/cast/cast_mut.rs → kernel/crates/intertrait/src/cast/cast_mut.rs


+ 0 - 0
kernel/src/libs/intertrait/src/cast/cast_rc.rs → kernel/crates/intertrait/src/cast/cast_rc.rs


+ 0 - 0
kernel/src/libs/intertrait/src/cast/cast_ref.rs → kernel/crates/intertrait/src/cast/cast_ref.rs


+ 0 - 0
kernel/src/libs/intertrait/src/hasher.rs → kernel/crates/intertrait/src/hasher.rs


+ 0 - 0
kernel/src/libs/intertrait/src/lib.rs → kernel/crates/intertrait/src/lib.rs


+ 0 - 0
kernel/src/libs/intertrait/tests/castable_to.rs → kernel/crates/intertrait/tests/castable_to.rs


+ 0 - 0
kernel/src/libs/intertrait/tests/on-enum.rs → kernel/crates/intertrait/tests/on-enum.rs


+ 0 - 0
kernel/src/libs/intertrait/tests/on-struct.rs → kernel/crates/intertrait/tests/on-struct.rs


+ 0 - 0
kernel/src/libs/intertrait/tests/on-trait-impl-assoc-type1.rs → kernel/crates/intertrait/tests/on-trait-impl-assoc-type1.rs


+ 0 - 0
kernel/src/libs/intertrait/tests/on-trait-impl-assoc-type2.rs → kernel/crates/intertrait/tests/on-trait-impl-assoc-type2.rs


+ 0 - 0
kernel/src/libs/intertrait/tests/on-trait-impl-assoc-type3.rs → kernel/crates/intertrait/tests/on-trait-impl-assoc-type3.rs


+ 0 - 0
kernel/src/libs/intertrait/tests/on-trait-impl.rs → kernel/crates/intertrait/tests/on-trait-impl.rs


+ 0 - 0
kernel/src/libs/intertrait/tests/on-type-multi-traits.rs → kernel/crates/intertrait/tests/on-type-multi-traits.rs


+ 0 - 0
kernel/src/libs/intertrait/tests/run.rs → kernel/crates/intertrait/tests/run.rs


+ 0 - 0
kernel/src/libs/intertrait/tests/ui/duplicate-flags.rs → kernel/crates/intertrait/tests/ui/duplicate-flags.rs


+ 0 - 0
kernel/src/libs/intertrait/tests/ui/duplicate-flags.stderr → kernel/crates/intertrait/tests/ui/duplicate-flags.stderr


+ 0 - 0
kernel/src/libs/intertrait/tests/ui/on-generic-type.rs → kernel/crates/intertrait/tests/ui/on-generic-type.rs


+ 0 - 0
kernel/src/libs/intertrait/tests/ui/on-generic-type.stderr → kernel/crates/intertrait/tests/ui/on-generic-type.stderr


+ 0 - 0
kernel/src/libs/intertrait/tests/ui/on-type-impl.rs → kernel/crates/intertrait/tests/ui/on-type-impl.rs


+ 0 - 0
kernel/src/libs/intertrait/tests/ui/on-type-impl.stderr → kernel/crates/intertrait/tests/ui/on-type-impl.stderr


+ 0 - 0
kernel/src/libs/intertrait/tests/ui/unknown-flag.rs → kernel/crates/intertrait/tests/ui/unknown-flag.rs


+ 0 - 0
kernel/src/libs/intertrait/tests/ui/unknown-flag.stderr → kernel/crates/intertrait/tests/ui/unknown-flag.stderr


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

@@ -175,6 +175,12 @@ 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()

+ 5 - 3
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_value());
+            *bitmap = AtomicU64::new(u64::MAX);
         }
 
         // 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_value() {
+            if bitval == u64::MAX {
                 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_value())
+            .filter(|&x| x.load(Ordering::Relaxed) != u64::MAX)
             .count()
             == 0
     }
@@ -410,6 +410,7 @@ 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,
@@ -453,6 +454,7 @@ 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.2"
+linkme = "=0.3.27"
 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.2"
+linkme = "=0.3.27"
 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| {
-                kerror!("Failed to call initializer {}: {:?}", initializer.name(), e);
+                log::error!("Failed to call initializer {}: {:?}", initializer.name(), e);
             });
         }
     };

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

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

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

@@ -0,0 +1,60 @@
+#![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
+    }};
+);

+ 3 - 0
kernel/env.mk

@@ -42,3 +42,6 @@ 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-2023-08-15"
+channel = "nightly-2024-07-23"
 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-2023-08-15 $(CARGO_ZBUILD) build --release --target $(TARGET_JSON)
+	RUSTFLAGS="$(RUSTFLAGS)" cargo +nightly-2024-07-23 $(CARGO_ZBUILD) build --release --target $(TARGET_JSON)
 
 
 all: kernel

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

@@ -1,4 +1,5 @@
 /// 每个架构都需要实现的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);
-        // kdebug!(
+        // debug!(
         //     "map_fdt paddr: {:?}, map_pa: {:?},fdt_size: {},  size: {:?}",
         //     fdt_paddr,
         //     map_paddr,
@@ -28,7 +28,7 @@ impl OpenFirmwareFdtDriver {
 
         // drop the boot params guard in order to avoid deadlock
         drop(bp_guard);
-        // kdebug!("map_fdt: map fdt to {:?}, size: {}", map_paddr, map_size);
+        // debug!("map_fdt: map fdt to {:?}, size: {}", map_paddr, map_size);
         mmio_guard.map_phys(map_paddr, map_size)?;
         let mut bp_guard = boot_params().write();
         let vaddr = mmio_guard.vaddr() + offset;

+ 5 - 6
kernel/src/arch/riscv64/init/mod.rs

@@ -1,11 +1,11 @@
 use fdt::node::FdtNode;
+use log::{debug, info};
 use system_error::SystemError;
 
 use crate::{
     arch::{driver::sbi::SbiDriver, mm::init::mm_early_init},
     driver::{firmware::efi::init::efi_init, open_firmware::fdt::open_firmware_fdt_driver},
     init::{boot_params, init::start_kernel},
-    kdebug, kinfo,
     mm::{memblock::mem_block_manager, PhysAddr, VirtAddr},
     print, println,
     smp::cpu::ProcessorId,
@@ -112,13 +112,12 @@ pub fn early_setup_arch() -> Result<(), SystemError> {
     arch_boot_params_guard.arch.fdt_paddr = fdt_paddr;
     arch_boot_params_guard.arch.fdt_size = fdt.total_size();
     arch_boot_params_guard.arch.boot_hartid = ProcessorId::new(hartid);
-    // kdebug!("fdt_paddr: {:?}, fdt_size: {}", fdt_paddr, fdt.total_size());
+    // debug!("fdt_paddr: {:?}, fdt_size: {}", fdt_paddr, fdt.total_size());
     drop(arch_boot_params_guard);
 
-    kinfo!(
+    info!(
         "DragonOS kernel is running on hart {}, fdt address:{:?}",
-        hartid,
-        fdt_paddr
+        hartid, fdt_paddr
     );
     mm_early_init();
 
@@ -127,7 +126,7 @@ pub fn early_setup_arch() -> Result<(), SystemError> {
     unsafe { parse_dtb() };
 
     for x in mem_block_manager().to_iter() {
-        kdebug!("before efi: {x:?}");
+        debug!("before efi: {x:?}");
     }
 
     efi_init();

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

@@ -3,9 +3,10 @@
 //! 架构相关的处理逻辑参考: https://code.dragonos.org.cn/xref/linux-6.6.21/arch/riscv/kernel/traps.c
 use core::hint::spin_loop;
 
+use log::error;
 use system_error::SystemError;
 
-use crate::{arch::syscall::syscall_handler, driver::irqchip::riscv_intc::riscv_intc_irq, kerror};
+use crate::{arch::syscall::syscall_handler, driver::irqchip::riscv_intc::riscv_intc_irq};
 
 use super::TrapFrame;
 
@@ -52,7 +53,7 @@ fn riscv64_do_exception(trap_frame: &mut TrapFrame) {
         let handler = EXCEPTION_HANDLERS[code];
         handler(trap_frame).ok();
     } else {
-        kerror!("riscv64_do_irq: exception code out of range");
+        error!("riscv64_do_irq: exception code out of range");
         loop {
             // kernel die
             spin_loop();
@@ -61,7 +62,7 @@ fn riscv64_do_exception(trap_frame: &mut TrapFrame) {
 }
 
 fn default_handler(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> {
-    kerror!("riscv64_do_irq: handler not found");
+    error!("riscv64_do_irq: handler not found");
     loop {
         spin_loop();
     }
@@ -69,7 +70,7 @@ fn default_handler(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> {
 
 /// 处理指令地址不对齐异常 #0
 fn do_trap_insn_misaligned(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> {
-    kerror!("riscv64_do_irq: do_trap_insn_misaligned");
+    error!("riscv64_do_irq: do_trap_insn_misaligned");
     loop {
         spin_loop();
     }
@@ -77,7 +78,7 @@ fn do_trap_insn_misaligned(_trap_frame: &mut TrapFrame) -> Result<(), SystemErro
 
 /// 处理指令访问异常 #1
 fn do_trap_insn_access_fault(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> {
-    kerror!("riscv64_do_irq: do_trap_insn_access_fault");
+    error!("riscv64_do_irq: do_trap_insn_access_fault");
     loop {
         spin_loop();
     }
@@ -85,7 +86,7 @@ fn do_trap_insn_access_fault(_trap_frame: &mut TrapFrame) -> Result<(), SystemEr
 
 /// 处理非法指令异常 #2
 fn do_trap_insn_illegal(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> {
-    kerror!("riscv64_do_irq: do_trap_insn_illegal");
+    error!("riscv64_do_irq: do_trap_insn_illegal");
     loop {
         spin_loop();
     }
@@ -93,7 +94,7 @@ fn do_trap_insn_illegal(_trap_frame: &mut TrapFrame) -> Result<(), SystemError>
 
 /// 处理断点异常 #3
 fn do_trap_break(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> {
-    kerror!("riscv64_do_irq: do_trap_break");
+    error!("riscv64_do_irq: do_trap_break");
     loop {
         spin_loop();
     }
@@ -101,7 +102,7 @@ fn do_trap_break(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> {
 
 /// 处理加载地址不对齐异常 #4
 fn do_trap_load_misaligned(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> {
-    kerror!("riscv64_do_irq: do_trap_load_misaligned");
+    error!("riscv64_do_irq: do_trap_load_misaligned");
     loop {
         spin_loop();
     }
@@ -109,7 +110,7 @@ fn do_trap_load_misaligned(_trap_frame: &mut TrapFrame) -> Result<(), SystemErro
 
 /// 处理加载访问异常 #5
 fn do_trap_load_access_fault(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> {
-    kerror!("riscv64_do_irq: do_trap_load_access_fault");
+    error!("riscv64_do_irq: do_trap_load_access_fault");
     loop {
         spin_loop();
     }
@@ -117,7 +118,7 @@ fn do_trap_load_access_fault(_trap_frame: &mut TrapFrame) -> Result<(), SystemEr
 
 /// 处理存储地址不对齐异常 #6
 fn do_trap_store_misaligned(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> {
-    kerror!("riscv64_do_irq: do_trap_store_misaligned");
+    error!("riscv64_do_irq: do_trap_store_misaligned");
     loop {
         spin_loop();
     }
@@ -125,7 +126,7 @@ fn do_trap_store_misaligned(_trap_frame: &mut TrapFrame) -> Result<(), SystemErr
 
 /// 处理存储访问异常 #7
 fn do_trap_store_access_fault(_trap_frame: &mut TrapFrame) -> Result<(), SystemError> {
-    kerror!("riscv64_do_irq: do_trap_store_access_fault");
+    error!("riscv64_do_irq: do_trap_store_access_fault");
     loop {
         spin_loop();
     }
@@ -151,11 +152,9 @@ fn do_trap_insn_page_fault(trap_frame: &mut TrapFrame) -> Result<(), SystemError
     let vaddr = trap_frame.badaddr;
     let cause = trap_frame.cause;
     let epc = trap_frame.epc;
-    kerror!(
+    error!(
         "riscv64_do_irq: do_insn_page_fault vaddr: {:#x}, cause: {:?} epc: {:#x}",
-        vaddr,
-        cause,
-        epc
+        vaddr, cause, epc
     );
     loop {
         spin_loop();
@@ -167,10 +166,9 @@ fn do_trap_load_page_fault(trap_frame: &mut TrapFrame) -> Result<(), SystemError
     let vaddr = trap_frame.badaddr;
     let cause = trap_frame.cause;
     let epc = trap_frame.epc;
-    kerror!(
+    error!(
         "riscv64_do_irq: do_trap_load_page_fault: epc: {epc:#x}, vaddr={:#x}, cause={:?}",
-        vaddr,
-        cause
+        vaddr, cause
     );
 
     loop {
@@ -182,11 +180,9 @@ fn do_trap_load_page_fault(trap_frame: &mut TrapFrame) -> Result<(), SystemError
 
 /// 处理页存储错误异常 #15
 fn do_trap_store_page_fault(trap_frame: &mut TrapFrame) -> Result<(), SystemError> {
-    kerror!(
+    error!(
         "riscv64_do_irq: do_trap_store_page_fault: epc: {:#x}, vaddr={:#x}, cause={:?}",
-        trap_frame.epc,
-        trap_frame.badaddr,
-        trap_frame.cause
+        trap_frame.epc, trap_frame.badaddr, trap_frame.cause
     );
     loop {
         spin_loop();

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

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

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

@@ -1,5 +1,6 @@
 use core::sync::atomic::{compiler_fence, AtomicBool, Ordering};
 
+use log::{debug, info};
 use system_error::SystemError;
 
 use crate::{
@@ -11,7 +12,6 @@ use crate::{
         MMArch,
     },
     driver::firmware::efi::efi_manager,
-    kdebug, kinfo,
     libs::lib_ui::screen_manager::scm_disable_put_to_window,
     mm::{
         allocator::{buddy::BuddyAllocator, bump::BumpAllocator, page_frame::FrameAllocator},
@@ -56,7 +56,7 @@ unsafe fn init_kernel_addr() {
     KERNEL_BEGIN_VA = VirtAddr::new(boot_text_start_pa as usize);
     KERNEL_END_VA = VirtAddr::new(_end as usize);
 
-    kdebug!(
+    debug!(
         "init_kernel_addr: \n\tKERNEL_BEGIN_PA: {KERNEL_BEGIN_PA:?}
         \tKERNEL_END_PA: {KERNEL_END_PA:?}
         \tKERNEL_BEGIN_VA: {KERNEL_BEGIN_VA:?}
@@ -78,7 +78,7 @@ pub(super) unsafe fn riscv_mm_init() -> Result<(), SystemError> {
 
     // 使用bump分配器,把所有的内存页都映射到页表
     {
-        // kdebug!("to create new page table");
+        // debug!("to create new page table");
         // 用bump allocator创建新的页表
         let mut mapper: crate::mm::page::PageMapper<MMArch, &mut BumpAllocator<MMArch>> =
             crate::mm::page::PageMapper::<MMArch, _>::create(
@@ -87,7 +87,7 @@ pub(super) unsafe fn riscv_mm_init() -> Result<(), SystemError> {
             )
             .expect("Failed to create page mapper");
         new_page_table = mapper.table().phys();
-        // kdebug!("PageMapper created");
+        // debug!("PageMapper created");
 
         // 取消最开始时候,在head.S中指定的映射(暂时不刷新TLB)
         {
@@ -99,12 +99,12 @@ pub(super) unsafe fn riscv_mm_init() -> Result<(), SystemError> {
                     .expect("Failed to empty page table entry");
             }
         }
-        kdebug!("Successfully emptied page table");
+        debug!("Successfully emptied page table");
 
         let total_num = mem_block_manager().total_initial_memory_regions();
         for i in 0..total_num {
             let area = mem_block_manager().get_initial_memory_region(i).unwrap();
-            // kdebug!("area: base={:?}, size={:#x}, end={:?}", area.base, area.size, area.base + area.size);
+            // debug!("area: base={:?}, size={:#x}, end={:?}", area.base, area.size, area.base + area.size);
             for i in 0..((area.size + MMArch::PAGE_SIZE - 1) / MMArch::PAGE_SIZE) {
                 let paddr = area.base.add(i * MMArch::PAGE_SIZE);
                 let vaddr = unsafe { MMArch::phys_2_virt(paddr) }.unwrap();
@@ -125,7 +125,7 @@ pub(super) unsafe fn riscv_mm_init() -> Result<(), SystemError> {
     unsafe {
         INITIAL_PGTABLE_VALUE = new_page_table;
     }
-    kdebug!(
+    debug!(
         "After mapping all physical memory, DragonOS used: {} KB",
         bump_allocator.usage().used().bytes() / 1024
     );
@@ -134,7 +134,7 @@ pub(super) unsafe fn riscv_mm_init() -> Result<(), SystemError> {
     let buddy_allocator = unsafe { BuddyAllocator::<MMArch>::new(bump_allocator).unwrap() };
     // 设置全局的页帧分配器
     unsafe { set_inner_allocator(buddy_allocator) };
-    kinfo!("Successfully initialized buddy allocator");
+    info!("Successfully initialized buddy allocator");
     // 关闭显示输出
     scm_disable_put_to_window();
 
@@ -142,7 +142,7 @@ pub(super) unsafe fn riscv_mm_init() -> Result<(), SystemError> {
     {
         let mut binding = INNER_ALLOCATOR.lock();
         let mut allocator_guard = binding.as_mut().unwrap();
-        kdebug!("To enable new page table.");
+        debug!("To enable new page table.");
         compiler_fence(Ordering::SeqCst);
         let mapper = crate::mm::page::PageMapper::<MMArch, _>::new(
             PageTableKind::Kernel,
@@ -152,10 +152,10 @@ pub(super) unsafe fn riscv_mm_init() -> Result<(), SystemError> {
         compiler_fence(Ordering::SeqCst);
         mapper.make_current();
         compiler_fence(Ordering::SeqCst);
-        // kdebug!("New page table enabled");
+        // debug!("New page table enabled");
     }
-    kdebug!("Successfully enabled new page table");
-    kinfo!("riscv mm init done");
+    debug!("Successfully enabled new page table");
+    info!("riscv mm init done");
 
     return Ok(());
 }

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

@@ -12,9 +12,9 @@ use crate::{
             page_frame::{FrameAllocator, PageFrameCount, PageFrameUsage, PhysPageFrame},
         },
         kernel_mapper::KernelMapper,
-        page::{PageEntry, PageFlags, PAGE_1G_SHIFT},
+        page::{EntryFlags, PageEntry, PAGE_1G_SHIFT},
         ucontext::UserMapper,
-        MemoryManagementArch, PageTableKind, PhysAddr, VirtAddr,
+        MemoryManagementArch, PageTableKind, PhysAddr, VirtAddr, VmFlags,
     },
     smp::cpu::ProcessorId,
 };
@@ -256,8 +256,74 @@ 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)]
@@ -270,8 +336,8 @@ impl VirtAddr {
 }
 
 /// 获取内核地址默认的页面标志
-pub unsafe fn kernel_page_flags<A: MemoryManagementArch>(_virt: VirtAddr) -> PageFlags<A> {
-    PageFlags::from_data(RiscV64MMArch::ENTRY_FLAG_DEFAULT_PAGE)
+pub unsafe fn kernel_page_flags<A: MemoryManagementArch>(_virt: VirtAddr) -> EntryFlags<A> {
+    EntryFlags::from_data(RiscV64MMArch::ENTRY_FLAG_DEFAULT_PAGE)
         .set_user(false)
         .set_execute(true)
 }

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

@@ -1,4 +1,5 @@
 use fdt::{node::FdtNode, Fdt};
+use log::debug;
 use system_error::SystemError;
 
 use crate::{
@@ -6,7 +7,6 @@ use crate::{
         open_firmware::fdt::open_firmware_fdt_driver,
         pci::ecam::{pci_ecam_root_info_manager, EcamRootInfo},
     },
-    kdebug,
     mm::PhysAddr,
 };
 
@@ -39,7 +39,7 @@ pub(super) fn pci_host_ecam_driver_init(fdt: &Fdt<'_>) -> Result<(), SystemError
             _ => panic!("Unexpected linux,pci-domain length"),
         };
 
-        kdebug!(
+        debug!(
             "pci_host_ecam_driver_init(): {} paddr: {:#x} size: {:#x} bus-range: {}-{} segement_group_number: {}",
             node.name,
             paddr,
@@ -61,10 +61,9 @@ pub(super) fn pci_host_ecam_driver_init(fdt: &Fdt<'_>) -> Result<(), SystemError
 
     for node in open_firmware_fdt_driver().find_node_by_compatible(&fdt, "pci-host-ecam-generic") {
         if let Err(err) = do_check(node) {
-            kdebug!(
+            debug!(
                 "pci_host_ecam_driver_init(): check {} error: {:?}",
-                node.name,
-                err
+                node.name, err
             );
         }
     }

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

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

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

@@ -6,6 +6,7 @@ use core::{
     sync::atomic::{compiler_fence, Ordering},
 };
 use kdepends::memoffset::offset_of;
+use log::error;
 use riscv::register::sstatus::Sstatus;
 use system_error::SystemError;
 
@@ -15,7 +16,6 @@ use crate::{
         CurrentIrqArch,
     },
     exception::InterruptArch,
-    kerror,
     libs::spinlock::SpinLockGuard,
     mm::VirtAddr,
     process::{
@@ -166,7 +166,7 @@ impl ProcessManager {
     /// 参考: https://code.dragonos.org.cn/xref/linux-6.6.21/arch/riscv/include/asm/switch_to.h#76
     pub unsafe fn switch_process(prev: Arc<ProcessControlBlock>, next: Arc<ProcessControlBlock>) {
         assert!(!CurrentIrqArch::is_irq_enabled());
-        // kdebug!(
+        // debug!(
         //     "riscv switch process: prev: {:?}, next: {:?}",
         //     prev.pid(),
         //     next.pid()
@@ -182,7 +182,7 @@ impl ProcessManager {
         drop(next_addr_space);
         compiler_fence(Ordering::SeqCst);
 
-        // kdebug!("current sum={}, prev sum={}, next_sum={}", riscv::register::sstatus::read().sum(), prev.arch_info_irqsave().sstatus.sum(), next.arch_info_irqsave().sstatus.sum());
+        // debug!("current sum={}, prev sum={}, next_sum={}", riscv::register::sstatus::read().sum(), prev.arch_info_irqsave().sstatus.sum(), next.arch_info_irqsave().sstatus.sum());
 
         // 获取arch info的锁,并强制泄露其守卫(切换上下文后,在switch_finish_hook中会释放锁)
         let next_arch = SpinLockGuard::leak(next.arch_info_irqsave()) as *mut ArchPCBInfo;
@@ -193,7 +193,7 @@ impl ProcessManager {
         ProcessManager::current_pcb().preempt_enable();
         PROCESS_SWITCH_RESULT.as_mut().unwrap().get_mut().prev_pcb = Some(prev);
         PROCESS_SWITCH_RESULT.as_mut().unwrap().get_mut().next_pcb = Some(next);
-        // kdebug!("riscv switch process: before to inner");
+        // debug!("riscv switch process: before to inner");
         compiler_fence(Ordering::SeqCst);
         // 正式切换上下文
         switch_to_inner(prev_arch, next_arch);
@@ -326,7 +326,7 @@ impl ProcessControlBlock {
         // 从内核栈的最低地址处取出pcb的地址
         let p = stack_base.data() as *const *const ProcessControlBlock;
         if core::intrinsics::unlikely((unsafe { *p }).is_null()) {
-            kerror!("p={:p}", p);
+            error!("p={:p}", p);
             panic!("current_pcb is null");
         }
         unsafe {

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

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

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

@@ -1,11 +1,9 @@
+use log::warn;
 use system_error::SystemError;
 
-use crate::{
-    kwarn,
-    smp::{
-        cpu::{CpuHpCpuState, ProcessorId},
-        SMPArch,
-    },
+use crate::smp::{
+    cpu::{CpuHpCpuState, ProcessorId},
+    SMPArch,
 };
 
 pub struct RiscV64SMPArch;
@@ -13,12 +11,12 @@ pub struct RiscV64SMPArch;
 impl SMPArch for RiscV64SMPArch {
     #[inline(never)]
     fn prepare_cpus() -> Result<(), SystemError> {
-        kwarn!("RiscV64SMPArch::prepare_cpus() is not implemented");
+        warn!("RiscV64SMPArch::prepare_cpus() is not implemented");
         Ok(())
     }
 
     fn start_cpu(_cpu_id: ProcessorId, _hp_state: &CpuHpCpuState) -> Result<(), SystemError> {
-        kwarn!("RiscV64SMPArch::start_cpu() is not implemented");
+        warn!("RiscV64SMPArch::start_cpu() is not implemented");
         Ok(())
     }
 }

+ 2 - 2
kernel/src/arch/riscv64/syscall/mod.rs

@@ -18,7 +18,7 @@ macro_rules! syscall_return {
 
         if $show {
             let pid = ProcessManager::current_pcb().pid();
-            crate::kdebug!("syscall return:pid={:?},ret= {:?}\n", pid, ret as isize);
+            log::debug!("syscall return:pid={:?},ret= {:?}\n", pid, ret as isize);
         }
 
         unsafe {
@@ -29,7 +29,7 @@ macro_rules! syscall_return {
 }
 
 pub(super) fn syscall_handler(syscall_num: usize, frame: &mut TrapFrame) -> () {
-    // kdebug!("syscall_handler: syscall_num: {}", syscall_num);
+    // debug!("syscall_handler: syscall_num: {}", syscall_num);
     unsafe {
         CurrentIrqArch::interrupt_enable();
     }

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

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

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

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

+ 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() {
-    kdebug!("init_bsp_apic_timer");
+    debug!("init_bsp_apic_timer");
     assert!(smp_get_processor_id().data() == 0);
     let mut local_apic_timer = local_apic_timer_instance_mut(ProcessorId::new(0));
     local_apic_timer.init(
@@ -113,11 +113,11 @@ fn init_bsp_apic_timer() {
         LocalApicTimer::periodic_default_initial_count(),
         LocalApicTimer::DIVISOR as u32,
     );
-    kdebug!("init_bsp_apic_timer done");
+    debug!("init_bsp_apic_timer done");
 }
 
 fn init_ap_apic_timer() {
-    kdebug!("init_ap_apic_timer");
+    debug!("init_ap_apic_timer");
     let cpu_id = smp_get_processor_id();
     assert!(cpu_id.data() != 0);
 
@@ -127,14 +127,14 @@ fn init_ap_apic_timer() {
         LocalApicTimer::periodic_default_initial_count(),
         LocalApicTimer::DIVISOR as u32,
     );
-    kdebug!("init_ap_apic_timer done");
+    debug!("init_ap_apic_timer done");
 }
 
 pub(super) struct LocalApicTimerIntrController;
 
 impl LocalApicTimerIntrController {
     pub(super) fn install(&self) {
-        kdebug!("LocalApicTimerIntrController::install");
+        debug!("LocalApicTimerIntrController::install");
         if smp_get_processor_id().data() == 0 {
             init_bsp_apic_timer();
         } else {
@@ -150,12 +150,13 @@ impl LocalApicTimerIntrController {
     }
 
     pub(super) fn enable(&self) {
-        kdebug!("LocalApicTimerIntrController::enable");
+        debug!("LocalApicTimerIntrController::enable");
         let cpu_id = smp_get_processor_id();
         let mut local_apic_timer = local_apic_timer_instance_mut(cpu_id);
         local_apic_timer.start_current();
     }
 
+    #[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);
@@ -221,19 +222,18 @@ impl LocalApicTimer {
     }
 
     fn install_periodic_mode(&mut self, initial_count: u64, divisor: u32) {
-        kdebug!(
+        debug!(
             "install_periodic_mode: initial_count = {}, divisor = {}",
-            initial_count,
-            divisor
+            initial_count, divisor
         );
         self.mode = LocalApicTimerMode::Periodic;
         self.set_divisor(divisor);
-        self.set_initial_cnt(initial_count);
         self.setup_lvt(
             APIC_TIMER_IRQ_NUM.data() as u8,
             true,
             LocalApicTimerMode::Periodic,
         );
+        self.set_initial_cnt(initial_count);
     }
 
     fn setup_lvt(&mut self, vector: u8, mask: bool, mode: LocalApicTimerMode) {
@@ -278,7 +278,7 @@ impl LocalApicTimer {
 
     pub(super) fn handle_irq(trap_frame: &TrapFrame) -> Result<IrqReturn, SystemError> {
         // sched_update_jiffies();
-        ProcessManager::update_process_times(trap_frame.is_from_user());
+        tick_handle_periodic(trap_frame);
         return Ok(IrqReturn::Handled);
     }
 }

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

@@ -4,6 +4,7 @@ use acpi::madt::Madt;
 use alloc::sync::Arc;
 use bit_field::BitField;
 use bitflags::bitflags;
+use log::{debug, info};
 use system_error::SystemError;
 
 use crate::{
@@ -16,7 +17,6 @@ use crate::{
         manage::irq_manager,
         IrqNumber,
     },
-    kdebug, kinfo,
     libs::{
         cpumask::CpuMask,
         once::Once,
@@ -68,7 +68,7 @@ impl IoApic {
 
         let mut result: Option<IoApic> = None;
         INIT_STATE.call_once(|| {
-            kinfo!("Initializing ioapic...");
+            info!("Initializing ioapic...");
 
             // get ioapic base from acpi
 
@@ -104,7 +104,7 @@ impl IoApic {
                 mmio_guard.map_phys(phys_base, 0x1000).is_ok(),
                 "IoApic::new(): failed to map phys"
             );
-            kdebug!("Ioapic map ok");
+            debug!("Ioapic map ok");
             let reg = mmio_guard.vaddr();
 
             result = Some(IoApic {
@@ -114,13 +114,13 @@ impl IoApic {
                 phys_base,
                 mmio_guard,
             });
-            kdebug!("IOAPIC: to mask all RTE");
+            debug!("IOAPIC: to mask all RTE");
             // 屏蔽所有的RTE
             let res_mut = result.as_mut().unwrap();
             for i in 0..res_mut.supported_interrupts() {
                 res_mut.write_rte(i, 0x20 + i, RedirectionEntry::DISABLED, 0);
             }
-            kdebug!("Ioapic init done");
+            debug!("Ioapic init done");
         });
 
         assert!(
@@ -393,7 +393,7 @@ impl InnerIoApicChipData {
 
 #[inline(never)]
 pub fn ioapic_init(ignore: &'static [IrqNumber]) {
-    kinfo!("Initializing ioapic...");
+    info!("Initializing ioapic...");
     let ioapic = unsafe { IoApic::new() };
     unsafe {
         __IOAPIC = Some(SpinLock::new(ioapic));
@@ -424,7 +424,7 @@ pub fn ioapic_init(ignore: &'static [IrqNumber]) {
         register_handler(&desc, level);
     }
 
-    kinfo!("IO Apic initialized.");
+    info!("IO Apic initialized.");
 }
 
 fn register_handler(desc: &Arc<IrqDesc>, level_triggered: bool) {

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

@@ -2,6 +2,7 @@ use core::intrinsics::unlikely;
 
 use alloc::{string::ToString, sync::Arc};
 use intertrait::CastFrom;
+use log::warn;
 use system_error::SystemError;
 
 use crate::{
@@ -25,7 +26,6 @@ use crate::{
         msi::MsiMsg,
         HardwareIrqNumber, IrqNumber,
     },
-    kwarn,
     libs::spinlock::{SpinLock, SpinLockGuard},
     smp::{core::smp_get_processor_id, cpu::ProcessorId},
 };
@@ -179,6 +179,7 @@ bitflags! {
     }
 }
 
+#[allow(dead_code)]
 pub(super) fn irq_msi_compose_msg(cfg: &HardwareIrqConfig, msg: &mut MsiMsg, dmar: bool) {
     *msg = MsiMsg::new_zeroed();
 
@@ -206,7 +207,7 @@ pub(super) fn irq_msi_compose_msg(cfg: &HardwareIrqConfig, msg: &mut MsiMsg, dma
         // 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/arch/x86/kernel/apic/apic.c?fi=__irq_msi_compose_msg#2580
         address_lo.set_virt_destid_8_14(cfg.apic_id.data() >> 8);
     } else if unlikely(cfg.apic_id.data() > 0xff) {
-        kwarn!(
+        warn!(
             "irq_msi_compose_msg: Invalid APIC ID: {}",
             cfg.apic_id.data()
         );
@@ -252,7 +253,7 @@ pub fn arch_early_irq_init() -> Result<(), SystemError> {
 
     // todo: add vector matrix
     // 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/arch/x86/kernel/apic/vector.c#803
-    kwarn!("arch_early_irq_init: todo: add vector matrix");
+    warn!("arch_early_irq_init: todo: add vector matrix");
 
     local_apic_timer_irq_desc_init();
     arch_ipi_handler_init();

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

@@ -1,6 +1,7 @@
 use core::sync::atomic::Ordering;
 
 use atomic_enum::atomic_enum;
+use log::{debug, info};
 use system_error::SystemError;
 use x86::{apic::Icr, msr::IA32_APIC_BASE};
 
@@ -10,7 +11,6 @@ use crate::{
         io::PortIOArch,
         CurrentPortIOArch,
     },
-    kdebug, kinfo,
     mm::PhysAddr,
     smp::core::smp_get_processor_id,
 };
@@ -468,7 +468,7 @@ impl CurrentApic {
         CurrentPortIOArch::out8(0x20, 0x20);
         CurrentPortIOArch::out8(0xa0, 0x20);
 
-        kdebug!("8259A Masked.");
+        debug!("8259A Masked.");
 
         // enable IMCR
         CurrentPortIOArch::out8(0x22, 0x70);
@@ -488,14 +488,14 @@ impl LocalAPIC for CurrentApic {
                 self.mask8259a();
             }
         }
-        kinfo!("Initializing apic for cpu {:?}", cpu_id);
+        info!("Initializing apic for cpu {:?}", cpu_id);
         if X2Apic::support() && X2Apic.init_current_cpu() {
             if cpu_id.data() == 0 {
                 LOCAL_APIC_ENABLE_TYPE.store(LocalApicEnableType::X2Apic, Ordering::SeqCst);
             }
-            kinfo!("x2APIC initialized for cpu {:?}", cpu_id);
+            info!("x2APIC initialized for cpu {:?}", cpu_id);
         } else {
-            kinfo!("x2APIC not supported or failed to initialize, fallback to xAPIC.");
+            info!("x2APIC not supported or failed to initialize, fallback to xAPIC.");
             if cpu_id.data() == 0 {
                 LOCAL_APIC_ENABLE_TYPE.store(LocalApicEnableType::XApic, Ordering::SeqCst);
             }
@@ -514,10 +514,10 @@ impl LocalAPIC for CurrentApic {
                 xapic.init_current_cpu();
             }
 
-            kinfo!("xAPIC initialized for cpu {:?}", cpu_id);
+            info!("xAPIC initialized for cpu {:?}", cpu_id);
         }
 
-        kinfo!("Apic initialized.");
+        info!("Apic initialized.");
         return true;
     }
 

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

@@ -1,12 +1,11 @@
 use core::sync::atomic::{fence, Ordering};
 
+use log::info;
 use x86::msr::{
     rdmsr, wrmsr, IA32_APIC_BASE, IA32_X2APIC_APICID, IA32_X2APIC_EOI, IA32_X2APIC_SIVR,
     IA32_X2APIC_VERSION,
 };
 
-use crate::kinfo;
-
 use super::{hw_irq::ApicId, LVTRegister, LocalAPIC, LVT};
 
 #[derive(Debug)]
@@ -45,19 +44,19 @@ impl LocalAPIC for X2Apic {
                     (rdmsr(IA32_X2APIC_SIVR) & 0x100) == 0x100,
                     "x2APIC software enable failed."
                 );
-                kinfo!("x2APIC software enabled.");
+                info!("x2APIC software enabled.");
 
                 if self.support_eoi_broadcast_suppression() {
                     assert!(
                         (rdmsr(IA32_X2APIC_SIVR) & 0x1000) == 0x1000,
                         "x2APIC EOI broadcast suppression enable failed."
                     );
-                    kinfo!("x2APIC EOI broadcast suppression enabled.");
+                    info!("x2APIC EOI broadcast suppression enabled.");
                 }
             }
-            // kdebug!("x2apic: to mask all lvt");
+            // debug!("x2apic: to mask all lvt");
             self.mask_all_lvt();
-            // kdebug!("x2apic: all lvt masked");
+            // debug!("x2apic: all lvt masked");
         }
         true
     }

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

@@ -4,8 +4,9 @@ use core::{
     ptr::{read_volatile, write_volatile},
 };
 
+use log::{debug, error, info};
+
 use crate::{
-    kdebug, kerror, kinfo,
     mm::{
         mmio_buddy::{mmio_pool, MMIOSpaceGuard},
         percpu::PerCpu,
@@ -157,7 +158,7 @@ impl XApic {
         g.map_phys(paddr, 4096).expect("Fail to map MMIO for XAPIC");
         let addr = g.vaddr() + offset;
 
-        kdebug!(
+        debug!(
             "XAPIC: {:#x} -> {:#x}, offset={offset}",
             xapic_base.data(),
             addr.data()
@@ -219,7 +220,7 @@ impl LocalAPIC for XApic {
             x86::msr::wrmsr(x86::msr::APIC_BASE, (self.xapic_base.data() | 0x800) as u64);
             let val = x86::msr::rdmsr(x86::msr::APIC_BASE);
             if val & 0x800 != 0x800 {
-                kerror!("xAPIC enable failed: APIC_BASE & 0x800 != 0x800");
+                error!("xAPIC enable failed: APIC_BASE & 0x800 != 0x800");
                 return false;
             }
             // 设置 Spurious Interrupt Vector Register
@@ -229,15 +230,15 @@ impl LocalAPIC for XApic {
 
             let val = self.read(XApicOffset::LOCAL_APIC_OFFSET_Local_APIC_SVR);
             if val & ENABLE == 0 {
-                kerror!("xAPIC software enable failed.");
+                error!("xAPIC software enable failed.");
 
                 return false;
             } else {
-                kinfo!("xAPIC software enabled.");
+                info!("xAPIC software enabled.");
             }
 
             if val & 0x1000 != 0 {
-                kinfo!("xAPIC EOI broadcast suppression enabled.");
+                info!("xAPIC EOI broadcast suppression enabled.");
             }
 
             self.mask_all_lvt();

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

@@ -7,6 +7,7 @@ use core::{
 
 use acpi::HpetInfo;
 use alloc::{string::ToString, sync::Arc};
+use log::{debug, error, info};
 use system_error::SystemError;
 
 use crate::{
@@ -21,7 +22,6 @@ use crate::{
         manage::irq_manager,
         InterruptArch, IrqNumber,
     },
-    kdebug, kerror, kinfo,
     libs::{
         rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard},
         volatile::volwrite,
@@ -30,10 +30,7 @@ use crate::{
         mmio_buddy::{mmio_pool, MMIOSpaceGuard},
         PhysAddr,
     },
-    time::{
-        jiffies::NSEC_PER_JIFFY,
-        timer::{try_raise_timer_softirq, update_timer_jiffies},
-    },
+    time::jiffies::NSEC_PER_JIFFY,
 };
 
 static mut HPET_INSTANCE: Option<Hpet> = None;
@@ -80,8 +77,8 @@ impl Hpet {
                 .unwrap()
         };
         let tm_num = hpet.timers_num();
-        kdebug!("HPET0_INTERVAL_USEC: {}", Self::HPET0_INTERVAL_USEC);
-        kinfo!("HPET has {} timers", tm_num);
+        debug!("HPET0_INTERVAL_USEC: {}", Self::HPET0_INTERVAL_USEC);
+        info!("HPET has {} timers", tm_num);
         hpet_info.hpet_number = tm_num as u8;
 
         drop(mmio);
@@ -124,10 +121,10 @@ impl Hpet {
         // !!!这里是临时糊代码的,需要在apic重构的时候修改!!!
         let (inner_guard, regs) = unsafe { self.hpet_regs_mut() };
         let freq = regs.frequency();
-        kdebug!("HPET frequency: {} Hz", freq);
+        debug!("HPET frequency: {} Hz", freq);
         let ticks = Self::HPET0_INTERVAL_USEC * freq / 1000000;
         if ticks == 0 || ticks > freq * 8 {
-            kerror!("HPET enable: ticks '{ticks}' is invalid");
+            error!("HPET enable: ticks '{ticks}' is invalid");
             return Err(SystemError::EINVAL);
         }
         if unlikely(regs.timers_num() == 0) {
@@ -166,7 +163,7 @@ impl Hpet {
 
         drop(inner_guard);
 
-        kinfo!("HPET enabled");
+        info!("HPET enabled");
 
         drop(irq_guard);
         return Ok(());
@@ -239,7 +236,7 @@ impl Hpet {
     pub fn period(&self) -> u64 {
         let (inner_guard, regs) = unsafe { self.hpet_regs() };
         let period = regs.counter_clock_period();
-        kdebug!("HPET period: {}", period);
+        debug!("HPET period: {}", period);
 
         drop(inner_guard);
         return period;
@@ -249,9 +246,6 @@ 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,6 +4,7 @@ use alloc::{
     string::{String, ToString},
     sync::{Arc, Weak},
 };
+use log::error;
 use system_error::SystemError;
 use unified_init::macros::unified_init;
 
@@ -25,7 +26,6 @@ use crate::{
     exception::InterruptArch,
     filesystem::kernfs::KernFSInode,
     init::initcall::INITCALL_DEVICE,
-    kerror,
     libs::{
         mutex::Mutex,
         rwlock::{RwLockReadGuard, RwLockWriteGuard},
@@ -286,7 +286,7 @@ impl RtcClassOps for CmosRtcClassOps {
     }
 
     fn set_time(&self, _dev: &Arc<dyn RtcDevice>, _time: &RtcTime) -> Result<(), SystemError> {
-        kerror!("set_time is not implemented for CmosRtcClassOps");
+        error!("set_time is not implemented for CmosRtcClassOps");
         Err(SystemError::ENOSYS)
     }
 }

+ 19 - 19
kernel/src/arch/x86_64/driver/tsc.rs

@@ -2,13 +2,13 @@ use crate::{
     arch::{io::PortIOArch, CurrentIrqArch, CurrentPortIOArch, CurrentTimeArch},
     driver::acpi::pmtmr::{acpi_pm_read_early, ACPI_PM_OVERRUN, PMTMR_TICKS_PER_SEC},
     exception::InterruptArch,
-    kdebug, kerror, kinfo, kwarn,
     time::{TimeArch, PIT_TICK_RATE},
 };
 use core::{
     cmp::{max, min},
     intrinsics::unlikely,
 };
+use log::{debug, error, info, warn};
 use system_error::SystemError;
 
 use super::hpet::{hpet_instance, is_hpet_enabled};
@@ -31,13 +31,13 @@ impl TSCManager {
         let cpuid = x86::cpuid::CpuId::new();
         let feat = cpuid.get_feature_info().ok_or(SystemError::ENODEV)?;
         if !feat.has_tsc() {
-            kerror!("TSC is not available");
+            error!("TSC is not available");
             return Err(SystemError::ENODEV);
         }
 
         if unsafe { TSC_KHZ == 0 } {
             if let Err(e) = Self::determine_cpu_tsc_frequency(false) {
-                kerror!("Failed to determine CPU TSC frequency: {:?}", e);
+                error!("Failed to determine CPU TSC frequency: {:?}", e);
                 // todo: mark TSC as unstable clock source
                 return Err(e);
             }
@@ -57,7 +57,7 @@ impl TSCManager {
     /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/arch/x86/kernel/tsc.c#1438
     fn determine_cpu_tsc_frequency(early: bool) -> Result<(), SystemError> {
         if unlikely(Self::cpu_khz() != 0 || Self::tsc_khz() != 0) {
-            kwarn!("TSC and CPU frequency already determined");
+            warn!("TSC and CPU frequency already determined");
         }
 
         if early {
@@ -79,16 +79,16 @@ impl TSCManager {
         }
 
         if Self::cpu_khz() == 0 {
-            kerror!("Failed to determine CPU frequency");
+            error!("Failed to determine CPU frequency");
             return Err(SystemError::ENODEV);
         }
 
-        kinfo!(
+        info!(
             "Detected {}.{} MHz processor",
             Self::cpu_khz() / 1000,
             Self::cpu_khz() % 1000
         );
-        kinfo!(
+        info!(
             "Detected {}.{} MHz TSC",
             Self::tsc_khz() / 1000,
             Self::tsc_khz() % 1000
@@ -102,7 +102,7 @@ impl TSCManager {
     /// 使用pit、hpet、ptimer来测量CPU总线的频率
     fn calibrate_cpu_by_pit_hpet_ptimer() -> Result<u64, SystemError> {
         let hpet = is_hpet_enabled();
-        kdebug!(
+        debug!(
             "Calibrating TSC with {}",
             if hpet { "HPET" } else { "PMTIMER" }
         );
@@ -143,7 +143,7 @@ impl TSCManager {
 
             // HPET或者PTIMER可能是不可用的
             if ref1 == ref2 {
-                kdebug!("HPET/PMTIMER not available");
+                debug!("HPET/PMTIMER not available");
                 continue;
             }
 
@@ -169,7 +169,7 @@ impl TSCManager {
             // 如果误差在10%以内,那么认为测量成功
             // 返回参考值,因为它是更精确的
             if (90..=110).contains(&delta) {
-                kinfo!(
+                info!(
                     "PIT calibration matches {}. {} loops",
                     if hpet { "HPET" } else { "PMTIMER" },
                     i + 1
@@ -185,20 +185,20 @@ impl TSCManager {
         }
 
         if tsc_pit_min == u64::MAX {
-            kwarn!("Unable to calibrate against PIT");
+            warn!("Unable to calibrate against PIT");
 
             // 如果没有参考值,那么禁用tsc
             if (!hpet) && (global_ref1 == 0) && (global_ref2 == 0) {
-                kwarn!("No reference (HPET/PMTIMER) available");
+                warn!("No reference (HPET/PMTIMER) available");
                 return Err(SystemError::ENODEV);
             }
 
             if tsc_ref_min == u64::MAX {
-                kwarn!("Unable to calibrate against HPET/PMTIMER");
+                warn!("Unable to calibrate against HPET/PMTIMER");
                 return Err(SystemError::ENODEV);
             }
 
-            kinfo!(
+            info!(
                 "Using {} reference calibration",
                 if hpet { "HPET" } else { "PMTIMER" }
             );
@@ -207,27 +207,27 @@ impl TSCManager {
 
         // We don't have an alternative source, use the PIT calibration value
         if (!hpet) && (global_ref1 == 0) && (global_ref2 == 0) {
-            kinfo!("Using PIT calibration value");
+            info!("Using PIT calibration value");
             return Ok(tsc_pit_min);
         }
 
         // The alternative source failed, use the PIT calibration value
         if tsc_ref_min == u64::MAX {
-            kwarn!("Unable to calibrate against HPET/PMTIMER, using PIT calibration value");
+            warn!("Unable to calibrate against HPET/PMTIMER, using PIT calibration value");
             return Ok(tsc_pit_min);
         }
 
         // The calibration values differ too much. In doubt, we use
         // the PIT value as we know that there are PMTIMERs around
         // running at double speed. At least we let the user know:
-        kwarn!(
+        warn!(
             "PIT calibration deviates from {}: tsc_pit_min={}, tsc_ref_min={}",
             if hpet { "HPET" } else { "PMTIMER" },
             tsc_pit_min,
             tsc_ref_min
         );
 
-        kinfo!("Using PIT calibration value");
+        info!("Using PIT calibration value");
         return Ok(tsc_pit_min);
     }
 
@@ -326,7 +326,7 @@ impl TSCManager {
             }
         }
 
-        kwarn!("TSCManager: Failed to read reference value, tsc delta too high");
+        warn!("TSCManager: Failed to read reference value, tsc delta too high");
         return (u64::MAX, ref_ret);
     }
 

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

@@ -1,5 +1,6 @@
 use core::sync::atomic::{compiler_fence, Ordering};
 
+use log::debug;
 use system_error::SystemError;
 use x86::dtables::DescriptorTablePointer;
 
@@ -7,7 +8,6 @@ use crate::{
     arch::{interrupt::trap::arch_trap_init, process::table::TSSManager},
     driver::clocksource::acpi_pm::init_acpi_pm_clocksource,
     init::init::start_kernel,
-    kdebug,
     mm::{MemoryManagementArch, PhysAddr},
 };
 
@@ -35,6 +35,7 @@ extern "C" {
 }
 
 #[no_mangle]
+#[allow(static_mut_refs)]
 unsafe extern "C" fn kernel_main(
     mb2_info: u64,
     mb2_magic: u64,
@@ -66,16 +67,17 @@ 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;
-    kdebug!("head_stack_start={:#x}\n", stack_start);
+    debug!("head_stack_start={:#x}\n", stack_start);
     unsafe {
         let gdt_vaddr =
             MMArch::phys_2_virt(PhysAddr::new(&GDT_Table as *const usize as usize)).unwrap();
         let idt_vaddr =
             MMArch::phys_2_virt(PhysAddr::new(&IDT_Table as *const usize as usize)).unwrap();
 
-        kdebug!("GDT_Table={:?}, IDT_Table={:?}\n", gdt_vaddr, idt_vaddr);
+        debug!("GDT_Table={:?}, IDT_Table={:?}\n", gdt_vaddr, idt_vaddr);
     }
 
     set_current_core_tss(stack_start, 0);
@@ -107,10 +109,9 @@ pub fn setup_arch_post() -> Result<(), SystemError> {
 
 fn set_current_core_tss(stack_start: usize, ist0: usize) {
     let current_tss = unsafe { TSSManager::current_tss() };
-    kdebug!(
+    debug!(
         "set_current_core_tss: stack_start={:#x}, ist0={:#x}\n",
-        stack_start,
-        ist0
+        stack_start, ist0
     );
     current_tss.set_rsp(x86::Ring::Ring0, stack_start as u64);
     current_tss.set_ist(0, ist0 as u64);

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

@@ -564,6 +564,7 @@ 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,4 +1,5 @@
 use alloc::sync::Arc;
+use log::error;
 use system_error::SystemError;
 use x86::apic::ApicId;
 
@@ -13,7 +14,6 @@ use crate::{
         irqdesc::{irq_desc_manager, IrqDesc, IrqFlowHandler, IrqHandler},
         HardwareIrqNumber, IrqNumber,
     },
-    kerror,
     smp::cpu::ProcessorId,
 };
 
@@ -122,14 +122,14 @@ impl From<ArchIpiTarget> for x86::apic::DestinationShorthand {
 
 #[inline(always)]
 pub fn send_ipi(kind: IpiKind, target: IpiTarget) {
-    // kdebug!("send_ipi: {:?} {:?}", kind, target);
+    // debug!("send_ipi: {:?} {:?}", kind, target);
 
     let ipi_vec = ArchIpiKind::from(kind).into();
     let target = ArchIpiTarget::from(target);
     let shorthand: x86::apic::DestinationShorthand = target.into();
     let destination: x86::apic::ApicId = target.into();
     let icr = if CurrentApic.x2apic_enabled() {
-        // kdebug!("send_ipi: x2apic");
+        // debug!("send_ipi: x2apic");
         x86::apic::Icr::for_x2apic(
             ipi_vec,
             destination,
@@ -141,7 +141,7 @@ pub fn send_ipi(kind: IpiKind, target: IpiTarget) {
             x86::apic::TriggerMode::Edge,
         )
     } else {
-        // kdebug!("send_ipi: xapic");
+        // debug!("send_ipi: xapic");
         x86::apic::Icr::for_xapic(
             ipi_vec,
             destination,
@@ -257,7 +257,7 @@ impl IrqFlowHandler for X86_64IpiIrqFlowHandler {
                 CurrentApic.send_eoi();
             }
             _ => {
-                kerror!("Unknown IPI: {}", irq.data());
+                error!("Unknown IPI: {}", irq.data());
                 CurrentApic.send_eoi();
             }
         }

+ 8 - 2
kernel/src/arch/x86_64/interrupt/mod.rs

@@ -9,12 +9,12 @@ use core::{
     sync::atomic::{compiler_fence, Ordering},
 };
 
+use log::error;
 use system_error::SystemError;
 
 use crate::{
     arch::CurrentIrqArch,
     exception::{InterruptArch, IrqFlags, IrqFlagsGuard, IrqNumber},
-    kerror,
 };
 
 use super::{
@@ -85,7 +85,7 @@ impl InterruptArch for X86_64InterruptArch {
     }
 
     fn ack_bad_irq(irq: IrqNumber) {
-        kerror!("Unexpected IRQ trap at vector {}", irq.data());
+        error!("Unexpected IRQ trap at vector {}", irq.data());
         CurrentApic.send_eoi();
     }
 
@@ -132,6 +132,12 @@ 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 {

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

@@ -26,6 +26,7 @@ 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) {
-    kerror!(
+    error!(
         "do_divide_error(0), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}",
         error_code,
         regs.rsp,
@@ -126,7 +126,7 @@ unsafe extern "C" fn do_divide_error(regs: &'static TrapFrame, error_code: u64)
 /// 处理调试异常 1 #DB
 #[no_mangle]
 unsafe extern "C" fn do_debug(regs: &'static TrapFrame, error_code: u64) {
-    kerror!(
+    error!(
         "do_debug(1), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}",
         error_code,
         regs.rsp,
@@ -140,7 +140,7 @@ unsafe extern "C" fn do_debug(regs: &'static TrapFrame, error_code: u64) {
 /// 处理NMI中断 2 NMI
 #[no_mangle]
 unsafe extern "C" fn do_nmi(regs: &'static TrapFrame, error_code: u64) {
-    kerror!(
+    error!(
         "do_nmi(2), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}",
         error_code,
         regs.rsp,
@@ -154,7 +154,7 @@ unsafe extern "C" fn do_nmi(regs: &'static TrapFrame, error_code: u64) {
 /// 处理断点异常 3 #BP
 #[no_mangle]
 unsafe extern "C" fn do_int3(regs: &'static TrapFrame, error_code: u64) {
-    kerror!(
+    error!(
         "do_int3(3), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}",
         error_code,
         regs.rsp,
@@ -168,7 +168,7 @@ unsafe extern "C" fn do_int3(regs: &'static TrapFrame, error_code: u64) {
 /// 处理溢出异常 4 #OF
 #[no_mangle]
 unsafe extern "C" fn do_overflow(regs: &'static TrapFrame, error_code: u64) {
-    kerror!(
+    error!(
         "do_overflow(4), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}",
         error_code,
         regs.rsp,
@@ -182,7 +182,7 @@ unsafe extern "C" fn do_overflow(regs: &'static TrapFrame, error_code: u64) {
 /// 处理BOUND指令检查异常 5 #BR
 #[no_mangle]
 unsafe extern "C" fn do_bounds(regs: &'static TrapFrame, error_code: u64) {
-    kerror!(
+    error!(
         "do_bounds(5), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}",
         error_code,
         regs.rsp,
@@ -196,7 +196,7 @@ unsafe extern "C" fn do_bounds(regs: &'static TrapFrame, error_code: u64) {
 /// 处理未定义操作码异常 6 #UD
 #[no_mangle]
 unsafe extern "C" fn do_undefined_opcode(regs: &'static TrapFrame, error_code: u64) {
-    kerror!(
+    error!(
         "do_undefined_opcode(6), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}",
         error_code,
         regs.rsp,
@@ -210,7 +210,7 @@ unsafe extern "C" fn do_undefined_opcode(regs: &'static TrapFrame, error_code: u
 /// 处理设备不可用异常(FPU不存在) 7 #NM
 #[no_mangle]
 unsafe extern "C" fn do_dev_not_avaliable(regs: &'static TrapFrame, error_code: u64) {
-    kerror!(
+    error!(
         "do_dev_not_avaliable(7), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}",
         error_code,
         regs.rsp,
@@ -224,7 +224,7 @@ unsafe extern "C" fn do_dev_not_avaliable(regs: &'static TrapFrame, error_code:
 /// 处理双重错误 8 #DF
 #[no_mangle]
 unsafe extern "C" fn do_double_fault(regs: &'static TrapFrame, error_code: u64) {
-    kerror!(
+    error!(
         "do_double_fault(8), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}",
         error_code,
         regs.rsp,
@@ -238,7 +238,7 @@ unsafe extern "C" fn do_double_fault(regs: &'static TrapFrame, error_code: u64)
 /// 处理协处理器段越界 9 #MF
 #[no_mangle]
 unsafe extern "C" fn do_coprocessor_segment_overrun(regs: &'static TrapFrame, error_code: u64) {
-    kerror!(
+    error!(
         "do_coprocessor_segment_overrun(9), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}",
         error_code,
         regs.rsp,
@@ -272,7 +272,7 @@ unsafe extern "C" fn do_invalid_TSS(regs: &'static TrapFrame, error_code: u64) {
         ERR_MSG_4
     };
 
-    kerror!(
+    error!(
         "do_invalid_TSS(10), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}\n{}{}",
         error_code,
         regs.rsp,
@@ -288,7 +288,7 @@ unsafe extern "C" fn do_invalid_TSS(regs: &'static TrapFrame, error_code: u64) {
 /// 处理段不存在 11 #NP
 #[no_mangle]
 unsafe extern "C" fn do_segment_not_exists(regs: &'static TrapFrame, error_code: u64) {
-    kerror!(
+    error!(
         "do_segment_not_exists(11), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}",
         error_code,
         regs.rsp,
@@ -302,7 +302,7 @@ unsafe extern "C" fn do_segment_not_exists(regs: &'static TrapFrame, error_code:
 /// 处理栈段错误 12 #SS
 #[no_mangle]
 unsafe extern "C" fn do_stack_segment_fault(regs: &'static TrapFrame, error_code: u64) {
-    kerror!(
+    error!(
         "do_stack_segment_fault(12), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}",
         error_code,
         regs.rsp,
@@ -343,7 +343,7 @@ unsafe extern "C" fn do_general_protection(regs: &'static TrapFrame, error_code:
     } else {
         ""
     };
-    kerror!(
+    error!(
         "do_general_protection(13), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t rflags: {:#x}\t CPU: {}, \tpid: {:?}
 {}{}{}
 Segment Selector Index: {:#x}\n
@@ -363,7 +363,7 @@ Segment Selector Index: {:#x}\n
 /// 处理页错误 14 #PF
 #[no_mangle]
 unsafe extern "C" fn do_page_fault(regs: &'static TrapFrame, error_code: u64) {
-    // kerror!(
+    // error!(
     //     "do_page_fault(14), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}, \nFault Address: {:#x}",
     //     error_code,
     //     regs.rsp,
@@ -401,7 +401,7 @@ unsafe extern "C" fn do_page_fault(regs: &'static TrapFrame, error_code: u64) {
     // panic!("Page Fault");
     CurrentIrqArch::interrupt_disable();
     let address = x86::controlregs::cr2();
-    // crate::kinfo!(
+    // log::info!(
     //     "fault address: {:#x}, error_code: {:#b}, pid: {}\n",
     //     address,
     //     error_code,
@@ -421,7 +421,7 @@ unsafe extern "C" fn do_page_fault(regs: &'static TrapFrame, error_code: u64) {
 /// 处理x87 FPU错误 16 #MF
 #[no_mangle]
 unsafe extern "C" fn do_x87_FPU_error(regs: &'static TrapFrame, error_code: u64) {
-    kerror!(
+    error!(
         "do_x87_FPU_error(16), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}",
         error_code,
         regs.rsp,
@@ -435,7 +435,7 @@ unsafe extern "C" fn do_x87_FPU_error(regs: &'static TrapFrame, error_code: u64)
 /// 处理对齐检查 17 #AC
 #[no_mangle]
 unsafe extern "C" fn do_alignment_check(regs: &'static TrapFrame, error_code: u64) {
-    kerror!(
+    error!(
         "do_alignment_check(17), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}",
         error_code,
         regs.rsp,
@@ -449,7 +449,7 @@ unsafe extern "C" fn do_alignment_check(regs: &'static TrapFrame, error_code: u6
 /// 处理机器检查 18 #MC
 #[no_mangle]
 unsafe extern "C" fn do_machine_check(regs: &'static TrapFrame, error_code: u64) {
-    kerror!(
+    error!(
         "do_machine_check(18), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}",
         error_code,
         regs.rsp,
@@ -463,7 +463,7 @@ unsafe extern "C" fn do_machine_check(regs: &'static TrapFrame, error_code: u64)
 /// 处理SIMD异常 19 #XM
 #[no_mangle]
 unsafe extern "C" fn do_SIMD_exception(regs: &'static TrapFrame, error_code: u64) {
-    kerror!(
+    error!(
         "do_SIMD_exception(19), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}",
         error_code,
         regs.rsp,
@@ -477,7 +477,7 @@ unsafe extern "C" fn do_SIMD_exception(regs: &'static TrapFrame, error_code: u64
 /// 处理虚拟化异常 20 #VE
 #[no_mangle]
 unsafe extern "C" fn do_virtualization_exception(regs: &'static TrapFrame, error_code: u64) {
-    kerror!(
+    error!(
         "do_virtualization_exception(20), \tError code: {:#x},\trsp: {:#x},\trip: {:#x},\t CPU: {}, \tpid: {:?}",
         error_code,
         regs.rsp,
@@ -490,5 +490,5 @@ unsafe extern "C" fn do_virtualization_exception(regs: &'static TrapFrame, error
 
 #[no_mangle]
 unsafe extern "C" fn ignore_int_handler(_regs: &'static TrapFrame, _error_code: u64) {
-    kwarn!("Unknown interrupt.");
+    warn!("Unknown interrupt.");
 }

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

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

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