1use super::store::{get_u32, get_u64, put_u32, put_u64, Marks, Record, Run};
17use super::*;
18use alloc::collections::BTreeSet;
19use alloc::string::String;
20use alloc::vec::Vec;
21
22pub(super) const V2_MAGIC: &[u8; 4] = b"SYV2";
24pub(super) const BUCKET_MAGIC: &[u8; 4] = b"SYBK";
26pub(super) const SNAP_MAGIC: &[u8; 4] = b"SYSN";
28pub const VERSION_DELETED: u32 = 1;
30pub const SB_KEEP_HISTORY: u32 = 1;
32pub const SNAP_PINNED: u32 = 1;
34pub const DEFAULT_MAX_SNAPSHOTS: u32 = 16;
36
37const REC: usize = DATA_SIZE_PER_SECTOR;
38const INLINE_RUNS: usize = 33;
39const RUNS_PER_OVERFLOW: usize = (REC - 4) / 8; const BUCKET_CAP: usize = (REC - 8) / 4; const SNAP_REC: usize = 56;
42const SNAPS_PER_SECTOR: usize = (REC - 12) / SNAP_REC; #[derive(Clone, Debug)]
46pub struct VersionMeta {
47 pub flags: u32,
48 pub name: String,
49 pub labels: String,
50 pub size: u64,
51 pub generation: u64,
52 pub mtime: u64,
53 pub prev_version: u32,
54 pub prev_gen: u64,
55 pub runs: Vec<Run>,
56 pub run_overflow: u32,
58}
59
60impl VersionMeta {
61 pub fn is_deleted(&self) -> bool {
62 self.flags & VERSION_DELETED != 0
63 }
64}
65
66fn fit(s: &str, max: usize) -> &str {
67 let mut end = 0;
68 for (i, c) in s.char_indices() {
69 if i + c.len_utf8() > max {
70 break;
71 }
72 end = i + c.len_utf8();
73 }
74 s.get(..end).unwrap_or("")
75}
76
77fn get_str(b: &[u8]) -> String {
78 let n = b.iter().position(|&x| x == 0).unwrap_or(b.len());
79 String::from(core::str::from_utf8(&b[..n]).unwrap_or(""))
80}
81
82fn encode_version(m: &VersionMeta, overflow: u32) -> Record {
86 let mut b = [0u8; REC];
87 b[0..4].copy_from_slice(V2_MAGIC);
88 put_u32(&mut b, 4, m.flags);
89 let n = fit(&m.name, 127).as_bytes();
90 b[8..8 + n.len()].copy_from_slice(n);
91 let l = fit(&m.labels, 63).as_bytes();
92 b[136..136 + l.len()].copy_from_slice(l);
93 put_u64(&mut b, 200, m.size);
94 put_u64(&mut b, 208, m.generation);
95 put_u64(&mut b, 216, m.mtime);
96 put_u32(&mut b, 224, m.prev_version);
97 put_u64(&mut b, 228, m.prev_gen);
98 put_u32(&mut b, 236, m.runs.len() as u32);
99 put_u32(&mut b, 240, overflow);
100 for (i, r) in m.runs.iter().take(INLINE_RUNS).enumerate() {
101 put_u32(&mut b, 244 + i * 8, r.start);
102 put_u32(&mut b, 248 + i * 8, r.len);
103 }
104 b
105}
106
107#[derive(Clone)]
109#[allow(clippy::large_enum_variant)] pub(super) enum AnyMeta {
111 V1(FileMetadata),
112 V2(VersionMeta),
113}
114
115impl AnyMeta {
116 fn name(&self) -> String {
117 match self {
118 AnyMeta::V1(m) => String::from(m.get_filename()),
119 AnyMeta::V2(m) => m.name.clone(),
120 }
121 }
122 fn is_deleted(&self) -> bool {
123 match self {
124 AnyMeta::V1(m) => m.filename[0] == 0,
125 AnyMeta::V2(m) => m.is_deleted(),
126 }
127 }
128 fn generation(&self) -> u64 {
129 match self {
130 AnyMeta::V1(_) => 0,
131 AnyMeta::V2(m) => m.generation,
132 }
133 }
134 fn size(&self) -> u64 {
135 match self {
136 AnyMeta::V1(m) => m.size,
137 AnyMeta::V2(m) => m.size,
138 }
139 }
140 pub(super) fn to_api(&self) -> FileMetadata {
142 match self {
143 AnyMeta::V1(m) => *m,
144 AnyMeta::V2(m) => FileMetadata::new(&m.name, &m.labels, m.size),
145 }
146 }
147}
148
149struct Lookup {
151 key: [u8; 16],
152 members: Vec<u32>,
154 index: Option<usize>,
156 meta: Option<(u32, AnyMeta)>,
157}
158
159impl Lookup {
160 fn live(&self) -> Option<&(u32, AnyMeta)> {
161 self.meta.as_ref().filter(|(_, m)| !m.is_deleted())
162 }
163}
164
165#[derive(Clone, Debug, PartialEq, Eq)]
167pub struct VersionInfo {
168 pub generation: u64,
169 pub mtime: u64,
170 pub size: u64,
171 pub deleted: bool,
172 pub labels: String,
173 pub(super) record: u32,
174}
175
176#[derive(Clone, Debug, PartialEq, Eq)]
178pub struct SnapshotInfo {
179 pub generation: u64,
180 pub time: u64,
181 pub name: String,
182 pub pinned: bool,
183 pub(super) root: u32,
184}
185
186#[derive(Clone, Debug, Default, PartialEq, Eq)]
188pub struct GcReport {
189 pub freed: u64,
191 pub fixed: u64,
193 pub tombstones_dropped: u64,
195 pub index_entries_dropped: u64,
197}
198
199#[derive(Default)]
201struct Census {
202 files: u64,
203 nodes: u64,
204 runs: u64,
205}
206
207fn now_unix() -> u64 {
208 crate::kernel::timer::get_unix_time().unwrap_or(0)
209}
210
211impl SylFS {
212 fn keep_history(&self) -> bool {
215 self.superblock.flags & SB_KEEP_HISTORY != 0
216 }
217
218 fn history_for(&self, path: &str) -> bool {
222 self.keep_history() && !storage_policy::is_disposable(path)
223 }
224
225 pub fn set_keep_history(&mut self, keep: bool) -> Result<(), &'static str> {
227 let mut sb = self.superblock;
228 if keep {
229 sb.flags |= SB_KEEP_HISTORY;
230 } else {
231 sb.flags &= !SB_KEEP_HISTORY;
232 }
233 let keep_n = self.pending.len();
234 self.commit_superblock(sb, keep_n)
235 }
236
237 pub(super) fn read_meta(&mut self, record: u32) -> Result<AnyMeta, &'static str> {
239 let b = self.read_record(record)?;
240 if &b[0..4] != V2_MAGIC {
241 return Ok(AnyMeta::V1(unsafe { *(b.as_ptr() as *const FileMetadata) }));
242 }
243 let count = get_u32(&b, 236) as usize;
244 let overflow = get_u32(&b, 240);
245 let mut runs = Vec::with_capacity(count);
246 for i in 0..count.min(INLINE_RUNS) {
247 runs.push(Run { start: get_u32(&b, 244 + i * 8), len: get_u32(&b, 248 + i * 8) });
248 }
249 let mut next = overflow;
250 let mut guard = 0;
251 while runs.len() < count && next != 0 {
252 guard += 1;
253 if guard > 1_000_000 {
254 return Err("run overflow chain loop");
255 }
256 let ob = self.read_record(next)?;
257 for i in 0..RUNS_PER_OVERFLOW {
258 if runs.len() >= count {
259 break;
260 }
261 runs.push(Run { start: get_u32(&ob, 4 + i * 8), len: get_u32(&ob, 8 + i * 8) });
262 }
263 next = get_u32(&ob, 0);
264 }
265 if runs.len() < count {
266 return Err("run list truncated");
267 }
268 Ok(AnyMeta::V2(VersionMeta {
269 flags: get_u32(&b, 4),
270 name: get_str(&b[8..136]),
271 labels: get_str(&b[136..200]),
272 size: get_u64(&b, 200),
273 generation: get_u64(&b, 208),
274 mtime: get_u64(&b, 216),
275 prev_version: get_u32(&b, 224),
276 prev_gen: get_u64(&b, 228),
277 runs,
278 run_overflow: overflow,
279 }))
280 }
281
282 fn overflow_records(&mut self, first: u32) -> Vec<u32> {
284 let mut out = Vec::new();
285 let mut next = first;
286 while next != 0 && out.len() < 1_000_000 {
287 out.push(next);
288 match self.read_record(next) {
289 Ok(b) => next = get_u32(&b, 0),
290 Err(_) => break,
291 }
292 }
293 out
294 }
295
296 fn write_version(&mut self, m: &VersionMeta) -> Result<u32, &'static str> {
298 let mut overflow = 0u32;
299 if m.runs.len() > INLINE_RUNS {
300 for part in m.runs[INLINE_RUNS..].chunks(RUNS_PER_OVERFLOW).rev() {
301 let mut ob = [0u8; REC];
302 put_u32(&mut ob, 0, overflow);
303 for (i, r) in part.iter().enumerate() {
304 put_u32(&mut ob, 4 + i * 8, r.start);
305 put_u32(&mut ob, 8 + i * 8, r.len);
306 }
307 overflow = self.write_record(&ob)?;
308 }
309 }
310 self.write_record(&encode_version(m, overflow))
311 }
312
313 fn members_of(&mut self, value: u32) -> Result<Vec<u32>, &'static str> {
317 if value == 0 {
318 return Ok(Vec::new());
319 }
320 let b = self.read_record(value)?;
321 if &b[0..4] == BUCKET_MAGIC {
322 let n = (get_u32(&b, 4) as usize).min(BUCKET_CAP);
323 return Ok((0..n).map(|i| get_u32(&b, 8 + i * 4)).collect());
324 }
325 if &b[0..4] == V2_MAGIC {
326 return Ok(alloc::vec![value]);
327 }
328 let mut out = Vec::new();
330 let mut cur = value as u64;
331 let mut guard = 0;
332 while cur != 0 {
333 guard += 1;
334 if guard > 1024 {
335 return Err("collision chain loop detected");
336 }
337 let mb = self.read_record(cur as u32)?;
338 let m = unsafe { *(mb.as_ptr() as *const FileMetadata) };
339 if m.filename[0] != 0 {
340 out.push(cur as u32);
341 }
342 cur = m.collision_next_sector;
343 }
344 Ok(out)
345 }
346
347 fn value_for_members(&mut self, members: &[u32]) -> Result<u32, &'static str> {
349 match members.len() {
350 0 => Ok(0),
351 1 => Ok(members[0]),
352 n if n > BUCKET_CAP => Err("too many paths share one hash"),
353 n => {
354 let mut b = [0u8; REC];
355 b[0..4].copy_from_slice(BUCKET_MAGIC);
356 put_u32(&mut b, 4, n as u32);
357 for (i, m) in members.iter().enumerate() {
358 put_u32(&mut b, 8 + i * 4, *m);
359 }
360 self.write_record(&b)
361 }
362 }
363 }
364
365 fn lookup_in(&mut self, root: u32, path: &str) -> Result<Lookup, &'static str> {
366 let key = self.name_key(path);
367 let value = self.index_search(root, &key).unwrap_or(0);
368 let members = self.members_of(value)?;
369 let mut index = None;
370 let mut meta = None;
371 for (i, &m) in members.iter().enumerate() {
372 let am = self.read_meta(m)?;
373 if am.name() == path {
374 index = Some(i);
375 meta = Some((m, am));
376 break;
377 }
378 }
379 Ok(Lookup { key, members, index, meta })
380 }
381
382 fn put_member(&mut self, root: u32, lk: &Lookup, new: Option<u32>) -> Result<u32, &'static str> {
384 let mut members = lk.members.clone();
385 match (lk.index, new) {
386 (Some(i), Some(s)) => members[i] = s,
387 (Some(i), None) => {
388 members.remove(i);
389 }
390 (None, Some(s)) => members.push(s),
391 (None, None) => {}
392 }
393 let value = self.value_for_members(&members)?;
394 self.index_insert(root, &lk.key, value)
395 }
396
397 fn runs_of_v1(&mut self, m: &FileMetadata) -> Result<Vec<Run>, &'static str> {
401 let extents = self.collect_extents(m).ok_or("extent list unreadable")?;
402 let mut left = m.size;
403 let mut runs = Vec::new();
404 for e in extents {
405 if left == 0 {
406 break;
407 }
408 let bytes = (e.count * DATA_SIZE_PER_SECTOR as u64).min(left);
409 runs.push(Run { start: e.start as u32, len: bytes as u32 });
410 left -= bytes;
411 }
412 Ok(runs)
413 }
414
415 fn runs_of(&mut self, m: &AnyMeta) -> Result<Vec<Run>, &'static str> {
416 match m {
417 AnyMeta::V1(v1) => self.runs_of_v1(v1),
418 AnyMeta::V2(v2) => Ok(v2.runs.clone()),
419 }
420 }
421
422 fn content_of(&mut self, m: &AnyMeta) -> Result<Vec<u8>, &'static str> {
423 let runs = self.runs_of(m)?;
424 self.read_blob(&runs, m.size())
425 }
426
427 fn transact(&mut self, f: impl FnOnce(&mut Self) -> Result<(), &'static str>) -> Result<(), &'static str> {
431 let r = f(self);
432 if r.is_err() {
433 self.abort();
434 }
435 r
436 }
437
438 pub fn save_file(&mut self, filename: &str, content: &[u8], labels: &str) -> Result<(), &'static str> {
440 let path = normalize_path(filename);
441 if let Some(v) = self.volatile_for(&path) {
442 return v.save_file(&path, content, labels);
443 }
444 self.maintain_space();
445 self.transact(|fs| fs.save_inner(&path, content, labels))
446 }
447
448 fn save_inner(&mut self, path: &str, content: &[u8], labels: &str) -> Result<(), &'static str> {
449 let root = self.superblock.root_sector;
450 let lk = self.lookup_in(root, path)?;
451 let mut chunk_root = self.superblock.chunk_root;
452 let dedup = self.history_for(path);
453 let runs = self.store_blob(content, &mut chunk_root, dedup)?;
454 if let Some((_, AnyMeta::V2(cur))) = lk.live() {
455 if cur.runs == runs && cur.size == content.len() as u64 && cur.labels == fit(labels, 63) {
456 self.abort();
458 return Ok(());
459 }
460 }
461 let (prev, prev_gen) = self.prev_of(&lk, path);
462 let meta = VersionMeta {
463 flags: 0,
464 name: String::from(path),
465 labels: String::from(labels),
466 size: content.len() as u64,
467 generation: self.superblock.generation + 1,
468 mtime: now_unix(),
469 prev_version: prev,
470 prev_gen,
471 runs,
472 run_overflow: 0,
473 };
474 let rec = self.write_version(&meta)?;
475 let new_root = self.put_member(root, &lk, Some(rec))?;
476 self.commit(new_root, chunk_root)
477 }
478
479 fn prev_of(&self, lk: &Lookup, path: &str) -> (u32, u64) {
481 if !self.history_for(path) {
482 return (0, 0);
483 }
484 match &lk.meta {
485 Some((s, m)) => (*s, m.generation()),
486 None => (0, 0),
487 }
488 }
489
490 fn derived_version(&mut self, lk: &Lookup, name: &str, labels: &str) -> Result<u32, &'static str> {
492 let (cs, cm) = lk.live().cloned().ok_or("file not found")?;
493 let runs = self.runs_of(&cm)?;
494 let keep = self.history_for(name) && self.history_for(&cm.name());
495 let meta = VersionMeta {
496 flags: 0,
497 name: String::from(name),
498 labels: String::from(labels),
499 size: cm.size(),
500 generation: self.superblock.generation + 1,
501 mtime: now_unix(),
502 prev_version: if keep { cs } else { 0 },
503 prev_gen: if keep { cm.generation() } else { 0 },
504 runs,
505 run_overflow: 0,
506 };
507 self.write_version(&meta)
508 }
509
510 fn tombstone_for(&mut self, lk: &Lookup) -> Result<Option<u32>, &'static str> {
512 let (cs, cm) = lk.live().cloned().ok_or("file not found")?;
513 if !self.history_for(&cm.name()) {
514 return Ok(None);
515 }
516 let meta = VersionMeta {
517 flags: VERSION_DELETED,
518 name: cm.name(),
519 labels: String::from(cm.to_api().get_labels()),
520 size: 0,
521 generation: self.superblock.generation + 1,
522 mtime: now_unix(),
523 prev_version: cs,
524 prev_gen: cm.generation(),
525 runs: Vec::new(),
526 run_overflow: 0,
527 };
528 self.write_version(&meta).map(Some)
529 }
530
531 pub fn read_file(&mut self, filename: &str) -> Option<(FileMetadata, Vec<u8>)> {
532 match self.read_file_checked(filename) {
533 Ok(v) => v,
534 Err(e) => {
535 crate::error!("[SylFS] read_file('{}') failed: {}", filename, e);
536 None
537 }
538 }
539 }
540
541 pub fn read_file_checked(&mut self, filename: &str) -> Result<Option<(FileMetadata, Vec<u8>)>, &'static str> {
543 let path = normalize_path(filename);
544 if let Some(v) = self.volatile_for(&path) {
545 return v.read_file_checked(&path);
546 }
547 let root = self.superblock.root_sector;
548 let lk = self.lookup_in(root, &path)?;
549 match lk.live().cloned() {
550 Some((_, m)) => {
551 let data = self.content_of(&m)?;
552 Ok(Some((m.to_api(), data)))
553 }
554 None => Ok(Self::rom_fallback(&path)),
555 }
556 }
557
558 pub fn delete_file(&mut self, filename: &str) -> Result<(), &'static str> {
560 let path = normalize_path(filename);
561 if let Some(v) = self.volatile_for(&path) {
562 return v.delete_file(&path);
563 }
564 let root = self.superblock.root_sector;
565 let lk = self.lookup_in(root, &path)?;
566 if lk.live().is_none() {
567 if let Some(v) = self.volatile.as_deref_mut() {
568 return v.delete_file(&path);
569 }
570 return Err("delete_file: file not found");
571 }
572 self.maintain_space();
573 let lk = self.lookup_in(self.superblock.root_sector, &path)?;
574 let root = self.superblock.root_sector;
575 self.transact(|fs| {
576 let t = fs.tombstone_for(&lk)?;
577 let new_root = fs.put_member(root, &lk, t)?;
578 let cr = fs.superblock.chunk_root;
579 fs.commit(new_root, cr)
580 })
581 }
582
583 pub fn update_labels(&mut self, filename: &str, new_labels: &str) -> Result<(), &'static str> {
585 let path = normalize_path(filename);
586 if let Some(v) = self.volatile_for(&path) {
587 return v.update_labels(&path, new_labels);
588 }
589 let root = self.superblock.root_sector;
590 let lk = self.lookup_in(root, &path)?;
591 if lk.live().is_none() {
592 if let Some(v) = self.volatile.as_deref_mut() {
593 return v.update_labels(&path, new_labels);
594 }
595 return Err("file not found");
596 }
597 self.maintain_space();
598 let lk = self.lookup_in(self.superblock.root_sector, &path)?;
599 let root = self.superblock.root_sector;
600 self.transact(|fs| {
601 let rec = fs.derived_version(&lk, &path, new_labels)?;
602 let new_root = fs.put_member(root, &lk, Some(rec))?;
603 let cr = fs.superblock.chunk_root;
604 fs.commit(new_root, cr)
605 })
606 }
607
608 pub fn truncate_file(&mut self, filename: &str, new_size: usize) -> Result<(), &'static str> {
610 let path = normalize_path(filename);
611 if let Some(v) = self.volatile_for(&path) {
612 return v.truncate_file(&path, new_size);
613 }
614 let (meta, mut data) = match self.read_file_checked(&path)? {
615 Some(x) => x,
616 None => {
617 if let Some(v) = self.volatile.as_deref_mut() {
618 return v.truncate_file(&path, new_size);
619 }
620 return Err("truncate_file: file not found");
621 }
622 };
623 if data.len() == new_size {
624 return Ok(());
625 }
626 data.resize(new_size, 0);
627 let labels = String::from(meta.get_labels());
628 self.save_file(&path, &data, &labels)
629 }
630
631 pub fn rename_file(&mut self, old_name: &str, new_name: &str) -> Result<(), &'static str> {
634 let old = normalize_path(old_name);
635 let new = normalize_path(new_name);
636 if old == new {
637 return Ok(());
638 }
639 if self.volatile.is_some() && storage_policy::is_disposable(&old) != storage_policy::is_disposable(&new) {
640 return Err("rename_file: cross-device (temporary and persistent storage)");
641 }
642 if let Some(v) = self.volatile_for(&old) {
643 return v.rename_file(&old, &new);
644 }
645 let root = self.superblock.root_sector;
646 let src = self.lookup_in(root, &old)?;
647 let Some((_, src_meta)) = src.live().cloned() else {
648 if let Some(v) = self.volatile.as_deref_mut() {
649 return v.rename_file(&old, &new);
650 }
651 return Err("rename_file: source file not found");
652 };
653 let dst = self.lookup_in(root, &new)?;
654 if dst.live().is_some() {
655 return Err("destination file already exists");
656 }
657 let labels = String::from(src_meta.to_api().get_labels());
658 self.maintain_space();
659 let root = self.superblock.root_sector;
660 let src = self.lookup_in(root, &old)?;
661 let dst = self.lookup_in(root, &new)?;
662 if src.live().is_none() {
663 return Err("rename_file: source file not found");
664 }
665 self.transact(|fs| {
666 let rec = fs.derived_version(&src, &new, &labels)?;
667 let t = fs.tombstone_for(&src)?;
668 let new_root = if src.key == dst.key {
669 let mut members = src.members.clone();
671 if let Some(i) = src.index {
672 match t {
673 Some(ts) => members[i] = ts,
674 None => {
675 members.remove(i);
676 }
677 }
678 }
679 match dst.index.and_then(|i| dst.members.get(i).copied()) {
680 Some(old_dst) => match members.iter().position(|&m| m == old_dst) {
681 Some(p) => members[p] = rec,
682 None => members.push(rec),
683 },
684 None => members.push(rec),
685 }
686 let value = fs.value_for_members(&members)?;
687 fs.index_insert(root, &src.key, value)?
688 } else {
689 let r1 = fs.put_member(root, &dst, Some(rec))?;
690 fs.put_member(r1, &src, t)?
691 };
692 let cr = fs.superblock.chunk_root;
693 fs.commit(new_root, cr)
694 })
695 }
696
697 pub fn list_files(&mut self) -> Vec<FileMetadata> {
699 let mut out = self.list_files_here();
700 if let Some(v) = self.volatile.as_deref_mut() {
701 out.extend(v.list_files_here());
702 }
703 out
704 }
705
706 fn list_files_here(&mut self) -> Vec<FileMetadata> {
707 self.list_index().files.clone()
708 }
709
710 pub(super) fn list_in(&mut self, root: u32) -> Vec<FileMetadata> {
711 let mut out = Vec::new();
712 for (_, value) in self.index_entries(root) {
713 let Ok(members) = self.members_of(value) else { continue };
714 for m in members {
715 if let Ok(am) = self.read_meta(m) {
716 if !am.is_deleted() {
717 out.push(am.to_api());
718 }
719 }
720 }
721 }
722 out
723 }
724
725 pub fn stat_file(&mut self, filename: &str) -> Result<FileStat, &'static str> {
726 let path = normalize_path(filename);
727 if let Some(v) = self.volatile_for(&path) {
728 return v.stat_file(&path);
729 }
730 let root = self.superblock.root_sector;
731 let lk = self.lookup_in(root, &path)?;
732 let Some((_, m)) = lk.live().cloned() else {
733 if let Some(v) = self.volatile.as_deref_mut() {
734 return v.stat_file(&path);
735 }
736 return Err("stat_file: file not found");
737 };
738 let api = m.to_api();
739 let (count, sectors, overflow) = match &m {
740 AnyMeta::V1(v1) => {
741 let ex = self.collect_extents(v1).unwrap_or_default();
742 (v1.extent_count, ex.iter().map(|e| e.count).sum::<u64>(), v1.overflow_sector != 0)
743 }
744 AnyMeta::V2(v2) => (
745 v2.runs.len() as u32,
746 v2.runs.iter().map(|r| u64::from(r.sectors())).sum(),
747 v2.run_overflow != 0,
748 ),
749 };
750 Ok(FileStat {
751 filename: String::from(api.get_filename()),
752 size: api.size,
753 labels: String::from(api.get_labels()),
754 extent_count: count,
755 sector_count: sectors,
756 has_overflow: overflow,
757 })
758 }
759
760 pub(crate) fn find_in_collision_chain(
762 &mut self,
763 start: u32,
764 filename: &str,
765 ) -> Result<Option<(u32, FileMetadata)>, &'static str> {
766 for m in self.members_of(start)? {
767 let am = self.read_meta(m)?;
768 if !am.is_deleted() && am.name() == filename {
769 return Ok(Some((m, am.to_api())));
770 }
771 }
772 Ok(None)
773 }
774
775 pub fn list_versions(&mut self, filename: &str) -> Result<Vec<VersionInfo>, &'static str> {
779 let path = normalize_path(filename);
780 if let Some(v) = self.volatile_for(&path) {
781 return v.list_versions(&path);
782 }
783 let horizon = self.superblock.last_snap_gen;
784 let root = self.superblock.root_sector;
785 let mut out: Vec<VersionInfo> = Vec::new();
786 let lk = self.lookup_in(root, &path)?;
787 if let Some((mut s, mut m)) = lk.meta.clone() {
788 loop {
789 out.push(Self::info_of(s, &m));
790 let AnyMeta::V2(v2) = &m else { break };
791 if !self.keep_history() || v2.prev_version == 0 || v2.prev_gen <= horizon {
792 break;
793 }
794 s = v2.prev_version;
795 m = self.read_meta(s)?;
796 }
797 }
798 for snap in self.list_snapshots()? {
799 let lk = self.lookup_in(snap.root, &path)?;
800 if let Some((s, m)) = lk.meta {
801 if !out.iter().any(|v| v.record == s) {
802 out.push(Self::info_of(s, &m));
803 }
804 }
805 }
806 out.sort_by_key(|v| core::cmp::Reverse(v.generation));
807 Ok(out)
808 }
809
810 fn info_of(record: u32, m: &AnyMeta) -> VersionInfo {
811 let api = m.to_api();
812 VersionInfo {
813 generation: m.generation(),
814 mtime: match m {
815 AnyMeta::V2(v) => v.mtime,
816 AnyMeta::V1(_) => 0,
817 },
818 size: api.size,
819 deleted: m.is_deleted(),
820 labels: String::from(api.get_labels()),
821 record,
822 }
823 }
824
825 pub fn read_version(
827 &mut self,
828 filename: &str,
829 generation: u64,
830 ) -> Result<Option<(FileMetadata, Vec<u8>)>, &'static str> {
831 let path = normalize_path(filename);
832 if let Some(v) = self.volatile_for(&path) {
833 return v.read_version(&path, generation);
834 }
835 let Some(info) = self.list_versions(&path)?.into_iter().find(|v| v.generation == generation) else {
836 return Ok(None);
837 };
838 if info.deleted {
839 return Ok(None);
840 }
841 let m = self.read_meta(info.record)?;
842 let data = self.content_of(&m)?;
843 Ok(Some((m.to_api(), data)))
844 }
845
846 pub fn restore_version(&mut self, filename: &str, generation: u64) -> Result<(), &'static str> {
848 let path = normalize_path(filename);
849 let (meta, data) = self.read_version(&path, generation)?.ok_or("restore_version: version not found")?;
850 let labels = String::from(meta.get_labels());
851 self.save_file(&path, &data, &labels)
852 }
853
854 pub fn list_snapshots(&mut self) -> Result<Vec<SnapshotInfo>, &'static str> {
858 let mut out = Vec::new();
859 for rec in self.snapshot_records()? {
860 let b = self.read_record(rec)?;
861 let n = (get_u32(&b, 8) as usize).min(SNAPS_PER_SECTOR);
862 for i in 0..n {
863 let o = 12 + i * SNAP_REC;
864 out.push(SnapshotInfo {
865 generation: get_u64(&b, o),
866 root: get_u32(&b, o + 8),
867 pinned: get_u32(&b, o + 12) & SNAP_PINNED != 0,
868 time: get_u64(&b, o + 16),
869 name: get_str(&b[o + 24..o + 56]),
870 });
871 }
872 }
873 Ok(out)
874 }
875
876 fn snapshot_records(&mut self) -> Result<Vec<u32>, &'static str> {
878 let mut out = Vec::new();
879 let mut next = self.superblock.snap_table;
880 while next != 0 {
881 if out.len() > 4096 {
882 return Err("snapshot table loop");
883 }
884 let b = self.read_record(next)?;
885 if &b[0..4] != SNAP_MAGIC {
886 return Err("snapshot table corrupted");
887 }
888 out.push(next);
889 next = get_u32(&b, 4);
890 }
891 Ok(out)
892 }
893
894 fn commit_snapshots(&mut self, snaps: &[SnapshotInfo], horizon: u64) -> Result<(), &'static str> {
897 let keep = self.pending.len();
898 let mut next = 0u32;
899 for part in snaps.chunks(SNAPS_PER_SECTOR).rev() {
900 let mut b = [0u8; REC];
901 b[0..4].copy_from_slice(SNAP_MAGIC);
902 put_u32(&mut b, 4, next);
903 put_u32(&mut b, 8, part.len() as u32);
904 for (i, sn) in part.iter().enumerate() {
905 let o = 12 + i * SNAP_REC;
906 put_u64(&mut b, o, sn.generation);
907 put_u32(&mut b, o + 8, sn.root);
908 put_u32(&mut b, o + 12, if sn.pinned { SNAP_PINNED } else { 0 });
909 put_u64(&mut b, o + 16, sn.time);
910 let nm = fit(&sn.name, 31).as_bytes();
911 b[o + 24..o + 24 + nm.len()].copy_from_slice(nm);
912 }
913 match self.write_record(&b) {
914 Ok(s) => next = s,
915 Err(e) => {
916 self.abort_from(keep);
917 return Err(e);
918 }
919 }
920 }
921 let mut sb = self.superblock;
922 sb.snap_table = next;
923 sb.last_snap_gen = sb.last_snap_gen.max(horizon);
924 self.commit_superblock(sb, keep)
926 }
927
928 pub fn max_pins(&self) -> usize {
930 let bytes = self.device.total_usable_sectors() as u64 * DATA_SIZE_PER_SECTOR as u64;
931 ((bytes * 8 / (1u64 << 30)) as usize).clamp(4, 64)
932 }
933
934 pub fn create_snapshot(&mut self, name: &str) -> Result<u64, &'static str> {
937 let mut snaps = self.list_snapshots()?;
938 let gen = self.superblock.generation;
939 if snaps.last().map(|s| s.generation) == Some(gen) {
940 return Ok(gen);
941 }
942 snaps.push(SnapshotInfo {
943 generation: gen,
944 time: now_unix(),
945 name: String::from(name),
946 pinned: false,
947 root: self.superblock.root_sector,
948 });
949 let max = self.superblock.max_snapshots.max(1) as usize;
950 while snaps.iter().filter(|s| !s.pinned).count() > max {
951 match snaps.iter().position(|s| !s.pinned) {
952 Some(i) => {
953 snaps.remove(i);
954 }
955 None => break,
956 }
957 }
958 self.commit_snapshots(&snaps, gen)?;
959 Ok(gen)
960 }
961
962 pub fn pin_snapshot(&mut self, generation: u64, pinned: bool) -> Result<(), &'static str> {
964 let mut snaps = self.list_snapshots()?;
965 let i = snaps.iter().position(|s| s.generation == generation).ok_or("snapshot not found")?;
966 if snaps[i].pinned == pinned {
967 return Ok(());
968 }
969 if pinned && snaps.iter().filter(|s| s.pinned).count() >= self.max_pins() {
970 return Err("too many pinned snapshots");
971 }
972 snaps[i].pinned = pinned;
973 let h = self.superblock.last_snap_gen;
974 self.commit_snapshots(&snaps, h)
975 }
976
977 pub fn delete_snapshot(&mut self, generation: u64) -> Result<(), &'static str> {
979 let mut snaps = self.list_snapshots()?;
980 let i = snaps.iter().position(|s| s.generation == generation).ok_or("snapshot not found")?;
981 snaps.remove(i);
982 let h = self.superblock.last_snap_gen;
983 self.commit_snapshots(&snaps, h)
984 }
985
986 fn snapshot(&mut self, generation: u64) -> Result<SnapshotInfo, &'static str> {
987 self.list_snapshots()?
988 .into_iter()
989 .find(|s| s.generation == generation)
990 .ok_or("snapshot not found")
991 }
992
993 pub fn read_file_at(
995 &mut self,
996 generation: u64,
997 filename: &str,
998 ) -> Result<Option<(FileMetadata, Vec<u8>)>, &'static str> {
999 let path = normalize_path(filename);
1000 let snap = self.snapshot(generation)?;
1001 let lk = self.lookup_in(snap.root, &path)?;
1002 match lk.live().cloned() {
1003 Some((_, m)) => {
1004 let data = self.content_of(&m)?;
1005 Ok(Some((m.to_api(), data)))
1006 }
1007 None => Ok(None),
1008 }
1009 }
1010
1011 pub fn list_files_at(&mut self, generation: u64) -> Result<Vec<FileMetadata>, &'static str> {
1013 let snap = self.snapshot(generation)?;
1014 Ok(self.list_in(snap.root))
1015 }
1016
1017 fn mark_live(&mut self) -> (Marks, Census) {
1021 let mut mk = self.new_marks();
1022 let mut census = Census::default();
1023 let mut done: BTreeSet<(u32, bool)> = BTreeSet::new();
1024 let root = self.superblock.root_sector;
1025 census.files = self.mark_names(root, true, &mut mk, &mut done, &mut census);
1026 match self.snapshot_records() {
1027 Ok(recs) => {
1028 for r in recs {
1029 mk.mark(u64::from(r));
1030 }
1031 }
1032 Err(_) => mk.corrupted += 1,
1033 }
1034 if let Ok(snaps) = self.list_snapshots() {
1035 for sn in snaps {
1036 let mut c = Census::default();
1037 self.mark_names(sn.root, false, &mut mk, &mut done, &mut c);
1038 }
1039 }
1040 (mk, census)
1041 }
1042
1043 fn mark_names(
1045 &mut self,
1046 root: u32,
1047 history: bool,
1048 mk: &mut Marks,
1049 done: &mut BTreeSet<(u32, bool)>,
1050 census: &mut Census,
1051 ) -> u64 {
1052 let nodes = self.index_nodes(root);
1053 census.nodes = nodes.len() as u64;
1054 for n in nodes {
1055 mk.mark(u64::from(n));
1056 }
1057 let mut live = 0u64;
1058 for (_, value) in self.index_entries(root) {
1059 let Ok(b) = self.read_record(value) else {
1060 mk.corrupted += 1;
1061 continue;
1062 };
1063 if &b[0..4] == BUCKET_MAGIC {
1064 mk.mark(u64::from(value));
1065 let n = (get_u32(&b, 4) as usize).min(BUCKET_CAP);
1066 for i in 0..n {
1067 live += self.mark_version(get_u32(&b, 8 + i * 4), history, false, mk, done, census);
1068 }
1069 } else {
1070 live += self.mark_version(value, history, true, mk, done, census);
1071 }
1072 }
1073 live
1074 }
1075
1076 fn mark_version(
1079 &mut self,
1080 record: u32,
1081 history: bool,
1082 legacy_chain: bool,
1083 mk: &mut Marks,
1084 done: &mut BTreeSet<(u32, bool)>,
1085 census: &mut Census,
1086 ) -> u64 {
1087 let horizon = self.superblock.last_snap_gen;
1088 let keep = self.keep_history();
1089 let mut live = 0u64;
1090 let mut cur = record;
1091 let mut first = true;
1092 while cur != 0 {
1093 if !done.insert((cur, history)) {
1094 break;
1095 }
1096 mk.mark(u64::from(cur));
1097 let am = match self.read_meta(cur) {
1098 Ok(m) => m,
1099 Err(_) => {
1100 mk.corrupted += 1;
1101 break;
1102 }
1103 };
1104 match am {
1105 AnyMeta::V2(v) => {
1106 if first && !v.is_deleted() {
1107 live += 1;
1108 }
1109 for r in self.overflow_records(v.run_overflow) {
1110 mk.mark(u64::from(r));
1111 }
1112 census.runs += v.runs.len() as u64;
1113 mk.mark_runs(&v.runs);
1114 first = false;
1115 if history && keep && v.prev_version != 0 && v.prev_gen > horizon {
1116 cur = v.prev_version;
1117 continue;
1118 }
1119 break;
1120 }
1121 AnyMeta::V1(m) => {
1122 if m.filename[0] != 0 {
1123 if first || legacy_chain {
1124 live += 1;
1125 }
1126 match self.runs_of_v1(&m) {
1127 Ok(runs) => {
1128 census.runs += runs.len() as u64;
1129 mk.mark_runs(&runs);
1130 }
1131 Err(_) => mk.corrupted += 1,
1132 }
1133 let mut ov = m.overflow_sector;
1134 let mut g = 0;
1135 while ov != 0 && g < 4096 {
1136 g += 1;
1137 mk.mark(ov);
1138 match self.read_record(ov as u32) {
1139 Ok(b) => ov = get_u64(&b, 0),
1140 Err(_) => break,
1141 }
1142 }
1143 }
1144 first = false;
1145 if legacy_chain && m.collision_next_sector != 0 {
1146 cur = m.collision_next_sector as u32;
1147 continue;
1148 }
1149 break;
1150 }
1151 }
1152 }
1153 live
1154 }
1155
1156 pub(super) fn reclaim_for_allocation(&mut self) -> u64 {
1160 let (mk, _) = self.mark_live();
1161 let free = mk.corrupted == 0;
1162 let mut freed = self.sweep(&mk, free).map(|(f, _)| f).unwrap_or(0);
1163 if freed == 0 && self.keep_history() {
1164 let latest = self.list_snapshots().ok().and_then(|s| s.last().map(|x| x.generation));
1165 if latest != Some(self.superblock.generation) && self.create_snapshot("auto").is_ok() {
1166 freed = self.sweep_live();
1167 }
1168 while freed == 0 && self.drop_oldest_snapshot() {
1170 freed = self.sweep_live();
1171 }
1172 }
1173 freed
1174 }
1175
1176 fn sweep_live(&mut self) -> u64 {
1177 let (mk, _) = self.mark_live();
1178 let free = mk.corrupted == 0;
1179 self.sweep(&mk, free).map(|(f, _)| f).unwrap_or(0)
1180 }
1181
1182 fn drop_oldest_snapshot(&mut self) -> bool {
1184 let Ok(mut snaps) = self.list_snapshots() else { return false };
1185 let last = snaps.len().saturating_sub(1);
1186 let Some(i) = snaps.iter().position(|s| !s.pinned).filter(|&i| i < last) else { return false };
1187 snaps.remove(i);
1188 let h = self.superblock.last_snap_gen;
1189 self.commit_snapshots(&snaps, h).is_ok()
1190 }
1191
1192 fn maintain_space(&mut self) {
1195 if !self.keep_history() || self.in_reclaim {
1196 return;
1197 }
1198 let low = (self.device.total_usable_sectors() as u64 / 16).max(64).min(self.device.total_usable_sectors() as u64 / 2);
1199 if self.free_sectors() >= low {
1200 return;
1201 }
1202 self.in_reclaim = true;
1203 let _ = self.create_snapshot("auto");
1204 let _ = self.collect_garbage();
1205 while self.free_sectors() < low && self.drop_oldest_snapshot() {
1206 let _ = self.collect_garbage();
1207 }
1208 self.in_reclaim = false;
1209 }
1210
1211 pub fn collect_garbage(&mut self) -> Result<GcReport, &'static str> {
1214 let mut report = GcReport::default();
1215 let (mk, _) = self.mark_live();
1216 if mk.corrupted == 0 {
1217 if let Err(e) = self.compact(&mk, &mut report) {
1218 crate::warn!("[SylFS] 回収: 索引の作り直しをやめた: {}", e);
1220 self.abort();
1221 }
1222 }
1223 let (mk, _) = self.mark_live();
1224 let free = mk.corrupted == 0;
1225 let (freed, fixed) = self.sweep(&mk, free)?;
1226 report.freed = freed;
1227 report.fixed = fixed;
1228 if freed > 0 || fixed > 0 {
1229 crate::warn!(
1230 "[SylFS] 回収: 解放 {} 個・使用中に直した {} 個・削除の版を外した {} 個・索引の項を外した {} 個",
1231 freed,
1232 fixed,
1233 report.tombstones_dropped,
1234 report.index_entries_dropped
1235 );
1236 }
1237 Ok(report)
1238 }
1239
1240 fn compact(&mut self, mk: &Marks, report: &mut GcReport) -> Result<(), &'static str> {
1242 {
1243 let horizon = self.superblock.last_snap_gen;
1244 let mut root = self.superblock.root_sector;
1245 let mut changed = false;
1246 let entries = self.index_entries(root);
1249 let mut rebuilt: Vec<([u8; 16], u32)> = Vec::with_capacity(entries.len());
1250 for (key, value) in entries {
1251 let members = self.members_of(value)?;
1252 let mut keep = Vec::new();
1253 for m in &members {
1254 match self.read_meta(*m)? {
1255 AnyMeta::V2(v) if v.is_deleted() && v.generation <= horizon => {
1256 report.tombstones_dropped += 1;
1257 }
1258 _ => keep.push(*m),
1259 }
1260 }
1261 if keep.len() != members.len() {
1262 let v = self.value_for_members(&keep)?;
1263 rebuilt.push((key, v));
1264 changed = true;
1265 } else {
1266 rebuilt.push((key, value));
1267 }
1268 }
1269 if changed {
1270 root = self.index_build(rebuilt)?;
1271 }
1272 let mut chunk_root = self.superblock.chunk_root;
1273 if let Some((r, n)) = self.prune_chunk_index(mk)? {
1274 chunk_root = r;
1275 report.index_entries_dropped = n;
1276 changed = true;
1277 }
1278 if changed {
1279 self.commit(root, chunk_root)?;
1280 }
1281 }
1282 Ok(())
1283 }
1284
1285 pub fn recover_after_power_loss(&mut self) -> Result<(u64, u64), &'static str> {
1288 let r = self.collect_garbage()?;
1289 Ok((r.freed, r.fixed))
1290 }
1291
1292 pub fn fsck(&mut self) -> Result<FsckReport, &'static str> {
1294 let (mk, census) = self.mark_live();
1295 let (used, leaked, unalloc) = self.compare_bitmap(&mk);
1296 Ok(FsckReport {
1297 total_sectors: self.device.total_usable_sectors() as u64,
1298 used_sectors: used,
1299 file_count: census.files,
1300 btree_node_count: census.nodes,
1301 extent_count: census.runs,
1302 corrupted_sectors: mk.corrupted,
1303 leaked_sectors: leaked,
1304 unallocated_refs: unalloc,
1305 double_refs: 0,
1306 is_healthy: mk.corrupted == 0 && unalloc == 0,
1307 })
1308 }
1309}