rigless 0.2.0

Virtual hardware-in-the-loop runtime: run unmodified firmware on an emulated MCU with every peripheral, chip model and unit of virtual time in Rust, and a CPU core of its own that translates the firmware's instructions to host code
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! A secure digital memory card that answers the [`crate::chip::sd::Card`] seam.
//!
//! RM0090 rev 22 section 31.4 is the card, described from the host's side, and it's enough to write
//! one from: 31.4.1 to 31.4.4 are identification, 31.4.5 and 31.4.6 the block write and read,
//! 31.4.9 the wide bus, 31.4.11 the card status register, and 31.4.14 the commands. No external
//! specification is used, which matters because the SD Association's isn't one of this project's
//! references. Where a host sends something 31.4.14 doesn't name, the table below says so instead
//! of the model inventing a page.
//!
//! The card speaks in commands and blocks, as [`crate::chip::sd`] says, and section 31.3.1 puts a
//! controller's command path and data path behind registers that speak the same way.
//!
//! | Register or section | Behavior | Source | Test |
//! |---|---|---|---|
//! | The card states | The states a card moves through: idle, ready, identification, standby, transfer, sending, receiving, programming | 31.4.1 to 31.4.4, 31.4.11 | `a_card_walks_the_identification_the_manual_gives`, `a_command_out_of_state_is_refused_and_says_so` |
//! | `CMD0` | `CMD0` resets it to idle, whatever it was doing | 31.4.2 | `a_reset_returns_the_card_to_idle_from_anywhere` |
//! | `ACMD41` | `ACMD41` answers the operating range, and is an application command so `CMD55` has to come first | 31.4.3, 31.4.14 | `an_application_command_needs_the_escape_before_it`, `a_card_walks_the_identification_the_manual_gives` |
//! | `CMD2`, `CMD3` | `CMD2` answers the identification, long, and `CMD3` gives it an address | 31.4.4 | `a_card_walks_the_identification_the_manual_gives` |
//! | `CMD9` | `CMD9` answers the card-specific data, long, and carries the size the host reads its capacity from | 31.4.4 | `the_card_reports_the_capacity_it_was_built_with` |
//! | `CMD7` | `CMD7` selects and deselects by address, which is what moves it between standby and transfer | 31.4.9 | `a_card_walks_the_identification_the_manual_gives` |
//! | `CMD16`, `ACMD6` | `CMD16` sets the block length, and `ACMD6` the bus width | 31.4.9, 31.4.14 | `the_block_length_and_the_bus_width_are_the_hosts_to_set` |
//! | `CMD17`, `CMD18`, `CMD24`, `CMD25`, `CMD12` | `CMD17` and `CMD18` read one block and many, `CMD24` and `CMD25` write one and many, and `CMD12` stops | 31.4.5, 31.4.6 | `a_block_written_is_the_block_read_back`, `a_multiple_read_walks_consecutive_blocks_until_it_is_stopped` |
//! | The card status register | The card status register every short answer carries, with `CURRENT_STATE` the field a driver reads | 31.4.11 | `every_answer_carries_the_state_the_card_is_in` |
//! | `R1b` | A block write takes a programming time the card is busy for, and `R1b` is how a host waits it out | 31.4.5, 31.5.2 | `a_write_leaves_the_card_busy_for_the_time_it_programs` |
//! | The blocks | The blocks themselves, as memory the machine gives it, so a run is deterministic and a test can look. A block never written reads zero, and the card is as large as its card-specific data says | 31.4.5, 31.4.6 | `a_block_written_is_the_block_read_back`, `an_unwritten_block_reads_zero_and_the_card_ends_where_its_data_says` |
//! | A formatted card | A formatted card: the volume `FatFs`'s own `f_mkfs` writes, so the reader on the part finds what its writer would have left | `FatFs` R0.14b `ff.c`, `f_mkfs` | `a_formatted_card_carries_the_volume_the_firmwares_formatter_writes` |
//!
//! **What the model leaves out, and why.**
//!
//! | Behavior | Source | Reason |
//! |---|---|---|
//! | `CMD8`, which a host sends to learn whether a card is the second version of the specification | not in 31.4.14 | The manual's command list doesn't carry it, and the specification that does isn't one of this project's references. A card that doesn't answer it is a valid earlier card and the host reads it as one. So the model answers nothing and the identification still completes, which is the behavior the page does describe |
//! | `CMD1`, `SEND_OP_COND` | 31.4.4 | The MultiMediaCard's half of the identification. This is a secure digital card and answers `ACMD41`. The page gives the two processes separately, and this model is the second |
//! | Erase: `CMD32`, `CMD33`, `CMD38` | 31.4.8 | Group and sector erase. Nothing on the boot path erases, and a card that refuses tells a host so through the status register rather than hanging it |
//! | Protection: the write-protect group commands and the card's lock | 31.4.10 | A mechanical switch and a password, neither of which a bench has |
//! | The SD status register, `ACMD13` | 31.4.12 | Five hundred and twelve bits of card characteristics a driver reads for performance hints. Nothing reads it to decide whether to go on |
//! | Stream access | 31.4.7 | The section's own title says MultiMediaCard only |
//! | SD I/O, `CMD5` and the rest | 31.4.13 | A different card class. A memory card answers nothing to `CMD5`, which is what this model does and what tells a host it isn't one |
//! | The real contents of the identification and the card-specific data, field by field | 31.4.4 | The host reads the capacity out of the card-specific data, and this model puts it there. The manufacturer, the serial number and the dates are filled with a fixed pattern, because a firmware that branches on them is one this bench doesn't have and would rather find than guess at |
//! | A wear-leveling or failure model | none | A card that returns what was written is the card a test wants. A card that fails is a condition of the board's to add, as a silent card already is |

use std::collections::BTreeMap;

use crate::chip::Timeline;
use crate::chip::sd::{Answer, BLOCK, Busy, Card, Outcome, command};
use crate::snapshot::store;
use crate::time::VirtualNanos;

/// The block length as the argument `CMD16` carries it, 31.4.5.
const BLOCK_LENGTH: u32 = 512;

/// The fields of 31.4.11's card status register the card sets.
mod status {
    use crate::soc::{Access, FieldSpec, ReadAction, WriteModify};

    const fn field(name: &'static str, bit: u8, width: u8) -> FieldSpec {
        FieldSpec {
            name,
            bit,
            width,
            access: Access::ReadOnly,
            read: ReadAction::None,
            write: WriteModify::None,
        }
    }

    pub(super) const CURRENT_STATE: FieldSpec = field("CURRENT_STATE", 9, 4);
    pub(super) const READY_FOR_DATA: FieldSpec = field("READY_FOR_DATA", 8, 1);
    pub(super) const APP_CMD: FieldSpec = field("APP_CMD", 5, 1);
}

/// The states of 31.4.11's `CURRENT_STATE`, which every short answer carries.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum State {
    /// Out of reset, and where `CMD0` puts it, 31.4.2.
    Idle = 0,
    /// The operating range is agreed, 31.4.3.
    Ready = 1,
    /// It has answered with its identification and has no address yet, 31.4.4.
    Identification = 2,
    /// It has an address and isn't selected, 31.4.4.
    Standby = 3,
    /// Selected, and where every transfer begins, 31.4.9.
    Transfer = 4,
    /// Sending a read's blocks, 31.4.6.
    SendingData = 5,
    /// Taking a write's blocks, 31.4.5.
    ReceivingData = 6,
    /// Programming what it took, 31.4.5.
    Programming = 7,
}

/// What a transfer in flight is doing, and where.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
struct Streaming {
    block: usize,
    multiple: bool,
}

/// A secure digital memory card of a size the board gives it.
///
/// Its blocks are memory, so a run is deterministic and a test can look at what landed. Only the
/// blocks ever written are held, so a card the size of the one a board carries costs what the
/// firmware wrote to it. It answers the identification of 31.4.4, reads and writes the blocks of
/// 31.4.5 and 31.4.6, and keeps the state of 31.4.11. The header's second table is everything it
/// doesn't do.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct MemoryCard {
    capacity: usize,
    #[serde(with = "blocks")]
    blocks: BTreeMap<usize, Box<[u8; BLOCK]>>,
    state: State,
    address: u16,
    block_length: u32,
    wide: bool,
    escaped: bool,
    streaming: Option<Streaming>,
    programming_until: Option<VirtualNanos>,
    commanded: Vec<(u8, u32)>,
    answer_corrupt: bool,
}

/// The blocks written, for a snapshot, each as its bytes: serde stops at arrays of 32.
mod blocks {
    use std::collections::BTreeMap;

    use serde::{Deserialize, Deserializer, Serializer};

    use super::BLOCK;

    pub(super) fn serialize<S: Serializer>(
        blocks: &BTreeMap<usize, Box<[u8; BLOCK]>>,
        serializer: S,
    ) -> Result<S::Ok, S::Error> {
        serializer.collect_map(blocks.iter().map(|(index, block)| (index, &block[..])))
    }

    pub(super) fn deserialize<'de, D: Deserializer<'de>>(
        deserializer: D,
    ) -> Result<BTreeMap<usize, Box<[u8; BLOCK]>>, D::Error> {
        BTreeMap::<usize, Vec<u8>>::deserialize(deserializer)?
            .into_iter()
            .map(|(index, block)| {
                let read = block.len();
                block
                    .into_boxed_slice()
                    .try_into()
                    .map(|block| (index, block))
                    .map_err(|_short| serde::de::Error::invalid_length(read, &"a block"))
            })
            .collect()
    }
}

/// What `ACMD41` answers: the operating range, with the power-up done, 31.4.3.
///
/// Bit 31 is the card saying it has finished its power-up sequence, which is what a host polls this
/// command for. The range bits below it are the windows 31.4.3 has the host check against its own
/// supply.
const OPERATING_RANGE: u32 = 0x8010_0000;

/// The programming a block write takes before the card will take another, 31.4.5.
///
/// The page gives no number, because programming time is the card's own and varies by part. So this
/// is the model's, chosen small enough that a firmware polling for it can't be said to be waiting
/// on the rig, and large enough that a firmware which doesn't poll at all is caught. It's one
/// microsecond, and it's said here and nowhere else.
const PROGRAMMING: VirtualNanos = VirtualNanos(1_000);

impl MemoryCard {
    /// A card of `blocks` blocks, every byte zero.
    ///
    /// # Panics
    ///
    /// Panics when `blocks` is zero, which isn't a card.
    #[must_use]
    pub fn empty(blocks: usize) -> Self {
        assert!(blocks > 0, "a card has at least one block");
        Self {
            capacity: blocks,
            blocks: BTreeMap::new(),
            state: State::Idle,
            address: 0,
            block_length: BLOCK_LENGTH,
            wide: false,
            escaped: false,
            streaming: None,
            programming_until: None,
            commanded: Vec::new(),
            answer_corrupt: false,
        }
    }

    /// A card whose blocks start as `contents`, rounded up to a whole block.
    ///
    /// This is what a board with an image on its card is built with, and what a test that wants to
    /// read something it didn't write uses.
    ///
    /// # Panics
    ///
    /// Panics when `contents` is empty, which isn't a card.
    #[must_use]
    pub fn holding(contents: &[u8]) -> Self {
        assert!(!contents.is_empty(), "a card has at least one block");
        let blocks = contents.len().div_ceil(BLOCK);
        let mut card = Self::empty(blocks);
        for (index, chunk) in contents.chunks(BLOCK).enumerate() {
            card.block_mut(index)[..chunk.len()].copy_from_slice(chunk);
        }
        card
    }

    /// A card of `blocks` blocks carrying an empty FAT32 volume, which is what a board's card holds when
    /// a firmware can mount but not format.
    ///
    /// # Panics
    ///
    /// Panics when `blocks` is fewer than FAT32 can hold, which isn't a card a board carries.
    #[must_use]
    pub fn formatted(blocks: usize) -> Self {
        let mut card = Self::empty(blocks);
        for (index, sector) in fat32::volume(blocks) {
            *card.block_mut(index) = sector;
        }
        card
    }

    fn block_mut(&mut self, index: usize) -> &mut [u8; BLOCK] {
        self.blocks
            .entry(index)
            .or_insert_with(|| Box::new([0; BLOCK]))
    }

    /// Makes every block this card gives fail its check, which is what a controller reads as `DCRCFAIL`.
    ///
    /// A card can't be asked to corrupt itself. This is the bench asking, so the error a controller
    /// must raise has a condition to be raised by. Nothing in 31.4 describes it, and nothing
    /// should. It's a fault a real card has and a model has to be told to have.
    pub fn corrupt_every_block(&mut self, corrupt: bool) {
        self.answer_corrupt = corrupt;
    }

    /// Where the card is in 31.4.11's `CURRENT_STATE`.
    #[must_use]
    pub fn state(&self) -> State {
        self.state
    }

    /// The bus width `ACMD6` last set, 31.4.9.
    #[must_use]
    pub fn wide(&self) -> bool {
        self.wide
    }

    /// The card status register every short answer carries, 31.4.11.
    ///
    /// Bits 12:9 are `CURRENT_STATE` and bit 8 is `READY_FOR_DATA`. Bit 5 is `APP_CMD`, which the
    /// page has the card set while it expects an application command.
    fn status(&self) -> u32 {
        let status = status::CURRENT_STATE.set(0, self.state as u64);
        let status = status::READY_FOR_DATA.set(status, 1);
        let status = status::APP_CMD.set(status, u64::from(self.escaped));
        u32::try_from(status).expect("the fields are inside 32 bits")
    }

    /// The card-specific data of 31.4.4, whose size fields are what a host reads its capacity from.
    ///
    /// The second version of the structure, which gives the size as a count of half-megabytes less one in
    /// bits 69:48, so a host multiplies rather than shifts. Everything else is the fixed pattern the
    /// header's second table records.
    fn card_specific(&self) -> [u32; 4] {
        let half_megabytes =
            u32::try_from(self.capacity / (512 * 1024 / BLOCK)).unwrap_or(u32::MAX);
        let size = half_megabytes.saturating_sub(1);
        [
            0x400E_0032,
            0x5B59_0000 | (size >> 16),
            (size & 0xFFFF) << 16,
            0x0A40_0001,
        ]
    }

    /// Where a command's argument points, as a block index into the card.
    ///
    /// The second version of the specification addresses by block rather than by byte, which is what the
    /// card-specific data above tells the host it is.
    fn offset(&self, argument: u32) -> Option<usize> {
        let block = argument as usize;
        (block < self.capacity).then_some(block)
    }
}

store!(MemoryCard);

impl Card for MemoryCard {
    fn command(&mut self, index: u8, argument: u32, context: &mut Timeline<'_, '_>) -> Answer {
        self.commanded.push((index, argument));
        if self
            .programming_until
            .is_some_and(|until| context.now() >= until)
        {
            self.programming_until = None;
            if self.state == State::Programming {
                self.state = State::Transfer;
            }
        }
        let escaped = std::mem::take(&mut self.escaped);
        if escaped {
            return self.application_command(index, argument);
        }
        match index {
            command::GO_IDLE_STATE => {
                self.state = State::Idle;
                self.streaming = None;
                self.escaped = false;
                Answer::None
            }
            command::ALL_SEND_CID if self.state == State::Ready => {
                self.state = State::Identification;
                Answer::Long([0x0353_4453, 0x4330_3847, 0x3080_1234, 0x0115_8000])
            }
            command::SET_RELATIVE_ADDR if self.state == State::Identification => {
                self.address = 0x0001;
                self.state = State::Standby;
                Answer::Short(u32::from(self.address) << 16)
            }
            command::SEND_CSD if self.state == State::Standby => Answer::Long(self.card_specific()),
            command::SELECT_DESELECT_CARD => {
                // Section 31.4.9: selecting by an address that isn't this card's deselects it.
                self.state = if argument >> 16 == u32::from(self.address) && self.address != 0 {
                    State::Transfer
                } else {
                    State::Standby
                };
                Answer::Short(self.status())
            }
            command::SET_BLOCKLEN if self.state == State::Transfer => {
                self.block_length = argument;
                Answer::Short(self.status())
            }
            command::APP_CMD => {
                self.escaped = true;
                Answer::Short(self.status())
            }
            command::READ_SINGLE_BLOCK | command::READ_MULTIPLE_BLOCK
                if self.state == State::Transfer =>
            {
                let Some(block) = self.offset(argument) else {
                    return Answer::Short(self.status());
                };
                self.streaming = Some(Streaming {
                    block,
                    multiple: index == command::READ_MULTIPLE_BLOCK,
                });
                self.state = State::SendingData;
                Answer::Short(self.status())
            }
            command::WRITE_BLOCK | command::WRITE_MULTIPLE_BLOCK
                if self.state == State::Transfer =>
            {
                let Some(block) = self.offset(argument) else {
                    return Answer::Short(self.status());
                };
                self.streaming = Some(Streaming {
                    block,
                    multiple: index == command::WRITE_MULTIPLE_BLOCK,
                });
                self.state = State::ReceivingData;
                Answer::Short(self.status())
            }
            command::STOP_TRANSMISSION => {
                self.streaming = None;
                self.state = match self.state {
                    State::ReceivingData => {
                        self.programming_until =
                            Some(VirtualNanos(context.now().0 + PROGRAMMING.0));
                        State::Programming
                    }
                    _ => State::Transfer,
                };
                Answer::Short(self.status())
            }
            // `SEND_STATUS` is the status register and nothing else, 31.4.11. And 31.4.14 has a
            // card answer an index it has no definition for as an illegal command, which a host
            // reads in that same register rather than by waiting. So both are the status, and
            // neither is a silence.
            _ => Answer::Short(self.status()),
        }
    }

    fn busy(&self) -> Busy {
        self.programming_until.map_or(Busy::Ready, Busy::Until)
    }

    fn read(&mut self, block: &mut [u8]) -> Outcome {
        let Some(streaming) = self.streaming else {
            return Outcome::Ended;
        };
        if streaming.block >= self.capacity || block.len() > BLOCK {
            self.streaming = None;
            self.state = State::Transfer;
            return Outcome::Ended;
        }
        let stored = self.stored(streaming.block);
        block.copy_from_slice(&stored[..block.len()]);
        if streaming.multiple {
            self.streaming = Some(Streaming {
                block: streaming.block + 1,
                ..streaming
            });
        } else {
            self.streaming = None;
            self.state = State::Transfer;
        }
        if self.answer_corrupt {
            Outcome::Corrupt
        } else {
            Outcome::Whole
        }
    }

    fn write(&mut self, block: &[u8]) -> Outcome {
        let Some(streaming) = self.streaming else {
            return Outcome::Ended;
        };
        if streaming.block >= self.capacity || block.len() > BLOCK {
            self.streaming = None;
            self.state = State::Transfer;
            return Outcome::Ended;
        }
        self.block_mut(streaming.block)[..block.len()].copy_from_slice(block);
        if streaming.multiple {
            self.streaming = Some(Streaming {
                block: streaming.block + 1,
                ..streaming
            });
        } else {
            self.streaming = None;
            self.state = State::Transfer;
        }
        Outcome::Whole
    }

    fn commanded(&self) -> &[(u8, u32)] {
        &self.commanded
    }
}

impl MemoryCard {
    /// What the card holds at `block`, as a read would find it.
    #[must_use]
    pub fn stored(&self, block: usize) -> [u8; BLOCK] {
        self.blocks.get(&block).map_or([0; BLOCK], |held| **held)
    }

    /// The application commands of 31.4.14, which are only these when `APP_CMD` came first.
    fn application_command(&mut self, index: u8, argument: u32) -> Answer {
        match index {
            command::SD_SEND_OP_COND => {
                // Section 31.4.3: the host polls this until the card reports its power-up done.
                if self.state == State::Idle {
                    self.state = State::Ready;
                }
                Answer::Short(OPERATING_RANGE)
            }
            command::SET_BUS_WIDTH if self.state == State::Transfer => {
                // Section 31.4.9: `00` is one line and `10` is four.
                self.wide = argument & 0b11 == 0b10;
                Answer::Short(self.status())
            }
            // Section 31.4.14 has an index with no application definition handled as the standard
            // command. This card does that for `CMD7` only, and answers the rest with the status.
            _ => self.command_after_escape(index, argument),
        }
    }

    fn command_after_escape(&mut self, index: u8, argument: u32) -> Answer {
        match index {
            command::SELECT_DESELECT_CARD => {
                self.state = if argument >> 16 == u32::from(self.address) && self.address != 0 {
                    State::Transfer
                } else {
                    State::Standby
                };
                Answer::Short(self.status())
            }
            _ => Answer::Short(self.status()),
        }
    }
}

/// The empty FAT32 volume `FatFs` R0.14b's `f_mkfs` writes, sector by sector, for a single-partition card
/// with a 512-byte sector: the same fields at the same offsets, named as `ff.c` names them, so the reader
/// on the part meets what its own formatter would have left.
mod fat32 {
    use super::BLOCK;

    /// `ff.c`: the offsets of the boot sector's fields, `BS_` and `BPB_`, and of the FSINFO sector's,
    /// `FSI_`.
    const BS_JMP_BOOT: usize = 0;
    const BPB_BYTS_PER_SEC: usize = 11;
    const BPB_SEC_PER_CLUS: usize = 13;
    const BPB_RSVD_SEC_CNT: usize = 14;
    const BPB_NUM_FATS: usize = 16;
    const BPB_MEDIA: usize = 21;
    const BPB_SEC_PER_TRK: usize = 24;
    const BPB_NUM_HEADS: usize = 26;
    const BPB_TOT_SEC32: usize = 32;
    const BPB_FAT_SZ32: usize = 36;
    const BPB_ROOT_CLUS32: usize = 44;
    const BPB_FS_INFO32: usize = 48;
    const BPB_BK_BOOT_SEC32: usize = 50;
    const BS_DRV_NUM32: usize = 64;
    const BS_BOOT_SIG32: usize = 66;
    const BS_VOL_ID32: usize = 67;
    const BS_VOL_LAB32: usize = 71;
    const BS_55AA: usize = 510;
    const FSI_LEAD_SIG: usize = 0;
    const FSI_STRUC_SIG: usize = 484;
    const FSI_FREE_COUNT: usize = 488;
    const FSI_NXT_FREE: usize = 492;

    /// `f_mkfs`: what it writes into those fields for a FAT32 volume.
    const JUMP_AND_OEM: &[u8; 11] = b"\xEB\xFE\x90MSDOS5.0";
    const RESERVED_SECTORS: u16 = 32;
    const FATS: u8 = 2;
    const MEDIA: u8 = 0xF8;
    const SECTORS_PER_TRACK: u16 = 63;
    const HEADS: u16 = 255;
    const ROOT_CLUSTER: u32 = 2;
    const FSINFO_SECTOR: u16 = 1;
    const BACKUP_BOOT_SECTOR: u16 = 6;
    const BACKUP_FSINFO_SECTOR: usize = 7;
    const DRIVE_NUMBER: u8 = 0x80;
    const EXTENDED_BOOT_SIGNATURE: u8 = 0x29;
    const LABEL_AND_TYPE: &[u8; 19] = b"NO NAME    FAT32   ";
    const SIGNATURE: u16 = 0xAA55;
    const FSI_LEAD: u32 = 0x4161_5252;
    const FSI_STRUC: u32 = 0x6141_7272;
    const FAT_0: u32 = 0xFFFF_FFF8;
    const FAT_1: u32 = 0xFFFF_FFFF;
    const FAT_ROOT: u32 = 0x0FFF_FFFF;
    /// `f_mkfs`'s largest cluster, 64 sectors, which its table picks for any volume of 4 GiB or more.
    const SECTORS_PER_CLUSTER: u8 = 64;
    /// `ff.c`'s `MAX_FAT16`: a FAT32 volume has more clusters than this.
    const MIN_FAT32_CLUSTERS: usize = 0xFFF5;
    /// The volume serial number, which `f_mkfs` takes from the clock and this takes once.
    const VOLUME_SERIAL: u32 = 0x5249_474C;

    /// The sectors that differ from zero in a fresh volume of `sectors` sectors, by index.
    ///
    /// # Panics
    ///
    /// Panics on a volume with too few clusters to be FAT32.
    pub(super) fn volume(sectors: usize) -> Vec<(usize, [u8; BLOCK])> {
        let per_cluster = usize::from(SECTORS_PER_CLUSTER);
        let clusters_at_most = sectors / per_cluster;
        let fat_sectors = (clusters_at_most * 4 + 8).div_ceil(BLOCK);
        let reserved = usize::from(RESERVED_SECTORS);
        let data = reserved + usize::from(FATS) * fat_sectors;
        let clusters = (sectors - data) / per_cluster;
        assert!(clusters > MIN_FAT32_CLUSTERS, "too few clusters for FAT32");

        let mut boot = [0; BLOCK];
        boot[..JUMP_AND_OEM.len()].copy_from_slice(JUMP_AND_OEM);
        word(
            &mut boot,
            BPB_BYTS_PER_SEC,
            u16::try_from(BLOCK).expect("a sector's size"),
        );
        boot[BPB_SEC_PER_CLUS] = SECTORS_PER_CLUSTER;
        word(&mut boot, BPB_RSVD_SEC_CNT, RESERVED_SECTORS);
        boot[BPB_NUM_FATS] = FATS;
        dword(&mut boot, BPB_TOT_SEC32, sector_count(sectors));
        boot[BPB_MEDIA] = MEDIA;
        word(&mut boot, BPB_SEC_PER_TRK, SECTORS_PER_TRACK);
        word(&mut boot, BPB_NUM_HEADS, HEADS);
        dword(&mut boot, BS_VOL_ID32, VOLUME_SERIAL);
        dword(&mut boot, BPB_FAT_SZ32, sector_count(fat_sectors));
        dword(&mut boot, BPB_ROOT_CLUS32, ROOT_CLUSTER);
        word(&mut boot, BPB_FS_INFO32, FSINFO_SECTOR);
        word(&mut boot, BPB_BK_BOOT_SEC32, BACKUP_BOOT_SECTOR);
        boot[BS_DRV_NUM32] = DRIVE_NUMBER;
        boot[BS_BOOT_SIG32] = EXTENDED_BOOT_SIGNATURE;
        boot[BS_VOL_LAB32..BS_VOL_LAB32 + LABEL_AND_TYPE.len()].copy_from_slice(LABEL_AND_TYPE);
        word(&mut boot, BS_55AA, SIGNATURE);

        let mut info = [0; BLOCK];
        dword(&mut info, FSI_LEAD_SIG, FSI_LEAD);
        dword(&mut info, FSI_STRUC_SIG, FSI_STRUC);
        dword(&mut info, FSI_FREE_COUNT, sector_count(clusters - 1));
        dword(&mut info, FSI_NXT_FREE, ROOT_CLUSTER);
        word(&mut info, BS_55AA, SIGNATURE);

        let mut fat = [0; BLOCK];
        dword(&mut fat, 0, FAT_0);
        dword(&mut fat, 4, FAT_1);
        dword(&mut fat, 8, FAT_ROOT);

        vec![
            (BS_JMP_BOOT, boot),
            (usize::from(BACKUP_BOOT_SECTOR), boot),
            (usize::from(FSINFO_SECTOR), info),
            (BACKUP_FSINFO_SECTOR, info),
            (reserved, fat),
            (reserved + fat_sectors, fat),
        ]
    }

    fn sector_count(count: usize) -> u32 {
        u32::try_from(count).expect("a FAT32 volume counts in thirty-two bits")
    }

    fn word(sector: &mut [u8; BLOCK], at: usize, value: u16) {
        sector[at..at + 2].copy_from_slice(&value.to_le_bytes());
    }

    fn dword(sector: &mut [u8; BLOCK], at: usize, value: u32) {
        sector[at..at + 4].copy_from_slice(&value.to_le_bytes());
    }
}