xref: /DragonOS/kernel/src/filesystem/sysfs/mod.rs (revision 83ed0ebc293d5a10245089f627f52770fd5b9dd4)
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, offset)?;
73 
74                 return Ok(len);
75             }
76             _ => {
77                 return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
78             }
79         }
80     }
81 
82     #[inline(always)]
83     pub fn callback_write(&self, buf: &[u8], offset: usize) -> Result<usize, SystemError> {
84         match self {
85             SysFSKernPrivateData::File(file) => {
86                 return file.callback_write(buf, offset);
87             }
88             _ => {
89                 return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
90             }
91         }
92     }
93 }
94 
95 /// sysfs文件目录的属性组
96 pub trait AttributeGroup: Debug + Send + Sync {
97     /// 属性组的名称
98     ///
99     /// 如果属性组的名称为None,则所有的属性都会被添加到父目录下,而不是创建一个新的目录
100     fn name(&self) -> Option<&str>;
101     /// 属性组的属性列表
102     fn attrs(&self) -> &[&'static dyn Attribute];
103 
104     /// 属性在当前属性组内的权限(该方法可选)
105     ///
106     /// 如果返回None,则使用Attribute的mode()方法返回的权限
107     ///
108     /// 如果返回Some,则使用返回的权限。
109     /// 如果要标识属性不可见,则返回Some(ModeType::empty())
110     fn is_visible(&self, kobj: Arc<dyn KObject>, attr: &'static dyn Attribute) -> Option<ModeType>;
111 }
112 
113 /// sysfs文件的属性
114 pub trait Attribute: Debug + Send + Sync {
115     fn name(&self) -> &str;
116     fn mode(&self) -> ModeType;
117 
118     fn support(&self) -> SysFSOpsSupport;
119 
120     fn show(&self, _kobj: Arc<dyn KObject>, _buf: &mut [u8]) -> Result<usize, SystemError> {
121         return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
122     }
123 
124     fn store(&self, _kobj: Arc<dyn KObject>, _buf: &[u8]) -> Result<usize, SystemError> {
125         return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
126     }
127 }
128 
129 pub trait BinAttribute: Attribute {
130     fn support_battr(&self) -> SysFSOpsSupport;
131 
132     fn write(
133         &self,
134         _kobj: Arc<dyn KObject>,
135         _buf: &[u8],
136         _offset: usize,
137     ) -> Result<usize, SystemError> {
138         return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
139     }
140 
141     fn read(
142         &self,
143         _kobj: Arc<dyn KObject>,
144         _buf: &mut [u8],
145         _offset: usize,
146     ) -> Result<usize, SystemError> {
147         return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
148     }
149 
150     fn size(&self) -> usize;
151 }
152 
153 pub trait SysFSOps: Debug {
154     /// 获取当前文件的支持的操作
155     fn support(&self, attr: &dyn Attribute) -> SysFSOpsSupport {
156         return attr.support();
157     }
158 
159     fn support_battr(&self, attr: &Arc<dyn BinAttribute>) -> SysFSOpsSupport {
160         return attr.support();
161     }
162 
163     fn show(
164         &self,
165         kobj: Arc<dyn KObject>,
166         attr: &dyn Attribute,
167         buf: &mut [u8],
168     ) -> Result<usize, SystemError>;
169 
170     fn store(
171         &self,
172         kobj: Arc<dyn KObject>,
173         attr: &dyn Attribute,
174         buf: &[u8],
175     ) -> Result<usize, SystemError>;
176 }
177 
178 bitflags! {
179     pub struct SysFSOpsSupport: u8{
180         // === for attribute ===
181         const SHOW = 1 << 0;
182         const STORE = 1 << 1;
183         // === for bin attribute ===
184         const READ = 1 << 2;
185         const WRITE = 1 << 3;
186     }
187 }
188 
189 #[derive(Debug)]
190 pub struct SysFS {
191     root_inode: Arc<KernFSInode>,
192     kernfs: Arc<KernFS>,
193 }
194 
195 impl SysFS {
196     pub fn new() -> Self {
197         let kernfs: Arc<KernFS> = KernFS::new();
198 
199         let root_inode: Arc<KernFSInode> = kernfs.root_inode().downcast_arc().unwrap();
200 
201         let sysfs = SysFS { root_inode, kernfs };
202 
203         return sysfs;
204     }
205 
206     pub fn root_inode(&self) -> &Arc<KernFSInode> {
207         return &self.root_inode;
208     }
209 
210     pub fn fs(&self) -> &Arc<KernFS> {
211         return &self.kernfs;
212     }
213 
214     /// 警告:重复的sysfs entry
215     pub(self) fn warn_duplicate(&self, parent: &Arc<KernFSInode>, name: &str) {
216         let path = self.kernfs_path(parent);
217         kwarn!("duplicate sysfs entry: {path}/{name}");
218     }
219 }
220