1 use core::intrinsics::unlikely; 2 use core::{any::Any, fmt::Debug}; 3 use system_error::SystemError; 4 5 use alloc::{ 6 collections::BTreeMap, 7 string::String, 8 sync::{Arc, Weak}, 9 vec::Vec, 10 }; 11 12 use crate::driver::base::device::device_number::DeviceNumber; 13 use crate::filesystem::vfs::SpecialNodeData; 14 use crate::ipc::pipe::LockedPipeInode; 15 use crate::{ 16 driver::base::block::{block_device::LBA_SIZE, disk_info::Partition, SeekFrom}, 17 filesystem::vfs::{ 18 core::generate_inode_id, 19 file::{FileMode, FilePrivateData}, 20 syscall::ModeType, 21 FileSystem, FileType, IndexNode, InodeId, Metadata, 22 }, 23 kerror, 24 libs::{ 25 spinlock::{SpinLock, SpinLockGuard}, 26 vec_cursor::VecCursor, 27 }, 28 time::TimeSpec, 29 }; 30 31 use super::entry::FATFile; 32 use super::{ 33 bpb::{BiosParameterBlock, FATType}, 34 entry::{FATDir, FATDirEntry, FATDirIter, FATEntry}, 35 utils::RESERVED_CLUSTERS, 36 }; 37 38 /// FAT32文件系统的最大的文件大小 39 pub const MAX_FILE_SIZE: u64 = 0xffff_ffff; 40 41 /// @brief 表示当前簇和上一个簇的关系的结构体 42 /// 定义这样一个结构体的原因是,FAT文件系统的文件中,前后两个簇具有关联关系。 43 #[derive(Debug, Clone, Copy, Default)] 44 pub struct Cluster { 45 pub cluster_num: u64, 46 pub parent_cluster: u64, 47 } 48 49 impl PartialOrd for Cluster { 50 /// @brief 根据当前簇号比较大小 51 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> { 52 return self.cluster_num.partial_cmp(&other.cluster_num); 53 } 54 } 55 56 impl PartialEq for Cluster { 57 /// @brief 根据当前簇号比较是否相等 58 fn eq(&self, other: &Self) -> bool { 59 self.cluster_num == other.cluster_num 60 } 61 } 62 63 impl Eq for Cluster {} 64 65 #[derive(Debug)] 66 pub struct FATFileSystem { 67 /// 当前文件系统所在的分区 68 pub partition: Arc<Partition>, 69 /// 当前文件系统的BOPB 70 pub bpb: BiosParameterBlock, 71 /// 当前文件系统的第一个数据扇区(相对分区开始位置) 72 pub first_data_sector: u64, 73 /// 文件系统信息结构体 74 pub fs_info: Arc<LockedFATFsInfo>, 75 /// 文件系统的根inode 76 root_inode: Arc<LockedFATInode>, 77 } 78 79 /// FAT文件系统的Inode 80 #[derive(Debug)] 81 pub struct LockedFATInode(SpinLock<FATInode>); 82 83 #[derive(Debug)] 84 pub struct LockedFATFsInfo(SpinLock<FATFsInfo>); 85 86 impl LockedFATFsInfo { 87 #[inline] 88 pub fn new(fs_info: FATFsInfo) -> Self { 89 return Self(SpinLock::new(fs_info)); 90 } 91 } 92 93 #[derive(Debug)] 94 pub struct FATInode { 95 /// 指向父Inode的弱引用 96 parent: Weak<LockedFATInode>, 97 /// 指向自身的弱引用 98 self_ref: Weak<LockedFATInode>, 99 /// 子Inode的B树. 该数据结构用作缓存区。其中,它的key表示inode的名称。 100 /// 请注意,由于FAT的查询过程对大小写不敏感,因此我们选择让key全部是大写的,方便统一操作。 101 children: BTreeMap<String, Arc<LockedFATInode>>, 102 /// 当前inode的元数据 103 metadata: Metadata, 104 /// 指向inode所在的文件系统对象的指针 105 fs: Weak<FATFileSystem>, 106 107 /// 根据不同的Inode类型,创建不同的私有字段 108 inode_type: FATDirEntry, 109 110 /// 若该节点是特殊文件节点,该字段则为真正的文件节点 111 special_node: Option<SpecialNodeData>, 112 } 113 114 impl FATInode { 115 /// @brief 更新当前inode的元数据 116 pub fn update_metadata(&mut self) { 117 // todo: 更新文件的访问时间等信息 118 match &self.inode_type { 119 FATDirEntry::File(f) | FATDirEntry::VolId(f) => { 120 self.metadata.size = f.size() as i64; 121 } 122 FATDirEntry::Dir(d) => { 123 self.metadata.size = d.size(&self.fs.upgrade().unwrap().clone()) as i64; 124 } 125 FATDirEntry::UnInit => { 126 kerror!("update_metadata: Uninitialized FATDirEntry: {:?}", self); 127 return; 128 } 129 }; 130 } 131 132 fn find(&mut self, name: &str) -> Result<Arc<LockedFATInode>, SystemError> { 133 match &self.inode_type { 134 FATDirEntry::Dir(d) => { 135 // 尝试在缓存区查找 136 if let Some(entry) = self.children.get(&name.to_uppercase()) { 137 return Ok(entry.clone()); 138 } 139 // 在缓存区找不到 140 // 在磁盘查找 141 let fat_entry: FATDirEntry = 142 d.find_entry(name, None, None, self.fs.upgrade().unwrap())?; 143 // 创建新的inode 144 let entry_inode: Arc<LockedFATInode> = LockedFATInode::new( 145 self.fs.upgrade().unwrap(), 146 self.self_ref.clone(), 147 fat_entry, 148 ); 149 // 加入缓存区, 由于FAT文件系统的大小写不敏感问题,因此存入缓存区的key应当是全大写的 150 self.children 151 .insert(name.to_uppercase(), entry_inode.clone()); 152 return Ok(entry_inode); 153 } 154 FATDirEntry::UnInit => { 155 panic!( 156 "Uninitialized FAT Inode, fs = {:?}, inode={self:?}", 157 self.fs 158 ) 159 } 160 _ => { 161 return Err(SystemError::ENOTDIR); 162 } 163 } 164 } 165 } 166 167 impl LockedFATInode { 168 pub fn new( 169 fs: Arc<FATFileSystem>, 170 parent: Weak<LockedFATInode>, 171 inode_type: FATDirEntry, 172 ) -> Arc<LockedFATInode> { 173 let file_type = if let FATDirEntry::Dir(_) = inode_type { 174 FileType::Dir 175 } else { 176 FileType::File 177 }; 178 179 let inode: Arc<LockedFATInode> = Arc::new(LockedFATInode(SpinLock::new(FATInode { 180 parent: parent, 181 self_ref: Weak::default(), 182 children: BTreeMap::new(), 183 fs: Arc::downgrade(&fs), 184 inode_type: inode_type, 185 metadata: Metadata { 186 dev_id: 0, 187 inode_id: generate_inode_id(), 188 size: 0, 189 blk_size: fs.bpb.bytes_per_sector as usize, 190 blocks: if let FATType::FAT32(_) = fs.bpb.fat_type { 191 fs.bpb.total_sectors_32 as usize 192 } else { 193 fs.bpb.total_sectors_16 as usize 194 }, 195 atime: TimeSpec::default(), 196 mtime: TimeSpec::default(), 197 ctime: TimeSpec::default(), 198 file_type: file_type, 199 mode: ModeType::from_bits_truncate(0o777), 200 nlinks: 1, 201 uid: 0, 202 gid: 0, 203 raw_dev: DeviceNumber::default(), 204 }, 205 special_node: None, 206 }))); 207 208 inode.0.lock().self_ref = Arc::downgrade(&inode); 209 210 inode.0.lock().update_metadata(); 211 212 return inode; 213 } 214 } 215 216 /// FsInfo结构体(内存中的一份拷贝,当卸载卷或者sync的时候,把它写入磁盘) 217 #[derive(Debug)] 218 pub struct FATFsInfo { 219 /// Lead Signature - must equal 0x41615252 220 lead_sig: u32, 221 /// Value must equal 0x61417272 222 struc_sig: u32, 223 /// 空闲簇数目 224 free_count: u32, 225 /// 第一个空闲簇的位置(不一定准确,仅供加速查找) 226 next_free: u32, 227 /// 0xAA550000 228 trail_sig: u32, 229 /// Dirty flag to flush to disk 230 dirty: bool, 231 /// FsInfo Structure 在磁盘上的字节偏移量 232 /// Not present for FAT12 and FAT16 233 offset: Option<u64>, 234 } 235 236 impl FileSystem for FATFileSystem { 237 fn root_inode(&self) -> Arc<dyn crate::filesystem::vfs::IndexNode> { 238 return self.root_inode.clone(); 239 } 240 241 fn info(&self) -> crate::filesystem::vfs::FsInfo { 242 todo!() 243 } 244 245 /// @brief 本函数用于实现动态转换。 246 /// 具体的文件系统在实现本函数时,最简单的方式就是:直接返回self 247 fn as_any_ref(&self) -> &dyn Any { 248 self 249 } 250 251 fn name(&self) -> &str { 252 "fat" 253 } 254 } 255 256 impl FATFileSystem { 257 /// FAT12允许的最大簇号 258 pub const FAT12_MAX_CLUSTER: u32 = 0xFF5; 259 /// FAT16允许的最大簇号 260 pub const FAT16_MAX_CLUSTER: u32 = 0xFFF5; 261 /// FAT32允许的最大簇号 262 pub const FAT32_MAX_CLUSTER: u32 = 0x0FFFFFF7; 263 264 pub fn new(partition: Arc<Partition>) -> Result<Arc<FATFileSystem>, SystemError> { 265 let bpb = BiosParameterBlock::new(partition.clone())?; 266 267 // 从磁盘上读取FAT32文件系统的FsInfo结构体 268 let fs_info: FATFsInfo = match bpb.fat_type { 269 FATType::FAT32(bpb32) => { 270 let fs_info_in_disk_bytes_offset = partition.lba_start * LBA_SIZE as u64 271 + bpb32.fs_info as u64 * bpb.bytes_per_sector as u64; 272 FATFsInfo::new( 273 partition.clone(), 274 fs_info_in_disk_bytes_offset, 275 bpb.bytes_per_sector as usize, 276 )? 277 } 278 _ => FATFsInfo::default(), 279 }; 280 281 // 根目录项占用的扇区数(向上取整) 282 let root_dir_sectors: u64 = ((bpb.root_entries_cnt as u64 * 32) 283 + (bpb.bytes_per_sector as u64 - 1)) 284 / (bpb.bytes_per_sector as u64); 285 286 // FAT表大小(单位:扇区) 287 let fat_size = if bpb.fat_size_16 != 0 { 288 bpb.fat_size_16 as u64 289 } else { 290 match bpb.fat_type { 291 FATType::FAT32(x) => x.fat_size_32 as u64, 292 _ => { 293 kerror!("FAT12 and FAT16 volumes should have non-zero BPB_FATSz16"); 294 return Err(SystemError::EINVAL); 295 } 296 } 297 }; 298 299 let first_data_sector = 300 bpb.rsvd_sec_cnt as u64 + (bpb.num_fats as u64 * fat_size) + root_dir_sectors; 301 302 // 创建文件系统的根节点 303 let root_inode: Arc<LockedFATInode> = Arc::new(LockedFATInode(SpinLock::new(FATInode { 304 parent: Weak::default(), 305 self_ref: Weak::default(), 306 children: BTreeMap::new(), 307 fs: Weak::default(), 308 inode_type: FATDirEntry::UnInit, 309 metadata: Metadata { 310 dev_id: 0, 311 inode_id: generate_inode_id(), 312 size: 0, 313 blk_size: bpb.bytes_per_sector as usize, 314 blocks: if let FATType::FAT32(_) = bpb.fat_type { 315 bpb.total_sectors_32 as usize 316 } else { 317 bpb.total_sectors_16 as usize 318 }, 319 atime: TimeSpec::default(), 320 mtime: TimeSpec::default(), 321 ctime: TimeSpec::default(), 322 file_type: FileType::Dir, 323 mode: ModeType::from_bits_truncate(0o777), 324 nlinks: 1, 325 uid: 0, 326 gid: 0, 327 raw_dev: DeviceNumber::default(), 328 }, 329 special_node: None, 330 }))); 331 332 let result: Arc<FATFileSystem> = Arc::new(FATFileSystem { 333 partition: partition, 334 bpb, 335 first_data_sector, 336 fs_info: Arc::new(LockedFATFsInfo::new(fs_info)), 337 root_inode: root_inode, 338 }); 339 340 // 对root inode加锁,并继续完成初始化工作 341 let mut root_guard: SpinLockGuard<FATInode> = result.root_inode.0.lock(); 342 root_guard.inode_type = FATDirEntry::Dir(result.root_dir()); 343 root_guard.parent = Arc::downgrade(&result.root_inode); 344 root_guard.self_ref = Arc::downgrade(&result.root_inode); 345 root_guard.fs = Arc::downgrade(&result); 346 // 释放锁 347 drop(root_guard); 348 349 return Ok(result); 350 } 351 352 /// @brief 计算每个簇有多少个字节 353 #[inline] 354 pub fn bytes_per_cluster(&self) -> u64 { 355 return (self.bpb.bytes_per_sector as u64) * (self.bpb.sector_per_cluster as u64); 356 } 357 358 /// @brief 读取当前簇在FAT表中存储的信息 359 /// 360 /// @param cluster 当前簇 361 /// 362 /// @return Ok(FATEntry) 当前簇在FAT表中,存储的信息。(详情见FATEntry的注释) 363 /// @return Err(SystemError) 错误码 364 pub fn get_fat_entry(&self, cluster: Cluster) -> Result<FATEntry, SystemError> { 365 let current_cluster = cluster.cluster_num; 366 if current_cluster < 2 { 367 // 0号簇和1号簇是保留簇,不允许用户使用 368 return Err(SystemError::EINVAL); 369 } 370 371 let fat_type: FATType = self.bpb.fat_type; 372 // 获取FAT表的起始扇区(相对分区起始扇区的偏移量) 373 let fat_start_sector = self.fat_start_sector(); 374 let bytes_per_sec = self.bpb.bytes_per_sector as u64; 375 376 // cluster对应的FAT表项在分区内的字节偏移量 377 let fat_bytes_offset = 378 fat_type.get_fat_bytes_offset(cluster, fat_start_sector, bytes_per_sec); 379 380 // FAT表项所在的LBA地址 381 // let fat_ent_lba = self.get_lba_from_offset(self.bytes_to_sector(fat_bytes_offset)); 382 let fat_ent_lba = self.partition.lba_start + fat_bytes_offset / LBA_SIZE as u64; 383 384 // FAT表项在逻辑块内的字节偏移量 385 let blk_offset = self.get_in_block_offset(fat_bytes_offset); 386 387 let mut v = Vec::<u8>::new(); 388 v.resize(self.bpb.bytes_per_sector as usize, 0); 389 self.partition 390 .disk() 391 .read_at(fat_ent_lba as usize, 1 * self.lba_per_sector(), &mut v)?; 392 393 let mut cursor = VecCursor::new(v); 394 cursor.seek(SeekFrom::SeekSet(blk_offset as i64))?; 395 396 let res: FATEntry = match self.bpb.fat_type { 397 FATType::FAT12(_) => { 398 let mut entry = cursor.read_u16()?; 399 // 由于FAT12文件系统的FAT表,每个entry占用1.5字节,因此奇数的簇需要取高12位的值。 400 if (current_cluster & 1) > 0 { 401 entry >>= 4; 402 } else { 403 entry &= 0x0fff; 404 } 405 406 if entry == 0 { 407 FATEntry::Unused 408 } else if entry == 0x0ff7 { 409 FATEntry::Bad 410 } else if entry >= 0x0ff8 { 411 FATEntry::EndOfChain 412 } else { 413 FATEntry::Next(Cluster { 414 cluster_num: entry as u64, 415 parent_cluster: current_cluster, 416 }) 417 } 418 } 419 FATType::FAT16(_) => { 420 let entry = cursor.read_u16()?; 421 422 if entry == 0 { 423 FATEntry::Unused 424 } else if entry == 0xfff7 { 425 FATEntry::Bad 426 } else if entry >= 0xfff8 { 427 FATEntry::EndOfChain 428 } else { 429 FATEntry::Next(Cluster { 430 cluster_num: entry as u64, 431 parent_cluster: current_cluster, 432 }) 433 } 434 } 435 FATType::FAT32(_) => { 436 let entry = cursor.read_u32()? & 0x0fffffff; 437 438 match entry { 439 _n if (current_cluster >= 0x0ffffff7 && current_cluster <= 0x0fffffff) => { 440 // 当前簇号不是一个能被获得的簇(可能是文件系统出错了) 441 kerror!("FAT32 get fat entry: current cluster number [{}] is not an allocatable cluster number.", current_cluster); 442 FATEntry::Bad 443 } 444 0 => FATEntry::Unused, 445 0x0ffffff7 => FATEntry::Bad, 446 0x0ffffff8..=0x0fffffff => FATEntry::EndOfChain, 447 _n => FATEntry::Next(Cluster { 448 cluster_num: entry as u64, 449 parent_cluster: current_cluster, 450 }), 451 } 452 } 453 }; 454 return Ok(res); 455 } 456 457 /// @brief 读取当前簇在FAT表中存储的信息(直接返回读取到的值,而不加处理) 458 /// 459 /// @param cluster 当前簇 460 /// 461 /// @return Ok(u64) 当前簇在FAT表中,存储的信息。 462 /// @return Err(SystemError) 错误码 463 pub fn get_fat_entry_raw(&self, cluster: Cluster) -> Result<u64, SystemError> { 464 let current_cluster = cluster.cluster_num; 465 466 let fat_type: FATType = self.bpb.fat_type; 467 // 获取FAT表的起始扇区(相对分区起始扇区的偏移量) 468 let fat_start_sector = self.fat_start_sector(); 469 let bytes_per_sec = self.bpb.bytes_per_sector as u64; 470 471 // cluster对应的FAT表项在分区内的字节偏移量 472 let fat_bytes_offset = 473 fat_type.get_fat_bytes_offset(cluster, fat_start_sector, bytes_per_sec); 474 475 // FAT表项所在的LBA地址 476 let fat_ent_lba = self.get_lba_from_offset(self.bytes_to_sector(fat_bytes_offset)); 477 478 // FAT表项在逻辑块内的字节偏移量 479 let blk_offset = self.get_in_block_offset(fat_bytes_offset); 480 481 let mut v = Vec::<u8>::new(); 482 v.resize(self.bpb.bytes_per_sector as usize, 0); 483 self.partition 484 .disk() 485 .read_at(fat_ent_lba, 1 * self.lba_per_sector(), &mut v)?; 486 487 let mut cursor = VecCursor::new(v); 488 cursor.seek(SeekFrom::SeekSet(blk_offset as i64))?; 489 490 let res = match self.bpb.fat_type { 491 FATType::FAT12(_) => { 492 let mut entry = cursor.read_u16()?; 493 entry = if (current_cluster & 0x0001) > 0 { 494 entry >> 4 495 } else { 496 entry & 0x0fff 497 }; 498 entry as u64 499 } 500 FATType::FAT16(_) => { 501 let entry = (cursor.read_u16()?) as u64; 502 entry 503 } 504 FATType::FAT32(_) => { 505 let entry = cursor.read_u32()? & 0x0fff_ffff; 506 entry as u64 507 } 508 }; 509 510 return Ok(res); 511 } 512 513 /// @brief 获取当前文件系统的root inode,在磁盘上的字节偏移量 514 pub fn root_dir_bytes_offset(&self) -> u64 { 515 match self.bpb.fat_type { 516 FATType::FAT32(s) => { 517 let first_sec_cluster: u64 = (s.root_cluster as u64 - 2) 518 * (self.bpb.sector_per_cluster as u64) 519 + self.first_data_sector; 520 return (self.get_lba_from_offset(first_sec_cluster) * LBA_SIZE) as u64; 521 } 522 _ => { 523 let root_sec = (self.bpb.rsvd_sec_cnt as u64) 524 + (self.bpb.num_fats as u64) * (self.bpb.fat_size_16 as u64); 525 return (self.get_lba_from_offset(root_sec) * LBA_SIZE) as u64; 526 } 527 } 528 } 529 530 /// @brief 获取当前文件系统的根目录项区域的结束位置,在磁盘上的字节偏移量。 531 /// 请注意,当前函数只对FAT12/FAT16生效。对于FAT32,返回None 532 pub fn root_dir_end_bytes_offset(&self) -> Option<u64> { 533 match self.bpb.fat_type { 534 FATType::FAT12(_) | FATType::FAT16(_) => { 535 return Some( 536 self.root_dir_bytes_offset() + (self.bpb.root_entries_cnt as u64) * 32, 537 ); 538 } 539 _ => { 540 return None; 541 } 542 } 543 } 544 545 /// @brief 获取簇在磁盘内的字节偏移量(相对磁盘起始位置。注意,不是分区内偏移量) 546 pub fn cluster_bytes_offset(&self, cluster: Cluster) -> u64 { 547 if cluster.cluster_num >= 2 { 548 // 指定簇的第一个扇区号 549 let first_sec_of_cluster = (cluster.cluster_num - 2) 550 * (self.bpb.sector_per_cluster as u64) 551 + self.first_data_sector; 552 return (self.get_lba_from_offset(first_sec_of_cluster) * LBA_SIZE) as u64; 553 } else { 554 return 0; 555 } 556 } 557 558 /// @brief 获取一个空闲簇 559 /// 560 /// @param prev_cluster 簇链的前一个簇。本函数将会把新获取的簇,连接到它的后面。 561 /// 562 /// @return Ok(Cluster) 新获取的空闲簇 563 /// @return Err(SystemError) 错误码 564 pub fn allocate_cluster(&self, prev_cluster: Option<Cluster>) -> Result<Cluster, SystemError> { 565 let end_cluster: Cluster = self.max_cluster_number(); 566 let start_cluster: Cluster = match self.bpb.fat_type { 567 FATType::FAT32(_) => { 568 let next_free: u64 = match self.fs_info.0.lock().next_free() { 569 Some(x) => x, 570 None => 0xffffffff, 571 }; 572 if next_free < end_cluster.cluster_num { 573 Cluster::new(next_free) 574 } else { 575 Cluster::new(RESERVED_CLUSTERS as u64) 576 } 577 } 578 _ => Cluster::new(RESERVED_CLUSTERS as u64), 579 }; 580 581 // 寻找一个空的簇 582 let free_cluster: Cluster = match self.get_free_cluster(start_cluster, end_cluster) { 583 Ok(c) => c, 584 Err(_) if start_cluster.cluster_num > RESERVED_CLUSTERS as u64 => { 585 self.get_free_cluster(Cluster::new(RESERVED_CLUSTERS as u64), end_cluster)? 586 } 587 Err(e) => return Err(e), 588 }; 589 590 self.set_entry(free_cluster, FATEntry::EndOfChain)?; 591 // 减少空闲簇计数 592 self.fs_info.0.lock().update_free_count_delta(-1); 593 // 更新搜索空闲簇的参考量 594 self.fs_info 595 .0 596 .lock() 597 .update_next_free((free_cluster.cluster_num + 1) as u32); 598 599 // 如果这个空闲簇不是簇链的第一个簇,那么把当前簇跟前一个簇连上。 600 if let Some(prev_cluster) = prev_cluster { 601 // kdebug!("set entry, prev ={prev_cluster:?}, next = {free_cluster:?}"); 602 self.set_entry(prev_cluster, FATEntry::Next(free_cluster))?; 603 } 604 // 清空新获取的这个簇 605 self.zero_cluster(free_cluster)?; 606 return Ok(free_cluster); 607 } 608 609 /// @brief 释放簇链上的所有簇 610 /// 611 /// @param start_cluster 簇链的第一个簇 612 pub fn deallocate_cluster_chain(&self, start_cluster: Cluster) -> Result<(), SystemError> { 613 let clusters: Vec<Cluster> = self.clusters(start_cluster); 614 for c in clusters { 615 self.deallocate_cluster(c)?; 616 } 617 return Ok(()); 618 } 619 620 /// @brief 释放簇 621 /// 622 /// @param 要释放的簇 623 pub fn deallocate_cluster(&self, cluster: Cluster) -> Result<(), SystemError> { 624 let entry: FATEntry = self.get_fat_entry(cluster)?; 625 // 如果不是坏簇 626 if entry != FATEntry::Bad { 627 self.set_entry(cluster, FATEntry::Unused)?; 628 self.fs_info.0.lock().update_free_count_delta(1); 629 // 安全选项:清空被释放的簇 630 #[cfg(feature = "secure")] 631 self.zero_cluster(cluster)?; 632 return Ok(()); 633 } else { 634 // 不能释放坏簇 635 kerror!("Bad clusters cannot be freed."); 636 return Err(SystemError::EFAULT); 637 } 638 } 639 640 /// @brief 获取文件系统的根目录项 641 pub fn root_dir(&self) -> FATDir { 642 match self.bpb.fat_type { 643 FATType::FAT32(s) => { 644 return FATDir { 645 first_cluster: Cluster::new(s.root_cluster as u64), 646 dir_name: String::from("/"), 647 root_offset: None, 648 short_dir_entry: None, 649 loc: None, 650 }; 651 } 652 _ => FATDir { 653 first_cluster: Cluster::new(0), 654 dir_name: String::from("/"), 655 root_offset: Some(self.root_dir_bytes_offset()), 656 short_dir_entry: None, 657 loc: None, 658 }, 659 } 660 } 661 662 /// @brief 获取FAT表的起始扇区(相对分区起始扇区的偏移量) 663 pub fn fat_start_sector(&self) -> u64 { 664 let active_fat = self.active_fat(); 665 let fat_size = self.fat_size(); 666 return self.bpb.rsvd_sec_cnt as u64 + active_fat * fat_size; 667 } 668 669 /// @brief 获取当前活动的FAT表 670 pub fn active_fat(&self) -> u64 { 671 if self.mirroring_enabled() { 672 return 0; 673 } else { 674 match self.bpb.fat_type { 675 FATType::FAT32(bpb32) => { 676 return (bpb32.ext_flags & 0x0f) as u64; 677 } 678 _ => { 679 return 0; 680 } 681 } 682 } 683 } 684 685 /// @brief 获取当前文件系统的每个FAT表的大小 686 pub fn fat_size(&self) -> u64 { 687 if self.bpb.fat_size_16 != 0 { 688 return self.bpb.fat_size_16 as u64; 689 } else { 690 match self.bpb.fat_type { 691 FATType::FAT32(bpb32) => { 692 return bpb32.fat_size_32 as u64; 693 } 694 695 _ => { 696 panic!("FAT12 and FAT16 volumes should have non-zero BPB_FATSz16"); 697 } 698 } 699 } 700 } 701 702 /// @brief 判断当前文件系统是否启用了FAT表镜像 703 pub fn mirroring_enabled(&self) -> bool { 704 match self.bpb.fat_type { 705 FATType::FAT32(bpb32) => { 706 return (bpb32.ext_flags & 0x80) == 0; 707 } 708 _ => { 709 return false; 710 } 711 } 712 } 713 714 /// @brief 根据分区内的扇区偏移量,获得在磁盘上的LBA地址 715 #[inline] 716 pub fn get_lba_from_offset(&self, in_partition_sec_offset: u64) -> usize { 717 return (self.partition.lba_start 718 + in_partition_sec_offset * (self.bpb.bytes_per_sector as u64 / LBA_SIZE as u64)) 719 as usize; 720 } 721 722 /// @brief 获取每个扇区占用多少个LBA 723 #[inline] 724 pub fn lba_per_sector(&self) -> usize { 725 return self.bpb.bytes_per_sector as usize / LBA_SIZE; 726 } 727 728 /// @brief 将分区内字节偏移量转换为扇区偏移量 729 #[inline] 730 pub fn bytes_to_sector(&self, in_partition_bytes_offset: u64) -> u64 { 731 return in_partition_bytes_offset / (self.bpb.bytes_per_sector as u64); 732 } 733 734 /// @brief 根据磁盘上的字节偏移量,获取对应位置在分区内的字节偏移量 735 #[inline] 736 pub fn get_in_partition_bytes_offset(&self, disk_bytes_offset: u64) -> u64 { 737 return disk_bytes_offset - (self.partition.lba_start * LBA_SIZE as u64); 738 } 739 740 /// @brief 根据字节偏移量计算在逻辑块内的字节偏移量 741 #[inline] 742 pub fn get_in_block_offset(&self, bytes_offset: u64) -> u64 { 743 return bytes_offset % LBA_SIZE as u64; 744 } 745 746 /// @brief 获取在FAT表中,以start_cluster开头的FAT链的所有簇的信息 747 /// 748 /// @param start_cluster 整个FAT链的起始簇号 749 pub fn clusters(&self, start_cluster: Cluster) -> Vec<Cluster> { 750 return self.cluster_iter(start_cluster).collect(); 751 } 752 753 /// @brief 获取在FAT表中,以start_cluster开头的FAT链的长度(总计经过多少个簇) 754 /// 755 /// @param start_cluster 整个FAT链的起始簇号 756 pub fn num_clusters_chain(&self, start_cluster: Cluster) -> u64 { 757 return self 758 .cluster_iter(start_cluster) 759 .fold(0, |size, _cluster| size + 1); 760 } 761 /// @brief 获取一个簇迭代器对象 762 /// 763 /// @param start_cluster 整个FAT链的起始簇号 764 fn cluster_iter(&self, start_cluster: Cluster) -> ClusterIter { 765 return ClusterIter { 766 current_cluster: Some(start_cluster), 767 fs: self, 768 }; 769 } 770 771 /// @brief 获取从start_cluster开始的簇链中,第n个簇的信息。(请注意,下标从0开始) 772 #[inline] 773 pub fn get_cluster_by_relative(&self, start_cluster: Cluster, n: usize) -> Option<Cluster> { 774 return self.cluster_iter(start_cluster).skip(n).next(); 775 } 776 777 /// @brief 获取整个簇链的最后一个簇 778 #[inline] 779 pub fn get_last_cluster(&self, start_cluster: Cluster) -> Option<Cluster> { 780 return self.cluster_iter(start_cluster).last(); 781 } 782 783 /// @brief 判断FAT文件系统的shut bit是否正常。 784 /// shut bit 表示文件系统是否正常卸载。如果这一位是1,则表示这个卷是“干净的” 785 /// 参考资料:https://thestarman.pcministry.com/DOS/DirtyShutdownFlag.html 786 /// 787 /// @return Ok(true) 正常 788 /// @return Ok(false) 不正常 789 /// @return Err(SystemError) 在判断时发生错误 790 #[allow(dead_code)] 791 pub fn is_shut_bit_ok(&mut self) -> Result<bool, SystemError> { 792 match self.bpb.fat_type { 793 FATType::FAT32(_) => { 794 // 对于FAT32, error bit位于第一个扇区的第8字节。 795 let bit = self.get_fat_entry_raw(Cluster::new(1))? & 0x0800_0000; 796 return Ok(bit > 0); 797 } 798 FATType::FAT16(_) => { 799 let bit = self.get_fat_entry_raw(Cluster::new(1))? & 0x8000; 800 return Ok(bit > 0); 801 } 802 _ => return Ok(true), 803 } 804 } 805 806 /// @brief 判断FAT文件系统的hard error bit是否正常。 807 /// 如果此位为0,则文件系统驱动程序在上次安装卷时遇到磁盘 I/O 错误,这表明 808 /// 卷上的某些扇区可能已损坏。 809 /// 参考资料:https://thestarman.pcministry.com/DOS/DirtyShutdownFlag.html 810 /// 811 /// @return Ok(true) 正常 812 /// @return Ok(false) 不正常 813 /// @return Err(SystemError) 在判断时发生错误 814 pub fn is_hard_error_bit_ok(&mut self) -> Result<bool, SystemError> { 815 match self.bpb.fat_type { 816 FATType::FAT32(_) => { 817 let bit = self.get_fat_entry_raw(Cluster::new(1))? & 0x0400_0000; 818 return Ok(bit > 0); 819 } 820 FATType::FAT16(_) => { 821 let bit = self.get_fat_entry_raw(Cluster::new(1))? & 0x4000; 822 return Ok(bit > 0); 823 } 824 _ => return Ok(true), 825 } 826 } 827 828 /// @brief 设置文件系统的shut bit为正常状态 829 /// 参考资料:https://thestarman.pcministry.com/DOS/DirtyShutdownFlag.html 830 /// 831 /// @return Ok(()) 设置成功 832 /// @return Err(SystemError) 在设置过程中,出现错误 833 pub fn set_shut_bit_ok(&mut self) -> Result<(), SystemError> { 834 match self.bpb.fat_type { 835 FATType::FAT32(_) => { 836 let raw_entry = self.get_fat_entry_raw(Cluster::new(1))? | 0x0800_0000; 837 self.set_entry(Cluster::new(1), FATEntry::Next(Cluster::new(raw_entry)))?; 838 839 return Ok(()); 840 } 841 842 FATType::FAT16(_) => { 843 let raw_entry = self.get_fat_entry_raw(Cluster::new(1))? | 0x8000; 844 self.set_entry(Cluster::new(1), FATEntry::Next(Cluster::new(raw_entry)))?; 845 return Ok(()); 846 } 847 _ => return Ok(()), 848 } 849 } 850 851 /// @brief 设置文件系统的hard error bit为正常状态 852 /// 参考资料:https://thestarman.pcministry.com/DOS/DirtyShutdownFlag.html 853 /// 854 /// @return Ok(()) 设置成功 855 /// @return Err(SystemError) 在设置过程中,出现错误 856 pub fn set_hard_error_bit_ok(&mut self) -> Result<(), SystemError> { 857 match self.bpb.fat_type { 858 FATType::FAT32(_) => { 859 let raw_entry = self.get_fat_entry_raw(Cluster::new(1))? | 0x0400_0000; 860 self.set_entry(Cluster::new(1), FATEntry::Next(Cluster::new(raw_entry)))?; 861 return Ok(()); 862 } 863 864 FATType::FAT16(_) => { 865 let raw_entry = self.get_fat_entry_raw(Cluster::new(1))? | 0x4000; 866 self.set_entry(Cluster::new(1), FATEntry::Next(Cluster::new(raw_entry)))?; 867 return Ok(()); 868 } 869 _ => return Ok(()), 870 } 871 } 872 873 /// @brief 执行文件系统卸载前的一些准备工作:设置好对应的标志位,并把缓存中的数据刷入磁盘 874 pub fn umount(&mut self) -> Result<(), SystemError> { 875 self.fs_info.0.lock().flush(&self.partition)?; 876 877 self.set_shut_bit_ok()?; 878 879 self.set_hard_error_bit_ok()?; 880 881 self.partition.disk().sync()?; 882 883 return Ok(()); 884 } 885 886 /// @brief 获取文件系统的最大簇号 887 pub fn max_cluster_number(&self) -> Cluster { 888 match self.bpb.fat_type { 889 FATType::FAT32(s) => { 890 // FAT32 891 892 // 数据扇区数量(总扇区数-保留扇区-FAT占用的扇区) 893 let data_sec: u64 = self.bpb.total_sectors_32 as u64 894 - (self.bpb.rsvd_sec_cnt as u64 895 + self.bpb.num_fats as u64 * s.fat_size_32 as u64); 896 897 // 数据区的簇数量 898 let total_clusters: u64 = data_sec / self.bpb.sector_per_cluster as u64; 899 900 // 返回最大的簇号 901 return Cluster::new(total_clusters + RESERVED_CLUSTERS as u64 - 1); 902 } 903 904 _ => { 905 // FAT12 / FAT16 906 let root_dir_sectors: u64 = (((self.bpb.root_entries_cnt as u64) * 32) 907 + self.bpb.bytes_per_sector as u64 908 - 1) 909 / self.bpb.bytes_per_sector as u64; 910 // 数据区扇区数 911 let data_sec: u64 = self.bpb.total_sectors_16 as u64 912 - (self.bpb.rsvd_sec_cnt as u64 913 + (self.bpb.num_fats as u64 * self.bpb.fat_size_16 as u64) 914 + root_dir_sectors); 915 let total_clusters = data_sec / self.bpb.sector_per_cluster as u64; 916 return Cluster::new(total_clusters + RESERVED_CLUSTERS as u64 - 1); 917 } 918 } 919 } 920 921 /// @brief 在文件系统中寻找一个簇号在给定的范围(左闭右开区间)内的空闲簇 922 /// 923 /// @param start_cluster 起始簇号 924 /// @param end_cluster 终止簇号(不包含) 925 /// 926 /// @return Ok(Cluster) 寻找到的空闲簇 927 /// @return Err(SystemError) 错误码。如果磁盘无剩余空间,或者簇号达到给定的最大值,则返回-ENOSPC. 928 pub fn get_free_cluster( 929 &self, 930 start_cluster: Cluster, 931 end_cluster: Cluster, 932 ) -> Result<Cluster, SystemError> { 933 let max_cluster: Cluster = self.max_cluster_number(); 934 let mut cluster: u64 = start_cluster.cluster_num; 935 936 let fat_type: FATType = self.bpb.fat_type; 937 let fat_start_sector: u64 = self.fat_start_sector(); 938 let bytes_per_sec: u64 = self.bpb.bytes_per_sector as u64; 939 940 match fat_type { 941 FATType::FAT12(_) => { 942 let part_bytes_offset: u64 = 943 fat_type.get_fat_bytes_offset(start_cluster, fat_start_sector, bytes_per_sec); 944 let in_block_offset = self.get_in_block_offset(part_bytes_offset); 945 946 let lba = self.get_lba_from_offset(self.bytes_to_sector(part_bytes_offset)); 947 948 // 由于FAT12的FAT表不大于6K,因此直接读取6K 949 let num_lba = (6 * 1024) / LBA_SIZE; 950 let mut v: Vec<u8> = Vec::new(); 951 v.resize(num_lba * LBA_SIZE, 0); 952 self.partition.disk().read_at(lba, num_lba, &mut v)?; 953 954 let mut cursor: VecCursor = VecCursor::new(v); 955 cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 956 957 let mut packed_val: u16 = cursor.read_u16()?; 958 loop { 959 let val = if (cluster & 0x1) > 0 { 960 packed_val >> 4 961 } else { 962 packed_val & 0x0fff 963 }; 964 if val == 0 { 965 return Ok(Cluster::new(cluster as u64)); 966 } 967 968 cluster += 1; 969 970 // 磁盘无剩余空间,或者簇号达到给定的最大值 971 if cluster == end_cluster.cluster_num || cluster == max_cluster.cluster_num { 972 return Err(SystemError::ENOSPC); 973 } 974 975 packed_val = match cluster & 1 { 976 0 => cursor.read_u16()?, 977 _ => { 978 let next_byte = cursor.read_u8()? as u16; 979 (packed_val >> 8) | (next_byte << 8) 980 } 981 }; 982 } 983 } 984 FATType::FAT16(_) => { 985 // todo: 优化这里,减少读取磁盘的次数。 986 while cluster < end_cluster.cluster_num && cluster < max_cluster.cluster_num { 987 let part_bytes_offset: u64 = fat_type.get_fat_bytes_offset( 988 Cluster::new(cluster), 989 fat_start_sector, 990 bytes_per_sec, 991 ); 992 let in_block_offset = self.get_in_block_offset(part_bytes_offset); 993 994 let lba = self.get_lba_from_offset(self.bytes_to_sector(part_bytes_offset)); 995 996 let mut v: Vec<u8> = Vec::new(); 997 v.resize(self.lba_per_sector() * LBA_SIZE, 0); 998 self.partition 999 .disk() 1000 .read_at(lba, self.lba_per_sector(), &mut v)?; 1001 1002 let mut cursor: VecCursor = VecCursor::new(v); 1003 cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1004 1005 let val = cursor.read_u16()?; 1006 // 找到空闲簇 1007 if val == 0 { 1008 return Ok(Cluster::new(val as u64)); 1009 } 1010 cluster += 1; 1011 } 1012 1013 // 磁盘无剩余空间,或者簇号达到给定的最大值 1014 return Err(SystemError::ENOSPC); 1015 } 1016 FATType::FAT32(_) => { 1017 // todo: 优化这里,减少读取磁盘的次数。 1018 while cluster < end_cluster.cluster_num && cluster < max_cluster.cluster_num { 1019 let part_bytes_offset: u64 = fat_type.get_fat_bytes_offset( 1020 Cluster::new(cluster), 1021 fat_start_sector, 1022 bytes_per_sec, 1023 ); 1024 let in_block_offset = self.get_in_block_offset(part_bytes_offset); 1025 1026 let lba = self.get_lba_from_offset(self.bytes_to_sector(part_bytes_offset)); 1027 1028 let mut v: Vec<u8> = Vec::new(); 1029 v.resize(self.lba_per_sector() * LBA_SIZE, 0); 1030 self.partition 1031 .disk() 1032 .read_at(lba, self.lba_per_sector(), &mut v)?; 1033 1034 let mut cursor: VecCursor = VecCursor::new(v); 1035 cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1036 1037 let val = cursor.read_u32()? & 0x0fffffff; 1038 1039 if val == 0 { 1040 return Ok(Cluster::new(cluster)); 1041 } 1042 cluster += 1; 1043 } 1044 1045 // 磁盘无剩余空间,或者簇号达到给定的最大值 1046 return Err(SystemError::ENOSPC); 1047 } 1048 } 1049 } 1050 1051 /// @brief 在FAT表中,设置指定的簇的信息。 1052 /// 1053 /// @param cluster 目标簇 1054 /// @param fat_entry 这个簇在FAT表中,存储的信息(下一个簇的簇号) 1055 pub fn set_entry(&self, cluster: Cluster, fat_entry: FATEntry) -> Result<(), SystemError> { 1056 // fat表项在分区上的字节偏移量 1057 let fat_part_bytes_offset: u64 = self.bpb.fat_type.get_fat_bytes_offset( 1058 cluster, 1059 self.fat_start_sector(), 1060 self.bpb.bytes_per_sector as u64, 1061 ); 1062 1063 match self.bpb.fat_type { 1064 FATType::FAT12(_) => { 1065 // 计算要写入的值 1066 let raw_val: u16 = match fat_entry { 1067 FATEntry::Unused => 0, 1068 FATEntry::Bad => 0xff7, 1069 FATEntry::EndOfChain => 0xfff, 1070 FATEntry::Next(c) => c.cluster_num as u16, 1071 }; 1072 1073 let in_block_offset = self.get_in_block_offset(fat_part_bytes_offset); 1074 1075 let lba = self.get_lba_from_offset(self.bytes_to_sector(fat_part_bytes_offset)); 1076 1077 let mut v: Vec<u8> = Vec::new(); 1078 v.resize(LBA_SIZE, 0); 1079 self.partition.disk().read_at(lba, 1, &mut v)?; 1080 1081 let mut cursor: VecCursor = VecCursor::new(v); 1082 cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1083 1084 let old_val: u16 = cursor.read_u16()?; 1085 let new_val: u16 = if (cluster.cluster_num & 0x1) > 0 { 1086 (old_val & 0x000f) | (raw_val << 4) 1087 } else { 1088 (old_val & 0xf000) | raw_val 1089 }; 1090 1091 // 写回数据到磁盘上 1092 cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1093 cursor.write_u16(new_val)?; 1094 self.partition.disk().write_at(lba, 1, cursor.as_slice())?; 1095 return Ok(()); 1096 } 1097 FATType::FAT16(_) => { 1098 // 计算要写入的值 1099 let raw_val: u16 = match fat_entry { 1100 FATEntry::Unused => 0, 1101 FATEntry::Bad => 0xfff7, 1102 FATEntry::EndOfChain => 0xfdff, 1103 FATEntry::Next(c) => c.cluster_num as u16, 1104 }; 1105 1106 let in_block_offset = self.get_in_block_offset(fat_part_bytes_offset); 1107 1108 let lba = self.get_lba_from_offset(self.bytes_to_sector(fat_part_bytes_offset)); 1109 1110 let mut v: Vec<u8> = Vec::new(); 1111 v.resize(LBA_SIZE, 0); 1112 self.partition.disk().read_at(lba, 1, &mut v)?; 1113 1114 let mut cursor: VecCursor = VecCursor::new(v); 1115 cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1116 1117 cursor.write_u16(raw_val)?; 1118 self.partition.disk().write_at(lba, 1, cursor.as_slice())?; 1119 1120 return Ok(()); 1121 } 1122 FATType::FAT32(_) => { 1123 let fat_size: u64 = self.fat_size(); 1124 let bound: u64 = if self.mirroring_enabled() { 1125 1 1126 } else { 1127 self.bpb.num_fats as u64 1128 }; 1129 // kdebug!("set entry, bound={bound}, fat_size={fat_size}"); 1130 for i in 0..bound { 1131 // 当前操作的FAT表在磁盘上的字节偏移量 1132 let f_offset: u64 = fat_part_bytes_offset + i * fat_size; 1133 let in_block_offset: u64 = self.get_in_block_offset(f_offset); 1134 let lba = self.get_lba_from_offset(self.bytes_to_sector(f_offset)); 1135 1136 // kdebug!("set entry, lba={lba}, in_block_offset={in_block_offset}"); 1137 let mut v: Vec<u8> = Vec::new(); 1138 v.resize(LBA_SIZE, 0); 1139 self.partition.disk().read_at(lba, 1, &mut v)?; 1140 1141 let mut cursor: VecCursor = VecCursor::new(v); 1142 cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1143 1144 // FAT32的高4位保留 1145 let old_bits = cursor.read_u32()? & 0xf0000000; 1146 1147 if fat_entry == FATEntry::Unused 1148 && cluster.cluster_num >= 0x0ffffff7 1149 && cluster.cluster_num <= 0x0fffffff 1150 { 1151 kerror!( 1152 "FAT32: Reserved Cluster {:?} cannot be marked as free", 1153 cluster 1154 ); 1155 return Err(SystemError::EPERM); 1156 } 1157 1158 // 计算要写入的值 1159 let mut raw_val: u32 = match fat_entry { 1160 FATEntry::Unused => 0, 1161 FATEntry::Bad => 0x0FFFFFF7, 1162 FATEntry::EndOfChain => 0x0FFFFFFF, 1163 FATEntry::Next(c) => c.cluster_num as u32, 1164 }; 1165 1166 // 恢复保留位 1167 raw_val |= old_bits; 1168 1169 // kdebug!("sent entry, raw_val={raw_val}"); 1170 1171 cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1172 cursor.write_u32(raw_val)?; 1173 1174 self.partition.disk().write_at(lba, 1, cursor.as_slice())?; 1175 } 1176 1177 return Ok(()); 1178 } 1179 } 1180 } 1181 1182 /// @brief 清空指定的簇 1183 /// 1184 /// @param cluster 要被清空的簇 1185 pub fn zero_cluster(&self, cluster: Cluster) -> Result<(), SystemError> { 1186 // 准备数据,用于写入 1187 let zeros: Vec<u8> = vec![0u8; self.bytes_per_cluster() as usize]; 1188 let offset: usize = self.cluster_bytes_offset(cluster) as usize; 1189 self.partition 1190 .disk() 1191 .write_at_bytes(offset, zeros.len(), zeros.as_slice())?; 1192 return Ok(()); 1193 } 1194 } 1195 1196 impl Drop for FATFileSystem { 1197 fn drop(&mut self) { 1198 let r = self.umount(); 1199 if r.is_err() { 1200 kerror!( 1201 "Umount FAT filesystem failed: errno={:?}, FS detail:{self:?}", 1202 r.as_ref().unwrap_err() 1203 ); 1204 } 1205 } 1206 } 1207 1208 impl FATFsInfo { 1209 const LEAD_SIG: u32 = 0x41615252; 1210 const STRUC_SIG: u32 = 0x61417272; 1211 const TRAIL_SIG: u32 = 0xAA550000; 1212 #[allow(dead_code)] 1213 const FS_INFO_SIZE: u64 = 512; 1214 1215 /// @brief 从磁盘上读取FAT文件系统的FSInfo结构体 1216 /// 1217 /// @param partition 磁盘分区 1218 /// @param in_disk_fs_info_offset FSInfo扇区在磁盘内的字节偏移量(单位:字节) 1219 /// @param bytes_per_sec 每扇区字节数 1220 pub fn new( 1221 partition: Arc<Partition>, 1222 in_disk_fs_info_offset: u64, 1223 bytes_per_sec: usize, 1224 ) -> Result<Self, SystemError> { 1225 let mut v = Vec::<u8>::new(); 1226 v.resize(bytes_per_sec, 0); 1227 1228 // 计算fs_info扇区在磁盘上的字节偏移量,从磁盘读取数据 1229 partition 1230 .disk() 1231 .read_at(in_disk_fs_info_offset as usize / LBA_SIZE, 1, &mut v)?; 1232 let mut cursor = VecCursor::new(v); 1233 1234 let mut fsinfo = FATFsInfo::default(); 1235 1236 fsinfo.lead_sig = cursor.read_u32()?; 1237 cursor.seek(SeekFrom::SeekCurrent(480))?; 1238 fsinfo.struc_sig = cursor.read_u32()?; 1239 fsinfo.free_count = cursor.read_u32()?; 1240 fsinfo.next_free = cursor.read_u32()?; 1241 1242 cursor.seek(SeekFrom::SeekCurrent(12))?; 1243 1244 fsinfo.trail_sig = cursor.read_u32()?; 1245 fsinfo.dirty = false; 1246 fsinfo.offset = Some(in_disk_fs_info_offset); 1247 1248 if fsinfo.is_valid() { 1249 return Ok(fsinfo); 1250 } else { 1251 kerror!("Error occurred while parsing FATFsInfo."); 1252 return Err(SystemError::EINVAL); 1253 } 1254 } 1255 1256 /// @brief 判断是否为正确的FsInfo结构体 1257 fn is_valid(&self) -> bool { 1258 self.lead_sig == Self::LEAD_SIG 1259 && self.struc_sig == Self::STRUC_SIG 1260 && self.trail_sig == Self::TRAIL_SIG 1261 } 1262 1263 /// @brief 根据fsinfo的信息,计算当前总的空闲簇数量 1264 /// 1265 /// @param 当前文件系统的最大簇号 1266 pub fn count_free_cluster(&self, max_cluster: Cluster) -> Option<u64> { 1267 let count_clusters = max_cluster.cluster_num - RESERVED_CLUSTERS as u64 + 1; 1268 // 信息不合理,当前的FsInfo中存储的free count大于计算出来的值 1269 if self.free_count as u64 > count_clusters { 1270 return None; 1271 } else { 1272 match self.free_count { 1273 // free count字段不可用 1274 0xffffffff => return None, 1275 // 返回FsInfo中存储的数据 1276 n => return Some(n as u64), 1277 } 1278 } 1279 } 1280 1281 /// @brief 更新FsInfo中的“空闲簇统计信息“为new_count 1282 /// 1283 /// 请注意,除非手动调用`flush()`,否则本函数不会将数据刷入磁盘 1284 pub fn update_free_count_abs(&mut self, new_count: u32) { 1285 self.free_count = new_count; 1286 } 1287 1288 /// @brief 更新FsInfo中的“空闲簇统计信息“,把它加上delta. 1289 /// 1290 /// 请注意,除非手动调用`flush()`,否则本函数不会将数据刷入磁盘 1291 pub fn update_free_count_delta(&mut self, delta: i32) { 1292 self.free_count = (self.free_count as i32 + delta) as u32; 1293 } 1294 1295 /// @brief 更新FsInfo中的“第一个空闲簇统计信息“为next_free. 1296 /// 1297 /// 请注意,除非手动调用`flush()`,否则本函数不会将数据刷入磁盘 1298 pub fn update_next_free(&mut self, next_free: u32) { 1299 // 这个值是参考量,不一定要准确,仅供加速查找 1300 self.next_free = next_free; 1301 } 1302 1303 /// @brief 获取fs info 记载的第一个空闲簇。(不一定准确,仅供参考) 1304 pub fn next_free(&self) -> Option<u64> { 1305 match self.next_free { 1306 0xffffffff => return None, 1307 0 | 1 => return None, 1308 n => return Some(n as u64), 1309 }; 1310 } 1311 1312 /// @brief 把fs info刷入磁盘 1313 /// 1314 /// @param partition fs info所在的分区 1315 pub fn flush(&self, partition: &Arc<Partition>) -> Result<(), SystemError> { 1316 if let Some(off) = self.offset { 1317 let in_block_offset = off % LBA_SIZE as u64; 1318 1319 let lba = off as usize / LBA_SIZE; 1320 1321 let mut v: Vec<u8> = Vec::new(); 1322 v.resize(LBA_SIZE, 0); 1323 partition.disk().read_at(lba, 1, &mut v)?; 1324 1325 let mut cursor: VecCursor = VecCursor::new(v); 1326 cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1327 1328 cursor.write_u32(self.lead_sig)?; 1329 cursor.seek(SeekFrom::SeekCurrent(480))?; 1330 cursor.write_u32(self.struc_sig)?; 1331 cursor.write_u32(self.free_count)?; 1332 cursor.write_u32(self.next_free)?; 1333 cursor.seek(SeekFrom::SeekCurrent(12))?; 1334 cursor.write_u32(self.trail_sig)?; 1335 1336 partition.disk().write_at(lba, 1, cursor.as_slice())?; 1337 } 1338 return Ok(()); 1339 } 1340 1341 /// @brief 读取磁盘上的Fs Info扇区,将里面的内容更新到结构体中 1342 /// 1343 /// @param partition fs info所在的分区 1344 pub fn update(&mut self, partition: Arc<Partition>) -> Result<(), SystemError> { 1345 if let Some(off) = self.offset { 1346 let in_block_offset = off % LBA_SIZE as u64; 1347 1348 let lba = off as usize / LBA_SIZE; 1349 1350 let mut v: Vec<u8> = Vec::new(); 1351 v.resize(LBA_SIZE, 0); 1352 partition.disk().read_at(lba, 1, &mut v)?; 1353 let mut cursor: VecCursor = VecCursor::new(v); 1354 cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1355 self.lead_sig = cursor.read_u32()?; 1356 1357 cursor.seek(SeekFrom::SeekCurrent(480))?; 1358 self.struc_sig = cursor.read_u32()?; 1359 self.free_count = cursor.read_u32()?; 1360 self.next_free = cursor.read_u32()?; 1361 cursor.seek(SeekFrom::SeekCurrent(12))?; 1362 self.trail_sig = cursor.read_u32()?; 1363 } 1364 return Ok(()); 1365 } 1366 } 1367 1368 impl IndexNode for LockedFATInode { 1369 fn read_at( 1370 &self, 1371 offset: usize, 1372 len: usize, 1373 buf: &mut [u8], 1374 _data: &mut FilePrivateData, 1375 ) -> Result<usize, SystemError> { 1376 let mut guard: SpinLockGuard<FATInode> = self.0.lock(); 1377 match &guard.inode_type { 1378 FATDirEntry::File(f) | FATDirEntry::VolId(f) => { 1379 let r = f.read( 1380 &guard.fs.upgrade().unwrap(), 1381 &mut buf[0..len], 1382 offset as u64, 1383 ); 1384 guard.update_metadata(); 1385 return r; 1386 } 1387 FATDirEntry::Dir(_) => { 1388 return Err(SystemError::EISDIR); 1389 } 1390 FATDirEntry::UnInit => { 1391 kerror!("FATFS: param: Inode_type uninitialized."); 1392 return Err(SystemError::EROFS); 1393 } 1394 } 1395 } 1396 1397 fn write_at( 1398 &self, 1399 offset: usize, 1400 len: usize, 1401 buf: &[u8], 1402 _data: &mut FilePrivateData, 1403 ) -> Result<usize, SystemError> { 1404 let mut guard: SpinLockGuard<FATInode> = self.0.lock(); 1405 let fs: &Arc<FATFileSystem> = &guard.fs.upgrade().unwrap(); 1406 1407 match &mut guard.inode_type { 1408 FATDirEntry::File(f) | FATDirEntry::VolId(f) => { 1409 let r = f.write(fs, &buf[0..len], offset as u64); 1410 guard.update_metadata(); 1411 return r; 1412 } 1413 FATDirEntry::Dir(_) => { 1414 return Err(SystemError::EISDIR); 1415 } 1416 FATDirEntry::UnInit => { 1417 kerror!("FATFS: param: Inode_type uninitialized."); 1418 return Err(SystemError::EROFS); 1419 } 1420 } 1421 } 1422 1423 fn create( 1424 &self, 1425 name: &str, 1426 file_type: FileType, 1427 _mode: ModeType, 1428 ) -> Result<Arc<dyn IndexNode>, SystemError> { 1429 // 由于FAT32不支持文件权限的功能,因此忽略mode参数 1430 let mut guard: SpinLockGuard<FATInode> = self.0.lock(); 1431 let fs: &Arc<FATFileSystem> = &guard.fs.upgrade().unwrap(); 1432 1433 match &mut guard.inode_type { 1434 FATDirEntry::File(_) | FATDirEntry::VolId(_) => { 1435 return Err(SystemError::ENOTDIR); 1436 } 1437 FATDirEntry::Dir(d) => match file_type { 1438 FileType::File => { 1439 d.create_file(name, fs)?; 1440 return Ok(guard.find(name)?); 1441 } 1442 FileType::Dir => { 1443 d.create_dir(name, fs)?; 1444 return Ok(guard.find(name)?); 1445 } 1446 1447 FileType::SymLink => return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP), 1448 _ => return Err(SystemError::EINVAL), 1449 }, 1450 FATDirEntry::UnInit => { 1451 kerror!("FATFS: param: Inode_type uninitialized."); 1452 return Err(SystemError::EROFS); 1453 } 1454 } 1455 } 1456 1457 fn fs(&self) -> Arc<dyn FileSystem> { 1458 return self.0.lock().fs.upgrade().unwrap(); 1459 } 1460 1461 fn as_any_ref(&self) -> &dyn core::any::Any { 1462 return self; 1463 } 1464 1465 fn metadata(&self) -> Result<Metadata, SystemError> { 1466 return Ok(self.0.lock().metadata.clone()); 1467 } 1468 fn resize(&self, len: usize) -> Result<(), SystemError> { 1469 let mut guard: SpinLockGuard<FATInode> = self.0.lock(); 1470 let fs: &Arc<FATFileSystem> = &guard.fs.upgrade().unwrap(); 1471 let old_size = guard.metadata.size as usize; 1472 1473 match &mut guard.inode_type { 1474 FATDirEntry::File(file) | FATDirEntry::VolId(file) => { 1475 // 如果新的长度和旧的长度相同,那么就直接返回 1476 if len == old_size { 1477 return Ok(()); 1478 } else if len > old_size { 1479 // 如果新的长度比旧的长度大,那么就在文件末尾添加空白 1480 let mut buf: Vec<u8> = Vec::new(); 1481 let mut remain_size = len - old_size; 1482 let buf_size = remain_size; 1483 // let buf_size = core::cmp::min(remain_size, 512 * 1024); 1484 buf.resize(buf_size, 0); 1485 1486 let mut offset = old_size; 1487 while remain_size > 0 { 1488 let write_size = core::cmp::min(remain_size, buf_size); 1489 file.write(fs, &buf[0..write_size], offset as u64)?; 1490 remain_size -= write_size; 1491 offset += write_size; 1492 } 1493 } else { 1494 file.truncate(fs, len as u64)?; 1495 } 1496 guard.update_metadata(); 1497 return Ok(()); 1498 } 1499 FATDirEntry::Dir(_) => return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP), 1500 FATDirEntry::UnInit => { 1501 kerror!("FATFS: param: Inode_type uninitialized."); 1502 return Err(SystemError::EROFS); 1503 } 1504 } 1505 } 1506 1507 fn truncate(&self, len: usize) -> Result<(), SystemError> { 1508 let guard: SpinLockGuard<FATInode> = self.0.lock(); 1509 let old_size = guard.metadata.size as usize; 1510 if len < old_size { 1511 drop(guard); 1512 self.resize(len) 1513 } else { 1514 Ok(()) 1515 } 1516 } 1517 1518 fn list(&self) -> Result<Vec<String>, SystemError> { 1519 let mut guard: SpinLockGuard<FATInode> = self.0.lock(); 1520 let fatent: &FATDirEntry = &guard.inode_type; 1521 match fatent { 1522 FATDirEntry::File(_) | FATDirEntry::VolId(_) => { 1523 return Err(SystemError::ENOTDIR); 1524 } 1525 FATDirEntry::Dir(dir) => { 1526 // 获取当前目录下的所有目录项 1527 let mut ret: Vec<String> = Vec::new(); 1528 let dir_iter: FATDirIter = dir.to_iter(guard.fs.upgrade().unwrap()); 1529 for ent in dir_iter { 1530 ret.push(ent.name()); 1531 1532 // ====== 生成inode缓存,存入B树 1533 let name: String = ent.name(); 1534 // kdebug!("name={name}"); 1535 1536 if guard.children.contains_key(&name.to_uppercase()) == false 1537 && name != "." 1538 && name != ".." 1539 { 1540 // 创建新的inode 1541 let entry_inode: Arc<LockedFATInode> = LockedFATInode::new( 1542 guard.fs.upgrade().unwrap(), 1543 guard.self_ref.clone(), 1544 ent, 1545 ); 1546 // 加入缓存区, 由于FAT文件系统的大小写不敏感问题,因此存入缓存区的key应当是全大写的 1547 guard 1548 .children 1549 .insert(name.to_uppercase(), entry_inode.clone()); 1550 } 1551 } 1552 return Ok(ret); 1553 } 1554 FATDirEntry::UnInit => { 1555 kerror!("FATFS: param: Inode_type uninitialized."); 1556 return Err(SystemError::EROFS); 1557 } 1558 } 1559 } 1560 1561 fn find(&self, name: &str) -> Result<Arc<dyn IndexNode>, SystemError> { 1562 let mut guard: SpinLockGuard<FATInode> = self.0.lock(); 1563 let target = guard.find(name)?; 1564 return Ok(target); 1565 } 1566 1567 fn open(&self, _data: &mut FilePrivateData, _mode: &FileMode) -> Result<(), SystemError> { 1568 return Ok(()); 1569 } 1570 1571 fn close(&self, _data: &mut FilePrivateData) -> Result<(), SystemError> { 1572 return Ok(()); 1573 } 1574 1575 fn unlink(&self, name: &str) -> Result<(), SystemError> { 1576 let mut guard: SpinLockGuard<FATInode> = self.0.lock(); 1577 let target: Arc<LockedFATInode> = guard.find(name)?; 1578 // 对目标inode上锁,以防更改 1579 let target_guard: SpinLockGuard<FATInode> = target.0.lock(); 1580 // 先从缓存删除 1581 let nod = guard.children.remove(&name.to_uppercase()); 1582 1583 // 若删除缓存中为管道的文件,则不需要再到磁盘删除 1584 if let Some(_) = nod { 1585 let file_type = target_guard.metadata.file_type; 1586 if file_type == FileType::Pipe { 1587 return Ok(()); 1588 } 1589 } 1590 1591 let dir = match &guard.inode_type { 1592 FATDirEntry::File(_) | FATDirEntry::VolId(_) => { 1593 return Err(SystemError::ENOTDIR); 1594 } 1595 FATDirEntry::Dir(d) => d, 1596 FATDirEntry::UnInit => { 1597 kerror!("FATFS: param: Inode_type uninitialized."); 1598 return Err(SystemError::EROFS); 1599 } 1600 }; 1601 // 检查文件是否存在 1602 dir.check_existence(name, Some(false), guard.fs.upgrade().unwrap())?; 1603 1604 // 再从磁盘删除 1605 let r = dir.remove(guard.fs.upgrade().unwrap().clone(), name, true); 1606 drop(target_guard); 1607 return r; 1608 } 1609 1610 fn rmdir(&self, name: &str) -> Result<(), SystemError> { 1611 let mut guard: SpinLockGuard<FATInode> = self.0.lock(); 1612 let target: Arc<LockedFATInode> = guard.find(name)?; 1613 // 对目标inode上锁,以防更改 1614 let target_guard: SpinLockGuard<FATInode> = target.0.lock(); 1615 // 先从缓存删除 1616 guard.children.remove(&name.to_uppercase()); 1617 1618 let dir = match &guard.inode_type { 1619 FATDirEntry::File(_) | FATDirEntry::VolId(_) => { 1620 return Err(SystemError::ENOTDIR); 1621 } 1622 FATDirEntry::Dir(d) => d, 1623 FATDirEntry::UnInit => { 1624 kerror!("FATFS: param: Inode_type uninitialized."); 1625 return Err(SystemError::EROFS); 1626 } 1627 }; 1628 // 检查文件夹是否存在 1629 dir.check_existence(name, Some(true), guard.fs.upgrade().unwrap())?; 1630 1631 // 再从磁盘删除 1632 let r: Result<(), SystemError> = 1633 dir.remove(guard.fs.upgrade().unwrap().clone(), name, true); 1634 if r.is_ok() { 1635 return r; 1636 } else { 1637 let r = r.unwrap_err(); 1638 if r == SystemError::ENOTEMPTY { 1639 // 如果要删除的是目录,且不为空,则删除动作未发生,重新加入缓存 1640 guard.children.insert(name.to_uppercase(), target.clone()); 1641 drop(target_guard); 1642 } 1643 return Err(r); 1644 } 1645 } 1646 1647 fn move_to( 1648 &self, 1649 old_name: &str, 1650 target: &Arc<dyn IndexNode>, 1651 new_name: &str, 1652 ) -> Result<(), SystemError> { 1653 let old_id = self.metadata().unwrap().inode_id; 1654 let new_id = target.metadata().unwrap().inode_id; 1655 // 若在同一父目录下 1656 if old_id == new_id { 1657 let mut guard = self.0.lock(); 1658 let old_inode: Arc<LockedFATInode> = guard.find(old_name)?; 1659 // 对目标inode上锁,以防更改 1660 let old_inode_guard: SpinLockGuard<FATInode> = old_inode.0.lock(); 1661 let fs = old_inode_guard.fs.upgrade().unwrap(); 1662 // 从缓存删除 1663 let _nod = guard.children.remove(&old_name.to_uppercase()); 1664 let old_dir = match &guard.inode_type { 1665 FATDirEntry::File(_) | FATDirEntry::VolId(_) => { 1666 return Err(SystemError::ENOTDIR); 1667 } 1668 FATDirEntry::Dir(d) => d, 1669 FATDirEntry::UnInit => { 1670 kerror!("FATFS: param: Inode_type uninitialized."); 1671 return Err(SystemError::EROFS); 1672 } 1673 }; 1674 // 检查文件是否存在 1675 // old_dir.check_existence(old_name, Some(false), guard.fs.upgrade().unwrap())?; 1676 1677 old_dir.rename(fs, old_name, new_name)?; 1678 } else { 1679 let mut old_guard = self.0.lock(); 1680 let other: &LockedFATInode = target 1681 .downcast_ref::<LockedFATInode>() 1682 .ok_or(SystemError::EPERM)?; 1683 1684 let new_guard = other.0.lock(); 1685 let old_inode: Arc<LockedFATInode> = old_guard.find(old_name)?; 1686 // 对目标inode上锁,以防更改 1687 let old_inode_guard: SpinLockGuard<FATInode> = old_inode.0.lock(); 1688 let fs = old_inode_guard.fs.upgrade().unwrap(); 1689 // 从缓存删除 1690 let _nod = old_guard.children.remove(&old_name.to_uppercase()); 1691 let old_dir = match &old_guard.inode_type { 1692 FATDirEntry::File(_) | FATDirEntry::VolId(_) => { 1693 return Err(SystemError::ENOTDIR); 1694 } 1695 FATDirEntry::Dir(d) => d, 1696 FATDirEntry::UnInit => { 1697 kerror!("FATFS: param: Inode_type uninitialized."); 1698 return Err(SystemError::EROFS); 1699 } 1700 }; 1701 let new_dir = match &new_guard.inode_type { 1702 FATDirEntry::File(_) | FATDirEntry::VolId(_) => { 1703 return Err(SystemError::ENOTDIR); 1704 } 1705 FATDirEntry::Dir(d) => d, 1706 FATDirEntry::UnInit => { 1707 kerror!("FATFA: param: Inode_type uninitialized."); 1708 return Err(SystemError::EROFS); 1709 } 1710 }; 1711 // 检查文件是否存在 1712 old_dir.check_existence(old_name, Some(false), old_guard.fs.upgrade().unwrap())?; 1713 old_dir.rename_across(fs, new_dir, old_name, new_name)?; 1714 } 1715 1716 return Ok(()); 1717 } 1718 1719 fn get_entry_name(&self, ino: InodeId) -> Result<String, SystemError> { 1720 let guard: SpinLockGuard<FATInode> = self.0.lock(); 1721 if guard.metadata.file_type != FileType::Dir { 1722 return Err(SystemError::ENOTDIR); 1723 } 1724 match ino.into() { 1725 0 => { 1726 return Ok(String::from(".")); 1727 } 1728 1 => { 1729 return Ok(String::from("..")); 1730 } 1731 ino => { 1732 // 暴力遍历所有的children,判断inode id是否相同 1733 // TODO: 优化这里,这个地方性能很差! 1734 let mut key: Vec<String> = guard 1735 .children 1736 .keys() 1737 .filter(|k| { 1738 guard 1739 .children 1740 .get(*k) 1741 .unwrap() 1742 .metadata() 1743 .unwrap() 1744 .inode_id 1745 .into() 1746 == ino 1747 }) 1748 .cloned() 1749 .collect(); 1750 1751 match key.len() { 1752 0=>{return Err(SystemError::ENOENT);} 1753 1=>{return Ok(key.remove(0));} 1754 _ => panic!("FatFS get_entry_name: key.len()={key_len}>1, current inode_id={inode_id:?}, to find={to_find:?}", key_len=key.len(), inode_id = guard.metadata.inode_id, to_find=ino) 1755 } 1756 } 1757 } 1758 } 1759 1760 fn mknod( 1761 &self, 1762 filename: &str, 1763 mode: ModeType, 1764 _dev_t: DeviceNumber, 1765 ) -> Result<Arc<dyn IndexNode>, SystemError> { 1766 let mut inode = self.0.lock(); 1767 if inode.metadata.file_type != FileType::Dir { 1768 return Err(SystemError::ENOTDIR); 1769 } 1770 1771 // 判断需要创建的类型 1772 if unlikely(mode.contains(ModeType::S_IFREG)) { 1773 // 普通文件 1774 return Ok(self.create(filename, FileType::File, mode)?); 1775 } 1776 1777 let nod = LockedFATInode::new( 1778 inode.fs.upgrade().unwrap(), 1779 inode.self_ref.clone(), 1780 FATDirEntry::File(FATFile::default()), 1781 ); 1782 1783 if mode.contains(ModeType::S_IFIFO) { 1784 nod.0.lock().metadata.file_type = FileType::Pipe; 1785 // 创建pipe文件 1786 let pipe_inode = LockedPipeInode::new(); 1787 // 设置special_node 1788 nod.0.lock().special_node = Some(SpecialNodeData::Pipe(pipe_inode)); 1789 } else if mode.contains(ModeType::S_IFBLK) { 1790 nod.0.lock().metadata.file_type = FileType::BlockDevice; 1791 unimplemented!() 1792 } else if mode.contains(ModeType::S_IFCHR) { 1793 nod.0.lock().metadata.file_type = FileType::CharDevice; 1794 unimplemented!() 1795 } else { 1796 return Err(SystemError::EINVAL); 1797 } 1798 1799 inode 1800 .children 1801 .insert(String::from(filename).to_uppercase(), nod.clone()); 1802 Ok(nod) 1803 } 1804 1805 fn special_node(&self) -> Option<SpecialNodeData> { 1806 self.0.lock().special_node.clone() 1807 } 1808 } 1809 1810 impl Default for FATFsInfo { 1811 fn default() -> Self { 1812 return FATFsInfo { 1813 lead_sig: FATFsInfo::LEAD_SIG, 1814 struc_sig: FATFsInfo::STRUC_SIG, 1815 free_count: 0xFFFFFFFF, 1816 next_free: RESERVED_CLUSTERS, 1817 trail_sig: FATFsInfo::TRAIL_SIG, 1818 dirty: false, 1819 offset: None, 1820 }; 1821 } 1822 } 1823 1824 impl Cluster { 1825 pub fn new(cluster: u64) -> Self { 1826 return Cluster { 1827 cluster_num: cluster, 1828 parent_cluster: 0, 1829 }; 1830 } 1831 } 1832 1833 /// @brief 用于迭代FAT表的内容的簇迭代器对象 1834 #[derive(Debug)] 1835 struct ClusterIter<'a> { 1836 /// 迭代器的next要返回的簇 1837 current_cluster: Option<Cluster>, 1838 /// 属于的文件系统 1839 fs: &'a FATFileSystem, 1840 } 1841 1842 impl<'a> Iterator for ClusterIter<'a> { 1843 type Item = Cluster; 1844 1845 fn next(&mut self) -> Option<Self::Item> { 1846 // 当前要返回的簇 1847 let ret: Option<Cluster> = self.current_cluster; 1848 1849 // 获得下一个要返回簇 1850 let new: Option<Cluster> = match self.current_cluster { 1851 Some(c) => { 1852 let entry: Option<FATEntry> = self.fs.get_fat_entry(c).ok(); 1853 match entry { 1854 Some(FATEntry::Next(c)) => Some(c), 1855 _ => None, 1856 } 1857 } 1858 _ => None, 1859 }; 1860 1861 self.current_cluster = new; 1862 return ret; 1863 } 1864 } 1865