1 use core::{cmp::min, fmt::Debug, intrinsics::unlikely};
2 
3 use alloc::{
4     string::String,
5     sync::{Arc, Weak},
6     vec::Vec,
7 };
8 use hashbrown::HashMap;
9 use system_error::SystemError;
10 
11 use crate::{
12     driver::base::device::device_number::DeviceNumber,
13     libs::{
14         casting::DowncastArc,
15         rwlock::RwLock,
16         spinlock::{SpinLock, SpinLockGuard},
17     },
18     time::TimeSpec,
19 };
20 
21 use self::callback::{KernCallbackData, KernFSCallback, KernInodePrivateData};
22 
23 use super::vfs::{
24     core::generate_inode_id, file::FileMode, syscall::ModeType, FilePrivateData, FileSystem,
25     FileType, FsInfo, IndexNode, InodeId, Metadata,
26 };
27 
28 pub mod callback;
29 
30 #[derive(Debug)]
31 pub struct KernFS {
32     root_inode: Arc<KernFSInode>,
33 }
34 
35 impl FileSystem for KernFS {
as_any_ref(&self) -> &dyn core::any::Any36     fn as_any_ref(&self) -> &dyn core::any::Any {
37         self
38     }
39 
info(&self) -> FsInfo40     fn info(&self) -> FsInfo {
41         return FsInfo {
42             blk_dev_id: 0,
43             max_name_len: KernFS::MAX_NAMELEN,
44         };
45     }
46 
root_inode(&self) -> Arc<dyn IndexNode>47     fn root_inode(&self) -> Arc<dyn IndexNode> {
48         return self.root_inode.clone();
49     }
50 }
51 
52 impl KernFS {
53     pub const MAX_NAMELEN: usize = 4096;
54 
55     #[allow(dead_code)]
new() -> Arc<Self>56     pub fn new() -> Arc<Self> {
57         let root_inode = Self::create_root_inode();
58         let fs = Arc::new(Self {
59             root_inode: root_inode.clone(),
60         });
61 
62         {
63             let ptr = root_inode.as_ref() as *const KernFSInode as *mut KernFSInode;
64             unsafe {
65                 (*ptr).self_ref = Arc::downgrade(&root_inode);
66             }
67         }
68         root_inode.inner.write().parent = Arc::downgrade(&root_inode);
69         *root_inode.fs.write() = Arc::downgrade(&fs);
70         return fs;
71     }
72 
create_root_inode() -> Arc<KernFSInode>73     fn create_root_inode() -> Arc<KernFSInode> {
74         let metadata = Metadata {
75             size: 0,
76             mode: ModeType::from_bits_truncate(0o755),
77             uid: 0,
78             gid: 0,
79             blk_size: 0,
80             blocks: 0,
81             atime: TimeSpec::new(0, 0),
82             mtime: TimeSpec::new(0, 0),
83             ctime: TimeSpec::new(0, 0),
84             dev_id: 0,
85             inode_id: generate_inode_id(),
86             file_type: FileType::Dir,
87             nlinks: 1,
88             raw_dev: DeviceNumber::default(),
89         };
90         let root_inode = Arc::new(KernFSInode {
91             name: String::from(""),
92             inner: RwLock::new(InnerKernFSInode {
93                 parent: Weak::new(),
94                 metadata,
95                 symlink_target: None,
96                 symlink_target_absolute_path: None,
97             }),
98             self_ref: Weak::new(),
99             fs: RwLock::new(Weak::new()),
100             private_data: SpinLock::new(None),
101             callback: None,
102             children: SpinLock::new(HashMap::new()),
103             inode_type: KernInodeType::Dir,
104         });
105 
106         return root_inode;
107     }
108 }
109 
110 #[derive(Debug)]
111 pub struct KernFSInode {
112     inner: RwLock<InnerKernFSInode>,
113     /// 指向当前Inode所属的文件系统的弱引用
114     fs: RwLock<Weak<KernFS>>,
115     /// 指向自身的弱引用
116     self_ref: Weak<KernFSInode>,
117     /// 私有数据
118     private_data: SpinLock<Option<KernInodePrivateData>>,
119     /// 回调函数
120     callback: Option<&'static dyn KernFSCallback>,
121     /// 子Inode
122     children: SpinLock<HashMap<String, Arc<KernFSInode>>>,
123     /// Inode类型
124     inode_type: KernInodeType,
125     /// Inode名称
126     name: String,
127 }
128 
129 #[derive(Debug)]
130 pub struct InnerKernFSInode {
131     parent: Weak<KernFSInode>,
132 
133     /// 当前inode的元数据
134     metadata: Metadata,
135     /// 符号链接指向的inode(仅当inode_type为SymLink时有效)
136     symlink_target: Option<Weak<KernFSInode>>,
137     symlink_target_absolute_path: Option<String>,
138 }
139 
140 impl IndexNode for KernFSInode {
as_any_ref(&self) -> &dyn core::any::Any141     fn as_any_ref(&self) -> &dyn core::any::Any {
142         self
143     }
144 
open(&self, _data: &mut FilePrivateData, _mode: &FileMode) -> Result<(), SystemError>145     fn open(&self, _data: &mut FilePrivateData, _mode: &FileMode) -> Result<(), SystemError> {
146         if let Some(callback) = self.callback {
147             let callback_data =
148                 KernCallbackData::new(self.self_ref.upgrade().unwrap(), self.private_data.lock());
149             return callback.open(callback_data);
150         }
151 
152         return Ok(());
153     }
154 
close(&self, _data: &mut FilePrivateData) -> Result<(), SystemError>155     fn close(&self, _data: &mut FilePrivateData) -> Result<(), SystemError> {
156         return Ok(());
157     }
158 
metadata(&self) -> Result<Metadata, SystemError>159     fn metadata(&self) -> Result<Metadata, SystemError> {
160         return Ok(self.inner.read().metadata.clone());
161     }
162 
set_metadata(&self, _metadata: &Metadata) -> Result<(), SystemError>163     fn set_metadata(&self, _metadata: &Metadata) -> Result<(), SystemError> {
164         // 若文件系统没有实现此方法,则返回“不支持”
165         return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
166     }
167 
resize(&self, _len: usize) -> Result<(), SystemError>168     fn resize(&self, _len: usize) -> Result<(), SystemError> {
169         return Ok(());
170     }
171 
create_with_data( &self, _name: &str, _file_type: FileType, _mode: ModeType, _data: usize, ) -> Result<Arc<dyn IndexNode>, SystemError>172     fn create_with_data(
173         &self,
174         _name: &str,
175         _file_type: FileType,
176         _mode: ModeType,
177         _data: usize,
178     ) -> Result<Arc<dyn IndexNode>, SystemError> {
179         // 应当通过kernfs的其它方法来创建文件,而不能从用户态直接调用此方法。
180         return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
181     }
182 
link(&self, _name: &str, _other: &Arc<dyn IndexNode>) -> Result<(), SystemError>183     fn link(&self, _name: &str, _other: &Arc<dyn IndexNode>) -> Result<(), SystemError> {
184         // 应当通过kernfs的其它方法来操作文件,而不能从用户态直接调用此方法。
185         return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
186     }
187 
unlink(&self, _name: &str) -> Result<(), SystemError>188     fn unlink(&self, _name: &str) -> Result<(), SystemError> {
189         // 应当通过kernfs的其它方法来操作文件,而不能从用户态直接调用此方法。
190         return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
191     }
192 
rmdir(&self, _name: &str) -> Result<(), SystemError>193     fn rmdir(&self, _name: &str) -> Result<(), SystemError> {
194         // 应当通过kernfs的其它方法来操作文件,而不能从用户态直接调用此方法。
195         return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
196     }
197 
move_( &self, _old_name: &str, _target: &Arc<dyn IndexNode>, _new_name: &str, ) -> Result<(), SystemError>198     fn move_(
199         &self,
200         _old_name: &str,
201         _target: &Arc<dyn IndexNode>,
202         _new_name: &str,
203     ) -> Result<(), SystemError> {
204         // 应当通过kernfs的其它方法来操作文件,而不能从用户态直接调用此方法。
205         return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
206     }
207 
find(&self, name: &str) -> Result<Arc<dyn IndexNode>, SystemError>208     fn find(&self, name: &str) -> Result<Arc<dyn IndexNode>, SystemError> {
209         if unlikely(name.len() > KernFS::MAX_NAMELEN) {
210             return Err(SystemError::ENAMETOOLONG);
211         }
212         if unlikely(self.inode_type != KernInodeType::Dir) {
213             return Err(SystemError::ENOTDIR);
214         }
215         match name {
216             "" | "." => {
217                 return Ok(self.self_ref.upgrade().ok_or(SystemError::ENOENT)?);
218             }
219 
220             ".." => {
221                 return Ok(self
222                     .inner
223                     .read()
224                     .parent
225                     .upgrade()
226                     .ok_or(SystemError::ENOENT)?);
227             }
228             name => {
229                 // 在子目录项中查找
230                 return Ok(self
231                     .children
232                     .lock()
233                     .get(name)
234                     .ok_or(SystemError::ENOENT)?
235                     .clone());
236             }
237         }
238     }
239 
get_entry_name(&self, ino: InodeId) -> Result<String, SystemError>240     fn get_entry_name(&self, ino: InodeId) -> Result<String, SystemError> {
241         if self.inode_type != KernInodeType::Dir {
242             return Err(SystemError::ENOTDIR);
243         }
244 
245         let children = self.children.lock();
246         let r = children
247             .iter()
248             .find(|(_, v)| v.metadata().unwrap().inode_id == ino)
249             .map(|(k, _)| k.clone());
250 
251         return r.ok_or(SystemError::ENOENT);
252     }
253 
get_entry_name_and_metadata(&self, ino: InodeId) -> Result<(String, Metadata), SystemError>254     fn get_entry_name_and_metadata(&self, ino: InodeId) -> Result<(String, Metadata), SystemError> {
255         // 如果有条件,请在文件系统中使用高效的方式实现本接口,而不是依赖这个低效率的默认实现。
256         let name = self.get_entry_name(ino)?;
257         let entry = self.find(&name)?;
258         return Ok((name, entry.metadata()?));
259     }
260 
ioctl( &self, _cmd: u32, _data: usize, _private_data: &FilePrivateData, ) -> Result<usize, SystemError>261     fn ioctl(
262         &self,
263         _cmd: u32,
264         _data: usize,
265         _private_data: &FilePrivateData,
266     ) -> Result<usize, SystemError> {
267         // 若文件系统没有实现此方法,则返回“不支持”
268         return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
269     }
270 
truncate(&self, _len: usize) -> Result<(), SystemError>271     fn truncate(&self, _len: usize) -> Result<(), SystemError> {
272         // 应当通过kernfs的其它方法来操作文件,而不能从用户态直接调用此方法。
273         return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
274     }
275 
sync(&self) -> Result<(), SystemError>276     fn sync(&self) -> Result<(), SystemError> {
277         return Ok(());
278     }
279 
fs(&self) -> Arc<dyn FileSystem>280     fn fs(&self) -> Arc<dyn FileSystem> {
281         return self.fs.read().upgrade().unwrap();
282     }
283 
list(&self) -> Result<Vec<String>, SystemError>284     fn list(&self) -> Result<Vec<String>, SystemError> {
285         let info = self.metadata()?;
286         if info.file_type != FileType::Dir {
287             return Err(SystemError::ENOTDIR);
288         }
289 
290         let mut keys: Vec<String> = Vec::new();
291         keys.push(String::from("."));
292         keys.push(String::from(".."));
293         self.children
294             .lock()
295             .keys()
296             .into_iter()
297             .for_each(|x| keys.push(x.clone()));
298 
299         return Ok(keys);
300     }
301 
read_at( &self, offset: usize, len: usize, buf: &mut [u8], _data: &mut FilePrivateData, ) -> Result<usize, SystemError>302     fn read_at(
303         &self,
304         offset: usize,
305         len: usize,
306         buf: &mut [u8],
307         _data: &mut FilePrivateData,
308     ) -> Result<usize, SystemError> {
309         if self.inode_type == KernInodeType::SymLink {
310             let inner = self.inner.read();
311             if offset >= inner.symlink_target_absolute_path.as_ref().unwrap().len() {
312                 return Ok(0);
313             }
314             let len = min(len, buf.len());
315             let len = min(
316                 len,
317                 inner.symlink_target_absolute_path.as_ref().unwrap().len() - offset,
318             );
319             buf[0..len].copy_from_slice(
320                 &inner
321                     .symlink_target_absolute_path
322                     .as_ref()
323                     .unwrap()
324                     .as_bytes()[offset..offset + len],
325             );
326             return Ok(len);
327         }
328         if self.inode_type != KernInodeType::File {
329             return Err(SystemError::EISDIR);
330         }
331 
332         if self.callback.is_none() {
333             kwarn!("kernfs: callback is none");
334             return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
335         }
336 
337         let callback_data =
338             KernCallbackData::new(self.self_ref.upgrade().unwrap(), self.private_data.lock());
339         return self
340             .callback
341             .as_ref()
342             .unwrap()
343             .read(callback_data, &mut buf[..len], offset);
344     }
345 
write_at( &self, offset: usize, len: usize, buf: &[u8], _data: &mut FilePrivateData, ) -> Result<usize, SystemError>346     fn write_at(
347         &self,
348         offset: usize,
349         len: usize,
350         buf: &[u8],
351         _data: &mut FilePrivateData,
352     ) -> Result<usize, SystemError> {
353         if self.inode_type != KernInodeType::File {
354             return Err(SystemError::EISDIR);
355         }
356 
357         if self.callback.is_none() {
358             return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
359         }
360 
361         let callback_data =
362             KernCallbackData::new(self.self_ref.upgrade().unwrap(), self.private_data.lock());
363         return self
364             .callback
365             .as_ref()
366             .unwrap()
367             .write(callback_data, &buf[..len], offset);
368     }
369 }
370 
371 impl KernFSInode {
new( parent: Option<Arc<KernFSInode>>, name: String, mut metadata: Metadata, inode_type: KernInodeType, private_data: Option<KernInodePrivateData>, callback: Option<&'static dyn KernFSCallback>, ) -> Arc<KernFSInode>372     pub fn new(
373         parent: Option<Arc<KernFSInode>>,
374         name: String,
375         mut metadata: Metadata,
376         inode_type: KernInodeType,
377         private_data: Option<KernInodePrivateData>,
378         callback: Option<&'static dyn KernFSCallback>,
379     ) -> Arc<KernFSInode> {
380         metadata.file_type = inode_type.into();
381         let parent: Weak<KernFSInode> = parent.map(|x| Arc::downgrade(&x)).unwrap_or_default();
382 
383         let inode = Arc::new(KernFSInode {
384             name,
385             inner: RwLock::new(InnerKernFSInode {
386                 parent: parent.clone(),
387                 metadata,
388                 symlink_target: None,
389                 symlink_target_absolute_path: None,
390             }),
391             self_ref: Weak::new(),
392             fs: RwLock::new(Weak::new()),
393             private_data: SpinLock::new(private_data),
394             callback,
395             children: SpinLock::new(HashMap::new()),
396             inode_type,
397         });
398 
399         {
400             let ptr = inode.as_ref() as *const KernFSInode as *mut KernFSInode;
401             unsafe {
402                 (*ptr).self_ref = Arc::downgrade(&inode);
403             }
404         }
405         if parent.strong_count() > 0 {
406             let kernfs = parent
407                 .upgrade()
408                 .unwrap()
409                 .fs()
410                 .downcast_arc::<KernFS>()
411                 .expect("KernFSInode::new: parent is not a KernFS instance");
412             *inode.fs.write() = Arc::downgrade(&kernfs);
413         }
414         return inode;
415     }
416 
417     /// 在当前inode下增加子目录
418     ///
419     /// ## 参数
420     ///
421     /// - `name`:子目录名称
422     /// - `mode`:子目录权限
423     /// - `private_data`:子目录私有数据
424     /// - `callback`:子目录回调函数
425     ///
426     /// ## 返回值
427     ///
428     /// - 成功:子目录inode
429     /// - 失败:错误码
430     #[allow(dead_code)]
431     #[inline]
add_dir( &self, name: String, mode: ModeType, private_data: Option<KernInodePrivateData>, callback: Option<&'static dyn KernFSCallback>, ) -> Result<Arc<KernFSInode>, SystemError>432     pub fn add_dir(
433         &self,
434         name: String,
435         mode: ModeType,
436         private_data: Option<KernInodePrivateData>,
437         callback: Option<&'static dyn KernFSCallback>,
438     ) -> Result<Arc<KernFSInode>, SystemError> {
439         if unlikely(self.inode_type != KernInodeType::Dir) {
440             return Err(SystemError::ENOTDIR);
441         }
442 
443         return self.inner_create(name, KernInodeType::Dir, mode, 0, private_data, callback);
444     }
445 
446     /// 在当前inode下增加文件
447     ///
448     /// ## 参数
449     ///
450     /// - `name`:文件名称
451     /// - `mode`:文件权限
452     /// - `size`:文件大小(如果不指定,则默认为4096)
453     /// - `private_data`:文件私有数据
454     /// - `callback`:文件回调函数
455     ///
456     ///
457     /// ## 返回值
458     ///
459     /// - 成功:文件inode
460     /// - 失败:错误码
461     #[allow(dead_code)]
462     #[inline]
add_file( &self, name: String, mode: ModeType, size: Option<usize>, private_data: Option<KernInodePrivateData>, callback: Option<&'static dyn KernFSCallback>, ) -> Result<Arc<KernFSInode>, SystemError>463     pub fn add_file(
464         &self,
465         name: String,
466         mode: ModeType,
467         size: Option<usize>,
468         private_data: Option<KernInodePrivateData>,
469         callback: Option<&'static dyn KernFSCallback>,
470     ) -> Result<Arc<KernFSInode>, SystemError> {
471         if unlikely(self.inode_type != KernInodeType::Dir) {
472             return Err(SystemError::ENOTDIR);
473         }
474 
475         let size = size.unwrap_or(4096);
476         return self.inner_create(
477             name,
478             KernInodeType::File,
479             mode,
480             size,
481             private_data,
482             callback,
483         );
484     }
485 
inner_create( &self, name: String, file_type: KernInodeType, mode: ModeType, mut size: usize, private_data: Option<KernInodePrivateData>, callback: Option<&'static dyn KernFSCallback>, ) -> Result<Arc<KernFSInode>, SystemError>486     fn inner_create(
487         &self,
488         name: String,
489         file_type: KernInodeType,
490         mode: ModeType,
491         mut size: usize,
492         private_data: Option<KernInodePrivateData>,
493         callback: Option<&'static dyn KernFSCallback>,
494     ) -> Result<Arc<KernFSInode>, SystemError> {
495         match file_type {
496             KernInodeType::Dir | KernInodeType::SymLink => {
497                 size = 0;
498             }
499             _ => {}
500         }
501 
502         let metadata = Metadata {
503             size: size as i64,
504             mode,
505             uid: 0,
506             gid: 0,
507             blk_size: 0,
508             blocks: 0,
509             atime: TimeSpec::new(0, 0),
510             mtime: TimeSpec::new(0, 0),
511             ctime: TimeSpec::new(0, 0),
512             dev_id: 0,
513             inode_id: generate_inode_id(),
514             file_type: file_type.into(),
515             nlinks: 1,
516             raw_dev: DeviceNumber::default(),
517         };
518 
519         let new_inode: Arc<KernFSInode> = Self::new(
520             Some(self.self_ref.upgrade().unwrap()),
521             name.clone(),
522             metadata,
523             file_type,
524             private_data,
525             callback,
526         );
527 
528         self.children.lock().insert(name, new_inode.clone());
529 
530         return Ok(new_inode);
531     }
532 
533     /// 在当前inode下删除子目录或者文件
534     ///
535     /// 如果要删除的是子目录,且子目录不为空,则返回ENOTEMPTY
536     ///
537     /// ## 参数
538     ///
539     /// - `name`:子目录或者文件名称
540     ///
541     /// ## 返回值
542     ///
543     /// - 成功:()
544     /// - 失败:错误码
545     #[allow(dead_code)]
remove(&self, name: &str) -> Result<(), SystemError>546     pub fn remove(&self, name: &str) -> Result<(), SystemError> {
547         if unlikely(self.inode_type != KernInodeType::Dir) {
548             return Err(SystemError::ENOTDIR);
549         }
550 
551         let mut children = self.children.lock();
552         let inode = children.get(name).ok_or(SystemError::ENOENT)?;
553         if inode.children.lock().is_empty() {
554             children.remove(name);
555             return Ok(());
556         } else {
557             return Err(SystemError::ENOTEMPTY);
558         }
559     }
560 
561     /// add_link - create a symlink in kernfs
562     ///
563     /// ## 参数
564     ///
565     /// - `parent`: directory to create the symlink in
566     /// - `name`: name of the symlink
567     /// - `target`: target node for the symlink to point to
568     ///
569     /// Returns the created node on success
570     ///
571     /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/fs/kernfs/symlink.c#25
add_link( &self, name: String, target: &Arc<KernFSInode>, target_absolute_path: String, ) -> Result<Arc<KernFSInode>, SystemError>572     pub fn add_link(
573         &self,
574         name: String,
575         target: &Arc<KernFSInode>,
576         target_absolute_path: String,
577     ) -> Result<Arc<KernFSInode>, SystemError> {
578         // kdebug!("kernfs add link: name:{name}, target path={target_absolute_path}");
579         let inode = self.inner_create(
580             name,
581             KernInodeType::SymLink,
582             ModeType::S_IFLNK | ModeType::from_bits_truncate(0o777),
583             0,
584             None,
585             None,
586         )?;
587 
588         inode.inner.write().symlink_target = Some(Arc::downgrade(target));
589         inode.inner.write().symlink_target_absolute_path = Some(target_absolute_path);
590         return Ok(inode);
591     }
592 
name(&self) -> &str593     pub fn name(&self) -> &str {
594         return &self.name;
595     }
596 
parent(&self) -> Option<Arc<KernFSInode>>597     pub fn parent(&self) -> Option<Arc<KernFSInode>> {
598         return self.inner.read().parent.upgrade();
599     }
600 
private_data_mut(&self) -> SpinLockGuard<Option<KernInodePrivateData>>601     pub fn private_data_mut(&self) -> SpinLockGuard<Option<KernInodePrivateData>> {
602         return self.private_data.lock();
603     }
604 
605     #[allow(dead_code)]
symlink_target(&self) -> Option<Arc<KernFSInode>>606     pub fn symlink_target(&self) -> Option<Arc<KernFSInode>> {
607         return self.inner.read().symlink_target.as_ref()?.upgrade();
608     }
609 
610     /// remove a kernfs_node recursively
remove_recursive(&self)611     pub fn remove_recursive(&self) {
612         let mut children = self.children.lock().drain().collect::<Vec<_>>();
613         while let Some((_, child)) = children.pop() {
614             children.append(&mut child.children.lock().drain().collect::<Vec<_>>());
615         }
616     }
617 
618     /// 删除当前的inode(包括其自身、子目录和子文件)
619     #[allow(dead_code)]
remove_inode_include_self(&self)620     pub fn remove_inode_include_self(&self) {
621         let parent = self.parent();
622         if let Some(parent) = parent {
623             parent.children.lock().remove(self.name());
624         }
625         self.remove_recursive();
626     }
627 }
628 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
629 pub enum KernInodeType {
630     Dir,
631     File,
632     SymLink,
633 }
634 
635 impl Into<FileType> for KernInodeType {
into(self) -> FileType636     fn into(self) -> FileType {
637         match self {
638             KernInodeType::Dir => FileType::Dir,
639             KernInodeType::File => FileType::File,
640             KernInodeType::SymLink => FileType::SymLink,
641         }
642     }
643 }
644