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::PosixTimeSpec, 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 // ptmx设备 151 if name == "ptmx" { 152 dev_root_inode.add_dev(name, device.clone())?; 153 } 154 device.set_fs(dev_char_inode.0.lock().fs.clone()); 155 } 156 FileType::BlockDevice => { 157 if dev_root_inode.find("block").is_err() { 158 dev_root_inode.create( 159 "block", 160 FileType::Dir, 161 ModeType::from_bits_truncate(0o755), 162 )?; 163 } 164 165 let any_block_inode = dev_root_inode.find("block")?; 166 let dev_block_inode: &LockedDevFSInode = any_block_inode 167 .as_any_ref() 168 .downcast_ref::<LockedDevFSInode>() 169 .unwrap(); 170 171 dev_block_inode.add_dev(name, device.clone())?; 172 device.set_fs(dev_block_inode.0.lock().fs.clone()); 173 } 174 FileType::KvmDevice => { 175 dev_root_inode 176 .add_dev(name, device.clone()) 177 .expect("DevFS: Failed to register /dev/kvm"); 178 } 179 FileType::FramebufferDevice => { 180 dev_root_inode 181 .add_dev(name, device.clone()) 182 .expect("DevFS: Failed to register /dev/fb"); 183 } 184 _ => { 185 return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP); 186 } 187 } 188 189 return Ok(()); 190 } 191 192 /// @brief 卸载设备 193 pub fn unregister_device<T: DeviceINode>( 194 &self, 195 name: &str, 196 device: Arc<T>, 197 ) -> Result<(), SystemError> { 198 let dev_root_inode: Arc<LockedDevFSInode> = self.root_inode.clone(); 199 match device.metadata().unwrap().file_type { 200 // 字节设备挂载在 /dev/char 201 FileType::CharDevice => { 202 if dev_root_inode.find("char").is_err() { 203 return Err(SystemError::ENOENT); 204 } 205 206 let any_char_inode = dev_root_inode.find("char")?; 207 let dev_char_inode = any_char_inode 208 .as_any_ref() 209 .downcast_ref::<LockedDevFSInode>() 210 .unwrap(); 211 // TODO: 调用设备的卸载接口(当引入卸载接口之后) 212 dev_char_inode.remove(name)?; 213 } 214 FileType::BlockDevice => { 215 if dev_root_inode.find("block").is_err() { 216 return Err(SystemError::ENOENT); 217 } 218 219 let any_block_inode = dev_root_inode.find("block")?; 220 let dev_block_inode = any_block_inode 221 .as_any_ref() 222 .downcast_ref::<LockedDevFSInode>() 223 .unwrap(); 224 225 dev_block_inode.remove(name)?; 226 } 227 _ => { 228 return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP); 229 } 230 } 231 232 return Ok(()); 233 } 234 } 235 236 /// @brief dev文件i节点(锁) 237 #[derive(Debug)] 238 pub struct LockedDevFSInode(SpinLock<DevFSInode>); 239 240 /// @brief dev文件i节点(无锁) 241 #[derive(Debug)] 242 pub struct DevFSInode { 243 /// 指向父Inode的弱引用 244 parent: Weak<LockedDevFSInode>, 245 /// 指向自身的弱引用 246 self_ref: Weak<LockedDevFSInode>, 247 /// 子Inode的B树 248 children: BTreeMap<String, Arc<dyn IndexNode>>, 249 /// 指向inode所在的文件系统对象的指针 250 fs: Weak<DevFS>, 251 /// INode 元数据 252 metadata: Metadata, 253 } 254 255 impl DevFSInode { 256 pub fn new(dev_type_: FileType, mode: ModeType, data_: usize) -> Self { 257 return Self::new_with_parent(Weak::default(), dev_type_, mode, data_); 258 } 259 260 pub fn new_with_parent( 261 parent: Weak<LockedDevFSInode>, 262 dev_type_: FileType, 263 mode: ModeType, 264 data_: usize, 265 ) -> Self { 266 return DevFSInode { 267 parent, 268 self_ref: Weak::default(), 269 children: BTreeMap::new(), 270 metadata: Metadata { 271 dev_id: 1, 272 inode_id: generate_inode_id(), 273 size: 0, 274 blk_size: 0, 275 blocks: 0, 276 atime: PosixTimeSpec::default(), 277 mtime: PosixTimeSpec::default(), 278 ctime: PosixTimeSpec::default(), 279 file_type: dev_type_, // 文件夹 280 mode, 281 nlinks: 1, 282 uid: 0, 283 gid: 0, 284 raw_dev: DeviceNumber::from(data_ as u32), 285 }, 286 fs: Weak::default(), 287 }; 288 } 289 } 290 291 impl LockedDevFSInode { 292 pub fn add_dir(&self, name: &str) -> Result<(), SystemError> { 293 let guard: SpinLockGuard<DevFSInode> = self.0.lock(); 294 295 if guard.children.contains_key(name) { 296 return Err(SystemError::EEXIST); 297 } 298 299 match self.do_create_with_data( 300 guard, 301 name, 302 FileType::Dir, 303 ModeType::from_bits_truncate(0o755), 304 0, 305 ) { 306 Ok(inode) => inode, 307 Err(err) => { 308 return Err(err); 309 } 310 }; 311 312 return Ok(()); 313 } 314 315 pub fn add_dev(&self, name: &str, dev: Arc<dyn IndexNode>) -> Result<(), SystemError> { 316 let mut this = self.0.lock(); 317 318 if this.children.contains_key(name) { 319 return Err(SystemError::EEXIST); 320 } 321 322 this.children.insert(name.to_string(), dev); 323 return Ok(()); 324 } 325 326 pub fn remove(&self, name: &str) -> Result<(), SystemError> { 327 let x = self 328 .0 329 .lock() 330 .children 331 .remove(name) 332 .ok_or(SystemError::ENOENT)?; 333 334 drop(x); 335 return Ok(()); 336 } 337 338 fn do_create_with_data( 339 &self, 340 mut guard: SpinLockGuard<DevFSInode>, 341 name: &str, 342 file_type: FileType, 343 mode: ModeType, 344 data: usize, 345 ) -> Result<Arc<dyn IndexNode>, SystemError> { 346 if guard.metadata.file_type != FileType::Dir { 347 return Err(SystemError::ENOTDIR); 348 } 349 350 // 如果有重名的,则返回 351 if guard.children.contains_key(name) { 352 return Err(SystemError::EEXIST); 353 } 354 355 // 创建inode 356 let result: Arc<LockedDevFSInode> = Arc::new(LockedDevFSInode(SpinLock::new(DevFSInode { 357 parent: guard.self_ref.clone(), 358 self_ref: Weak::default(), 359 children: BTreeMap::new(), 360 metadata: Metadata { 361 dev_id: 0, 362 inode_id: generate_inode_id(), 363 size: 0, 364 blk_size: 0, 365 blocks: 0, 366 atime: PosixTimeSpec::default(), 367 mtime: PosixTimeSpec::default(), 368 ctime: PosixTimeSpec::default(), 369 file_type, 370 mode, 371 nlinks: 1, 372 uid: 0, 373 gid: 0, 374 raw_dev: DeviceNumber::from(data as u32), 375 }, 376 fs: guard.fs.clone(), 377 }))); 378 379 // 初始化inode的自引用的weak指针 380 result.0.lock().self_ref = Arc::downgrade(&result); 381 382 // 将子inode插入父inode的B树中 383 guard.children.insert(String::from(name), result.clone()); 384 return Ok(result); 385 } 386 } 387 388 impl IndexNode for LockedDevFSInode { 389 fn as_any_ref(&self) -> &dyn core::any::Any { 390 self 391 } 392 393 fn open( 394 &self, 395 _data: SpinLockGuard<FilePrivateData>, 396 _mode: &FileMode, 397 ) -> Result<(), SystemError> { 398 return Ok(()); 399 } 400 401 fn close(&self, _data: SpinLockGuard<FilePrivateData>) -> Result<(), SystemError> { 402 return Ok(()); 403 } 404 405 fn create_with_data( 406 &self, 407 name: &str, 408 file_type: FileType, 409 mode: ModeType, 410 data: usize, 411 ) -> Result<Arc<dyn IndexNode>, SystemError> { 412 // 获取当前inode 413 let guard: SpinLockGuard<DevFSInode> = self.0.lock(); 414 // 如果当前inode不是文件夹,则返回 415 return self.do_create_with_data(guard, name, file_type, mode, data); 416 } 417 418 fn find(&self, name: &str) -> Result<Arc<dyn IndexNode>, SystemError> { 419 let inode = self.0.lock(); 420 421 if inode.metadata.file_type != FileType::Dir { 422 return Err(SystemError::ENOTDIR); 423 } 424 425 match name { 426 "" | "." => { 427 return Ok(inode.self_ref.upgrade().ok_or(SystemError::ENOENT)?); 428 } 429 ".." => { 430 return Ok(inode.parent.upgrade().ok_or(SystemError::ENOENT)?); 431 } 432 name => { 433 // 在子目录项中查找 434 return Ok(inode.children.get(name).ok_or(SystemError::ENOENT)?.clone()); 435 } 436 } 437 } 438 439 fn fs(&self) -> Arc<dyn FileSystem> { 440 return self.0.lock().fs.upgrade().unwrap(); 441 } 442 443 fn get_entry_name(&self, ino: super::vfs::InodeId) -> Result<String, SystemError> { 444 let inode: SpinLockGuard<DevFSInode> = self.0.lock(); 445 if inode.metadata.file_type != FileType::Dir { 446 return Err(SystemError::ENOTDIR); 447 } 448 449 match ino.into() { 450 0 => { 451 return Ok(String::from(".")); 452 } 453 1 => { 454 return Ok(String::from("..")); 455 } 456 ino => { 457 // 暴力遍历所有的children,判断inode id是否相同 458 // TODO: 优化这里,这个地方性能很差! 459 let mut key: Vec<String> = inode 460 .children 461 .keys() 462 .filter(|k| { 463 inode 464 .children 465 .get(*k) 466 .unwrap() 467 .metadata() 468 .unwrap() 469 .inode_id 470 .into() 471 == ino 472 }) 473 .cloned() 474 .collect(); 475 476 match key.len() { 477 0=>{return Err(SystemError::ENOENT);} 478 1=>{return Ok(key.remove(0));} 479 _ => 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) 480 } 481 } 482 } 483 } 484 485 fn ioctl( 486 &self, 487 _cmd: u32, 488 _data: usize, 489 _private_data: &FilePrivateData, 490 ) -> Result<usize, SystemError> { 491 Err(SystemError::EOPNOTSUPP_OR_ENOTSUP) 492 } 493 494 fn list(&self) -> Result<Vec<String>, SystemError> { 495 let info = self.metadata()?; 496 if info.file_type != FileType::Dir { 497 return Err(SystemError::ENOTDIR); 498 } 499 500 let mut keys: Vec<String> = Vec::new(); 501 keys.push(String::from(".")); 502 keys.push(String::from("..")); 503 keys.append(&mut self.0.lock().children.keys().cloned().collect()); 504 505 return Ok(keys); 506 } 507 508 fn metadata(&self) -> Result<Metadata, SystemError> { 509 return Ok(self.0.lock().metadata.clone()); 510 } 511 512 fn set_metadata(&self, metadata: &Metadata) -> Result<(), SystemError> { 513 let mut inode = self.0.lock(); 514 inode.metadata.atime = metadata.atime; 515 inode.metadata.mtime = metadata.mtime; 516 inode.metadata.ctime = metadata.ctime; 517 inode.metadata.mode = metadata.mode; 518 inode.metadata.uid = metadata.uid; 519 inode.metadata.gid = metadata.gid; 520 521 return Ok(()); 522 } 523 524 /// 读设备 - 应该调用设备的函数读写,而不是通过文件系统读写 525 fn read_at( 526 &self, 527 _offset: usize, 528 _len: usize, 529 _buf: &mut [u8], 530 _data: SpinLockGuard<FilePrivateData>, 531 ) -> Result<usize, SystemError> { 532 kerror!("DevFS: read_at is not supported!"); 533 Err(SystemError::EOPNOTSUPP_OR_ENOTSUP) 534 } 535 536 /// 写设备 - 应该调用设备的函数读写,而不是通过文件系统读写 537 fn write_at( 538 &self, 539 _offset: usize, 540 _len: usize, 541 _buf: &[u8], 542 _data: SpinLockGuard<FilePrivateData>, 543 ) -> Result<usize, SystemError> { 544 Err(SystemError::EOPNOTSUPP_OR_ENOTSUP) 545 } 546 } 547 548 /// @brief 所有的设备INode都需要额外实现这个trait 549 pub trait DeviceINode: IndexNode { 550 fn set_fs(&self, fs: Weak<DevFS>); 551 // TODO: 增加 unregister 方法 552 } 553 554 /// @brief 获取devfs实例的强类型不可变引用 555 macro_rules! devfs_exact_ref { 556 () => {{ 557 let devfs_inode: Result<Arc<dyn IndexNode>, SystemError> = ROOT_INODE().find("dev"); 558 if let Err(e) = devfs_inode { 559 kerror!("failed to get DevFS ref. errcode = {:?}", e); 560 return Err(SystemError::ENOENT); 561 } 562 563 let binding = devfs_inode.unwrap(); 564 let devfs_inode: &LockedDevFSInode = binding 565 .as_any_ref() 566 .downcast_ref::<LockedDevFSInode>() 567 .unwrap(); 568 let binding = devfs_inode.fs(); 569 binding 570 } 571 .as_any_ref() 572 .downcast_ref::<DevFS>() 573 .unwrap()}; 574 } 575 /// @brief devfs的设备注册函数 576 pub fn devfs_register<T: DeviceINode>(name: &str, device: Arc<T>) -> Result<(), SystemError> { 577 return devfs_exact_ref!().register_device(name, device); 578 } 579 580 /// @brief devfs的设备卸载函数 581 #[allow(dead_code)] 582 pub fn devfs_unregister<T: DeviceINode>(name: &str, device: Arc<T>) -> Result<(), SystemError> { 583 return devfs_exact_ref!().unregister_device(name, device); 584 } 585 586 pub fn devfs_init() -> Result<(), SystemError> { 587 static INIT: Once = Once::new(); 588 let mut result = None; 589 INIT.call_once(|| { 590 kinfo!("Initializing DevFS..."); 591 // 创建 devfs 实例 592 let devfs: Arc<DevFS> = DevFS::new(); 593 // devfs 挂载 594 let _t = ROOT_INODE() 595 .find("dev") 596 .expect("Cannot find /dev") 597 .mount(devfs) 598 .expect("Failed to mount devfs"); 599 kinfo!("DevFS mounted."); 600 result = Some(Ok(())); 601 }); 602 603 return result.unwrap(); 604 } 605