vfat-rs 0.1.1

A no_std-compatible FAT32/VFAT filesystem implementation in Rust for custom kernels
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
use alloc::sync::Arc;
use alloc::vec::Vec;

use crate::error::{self, Result};
use crate::fat_table::{FatEntry, get_params};
use crate::{ArcMutex, CachedPartition, ClusterId, fat_table};
use snafu::ensure;

/// Maximum cluster chain length to prevent infinite loops in corrupted filesystems.
const MAX_CLUSTER_CHAIN_LENGTH: u32 = 1_048_576;

/// Delete a cluster chain starting from `start`.
///
/// For crash safety, the chain is collected first and then deleted in reverse
/// order (last cluster to first). If a power failure interrupts the operation,
/// the head of the chain still points to valid (not-yet-freed) clusters,
/// avoiding orphaned cluster chains. A filesystem check tool can reclaim the
/// partially-freed tail.
pub(crate) fn delete_cluster_chain(
    start: ClusterId,
    device: ArcMutex<CachedPartition>,
) -> Result<()> {
    // Phase 1: collect the full chain.
    let mut chain = Vec::new();
    let mut current = start;
    loop {
        ensure!(
            chain.len() < MAX_CLUSTER_CHAIN_LENGTH as usize,
            error::FilesystemCorruptedSnafu {
                reason: "Cluster chain exceeds maximum length (possible circular reference)"
            }
        );
        chain.push(current);
        match fat_table::next_cluster(current, device.clone())? {
            Some(next) => current = next,
            None => break,
        }
    }

    // Phase 2: delete from last to first for crash safety.
    const DELETED_ENTRY: FatEntry = FatEntry::Unused;
    for &cluster in chain.iter().rev() {
        set_fat_entry(device.clone(), cluster, DELETED_ENTRY)?;
    }

    Ok(())
}

/// Truncate a cluster chain, keeping `keep_count` clusters and freeing the rest.
///
/// If `keep_count` is 0, the entire chain is freed (equivalent to `delete_cluster_chain`).
/// Otherwise, the `keep_count`-th cluster is marked as `LastCluster` and all
/// subsequent clusters are freed in reverse order for crash safety.
pub(crate) fn truncate_cluster_chain(
    start: ClusterId,
    keep_count: u32,
    device: ArcMutex<CachedPartition>,
) -> Result<()> {
    if keep_count == 0 {
        return delete_cluster_chain(start, device);
    }

    // Walk the chain to find the last cluster to keep and collect the tail to free.
    let mut current = start;
    for _ in 1..keep_count {
        match fat_table::next_cluster(current, device.clone())? {
            Some(next) => current = next,
            None => return Ok(()), // Chain is already shorter than keep_count
        }
    }
    let last_keep = current;

    // Collect the tail (clusters after last_keep)
    let mut tail = Vec::new();
    let mut cursor = match fat_table::next_cluster(last_keep, device.clone())? {
        Some(next) => next,
        None => return Ok(()), // Already at end of chain, nothing to free
    };
    loop {
        ensure!(
            tail.len() < MAX_CLUSTER_CHAIN_LENGTH as usize,
            error::FilesystemCorruptedSnafu {
                reason: "Cluster chain exceeds maximum length (possible circular reference)"
            }
        );
        tail.push(cursor);
        match fat_table::next_cluster(cursor, device.clone())? {
            Some(next) => cursor = next,
            None => break,
        }
    }

    // Mark the last kept cluster as end-of-chain
    set_fat_entry(device.clone(), last_keep, FatEntry::LastCluster(0x0FFFFFFF))?;

    // Free the tail in reverse order for crash safety
    for &cluster in tail.iter().rev() {
        set_fat_entry(device.clone(), cluster, FatEntry::Unused)?;
    }

    Ok(())
}

pub(crate) fn set_fat_entry(
    device: Arc<CachedPartition>,
    cluster_id: ClusterId,
    entry: FatEntry,
) -> Result<()> {
    let (sector, offset) = get_params(&device, cluster_id)?;
    let entry_bytes = entry.as_buff();

    // Write to all FAT copies for redundancy (FAT mirroring)
    // Typically fat_amount is 2, but FAT32 spec allows up to 4 copies
    for fat_num in 0..device.fat_amount {
        let fat_sector = sector + (fat_num as u32 * device.sectors_per_fat);
        device
            .clone()
            .write_sector_offset(fat_sector, offset, &entry_bytes)?;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fat_table::FAT_ENTRY_SIZE;
    use crate::{BlockDevice, CachedPartition, ClusterId, SectorId};
    use alloc::sync::Arc;
    use alloc::vec::Vec;
    use spin::mutex::SpinMutex;

    struct WriteTrackingDevice {
        writes: Arc<SpinMutex<Vec<(SectorId, usize, Vec<u8>)>>>,
    }

    impl WriteTrackingDevice {
        fn new(writes: Arc<SpinMutex<Vec<(SectorId, usize, Vec<u8>)>>>) -> Self {
            Self { writes }
        }
    }

    impl BlockDevice for WriteTrackingDevice {
        fn read_sector_offset(
            &mut self,
            _sector: SectorId,
            _offset: usize,
            buf: &mut [u8],
        ) -> Result<usize> {
            // Return dummy data for FAT entry reads
            buf.fill(0xFF);
            Ok(4) // FAT entry size
        }

        fn write_sector_offset(
            &mut self,
            sector: SectorId,
            offset: usize,
            buf: &[u8],
        ) -> Result<usize> {
            self.writes.lock().push((sector, offset, buf.to_vec()));
            Ok(buf.len())
        }

        fn get_canonical_name() -> &'static str
        where
            Self: Sized,
        {
            "WriteTrackingDevice"
        }
    }

    #[test]
    fn test_fat_mirroring_two_copies() {
        let writes = Arc::new(SpinMutex::new(Vec::new()));
        let device = WriteTrackingDevice::new(writes.clone());

        let cached = Arc::new(CachedPartition::new(
            device,
            512,
            SectorId(100), // FAT starts at sector 100
            1,
            SectorId(300),
            2,  // 2 FAT copies
            50, // 50 sectors per FAT
        ));

        let entry = FatEntry::LastCluster(0x0FFFFFFF);
        set_fat_entry(cached.clone(), ClusterId::new(5), entry).unwrap();

        // Check writes through the shared Arc
        let write_log = writes.lock();
        assert_eq!(write_log.len(), 2, "Should write to 2 FAT copies");
        assert_eq!(
            write_log[0].0,
            SectorId(100),
            "First write should be to FAT #1 at sector 100"
        );
        assert_eq!(
            write_log[1].0,
            SectorId(150),
            "Second write should be to FAT #2 at sector 150 (100 + 50)"
        );
        assert_eq!(
            write_log[0].2, write_log[1].2,
            "Both writes should contain identical data"
        );
        assert_eq!(write_log[0].2.len(), 4, "FAT entry should be 4 bytes");
    }

    #[test]
    fn test_fat_mirroring_four_copies() {
        let writes = Arc::new(SpinMutex::new(Vec::new()));
        let device = WriteTrackingDevice::new(writes.clone());

        let cached = Arc::new(CachedPartition::new(
            device,
            512,
            SectorId(32), // FAT starts at sector 32
            4,
            SectorId(500),
            4,   // 4 FAT copies (maximum per spec)
            100, // 100 sectors per FAT
        ));

        let entry = FatEntry::from_chain(ClusterId::new(10));
        set_fat_entry(cached.clone(), ClusterId::new(3), entry).unwrap();

        let write_log = writes.lock();
        assert_eq!(write_log.len(), 4, "Should write to 4 FAT copies");
        assert_eq!(write_log[0].0, SectorId(32), "FAT #1 at sector 32");
        assert_eq!(
            write_log[1].0,
            SectorId(132),
            "FAT #2 at sector 132 (32 + 100)"
        );
        assert_eq!(
            write_log[2].0,
            SectorId(232),
            "FAT #3 at sector 232 (32 + 200)"
        );
        assert_eq!(
            write_log[3].0,
            SectorId(332),
            "FAT #4 at sector 332 (32 + 300)"
        );

        // All writes should be identical
        for i in 1..write_log.len() {
            assert_eq!(
                write_log[0].2, write_log[i].2,
                "All FAT copies should have identical data"
            );
        }
    }

    /// A block device backed by an in-memory FAT sector that supports
    /// simulating a crash after a configurable number of writes.
    struct CrashSimDevice {
        /// Raw FAT sector data. One sector of 512 bytes = 128 FAT entries.
        fat_sector: Arc<SpinMutex<[u8; 512]>>,
        /// Number of writes remaining before the device "crashes".
        /// None means no crash simulation.
        writes_before_crash: Arc<SpinMutex<Option<usize>>>,
    }

    impl CrashSimDevice {
        fn new(
            fat_sector: Arc<SpinMutex<[u8; 512]>>,
            writes_before_crash: Arc<SpinMutex<Option<usize>>>,
        ) -> Self {
            Self {
                fat_sector,
                writes_before_crash,
            }
        }

        /// Write a FAT entry directly into the backing store (bypasses crash limit).
        fn set_entry(fat_sector: &Arc<SpinMutex<[u8; 512]>>, cluster_id: u32, entry: FatEntry) {
            let offset = cluster_id as usize * FAT_ENTRY_SIZE;
            let bytes = entry.as_buff();
            fat_sector.lock()[offset..offset + FAT_ENTRY_SIZE].copy_from_slice(&bytes);
        }

        /// Read a FAT entry directly from the backing store.
        fn get_entry(fat_sector: &Arc<SpinMutex<[u8; 512]>>, cluster_id: u32) -> FatEntry {
            let offset = cluster_id as usize * FAT_ENTRY_SIZE;
            let data = fat_sector.lock();
            let mut buf = [0u8; FAT_ENTRY_SIZE];
            buf.copy_from_slice(&data[offset..offset + FAT_ENTRY_SIZE]);
            FatEntry::from(buf)
        }
    }

    impl BlockDevice for CrashSimDevice {
        fn read_sector_offset(
            &mut self,
            _sector: SectorId,
            offset: usize,
            buf: &mut [u8],
        ) -> Result<usize> {
            let data = self.fat_sector.lock();
            let end = core::cmp::min(offset + buf.len(), data.len());
            let len = end - offset;
            buf[..len].copy_from_slice(&data[offset..end]);
            Ok(len)
        }

        fn write_sector_offset(
            &mut self,
            _sector: SectorId,
            offset: usize,
            buf: &[u8],
        ) -> Result<usize> {
            let mut limit = self.writes_before_crash.lock();
            if let Some(ref mut remaining) = *limit {
                if *remaining == 0 {
                    return Err(crate::io::ErrorKind::Other.into());
                }
                *remaining -= 1;
            }
            let mut data = self.fat_sector.lock();
            let end = offset + buf.len();
            data[offset..end].copy_from_slice(buf);
            Ok(buf.len())
        }

        fn get_canonical_name() -> &'static str
        where
            Self: Sized,
        {
            "CrashSimDevice"
        }
    }

    /// Build a chain 2 → 3 → 4 → 5 → 6 (last), then simulate a crash
    /// after `crash_after` FAT writes during deletion. Verify the remaining
    /// chain from cluster 2 is still valid: every reachable cluster must be
    /// either a DataCluster pointing to the next or a LastCluster.
    fn crash_during_delete_helper(crash_after: usize) {
        let fat_sector = Arc::new(SpinMutex::new([0u8; 512]));
        let writes_before_crash = Arc::new(SpinMutex::new(None));

        // Build chain: 2→3→4→5→6(last)
        CrashSimDevice::set_entry(&fat_sector, 2, FatEntry::DataCluster(3));
        CrashSimDevice::set_entry(&fat_sector, 3, FatEntry::DataCluster(4));
        CrashSimDevice::set_entry(&fat_sector, 4, FatEntry::DataCluster(5));
        CrashSimDevice::set_entry(&fat_sector, 5, FatEntry::DataCluster(6));
        CrashSimDevice::set_entry(&fat_sector, 6, FatEntry::LastCluster(0x0FFFFFFF));

        let device = CrashSimDevice::new(fat_sector.clone(), writes_before_crash.clone());

        // 1 FAT copy so each cluster deletion = 1 write
        let cached = Arc::new(CachedPartition::new(
            device,
            512,
            SectorId(0), // FAT at sector 0 (matches our single sector)
            1,
            SectorId(100),
            1, // 1 FAT copy
            1, // 1 sector per FAT
        ));

        // Arm the crash: allow only `crash_after` writes
        *writes_before_crash.lock() = Some(crash_after);

        // Deletion will partially succeed then fail
        let _ = delete_cluster_chain(ClusterId::new(2), cached);

        // Verify: walk from cluster 2, every reachable entry must be valid
        let mut current = 2u32;
        let mut visited = 0;
        loop {
            let entry = CrashSimDevice::get_entry(&fat_sector, current);
            match entry {
                FatEntry::DataCluster(next) => {
                    assert!(
                        next >= 2 && next <= 6,
                        "Cluster {} points to invalid cluster {}",
                        current,
                        next
                    );
                    current = next;
                    visited += 1;
                    assert!(visited <= 5, "Infinite loop detected in chain");
                }
                FatEntry::LastCluster(_) => break, // valid chain end
                FatEntry::Unused => break,         // reached freed portion (head was freed)
                other => panic!("Cluster {} has unexpected FAT entry {:?}", current, other),
            }
        }
    }

    #[test]
    fn test_crash_safety_delete_no_writes() {
        // Crash immediately: no clusters freed, full chain intact
        crash_during_delete_helper(0);
    }

    #[test]
    fn test_crash_safety_delete_partial() {
        // Crash after 1-4 writes: chain should still be traversable
        for crash_after in 1..=4 {
            crash_during_delete_helper(crash_after);
        }
    }

    #[test]
    fn test_crash_safety_delete_complete() {
        // All 5 writes succeed: full chain deleted
        crash_during_delete_helper(5);
    }

    #[test]
    fn test_truncate_chain_keep_two() {
        // Chain: 2→3→4→5→6(last). Keep 2 clusters → 2→3(last), free 4,5,6.
        let fat_sector = Arc::new(SpinMutex::new([0u8; 512]));
        let writes_before_crash = Arc::new(SpinMutex::new(None));

        CrashSimDevice::set_entry(&fat_sector, 2, FatEntry::DataCluster(3));
        CrashSimDevice::set_entry(&fat_sector, 3, FatEntry::DataCluster(4));
        CrashSimDevice::set_entry(&fat_sector, 4, FatEntry::DataCluster(5));
        CrashSimDevice::set_entry(&fat_sector, 5, FatEntry::DataCluster(6));
        CrashSimDevice::set_entry(&fat_sector, 6, FatEntry::LastCluster(0x0FFFFFFF));

        let device = CrashSimDevice::new(fat_sector.clone(), writes_before_crash.clone());
        let cached = Arc::new(CachedPartition::new(
            device,
            512,
            SectorId(0),
            1,
            SectorId(100),
            1,
            1,
        ));

        truncate_cluster_chain(ClusterId::new(2), 2, cached).unwrap();

        // Cluster 2 → 3(last)
        assert!(matches!(
            CrashSimDevice::get_entry(&fat_sector, 2),
            FatEntry::DataCluster(3)
        ));
        assert!(matches!(
            CrashSimDevice::get_entry(&fat_sector, 3),
            FatEntry::LastCluster(_)
        ));
        // Clusters 4,5,6 freed
        assert!(matches!(
            CrashSimDevice::get_entry(&fat_sector, 4),
            FatEntry::Unused
        ));
        assert!(matches!(
            CrashSimDevice::get_entry(&fat_sector, 5),
            FatEntry::Unused
        ));
        assert!(matches!(
            CrashSimDevice::get_entry(&fat_sector, 6),
            FatEntry::Unused
        ));
    }

    #[test]
    fn test_truncate_chain_keep_zero() {
        // Keep 0 = free everything
        let fat_sector = Arc::new(SpinMutex::new([0u8; 512]));
        let writes_before_crash = Arc::new(SpinMutex::new(None));

        CrashSimDevice::set_entry(&fat_sector, 2, FatEntry::DataCluster(3));
        CrashSimDevice::set_entry(&fat_sector, 3, FatEntry::LastCluster(0x0FFFFFFF));

        let device = CrashSimDevice::new(fat_sector.clone(), writes_before_crash.clone());
        let cached = Arc::new(CachedPartition::new(
            device,
            512,
            SectorId(0),
            1,
            SectorId(100),
            1,
            1,
        ));

        truncate_cluster_chain(ClusterId::new(2), 0, cached).unwrap();

        assert!(matches!(
            CrashSimDevice::get_entry(&fat_sector, 2),
            FatEntry::Unused
        ));
        assert!(matches!(
            CrashSimDevice::get_entry(&fat_sector, 3),
            FatEntry::Unused
        ));
    }

    #[test]
    fn test_truncate_chain_keep_all() {
        // Keep 5 on a 5-cluster chain = no-op
        let fat_sector = Arc::new(SpinMutex::new([0u8; 512]));
        let writes_before_crash = Arc::new(SpinMutex::new(None));

        CrashSimDevice::set_entry(&fat_sector, 2, FatEntry::DataCluster(3));
        CrashSimDevice::set_entry(&fat_sector, 3, FatEntry::DataCluster(4));
        CrashSimDevice::set_entry(&fat_sector, 4, FatEntry::DataCluster(5));
        CrashSimDevice::set_entry(&fat_sector, 5, FatEntry::DataCluster(6));
        CrashSimDevice::set_entry(&fat_sector, 6, FatEntry::LastCluster(0x0FFFFFFF));

        let device = CrashSimDevice::new(fat_sector.clone(), writes_before_crash.clone());
        let cached = Arc::new(CachedPartition::new(
            device,
            512,
            SectorId(0),
            1,
            SectorId(100),
            1,
            1,
        ));

        truncate_cluster_chain(ClusterId::new(2), 5, cached).unwrap();

        // Chain should be unchanged
        assert!(matches!(
            CrashSimDevice::get_entry(&fat_sector, 2),
            FatEntry::DataCluster(3)
        ));
        assert!(matches!(
            CrashSimDevice::get_entry(&fat_sector, 3),
            FatEntry::DataCluster(4)
        ));
        assert!(matches!(
            CrashSimDevice::get_entry(&fat_sector, 4),
            FatEntry::DataCluster(5)
        ));
        assert!(matches!(
            CrashSimDevice::get_entry(&fat_sector, 5),
            FatEntry::DataCluster(6)
        ));
        assert!(matches!(
            CrashSimDevice::get_entry(&fat_sector, 6),
            FatEntry::LastCluster(_)
        ));
    }
}