xref: /DragonOS/kernel/src/misc/ksysfs.rs (revision c635d8a9cfe25bc11779f323ef0c7d7a0f597d4a)
1 use crate::{
2     driver::base::{kobject::KObject, kset::KSet},
3     filesystem::{
4         sysfs::{sysfs_instance, Attribute, AttributeGroup},
5         vfs::syscall::ModeType,
6     },
7     init::initcall::INITCALL_CORE,
8 };
9 use alloc::{string::ToString, sync::Arc};
10 use log::error;
11 use system_error::SystemError;
12 use unified_init::macros::unified_init;
13 
14 /// `/sys/kernel`的kset
15 static mut KERNEL_KSET_INSTANCE: Option<Arc<KSet>> = None;
16 
17 #[inline(always)]
18 #[allow(dead_code)]
19 pub fn sys_kernel_kset() -> Arc<KSet> {
20     unsafe { KERNEL_KSET_INSTANCE.clone().unwrap() }
21 }
22 
23 #[unified_init(INITCALL_CORE)]
24 fn ksysfs_init() -> Result<(), SystemError> {
25     let kernel_kset = KSet::new("kernel".to_string());
26     kernel_kset
27         .register(None)
28         .expect("register kernel kset failed");
29 
30     sysfs_instance()
31         .create_groups(&kernel_kset.as_kobject(), &[&KernelAttrGroup])
32         .map_err(|e| {
33             error!("Failed to create sysfs groups for kernel kset: {:?}", e);
34             kernel_kset.unregister();
35             SystemError::ENOMEM
36         })?;
37 
38     unsafe {
39         KERNEL_KSET_INSTANCE = Some(kernel_kset);
40     }
41 
42     return Ok(());
43 }
44 
45 #[derive(Debug)]
46 struct KernelAttrGroup;
47 
48 impl AttributeGroup for KernelAttrGroup {
49     fn name(&self) -> Option<&str> {
50         None
51     }
52 
53     fn attrs(&self) -> &[&'static dyn Attribute] {
54         &[]
55     }
56 
57     fn is_visible(
58         &self,
59         _kobj: Arc<dyn KObject>,
60         attr: &'static dyn Attribute,
61     ) -> Option<ModeType> {
62         Some(attr.mode())
63     }
64 }
65