rigless 0.0.5

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; a fork of QEMU is built in and executes the instructions
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The card end of a secure digital bus: the seam a controller calls, and a memory card that answers it.
//!
//! RM0090 rev 22 section 31.4 is the card, described from the host's side, and it is 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 is not one of this project's references; where a host sends
//! something 31.4.14 does not name, the table below says so rather than the model inventing a page.
//!
//! The bus is command and answer, not bits on a wire. A controller sends an index and an argument and takes
//! back a response, and a transfer moves whole blocks. Modelling the line coding would be a great deal of
//! work that nothing could observe, because the controller does not expose a bit either: 31.3.1 puts the
//! command path and the data path behind registers that speak in commands and blocks.
//!
//! | Behaviour | Source | Test |
//! |---|---|---|
//! | 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` resets it to idle, whatever it was doing | 31.4.2 | `a_reset_returns_the_card_to_idle_from_anywhere` |
//! | `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` answers the identification, long, and `CMD3` gives it an address | 31.4.4 | `a_card_walks_the_identification_the_manual_gives` |
//! | `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` 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` 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` and `CMD18` read one block and many; `CMD24` and `CMD25` write one and many; `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 every short answer carries, with `CURRENT_STATE` the field a driver reads | 31.4.11 | `every_answer_carries_the_state_the_card_is_in` |
//! | A block write takes a programming time the card is busy for, which `R1b` is how a host waits out | 31.4.5, 31.5.2 | `a_write_leaves_the_card_busy_for_the_time_it_programs` |
//! | 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: 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.**
//!
//! | Behaviour | 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 does not carry it, and the specification that does is not one of this project's references. A card that does not 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 behaviour 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 is not 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 does not have and would rather find than guess at |
//! | A wear-levelling or failure model | none | A card that returns what was written is the card a test wants. Failure is the injector's to add, and it has no ticket yet |

use std::collections::BTreeMap;
use std::fmt;

use crate::device::DeviceContext;
use crate::time::VirtualNanos;

/// Bytes in a block, the length a host sets with `CMD16` and the one every driver uses, 31.4.5.
pub const BLOCK: usize = 512;

/// The same length as the argument `CMD16` carries.
const BLOCK_LENGTH: u32 = 512;

/// What a card answers a command with.
///
/// A response is the card's whole reply; which registers the controller puts it in is the controller's
/// business and depends on what the host asked for, 31.9.4.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Answer {
    /// Nothing at all, which is a host waiting until its command times out. It is also a bench with no
    /// card in the slot, and a command a card does not implement.
    None,
    /// Forty-eight bits, of which the thirty-two the host reads are these; 31.5.1 and 31.5.4.
    Short(u32),
    /// One hundred and thirty-six bits, most significant word first; 31.5.3.
    Long([u32; 4]),
}

/// Whether the card is still doing what the last command asked, 31.4.5 and 31.5.2.
///
/// A block write is not done when the card answers: it programs, and says so by holding the line the host
/// watches. This is that line.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Busy {
    /// The card is ready for the next command.
    Ready,
    /// The card is programming and will be ready at this instant.
    Until(VirtualNanos),
}

/// What a block transfer did.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Outcome {
    /// The block crossed whole.
    Whole,
    /// The block crossed and its check does not hold, which a controller reads as a failed block rather
    /// than as a card that stopped answering.
    Corrupt,
    /// The card has no block to give, or will take no more.
    Ended,
}

/// The card end of a secure digital bus.
///
/// The controller calls this and never learns what is behind it; a card implements it and never learns
/// there is a controller. A bench with nothing in the slot has no card at all rather than one that answers
/// nothing, so that a firmware sees the part behave as it does with an empty slot.
pub trait Card: fmt::Debug + Send {
    /// The card's answer to `index` carrying `argument`, 31.4.14.
    ///
    /// `context` is the card's own, at the instant of the command, so a card that needs to know the time to
    /// answer — a write's programming, 31.4.5 — can ask for it.
    fn command(&mut self, index: u8, argument: u32, context: &DeviceContext<'_>) -> Answer;

    /// Whether the card is still busy with the last command, and until when.
    fn busy(&self) -> Busy {
        Busy::Ready
    }

    /// Fills `block` with the next block of a read the last command started.
    fn read(&mut self, block: &mut [u8]) -> Outcome;

    /// Takes `block` as the next block of a write the last command started.
    fn write(&mut self, block: &[u8]) -> Outcome;

    /// Every command the card was sent, oldest first, as index and argument.
    ///
    /// The card's own record, and the only thing that can say a host's sequence arrived: what the
    /// controller believes it sent is a thing a model that never reached its card fills just as happily.
    fn commanded(&self) -> &[(u8, u32)] {
        &[]
    }

    /// What the card holds at `block`, for a test to assert a write landed where a read would find it.
    fn stored(&self, block: usize) -> [u8; BLOCK] {
        let _ = block;
        [0; BLOCK]
    }
}

/// The states of 31.4.11's `CURRENT_STATE`, which every short answer carries.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
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 is not 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)]
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 does not.
#[derive(Debug)]
pub struct MemoryCard {
    capacity: usize,
    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 commands of 31.4.14 this card answers, by the index the manual gives each.
pub mod command {
    /// The software reset of 31.4.2.
    pub const GO_IDLE_STATE: u8 = 0;
    /// Step 5 of the identification of 31.4.4: every active card answers its identification.
    pub const ALL_SEND_CID: u8 = 2;
    /// Step 7 of the identification of 31.4.4: the card takes an address.
    pub const SET_RELATIVE_ADDR: u8 = 3;
    /// Step 1 of every transfer of 31.4.5 and 31.4.6.
    pub const SELECT_DESELECT_CARD: u8 = 7;
    /// The card-specific data, which is where a host reads the capacity.
    pub const SEND_CSD: u8 = 9;
    /// What ends a multiple-block transfer, 31.4.6.
    pub const STOP_TRANSMISSION: u8 = 12;
    /// The card status register of 31.4.11, which 31.4.5 has a host poll a write with.
    pub const SEND_STATUS: u8 = 13;
    /// Step 2 of every transfer of 31.4.5 and 31.4.6.
    pub const SET_BLOCKLEN: u8 = 16;
    /// One block, 31.4.6.
    pub const READ_SINGLE_BLOCK: u8 = 17;
    /// Consecutive blocks until `STOP_TRANSMISSION`, 31.4.6.
    pub const READ_MULTIPLE_BLOCK: u8 = 18;
    /// One block, 31.4.5.
    pub const WRITE_BLOCK: u8 = 24;
    /// Consecutive blocks until `STOP_TRANSMISSION`, 31.4.5.
    pub const WRITE_MULTIPLE_BLOCK: u8 = 25;
    /// The escape of 31.4.14: the next command is an application command.
    pub const APP_CMD: u8 = 55;
    /// Application commands, which 31.4.14 says are recognised only after `APP_CMD`.
    /// The wide bus of 31.4.9, valid only in the transfer state.
    pub const SET_BUS_WIDTH: u8 = 6;
    /// Step 2 of the secure digital identification of 31.4.4, the operating range.
    pub const SD_SEND_OP_COND: u8 = 41;
}

/// 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 — 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 cannot be said to be waiting on the rig and
/// large enough that a firmware which does not poll at all is caught. It is one microsecond and it is 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 is not 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 did not write uses.
    ///
    /// # Panics
    ///
    /// Panics when `contents` is empty, which is not 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 is not 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 cannot be asked to corrupt itself; this is the bench asking, so that the error a controller
    /// must raise has a condition to be raised by. Nothing in 31.4 describes it, and nothing should: it is
    /// 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 ready = 1 << 8;
        let escaped = u32::from(self.escaped) << 5;
        ((self.state as u32) << 9) | ready | escaped
    }

    /// 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)
    }
}

impl Card for MemoryCard {
    fn command(&mut self, index: u8, argument: u32, context: &DeviceContext<'_>) -> 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 is not 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
    }

    fn stored(&self, block: usize) -> [u8; BLOCK] {
        self.blocks.get(&block).map_or([0; BLOCK], |held| **held)
    }
}

impl MemoryCard {
    /// 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: an index with no application definition is handled as the standard command.
            _ => 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());
    }
}