norbert 0.1.1

A patient SPI-NOR flasher for the Pico de Gallo: read JEDEC/SFDP, erase, program, verify, and boot bitstreams.
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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
//! Hardware-agnostic iCE40HX8K-EVB SPI-NOR flashing core.

use core::fmt;
use embedded_hal_async::spi::{Operation, SpiDevice};
use std::time::Duration;

use crate::catalog::lookup_fallback;
use crate::profile::{AddressWidth, EraseMenu, ErasePlan, FlashProfile, ProfileSource, plan_erase};
use crate::sfdp::{Bfpt, ParamHeader, SfdpHeader};

// Universal SPI-NOR opcodes (M25P16 / EN25QH16B / W25Q16).
const CMD_RDID: u8 = 0x9F;
const CMD_WREN: u8 = 0x06;
const CMD_WRSR: u8 = 0x01; // write status register (clears block-protect bits)
const CMD_RDSR: u8 = 0x05;
const CMD_READ: u8 = 0x03;
const CMD_PP: u8 = 0x02;
const CMD_CE: u8 = 0xC7; // chip erase
const CMD_SFDP: u8 = 0x5A; // read SFDP parameter space
const CMD_EN4B: u8 = 0xB7; // enter 4-byte addressing mode
const CMD_RSTEN: u8 = 0x66; // enable reset
const CMD_RST: u8 = 0x99; // software reset
const CMD_RELEASE_PD: u8 = 0xAB; // Release from Deep Power-Down
const SR_WIP: u8 = 0x01;
const SR_BP_MASK: u8 = 0x1C; // BP0..BP2 (typical)

/// Append `opcode` + a 3- or 4-byte big-endian address.
fn push_cmd_addr(cmd: &mut Vec<u8>, opcode: u8, addr: u32, width: AddressWidth) {
    cmd.push(opcode);
    if width.is_four_byte() {
        cmd.push((addr >> 24) as u8);
    }
    cmd.push((addr >> 16) as u8);
    cmd.push((addr >> 8) as u8);
    cmd.push(addr as u8);
}

/// 256-byte program page.
pub const PAGE_SIZE: usize = 256;

/// JEDEC RDID (0x9F) response.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FlashId {
    pub manufacturer: u8,
    pub mem_type: u8,
    pub capacity_code: u8,
}

impl FlashId {
    /// Density in bytes = `2^capacity_code`; `None` for implausible codes.
    pub fn capacity_bytes(&self) -> Option<usize> {
        match self.capacity_code {
            0x10..=0x1B => Some(1usize << self.capacity_code),
            _ => None,
        }
    }

    /// True if a chip actually responded to RDID (an idle/floating bus reads
    /// all `0x00` or all `0xFF`).
    pub fn is_present(&self) -> bool {
        self.manufacturer != 0x00 && self.manufacturer != 0xFF
    }

    pub fn jedec(&self) -> [u8; 3] {
        [self.manufacturer, self.mem_type, self.capacity_code]
    }
}

impl fmt::Display for FlashId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "mfr=0x{:02X} type=0x{:02X} cap=0x{:02X}",
            self.manufacturer, self.mem_type, self.capacity_code
        )?;
        if let Some(n) = self.capacity_bytes() {
            write!(f, " ({} KiB)", n / 1024)?;
        }
        Ok(())
    }
}

/// Holds another bus master off the shared SPI while we program, then releases it.
///
/// `acquire` must make the flash's SPI bus exclusively ours; `release` returns
/// control. For a bare chip / clip this is a no-op. For a shared bus
/// it is a GPIO held at a level (the device layer's `HostBus`) — e.g. the iCE40 CRESET driven low
/// to tri-state the FPGA's SPI pins, then driven high on release so it reconfigures.
pub trait BusAccess {
    type Error: fmt::Debug;
    fn acquire(&mut self) -> Result<(), Self::Error>;
    fn release(&mut self) -> Result<(), Self::Error>;
}

/// Flasher errors, generic over the SPI and bus-access error types.
#[derive(Debug)]
pub enum FlashError<S: fmt::Debug, R: fmt::Debug> {
    Spi(S),
    Bus(R),
    Timeout,
    VerifyMismatch {
        addr: usize,
        expected: u8,
        got: u8,
    },
    /// RDID read nothing — no chip on the bus.
    NoFlash,
    /// A chip responded but has no SFDP and no fallback-table entry.
    UnsupportedChip {
        jedec: [u8; 3],
    },
    /// A geometry op was attempted before `detect_profile` succeeded.
    NotDetected,
}

impl<S: fmt::Debug, R: fmt::Debug> fmt::Display for FlashError<S, R> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FlashError::Spi(e) => write!(f, "SPI error: {e:?}"),
            FlashError::Bus(e) => write!(f, "bus-hold error: {e:?}"),
            FlashError::Timeout => write!(f, "timed out waiting for flash WIP to clear"),
            FlashError::VerifyMismatch {
                addr,
                expected,
                got,
            } => write!(
                f,
                "verify mismatch @0x{addr:06X}: expected 0x{expected:02X}, got 0x{got:02X}"
            ),
            FlashError::NoFlash => write!(f, "no SPI-NOR flash detected (RDID read all 0x00/0xFF)"),
            FlashError::UnsupportedChip { jedec } => write!(
                f,
                "unsupported flash: JEDEC {jedec:02X?} has no SFDP and no fallback-table entry (add one)"
            ),
            FlashError::NotDetected => write!(f, "flash geometry unknown; run `detect` first"),
        }
    }
}
impl<S: fmt::Debug, R: fmt::Debug> std::error::Error for FlashError<S, R> {}

/// SPI-NOR flasher over an `embedded-hal` `SpiDevice` and a `BusAccess` line.
pub struct Flasher<SPI, RST> {
    spi: SPI,
    reset: RST,
    max_chunk: usize,
    poll_interval: Duration,
    poll_timeout: Duration,
    profile: Option<FlashProfile>,
}

impl<SPI, RST> Flasher<SPI, RST>
where
    SPI: SpiDevice,
    RST: BusAccess,
{
    /// `max_chunk` bounds bytes per USB SPI op; all writes/reads are split to it
    /// *within* a single CS transaction, so any value >= 4 is correct.
    pub fn with_config(
        spi: SPI,
        reset: RST,
        max_chunk: usize,
        poll_interval: Duration,
        poll_timeout: Duration,
    ) -> Self {
        assert!(max_chunk >= 4, "max_chunk must be >= 4");
        Self {
            spi,
            reset,
            max_chunk,
            poll_interval,
            poll_timeout,
            profile: None,
        }
    }

    fn spi_err(e: SPI::Error) -> FlashError<SPI::Error, RST::Error> {
        FlashError::Spi(e)
    }
    fn bus_err(e: RST::Error) -> FlashError<SPI::Error, RST::Error> {
        FlashError::Bus(e)
    }

    /// Read the JEDEC ID (0x9F).
    pub async fn read_id(&mut self) -> Result<FlashId, FlashError<SPI::Error, RST::Error>> {
        let mut id = [0u8; 3];
        self.spi
            .transaction(&mut [Operation::Write(&[CMD_RDID]), Operation::Read(&mut id)])
            .await
            .map_err(Self::spi_err)?;
        Ok(FlashId {
            manufacturer: id[0],
            mem_type: id[1],
            capacity_code: id[2],
        })
    }

    /// Read `buf.len()` bytes from SFDP space at `addr`
    /// (0x5A + 24-bit addr + 8 dummy cycles).
    pub async fn read_sfdp(
        &mut self,
        addr: u32,
        buf: &mut [u8],
    ) -> Result<(), FlashError<SPI::Error, RST::Error>> {
        let a = addr.to_be_bytes();
        let header = [CMD_SFDP, a[1], a[2], a[3], 0x00]; // trailing byte = 8 dummy cycles
        self.spi
            .transaction(&mut [Operation::Write(&header), Operation::Read(buf)])
            .await
            .map_err(Self::spi_err)
    }

    async fn write_enable(&mut self) -> Result<(), FlashError<SPI::Error, RST::Error>> {
        self.spi
            .transaction(&mut [Operation::Write(&[CMD_WREN])])
            .await
            .map_err(Self::spi_err)
    }

    /// Switch the device to 32-bit addressing (needed for >16 MB parts).
    async fn enter_4byte(&mut self) -> Result<(), FlashError<SPI::Error, RST::Error>> {
        self.spi
            .transaction(&mut [Operation::Write(&[CMD_EN4B])])
            .await
            .map_err(Self::spi_err)
    }

    async fn read_status(&mut self) -> Result<u8, FlashError<SPI::Error, RST::Error>> {
        let mut sr = [0u8; 1];
        self.spi
            .transaction(&mut [Operation::Write(&[CMD_RDSR]), Operation::Read(&mut sr)])
            .await
            .map_err(Self::spi_err)?;
        Ok(sr[0])
    }

    /// Poll RDSR until WIP clears, sleeping `poll_interval` between polls.
    /// Bounded by `poll_timeout` via `tokio::time::timeout`.
    async fn wait_ready(&mut self) -> Result<(), FlashError<SPI::Error, RST::Error>> {
        let poll_timeout = self.poll_timeout;
        let poll = async {
            loop {
                if self.read_status().await? & SR_WIP == 0 {
                    return Ok::<(), FlashError<SPI::Error, RST::Error>>(());
                }
                tokio::time::sleep(self.poll_interval).await;
            }
        };
        match tokio::time::timeout(poll_timeout, poll).await {
            Ok(r) => r,
            Err(_) => Err(FlashError::Timeout),
        }
    }

    /// Active flash profile, or `None` until `detect_profile` succeeds.
    pub fn profile(&self) -> Option<&FlashProfile> {
        self.profile.as_ref()
    }
    pub fn set_profile(&mut self, profile: FlashProfile) {
        self.profile = Some(profile);
    }

    fn require_profile(&self) -> Result<&FlashProfile, FlashError<SPI::Error, RST::Error>> {
        self.profile.as_ref().ok_or(FlashError::NotDetected)
    }

    /// Resolve how to talk to the flash and store the profile in `self`:
    /// RDID (absent → `NoFlash`) → SFDP → JEDEC fallback table → else
    /// `UnsupportedChip`. **Never guesses.** Requires the bus (call while acquired).
    pub async fn detect_profile(
        &mut self,
    ) -> Result<FlashProfile, FlashError<SPI::Error, RST::Error>> {
        let id = self.read_id().await?;
        if !id.is_present() {
            return Err(FlashError::NoFlash);
        }
        // 1) The chip describes itself.
        if let Some(profile) = self.try_sfdp_profile(id).await? {
            return self.adopt_profile(profile).await;
        }
        // 2) A known no-SFDP part.
        if let Some(profile) = lookup_fallback(id.jedec()) {
            return self.adopt_profile(profile).await;
        }
        // 3) Present but unknown → don't guess.
        Err(FlashError::UnsupportedChip { jedec: id.jedec() })
    }

    /// Store `profile` in `self`, first putting >16 MB parts into 4-byte
    /// addressing so subsequent read/erase/program headers match.
    async fn adopt_profile(
        &mut self,
        profile: FlashProfile,
    ) -> Result<FlashProfile, FlashError<SPI::Error, RST::Error>> {
        if profile.address_width.is_four_byte() {
            self.enter_4byte().await?;
        }
        self.set_profile(profile.clone());
        Ok(profile)
    }

    /// Build a profile from SFDP; `Ok(None)` if the chip has no usable SFDP.
    async fn try_sfdp_profile(
        &mut self,
        id: FlashId,
    ) -> Result<Option<FlashProfile>, FlashError<SPI::Error, RST::Error>> {
        let mut header = [0u8; 8];
        self.read_sfdp(0, &mut header).await?;
        let Some(h) = SfdpHeader::parse(&header) else {
            return Ok(None);
        };

        let mut bfpt_ph = None;
        for i in 0..h.param_header_count() {
            let mut ph = [0u8; 8];
            self.read_sfdp(8 + (i as u32) * 8, &mut ph).await?;
            if let Some(p) = ParamHeader::parse(&ph)
                && p.id == ParamHeader::BFPT_ID
            {
                bfpt_ph = Some(p);
                break;
            }
        }
        let Some(p) = bfpt_ph else {
            return Ok(None);
        };

        let mut bytes = vec![0u8; p.length_dwords as usize * 4];
        self.read_sfdp(p.table_pointer, &mut bytes).await?;
        let bfpt = Bfpt::parse(&bytes);
        let Some(erase) = EraseMenu::new(bfpt.erase_types) else {
            return Ok(None); // SFDP present but no usable erase menu → fall through to the table
        };
        Ok(Some(FlashProfile {
            page_size: bfpt.page_size,
            address_width: bfpt.address_width,
            capacity: bfpt.capacity.or(id.capacity_bytes()),
            erase,
            source: ProfileSource::Sfdp,
            sfdp_revision: Some((h.major, h.minor)),
        }))
    }

    /// Erase one block/sector at `addr` using erase `opcode`.
    async fn erase_op(
        &mut self,
        addr: u32,
        opcode: u8,
    ) -> Result<(), FlashError<SPI::Error, RST::Error>> {
        let width = self.require_profile()?.address_width;
        self.write_enable().await?;
        let mut header = Vec::with_capacity(1 + width.bytes() as usize);
        push_cmd_addr(&mut header, opcode, addr, width);
        self.spi
            .transaction(&mut [Operation::Write(&header)])
            .await
            .map_err(Self::spi_err)?;
        self.wait_ready().await
    }

    /// Erase the whole device (0xC7). Slowest but universally supported.
    pub async fn chip_erase(&mut self) -> Result<(), FlashError<SPI::Error, RST::Error>> {
        self.write_enable().await?;
        self.spi
            .transaction(&mut [Operation::Write(&[CMD_CE])])
            .await
            .map_err(Self::spi_err)?;
        self.wait_ready().await
    }

    /// Clear status-register block-protection bits (WREN + WRSR 0x00).
    pub async fn unprotect(&mut self) -> Result<(), FlashError<SPI::Error, RST::Error>> {
        self.write_enable().await?;
        self.spi
            .transaction(&mut [Operation::Write(&[CMD_WRSR, 0x00])])
            .await
            .map_err(Self::spi_err)?;
        self.wait_ready().await
    }

    /// True if any block-protect bit is set.
    pub async fn is_protected(&mut self) -> Result<bool, FlashError<SPI::Error, RST::Error>> {
        Ok(self.read_status().await? & SR_BP_MASK != 0)
    }

    /// Set block-protection (WREN + WRSR with BP bits set).
    pub async fn protect(&mut self) -> Result<(), FlashError<SPI::Error, RST::Error>> {
        self.write_enable().await?;
        self.spi
            .transaction(&mut [Operation::Write(&[CMD_WRSR, SR_BP_MASK])])
            .await
            .map_err(Self::spi_err)?;
        self.wait_ready().await
    }

    /// Flash software reset: 0x66 (enable) then 0x99 (reset).
    pub async fn reset_flash(&mut self) -> Result<(), FlashError<SPI::Error, RST::Error>> {
        self.spi
            .transaction(&mut [Operation::Write(&[CMD_RSTEN])])
            .await
            .map_err(Self::spi_err)?;
        self.spi
            .transaction(&mut [Operation::Write(&[CMD_RST])])
            .await
            .map_err(Self::spi_err)
    }

    /// Compute the erase plan covering `[offset, offset+len)` from the detected profile.
    pub fn erase_plan(
        &self,
        offset: usize,
        len: usize,
    ) -> Result<ErasePlan, FlashError<SPI::Error, RST::Error>> {
        Ok(plan_erase(self.require_profile()?, offset, len))
    }

    /// Execute a precomputed plan, calling `progress(blocks_done)` after each op.
    pub async fn run_erase(
        &mut self,
        plan: &ErasePlan,
        mut progress: impl FnMut(usize),
    ) -> Result<(), FlashError<SPI::Error, RST::Error>> {
        for (i, op) in plan.ops().iter().enumerate() {
            self.erase_op(op.addr as u32, op.ty.opcode).await?;
            progress(i + 1);
        }
        Ok(())
    }

    /// Erase every block overlapping `[offset, offset+len)` (plan then execute).
    pub async fn erase_range(
        &mut self,
        offset: usize,
        len: usize,
    ) -> Result<(), FlashError<SPI::Error, RST::Error>> {
        let plan = self.erase_plan(offset, len)?;
        self.run_erase(&plan, |_| {}).await
    }

    async fn page_program(
        &mut self,
        addr: u32,
        data: &[u8],
    ) -> Result<(), FlashError<SPI::Error, RST::Error>> {
        let width = self.require_profile()?.address_width;
        self.write_enable().await?;
        let mut header = Vec::with_capacity(1 + width.bytes() as usize);
        push_cmd_addr(&mut header, CMD_PP, addr, width);
        let mut ops: Vec<Operation<'_, u8>> =
            Vec::with_capacity(1 + data.len() / self.max_chunk + 1);
        ops.push(Operation::Write(&header));
        for chunk in data.chunks(self.max_chunk) {
            ops.push(Operation::Write(chunk));
        }
        self.spi
            .transaction(&mut ops)
            .await
            .map_err(Self::spi_err)?;
        self.wait_ready().await
    }

    /// Program `data` at `offset`, splitting on the profile's page boundaries.
    /// `progress(bytes_written)` is called after each page.
    pub async fn program(
        &mut self,
        offset: usize,
        data: &[u8],
        mut progress: impl FnMut(usize),
    ) -> Result<(), FlashError<SPI::Error, RST::Error>> {
        let page = self.require_profile()?.page_size;
        let mut written = 0;
        while written < data.len() {
            let addr = offset + written;
            let page_left = page - (addr % page);
            let n = page_left.min(data.len() - written);
            self.page_program(addr as u32, &data[written..written + n])
                .await?;
            written += n;
            progress(written);
        }
        Ok(())
    }

    /// Read `buf.len()` bytes starting at `offset`, in `max_chunk` units.
    pub async fn read(
        &mut self,
        offset: usize,
        buf: &mut [u8],
    ) -> Result<(), FlashError<SPI::Error, RST::Error>> {
        let width = self.require_profile()?.address_width;
        let mut done = 0;
        while done < buf.len() {
            let mut header = Vec::with_capacity(1 + width.bytes() as usize);
            push_cmd_addr(&mut header, CMD_READ, (offset + done) as u32, width);
            let n = self.max_chunk.min(buf.len() - done);
            self.spi
                .transaction(&mut [
                    Operation::Write(&header),
                    Operation::Read(&mut buf[done..done + n]),
                ])
                .await
                .map_err(Self::spi_err)?;
            done += n;
        }
        Ok(())
    }

    /// Read back and compare against `expected`. `progress(bytes_verified)` per chunk.
    pub async fn verify(
        &mut self,
        offset: usize,
        expected: &[u8],
        mut progress: impl FnMut(usize),
    ) -> Result<(), FlashError<SPI::Error, RST::Error>> {
        let mut done = 0;
        let mut buf = vec![0u8; self.max_chunk];
        while done < expected.len() {
            let n = self.max_chunk.min(expected.len() - done);
            self.read(offset + done, &mut buf[..n]).await?;
            for i in 0..n {
                if buf[i] != expected[done + i] {
                    return Err(FlashError::VerifyMismatch {
                        addr: offset + done + i,
                        expected: expected[done + i],
                        got: buf[i],
                    });
                }
            }
            done += n;
            progress(done);
        }
        Ok(())
    }

    /// Release the flash from Deep Power-Down (0xAB), then wait tRES1.
    ///
    /// An iCE40 (and similar) puts its configuration flash into deep power-down
    /// after loading its bitstream; in that state the flash ignores every command
    /// except 0xAB. This is a no-op on a flash that is already awake.
    pub async fn wake(&mut self) -> Result<(), FlashError<SPI::Error, RST::Error>> {
        self.spi
            .transaction(&mut [Operation::Write(&[CMD_RELEASE_PD])])
            .await
            .map_err(Self::spi_err)?;
        // tRES1 is ~3 us on a W25Q; a USB round-trip already covers it, but be explicit.
        tokio::time::sleep(Duration::from_micros(50)).await;
        Ok(())
    }

    /// Take the shared bus (hold any other master off) and wake the flash from
    /// Deep Power-Down, so a flash the FPGA put to sleep after config responds.
    pub async fn acquire_bus(&mut self) -> Result<(), FlashError<SPI::Error, RST::Error>> {
        self.reset.acquire().map_err(Self::bus_err)?;
        if let Err(e) = self.wake().await {
            let _ = self.release_bus(); // don't leave the held master stuck in reset
            return Err(e);
        }
        Ok(())
    }

    /// Release CRESET (driven high) so the FPGA reconfigures from flash.
    pub fn release_bus(&mut self) -> Result<(), FlashError<SPI::Error, RST::Error>> {
        self.reset.release().map_err(Self::bus_err)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use super::testfakes::{FakeBus, FakeFlash, flasher};

    /// 64 KiB erase block (test reference constant; production geometry comes from FlashProfile).
    const BLOCK_SIZE: usize = 64 * 1024;

    #[test]
    fn capacity_decode() {
        let id = FlashId {
            manufacturer: 0x20,
            mem_type: 0x20,
            capacity_code: 0x15,
        };
        assert_eq!(id.capacity_bytes(), Some(2 * 1024 * 1024)); // 16 Mbit = 2 MiB
        let bad = FlashId {
            manufacturer: 0,
            mem_type: 0,
            capacity_code: 0x00,
        };
        assert_eq!(bad.capacity_bytes(), None);
    }

    #[tokio::test]
    async fn read_id_returns_jedec() {
        let flash = FakeFlash::new(2 * 1024 * 1024, [0x20, 0x20, 0x15]);
        let mut f = flasher(flash, FakeBus::new(), 256);
        let id = f.read_id().await.unwrap();
        assert_eq!(
            id,
            FlashId {
                manufacturer: 0x20,
                mem_type: 0x20,
                capacity_code: 0x15
            }
        );
        assert_eq!(id.capacity_bytes(), Some(2 * 1024 * 1024));
    }

    #[tokio::test]
    async fn wait_ready_polls_until_wip_clears() {
        let flash = FakeFlash::new(1024, [0x20, 0x20, 0x15]);
        flash.set_busy_reads(3); // WIP=1 for 3 RDSR calls, then clears
        let mut f = flasher(flash, FakeBus::new(), 256);
        f.write_enable().await.unwrap();
        assert_eq!(f.read_status().await.unwrap() & 0x02, 0x02); // WEL set
        f.wait_ready().await.unwrap(); // consumes the 3 busy reads, then returns Ok
    }

    #[tokio::test]
    async fn wait_ready_times_out() {
        let flash = FakeFlash::new(1024, [0x20, 0x20, 0x15]);
        flash.set_busy_reads(u32::MAX); // never clears
        let mut f =
            Flasher::with_config(flash, FakeBus::new(), 256, Duration::ZERO, Duration::ZERO);
        assert!(matches!(f.wait_ready().await, Err(FlashError::Timeout)));
    }

    #[tokio::test]
    async fn erase_range_sets_ff_across_covered_blocks() {
        let size = 256 * 1024; // 4 blocks
        let flash = FakeFlash::new(size, [0x20, 0x20, 0x15]);
        for i in 0..size {
            flash.preset(i, &[0x00]);
        } // dirty everything
        let probe = flash.clone();
        let mut f = flasher(flash, FakeBus::new(), 256);

        // A 1-byte image at offset 100 must erase exactly block 0 (0..64K).
        f.erase_range(100, 1).await.unwrap();
        let mem = probe.mem();
        assert!(mem[0..BLOCK_SIZE].iter().all(|&b| b == 0xFF)); // block 0 erased
        assert!(mem[BLOCK_SIZE..].iter().all(|&b| b == 0x00)); // block 1+ untouched
    }

    #[tokio::test]
    async fn chip_erase_clears_all() {
        let flash = FakeFlash::new(BLOCK_SIZE, [0x20, 0x20, 0x15]);
        for i in 0..BLOCK_SIZE {
            flash.preset(i, &[0x00]);
        }
        let probe = flash.clone();
        let mut f = flasher(flash, FakeBus::new(), 256);
        f.chip_erase().await.unwrap();
        assert!(probe.mem().iter().all(|&b| b == 0xFF));
    }

    #[tokio::test]
    async fn program_crossing_page_and_small_chunks() {
        let flash = FakeFlash::new(64 * 1024, [0x20, 0x20, 0x15]);
        let probe = flash.clone();
        // max_chunk = 8 forces multi-op writes within a page program.
        let mut f = flasher(flash, FakeBus::new(), 8);

        // 300 bytes starting at 250 → crosses the 256 boundary (pages 0 and 1).
        let data: Vec<u8> = (0..300).map(|i| (i % 251) as u8).collect();
        f.erase_range(0, 300).await.unwrap();
        f.program(250, &data, |_| {}).await.unwrap();

        assert_eq!(&probe.mem()[250..250 + 300], &data[..]);
        // Byte just before the write is still erased.
        assert_eq!(probe.mem()[249], 0xFF);
    }

    #[tokio::test]
    async fn read_back_and_verify() {
        let flash = FakeFlash::new(64 * 1024, [0x20, 0x20, 0x15]);
        let mut f = flasher(flash, FakeBus::new(), 8); // tiny chunk exercises splitting
        let data: Vec<u8> = (0..500).map(|i| (i * 7 % 256) as u8).collect();
        f.erase_range(0, 500).await.unwrap();
        f.program(0, &data, |_| {}).await.unwrap();

        let mut buf = vec![0u8; 500];
        f.read(0, &mut buf).await.unwrap();
        assert_eq!(buf, data);

        f.verify(0, &data, |_| {}).await.unwrap();

        // A mismatch is reported with the absolute address.
        let mut wrong = data.clone();
        wrong[123] ^= 0xFF;
        match f.verify(0, &wrong, |_| {}).await {
            Err(FlashError::VerifyMismatch { addr, .. }) => assert_eq!(addr, 123),
            other => panic!("expected mismatch, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn erase_uses_profile_small_sector_at_tail() {
        use crate::profile::{AddressWidth, EraseMenu, EraseType, FlashProfile, ProfileSource};
        let size = 256 * 1024;
        let flash = FakeFlash::new(size, [0xEF, 0x40, 0x15]);
        for i in 0..size {
            flash.preset(i, &[0x00]);
        }
        let probe = flash.clone();
        let mut f = flasher(flash, FakeBus::new(), 256);
        f.set_profile(FlashProfile {
            page_size: 256,
            address_width: AddressWidth::Three,
            capacity: Some(size),
            erase: EraseMenu::new(vec![
                EraseType {
                    size: 64 * 1024,
                    opcode: 0xD8,
                },
                EraseType {
                    size: 4 * 1024,
                    opcode: 0x20,
                },
            ])
            .unwrap(),
            source: ProfileSource::Sfdp,
            sfdp_revision: None,
        });
        f.erase_range(0, 131_072 + 100).await.unwrap();
        let mem = probe.mem();
        assert!(mem[0..131_072 + 4096].iter().all(|&b| b == 0xFF)); // erased through tail sector
        assert!(mem[131_072 + 4096..].iter().all(|&b| b == 0x00)); // nothing beyond
    }

    #[tokio::test]
    async fn erase_without_profile_is_not_detected() {
        let flash = FakeFlash::new(1024, [0xEF, 0x40, 0x15]);
        let mut f = Flasher::with_config(
            flash,
            FakeBus::new(),
            256,
            Duration::ZERO,
            Duration::from_secs(1),
        );
        assert!(matches!(
            f.erase_range(0, 10).await,
            Err(FlashError::NotDetected)
        ));
    }

    #[tokio::test]
    async fn read_sfdp_returns_blob() {
        let flash = FakeFlash::new(1024, [0xEF, 0x40, 0x15]);
        flash.set_sfdp(&[0x53, 0x46, 0x44, 0x50, 0x06, 0x01, 0x00, 0xFF]);
        let mut f = flasher(flash, FakeBus::new(), 256);
        let mut hdr = [0u8; 8];
        f.read_sfdp(0, &mut hdr).await.unwrap();
        assert_eq!(&hdr[0..4], b"SFDP");
    }

    // Full SFDP image: header@0, BFPT param header@8, BFPT@0x10.
    fn sfdp_blob() -> Vec<u8> {
        let mut v = vec![0xFFu8; 0x10];
        v[0..8].copy_from_slice(&[0x53, 0x46, 0x44, 0x50, 0x06, 0x01, 0x00, 0xFF]); // "SFDP" rev1.6 nph=0
        v[8..16].copy_from_slice(&[0x00, 0x01, 0x01, 0x0B, 0x10, 0x00, 0x00, 0xFF]); // BFPT id0xFF00 len11 ptp0x10
        let mut b = vec![0u8; 11 * 4];
        b[0..4].copy_from_slice(&[0xE5, 0x20, 0x00, 0x00]);
        b[4..8].copy_from_slice(&[0xFF, 0xFF, 0xFF, 0x00]);
        b[28..32].copy_from_slice(&[0x0C, 0x20, 0x0F, 0x52]);
        b[32..36].copy_from_slice(&[0x10, 0xD8, 0x00, 0x00]);
        b[40..44].copy_from_slice(&[0x80, 0x00, 0x00, 0x00]);
        v.extend_from_slice(&b);
        v
    }

    #[tokio::test]
    async fn detect_via_sfdp_builds_profile() {
        use crate::profile::ProfileSource;
        let flash = FakeFlash::new(2 * 1024 * 1024, [0xEF, 0x40, 0x15]);
        flash.set_sfdp(&sfdp_blob());
        let mut f = flasher(flash, FakeBus::new(), 256);
        let p = f.detect_profile().await.unwrap();
        assert_eq!(p.source, ProfileSource::Sfdp);
        assert_eq!(p.page_size, 256);
        assert_eq!(p.capacity, Some(2 * 1024 * 1024));
        assert_eq!(p.erase.iter().count(), 3);
        assert_eq!(p.erase.largest().size, 64 * 1024); // largest first
        assert_eq!(p.sfdp_revision, Some((1, 6))); // "SFDP" rev 1.6 from the header
    }

    #[tokio::test]
    async fn detect_uses_fallback_table_for_m25p16() {
        use crate::profile::{EraseType, ProfileSource};
        let flash = FakeFlash::new(2 * 1024 * 1024, [0x20, 0x20, 0x15]); // M25P16: no SFDP, in table
        let mut f = flasher(flash, FakeBus::new(), 256);
        let p = f.detect_profile().await.unwrap();
        assert_eq!(p.source, ProfileSource::Table);
        assert_eq!(p.capacity, Some(2 * 1024 * 1024));
        assert_eq!(
            p.erase.iter().collect::<Vec<_>>(),
            vec![EraseType {
                size: 64 * 1024,
                opcode: 0xD8
            }]
        );
    }

    #[tokio::test]
    async fn detect_unsupported_chip_errs() {
        // A chip responds, but no SFDP and not in the table.
        let flash = FakeFlash::new(1024, [0xAB, 0xCD, 0xEF]);
        let mut f = flasher(flash, FakeBus::new(), 256);
        assert!(matches!(
            f.detect_profile().await,
            Err(FlashError::UnsupportedChip { .. })
        ));
    }

    #[tokio::test]
    async fn detect_no_flash_errs() {
        // Idle/floating bus: RDID reads all 0xFF.
        let flash = FakeFlash::new(1024, [0xFF, 0xFF, 0xFF]);
        let mut f = flasher(flash, FakeBus::new(), 256);
        assert!(matches!(f.detect_profile().await, Err(FlashError::NoFlash)));
    }

    #[tokio::test]
    async fn four_byte_addressing_roundtrips() {
        use crate::profile::{AddressWidth, EraseMenu, EraseType, FlashProfile, ProfileSource};
        let flash = FakeFlash::new(1024 * 1024, [0xEF, 0x40, 0x19]); // pretend 256 Mbit part
        let probe = flash.clone();
        let mut f = flasher(flash, FakeBus::new(), 256);
        f.set_profile(FlashProfile {
            page_size: 256,
            address_width: AddressWidth::Four,
            capacity: Some(32 * 1024 * 1024),
            erase: EraseMenu::new(vec![EraseType {
                size: 64 * 1024,
                opcode: 0xD8,
            }])
            .unwrap(),
            source: ProfileSource::Sfdp,
            sfdp_revision: None,
        });
        f.enter_4byte().await.unwrap(); // put the fake into 4-byte mode
        let addr = 0x0002_0000; // emitted as 4 bytes because the profile says so
        let data: Vec<u8> = (0..600).map(|i| (i % 256) as u8).collect();
        f.erase_range(addr, data.len()).await.unwrap();
        f.program(addr, &data, |_| {}).await.unwrap();
        let mut buf = vec![0u8; data.len()];
        f.read(addr, &mut buf).await.unwrap();
        assert_eq!(buf, data);
        assert_eq!(&probe.mem()[addr..addr + data.len()], &data[..]);
    }

    #[tokio::test]
    async fn unprotect_enables_programming() {
        let flash = FakeFlash::new(1024, [0xEF, 0x40, 0x15]);
        flash.set_protected(true);
        let probe = flash.clone();
        let mut f = flasher(flash, FakeBus::new(), 256);
        f.program(0, &[1, 2, 3, 4], |_| {}).await.unwrap();
        assert_eq!(&probe.mem()[0..4], &[0xFF, 0xFF, 0xFF, 0xFF]); // blocked while protected
        f.unprotect().await.unwrap();
        f.program(0, &[1, 2, 3, 4], |_| {}).await.unwrap();
        assert_eq!(&probe.mem()[0..4], &[1, 2, 3, 4]); // now written
    }

    #[tokio::test]
    async fn protect_then_unprotect_roundtrip() {
        let flash = FakeFlash::new(1024, [0xEF, 0x40, 0x15]);
        let mut f = flasher(flash, FakeBus::new(), 256);
        assert!(!f.is_protected().await.unwrap());
        f.protect().await.unwrap();
        assert!(f.is_protected().await.unwrap());
        f.unprotect().await.unwrap();
        assert!(!f.is_protected().await.unwrap());
    }

    #[tokio::test]
    async fn soft_reset_runs() {
        let flash = FakeFlash::new(1024, [0xEF, 0x40, 0x15]);
        let mut f = flasher(flash, FakeBus::new(), 256);
        f.reset_flash().await.unwrap(); // 0x66 then 0x99
    }

    #[tokio::test]
    async fn wake_releases_power_down() {
        // An iCE40 leaves its config flash in Deep Power-Down after booting.
        let flash = FakeFlash::new(2 * 1024 * 1024, [0xEF, 0x40, 0x18]);
        flash.set_powered_down(true);
        let mut f = flasher(flash, FakeBus::new(), 256);
        // Asleep: RDID reads 0xFF -> not present.
        assert!(!f.read_id().await.unwrap().is_present());
        // Wake it, then RDID works.
        f.wake().await.unwrap();
        assert_eq!(
            f.read_id().await.unwrap(),
            FlashId {
                manufacturer: 0xEF,
                mem_type: 0x40,
                capacity_code: 0x18
            }
        );
    }

    #[tokio::test]
    async fn acquire_bus_wakes_the_flash() {
        let flash = FakeFlash::new(2 * 1024 * 1024, [0xEF, 0x40, 0x18]);
        flash.set_powered_down(true);
        let mut f = flasher(flash, FakeBus::new(), 256);
        f.acquire_bus().await.unwrap(); // must hold the bus AND wake the flash
        assert!(f.read_id().await.unwrap().is_present());
    }
}

#[cfg(test)]
pub(crate) mod testfakes {
    use super::*;

    use embedded_hal::spi::{Error as SpiErrorTrait, ErrorKind, ErrorType};
    use std::cell::RefCell;
    use std::convert::Infallible;
    use std::rc::Rc;

    #[derive(Debug)]
    pub struct FakeErr;
    impl SpiErrorTrait for FakeErr {
        fn kind(&self) -> ErrorKind {
            ErrorKind::Other
        }
    }

    struct FakeState {
        mem: Vec<u8>,
        id: [u8; 3],
        wel: bool,
        busy_reads: u32, // # of RDSR calls that report WIP=1 before clearing
        sfdp: Vec<u8>,
        mode4b: bool,               // true once EN4B (0xB7) seen → 32-bit addresses
        protected: bool,            // true once BP bits set → PAGE PROGRAM silently no-ops
        powered_down: bool,         // true once 0xB9 seen → ignores all but 0xAB (models the iCE40)
        corrupt_next_program: bool, // one-shot: next PAGE PROGRAM silently fails (fault injection)
    }

    /// Shareable behavioral SPI-NOR. Clone to inspect memory after moving one
    /// clone into a `Flasher`.
    #[derive(Clone)]
    pub(crate) struct FakeFlash(Rc<RefCell<FakeState>>);

    impl FakeFlash {
        pub(crate) fn new(size: usize, id: [u8; 3]) -> Self {
            FakeFlash(Rc::new(RefCell::new(FakeState {
                mem: vec![0xFF; size],
                id,
                wel: false,
                busy_reads: 0,
                sfdp: Vec::new(),
                mode4b: false,
                protected: false,
                powered_down: false,
                corrupt_next_program: false,
            })))
        }
        pub(crate) fn set_busy_reads(&self, n: u32) {
            self.0.borrow_mut().busy_reads = n;
        }
        pub(crate) fn set_sfdp(&self, blob: &[u8]) {
            self.0.borrow_mut().sfdp = blob.to_vec();
        }
        pub(crate) fn set_protected(&self, p: bool) {
            self.0.borrow_mut().protected = p;
        }
        pub(crate) fn set_powered_down(&self, p: bool) {
            self.0.borrow_mut().powered_down = p;
        }
        /// One-shot fault injection: the next PAGE PROGRAM silently writes nothing,
        /// so a following verify mismatches (models a failed program).
        pub(crate) fn set_corrupt_next_program(&self) {
            self.0.borrow_mut().corrupt_next_program = true;
        }
        pub(crate) fn mem(&self) -> Vec<u8> {
            self.0.borrow().mem.clone()
        }
        pub(crate) fn preset(&self, addr: usize, bytes: &[u8]) {
            self.0.borrow_mut().mem[addr..addr + bytes.len()].copy_from_slice(bytes);
        }
    }

    impl ErrorType for FakeFlash {
        type Error = FakeErr;
    }

    impl embedded_hal_async::spi::SpiDevice for FakeFlash {
        async fn transaction(&mut self, ops: &mut [Operation<'_, u8>]) -> Result<(), FakeErr> {
            // Flatten MOSI bytes; collect MISO destinations in order.
            let mut mosi: Vec<u8> = Vec::new();
            let mut reads: Vec<&mut [u8]> = Vec::new();
            for op in ops.iter_mut() {
                match op {
                    Operation::Write(w) => mosi.extend_from_slice(w),
                    Operation::Read(r) => reads.push(r),
                    Operation::Transfer(r, w) => {
                        mosi.extend_from_slice(w);
                        reads.push(r);
                    }
                    Operation::TransferInPlace(b) => {
                        let c = b.to_vec();
                        mosi.extend_from_slice(&c);
                        reads.push(b);
                    }
                    Operation::DelayNs(_) => {}
                }
            }
            if mosi.is_empty() {
                return Ok(());
            }

            let mut st = self.0.borrow_mut();
            let mut resp: Vec<u8> = Vec::new();
            let ab = if st.mode4b { 4 } else { 3 };
            let addr_at = |m: &[u8]| -> usize {
                let mut a = 0usize;
                for i in 0..ab {
                    a = (a << 8) | m[1 + i] as usize;
                }
                a
            };
            match mosi[0] {
                CMD_RELEASE_PD => st.powered_down = false, // 0xAB wakes it
                0xB9 => st.powered_down = true, // 0xB9 = Deep Power-Down (models the FPGA)
                _ if st.powered_down => {}      // asleep: ignore every other command
                CMD_RDID => resp.extend_from_slice(&st.id),
                CMD_WREN => st.wel = true,
                CMD_EN4B => st.mode4b = true,
                CMD_RDSR => {
                    let wip = if st.busy_reads > 0 {
                        st.busy_reads -= 1;
                        SR_WIP
                    } else {
                        0
                    };
                    let wel = if st.wel { 0x02 } else { 0 };
                    let bp = if st.protected { 0x1C } else { 0 };
                    resp.push(wip | wel | bp);
                }
                CMD_READ => {
                    let a = addr_at(&mosi);
                    let total: usize = reads.iter().map(|r| r.len()).sum();
                    for i in 0..total {
                        resp.push(*st.mem.get(a + i).unwrap_or(&0xFF));
                    }
                }
                CMD_SFDP => {
                    let a = u32::from_be_bytes([0, mosi[1], mosi[2], mosi[3]]) as usize;
                    let total: usize = reads.iter().map(|r| r.len()).sum();
                    for i in 0..total {
                        resp.push(*st.sfdp.get(a + i).unwrap_or(&0xFF));
                    }
                }
                CMD_WRSR => {
                    if st.wel {
                        let sr = mosi.get(1).copied().unwrap_or(0);
                        st.protected = sr & 0x1C != 0; // any BP bit set
                    }
                    st.wel = false;
                }
                CMD_PP => {
                    let a = addr_at(&mosi);
                    if st.wel && !st.protected {
                        if st.corrupt_next_program {
                            st.corrupt_next_program = false; // one-shot: this PP silently fails
                        } else {
                            for (i, b) in mosi[1 + ab..].iter().enumerate() {
                                let page = a & !(PAGE_SIZE - 1);
                                let off = (a + i - page) % PAGE_SIZE; // wraps within page
                                st.mem[page + off] &= *b; // NOR: program clears bits
                            }
                        }
                    }
                    st.wel = false;
                }
                CMD_CE => {
                    if st.wel {
                        st.mem.iter_mut().for_each(|b| *b = 0xFF);
                    }
                    st.wel = false;
                }
                op @ (0x20 | 0x52 | 0xD8) => {
                    let size = match op {
                        0x20 => 4 * 1024,
                        0x52 => 32 * 1024,
                        _ => 64 * 1024,
                    };
                    let a = addr_at(&mosi);
                    if st.wel {
                        let base = a & !(size - 1);
                        for b in &mut st.mem[base..base + size] {
                            *b = 0xFF;
                        }
                    }
                    st.wel = false;
                }
                _ => {}
            }
            let mut ri = 0;
            for r in reads.iter_mut() {
                for b in r.iter_mut() {
                    *b = *resp.get(ri).unwrap_or(&0xFF);
                    ri += 1;
                }
            }
            Ok(())
        }
    }

    /// Shareable reset line; `true` = asserted (FPGA held in reset).
    #[derive(Clone)]
    pub(crate) struct FakeBus(Rc<RefCell<bool>>);
    impl FakeBus {
        pub(crate) fn new() -> Self {
            FakeBus(Rc::new(RefCell::new(false)))
        }
    }
    impl BusAccess for FakeBus {
        type Error = Infallible;
        fn acquire(&mut self) -> Result<(), Infallible> {
            *self.0.borrow_mut() = true;
            Ok(())
        }
        fn release(&mut self) -> Result<(), Infallible> {
            *self.0.borrow_mut() = false;
            Ok(())
        }
    }

    /// Fast Flasher over the fakes (zero poll interval so tests don't sleep),
    /// pre-loaded with a default profile so geometry ops resolve.
    pub(crate) fn flasher(
        flash: FakeFlash,
        bus: FakeBus,
        max_chunk: usize,
    ) -> Flasher<FakeFlash, FakeBus> {
        let mut f = Flasher::with_config(
            flash,
            bus,
            max_chunk,
            Duration::ZERO,
            Duration::from_secs(1),
        );
        f.set_profile(crate::profile::FlashProfile {
            page_size: 256,
            address_width: crate::profile::AddressWidth::Three,
            capacity: Some(2 * 1024 * 1024),
            erase: crate::profile::EraseMenu::new(vec![crate::profile::EraseType {
                size: 64 * 1024,
                opcode: 0xD8,
            }])
            .unwrap(),
            source: crate::profile::ProfileSource::Table,
            sfdp_revision: None,
        });
        f
    }
}