1#![allow(dead_code)]
15#![allow(static_mut_refs)]
16
17pub mod storage_policy;
18pub mod block;
19pub mod btree;
20pub mod checksum;
21pub mod chunk;
23mod store;
25mod files;
27pub use files::{GcReport, SnapshotInfo, VersionInfo, DEFAULT_MAX_SNAPSHOTS, SB_KEEP_HISTORY};
28pub use store::Run;
29
30extern crate alloc;
31use alloc::boxed::Box;
32use alloc::vec::Vec;
33
34use block::{MirroredBlockDevice, RAMDisk, DATA_SIZE_PER_SECTOR};
35use btree::CowBTree;
36use core::ptr::null_mut;
37
38pub fn fnv1a_128(data: &[u8]) -> [u8; 16] {
39 let mut hash: u128 = 0x6c62272e07bb014262b821756295c58d;
40 for &b in data {
41 hash ^= b as u128;
42 hash = hash.wrapping_mul(0x0000000001000000000000000000013B);
43 }
44 hash.to_le_bytes()
45}
46
47pub fn normalize_path(path: &str) -> alloc::string::String {
54 let mut parts: alloc::vec::Vec<&str> = alloc::vec::Vec::new();
55 for seg in path.split('/') {
56 match seg {
57 "" | "." => {}
58 ".." => {
59 parts.pop();
60 }
61 s => {
62 parts.push(s);
63 }
64 }
65 }
66 if parts.is_empty() {
67 return alloc::string::String::from("/");
68 }
69 let mut out = alloc::string::String::with_capacity(path.len() + 1);
70 for seg in parts {
71 out.push('/');
72 out.push_str(seg);
73 }
74 out
75}
76
77#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct FileStat {
80 pub filename: alloc::string::String,
81 pub size: u64,
82 pub labels: alloc::string::String,
83 pub extent_count: u32,
84 pub sector_count: u64,
85 pub has_overflow: bool,
86}
87
88#[repr(C, packed)]
96#[derive(Clone, Copy, Default)]
97pub struct Extent {
98 pub start: u64,
100 pub count: u64,
102}
103
104const MAX_INLINE_EXTENTS: usize = 18;
107
108const EXTENTS_PER_OVERFLOW_SECTOR: usize = (DATA_SIZE_PER_SECTOR - 8) / 16;
111
112const SUPERBLOCK_SECTOR: usize = 0;
113const BITMAP_START_SECTOR: u32 = 1;
114const BITS_PER_BITMAP_SECTOR: u64 = (DATA_SIZE_PER_SECTOR as u64) * 8;
116
117fn bitmap_sectors_for(total_sectors: u64) -> u64 {
126 total_sectors.div_ceil(BITS_PER_BITMAP_SECTOR).max(1)
127}
128
129pub const SYLFS_MAGIC: &[u8; 8] = b"SYLFS\0\0\0";
130
131#[repr(C, packed)]
133#[derive(Clone, Copy)]
134pub struct Superblock {
135 pub magic: [u8; 8],
136 pub version: u32,
137 pub root_sector: u32, pub bitmap_start: u32,
139 pub bitmap_sectors: u32,
140 pub chunk_root: u32,
143 pub generation: u64,
145 pub snap_table: u32,
147 pub last_snap_gen: u64,
149 pub flags: u32,
151 pub max_snapshots: u32,
153}
154
155pub const SYLFS_FORMAT_VERSION: u32 = 2;
157
158#[repr(C, packed)]
160#[derive(Clone, Copy)]
161pub struct FileMetadata {
162 pub filename: [u8; 128],
166 pub label_data: [u8; 64], pub size: u64,
169 pub extent_count: u32,
171 pub overflow_sector: u64,
174 pub collision_next_sector: u64,
176 pub extents: [Extent; MAX_INLINE_EXTENTS],
178}
179
180const _: () = assert!(
186 core::mem::size_of::<FileMetadata>() <= DATA_SIZE_PER_SECTOR,
187 "FileMetadata must fit within a single sector"
188);
189
190impl FileMetadata {
191 pub fn new(name: &str, labels: &str, size: u64) -> Self {
192 let mut fm = Self {
193 filename: [0; 128],
194 label_data: [0; 64],
195 size,
196 extent_count: 0,
197 overflow_sector: 0,
198 collision_next_sector: 0,
199 extents: [Extent::default(); MAX_INLINE_EXTENTS],
200 };
201
202 let mut name_valid_len = 0;
204 for (i, c) in name.char_indices() {
205 if i + c.len_utf8() > 127 {
206 break;
207 }
208 name_valid_len = i + c.len_utf8();
209 }
210 let name_bytes = name.as_bytes();
211 fm.filename[..name_valid_len].copy_from_slice(&name_bytes[..name_valid_len]);
212
213 let mut label_valid_len = 0;
214 for (i, c) in labels.char_indices() {
215 if i + c.len_utf8() > 63 {
216 break;
217 }
218 label_valid_len = i + c.len_utf8();
219 }
220 let label_bytes = labels.as_bytes();
221 fm.label_data[..label_valid_len].copy_from_slice(&label_bytes[..label_valid_len]);
222
223 fm
224 }
225
226 pub fn get_filename(&self) -> &str {
227 let len = self.filename.iter().position(|&x| x == 0).unwrap_or(128);
228 unsafe { core::str::from_utf8_unchecked(&self.filename[..len]) }
229 }
230
231 pub fn get_labels(&self) -> &str {
232 let len = self.label_data.iter().position(|&x| x == 0).unwrap_or(64);
233 unsafe { core::str::from_utf8_unchecked(&self.label_data[..len]) }
234 }
235}
236
237pub struct SylFS {
238 pub device: MirroredBlockDevice<block::BackendDevice>,
239 pub superblock: Superblock,
240 next_bitmap_hint: u32,
251 volatile: Option<Box<SylFS>>,
255 pending: Vec<u32>,
258 free_count: Option<u64>,
260 pub name_hash_bits: u32,
264 in_reclaim: bool,
266 list_cache: Option<ListCache>,
269}
270
271struct ListCache {
277 generation: u64,
278 root: u32,
279 files: Vec<FileMetadata>,
280 by_label: alloc::collections::BTreeMap<alloc::string::String, Vec<u32>>,
282}
283
284impl SylFS {
285 pub fn from_parts(
291 device: MirroredBlockDevice<block::BackendDevice>,
292 superblock: Superblock,
293 ) -> Self {
294 Self {
295 device,
296 superblock,
297 next_bitmap_hint: 0,
298 volatile: None,
299 pending: Vec::new(),
300 free_count: None,
301 name_hash_bits: 0,
302 in_reclaim: false,
303 list_cache: None,
304 }
305 }
306
307 pub fn open(mut device: MirroredBlockDevice<block::BackendDevice>) -> Result<Self, &'static str> {
309 let mut buf = [0u8; DATA_SIZE_PER_SECTOR];
310 device.read_sector(SUPERBLOCK_SECTOR, &mut buf)?;
311 let superblock = unsafe { *(buf.as_ptr() as *const Superblock) };
312 if &superblock.magic != SYLFS_MAGIC {
313 return Err("open: not a SylFS volume");
314 }
315 let mut fs = Self::from_parts(device, superblock);
316 fs.upgrade_format()?;
317 Ok(fs)
318 }
319
320 pub fn upgrade_format(&mut self) -> Result<(), &'static str> {
323 if self.superblock.version >= SYLFS_FORMAT_VERSION {
324 return Ok(());
325 }
326 let mut sb = self.superblock;
327 sb.version = SYLFS_FORMAT_VERSION;
328 sb.chunk_root = 0;
329 sb.generation = 0;
330 sb.snap_table = 0;
331 sb.last_snap_gen = 0;
332 sb.flags = SB_KEEP_HISTORY;
333 sb.max_snapshots = DEFAULT_MAX_SNAPSHOTS;
334 let keep = self.pending.len();
335 self.commit_superblock(sb, keep)?;
336 crate::warn!("[FS] SylFS を形式 1 から形式 2(版の履歴・チャンク・スナップショット)へ移した");
337 Ok(())
338 }
339
340 pub fn name_key(&self, path: &str) -> [u8; 16] {
342 let key = fnv1a_128(path.as_bytes());
343 let bits = self.name_hash_bits;
344 if bits == 0 || bits >= 128 {
345 return key;
346 }
347 (u128::from_le_bytes(key) & ((1u128 << bits) - 1)).to_le_bytes()
348 }
349
350 pub fn set_volatile(&mut self, v: SylFS) {
352 self.volatile = Some(Box::new(v));
353 }
354
355 fn volatile_for(&mut self, path: &str) -> Option<&mut SylFS> {
357 if storage_policy::is_disposable(path) {
358 self.volatile.as_deref_mut()
359 } else {
360 None
361 }
362 }
363}
364
365static mut FS_INSTANCE: *mut SylFS = null_mut();
366
367include!(concat!(env!("OUT_DIR"), "/app_assets.rs"));
369
370pub fn format_device(
379 device: &mut MirroredBlockDevice<block::BackendDevice>,
380) -> Result<Superblock, &'static str> {
381 let total = device.total_usable_sectors() as u64;
382 let bitmap_sectors = bitmap_sectors_for(total);
383
384 let superblock = Superblock {
385 magic: *SYLFS_MAGIC,
386 version: SYLFS_FORMAT_VERSION,
387 root_sector: 0, bitmap_start: BITMAP_START_SECTOR,
389 bitmap_sectors: bitmap_sectors as u32,
390 chunk_root: 0,
391 generation: 0,
392 snap_table: 0,
393 last_snap_gen: 0,
394 flags: SB_KEEP_HISTORY,
395 max_snapshots: DEFAULT_MAX_SNAPSHOTS,
396 };
397
398 crate::info!(
399 "[FS] Formatting: total_sectors={} bitmap_sectors={} (capacity {} MiB)",
400 total,
401 bitmap_sectors,
402 total * DATA_SIZE_PER_SECTOR as u64 / (1024 * 1024)
403 );
404
405 let reserved = 1 + bitmap_sectors; let mut first = [0u8; DATA_SIZE_PER_SECTOR];
409 for s in 0..reserved.min(BITS_PER_BITMAP_SECTOR) {
410 let byte = (s / 8) as usize;
411 let bit = (s % 8) as u8;
412 first[byte] |= 1 << bit;
413 }
414
415 for i in 0..bitmap_sectors {
416 let sec = BITMAP_START_SECTOR as u64 + i;
417 let data_to_write = if i == 0 {
418 &first[..]
419 } else {
420 &[0u8; DATA_SIZE_PER_SECTOR][..]
421 };
422 if let Err(e) = device.write_sector(sec as usize, data_to_write) {
423 crate::error!("[FS] Format failed: bitmap sector {} not written: {}", sec, e);
424 return Err(e);
425 }
426 }
427
428 let mut sb_buf = [0u8; DATA_SIZE_PER_SECTOR];
430 unsafe {
431 core::ptr::copy_nonoverlapping(
432 &superblock as *const Superblock as *const u8,
433 sb_buf.as_mut_ptr(),
434 core::mem::size_of::<Superblock>(),
435 );
436 }
437 if let Err(e) = device.write_sector(SUPERBLOCK_SECTOR, &sb_buf) {
438 crate::error!("[FS] Format failed: superblock not written: {}", e);
439 return Err(e);
440 }
441
442 crate::info!("[FS] Format completed successfully!");
443 Ok(superblock)
444}
445
446fn dedicated_ramdisk() -> block::RAMDisk {
449 extern "C" {
454 static __cpu_stacks_end: u8;
455 }
456 let heap_start = core::ptr::addr_of!(__cpu_stacks_end) as usize;
457 let heap_size = crate::kernel::allocator::KERNEL_HEAP_SIZE;
459 let ramdisk_start = heap_start + heap_size;
460 let gpu_boundary = crate::kernel::mmu::DEVICE_REGION_START;
463 let ramdisk_size = if gpu_boundary > ramdisk_start {
464 gpu_boundary - ramdisk_start
465 } else {
466 64 * 1024 * 1024
467 };
468
469 let ram_disk = unsafe { block::RAMDisk::from_raw_memory(ramdisk_start, ramdisk_size) };
470 crate::warn!(
475 "[FS] Dedicated RAMDisk allocated from 0x{:08X} to 0x{:08X} ({} MB)",
476 ramdisk_start,
477 ramdisk_start + ramdisk_size,
478 ramdisk_size / (1024 * 1024)
479 );
480 ram_disk
481}
482
483pub fn mount() -> Result<(), &'static str> {
490 crate::info!("[FS] Mounting SylFS (COW Label-based File System)...");
491
492 let backend = match block::SDCard::new() {
494 Ok(sd_card) => {
495 crate::info!("[FS] microSD card backend successfully initialized.");
496 block::BackendDevice::SD(sd_card)
497 }
498 Err(e) => {
499 crate::warn!("[FS] Failed to initialize microSD card: {}. Falling back to RAMDisk...", e);
500 block::BackendDevice::RAM(dedicated_ramdisk())
529 }
530 };
531
532 let mut device = MirroredBlockDevice::new(backend);
533
534 let mut superblock = Superblock {
535 magic: [0; 8],
536 version: 0,
537 root_sector: 0,
538 bitmap_start: BITMAP_START_SECTOR,
539 bitmap_sectors: 4, chunk_root: 0,
541 generation: 0,
542 snap_table: 0,
543 last_snap_gen: 0,
544 flags: 0,
545 max_snapshots: 0,
546 };
547
548 let mut is_formatted = false;
549 let mut buf = [0u8; DATA_SIZE_PER_SECTOR];
550
551 crate::kernel::uart::set_silent(true);
553 let read_res = device.read_sector(SUPERBLOCK_SECTOR, &mut buf);
554 crate::kernel::uart::set_silent(false);
555
556 if read_res.is_ok() {
557 unsafe {
558 core::ptr::copy_nonoverlapping(
559 buf.as_ptr(),
560 &mut superblock as *mut Superblock as *mut u8,
561 core::mem::size_of::<Superblock>(),
562 );
563 }
564 if &superblock.magic == SYLFS_MAGIC {
565 is_formatted = true;
566 let root_sec = superblock.root_sector;
567 crate::info!(
568 "[FS] SylFS successfully mounted! Root B-Tree root at Sector {}",
569 root_sec
570 );
571 }
572 }
573
574 let mut status: Result<(), &'static str> = Ok(());
576
577 if !is_formatted {
578 crate::info!("[FS] SylFS not detected. Formatting disk...");
579 match format_device(&mut device) {
580 Ok(sb) => superblock = sb,
581 Err(e) => {
582 crate::error!("[FS] Format failed: {}", e);
585 status = Err(e);
586 }
587 }
588 }
589
590 let on_sd = device.is_mirrored();
591 let mut fs = Box::new(SylFS::from_parts(device, superblock));
592 if is_formatted {
598 if let Err(e) = fs.upgrade_format() {
599 crate::error!("[FS] 形式 2 への移行に失敗: {}", e);
600 }
601 }
602 if on_sd {
605 let mut vdev = MirroredBlockDevice::new(block::BackendDevice::RAM(dedicated_ramdisk()));
606 match format_device(&mut vdev) {
607 Ok(vsb) => {
608 let mut vfs = SylFS::from_parts(vdev, vsb);
609 if let Err(e) = vfs.set_keep_history(false) {
611 crate::error!("[FS] 一時ファイルの置き場の設定に失敗: {}", e);
612 }
613 fs.set_volatile(vfs);
614 crate::warn!("[FS] 一時ファイル(/cache/・/tmp/)は RAMDisk に置く");
615 }
616 Err(e) => {
617 crate::error!("[FS] 一時ファイル用の RAMDisk をフォーマットできない: {}(一時ファイルも microSD に書く)", e);
619 if status.is_ok() {
620 status = Err(e);
621 }
622 }
623 }
624 }
625 unsafe {
626 FS_INSTANCE = Box::into_raw(fs);
627 }
628
629 let fs_ref = get_fs();
631
632 let mut asset_failures = 0usize;
633 for asset in APP_ASSETS.iter() {
634 if let Err(e) = fs_ref.save_file(asset.path, asset.data, "sys") {
635 crate::error!("[FS] Failed to install default app '{}': {}", asset.path, e);
638 asset_failures += 1;
639 }
640 }
641
642 if asset_failures > 0 {
643 crate::error!(
644 "[FS] {} of {} pre-installed apps could not be written.",
645 asset_failures,
646 APP_ASSETS.len()
647 );
648 if status.is_ok() {
649 status = Err("failed to install pre-installed apps");
650 }
651 } else {
652 crate::info!("[FS] Pre-installed default apps updated.");
653 }
654
655 status
656}
657
658pub fn read_file(path: &str) -> Option<alloc::vec::Vec<u8>> {
660 let fs = get_fs();
661 let (_meta, data) = fs.read_file(path)?;
662 Some(data)
663}
664
665pub fn read_file_checked(path: &str) -> Result<Option<alloc::vec::Vec<u8>>, &'static str> {
667 let fs = get_fs();
668 match fs.read_file_checked(path) {
669 Ok(Some((_meta, data))) => Ok(Some(data)),
670 Ok(None) => Ok(None),
671 Err(e) => Err(e),
672 }
673}
674
675pub fn is_mounted() -> bool {
677 unsafe { !FS_INSTANCE.is_null() }
678}
679
680pub static FS_LOCK: crate::kernel::reclock::RecoverableMutex<()> =
748 crate::kernel::reclock::RecoverableMutex::new(());
749
750pub fn force_release_locks(cid: i16) {
753 unsafe {
754 FS_LOCK.force_release_if_core(cid);
755 }
756}
757
758pub fn get_fs() -> &'static mut SylFS {
759 unsafe {
760 assert!(!FS_INSTANCE.is_null(), "SylFS not mounted!");
761 &mut *FS_INSTANCE
762 }
763}
764
765impl SylFS {
766 pub fn allocate_sector(&mut self) -> u32 {
770 let mut s = self.allocate_raw();
771 if s == 0 && !self.in_reclaim {
772 self.in_reclaim = true;
773 if self.reclaim_for_allocation() > 0 {
774 s = self.allocate_raw();
775 }
776 self.in_reclaim = false;
777 }
778 if s != 0 {
779 self.pending.push(s);
780 }
781 s
782 }
783
784 fn allocate_raw(&mut self) -> u32 {
785 let mut buf = [0u8; DATA_SIZE_PER_SECTOR];
786
787 let total = self.superblock.bitmap_sectors;
794 for step in 0..total {
795 let i = (self.next_bitmap_hint + step) % total.max(1);
796 let sec = self.superblock.bitmap_start + i;
797 if self.device.read_sector(sec as usize, &mut buf).is_err() {
798 crate::error!("[FS] [SylFS] Failed to read bitmap sector {}", sec);
799 continue;
800 }
801
802 for byte_idx in 0..DATA_SIZE_PER_SECTOR {
803 let byte = buf[byte_idx];
804 if byte != 0xFF {
805 for bit in 0..8 {
807 if (byte & (1 << bit)) == 0 {
808 buf[byte_idx] |= 1 << bit;
810
811 if let Err(e) = self.device.write_sector(sec as usize, &buf) {
817 crate::error!(
818 "[SylFS] allocate_sector: bitmap write failed on sector {}: {}",
819 sec,
820 e
821 );
822 return 0;
823 }
824
825 self.next_bitmap_hint = i;
827 let allocated_sector = (i * DATA_SIZE_PER_SECTOR as u32 * 8)
828 + (byte_idx as u32 * 8)
829 + bit as u32;
830 if allocated_sector as usize >= self.device.total_usable_sectors() {
846 buf[byte_idx] &= !(1 << bit);
848 if let Err(e) = self.device.write_sector(sec as usize, &buf) {
853 crate::error!(
854 "[SylFS] allocate_sector: 余剰ビットの戻し書きに失敗 sector={} err={}(ビットが漏れる)",
855 sec,
856 e
857 );
858 }
859 crate::warn!(
860 "[SylFS] allocate_sector: ビットマップの余剰ビットに到達 (sector={} usable={})。満杯として扱う",
861 allocated_sector,
862 self.device.total_usable_sectors()
863 );
864 return 0;
865 }
866 if let Some(f) = self.free_count.as_mut() {
867 *f = f.saturating_sub(1);
868 }
869 return allocated_sector;
870 }
871 }
872 }
873 }
874 }
875 crate::error!("[FS] [SylFS] allocate_sector failed (Disk Full)");
876 0 }
878
879 pub fn deallocate_sector(&mut self, sector: u32) {
881 let i = sector / (DATA_SIZE_PER_SECTOR as u32 * 8);
882 let rem = sector % (DATA_SIZE_PER_SECTOR as u32 * 8);
883 let byte_idx = (rem / 8) as usize;
884 let bit = rem % 8;
885
886 let sec = self.superblock.bitmap_start + i;
887 let mut buf = [0u8; DATA_SIZE_PER_SECTOR];
888 if self.device.read_sector(sec as usize, &mut buf).is_ok() {
889 let was_used = buf[byte_idx] & (1 << bit) != 0;
890 buf[byte_idx] &= !(1 << bit); if was_used {
892 if let Some(f) = self.free_count.as_mut() {
893 *f += 1;
894 }
895 }
896 if let Err(e) = self.device.write_sector(sec as usize, &buf) {
900 crate::error!(
901 "[SylFS] deallocate_sector({}): bitmap write failed: {} (sector leaked)",
902 sector,
903 e
904 );
905 }
906 } else {
907 crate::error!(
908 "[SylFS] deallocate_sector({}): bitmap read failed (sector leaked)",
909 sector
910 );
911 }
912 }
913
914
915
916 fn collect_extents(&mut self, meta: &FileMetadata) -> Option<Vec<Extent>> {
918 let total = meta.extent_count as usize;
919 let mut out: Vec<Extent> = Vec::with_capacity(total);
920
921 let inline_n = total.min(MAX_INLINE_EXTENTS);
922 for e in meta.extents.iter().take(inline_n) {
923 out.push(*e);
924 }
925
926 let mut next = meta.overflow_sector;
927 while next != 0 && out.len() < total {
928 let mut buf = [0u8; DATA_SIZE_PER_SECTOR];
929 if self.device.read_sector(next as usize, &mut buf).is_err() {
930 return None;
931 }
932 let following = u64::from_le_bytes([
933 buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7],
934 ]);
935 for i in 0..EXTENTS_PER_OVERFLOW_SECTOR {
936 if out.len() >= total {
937 break;
938 }
939 let off = 8 + i * 16;
940 let start = u64::from_le_bytes([
941 buf[off], buf[off + 1], buf[off + 2], buf[off + 3],
942 buf[off + 4], buf[off + 5], buf[off + 6], buf[off + 7],
943 ]);
944 let count = u64::from_le_bytes([
945 buf[off + 8], buf[off + 9], buf[off + 10], buf[off + 11],
946 buf[off + 12], buf[off + 13], buf[off + 14], buf[off + 15],
947 ]);
948 if count == 0 {
949 continue;
950 }
951 out.push(Extent { start, count });
952 }
953 next = following;
954 }
955 Some(out)
956 }
957
958 fn rom_fallback(filename: &str) -> Option<(FileMetadata, Vec<u8>)> {
961 APP_ASSETS
962 .iter()
963 .find(|a| a.path == filename)
964 .map(|a| (FileMetadata::new(filename, "rom", a.data.len() as u64), a.data.to_vec()))
965 }
966
967 fn extents_to_sectors(extents: &[Extent]) -> Vec<u64> {
968 let mut secs = Vec::new();
969 for e in extents {
970 for k in 0..e.count {
971 secs.push(e.start + k);
972 }
973 }
974 secs
975 }
976
977 pub fn find_by_label(&mut self, label: &str) -> Vec<FileMetadata> {
979 self.find_by_labels(&[label], false)
980 }
981
982 pub fn find_by_labels(&mut self, labels: &[&str], match_all: bool) -> Vec<FileMetadata> {
988 if labels.is_empty() {
989 return Vec::new();
990 }
991 let mut out = self.find_by_labels_here(labels, match_all);
992 if let Some(v) = self.volatile.as_deref_mut() {
993 out.extend(v.find_by_labels_here(labels, match_all));
994 }
995 out
996 }
997
998 fn find_by_labels_here(&mut self, labels: &[&str], match_all: bool) -> Vec<FileMetadata> {
999 let cache = self.list_index();
1000 let hits = |l: &&str| cache.by_label.get(*l).map(Vec::as_slice).unwrap_or(&[]);
1001 let mut idx: Vec<u32> = if match_all {
1002 let mut sets: Vec<&[u32]> = labels.iter().map(hits).collect();
1004 sets.sort_by_key(|s| s.len());
1005 let (first, rest) = sets.split_first().map(|(f, r)| (*f, r)).unwrap_or((&[], &[]));
1006 first.iter().copied().filter(|i| rest.iter().all(|s| s.binary_search(i).is_ok())).collect()
1007 } else {
1008 labels.iter().flat_map(|l| hits(l).iter().copied()).collect()
1009 };
1010 idx.sort_unstable();
1011 idx.dedup();
1012 idx.into_iter().filter_map(|i| cache.files.get(i as usize).copied()).collect()
1013 }
1014
1015 pub fn list_all_labels(&mut self) -> Vec<alloc::string::String> {
1017 let mut labels: Vec<alloc::string::String> =
1018 self.list_index().by_label.keys().filter(|k| !k.is_empty()).cloned().collect();
1019 if let Some(v) = self.volatile.as_deref_mut() {
1020 labels.extend(v.list_index().by_label.keys().filter(|k| !k.is_empty()).cloned());
1021 }
1022 labels.sort();
1023 labels.dedup();
1024 labels
1025 }
1026
1027 fn list_index(&mut self) -> &ListCache {
1029 let (generation, root) = (self.superblock.generation, self.superblock.root_sector);
1030 let fresh = matches!(&self.list_cache, Some(c) if c.generation == generation && c.root == root);
1031 if !fresh {
1032 let failures = self.device.read_failures();
1033 let files = self.list_in(root);
1034 let mut by_label: alloc::collections::BTreeMap<alloc::string::String, Vec<u32>> =
1035 alloc::collections::BTreeMap::new();
1036 for (i, meta) in files.iter().enumerate() {
1037 for l in meta.get_labels().split(',') {
1038 let ids = by_label.entry(alloc::string::String::from(l.trim())).or_default();
1039 if ids.last() != Some(&(i as u32)) {
1040 ids.push(i as u32);
1041 }
1042 }
1043 }
1044 let complete = self.device.read_failures() == failures;
1046 self.list_cache = Some(ListCache {
1047 generation: if complete { generation } else { u64::MAX },
1048 root,
1049 files,
1050 by_label,
1051 });
1052 }
1053 self.list_cache.get_or_insert_with(|| ListCache {
1055 generation: u64::MAX,
1056 root,
1057 files: Vec::new(),
1058 by_label: alloc::collections::BTreeMap::new(),
1059 })
1060 }
1061
1062 pub fn list_dir(&mut self, prefix: &str) -> Vec<FileMetadata> {
1064 let mut results = Vec::new();
1065 let all_files = self.list_files();
1066 for meta in all_files {
1067 if meta.get_filename().starts_with(prefix) {
1068 results.push(meta);
1069 }
1070 }
1071 results
1072 }
1073
1074}
1075
1076#[derive(Debug, Default, PartialEq, Eq, Clone)]
1078pub struct FsckReport {
1079 pub total_sectors: u64,
1080 pub used_sectors: u64,
1081 pub file_count: u64,
1082 pub btree_node_count: u64,
1083 pub extent_count: u64,
1084 pub corrupted_sectors: u64,
1085 pub leaked_sectors: u64,
1087 pub unallocated_refs: u64,
1089 pub double_refs: u64,
1091 pub is_healthy: bool,
1092}
1093
1094pub fn selftest() -> (u32, u32) {
1099 let mut pass = 0u32;
1100 let mut total = 0u32;
1101
1102 {
1104 let mut dev = MirroredBlockDevice::new(RAMDisk::new(1024 * 1024));
1105 let mut next_sec: u32 = 10; let mut btree = CowBTree::new(0);
1107 const N: u32 = 40; let make_key = |i: u32| -> [u8; 16] {
1110 let mut k = [0u8; 16];
1111 k[..4].copy_from_slice(&i.to_be_bytes());
1112 k
1113 };
1114
1115 let mut ok = true;
1117 for i in 0..N {
1118 let key = make_key(i);
1119 let mut alloc = || {
1120 let s = next_sec;
1121 next_sec += 1;
1122 s
1123 };
1124 if btree.insert(&mut dev, &key, 2000 + i, &mut alloc).is_err() {
1125 ok = false;
1126 break;
1127 }
1128 }
1129 total += 1;
1130 if ok {
1131 pass += 1;
1132 }
1133
1134 let mut ok2 = true;
1136 for i in 0..N {
1137 let key = make_key(i);
1138 let mut alloc = || {
1139 let s = next_sec;
1140 next_sec += 1;
1141 s
1142 };
1143 if btree.insert(&mut dev, &key, 3000 + i, &mut alloc).is_err() {
1144 ok2 = false;
1145 break;
1146 }
1147 }
1148 total += 1;
1149 if ok2 {
1150 pass += 1;
1151 }
1152
1153 let mut all_ok = true;
1155 for i in 0..N {
1156 let key = make_key(i);
1157 if btree.search(&mut dev, &key) != Some(3000 + i) {
1158 all_ok = false;
1159 }
1160 }
1161 total += 1;
1162 if all_ok {
1163 pass += 1;
1164 }
1165 }
1166
1167 {
1169 let mut dev = MirroredBlockDevice::new_mirrored(RAMDisk::new(64 * 1024));
1170 let sector = 5usize;
1171 let payload = b"SylFS dual-redundancy selftest payload";
1172 total += 1;
1175 if dev.write_sector(sector, payload).is_ok() {
1176 pass += 1;
1177 }
1178
1179 let _ = dev.force_corrupt_raw_sector(sector);
1181 let mut buf = [0u8; DATA_SIZE_PER_SECTOR];
1182 let healed = dev.read_sector(sector, &mut buf).is_ok() && &buf[..payload.len()] == payload;
1183 total += 1;
1184 if healed {
1185 pass += 1;
1186 }
1187
1188 let mut buf2 = [0u8; DATA_SIZE_PER_SECTOR];
1190 let reread =
1191 dev.read_sector(sector, &mut buf2).is_ok() && &buf2[..payload.len()] == payload;
1192 total += 1;
1193 if reread {
1194 pass += 1;
1195 }
1196
1197 let mirror = sector + dev.total_usable_sectors();
1199 let _ = dev.force_corrupt_raw_sector(sector);
1200 let _ = dev.force_corrupt_raw_sector(mirror);
1201 let mut buf3 = [0u8; DATA_SIZE_PER_SECTOR];
1202 total += 1;
1203 if dev.read_sector(sector, &mut buf3).is_err() {
1204 pass += 1;
1205 }
1206 }
1207
1208 (pass, total)
1209}