xref: /DragonOS/kernel/src/filesystem/sysfs/mod.rs (revision f79998f626801329580c782fd05e36cb2027f474)
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     libs::{casting::DowncastArc, once::Once},
13 };
14 use alloc::sync::Arc;
15 use log::{info, warn};
16 use system_error::SystemError;
17 
18 pub mod dir;
19 pub mod file;
20 pub mod group;
21 pub mod symlink;
22 
23 /// 全局的sysfs实例
24 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         info!("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         ROOT_INODE()
46             .mkdir("sys", ModeType::from_bits_truncate(0o755))
47             .expect("Unabled to find /sys")
48             .mount(sysfs_instance().fs().clone())
49             .expect("Failed to mount at /sys");
50         info!("SysFS mounted.");
51 
52         // debug!("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::ENOSYS);
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::ENOSYS);
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(
111         &self,
112         _kobj: Arc<dyn KObject>,
113         attr: &'static dyn Attribute,
114     ) -> Option<ModeType> {
115         return Some(attr.mode());
116     }
117 }
118 
119 /// sysfs只读属性文件的权限
120 pub const SYSFS_ATTR_MODE_RO: ModeType = ModeType::from_bits_truncate(0o444);
121 /// sysfs只写属性文件的权限
122 pub const SYSFS_ATTR_MODE_WO: ModeType = ModeType::from_bits_truncate(0o200);
123 /// sysfs读写属性文件的权限
124 pub const SYSFS_ATTR_MODE_RW: ModeType = ModeType::from_bits_truncate(0o644);
125 
126 /// sysfs文件的属性
127 pub trait Attribute: Debug + Send + Sync {
128     fn name(&self) -> &str;
129     fn mode(&self) -> ModeType;
130 
131     fn support(&self) -> SysFSOpsSupport;
132 
133     fn show(&self, _kobj: Arc<dyn KObject>, _buf: &mut [u8]) -> Result<usize, SystemError> {
134         return Err(SystemError::ENOSYS);
135     }
136 
137     fn store(&self, _kobj: Arc<dyn KObject>, _buf: &[u8]) -> Result<usize, SystemError> {
138         return Err(SystemError::ENOSYS);
139     }
140 }
141 
142 pub trait BinAttribute: Attribute {
143     fn support_battr(&self) -> SysFSOpsSupport;
144 
145     fn write(
146         &self,
147         _kobj: Arc<dyn KObject>,
148         _buf: &[u8],
149         _offset: usize,
150     ) -> Result<usize, SystemError> {
151         return Err(SystemError::ENOSYS);
152     }
153 
154     fn read(
155         &self,
156         _kobj: Arc<dyn KObject>,
157         _buf: &mut [u8],
158         _offset: usize,
159     ) -> Result<usize, SystemError> {
160         return Err(SystemError::ENOSYS);
161     }
162 
163     fn size(&self) -> usize;
164 }
165 
166 pub trait SysFSOps: Debug {
167     /// 获取当前文件的支持的操作
168     fn support(&self, attr: &dyn Attribute) -> SysFSOpsSupport {
169         return attr.support();
170     }
171 
172     fn support_battr(&self, attr: &Arc<dyn BinAttribute>) -> SysFSOpsSupport {
173         return attr.support();
174     }
175 
176     fn show(
177         &self,
178         kobj: Arc<dyn KObject>,
179         attr: &dyn Attribute,
180         buf: &mut [u8],
181     ) -> Result<usize, SystemError>;
182 
183     fn store(
184         &self,
185         kobj: Arc<dyn KObject>,
186         attr: &dyn Attribute,
187         buf: &[u8],
188     ) -> Result<usize, SystemError>;
189 }
190 
191 bitflags! {
192     pub struct SysFSOpsSupport: u8{
193         // === for attribute ===
194         const ATTR_SHOW = 1 << 0;
195         const ATTR_STORE = 1 << 1;
196         // === for bin attribute ===
197         const BATTR_READ = 1 << 2;
198         const BATTR_WRITE = 1 << 3;
199     }
200 }
201 
202 #[derive(Debug)]
203 pub struct SysFS {
204     root_inode: Arc<KernFSInode>,
205     kernfs: Arc<KernFS>,
206 }
207 
208 impl SysFS {
209     pub fn new() -> Self {
210         let kernfs: Arc<KernFS> = KernFS::new();
211 
212         let root_inode: Arc<KernFSInode> = kernfs.root_inode().downcast_arc().unwrap();
213 
214         let sysfs = SysFS { root_inode, kernfs };
215 
216         return sysfs;
217     }
218 
219     pub fn root_inode(&self) -> &Arc<KernFSInode> {
220         return &self.root_inode;
221     }
222 
223     pub fn fs(&self) -> &Arc<KernFS> {
224         return &self.kernfs;
225     }
226 
227     /// 警告:重复的sysfs entry
228     pub(self) fn warn_duplicate(&self, parent: &Arc<KernFSInode>, name: &str) {
229         let path = self.kernfs_path(parent);
230         warn!("duplicate sysfs entry: {path}/{name}");
231     }
232 }
233