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