Skip to main content

sdmmc_async/
fs.rs

1#[cfg(feature = "exfat")]
2use crate::exfat;
3#[cfg(feature = "fat32")]
4use crate::fat32;
5#[cfg(feature = "write")]
6use crate::time::{default_clock, Timestamp};
7#[cfg(feature = "write")]
8use crate::BlockWrite;
9use crate::{BlockDevice, Error, Name, BLOCK_SIZE};
10
11/// Where a file's or directory's entry sits in its parent directory, for the operations that change it.
12#[cfg(feature = "write")]
13#[derive(Clone, Copy, Debug)]
14pub(crate) enum EntryLoc {
15    #[cfg(feature = "fat32")]
16    Fat32(fat32::EntryLoc),
17    #[cfg(feature = "exfat")]
18    ExFat(exfat::EntryLoc),
19}
20
21#[cfg(feature = "write")]
22impl EntryLoc {
23    #[cfg(feature = "fat32")]
24    pub(crate) fn fat32(self) -> Option<fat32::EntryLoc> {
25        match self {
26            EntryLoc::Fat32(loc) => Some(loc),
27            #[cfg(feature = "exfat")]
28            EntryLoc::ExFat(_) => None,
29        }
30    }
31
32    #[cfg(feature = "exfat")]
33    pub(crate) fn exfat(self) -> Option<exfat::EntryLoc> {
34        match self {
35            EntryLoc::ExFat(loc) => Some(loc),
36            #[cfg(feature = "fat32")]
37            EntryLoc::Fat32(_) => None,
38        }
39    }
40}
41
42/// An open file. It is plain data: the `Volume` owns the device and performs
43/// the reads, so the file handle can be stored anywhere without borrowing the
44/// filesystem.
45///
46/// A handle belongs to the volume that opened it. Using it on another volume reads or (with `write`) overwrites unrelated
47/// places on that volume's card. After the file is removed or renamed, or the volume is unmounted, it must not be used.
48#[derive(Clone, Copy, Debug)]
49pub struct File {
50    pub(crate) first_cluster: u32,
51    pub(crate) cluster: u32,
52    pub(crate) size: u64,
53    pub(crate) cursor: u64,
54    pub(crate) clusters_walked: u32,
55    /// Only exFAT has files with no FAT chain.
56    #[cfg(feature = "exfat")]
57    pub(crate) no_fat_chain: bool,
58    /// Where the entry is, to update its size.
59    #[cfg(feature = "write")]
60    pub(crate) loc: EntryLoc,
61    /// The size or first cluster changed since the entry was last written.
62    #[cfg(feature = "write")]
63    pub(crate) dirty: bool,
64}
65
66impl File {
67    /// The file's size in bytes.
68    pub fn size(&self) -> u64 {
69        self.size
70    }
71
72    /// The current read position, in bytes from the start.
73    pub fn position(&self) -> u64 {
74        self.cursor
75    }
76
77    /// Whether the file has no data.
78    pub fn is_empty(&self) -> bool {
79        self.size == 0
80    }
81}
82
83/// One entry of a directory listing.
84#[derive(Clone, Copy, Debug)]
85pub struct DirEntry {
86    /// The long name (on FAT32, the 8.3 name when there is no long one).
87    pub name: Name,
88    #[cfg(feature = "fat32")]
89    pub(crate) short_name: Name,
90    /// The raw attribute byte (read-only 0x01, hidden 0x02, system 0x04, directory 0x10, archive 0x20).
91    pub attributes: u8,
92    /// The first cluster of the file's or directory's data.
93    pub first_cluster: u32,
94    /// The size in bytes (0 for a FAT32 directory).
95    pub size: u64,
96    /// Whether the entry is a directory.
97    pub is_directory: bool,
98    #[cfg(feature = "exfat")]
99    pub(crate) no_fat_chain: bool,
100    #[cfg(feature = "write")]
101    pub(crate) loc: EntryLoc,
102}
103
104/// An open directory. Opaque: obtain one from `Volume::open_root` or
105/// `Volume::open_dir` and pass it back to `Volume::next_entry`.
106#[derive(Clone, Copy, Debug)]
107pub struct Directory {
108    inner: DirectoryInner,
109}
110
111#[derive(Clone, Copy, Debug)]
112enum DirectoryInner {
113    #[cfg(feature = "fat32")]
114    Fat32(fat32::Directory),
115    #[cfg(feature = "exfat")]
116    ExFat(exfat::Directory),
117}
118
119/// A mounted volume. The filesystem type is detected from the boot sector, so
120/// callers use one API for FAT32 and exFAT cards.
121pub struct Volume<D: BlockDevice> {
122    inner: VolumeInner<D>,
123    #[cfg(feature = "write")]
124    clock: fn() -> Timestamp,
125}
126
127enum VolumeInner<D: BlockDevice> {
128    #[cfg(feature = "fat32")]
129    Fat32(fat32::Volume<D>),
130    #[cfg(feature = "exfat")]
131    ExFat(exfat::Volume<D>),
132}
133
134/// Runs `$body` on whichever filesystem the volume is, binding it as `$volume`.
135macro_rules! on_volume {
136    ($inner:expr, $volume:ident => $body:expr) => {
137        match $inner {
138            #[cfg(feature = "fat32")]
139            VolumeInner::Fat32($volume) => $body,
140            #[cfg(feature = "exfat")]
141            VolumeInner::ExFat($volume) => $body,
142        }
143    };
144}
145
146impl<D: BlockDevice> Volume<D> {
147    /// Mounts the volume on `device`, detecting FAT32 or exFAT from the boot sector at block 0 or in the first partition of
148    /// an MBR. Fails with `Error::FilesystemNotEnabled` if the card holds a filesystem whose feature is off.
149    ///
150    /// The returned future holds `device` once, and the detection work borrows it. (An `async fn` would hold two copies of
151    /// an argument, which for a card of a few kilobytes is the larger part of the future.)
152    #[allow(clippy::manual_async_fn)] // deliberate, see above
153    pub fn mount(
154        mut device: D,
155    ) -> impl core::future::Future<Output = Result<Self, Error<D::Error>>> {
156        async move {
157            let detected = detect(&mut device).await?;
158            Ok(match detected {
159                #[cfg(feature = "fat32")]
160                Detected::Fat32 { start, geometry } => Volume {
161                    inner: VolumeInner::Fat32(fat32::Volume::new(device, start, geometry)),
162                    #[cfg(feature = "write")]
163                    clock: default_clock,
164                },
165                #[cfg(feature = "exfat")]
166                Detected::ExFat { start, geometry } => Volume {
167                    inner: VolumeInner::ExFat(exfat::Volume::new(device, start, geometry)),
168                    #[cfg(feature = "write")]
169                    clock: default_clock,
170                },
171            })
172        }
173    }
174
175    /// The device, when the volume is no longer wanted.
176    pub fn into_device(self) -> D {
177        on_volume!(self.inner, volume => volume.into_device())
178    }
179
180    /// The root directory.
181    pub fn open_root(&self) -> Directory {
182        Directory {
183            inner: match &self.inner {
184                #[cfg(feature = "fat32")]
185                VolumeInner::Fat32(volume) => DirectoryInner::Fat32(volume.open_root()),
186                #[cfg(feature = "exfat")]
187                VolumeInner::ExFat(volume) => DirectoryInner::ExFat(volume.open_root()),
188            },
189        }
190    }
191
192    /// Opens the file at `path`: names separated by `/`, matched ignoring ASCII case. A leading `/` is allowed.
193    pub async fn open_file(&mut self, path: &str) -> Result<File, Error<D::Error>> {
194        on_volume!(&mut self.inner, volume => volume.open_file(path).await)
195    }
196
197    /// Opens the directory at `path`, as for `open_file`.
198    pub async fn open_dir(&mut self, path: &str) -> Result<Directory, Error<D::Error>> {
199        let inner = match &mut self.inner {
200            #[cfg(feature = "fat32")]
201            VolumeInner::Fat32(volume) => DirectoryInner::Fat32(volume.open_dir(path).await?),
202            #[cfg(feature = "exfat")]
203            VolumeInner::ExFat(volume) => DirectoryInner::ExFat(volume.open_dir(path).await?),
204        };
205        Ok(Directory { inner })
206    }
207
208    /// The next entry of `dir`, or `None` at the end. Entries come in directory order; `.` and `..` are skipped.
209    pub async fn next_entry(
210        &mut self,
211        dir: &mut Directory,
212    ) -> Result<Option<DirEntry>, Error<D::Error>> {
213        match (&mut self.inner, &mut dir.inner) {
214            #[cfg(feature = "fat32")]
215            (VolumeInner::Fat32(volume), DirectoryInner::Fat32(dir)) => {
216                volume.next_entry(dir).await
217            }
218            #[cfg(feature = "exfat")]
219            (VolumeInner::ExFat(volume), DirectoryInner::ExFat(dir)) => {
220                volume.next_entry(dir).await
221            }
222            #[cfg(all(feature = "fat32", feature = "exfat"))]
223            _ => Err(Error::Unsupported),
224        }
225    }
226
227    /// Reads from the file's position into `buffer` and advances it; returns the bytes read, 0 at the end of the file.
228    pub async fn read_file(
229        &mut self,
230        file: &mut File,
231        buffer: &mut [u8],
232    ) -> Result<usize, Error<D::Error>> {
233        on_volume!(&mut self.inner, volume => volume.read_file(file, buffer).await)
234    }
235
236    /// Moves the file's position to `position` bytes from the start; past the end of the file is `Error::InvalidPosition`.
237    pub async fn seek(&mut self, file: &mut File, position: u64) -> Result<(), Error<D::Error>> {
238        on_volume!(&mut self.inner, volume => volume.seek(file, position).await)
239    }
240}
241
242#[cfg(feature = "write")]
243impl<D: BlockDevice + BlockWrite> Volume<D> {
244    /// Sets where the volume gets the time to stamp on what it writes (FAT has no other source: there is no clock here).
245    /// Until this is called, everything is stamped 1980-01-01 00:00:00.
246    pub fn set_clock(&mut self, clock: fn() -> Timestamp) {
247        self.clock = clock;
248    }
249
250    /// Writes `data` at the file's position and moves it on, growing the file as needed (the position can be anywhere up
251    /// to the end of the file). Returns the bytes written: fewer than `data.len()` only when the volume is full or the
252    /// file reaches its largest size, and `Error::NoSpace` or `Error::FileTooLarge` when none could be.
253    ///
254    /// The file's directory entry is updated by `flush_file`, not here.
255    pub async fn write_file(
256        &mut self,
257        file: &mut File,
258        data: &[u8],
259    ) -> Result<usize, Error<D::Error>> {
260        on_volume!(&mut self.inner, volume => volume.write_file(file, data).await)
261    }
262
263    /// Writes the file's size, first cluster and times into its directory entry. Until this is called, a PC reading the
264    /// card sees the file as it was.
265    pub async fn flush_file(&mut self, file: &mut File) -> Result<(), Error<D::Error>> {
266        let now = (self.clock)();
267        on_volume!(&mut self.inner, volume => volume.flush_file(file, now).await)
268    }
269
270    /// Sets the file's length: shorter frees the clusters past it, longer fills with zeros. A position past the new end
271    /// moves to it. Call `flush_file` afterwards. When lengthening runs out of space it fails with `Error::NoSpace` having
272    /// grown the file as far as it could; the file's size says how far.
273    pub async fn set_len(&mut self, file: &mut File, length: u64) -> Result<(), Error<D::Error>> {
274        let now = (self.clock)();
275        on_volume!(&mut self.inner, volume => volume.set_len(file, length, now).await)
276    }
277
278    /// Creates an empty file at `path` (the directory must exist) and opens it. Fails with `Error::AlreadyExists` if the
279    /// name is taken, ignoring case. Names may be up to 255 characters, with the usual restrictions (no `\ / : * ? " < > |`,
280    /// no trailing dot or space).
281    pub async fn create_file(&mut self, path: &str) -> Result<File, Error<D::Error>> {
282        let now = (self.clock)();
283        on_volume!(&mut self.inner, volume => volume.create_file(path, now).await)
284    }
285
286    /// Creates an empty directory at `path` (its parent must exist).
287    pub async fn create_dir(&mut self, path: &str) -> Result<(), Error<D::Error>> {
288        let now = (self.clock)();
289        on_volume!(&mut self.inner, volume => volume.create_dir(path, now).await)
290    }
291
292    /// Deletes the file at `path` and frees its clusters. Handles open on it must not be used afterwards.
293    pub async fn remove_file(&mut self, path: &str) -> Result<(), Error<D::Error>> {
294        on_volume!(&mut self.inner, volume => volume.remove_file(path).await)
295    }
296
297    /// Deletes the directory at `path`, which must be empty (`Error::NotEmpty` otherwise).
298    pub async fn remove_dir(&mut self, path: &str) -> Result<(), Error<D::Error>> {
299        on_volume!(&mut self.inner, volume => volume.remove_dir(path).await)
300    }
301
302    /// Renames or moves a file or directory. `to` must not exist (`Error::AlreadyExists`), except that changing only the
303    /// case of the name is allowed, and a directory cannot move into itself. Handles open on it must not be used
304    /// afterwards.
305    pub async fn rename(&mut self, from: &str, to: &str) -> Result<(), Error<D::Error>> {
306        let now = (self.clock)();
307        on_volume!(&mut self.inner, volume => volume.rename(from, to, now).await)
308    }
309
310    /// Records that the volume was unmounted cleanly and updates its free-space information. Call it when done writing;
311    /// until then a PC that mounts the card will offer to check it. It does not flush open files: call `flush_file` on each
312    /// first, or a file's new size is lost. A volume that was already marked in use when it was mounted (a writer before
313    /// this one did not finish) stays marked, for a checker to clear.
314    pub async fn sync(&mut self) -> Result<(), Error<D::Error>> {
315        on_volume!(&mut self.inner, volume => volume.sync().await)
316    }
317}
318
319/// What the boot sectors say, found without owning the device.
320enum Detected {
321    #[cfg(feature = "fat32")]
322    Fat32 {
323        start: u32,
324        geometry: fat32::Geometry,
325    },
326    #[cfg(feature = "exfat")]
327    ExFat {
328        start: u32,
329        geometry: exfat::Geometry,
330    },
331}
332
333async fn detect<D: BlockDevice>(device: &mut D) -> Result<Detected, Error<D::Error>> {
334    // One sector buffer serves the boot sector, the partition table and the backup boot sector in turn.
335    let mut sector = [0u8; BLOCK_SIZE];
336    device
337        .read_block(0, &mut sector)
338        .await
339        .map_err(Error::Device)?;
340
341    if is_exfat_boot(&sector) {
342        return detect_exfat(device, 0, &mut sector).await;
343    }
344    if is_fat32_boot(&sector) {
345        return detect_fat32(device, 0, &mut sector).await;
346    }
347    if is_fat_boot(&sector) {
348        return Err(Error::Unsupported);
349    }
350
351    let Some(start) = first_partition(&sector) else {
352        // No partition table: a superfloppy FAT32 volume whose boot sector is damaged.
353        return if read_backup_boot(device, 0, &mut sector).await {
354            detect_fat32(device, 0, &mut sector).await
355        } else {
356            Err(Error::NoPartition)
357        };
358    };
359    device
360        .read_block(start, &mut sector)
361        .await
362        .map_err(Error::Device)?;
363    if is_exfat_boot(&sector) {
364        return detect_exfat(device, start, &mut sector).await;
365    }
366    if is_fat32_boot(&sector) {
367        return detect_fat32(device, start, &mut sector).await;
368    }
369    if is_fat_boot(&sector) {
370        return Err(Error::Unsupported);
371    }
372    if read_backup_boot(device, start, &mut sector).await {
373        detect_fat32(device, start, &mut sector).await
374    } else {
375        Err(Error::BadBootSector)
376    }
377}
378
379/// Validates FAT32 from the boot sector in `boot`; if its geometry is damaged, the backup boot sector (sector 6 of the
380/// volume) gets a chance before the error is reported. `boot` is reused for the backup.
381#[cfg(feature = "fat32")]
382async fn detect_fat32<D: BlockDevice>(
383    device: &mut D,
384    start: u32,
385    boot: &mut [u8; BLOCK_SIZE],
386) -> Result<Detected, Error<D::Error>> {
387    let blocks = device.num_blocks().await.map_err(Error::Device)?;
388    let error = match fat32::geometry(boot, start, blocks) {
389        Ok(geometry) => return Ok(Detected::Fat32 { start, geometry }),
390        Err(error) => error,
391    };
392    if read_backup_boot(device, start, boot).await {
393        if let Ok(geometry) = fat32::geometry::<D::Error>(boot, start, blocks) {
394            return Ok(Detected::Fat32 { start, geometry });
395        }
396    }
397    Err(error)
398}
399
400#[cfg(not(feature = "fat32"))]
401async fn detect_fat32<D: BlockDevice>(
402    _device: &mut D,
403    _start: u32,
404    _boot: &mut [u8; BLOCK_SIZE],
405) -> Result<Detected, Error<D::Error>> {
406    Err(Error::FilesystemNotEnabled)
407}
408
409#[cfg(feature = "exfat")]
410async fn detect_exfat<D: BlockDevice>(
411    device: &mut D,
412    start: u32,
413    buffer: &mut [u8; BLOCK_SIZE],
414) -> Result<Detected, Error<D::Error>> {
415    Ok(Detected::ExFat {
416        start,
417        geometry: exfat::probe(device, start, buffer).await?,
418    })
419}
420
421#[cfg(not(feature = "exfat"))]
422async fn detect_exfat<D: BlockDevice>(
423    _device: &mut D,
424    _start: u32,
425    _buffer: &mut [u8; BLOCK_SIZE],
426) -> Result<Detected, Error<D::Error>> {
427    Err(Error::FilesystemNotEnabled)
428}
429
430/// Reads the backup boot sector (sector 6 of the volume) into `backup`; false when it cannot be read or is not a FAT32 boot
431/// sector. `backup` is only meaningful when this returns true.
432async fn read_backup_boot<D: BlockDevice>(
433    device: &mut D,
434    start: u32,
435    backup: &mut [u8; BLOCK_SIZE],
436) -> bool {
437    let Some(sector) = start.checked_add(6) else {
438        return false;
439    };
440    device.read_block(sector, backup).await.is_ok() && is_fat32_boot(backup)
441}
442
443fn is_exfat_boot(sector: &[u8; BLOCK_SIZE]) -> bool {
444    sector[510] == 0x55 && sector[511] == 0xaa && &sector[3..11] == b"EXFAT   "
445}
446
447fn is_fat32_boot(sector: &[u8; BLOCK_SIZE]) -> bool {
448    // Structural markers only: the full geometry is validated by the FAT32 mount, so a corrupt
449    // sectors-per-cluster still reaches that validation and reports BadGeometry rather than
450    // falling through to the MBR path.
451    let bytes_per_sector = u16::from_le_bytes([sector[11], sector[12]]);
452    let root_entries = u16::from_le_bytes([sector[17], sector[18]]);
453    let fat_size16 = u16::from_le_bytes([sector[22], sector[23]]);
454    let fat_size32 = u32::from_le_bytes([sector[36], sector[37], sector[38], sector[39]]);
455    sector[510] == 0x55
456        && sector[511] == 0xaa
457        && bytes_per_sector == 512
458        && root_entries == 0
459        && fat_size16 == 0
460        && fat_size32 != 0
461}
462
463fn is_fat_boot(sector: &[u8; BLOCK_SIZE]) -> bool {
464    let bytes_per_sector = u16::from_le_bytes([sector[11], sector[12]]);
465    let sectors_per_cluster = sector[13];
466    let reserved = u16::from_le_bytes([sector[14], sector[15]]);
467    let num_fats = sector[16];
468    let fat_size16 = u16::from_le_bytes([sector[22], sector[23]]);
469    let fat_size32 = u32::from_le_bytes([sector[36], sector[37], sector[38], sector[39]]);
470    sector[510] == 0x55
471        && sector[511] == 0xaa
472        && bytes_per_sector == 512
473        && sectors_per_cluster != 0
474        && sectors_per_cluster.is_power_of_two()
475        && reserved != 0
476        && (1..=2).contains(&num_fats)
477        && (fat_size16 != 0 || fat_size32 != 0)
478}
479
480fn first_partition(mbr: &[u8; BLOCK_SIZE]) -> Option<u32> {
481    if mbr[510] != 0x55 || mbr[511] != 0xaa {
482        return None;
483    }
484    for index in 0..4 {
485        let offset = 0x1be + index * 16;
486        let kind = mbr[offset + 4];
487        let start = u32::from_le_bytes([
488            mbr[offset + 8],
489            mbr[offset + 9],
490            mbr[offset + 10],
491            mbr[offset + 11],
492        ]);
493        if start != 0 && matches!(kind, 0x04 | 0x06 | 0x07 | 0x0b | 0x0c | 0x0e) {
494            return Some(start);
495        }
496    }
497    None
498}