xref: /DragonOS/kernel/src/filesystem/sysfs/mod.rs (revision 06d5e247267cb65b84a80f219853ccd0f384b16e)
1 use core::fmt::Debug;
2 
3 use self::{dir::SysKernDirPriv, file::SysKernFilePriv};
4 
5 use super::{
6     kernfs::{KernFS, KernFSInode},
7     vfs::{syscall::ModeType, FileSystem},
8 };
9 use crate::{
10     driver::base::kobject::KObject,
11     filesystem::vfs::ROOT_INODE,
12     kinfo, kwarn,
13     libs::{casting::DowncastArc, once::Once},
14     syscall::SystemError,
15 };
16 use alloc::sync::Arc;
17 
18 pub mod dir;
19 pub mod file;
20 pub mod group;
21 pub mod symlink;
22 
23 /// 全局的sysfs实例
24 pub(self) static mut SYSFS_INSTANCE: Option<SysFS> = None;
25 
26 #[inline(always)]
27 pub fn sysfs_instance() -> &'static SysFS {
28     unsafe {
29         return &SYSFS_INSTANCE.as_ref().unwrap();
30     }
31 }
32 
33 pub fn sysfs_init() -> Result<(), SystemError> {
34     static INIT: Once = Once::new();
35     let mut result = None;
36     INIT.call_once(|| {
37         kinfo!("Initializing SysFS...");
38 
39         // 创建 sysfs 实例
40         // let sysfs: Arc<OldSysFS> = OldSysFS::new();
41         let sysfs = SysFS::new();
42         unsafe { SYSFS_INSTANCE = Some(sysfs) };
43 
44         // sysfs 挂载
45         let _t = ROOT_INODE()
46             .find("sys")
47             .expect("Cannot find /sys")
48             .mount(sysfs_instance().fs().clone())
49             .expect("Failed to mount sysfs");
50         kinfo!("SysFS mounted.");
51 
52         // kdebug!("sys_bus_init result: {:?}", SYS_BUS_INODE().list());
53         result = Some(Ok(()));
54     });
55 
56     return result.unwrap();
57 }
58 
59 /// SysFS在KernFS的inode中的私有信息
60 #[allow(dead_code)]
61 #[derive(Debug)]
62 pub enum SysFSKernPrivateData {
63     Dir(SysKernDirPriv),
64     File(SysKernFilePriv),
65 }
66 
67 impl SysFSKernPrivateData {
68     #[inline(always)]
69     pub fn callback_read(&self, buf: &mut [u8], offset: usize) -> Result<usize, SystemError> {
70         match self {
71             SysFSKernPrivateData::File(file) => {
72                 let len = file.callback_read(buf)?;
73                 if offset > 0 {
74                     if len <= offset {
75                         return Ok(0);
76                     }
77                     let len = len - offset;
78                     buf.copy_within(offset..offset + len, 0);
79                     buf[len] = 0;
80                 }
81                 return Ok(len);
82             }
83             _ => {
84                 return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
85             }
86         }
87     }
88 
89     #[inline(always)]
90     pub fn callback_write(&self, buf: &[u8], _offset: usize) -> Result<usize, SystemError> {
91         match self {
92             SysFSKernPrivateData::File(file) => {
93                 return file.callback_write(buf);
94             }
95             _ => {
96                 return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
97             }
98         }
99     }
100 }
101 
102 /// sysfs文件目录的属性组
103 pub trait AttributeGroup: Debug + Send + Sync {
104     /// 属性组的名称
105     ///
106     /// 如果属性组的名称为None,则所有的属性都会被添加到父目录下,而不是创建一个新的目录
107     fn name(&self) -> Option<&str>;
108     /// 属性组的属性列表
109     fn attrs(&self) -> &[&'static dyn Attribute];
110 
111     /// 属性在当前属性组内的权限(该方法可选)
112     ///
113     /// 如果返回None,则使用Attribute的mode()方法返回的权限
114     ///
115     /// 如果返回Some,则使用返回的权限。
116     /// 如果要标识属性不可见,则返回Some(ModeType::empty())
117     fn is_visible(&self, kobj: Arc<dyn KObject>, attr: &dyn Attribute) -> Option<ModeType>;
118 }
119 
120 /// sysfs文件的属性
121 pub trait Attribute: Debug + Send + Sync {
122     fn name(&self) -> &str;
123     fn mode(&self) -> ModeType;
124 
125     fn support(&self) -> SysFSOpsSupport;
126 
127     fn show(&self, _kobj: Arc<dyn KObject>, _buf: &mut [u8]) -> Result<usize, SystemError> {
128         return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
129     }
130 
131     fn store(&self, _kobj: Arc<dyn KObject>, _buf: &[u8]) -> Result<usize, SystemError> {
132         return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
133     }
134 }
135 
136 pub trait SysFSOps: Debug {
137     /// 获取当前文件的支持的操作
138     fn support(&self, attr: &dyn Attribute) -> SysFSOpsSupport {
139         return attr.support();
140     }
141 
142     fn show(
143         &self,
144         kobj: Arc<dyn KObject>,
145         attr: &dyn Attribute,
146         buf: &mut [u8],
147     ) -> Result<usize, SystemError>;
148 
149     fn store(
150         &self,
151         kobj: Arc<dyn KObject>,
152         attr: &dyn Attribute,
153         buf: &[u8],
154     ) -> Result<usize, SystemError>;
155 }
156 
157 bitflags! {
158     pub struct SysFSOpsSupport: u8{
159         const SHOW = 1 << 0;
160         const STORE = 1 << 1;
161     }
162 }
163 
164 #[derive(Debug)]
165 pub struct SysFS {
166     root_inode: Arc<KernFSInode>,
167     kernfs: Arc<KernFS>,
168 }
169 
170 impl SysFS {
171     pub fn new() -> Self {
172         let kernfs: Arc<KernFS> = KernFS::new();
173 
174         let root_inode: Arc<KernFSInode> = kernfs.root_inode().downcast_arc().unwrap();
175 
176         let sysfs = SysFS { root_inode, kernfs };
177 
178         return sysfs;
179     }
180 
181     pub fn root_inode(&self) -> &Arc<KernFSInode> {
182         return &self.root_inode;
183     }
184 
185     pub fn fs(&self) -> &Arc<KernFS> {
186         return &self.kernfs;
187     }
188 
189     /// 警告:重复的sysfs entry
190     pub(self) fn warn_duplicate(&self, parent: &Arc<KernFSInode>, name: &str) {
191         let path = self.kernfs_path(parent);
192         kwarn!("duplicate sysfs entry: {path}/{name}");
193     }
194 }
195