实现unified-init库,支持收集初始化函数到一个数组,并统一初始化 (#474)

* 添加“统一初始化”的过程宏,并把SystemError独立成crate

* 使用unified-init来初始化fbmem

* 更新workflow,增加内核自动化静态测试
This commit is contained in:
LoGin 2023-12-25 23:12:27 +08:00 committed by GitHub
parent f110d330d5
commit 91e9d4ab55
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
158 changed files with 1102 additions and 610 deletions

View File

@ -42,6 +42,14 @@ jobs:
~/.bashrc
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ env.dadk_version }}-${{ hashFiles('.github/workflows/cache-toolchain.yml') }}
- name: Format check
run: |
printf "\n" >> kernel/src/include/bindings/bindings.rs
printf "\n" >> user/libs/libc/src/include/internal/bindings/bindings.rs
FMT_CHECK=1 make fmt
- name: build the DragonOS
run: bash -c "source ~/.cargo/env && export DragonOS_GCC=$HOME/opt/dragonos-gcc/gcc-x86_64-unknown-none/bin && make -j $(nproc) "
- name: Run kernel static test
run: bash -c "source ~/.cargo/env && cd kernel && make test"

View File

@ -1,38 +0,0 @@
name: Rust format check
on: [push, pull_request]
jobs:
# ensure the toolchain is cached
ensure-toolchain:
uses: ./.github/workflows/cache-toolchain.yml
fmt:
name: check
runs-on: ubuntu-latest
needs: [ensure-toolchain]
steps:
- uses: actions/checkout@v3
- name: Cache build tools
id: cache-build-tools
uses: actions/cache@v3
env:
cache-name: cache-build-tools
dadk_version: 0.1.2
with:
path: |
~/.cargo
~/.rustup
~/.bashrc
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ env.dadk_version }}-${{ hashFiles('.github/workflows/cache-toolchain.yml') }}
# 准备 bindings.rs
# 由于 bindings.rs 是在 build.rs 中生成的,而这里为了方便,直接 touch 一个空文件
- name: prepare bindings
run: |
printf "\n" >> kernel/src/include/bindings/bindings.rs
printf "\n" >> user/libs/libc/src/include/internal/bindings/bindings.rs
- name: Check format
run: |
FMT_CHECK=1 make fmt

View File

@ -9,4 +9,5 @@
lib_ui/scm
lib_ui/textui
unified-init

View File

@ -0,0 +1,54 @@
# unified-init 统一初始化库
:::{note}
本文作者:龙进 <longjin@DragonOS.org>
2023年12月25日
:::
## 1. 简介
该库位于`kernel/crates/unified-init`中.
提供统一初始化宏,用于将函数注册到统一初始化列表中. 便于统一进行初始化.
需要注意的是初始化器的数组是no_mangle的因此其命名应当遵守`模块_初始化器`的规则,防止重名导致意想不到的错误.
## 2. 用法
```rust
use system_error::SystemError;
use unified_init::define_unified_initializer_slice;
use unified_init_macros::unified_init;
/// 初始化函数都将会被放到这个列表中
define_unified_initializer_slice!(INITIALIZER_LIST);
#[unified_init(INITIALIZER_LIST)]
fn init1() -> Result<(), SystemError> {
Ok(())
}
#[unified_init(INITIALIZER_LIST)]
fn init2() -> Result<(), SystemError> {
Ok(())
}
fn main() {
assert_eq!(INITIALIZER_LIST.len(), 2);
}
```
## 3.开发
需要测试的时候可以在`main.rs`写测试代码,
然后在当前目录执行 `cargo expand --bin unified-init-expand`
就可以看到把proc macro展开后的代码了.
## 4. Maintainer
龙进 <longjin@DragonOS.org>

View File

@ -23,32 +23,33 @@ backtrace = []
# 运行时依赖项
[dependencies]
acpi = { git = "https://git.mirrors.dragonos.org/DragonOS-Community/acpi-rs.git", rev = "fb69243dcf" }
atomic_enum = "0.2.0"
bit_field = "0.10"
bitflags = "1.3.2"
bitfield-struct = "0.5.3"
virtio-drivers = { git = "https://git.mirrors.dragonos.org/DragonOS-Community/virtio-drivers.git", rev = "f1d1cbb" }
smoltcp = { git = "https://git.mirrors.dragonos.org/DragonOS-Community/smoltcp.git", rev = "9027825", default-features = false, features = ["log", "alloc", "socket-raw", "socket-udp", "socket-tcp", "socket-icmp", "socket-dhcpv4", "socket-dns", "proto-ipv4", "proto-ipv6"]}
# num-traits 0.2.15
num-traits = { git = "https://git.mirrors.dragonos.org/DragonOS-Community/num-traits.git", rev="1597c1c", default-features = false }
# 一个no_std的hashmap、hashset
elf = { version = "0.7.2", default-features = false }
hashbrown = "0.13.2"
ida = { path = "src/libs/ida" }
intertrait = { path = "src/libs/intertrait" }
kdepends = { path = "crates/kdepends" }
klog_types = { path = "crates/klog_types" }
linkme = "0.2"
num = { version = "0.4.0", default-features = false }
num-derive = "0.3"
# 一个no_std的hashmap、hashset
hashbrown = "0.13.2"
elf = { version = "0.7.2", default-features = false }
atomic_enum = "0.2.0"
num-traits = { git = "https://git.mirrors.dragonos.org/DragonOS-Community/num-traits.git", rev="1597c1c", default-features = false }
raw-cpuid = "11.0.1"
acpi = { git = "https://git.mirrors.dragonos.org/DragonOS-Community/acpi-rs.git", rev = "fb69243dcf" }
intertrait = { path = "src/libs/intertrait" }
linkme = "0.2"
ida = { path = "src/libs/ida" }
klog_types = { path = "crates/klog_types" }
kdepends = { path = "crates/kdepends" }
smoltcp = { git = "https://git.mirrors.dragonos.org/DragonOS-Community/smoltcp.git", rev = "9027825", 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/DragonOS-Community/virtio-drivers.git", rev = "f1d1cbb" }
# target为x86_64时使用下面的依赖
[target.'cfg(target_arch = "x86_64")'.dependencies]
mini-backtrace = { git = "https://git.mirrors.dragonos.org/DragonOS-Community/mini-backtrace.git", rev = "ba98506685" }
x86 = "0.52.0"
x86_64 = "0.14.10"
mini-backtrace = { git = "https://git.mirrors.dragonos.org/DragonOS-Community/mini-backtrace.git", rev = "ba98506685" }
# 构建时依赖项

View File

@ -38,3 +38,7 @@ else ifeq ($(ARCH), riscv64)
@cargo +nightly-2023-08-15 check --workspace $(CARGO_ZBUILD) --message-format=json --target ./src/$(TARGET_JSON)
endif
test:
# 测试内核库
@cargo +nightly-2023-08-15 test --workspace --exclude dragonos_kernel

View File

@ -0,0 +1,12 @@
[package]
name = "system_error"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
kdepends = { path = "../kdepends" }
num-traits = { git = "https://git.mirrors.dragonos.org/DragonOS-Community/num-traits.git", rev="1597c1c", default-features = false }
num = { version = "0.4.0", default-features = false }
num-derive = "0.3"

View File

@ -0,0 +1,312 @@
#![no_std]
use num_derive::{FromPrimitive, ToPrimitive};
#[repr(i32)]
#[derive(Debug, FromPrimitive, ToPrimitive, PartialEq, Eq, Clone)]
#[allow(dead_code, non_camel_case_types)]
pub enum SystemError {
/// 操作不被允许 Operation not permitted.
EPERM = 1,
/// 没有指定的文件或目录 No such file or directory.
ENOENT = 2,
/// 没有这样的进程 No such process.
ESRCH = 3,
/// 被中断的函数 Interrupted function.
EINTR = 4,
/// I/O错误 I/O error.
EIO = 5,
/// 没有这样的设备或地址 No such device or address.
ENXIO = 6,
/// 参数列表过长或者在输出buffer中缺少空间 或者参数比系统内建的最大值要大 Argument list too long.
E2BIG = 7,
/// 可执行文件格式错误 Executable file format error
ENOEXEC = 8,
/// 错误的文件描述符 Bad file descriptor.
EBADF = 9,
/// 没有子进程 No child processes.
ECHILD = 10,
/// 资源不可用,请重试。 Resource unavailable, try again.(may be the same value as [EWOULDBLOCK])
///
/// 操作将被禁止 Operation would block.(may be the same value as [EAGAIN]).
EAGAIN_OR_EWOULDBLOCK = 11,
/// 没有足够的空间 Not enough space.
ENOMEM = 12,
/// 访问被拒绝 Permission denied
EACCES = 13,
/// 错误的地址 Bad address
EFAULT = 14,
/// 需要块设备 Block device required
ENOTBLK = 15,
/// 设备或资源忙 Device or resource busy.
EBUSY = 16,
/// 文件已存在 File exists.
EEXIST = 17,
/// 跨设备连接 Cross-device link.
EXDEV = 18,
/// 没有指定的设备 No such device.
ENODEV = 19,
/// 不是目录 Not a directory.
ENOTDIR = 20,
/// 是一个目录 Is a directory
EISDIR = 21,
/// 不可用的参数 Invalid argument.
EINVAL = 22,
/// 系统中打开的文件过多 Too many files open in system.
ENFILE = 23,
/// 文件描述符的值过大 File descriptor value too large.
EMFILE = 24,
/// 不正确的I/O控制操作 Inappropriate I/O control operation.
ENOTTY = 25,
/// 文本文件忙 Text file busy.
ETXTBSY = 26,
/// 文件太大 File too large.
EFBIG = 27,
/// 设备上没有空间 No space left on device.
ENOSPC = 28,
/// 错误的寻道.当前文件是pipe不允许seek请求 Invalid seek.
ESPIPE = 29,
/// 只读的文件系统 Read-only file system.
EROFS = 30,
/// 链接数过多 Too many links.
EMLINK = 31,
/// 断开的管道 Broken pipe.
EPIPE = 32,
/// 数学参数超出作用域 Mathematics argument out of domain of function.
EDOM = 33,
/// 结果过大 Result too large.
ERANGE = 34,
/// 资源死锁将要发生 Resource deadlock would occur.
EDEADLK = 35,
/// 文件名过长 Filename too long.
ENAMETOOLONG = 36,
/// 没有可用的锁 No locks available.
ENOLCK = 37,
/// 功能不支持 Function not supported.
ENOSYS = 38,
/// 目录非空 Directory not empty.
ENOTEMPTY = 39,
/// 符号链接级别过多 Too many levels of symbolic links.
ELOOP = 40,
/// 没有期待类型的消息 No message of the desired type.
ENOMSG = 41,
/// 标志符被移除 Identifier removed.
EIDRM = 42,
/// 通道号超出范围 Channel number out of range
ECHRNG = 43,
/// 二级不同步 Level 2 not synchronized
EL2NSYNC = 44,
/// 三级暂停 Level 3 halted
EL3HLT = 45,
/// 三级重置 Level 3 reset
EL3RST = 46,
/// 链接号超出范围 Link number out of range
ELNRNG = 47,
/// 未连接协议驱动程序 Protocol driver not attached
EUNATCH = 48,
/// 没有可用的CSI结构 No CSI structure available
ENOCSI = 49,
/// 二级暂停 Level 2 halted
EL2HLT = 50,
/// 无效交换 Invalid exchange
EBADE = 51,
/// 无效的请求描述符 Invalid request descriptor
EBADR = 52,
/// 交换满 Exchange full
EXFULL = 53,
/// 无阳极 No anode
ENOANO = 54,
/// 请求码无效 Invalid request code
EBADRQC = 55,
/// 无效插槽 Invalid slot
EBADSLT = 56,
/// 资源死锁 Resource deadlock would occur
EDEADLOCK = 57,
/// 错误的字体文件格式 Bad font file format
EBFONT = 58,
/// 不是STREAM Not a STREAM
ENOSTR = 59,
/// 队列头没有可读取的消息 No message is available on the STREAM head read queue.
ENODATA = 60,
/// 流式ioctl()超时 Stream ioctl() timeout
ETIME = 61,
/// 没有STREAM资源 No STREAM resources.
ENOSR = 62,
/// 机器不在网络上 Machine is not on the network
ENONET = 63,
/// 未安装软件包 Package not installed
ENOPKG = 64,
/// 远程对象 Object is remote
EREMOTE = 65,
/// 保留 Reserved.
ENOLINK = 66,
/// 外设错误 Advertise error.
EADV = 67,
/// 安装错误 Srmount error
ESRMNT = 68,
/// 发送时发生通信错误 Communication error on send
ECOMM = 69,
/// 协议错误 Protocol error.
EPROTO = 70,
/// 保留使用 Reserved.
EMULTIHOP = 71,
/// RFS特定错误 RFS specific error
EDOTDOT = 72,
/// 错误的消息 Bad message.
EBADMSG = 73,
/// 数值过大,产生溢出 Value too large to be stored in data type.
EOVERFLOW = 74,
/// 名称在网络上不是唯一的 Name not unique on network
ENOTUNIQ = 75,
/// 处于不良状态的文件描述符 File descriptor in bad state
EBADFD = 76,
/// 远程地址已更改 Remote address changed
EREMCHG = 77,
/// 无法访问所需的共享库 Can not access a needed shared library
ELIBACC = 78,
/// 访问损坏的共享库 Accessing a corrupted shared library
ELIBBAD = 79,
/// a. out中的.lib部分已损坏 .lib section in a.out corrupted
ELIBSCN = 80,
/// 尝试链接太多共享库 Attempting to link in too many shared libraries
ELIBMAX = 81,
/// 无法直接执行共享库 Cannot exec a shared library directly
ELIBEXEC = 82,
/// 不合法的字符序列 Illegal byte sequence.
EILSEQ = 83,
/// 中断的系统调用应该重新启动 Interrupted system call should be restarted
ERESTART = 84,
/// 流管道错误 Streams pipe error
ESTRPIPE = 85,
/// 用户太多 Too many users
EUSERS = 86,
/// 不是一个套接字 Not a socket.
ENOTSOCK = 87,
/// 需要目标地址 Destination address required.
EDESTADDRREQ = 88,
/// 消息过大 Message too large.
EMSGSIZE = 89,
/// 对于套接字而言,错误的协议 Protocol wrong type for socket.
EPROTOTYPE = 90,
/// 协议不可用 Protocol not available.
ENOPROTOOPT = 91,
/// 协议不被支持 Protocol not supported.
EPROTONOSUPPORT = 92,
/// 不支持套接字类型 Socket type not supported
ESOCKTNOSUPPORT = 93,
/// 套接字不支持该操作 Operation not supported on socket (may be the same value as [ENOTSUP]).
///
/// 不被支持 Not supported (may be the same value as [EOPNOTSUPP]).
EOPNOTSUPP_OR_ENOTSUP = 94,
/// 不支持协议系列 Protocol family not supported
EPFNOSUPPORT = 95,
/// 地址family不支持 Address family not supported.
EAFNOSUPPORT = 96,
/// 地址正在被使用 Address in use.
EADDRINUSE = 97,
/// 地址不可用 Address not available.
EADDRNOTAVAIL = 98,
/// 网络已关闭 Network is down.
ENETDOWN = 99,
/// 网络不可达 Network unreachable.
ENETUNREACH = 100,
/// 网络连接已断开 Connection aborted by network.
ENETRESET = 101,
/// 连接已断开 Connection aborted.
ECONNABORTED = 102,
/// 连接被重置 Connection reset.
ECONNRESET = 103,
/// 缓冲区空间不足 No buffer space available.
ENOBUFS = 104,
/// 套接字已连接 Socket is connected.
EISCONN = 105,
/// 套接字未连接 The socket is not connected.
ENOTCONN = 106,
/// 传输端点关闭后无法发送 Cannot send after transport endpoint shutdown
ESHUTDOWN = 107,
/// 引用太多:无法拼接 Too many references: cannot splice
ETOOMANYREFS = 108,
/// 连接超时 Connection timed out.
ETIMEDOUT = 109,
/// 连接被拒绝 Connection refused.
ECONNREFUSED = 110,
/// 主机已关闭 Host is down
EHOSTDOWN = 111,
/// 主机不可达 Host is unreachable.
EHOSTUNREACH = 112,
/// 连接已经在处理 Connection already in progress.
EALREADY = 113,
/// 操作正在处理 Operation in progress.
EINPROGRESS = 114,
/// 保留 Reserved.
ESTALE = 115,
/// 结构需要清理 Structure needs cleaning
EUCLEAN = 116,
/// 不是XENIX命名类型文件 Not a XENIX named type file
ENOTNAM = 117,
/// 没有可用的XENIX信号量 No XENIX semaphores available
ENAVAIL = 118,
/// 是命名类型文件 Is a named type file
EISNAM = 119,
/// 远程I/O错误 Remote I/O error
EREMOTEIO = 120,
/// 保留使用 Reserved
EDQUOT = 121,
/// 没有找到媒介 No medium found
ENOMEDIUM = 122,
/// 介质类型错误 Wrong medium type
EMEDIUMTYPE = 123,
/// 操作被取消 Operation canceled.
ECANCELED = 124,
/// 所需的密钥不可用 Required key not available
ENOKEY = 125,
/// 密钥已过期 Key has expired
EKEYEXPIRED = 126,
/// 密钥已被撤销 Key has been revoked
EKEYREVOKED = 127,
/// 密钥被服务拒绝 Key has been revoked
EKEYREJECTED = 128,
/// 之前的拥有者挂了 Previous owner died.
EOWNERDEAD = 129,
/// 状态不可恢复 State not recoverable.
ENOTRECOVERABLE = 130,
// VMX on 虚拟化开启指令出错
EVMXONFailed = 131,
// VMX off 虚拟化关闭指令出错
EVMXOFFFailed = 132,
// VMX VMWRITE 写入虚拟化VMCS内存出错
EVMWRITEFailed = 133,
EVMREADFailed = 134,
EVMPRTLDFailed = 135,
EVMLAUNCHFailed = 136,
KVM_HVA_ERR_BAD = 137,
// === 以下错误码不应该被用户态程序使用 ===
ERESTARTSYS = 512,
}
impl SystemError {
/// @brief 把posix错误码转换为系统错误枚举类型。
pub fn from_posix_errno(errno: i32) -> Option<SystemError> {
// posix 错误码是小于0的
if errno >= 0 {
return None;
}
return <Self as num_traits::FromPrimitive>::from_i32(-errno);
}
/// @brief 把系统错误枚举类型转换为负数posix错误码。
pub fn to_posix_errno(&self) -> i32 {
return -<Self as num_traits::ToPrimitive>::to_i32(self).unwrap();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
assert_eq!(SystemError::EPERM.to_posix_errno(), -1);
}
}

View File

@ -0,0 +1,14 @@
[package]
name = "unified-init"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[[bin]]
name = "unified-init-expand"
path = "src/main.rs"
[dependencies]
unified-init-macros = { path = "macros" }
linkme = "0.2"
system_error = { path = "../system_error" }

View File

@ -0,0 +1,20 @@
[package]
name = "unified-init-macros"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
proc-macro = true
[dependencies]
proc-macro2 = "1.0.71"
quote = "1.0.33"
syn = { version = "2.0.42", features = ["full"] }
uuid = { version = "0.8", features = ["v4"] }
[dev-dependencies]
unified-init = { path = ".." }
linkme = "0.2"
system_error = { path = "../../system_error" }

View File

@ -0,0 +1,230 @@
extern crate alloc;
extern crate quote;
use proc_macro::TokenStream;
use quote::quote;
use syn::{
__private::ToTokens,
parse::{self, Parse, ParseStream},
spanned::Spanned,
ItemFn, Path,
};
use uuid::Uuid;
/// 统一初始化宏,
/// 用于将函数注册到统一初始化列表中
///
/// ## 用法
///
/// ```rust
/// use system_error::SystemError;
/// use unified_init::define_unified_initializer_slice;
/// use unified_init_macros::unified_init;
///
/// /// 初始化函数都将会被放到这个列表中
/// define_unified_initializer_slice!(INITIALIZER_LIST);
///
/// #[unified_init(INITIALIZER_LIST)]
/// fn init1() -> Result<(), SystemError> {
/// Ok(())
/// }
///
/// #[unified_init(INITIALIZER_LIST)]
/// fn init2() -> Result<(), SystemError> {
/// Ok(())
/// }
///
/// fn main() {
/// assert_eq!(INITIALIZER_LIST.len(), 2);
/// }
///
/// ```
#[proc_macro_attribute]
pub fn unified_init(args: TokenStream, input: TokenStream) -> TokenStream {
do_unified_init(args, input)
.unwrap_or_else(|e| e.to_compile_error().into())
.into()
}
fn do_unified_init(args: TokenStream, input: TokenStream) -> syn::Result<proc_macro2::TokenStream> {
// 解析属性数
let attr_arg = syn::parse::<UnifiedInitArg>(args)?;
// 获取当前函数
let function = syn::parse::<ItemFn>(input)?;
// 检查函数签名
check_function_signature(&function)?;
// 添加#[::linkme::distributed_slice(attr_args.initializer_instance)]属性
let target_slice = attr_arg.initializer_instance.get_ident().unwrap();
// 在旁边添加一个UnifiedInitializer
let initializer =
generate_unified_initializer(&function, &target_slice, function.sig.ident.to_string())?;
// 拼接
let mut output = proc_macro2::TokenStream::new();
output.extend(function.into_token_stream());
output.extend(initializer);
Ok(output)
}
/// 检查函数签名是否满足要求
/// 函数签名应该为
///
/// ```rust
/// use system_error::SystemError;
/// fn xxx() -> Result<(), SystemError> {
/// Ok(())
/// }
/// ```
fn check_function_signature(function: &ItemFn) -> syn::Result<()> {
// 检查函数签名
if function.sig.inputs.len() != 0 {
return Err(syn::Error::new(
function.sig.inputs.span(),
"Expected no arguments",
));
}
if let syn::ReturnType::Type(_, ty) = &function.sig.output {
// 确认返回类型为 Result<(), SystemError>
// 解析类型
let output_type: syn::Type = syn::parse2(ty.clone().into_token_stream())?;
// 检查类型是否为 Result<(), SystemError>
if let syn::Type::Path(type_path) = output_type {
if type_path.path.segments.last().unwrap().ident == "Result" {
// 检查泛型参数,看看是否满足 Result<(), SystemError>
if let syn::PathArguments::AngleBracketed(generic_args) =
type_path.path.segments.last().unwrap().arguments.clone()
{
if generic_args.args.len() != 2 {
return Err(syn::Error::new(
generic_args.span(),
"Expected two generic arguments",
));
}
// 检查第一个泛型参数是否为()
if let syn::GenericArgument::Type(type_arg) = generic_args.args.first().unwrap()
{
if let syn::Type::Tuple(tuple) = type_arg {
if tuple.elems.len() != 0 {
return Err(syn::Error::new(tuple.span(), "Expected empty tuple"));
}
} else {
return Err(syn::Error::new(type_arg.span(), "Expected empty tuple"));
}
} else {
return Err(syn::Error::new(
generic_args.span(),
"Expected first generic argument to be a type",
));
}
// 检查第二个泛型参数是否为SystemError
if let syn::GenericArgument::Type(type_arg) = generic_args.args.last().unwrap()
{
if let syn::Type::Path(type_path) = type_arg {
if type_path.path.segments.last().unwrap().ident == "SystemError" {
// 类型匹配,返回 Ok
return Ok(());
}
}
} else {
return Err(syn::Error::new(
generic_args.span(),
"Expected second generic argument to be a type",
));
}
return Err(syn::Error::new(
generic_args.span(),
"Expected second generic argument to be SystemError",
));
}
return Ok(());
}
}
}
Err(syn::Error::new(
function.sig.output.span(),
"Expected -> Result<(), SystemError>",
))
}
/// 生成UnifiedInitializer全局变量
fn generate_unified_initializer(
function: &ItemFn,
target_slice: &syn::Ident,
raw_initializer_name: String,
) -> syn::Result<proc_macro2::TokenStream> {
let initializer_name = format!(
"unified_initializer_{}_{}",
raw_initializer_name,
Uuid::new_v4().to_simple().to_string().to_ascii_uppercase()[..8].to_string()
)
.to_ascii_uppercase();
// 获取函数的全名
let initializer_name_ident = syn::Ident::new(&initializer_name, function.sig.ident.span());
let function_ident = &function.sig.ident;
// 生成UnifiedInitializer
let initializer = quote! {
#[::linkme::distributed_slice(#target_slice)]
static #initializer_name_ident: unified_init::UnifiedInitializer = ::unified_init::UnifiedInitializer::new(#raw_initializer_name, &(#function_ident as ::unified_init::UnifiedInitFunction));
};
Ok(initializer)
}
struct UnifiedInitArg {
initializer_instance: Path,
}
impl Parse for UnifiedInitArg {
fn parse(input: ParseStream) -> parse::Result<Self> {
let mut initializer_instance = None;
while !input.is_empty() {
if initializer_instance.is_some() {
return Err(parse::Error::new(
input.span(),
"Expected exactly one initializer instance",
));
}
// 解析Ident
let ident = input.parse::<syn::Ident>()?;
// 将Ident转换为Path
let initializer = syn::Path::from(ident);
initializer_instance = Some(initializer);
}
if initializer_instance.is_none() {
return Err(parse::Error::new(
input.span(),
"Expected exactly one initializer instance",
));
}
// 判断是否为标识符
if initializer_instance.as_ref().unwrap().get_ident().is_none() {
return Err(parse::Error::new(
initializer_instance.span(),
"Expected identifier",
));
}
Ok(UnifiedInitArg {
initializer_instance: initializer_instance.unwrap(),
})
}
}

View File

@ -0,0 +1,72 @@
#![no_std]
use system_error::SystemError;
pub use unified_init_macros as macros;
/// 统一初始化器
#[derive(Debug)]
pub struct UnifiedInitializer {
function: &'static UnifiedInitFunction,
name: &'static str,
}
impl UnifiedInitializer {
pub const fn new(
name: &'static str,
function: &'static UnifiedInitFunction,
) -> UnifiedInitializer {
UnifiedInitializer { function, name }
}
/// 调用初始化函数
pub fn call(&self) -> Result<(), SystemError> {
(self.function)()
}
/// 获取初始化函数的名称
pub const fn name(&self) -> &'static str {
self.name
}
}
pub type UnifiedInitFunction = fn() -> core::result::Result<(), SystemError>;
/// 定义统一初始化器的分布式切片数组(私有)
#[macro_export]
macro_rules! define_unified_initializer_slice {
($name:ident) => {
#[::linkme::distributed_slice]
static $name: [::unified_init::UnifiedInitializer] = [..];
};
() => {
compile_error!(
"define_unified_initializer_slice! requires at least one argument: slice_name"
);
};
}
/// 定义统一初始化器的分布式切片数组(公开)
#[macro_export]
macro_rules! define_public_unified_initializer_slice {
($name:ident) => {
#[::linkme::distributed_slice]
pub static $name: [::unified_init::UnifiedInitializer] = [..];
};
() => {
compile_error!(
"define_unified_initializer_slice! requires at least one argument: slice_name"
);
};
}
/// 调用指定数组中的所有初始化器
#[macro_export]
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);
});
}
};
}

View File

@ -0,0 +1,63 @@
//! 需要测试的时候可以在这里写测试代码,
//! 然后在当前目录执行 `cargo expand --bin unified-init-expand`
//! 就可以看到把proc macro展开后的代码了
#![no_std]
fn main() {
todo!()
}
#[cfg(test)]
mod tests {
use system_error::SystemError;
use unified_init::define_unified_initializer_slice;
use unified_init_macros::unified_init;
use super::*;
#[test]
fn no_element() {
define_unified_initializer_slice!(TEST_0);
assert_eq!(TEST_0.len(), 0);
}
#[test]
fn no_element_ne() {
define_unified_initializer_slice!(TEST_0_NE);
#[unified_init(TEST_0_NE)]
fn x() -> Result<(), SystemError> {
todo!()
}
assert_ne!(TEST_0_NE.len(), 0);
}
#[test]
fn one_element() {
define_unified_initializer_slice!(TEST_1);
#[unified_init(TEST_1)]
fn x() -> Result<(), SystemError> {
todo!()
}
assert_eq!(TEST_1.len(), 1);
}
#[test]
fn two_elements() {
define_unified_initializer_slice!(TEST_2);
#[unified_init(TEST_2)]
fn x() -> Result<(), SystemError> {
todo!()
}
#[unified_init(TEST_2)]
fn y() -> Result<(), SystemError> {
todo!()
}
assert_eq!(TEST_2.len(), 2);
}
}

View File

@ -1,6 +1,4 @@
use alloc::sync::Arc;
use crate::{libs::mutex::Mutex, syscall::SystemError};
use system_error::SystemError;
#[derive(Debug, Clone, Default)]
pub struct RiscV64KVMArch {}

View File

@ -1,3 +1,5 @@
use system_error::SystemError;
use crate::mm::{
allocator::page_frame::{FrameAllocator, PageFrameCount, PageFrameUsage},
page::PageFlags,
@ -79,8 +81,7 @@ impl MemoryManagementArch for RiscV64MMArch {
todo!()
}
fn setup_new_usermapper() -> Result<crate::mm::ucontext::UserMapper, crate::syscall::SystemError>
{
fn setup_new_usermapper() -> Result<crate::mm::ucontext::UserMapper, SystemError> {
todo!()
}
}

View File

@ -1,12 +1,10 @@
use alloc::sync::Arc;
use system_error::SystemError;
use crate::{
process::{
fork::CloneFlags,
kthread::{KernelThreadCreateInfo, KernelThreadMechanism},
Pid,
},
syscall::SystemError,
use crate::process::{
fork::CloneFlags,
kthread::{KernelThreadCreateInfo, KernelThreadMechanism},
Pid,
};
impl KernelThreadMechanism {

View File

@ -1,9 +1,7 @@
use alloc::{string::String, sync::Arc, vec::Vec};
use system_error::SystemError;
use crate::{
process::{fork::KernelCloneArgs, KernelStack, ProcessControlBlock, ProcessManager},
syscall::SystemError,
};
use crate::process::{fork::KernelCloneArgs, KernelStack, ProcessControlBlock, ProcessManager};
use super::interrupt::TrapFrame;

View File

@ -1,9 +1,7 @@
use alloc::{string::String, vec::Vec};
use system_error::SystemError;
use crate::{
arch::interrupt::TrapFrame,
syscall::{Syscall, SystemError},
};
use crate::{arch::interrupt::TrapFrame, syscall::Syscall};
impl Syscall {
pub fn do_execve(

View File

@ -1,6 +1,8 @@
/// 系统调用号
pub mod nr;
use crate::{exception::InterruptArch, syscall::SystemError};
use system_error::SystemError;
use crate::exception::InterruptArch;
use super::{interrupt::TrapFrame, CurrentIrqArch};

View File

@ -1,4 +1,6 @@
use crate::{driver::acpi::acpi_manager, kinfo, mm::percpu::PerCpu, syscall::SystemError};
use system_error::SystemError;
use crate::{driver::acpi::acpi_manager, kinfo, mm::percpu::PerCpu};
use super::smp::SMP_BOOT_DATA;

View File

@ -7,9 +7,9 @@ use crate::kdebug;
use crate::mm::percpu::PerCpu;
use crate::sched::core::sched_update_jiffies;
use crate::smp::core::smp_get_processor_id;
use crate::syscall::SystemError;
use crate::time::clocksource::HZ;
pub use drop;
use system_error::SystemError;
use x86::cpuid::cpuid;
use x86::msr::{wrmsr, IA32_X2APIC_DIV_CONF, IA32_X2APIC_INIT_COUNT};

View File

@ -3,6 +3,7 @@ use core::ptr::NonNull;
use acpi::madt::Madt;
use bit_field::BitField;
use bitflags::bitflags;
use system_error::SystemError;
use crate::{
driver::acpi::acpi_manager,
@ -16,7 +17,6 @@ use crate::{
mmio_buddy::{mmio_pool, MMIOSpaceGuard},
PhysAddr,
},
syscall::SystemError,
};
use super::{CurrentApic, LocalAPIC};

View File

@ -1,6 +1,7 @@
use core::sync::atomic::Ordering;
use atomic_enum::atomic_enum;
use system_error::SystemError;
use x86::{apic::Icr, msr::IA32_APIC_BASE};
use crate::{
@ -12,7 +13,6 @@ use crate::{
kdebug, kinfo,
mm::PhysAddr,
smp::core::smp_get_processor_id,
syscall::SystemError,
};
use self::{

View File

@ -7,6 +7,7 @@ use core::{
};
use acpi::HpetInfo;
use system_error::SystemError;
use crate::{
driver::{
@ -23,7 +24,6 @@ use crate::{
mmio_buddy::{mmio_pool, MMIOSpaceGuard},
PhysAddr,
},
syscall::SystemError,
time::timer::{clock, timer_get_first_expire, update_timer_jiffies},
};

View File

@ -1,16 +1,15 @@
use core::{
cmp::{max, min},
intrinsics::unlikely,
};
use crate::{
arch::{io::PortIOArch, CurrentIrqArch, CurrentPortIOArch, CurrentTimeArch},
driver::acpi::pmtmr::{ACPI_PM_OVERRUN, PMTMR_TICKS_PER_SEC},
exception::InterruptArch,
kdebug, kerror, kinfo, kwarn,
syscall::SystemError,
time::TimeArch,
};
use core::{
cmp::{max, min},
intrinsics::unlikely,
};
use system_error::SystemError;
use super::hpet::hpet_instance;

View File

@ -1,3 +1,4 @@
use system_error::SystemError;
use x86::apic::ApicId;
use crate::{
@ -6,7 +7,6 @@ use crate::{
smp::SMP_BOOT_DATA,
},
exception::ipi::{IpiKind, IpiTarget},
syscall::SystemError,
};
/// IPI的种类(架构相关,指定了向量号)

View File

@ -1,5 +1,7 @@
use core::{ffi::c_void, intrinsics::unlikely, mem::size_of};
use system_error::SystemError;
use crate::{
arch::{
fpu::FpState,
@ -16,7 +18,7 @@ use crate::{
kerror,
mm::MemoryManagementArch,
process::ProcessManager,
syscall::{user_access::UserBufferWriter, Syscall, SystemError},
syscall::{user_access::UserBufferWriter, Syscall},
};
/// 信号处理的栈的栈指针的最小对齐数量

View File

@ -6,11 +6,11 @@ use crate::{
kdebug,
kerror,
// libs::spinlock::{SpinLock, SpinLockGuard},
syscall::SystemError,
};
use alloc::sync::Arc;
use core::arch::asm;
use raw_cpuid::CpuId;
use system_error::SystemError;
// use crate::virt::kvm::guest_code;
use self::vmx::mmu::{kvm_mmu_setup, kvm_vcpu_mtrr_init};
use self::vmx::vcpu::VmxVcpu;

View File

@ -1,10 +1,11 @@
use crate::arch::mm::LockedFrameAllocator;
use crate::arch::mm::PageMapper;
use crate::arch::MMArch;
use crate::mm::page::PageFlags;
use crate::mm::{PageTableKind, PhysAddr, VirtAddr};
use crate::smp::core::smp_get_processor_id;
use crate::{arch::mm::LockedFrameAllocator, syscall::SystemError};
use core::sync::atomic::{compiler_fence, AtomicUsize, Ordering};
use system_error::SystemError;
use x86::msr;
/// Check if MTRR is supported

View File

@ -3,10 +3,10 @@ use crate::{
kdebug,
libs::mutex::Mutex,
mm::{page::PageFlags, syscall::ProtFlags},
syscall::SystemError,
virt::kvm::host_mem::{__gfn_to_pfn, kvm_vcpu_gfn_to_memslot, PAGE_MASK, PAGE_SHIFT},
};
use bitfield_struct::bitfield;
use system_error::SystemError;
use super::{
ept::check_ept_features,

View File

@ -22,7 +22,7 @@ use crate::arch::kvm::VmcsFields::{
use crate::arch::kvm::VmcsFields::{
GUEST_TR_ACCESS_RIGHTS, GUEST_TR_BASE, GUEST_TR_LIMIT, GUEST_TR_SELECTOR,
};
use crate::syscall::SystemError;
use system_error::SystemError;
use super::vmx_asm_wrapper::vmx_vmwrite;

View File

@ -12,13 +12,13 @@ use crate::arch::MMArch;
use crate::kdebug;
use crate::mm::{phys_2_virt, VirtAddr};
use crate::mm::{MemoryManagementArch, PageTableKind};
use crate::syscall::SystemError;
use crate::virt::kvm::vcpu::Vcpu;
use crate::virt::kvm::vm::Vm;
use alloc::alloc::Global;
use alloc::boxed::Box;
use core::slice;
use raw_cpuid::CpuId;
use system_error::SystemError;
use x86;
use x86::{controlregs, msr, segmentation};
// use crate::arch::kvm::vmx::seg::RMODE_TSS_SIZE;

View File

@ -1,8 +1,9 @@
use super::vmcs::{VmcsFields, VmxExitReason};
use super::vmx_asm_wrapper::{vmx_vmread, vmx_vmwrite};
use crate::kdebug;
use crate::{syscall::SystemError, virt::kvm::vm};
use crate::virt::kvm::vm;
use core::arch::asm;
use system_error::SystemError;
use x86::vmx::vmcs::ro::GUEST_PHYSICAL_ADDR_FULL;
#[derive(FromPrimitive)]

View File

@ -1,7 +1,7 @@
use super::vmcs::VmcsFields;
use crate::kdebug;
use crate::syscall::SystemError;
use core::arch::asm;
use system_error::SystemError;
use x86;
/// Enable VMX operation.
pub fn vmxon(vmxon_pa: u64) -> Result<(), SystemError> {

View File

@ -27,8 +27,8 @@ use crate::{
use crate::mm::kernel_mapper::KernelMapper;
use crate::mm::page::{PageEntry, PageFlags};
use crate::mm::{MemoryManagementArch, PageTableKind, PhysAddr, PhysMemoryArea, VirtAddr};
use crate::syscall::SystemError;
use crate::{kdebug, kinfo};
use system_error::SystemError;
use core::arch::asm;
use core::ffi::c_void;

View File

@ -1,6 +1,7 @@
use core::arch::asm;
use alloc::sync::Arc;
use system_error::SystemError;
use crate::{
arch::{
@ -12,7 +13,6 @@ use crate::{
kthread::{kernel_thread_bootstrap_stage2, KernelThreadCreateInfo, KernelThreadMechanism},
Pid, ProcessManager,
},
syscall::SystemError,
};
impl KernelThreadMechanism {

View File

@ -12,6 +12,7 @@ use alloc::{
};
use kdepends::memoffset::offset_of;
use system_error::SystemError;
use x86::{controlregs::Cr4, segmentation::SegmentSelector};
use crate::{
@ -28,7 +29,7 @@ use crate::{
KernelStack, ProcessControlBlock, ProcessFlags, ProcessManager, SwitchResult,
SWITCH_RESULT,
},
syscall::{Syscall, SystemError},
syscall::Syscall,
};
use self::{

View File

@ -1,4 +1,5 @@
use alloc::{string::String, sync::Arc, vec::Vec};
use system_error::SystemError;
use crate::{
arch::{
@ -12,7 +13,7 @@ use crate::{
exec::{load_binary_file, ExecParam, ExecParamFlags},
ProcessControlBlock, ProcessManager,
},
syscall::{user_access::UserBufferWriter, Syscall, SystemError},
syscall::{user_access::UserBufferWriter, Syscall},
};
impl Syscall {

View File

@ -1,4 +1,4 @@
use crate::syscall::SystemError;
use system_error::SystemError;
use super::{acpi::early_acpi_boot_init, smp::X86_64_SMP_MANAGER};

View File

@ -5,11 +5,12 @@ use core::{
};
use kdepends::memoffset::offset_of;
use system_error::SystemError;
use crate::{
arch::process::table::TSSManager, exception::InterruptArch,
include::bindings::bindings::cpu_core_info, kdebug, libs::rwlock::RwLock, mm::percpu::PerCpu,
process::ProcessManager, smp::core::smp_get_processor_id, syscall::SystemError,
process::ProcessManager, smp::core::smp_get_processor_id,
};
use super::CurrentIrqArch;

View File

@ -12,9 +12,10 @@ use crate::{
libs::align::SafeForZero,
mm::VirtAddr,
process::ProcessManager,
syscall::{Syscall, SystemError, SYS_SCHED},
syscall::{Syscall, SYS_SCHED},
};
use alloc::string::String;
use system_error::SystemError;
use super::{interrupt::TrapFrame, mm::barrier::mfence};

View File

@ -1,19 +1,16 @@
use crate::driver::base::{
device::{
bus::{bus_manager, Bus},
driver::Driver,
Device,
},
subsys::SubSysPrivate,
};
use alloc::{
string::{String, ToString},
sync::Arc,
};
use crate::{
driver::base::{
device::{
bus::{bus_manager, Bus},
driver::Driver,
Device,
},
subsys::SubSysPrivate,
},
syscall::SystemError,
};
use system_error::SystemError;
use super::AcpiManager;

View File

@ -12,8 +12,8 @@ use crate::{
mmio_buddy::{mmio_pool, MMIOSpaceGuard},
MemoryManagementArch, PhysAddr, VirtAddr,
},
syscall::SystemError,
};
use system_error::SystemError;
use super::base::kset::KSet;

View File

@ -1,10 +1,3 @@
use acpi::sdt::SdtHeader;
use alloc::{
string::{String, ToString},
sync::Arc,
vec::Vec,
};
use crate::{
driver::{
acpi::acpi_manager,
@ -15,8 +8,14 @@ use crate::{
vfs::syscall::ModeType,
},
libs::rwlock::RwLock,
syscall::SystemError,
};
use acpi::sdt::SdtHeader;
use alloc::{
string::{String, ToString},
sync::Arc,
vec::Vec,
};
use system_error::SystemError;
use super::{acpi_kset, AcpiManager};

View File

@ -8,10 +8,11 @@ use crate::{
},
},
kerror,
syscall::SystemError,
};
use alloc::{sync::Arc, vec::Vec};
use core::any::Any;
use system_error::SystemError;
use super::disk_info::Partition;

View File

@ -1,6 +1,7 @@
use alloc::sync::Arc;
use crate::{kerror, syscall::SystemError};
use crate::kerror;
use system_error::SystemError;
use super::{
device::{device_manager, mkdev, Device, DeviceNumber, IdTable, CHARDEVS, DEVMAP},

View File

@ -2,18 +2,14 @@ use alloc::{string::ToString, sync::Arc};
use core::fmt::Debug;
use crate::{
driver::video::fbdev::base::fbmem::fbmem_init,
filesystem::sysfs::{sysfs_instance, Attribute, AttributeGroup, SysFSOps},
syscall::SystemError,
};
use super::{
device::{sys_dev_char_kset, Device, DeviceMatchName, DeviceMatcher},
kobject::{KObjType, KObject},
kset::KSet,
subsys::SubSysPrivate,
};
use crate::filesystem::sysfs::{sysfs_instance, Attribute, AttributeGroup, SysFSOps};
use system_error::SystemError;
/// `/sys/class`的kset
static mut CLASS_KSET_INSTANCE: Option<Arc<KSet>> = None;
@ -34,7 +30,6 @@ pub(super) fn classes_init() -> Result<(), SystemError> {
CLASS_KSET_INSTANCE = Some(class_kset);
}
fbmem_init()?;
return Ok(());
}

View File

@ -9,9 +9,10 @@ use crate::{
driver::acpi::acpi_manager,
filesystem::kernfs::KernFSInode,
libs::rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard},
syscall::SystemError,
};
use system_error::SystemError;
use super::{
class::Class,
device::{

View File

@ -17,7 +17,6 @@ use crate::{
vfs::syscall::ModeType,
},
libs::rwlock::RwLock,
syscall::SystemError,
};
use alloc::{
string::{String, ToString},
@ -26,6 +25,7 @@ use alloc::{
use core::{ffi::CStr, fmt::Debug, intrinsics::unlikely};
use hashbrown::HashMap;
use intertrait::cast::CastArc;
use system_error::SystemError;
/// `/sys/bus`的kset
static mut BUS_KSET_INSTANCE: Option<Arc<KSet>> = None;

View File

@ -10,8 +10,8 @@ use crate::{
vfs::syscall::ModeType,
},
libs::wait_queue::WaitQueue,
syscall::SystemError,
};
use system_error::SystemError;
use super::{
bus::BusNotifyEvent,

View File

@ -5,10 +5,10 @@ use super::{
use crate::{
driver::base::kobject::KObject,
filesystem::sysfs::{sysfs_instance, Attribute, AttributeGroup},
syscall::SystemError,
};
use alloc::{sync::Arc, vec::Vec};
use core::fmt::Debug;
use system_error::SystemError;
/// @brief: Driver error
#[allow(dead_code)]

View File

@ -11,9 +11,10 @@ use crate::{
kset::KSet,
},
kinfo,
syscall::SystemError,
};
use system_error::SystemError;
pub fn devices_init() -> Result<(), SystemError> {
// 创建 `/sys/devices` 目录
{

View File

@ -16,10 +16,11 @@ use crate::{
},
vfs::syscall::ModeType,
},
syscall::SystemError,
};
use core::fmt::Debug;
use core::intrinsics::unlikely;
use system_error::SystemError;
use self::{
bus::{bus_add_device, bus_probe_device, Bus},

View File

@ -1,6 +1,6 @@
use alloc::{string::ToString, sync::Arc};
use crate::syscall::SystemError;
use system_error::SystemError;
use super::kset::KSet;

View File

@ -1,6 +1,6 @@
use alloc::{string::ToString, sync::Arc};
use crate::syscall::SystemError;
use system_error::SystemError;
use super::kset::KSet;

View File

@ -1,4 +1,6 @@
use crate::{driver::tty::tty_device::tty_init, syscall::SystemError};
use crate::driver::tty::tty_device::tty_init;
use system_error::SystemError;
use unified_init::{define_public_unified_initializer_slice, unified_init};
use super::{
class::classes_init,
@ -9,6 +11,8 @@ use super::{
platform::platform_bus_init,
};
define_public_unified_initializer_slice!(SUBSYSTEM_INITIALIZER_SLICE);
pub(super) fn driver_init() -> Result<(), SystemError> {
devices_init()?;
buses_init()?;
@ -17,7 +21,7 @@ pub(super) fn driver_init() -> Result<(), SystemError> {
hypervisor_init()?;
platform_bus_init()?;
cpu_device_manager().init()?;
subsystem_init()?;
// 至此,已完成设备驱动模型的初始化
// 接下来,初始化设备
actual_device_init()?;
@ -29,3 +33,8 @@ fn actual_device_init() -> Result<(), SystemError> {
return Ok(());
}
fn subsystem_init() -> Result<(), SystemError> {
unified_init!(SUBSYSTEM_INITIALIZER_SLICE);
return Ok(());
}

View File

@ -16,9 +16,10 @@ use crate::{
casting::DowncastArc,
rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard},
},
syscall::SystemError,
};
use system_error::SystemError;
use super::kset::KSet;
pub trait KObject: Any + Send + Sync + Debug + CastFromSync {

View File

@ -6,15 +6,14 @@ use alloc::{
use core::hash::Hash;
use crate::{
filesystem::kernfs::KernFSInode,
libs::rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard},
syscall::SystemError,
};
use super::kobject::{
DynamicKObjKType, KObjType, KObject, KObjectManager, KObjectState, LockedKObjectState,
};
use crate::{
filesystem::kernfs::KernFSInode,
libs::rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard},
};
use system_error::SystemError;
#[derive(Debug)]
pub struct KSet {

View File

@ -7,9 +7,11 @@ use super::{
},
kobject::KObject,
};
use crate::{driver::base::device::device_register, syscall::SystemError};
use crate::driver::base::device::device_register;
use alloc::{collections::BTreeSet, string::ToString, sync::Arc, vec::Vec};
use core::fmt::Debug;
use system_error::SystemError;
use unified_init::{define_unified_initializer_slice, unified_init};
pub mod platform_device;
pub mod platform_driver;
@ -18,6 +20,8 @@ pub mod subsys;
static mut PLATFORM_BUS_DEVICE: Option<Arc<PlatformBusDevice>> = None;
static mut PLATFORM_BUS: Option<Arc<PlatformBus>> = None;
define_unified_initializer_slice!(PLATFORM_DEVICE_INITIALIZER);
#[allow(dead_code)]
#[inline(always)]
pub fn platform_bus_device() -> Arc<PlatformBusDevice> {
@ -92,5 +96,7 @@ pub fn platform_bus_init() -> Result<(), SystemError> {
}
unsafe { PLATFORM_BUS = Some(paltform_bus) };
unified_init!(PLATFORM_DEVICE_INITIALIZER);
return r;
}

View File

@ -21,8 +21,8 @@ use crate::{
rwlock::{RwLockReadGuard, RwLockWriteGuard},
spinlock::SpinLock,
},
syscall::SystemError,
};
use system_error::SystemError;
use super::{super::device::DeviceState, platform_bus, platform_bus_device, CompatibleTable};

View File

@ -1,13 +1,12 @@
use alloc::sync::Arc;
use crate::{
driver::base::device::{
bus::Bus,
driver::{driver_manager, Driver},
},
syscall::SystemError,
use crate::driver::base::device::{
bus::Bus,
driver::{driver_manager, Driver},
};
use system_error::SystemError;
use super::{platform_bus, platform_device::PlatformDevice};
/// @brief: 实现该trait的设备驱动实例应挂载在platform总线上

View File

@ -4,6 +4,7 @@ use alloc::{
};
use intertrait::cast::CastArc;
use super::{platform_device::PlatformDevice, platform_driver::PlatformDriver};
use crate::{
driver::{
acpi::acpi_manager,
@ -17,10 +18,8 @@ use crate::{
sysfs::{Attribute, AttributeGroup},
vfs::syscall::ModeType,
},
syscall::SystemError,
};
use super::{platform_device::PlatformDevice, platform_driver::PlatformDriver};
use system_error::SystemError;
#[derive(Debug)]
pub struct PlatformBus {

View File

@ -3,20 +3,17 @@ use core::{
sync::atomic::{AtomicBool, Ordering},
};
use crate::libs::{
notifier::AtomicNotifierChain,
rwlock::{RwLock, RwLockReadGuard},
spinlock::SpinLock,
};
use alloc::{
string::String,
sync::{Arc, Weak},
vec::Vec,
};
use crate::{
libs::{
notifier::AtomicNotifierChain,
rwlock::{RwLock, RwLockReadGuard},
spinlock::SpinLock,
},
syscall::SystemError,
};
use system_error::SystemError;
use super::{
class::Class,

View File

@ -6,13 +6,13 @@ use crate::filesystem::vfs::{
core::generate_inode_id, make_rawdev, FilePrivateData, FileSystem, FileType, IndexNode,
Metadata,
};
use crate::syscall::SystemError;
use crate::{libs::spinlock::SpinLock, time::TimeSpec};
use alloc::{
string::String,
sync::{Arc, Weak},
vec::Vec,
};
use system_error::SystemError;
use super::ahcidisk::LockedAhciDisk;

View File

@ -18,7 +18,6 @@ use crate::kdebug;
use crate::libs::rwlock::{RwLockReadGuard, RwLockWriteGuard};
use crate::libs::{spinlock::SpinLock, vec_cursor::VecCursor};
use crate::mm::{phys_2_virt, verify_area, VirtAddr};
use crate::syscall::SystemError;
use crate::{
driver::disk::ahci::hba::{
FisRegH2D, FisType, HbaCmdHeader, ATA_CMD_READ_DMA_EXT, ATA_CMD_WRITE_DMA_EXT,
@ -26,6 +25,7 @@ use crate::{
},
kerror,
};
use system_error::SystemError;
use alloc::sync::Weak;
use alloc::{string::String, sync::Arc, vec::Vec};

View File

@ -14,7 +14,6 @@ use crate::kerror;
use crate::libs::rwlock::RwLockWriteGuard;
use crate::libs::spinlock::{SpinLock, SpinLockGuard};
use crate::mm::virt_2_phys;
use crate::syscall::SystemError;
use crate::{
driver::disk::ahci::{
ahcidisk::LockedAhciDisk,
@ -33,6 +32,7 @@ use alloc::{
vec::Vec,
};
use core::sync::atomic::compiler_fence;
use system_error::SystemError;
// 仅module内可见 全局数据区 hbr_port, disks
static LOCKED_HBA_MEM_LIST: SpinLock<Vec<&mut HbaMem>> = SpinLock::new(Vec::new());

View File

@ -13,10 +13,9 @@ use crate::{
},
include::bindings::bindings::vfs_file_operations_t,
libs::{keyboard_parser::TypeOneFSM, rwlock::RwLock, spinlock::SpinLock},
syscall::SystemError,
time::TimeSpec,
};
use system_error::SystemError;
#[derive(Debug)]
pub struct LockedPS2KeyBoardInode(RwLock<PS2KeyBoardInode>, AtomicI32); // self.1 用来记录有多少个文件打开了这个inode

View File

@ -11,7 +11,6 @@ use crate::{
kinfo,
libs::spinlock::SpinLock,
net::{generate_iface_id, NET_DRIVERS},
syscall::SystemError,
time::Instant,
};
use alloc::{string::String, sync::Arc};
@ -21,6 +20,7 @@ use core::{
ops::{Deref, DerefMut},
};
use smoltcp::{phy, wire};
use system_error::SystemError;
use super::e1000e::{E1000EBuffer, E1000EDevice};
@ -260,10 +260,7 @@ impl NetDriver for E1000EInterface {
return Ok(());
}
fn poll(
&self,
sockets: &mut smoltcp::iface::SocketSet,
) -> Result<(), crate::syscall::SystemError> {
fn poll(&self, sockets: &mut smoltcp::iface::SocketSet) -> Result<(), SystemError> {
let timestamp: smoltcp::time::Instant = Instant::now().into();
let mut guard = self.iface.lock();
let poll_res = guard.poll(timestamp, self.driver.force_get_mut(), sockets);

View File

@ -4,9 +4,9 @@ use smoltcp::{
wire::{self, EthernetAddress},
};
use crate::{libs::spinlock::SpinLock, syscall::SystemError};
use super::base::device::driver::Driver;
use crate::libs::spinlock::SpinLock;
use system_error::SystemError;
mod dma;
pub mod e1000e;

View File

@ -8,6 +8,7 @@ use alloc::{string::String, sync::Arc};
use smoltcp::{phy, wire};
use virtio_drivers::{device::net::VirtIONet, transport::Transport};
use super::NetDriver;
use crate::{
driver::{
base::{
@ -19,11 +20,9 @@ use crate::{
kerror, kinfo,
libs::spinlock::SpinLock,
net::{generate_iface_id, NET_DRIVERS},
syscall::SystemError,
time::Instant,
};
use super::NetDriver;
use system_error::SystemError;
/// @brief Virtio网络设备驱动(加锁)
pub struct VirtioNICDriver<T: Transport> {
@ -302,10 +301,7 @@ impl<T: Transport + 'static> NetDriver for VirtioInterface<T> {
return Ok(());
}
fn poll(
&self,
sockets: &mut smoltcp::iface::SocketSet,
) -> Result<(), crate::syscall::SystemError> {
fn poll(&self, sockets: &mut smoltcp::iface::SocketSet) -> Result<(), SystemError> {
let timestamp: smoltcp::time::Instant = Instant::now().into();
let mut guard = self.iface.lock();
let poll_res = guard.poll(timestamp, self.driver.force_get_mut(), sockets);

View File

@ -1,7 +1,8 @@
use system_error::SystemError;
use crate::{
arch::{io::PortIOArch, CurrentIrqArch, CurrentPortIOArch},
exception::InterruptArch,
syscall::SystemError,
};
pub struct RtcTime {

View File

@ -1,6 +1,5 @@
use crate::syscall::SystemError;
use super::serial::serial_early_init;
use system_error::SystemError;
pub fn tty_early_init() -> Result<(), SystemError> {
serial_early_init()?;

View File

@ -1,8 +1,9 @@
use core::{fmt::Debug, sync::atomic::AtomicU32};
use alloc::sync::Arc;
use system_error::SystemError;
use crate::{driver::base::device::DeviceNumber, mm::VirtAddr, syscall::SystemError};
use crate::{driver::base::device::DeviceNumber, mm::VirtAddr};
use self::serial8250::serial8250_manager;

View File

@ -8,6 +8,7 @@ use alloc::{
sync::{Arc, Weak},
vec::Vec,
};
use system_error::SystemError;
use crate::{
driver::{
@ -31,7 +32,6 @@ use crate::{
},
filesystem::kernfs::KernFSInode,
libs::rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard},
syscall::SystemError,
};
use self::serial8250_pio::{send_to_serial8250_pio_com1, serial8250_pio_port_early_init};

View File

@ -11,8 +11,8 @@ use crate::{
arch::{io::PortIOArch, CurrentPortIOArch},
driver::tty::serial::{AtomicBaudRate, BaudRate, DivisorFraction, UartPort},
libs::rwlock::RwLock,
syscall::SystemError,
};
use system_error::SystemError;
use super::{Serial8250ISADevices, Serial8250ISADriver, Serial8250Manager, Serial8250Port};

View File

@ -3,6 +3,7 @@ use alloc::{
string::{String, ToString},
sync::{Arc, Weak},
};
use system_error::SystemError;
use crate::{
filesystem::{
@ -17,7 +18,6 @@ use crate::{
lib_ui::textui::{textui_putchar, FontColor},
rwlock::RwLock,
},
syscall::SystemError,
};
use super::{serial::serial_init, TtyCore, TtyError, TtyFileFlag, TtyFilePrivateData};

View File

@ -2,6 +2,7 @@ use alloc::{
string::{String, ToString},
sync::{Arc, Weak},
};
use system_error::SystemError;
use crate::{
driver::base::{
@ -19,7 +20,6 @@ use crate::{
rwlock::{RwLockReadGuard, RwLockWriteGuard},
spinlock::SpinLock,
},
syscall::SystemError,
};
use super::fbmem::sys_class_graphics_instance;

View File

@ -2,15 +2,15 @@ use alloc::{
string::ToString,
sync::{Arc, Weak},
};
use system_error::SystemError;
use unified_init::macros::unified_init;
use crate::{
driver::base::{
class::{class_manager, Class},
device::sys_dev_char_kset,
kobject::KObject,
subsys::SubSysPrivate,
},
syscall::SystemError,
use crate::driver::base::{
class::{class_manager, Class},
device::sys_dev_char_kset,
init::SUBSYSTEM_INITIALIZER_SLICE,
kobject::KObject,
subsys::SubSysPrivate,
};
use super::fbcon::fb_console_init;
@ -26,6 +26,7 @@ pub fn sys_class_graphics_instance() -> Option<&'static Arc<GraphicsClass>> {
}
/// 初始化帧缓冲区子系统
#[unified_init(SUBSYSTEM_INITIALIZER_SLICE)]
pub fn fbmem_init() -> Result<(), SystemError> {
let graphics_class = GraphicsClass::new();
class_manager().class_register(&(graphics_class.clone() as Arc<dyn Class>))?;

View File

@ -1,9 +1,9 @@
use alloc::{string::String, sync::Arc};
use system_error::SystemError;
use crate::{
driver::base::device::Device,
mm::{ucontext::LockedVMA, PhysAddr},
syscall::SystemError,
};
pub mod fbcon;

View File

@ -4,8 +4,6 @@ use core::{
sync::atomic::{AtomicBool, Ordering},
};
use alloc::{boxed::Box, sync::Arc};
use crate::{
arch::MMArch,
driver::tty::serial::serial8250::send_to_default_serial8250_port,
@ -24,9 +22,10 @@ use crate::{
allocator::page_frame::PageFrameCount, kernel_mapper::KernelMapper,
no_init::pseudo_map_phys, page::PageFlags, MemoryManagementArch, PhysAddr, VirtAddr,
},
syscall::SystemError,
time::timer::{Timer, TimerFunction},
};
use alloc::{boxed::Box, sync::Arc};
use system_error::SystemError;
pub mod fbdev;

View File

@ -8,11 +8,12 @@ use core::{
use alloc::{boxed::Box, sync::Arc};
use num_traits::FromPrimitive;
use system_error::SystemError;
use crate::{
arch::CurrentIrqArch, exception::InterruptArch, kdebug, kinfo, libs::rwlock::RwLock,
mm::percpu::PerCpu, process::ProcessManager, smp::core::smp_get_processor_id,
syscall::SystemError, time::timer::clock,
time::timer::clock,
};
const MAX_SOFTIRQ_NUM: u64 = 64;

View File

@ -14,7 +14,6 @@ use crate::{
once::Once,
spinlock::{SpinLock, SpinLockGuard},
},
syscall::SystemError,
time::TimeSpec,
};
use alloc::{
@ -23,6 +22,7 @@ use alloc::{
sync::{Arc, Weak},
vec::Vec,
};
use system_error::SystemError;
const DEVFS_MAX_NAMELEN: usize = 64;

View File

@ -4,12 +4,13 @@ use crate::filesystem::vfs::syscall::ModeType;
use crate::filesystem::vfs::{
core::generate_inode_id, FilePrivateData, FileSystem, FileType, IndexNode, Metadata,
};
use crate::{libs::spinlock::SpinLock, syscall::SystemError, time::TimeSpec};
use crate::{libs::spinlock::SpinLock, time::TimeSpec};
use alloc::{
string::String,
sync::{Arc, Weak},
vec::Vec,
};
use system_error::SystemError;
// use uuid::{uuid, Uuid};
use super::{DevFS, DeviceINode};

View File

@ -4,12 +4,13 @@ use crate::filesystem::vfs::syscall::ModeType;
use crate::filesystem::vfs::{
core::generate_inode_id, FilePrivateData, FileSystem, FileType, IndexNode, Metadata,
};
use crate::{libs::spinlock::SpinLock, syscall::SystemError, time::TimeSpec};
use crate::{libs::spinlock::SpinLock, time::TimeSpec};
use alloc::{
string::String,
sync::{Arc, Weak},
vec::Vec,
};
use system_error::SystemError;
// use uuid::{uuid, Uuid};
use super::{DevFS, DeviceINode};

View File

@ -1,11 +1,11 @@
#![allow(dead_code)]
use alloc::{sync::Arc, vec::Vec};
use system_error::SystemError;
use crate::{
driver::base::block::{block_device::LBA_SIZE, disk_info::Partition, SeekFrom},
kerror,
libs::vec_cursor::VecCursor,
syscall::SystemError,
};
use super::fs::{Cluster, FATFileSystem};

View File

@ -1,11 +1,11 @@
#![allow(dead_code)]
use core::{cmp::min, intrinsics::unlikely};
use system_error::SystemError;
use crate::{
driver::base::block::{block_device::LBA_SIZE, SeekFrom},
kwarn,
libs::vec_cursor::VecCursor,
syscall::SystemError,
};
use alloc::{
string::{String, ToString},

View File

@ -1,6 +1,6 @@
#![allow(dead_code)]
use core::intrinsics::unlikely;
use core::{any::Any, fmt::Debug};
use system_error::SystemError;
use alloc::{
collections::BTreeMap,
@ -24,7 +24,6 @@ use crate::{
spinlock::{SpinLock, SpinLockGuard},
vec_cursor::VecCursor,
},
syscall::SystemError,
time::TimeSpec,
};
@ -784,6 +783,7 @@ impl FATFileSystem {
/// @return Ok(true) 正常
/// @return Ok(false) 不正常
/// @return Err(SystemError) 在判断时发生错误
#[allow(dead_code)]
pub fn is_shut_bit_ok(&mut self) -> Result<bool, SystemError> {
match self.bpb.fat_type {
FATType::FAT32(_) => {
@ -1205,6 +1205,7 @@ impl FATFsInfo {
const LEAD_SIG: u32 = 0x41615252;
const STRUC_SIG: u32 = 0x61417272;
const TRAIL_SIG: u32 = 0xAA550000;
#[allow(dead_code)]
const FS_INFO_SIZE: u64 = 512;
/// @brief 从磁盘上读取FAT文件系统的FSInfo结构体

View File

@ -1,10 +1,10 @@
use crate::{
filesystem::{sysfs::SysFSKernPrivateData, vfs::PollStatus},
libs::spinlock::SpinLockGuard,
syscall::SystemError,
};
use alloc::sync::Arc;
use core::fmt::Debug;
use system_error::SystemError;
use super::KernFSInode;

View File

@ -6,6 +6,7 @@ use alloc::{
vec::Vec,
};
use hashbrown::HashMap;
use system_error::SystemError;
use crate::{
libs::{
@ -13,7 +14,6 @@ use crate::{
rwlock::RwLock,
spinlock::{SpinLock, SpinLockGuard},
},
syscall::SystemError,
time::TimeSpec,
};

View File

@ -8,6 +8,7 @@ use alloc::{
sync::{Arc, Weak},
vec::Vec,
};
use system_error::SystemError;
use crate::{
arch::mm::LockedFrameAllocator,
@ -22,7 +23,6 @@ use crate::{
},
mm::allocator::page_frame::FrameAllocator,
process::{Pid, ProcessManager},
syscall::SystemError,
time::TimeSpec,
};

View File

@ -7,12 +7,12 @@ use alloc::{
sync::{Arc, Weak},
vec::Vec,
};
use system_error::SystemError;
use crate::{
filesystem::vfs::{core::generate_inode_id, FileType},
ipc::pipe::LockedPipeInode,
libs::spinlock::{SpinLock, SpinLockGuard},
syscall::SystemError,
time::TimeSpec,
};

View File

@ -4,6 +4,7 @@ use alloc::{
sync::{Arc, Weak},
vec::Vec,
};
use system_error::SystemError;
use crate::{
driver::base::kobject::KObject,
@ -11,7 +12,6 @@ use crate::{
kernfs::{callback::KernInodePrivateData, KernFSInode},
vfs::syscall::ModeType,
},
syscall::SystemError,
};
use super::{SysFS, SysFSKernPrivateData};

View File

@ -4,6 +4,7 @@ use alloc::{
string::ToString,
sync::{Arc, Weak},
};
use system_error::SystemError;
use crate::{
driver::base::kobject::KObject,
@ -16,7 +17,6 @@ use crate::{
vfs::{syscall::ModeType, PollStatus},
},
kwarn,
syscall::SystemError,
};
use super::{Attribute, BinAttribute, SysFS, SysFSKernPrivateData};

View File

@ -1,6 +1,7 @@
use core::intrinsics::unlikely;
use alloc::{string::ToString, sync::Arc};
use system_error::SystemError;
use crate::{
driver::base::kobject::KObject,
@ -11,7 +12,6 @@ use crate::{
},
kwarn,
libs::casting::DowncastArc,
syscall::SystemError,
};
use super::{AttributeGroup, SysFS};

View File

@ -11,9 +11,9 @@ use crate::{
filesystem::vfs::ROOT_INODE,
kinfo, kwarn,
libs::{casting::DowncastArc, once::Once},
syscall::SystemError,
};
use alloc::sync::Arc;
use system_error::SystemError;
pub mod dir;
pub mod file;

View File

@ -3,10 +3,9 @@ use alloc::{
string::{String, ToString},
sync::Arc,
};
use system_error::SystemError;
use crate::{
driver::base::kobject::KObject, filesystem::kernfs::KernFSInode, syscall::SystemError,
};
use crate::{driver::base::kobject::KObject, filesystem::kernfs::KernFSInode};
use super::SysFS;

View File

@ -1,6 +1,7 @@
use core::{hint::spin_loop, sync::atomic::Ordering};
use alloc::{format, string::ToString, sync::Arc};
use system_error::SystemError;
use crate::{
driver::{
@ -17,7 +18,6 @@ use crate::{
},
kdebug, kerror, kinfo,
process::ProcessManager,
syscall::SystemError,
};
use super::{

View File

@ -3,6 +3,7 @@ use alloc::{
sync::{Arc, Weak},
vec::Vec,
};
use system_error::SystemError;
use crate::{
driver::{
@ -18,7 +19,6 @@ use crate::{
socket::SocketInode,
},
process::ProcessManager,
syscall::SystemError,
};
use super::{Dirent, FileType, IndexNode, InodeId, Metadata, SpecialNodeData};

View File

@ -9,12 +9,12 @@ mod utils;
use ::core::{any::Any, fmt::Debug, sync::atomic::AtomicUsize};
use alloc::{string::String, sync::Arc, vec::Vec};
use system_error::SystemError;
use crate::{
driver::base::{block::block_device::BlockDevice, char::CharDevice, device::DeviceNumber},
ipc::pipe::LockedPipeInode,
libs::casting::DowncastArc,
syscall::SystemError,
time::TimeSpec,
};

View File

@ -7,8 +7,9 @@ use alloc::{
collections::BTreeMap,
sync::{Arc, Weak},
};
use system_error::SystemError;
use crate::{driver::base::device::DeviceNumber, libs::spinlock::SpinLock, syscall::SystemError};
use crate::{driver::base::device::DeviceNumber, libs::spinlock::SpinLock};
use super::{
file::FileMode, syscall::ModeType, FilePrivateData, FileSystem, FileType, IndexNode, InodeId,

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