sdmmc-async 0.2.0

An async, no_std, no-alloc SD card stack: an SPI-mode card driver and FAT32 and exFAT (read-only, or writable with the `write` feature), over embedded-hal-async.
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
#[cfg(feature = "exfat")]
use crate::exfat;
#[cfg(feature = "fat32")]
use crate::fat32;
#[cfg(feature = "write")]
use crate::time::{default_clock, Timestamp};
#[cfg(feature = "write")]
use crate::BlockWrite;
use crate::{BlockDevice, Error, Name, BLOCK_SIZE};

/// Where a file's or directory's entry sits in its parent directory, for the operations that change it.
#[cfg(feature = "write")]
#[derive(Clone, Copy, Debug)]
pub(crate) enum EntryLoc {
    #[cfg(feature = "fat32")]
    Fat32(fat32::EntryLoc),
    #[cfg(feature = "exfat")]
    ExFat(exfat::EntryLoc),
}

#[cfg(feature = "write")]
impl EntryLoc {
    #[cfg(feature = "fat32")]
    pub(crate) fn fat32(self) -> Option<fat32::EntryLoc> {
        match self {
            EntryLoc::Fat32(loc) => Some(loc),
            #[cfg(feature = "exfat")]
            EntryLoc::ExFat(_) => None,
        }
    }

    #[cfg(feature = "exfat")]
    pub(crate) fn exfat(self) -> Option<exfat::EntryLoc> {
        match self {
            EntryLoc::ExFat(loc) => Some(loc),
            #[cfg(feature = "fat32")]
            EntryLoc::Fat32(_) => None,
        }
    }
}

/// An open file. It is plain data: the `Volume` owns the device and performs
/// the reads, so the file handle can be stored anywhere without borrowing the
/// filesystem.
///
/// A handle belongs to the volume that opened it. Using it on another volume reads or (with `write`) overwrites unrelated
/// places on that volume's card. After the file is removed or renamed, or the volume is unmounted, it must not be used.
#[derive(Clone, Copy, Debug)]
pub struct File {
    pub(crate) first_cluster: u32,
    pub(crate) cluster: u32,
    pub(crate) size: u64,
    pub(crate) cursor: u64,
    pub(crate) clusters_walked: u32,
    /// Only exFAT has files with no FAT chain.
    #[cfg(feature = "exfat")]
    pub(crate) no_fat_chain: bool,
    /// Where the entry is, to update its size.
    #[cfg(feature = "write")]
    pub(crate) loc: EntryLoc,
    /// The size or first cluster changed since the entry was last written.
    #[cfg(feature = "write")]
    pub(crate) dirty: bool,
}

impl File {
    /// The file's size in bytes.
    pub fn size(&self) -> u64 {
        self.size
    }

    /// The current read position, in bytes from the start.
    pub fn position(&self) -> u64 {
        self.cursor
    }

    /// Whether the file has no data.
    pub fn is_empty(&self) -> bool {
        self.size == 0
    }
}

/// One entry of a directory listing.
#[derive(Clone, Copy, Debug)]
pub struct DirEntry {
    /// The long name (on FAT32, the 8.3 name when there is no long one).
    pub name: Name,
    #[cfg(feature = "fat32")]
    pub(crate) short_name: Name,
    /// The raw attribute byte (read-only 0x01, hidden 0x02, system 0x04, directory 0x10, archive 0x20).
    pub attributes: u8,
    /// The first cluster of the file's or directory's data.
    pub first_cluster: u32,
    /// The size in bytes (0 for a FAT32 directory).
    pub size: u64,
    /// Whether the entry is a directory.
    pub is_directory: bool,
    #[cfg(feature = "exfat")]
    pub(crate) no_fat_chain: bool,
    #[cfg(feature = "write")]
    pub(crate) loc: EntryLoc,
}

/// An open directory. Opaque: obtain one from `Volume::open_root` or
/// `Volume::open_dir` and pass it back to `Volume::next_entry`.
#[derive(Clone, Copy, Debug)]
pub struct Directory {
    inner: DirectoryInner,
}

#[derive(Clone, Copy, Debug)]
enum DirectoryInner {
    #[cfg(feature = "fat32")]
    Fat32(fat32::Directory),
    #[cfg(feature = "exfat")]
    ExFat(exfat::Directory),
}

/// A mounted volume. The filesystem type is detected from the boot sector, so
/// callers use one API for FAT32 and exFAT cards.
pub struct Volume<D: BlockDevice> {
    inner: VolumeInner<D>,
    #[cfg(feature = "write")]
    clock: fn() -> Timestamp,
}

enum VolumeInner<D: BlockDevice> {
    #[cfg(feature = "fat32")]
    Fat32(fat32::Volume<D>),
    #[cfg(feature = "exfat")]
    ExFat(exfat::Volume<D>),
}

/// Runs `$body` on whichever filesystem the volume is, binding it as `$volume`.
macro_rules! on_volume {
    ($inner:expr, $volume:ident => $body:expr) => {
        match $inner {
            #[cfg(feature = "fat32")]
            VolumeInner::Fat32($volume) => $body,
            #[cfg(feature = "exfat")]
            VolumeInner::ExFat($volume) => $body,
        }
    };
}

impl<D: BlockDevice> Volume<D> {
    /// Mounts the volume on `device`, detecting FAT32 or exFAT from the boot sector at block 0 or in the first partition of
    /// an MBR. Fails with `Error::FilesystemNotEnabled` if the card holds a filesystem whose feature is off.
    ///
    /// The returned future holds `device` once, and the detection work borrows it. (An `async fn` would hold two copies of
    /// an argument, which for a card of a few kilobytes is the larger part of the future.)
    #[allow(clippy::manual_async_fn)] // deliberate, see above
    pub fn mount(
        mut device: D,
    ) -> impl core::future::Future<Output = Result<Self, Error<D::Error>>> {
        async move {
            let detected = detect(&mut device).await?;
            Ok(match detected {
                #[cfg(feature = "fat32")]
                Detected::Fat32 { start, geometry } => Volume {
                    inner: VolumeInner::Fat32(fat32::Volume::new(device, start, geometry)),
                    #[cfg(feature = "write")]
                    clock: default_clock,
                },
                #[cfg(feature = "exfat")]
                Detected::ExFat { start, geometry } => Volume {
                    inner: VolumeInner::ExFat(exfat::Volume::new(device, start, geometry)),
                    #[cfg(feature = "write")]
                    clock: default_clock,
                },
            })
        }
    }

    /// The device, when the volume is no longer wanted.
    pub fn into_device(self) -> D {
        on_volume!(self.inner, volume => volume.into_device())
    }

    /// The root directory.
    pub fn open_root(&self) -> Directory {
        Directory {
            inner: match &self.inner {
                #[cfg(feature = "fat32")]
                VolumeInner::Fat32(volume) => DirectoryInner::Fat32(volume.open_root()),
                #[cfg(feature = "exfat")]
                VolumeInner::ExFat(volume) => DirectoryInner::ExFat(volume.open_root()),
            },
        }
    }

    /// Opens the file at `path`: names separated by `/`, matched ignoring ASCII case. A leading `/` is allowed.
    pub async fn open_file(&mut self, path: &str) -> Result<File, Error<D::Error>> {
        on_volume!(&mut self.inner, volume => volume.open_file(path).await)
    }

    /// Opens the directory at `path`, as for `open_file`.
    pub async fn open_dir(&mut self, path: &str) -> Result<Directory, Error<D::Error>> {
        let inner = match &mut self.inner {
            #[cfg(feature = "fat32")]
            VolumeInner::Fat32(volume) => DirectoryInner::Fat32(volume.open_dir(path).await?),
            #[cfg(feature = "exfat")]
            VolumeInner::ExFat(volume) => DirectoryInner::ExFat(volume.open_dir(path).await?),
        };
        Ok(Directory { inner })
    }

    /// The next entry of `dir`, or `None` at the end. Entries come in directory order; `.` and `..` are skipped.
    pub async fn next_entry(
        &mut self,
        dir: &mut Directory,
    ) -> Result<Option<DirEntry>, Error<D::Error>> {
        match (&mut self.inner, &mut dir.inner) {
            #[cfg(feature = "fat32")]
            (VolumeInner::Fat32(volume), DirectoryInner::Fat32(dir)) => {
                volume.next_entry(dir).await
            }
            #[cfg(feature = "exfat")]
            (VolumeInner::ExFat(volume), DirectoryInner::ExFat(dir)) => {
                volume.next_entry(dir).await
            }
            #[cfg(all(feature = "fat32", feature = "exfat"))]
            _ => Err(Error::Unsupported),
        }
    }

    /// Reads from the file's position into `buffer` and advances it; returns the bytes read, 0 at the end of the file.
    pub async fn read_file(
        &mut self,
        file: &mut File,
        buffer: &mut [u8],
    ) -> Result<usize, Error<D::Error>> {
        on_volume!(&mut self.inner, volume => volume.read_file(file, buffer).await)
    }

    /// Moves the file's position to `position` bytes from the start; past the end of the file is `Error::InvalidPosition`.
    pub async fn seek(&mut self, file: &mut File, position: u64) -> Result<(), Error<D::Error>> {
        on_volume!(&mut self.inner, volume => volume.seek(file, position).await)
    }
}

#[cfg(feature = "write")]
impl<D: BlockDevice + BlockWrite> Volume<D> {
    /// Sets where the volume gets the time to stamp on what it writes (FAT has no other source: there is no clock here).
    /// Until this is called, everything is stamped 1980-01-01 00:00:00.
    pub fn set_clock(&mut self, clock: fn() -> Timestamp) {
        self.clock = clock;
    }

    /// Writes `data` at the file's position and moves it on, growing the file as needed (the position can be anywhere up
    /// to the end of the file). Returns the bytes written: fewer than `data.len()` only when the volume is full or the
    /// file reaches its largest size, and `Error::NoSpace` or `Error::FileTooLarge` when none could be.
    ///
    /// The file's directory entry is updated by `flush_file`, not here.
    pub async fn write_file(
        &mut self,
        file: &mut File,
        data: &[u8],
    ) -> Result<usize, Error<D::Error>> {
        on_volume!(&mut self.inner, volume => volume.write_file(file, data).await)
    }

    /// Writes the file's size, first cluster and times into its directory entry. Until this is called, a PC reading the
    /// card sees the file as it was.
    pub async fn flush_file(&mut self, file: &mut File) -> Result<(), Error<D::Error>> {
        let now = (self.clock)();
        on_volume!(&mut self.inner, volume => volume.flush_file(file, now).await)
    }

    /// Sets the file's length: shorter frees the clusters past it, longer fills with zeros. A position past the new end
    /// moves to it. Call `flush_file` afterwards. When lengthening runs out of space it fails with `Error::NoSpace` having
    /// grown the file as far as it could; the file's size says how far.
    pub async fn set_len(&mut self, file: &mut File, length: u64) -> Result<(), Error<D::Error>> {
        let now = (self.clock)();
        on_volume!(&mut self.inner, volume => volume.set_len(file, length, now).await)
    }

    /// Creates an empty file at `path` (the directory must exist) and opens it. Fails with `Error::AlreadyExists` if the
    /// name is taken, ignoring case. Names may be up to 255 characters, with the usual restrictions (no `\ / : * ? " < > |`,
    /// no trailing dot or space).
    pub async fn create_file(&mut self, path: &str) -> Result<File, Error<D::Error>> {
        let now = (self.clock)();
        on_volume!(&mut self.inner, volume => volume.create_file(path, now).await)
    }

    /// Creates an empty directory at `path` (its parent must exist).
    pub async fn create_dir(&mut self, path: &str) -> Result<(), Error<D::Error>> {
        let now = (self.clock)();
        on_volume!(&mut self.inner, volume => volume.create_dir(path, now).await)
    }

    /// Deletes the file at `path` and frees its clusters. Handles open on it must not be used afterwards.
    pub async fn remove_file(&mut self, path: &str) -> Result<(), Error<D::Error>> {
        on_volume!(&mut self.inner, volume => volume.remove_file(path).await)
    }

    /// Deletes the directory at `path`, which must be empty (`Error::NotEmpty` otherwise).
    pub async fn remove_dir(&mut self, path: &str) -> Result<(), Error<D::Error>> {
        on_volume!(&mut self.inner, volume => volume.remove_dir(path).await)
    }

    /// Renames or moves a file or directory. `to` must not exist (`Error::AlreadyExists`), except that changing only the
    /// case of the name is allowed, and a directory cannot move into itself. Handles open on it must not be used
    /// afterwards.
    pub async fn rename(&mut self, from: &str, to: &str) -> Result<(), Error<D::Error>> {
        let now = (self.clock)();
        on_volume!(&mut self.inner, volume => volume.rename(from, to, now).await)
    }

    /// Records that the volume was unmounted cleanly and updates its free-space information. Call it when done writing;
    /// until then a PC that mounts the card will offer to check it. It does not flush open files: call `flush_file` on each
    /// first, or a file's new size is lost. A volume that was already marked in use when it was mounted (a writer before
    /// this one did not finish) stays marked, for a checker to clear.
    pub async fn sync(&mut self) -> Result<(), Error<D::Error>> {
        on_volume!(&mut self.inner, volume => volume.sync().await)
    }
}

/// What the boot sectors say, found without owning the device.
enum Detected {
    #[cfg(feature = "fat32")]
    Fat32 {
        start: u32,
        geometry: fat32::Geometry,
    },
    #[cfg(feature = "exfat")]
    ExFat {
        start: u32,
        geometry: exfat::Geometry,
    },
}

async fn detect<D: BlockDevice>(device: &mut D) -> Result<Detected, Error<D::Error>> {
    // One sector buffer serves the boot sector, the partition table and the backup boot sector in turn.
    let mut sector = [0u8; BLOCK_SIZE];
    device
        .read_block(0, &mut sector)
        .await
        .map_err(Error::Device)?;

    if is_exfat_boot(&sector) {
        return detect_exfat(device, 0, &mut sector).await;
    }
    if is_fat32_boot(&sector) {
        return detect_fat32(device, 0, &mut sector).await;
    }
    if is_fat_boot(&sector) {
        return Err(Error::Unsupported);
    }

    let Some(start) = first_partition(&sector) else {
        // No partition table: a superfloppy FAT32 volume whose boot sector is damaged.
        return if read_backup_boot(device, 0, &mut sector).await {
            detect_fat32(device, 0, &mut sector).await
        } else {
            Err(Error::NoPartition)
        };
    };
    device
        .read_block(start, &mut sector)
        .await
        .map_err(Error::Device)?;
    if is_exfat_boot(&sector) {
        return detect_exfat(device, start, &mut sector).await;
    }
    if is_fat32_boot(&sector) {
        return detect_fat32(device, start, &mut sector).await;
    }
    if is_fat_boot(&sector) {
        return Err(Error::Unsupported);
    }
    if read_backup_boot(device, start, &mut sector).await {
        detect_fat32(device, start, &mut sector).await
    } else {
        Err(Error::BadBootSector)
    }
}

/// Validates FAT32 from the boot sector in `boot`; if its geometry is damaged, the backup boot sector (sector 6 of the
/// volume) gets a chance before the error is reported. `boot` is reused for the backup.
#[cfg(feature = "fat32")]
async fn detect_fat32<D: BlockDevice>(
    device: &mut D,
    start: u32,
    boot: &mut [u8; BLOCK_SIZE],
) -> Result<Detected, Error<D::Error>> {
    let blocks = device.num_blocks().await.map_err(Error::Device)?;
    let error = match fat32::geometry(boot, start, blocks) {
        Ok(geometry) => return Ok(Detected::Fat32 { start, geometry }),
        Err(error) => error,
    };
    if read_backup_boot(device, start, boot).await {
        if let Ok(geometry) = fat32::geometry::<D::Error>(boot, start, blocks) {
            return Ok(Detected::Fat32 { start, geometry });
        }
    }
    Err(error)
}

#[cfg(not(feature = "fat32"))]
async fn detect_fat32<D: BlockDevice>(
    _device: &mut D,
    _start: u32,
    _boot: &mut [u8; BLOCK_SIZE],
) -> Result<Detected, Error<D::Error>> {
    Err(Error::FilesystemNotEnabled)
}

#[cfg(feature = "exfat")]
async fn detect_exfat<D: BlockDevice>(
    device: &mut D,
    start: u32,
    buffer: &mut [u8; BLOCK_SIZE],
) -> Result<Detected, Error<D::Error>> {
    Ok(Detected::ExFat {
        start,
        geometry: exfat::probe(device, start, buffer).await?,
    })
}

#[cfg(not(feature = "exfat"))]
async fn detect_exfat<D: BlockDevice>(
    _device: &mut D,
    _start: u32,
    _buffer: &mut [u8; BLOCK_SIZE],
) -> Result<Detected, Error<D::Error>> {
    Err(Error::FilesystemNotEnabled)
}

/// Reads the backup boot sector (sector 6 of the volume) into `backup`; false when it cannot be read or is not a FAT32 boot
/// sector. `backup` is only meaningful when this returns true.
async fn read_backup_boot<D: BlockDevice>(
    device: &mut D,
    start: u32,
    backup: &mut [u8; BLOCK_SIZE],
) -> bool {
    let Some(sector) = start.checked_add(6) else {
        return false;
    };
    device.read_block(sector, backup).await.is_ok() && is_fat32_boot(backup)
}

fn is_exfat_boot(sector: &[u8; BLOCK_SIZE]) -> bool {
    sector[510] == 0x55 && sector[511] == 0xaa && &sector[3..11] == b"EXFAT   "
}

fn is_fat32_boot(sector: &[u8; BLOCK_SIZE]) -> bool {
    // Structural markers only: the full geometry is validated by the FAT32 mount, so a corrupt
    // sectors-per-cluster still reaches that validation and reports BadGeometry rather than
    // falling through to the MBR path.
    let bytes_per_sector = u16::from_le_bytes([sector[11], sector[12]]);
    let root_entries = u16::from_le_bytes([sector[17], sector[18]]);
    let fat_size16 = u16::from_le_bytes([sector[22], sector[23]]);
    let fat_size32 = u32::from_le_bytes([sector[36], sector[37], sector[38], sector[39]]);
    sector[510] == 0x55
        && sector[511] == 0xaa
        && bytes_per_sector == 512
        && root_entries == 0
        && fat_size16 == 0
        && fat_size32 != 0
}

fn is_fat_boot(sector: &[u8; BLOCK_SIZE]) -> bool {
    let bytes_per_sector = u16::from_le_bytes([sector[11], sector[12]]);
    let sectors_per_cluster = sector[13];
    let reserved = u16::from_le_bytes([sector[14], sector[15]]);
    let num_fats = sector[16];
    let fat_size16 = u16::from_le_bytes([sector[22], sector[23]]);
    let fat_size32 = u32::from_le_bytes([sector[36], sector[37], sector[38], sector[39]]);
    sector[510] == 0x55
        && sector[511] == 0xaa
        && bytes_per_sector == 512
        && sectors_per_cluster != 0
        && sectors_per_cluster.is_power_of_two()
        && reserved != 0
        && (1..=2).contains(&num_fats)
        && (fat_size16 != 0 || fat_size32 != 0)
}

fn first_partition(mbr: &[u8; BLOCK_SIZE]) -> Option<u32> {
    if mbr[510] != 0x55 || mbr[511] != 0xaa {
        return None;
    }
    for index in 0..4 {
        let offset = 0x1be + index * 16;
        let kind = mbr[offset + 4];
        let start = u32::from_le_bytes([
            mbr[offset + 8],
            mbr[offset + 9],
            mbr[offset + 10],
            mbr[offset + 11],
        ]);
        if start != 0 && matches!(kind, 0x04 | 0x06 | 0x07 | 0x0b | 0x0c | 0x0e) {
            return Some(start);
        }
    }
    None
}