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