1 /// 导出devfs的模块 2 pub mod null_dev; 3 pub mod zero_dev; 4 5 use super::vfs::{ 6 core::{generate_inode_id, ROOT_INODE}, 7 file::FileMode, 8 syscall::ModeType, 9 FilePrivateData, FileSystem, FileType, FsInfo, IndexNode, Magic, Metadata, SuperBlock, 10 }; 11 use crate::{ 12 driver::base::device::device_number::DeviceNumber, 13 kerror, kinfo, 14 libs::{ 15 once::Once, 16 spinlock::{SpinLock, SpinLockGuard}, 17 }, 18 time::TimeSpec, 19 }; 20 use alloc::{ 21 collections::BTreeMap, 22 string::{String, ToString}, 23 sync::{Arc, Weak}, 24 vec::Vec, 25 }; 26 use system_error::SystemError; 27 28 const DEVFS_BLOCK_SIZE: u64 = 512; 29 const DEVFS_MAX_NAMELEN: usize = 255; 30 /// @brief dev文件系统 31 #[derive(Debug)] 32 pub struct DevFS { 33 // 文件系统根节点 34 root_inode: Arc<LockedDevFSInode>, 35 super_block: SuperBlock, 36 } 37 38 impl FileSystem for DevFS { 39 fn as_any_ref(&self) -> &dyn core::any::Any { 40 self 41 } 42 43 fn root_inode(&self) -> Arc<dyn super::vfs::IndexNode> { 44 return self.root_inode.clone(); 45 } 46 47 fn info(&self) -> super::vfs::FsInfo { 48 return FsInfo { 49 blk_dev_id: 0, 50 max_name_len: DEVFS_MAX_NAMELEN, 51 }; 52 } 53 54 fn name(&self) -> &str { 55 "devfs" 56 } 57 58 fn super_block(&self) -> SuperBlock { 59 self.super_block.clone() 60 } 61 } 62 63 impl DevFS { 64 pub fn new() -> Arc<Self> { 65 let super_block = SuperBlock::new( 66 Magic::DEVFS_MAGIC, 67 DEVFS_BLOCK_SIZE, 68 DEVFS_MAX_NAMELEN as u64, 69 ); 70 // 初始化root inode 71 let root: Arc<LockedDevFSInode> = Arc::new(LockedDevFSInode(SpinLock::new( 72 // /dev 的权限设置为 读+执行,root 可以读写 73 // root 的 parent 是空指针 74 DevFSInode::new(FileType::Dir, ModeType::from_bits_truncate(0o755), 0), 75 ))); 76 77 let devfs: Arc<DevFS> = Arc::new(DevFS { 78 root_inode: root, 79 super_block, 80 }); 81 82 // 对root inode加锁,并继续完成初始化工作 83 let mut root_guard: SpinLockGuard<DevFSInode> = devfs.root_inode.0.lock(); 84 root_guard.parent = Arc::downgrade(&devfs.root_inode); 85 root_guard.self_ref = Arc::downgrade(&devfs.root_inode); 86 root_guard.fs = Arc::downgrade(&devfs); 87 // 释放锁 88 drop(root_guard); 89 90 // 创建文件夹 91 let root: &Arc<LockedDevFSInode> = &devfs.root_inode; 92 root.add_dir("char") 93 .expect("DevFS: Failed to create /dev/char"); 94 95 root.add_dir("block") 96 .expect("DevFS: Failed to create /dev/block"); 97 devfs.register_bultinin_device(); 98 99 // kdebug!("ls /dev: {:?}", root.list()); 100 return devfs; 101 } 102 103 /// @brief 注册系统内部自带的设备 104 fn register_bultinin_device(&self) { 105 use null_dev::LockedNullInode; 106 use zero_dev::LockedZeroInode; 107 let dev_root: Arc<LockedDevFSInode> = self.root_inode.clone(); 108 dev_root 109 .add_dev("null", LockedNullInode::new()) 110 .expect("DevFS: Failed to register /dev/null"); 111 dev_root 112 .add_dev("zero", LockedZeroInode::new()) 113 .expect("DevFS: Failed to register /dev/zero"); 114 } 115 116 /// @brief 在devfs内注册设备 117 /// 118 /// @param name 设备名称 119 /// @param device 设备节点的结构体 120 pub fn register_device<T: DeviceINode>( 121 &self, 122 name: &str, 123 device: Arc<T>, 124 ) -> Result<(), SystemError> { 125 let dev_root_inode: Arc<LockedDevFSInode> = self.root_inode.clone(); 126 let metadata = device.metadata()?; 127 match metadata.file_type { 128 // 字节设备挂载在 /dev/char 129 FileType::CharDevice => { 130 if dev_root_inode.find("char").is_err() { 131 dev_root_inode.create( 132 "char", 133 FileType::Dir, 134 ModeType::from_bits_truncate(0o755), 135 )?; 136 } 137 138 let any_char_inode = dev_root_inode.find("char")?; 139 let dev_char_inode: &LockedDevFSInode = any_char_inode 140 .as_any_ref() 141 .downcast_ref::<LockedDevFSInode>() 142 .unwrap(); 143 // 在 /dev/char 下创建设备节点 144 dev_char_inode.add_dev(name, device.clone())?; 145 146 // 特殊处理 tty 设备,挂载在 /dev 下 147 if name.starts_with("tty") && name.len() > 3 { 148 dev_root_inode.add_dev(name, device.clone())?; 149 } 150 device.set_fs(dev_char_inode.0.lock().fs.clone()); 151 } 152 FileType::BlockDevice => { 153 if dev_root_inode.find("block").is_err() { 154 dev_root_inode.create( 155 "block", 156 FileType::Dir, 157 ModeType::from_bits_truncate(0o755), 158 )?; 159 } 160 161 let any_block_inode = dev_root_inode.find("block")?; 162 let dev_block_inode: &LockedDevFSInode = any_block_inode 163 .as_any_ref() 164 .downcast_ref::<LockedDevFSInode>() 165 .unwrap(); 166 167 dev_block_inode.add_dev(name, device.clone())?; 168 device.set_fs(dev_block_inode.0.lock().fs.clone()); 169 } 170 FileType::KvmDevice => { 171 dev_root_inode 172 .add_dev(name, device.clone()) 173 .expect("DevFS: Failed to register /dev/kvm"); 174 } 175 FileType::FramebufferDevice => { 176 dev_root_inode 177 .add_dev(name, device.clone()) 178 .expect("DevFS: Failed to register /dev/fb"); 179 } 180 _ => { 181 return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP); 182 } 183 } 184 185 return Ok(()); 186 } 187 188 /// @brief 卸载设备 189 pub fn unregister_device<T: DeviceINode>( 190 &self, 191 name: &str, 192 device: Arc<T>, 193 ) -> Result<(), SystemError> { 194 let dev_root_inode: Arc<LockedDevFSInode> = self.root_inode.clone(); 195 match device.metadata().unwrap().file_type { 196 // 字节设备挂载在 /dev/char 197 FileType::CharDevice => { 198 if dev_root_inode.find("char").is_err() { 199 return Err(SystemError::ENOENT); 200 } 201 202 let any_char_inode = dev_root_inode.find("char")?; 203 let dev_char_inode = any_char_inode 204 .as_any_ref() 205 .downcast_ref::<LockedDevFSInode>() 206 .unwrap(); 207 // TODO: 调用设备的卸载接口(当引入卸载接口之后) 208 dev_char_inode.remove(name)?; 209 } 210 FileType::BlockDevice => { 211 if dev_root_inode.find("block").is_err() { 212 return Err(SystemError::ENOENT); 213 } 214 215 let any_block_inode = dev_root_inode.find("block")?; 216 let dev_block_inode = any_block_inode 217 .as_any_ref() 218 .downcast_ref::<LockedDevFSInode>() 219 .unwrap(); 220 221 dev_block_inode.remove(name)?; 222 } 223 _ => { 224 return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP); 225 } 226 } 227 228 return Ok(()); 229 } 230 } 231 232 /// @brief dev文件i节点(锁) 233 #[derive(Debug)] 234 pub struct LockedDevFSInode(SpinLock<DevFSInode>); 235 236 /// @brief dev文件i节点(无锁) 237 #[derive(Debug)] 238 pub struct DevFSInode { 239 /// 指向父Inode的弱引用 240 parent: Weak<LockedDevFSInode>, 241 /// 指向自身的弱引用 242 self_ref: Weak<LockedDevFSInode>, 243 /// 子Inode的B树 244 children: BTreeMap<String, Arc<dyn IndexNode>>, 245 /// 指向inode所在的文件系统对象的指针 246 fs: Weak<DevFS>, 247 /// INode 元数据 248 metadata: Metadata, 249 } 250 251 impl DevFSInode { 252 pub fn new(dev_type_: FileType, mode: ModeType, data_: usize) -> Self { 253 return Self::new_with_parent(Weak::default(), dev_type_, mode, data_); 254 } 255 256 pub fn new_with_parent( 257 parent: Weak<LockedDevFSInode>, 258 dev_type_: FileType, 259 mode: ModeType, 260 data_: usize, 261 ) -> Self { 262 return DevFSInode { 263 parent, 264 self_ref: Weak::default(), 265 children: BTreeMap::new(), 266 metadata: Metadata { 267 dev_id: 1, 268 inode_id: generate_inode_id(), 269 size: 0, 270 blk_size: 0, 271 blocks: 0, 272 atime: TimeSpec::default(), 273 mtime: TimeSpec::default(), 274 ctime: TimeSpec::default(), 275 file_type: dev_type_, // 文件夹 276 mode, 277 nlinks: 1, 278 uid: 0, 279 gid: 0, 280 raw_dev: DeviceNumber::from(data_ as u32), 281 }, 282 fs: Weak::default(), 283 }; 284 } 285 } 286 287 impl LockedDevFSInode { 288 pub fn add_dir(&self, name: &str) -> Result<(), SystemError> { 289 let guard: SpinLockGuard<DevFSInode> = self.0.lock(); 290 291 if guard.children.contains_key(name) { 292 return Err(SystemError::EEXIST); 293 } 294 295 match self.do_create_with_data( 296 guard, 297 name, 298 FileType::Dir, 299 ModeType::from_bits_truncate(0o755), 300 0, 301 ) { 302 Ok(inode) => inode, 303 Err(err) => { 304 return Err(err); 305 } 306 }; 307 308 return Ok(()); 309 } 310 311 pub fn add_dev(&self, name: &str, dev: Arc<dyn IndexNode>) -> Result<(), SystemError> { 312 let mut this = self.0.lock(); 313 314 if this.children.contains_key(name) { 315 return Err(SystemError::EEXIST); 316 } 317 318 this.children.insert(name.to_string(), dev); 319 return Ok(()); 320 } 321 322 pub fn remove(&self, name: &str) -> Result<(), SystemError> { 323 let x = self 324 .0 325 .lock() 326 .children 327 .remove(name) 328 .ok_or(SystemError::ENOENT)?; 329 330 drop(x); 331 return Ok(()); 332 } 333 334 fn do_create_with_data( 335 &self, 336 mut guard: SpinLockGuard<DevFSInode>, 337 name: &str, 338 file_type: FileType, 339 mode: ModeType, 340 data: usize, 341 ) -> Result<Arc<dyn IndexNode>, SystemError> { 342 if guard.metadata.file_type != FileType::Dir { 343 return Err(SystemError::ENOTDIR); 344 } 345 346 // 如果有重名的,则返回 347 if guard.children.contains_key(name) { 348 return Err(SystemError::EEXIST); 349 } 350 351 // 创建inode 352 let result: Arc<LockedDevFSInode> = Arc::new(LockedDevFSInode(SpinLock::new(DevFSInode { 353 parent: guard.self_ref.clone(), 354 self_ref: Weak::default(), 355 children: BTreeMap::new(), 356 metadata: Metadata { 357 dev_id: 0, 358 inode_id: generate_inode_id(), 359 size: 0, 360 blk_size: 0, 361 blocks: 0, 362 atime: TimeSpec::default(), 363 mtime: TimeSpec::default(), 364 ctime: TimeSpec::default(), 365 file_type, 366 mode, 367 nlinks: 1, 368 uid: 0, 369 gid: 0, 370 raw_dev: DeviceNumber::from(data as u32), 371 }, 372 fs: guard.fs.clone(), 373 }))); 374 375 // 初始化inode的自引用的weak指针 376 result.0.lock().self_ref = Arc::downgrade(&result); 377 378 // 将子inode插入父inode的B树中 379 guard.children.insert(String::from(name), result.clone()); 380 return Ok(result); 381 } 382 } 383 384 impl IndexNode for LockedDevFSInode { 385 fn as_any_ref(&self) -> &dyn core::any::Any { 386 self 387 } 388 389 fn open( 390 &self, 391 _data: &mut super::vfs::FilePrivateData, 392 _mode: &FileMode, 393 ) -> Result<(), SystemError> { 394 return Ok(()); 395 } 396 397 fn close(&self, _data: &mut super::vfs::FilePrivateData) -> Result<(), SystemError> { 398 return Ok(()); 399 } 400 401 fn create_with_data( 402 &self, 403 name: &str, 404 file_type: FileType, 405 mode: ModeType, 406 data: usize, 407 ) -> Result<Arc<dyn IndexNode>, SystemError> { 408 // 获取当前inode 409 let guard: SpinLockGuard<DevFSInode> = self.0.lock(); 410 // 如果当前inode不是文件夹,则返回 411 return self.do_create_with_data(guard, name, file_type, mode, data); 412 } 413 414 fn find(&self, name: &str) -> Result<Arc<dyn IndexNode>, SystemError> { 415 let inode = self.0.lock(); 416 417 if inode.metadata.file_type != FileType::Dir { 418 return Err(SystemError::ENOTDIR); 419 } 420 421 match name { 422 "" | "." => { 423 return Ok(inode.self_ref.upgrade().ok_or(SystemError::ENOENT)?); 424 } 425 ".." => { 426 return Ok(inode.parent.upgrade().ok_or(SystemError::ENOENT)?); 427 } 428 name => { 429 // 在子目录项中查找 430 return Ok(inode.children.get(name).ok_or(SystemError::ENOENT)?.clone()); 431 } 432 } 433 } 434 435 fn fs(&self) -> Arc<dyn FileSystem> { 436 return self.0.lock().fs.upgrade().unwrap(); 437 } 438 439 fn get_entry_name(&self, ino: super::vfs::InodeId) -> Result<String, SystemError> { 440 let inode: SpinLockGuard<DevFSInode> = self.0.lock(); 441 if inode.metadata.file_type != FileType::Dir { 442 return Err(SystemError::ENOTDIR); 443 } 444 445 match ino.into() { 446 0 => { 447 return Ok(String::from(".")); 448 } 449 1 => { 450 return Ok(String::from("..")); 451 } 452 ino => { 453 // 暴力遍历所有的children,判断inode id是否相同 454 // TODO: 优化这里,这个地方性能很差! 455 let mut key: Vec<String> = inode 456 .children 457 .keys() 458 .filter(|k| { 459 inode 460 .children 461 .get(*k) 462 .unwrap() 463 .metadata() 464 .unwrap() 465 .inode_id 466 .into() 467 == ino 468 }) 469 .cloned() 470 .collect(); 471 472 match key.len() { 473 0=>{return Err(SystemError::ENOENT);} 474 1=>{return Ok(key.remove(0));} 475 _ => panic!("Devfs get_entry_name: key.len()={key_len}>1, current inode_id={inode_id:?}, to find={to_find:?}", key_len=key.len(), inode_id = inode.metadata.inode_id, to_find=ino) 476 } 477 } 478 } 479 } 480 481 fn ioctl( 482 &self, 483 _cmd: u32, 484 _data: usize, 485 _private_data: &FilePrivateData, 486 ) -> Result<usize, SystemError> { 487 Err(SystemError::EOPNOTSUPP_OR_ENOTSUP) 488 } 489 490 fn list(&self) -> Result<Vec<String>, SystemError> { 491 let info = self.metadata()?; 492 if info.file_type != FileType::Dir { 493 return Err(SystemError::ENOTDIR); 494 } 495 496 let mut keys: Vec<String> = Vec::new(); 497 keys.push(String::from(".")); 498 keys.push(String::from("..")); 499 keys.append(&mut self.0.lock().children.keys().cloned().collect()); 500 501 return Ok(keys); 502 } 503 504 fn metadata(&self) -> Result<Metadata, SystemError> { 505 return Ok(self.0.lock().metadata.clone()); 506 } 507 508 fn set_metadata(&self, metadata: &Metadata) -> Result<(), SystemError> { 509 let mut inode = self.0.lock(); 510 inode.metadata.atime = metadata.atime; 511 inode.metadata.mtime = metadata.mtime; 512 inode.metadata.ctime = metadata.ctime; 513 inode.metadata.mode = metadata.mode; 514 inode.metadata.uid = metadata.uid; 515 inode.metadata.gid = metadata.gid; 516 517 return Ok(()); 518 } 519 520 /// 读设备 - 应该调用设备的函数读写,而不是通过文件系统读写 521 fn read_at( 522 &self, 523 _offset: usize, 524 _len: usize, 525 _buf: &mut [u8], 526 _data: &mut super::vfs::file::FilePrivateData, 527 ) -> Result<usize, SystemError> { 528 kerror!("DevFS: read_at is not supported!"); 529 Err(SystemError::EOPNOTSUPP_OR_ENOTSUP) 530 } 531 532 /// 写设备 - 应该调用设备的函数读写,而不是通过文件系统读写 533 fn write_at( 534 &self, 535 _offset: usize, 536 _len: usize, 537 _buf: &[u8], 538 _data: &mut super::vfs::file::FilePrivateData, 539 ) -> Result<usize, SystemError> { 540 Err(SystemError::EOPNOTSUPP_OR_ENOTSUP) 541 } 542 } 543 544 /// @brief 所有的设备INode都需要额外实现这个trait 545 pub trait DeviceINode: IndexNode { 546 fn set_fs(&self, fs: Weak<DevFS>); 547 // TODO: 增加 unregister 方法 548 } 549 550 /// @brief 获取devfs实例的强类型不可变引用 551 macro_rules! devfs_exact_ref { 552 () => {{ 553 let devfs_inode: Result<Arc<dyn IndexNode>, SystemError> = ROOT_INODE().find("dev"); 554 if let Err(e) = devfs_inode { 555 kerror!("failed to get DevFS ref. errcode = {:?}", e); 556 return Err(SystemError::ENOENT); 557 } 558 559 let binding = devfs_inode.unwrap(); 560 let devfs_inode: &LockedDevFSInode = binding 561 .as_any_ref() 562 .downcast_ref::<LockedDevFSInode>() 563 .unwrap(); 564 let binding = devfs_inode.fs(); 565 binding 566 } 567 .as_any_ref() 568 .downcast_ref::<DevFS>() 569 .unwrap()}; 570 } 571 /// @brief devfs的设备注册函数 572 pub fn devfs_register<T: DeviceINode>(name: &str, device: Arc<T>) -> Result<(), SystemError> { 573 return devfs_exact_ref!().register_device(name, device); 574 } 575 576 /// @brief devfs的设备卸载函数 577 #[allow(dead_code)] 578 pub fn devfs_unregister<T: DeviceINode>(name: &str, device: Arc<T>) -> Result<(), SystemError> { 579 return devfs_exact_ref!().unregister_device(name, device); 580 } 581 582 pub fn devfs_init() -> Result<(), SystemError> { 583 static INIT: Once = Once::new(); 584 let mut result = None; 585 INIT.call_once(|| { 586 kinfo!("Initializing DevFS..."); 587 // 创建 devfs 实例 588 let devfs: Arc<DevFS> = DevFS::new(); 589 // devfs 挂载 590 let _t = ROOT_INODE() 591 .find("dev") 592 .expect("Cannot find /dev") 593 .mount(devfs) 594 .expect("Failed to mount devfs"); 595 kinfo!("DevFS mounted."); 596 result = Some(Ok(())); 597 }); 598 599 return result.unwrap(); 600 } 601