vorago-shared-hal 0.4.0

Peripheral HAL components shared between Vorago families
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
use crate::FunctionSelect;
use crate::gpio::{DynPinId, IoPeriphPin};
use crate::{PeripheralSelect, enable_peripheral_clock, pins::AnyPin, sealed::Sealed, time::Hertz};
use core::{convert::Infallible, fmt::Debug, marker::PhantomData};
use embedded_hal::spi::{MODE_0, Mode};

use regs::{ClockPrescaler, Data, FifoClear, WordSize};
#[cfg(feature = "vor1x")]
use va108xx as pac;
#[cfg(feature = "vor4x")]
use va416xx as pac;

pub use regs::{Bank, HwChipSelectId};

pub mod asynch;
pub mod regs;

pub const FIFO_DEPTH: usize = 16;

pub fn configure_pin_as_hw_cs_pin<P: AnyPin + HwCsProvider>(_pin: P) -> HwChipSelectId {
    IoPeriphPin::new(P::ID, P::FUN_SEL, None);
    P::CS_ID
}

//==================================================================================================
// Pins and traits.
//==================================================================================================

pub trait PinSck0: AnyPin {
    const SPI_ID: Bank = Bank::Spi0;
    const FUN_SEL: FunctionSelect;
}

pub trait PinMosi0: AnyPin {
    const SPI_ID: Bank = Bank::Spi0;
    const FUN_SEL: FunctionSelect;
}

pub trait PinMiso0: AnyPin {
    const SPI_ID: Bank = Bank::Spi0;
    const FUN_SEL: FunctionSelect;
}

pub trait PinSck1: AnyPin {
    const SPI_ID: Bank = Bank::Spi1;
    const FUN_SEL: FunctionSelect;
}

pub trait PinMosi1: AnyPin {
    const SPI_ID: Bank = Bank::Spi1;
    const FUN_SEL: FunctionSelect;
}

pub trait PinMiso1: AnyPin {
    const SPI_ID: Bank = Bank::Spi1;
    const FUN_SEL: FunctionSelect;
}

pub trait PinSck2: AnyPin {
    const SPI_ID: Bank = Bank::Spi2;
    const FUN_SEL: FunctionSelect;
}

pub trait PinMosi2: AnyPin {
    const SPI_ID: Bank = Bank::Spi2;
    const FUN_SEL: FunctionSelect;
}

pub trait PinMiso2: AnyPin {
    const SPI_ID: Bank = Bank::Spi2;
    const FUN_SEL: FunctionSelect;
}

pub trait HwCsProvider {
    const PIN_ID: DynPinId;
    const SPI_ID: Bank;
    const FUN_SEL: FunctionSelect;
    const CS_ID: HwChipSelectId;
}

#[macro_use]
mod macros {
    #[cfg(not(feature = "va41628"))]
    macro_rules! hw_cs_multi_pin {
    (
        // name of the newtype wrapper struct
        $name:ident,
        // Pb0
        $pin_id:ident,
        // SpiId::B
        $spi_id:path,
        // FunSel::Sel1
        $fun_sel:path,
        // HwChipSelectId::Id2
        $cs_id:path
    ) => {
            #[doc = concat!(
                "Newtype wrapper to use [Pin] [`", stringify!($pin_id), "`] as a HW CS pin for [`", stringify!($spi_id), "`] with [`", stringify!($cs_id), "`]."
            )]
            pub struct $name(Pin<$pin_id>);

            impl $name {
                pub fn new(pin: Pin<$pin_id>) -> Self {
                    Self(pin)
                }
            }

            impl crate::sealed::Sealed for $name {}

            impl AnyPin for $name {
                const ID: DynPinId = <$pin_id as PinId>::ID;
            }

            impl HwCsProvider for $name {
                const PIN_ID: DynPinId = <$pin_id as PinId>::ID;
                const SPI_ID: Bank = $spi_id;
                const FUN_SEL: FunctionSelect = $fun_sel;
                const CS_ID: HwChipSelectId = $cs_id;
            }
        };
    }

    #[macro_export]
    macro_rules! hw_cs_pins {
        ($SpiId:path, $(($Px:ident, $FunSel:path, $HwCsIdent:path)$(,)?)+) => {
            $(
                impl HwCsProvider for Pin<$Px> {
                    const PIN_ID: DynPinId = $Px::ID;
                    const SPI_ID: Bank = $SpiId;
                    const FUN_SEL: FunctionSelect = $FunSel;
                    const CS_ID: HwChipSelectId = $HwCsIdent;
                }
            )+
        };
    }
}

#[cfg(feature = "vor1x")]
pub mod pins_vor1x;
#[cfg(feature = "vor4x")]
pub mod pins_vor4x;

//==================================================================================================
// Defintions
//==================================================================================================

// FIFO has a depth of 16.
const FILL_DEPTH: usize = 12;

pub const BMSTART_BMSTOP_MASK: u32 = 1 << 31;
pub const BMSKIPDATA_MASK: u32 = 1 << 30;

pub const DEFAULT_CLK_DIV: u16 = 2;

pub trait Spi0Instance: Sealed {
    const ID: Bank = Bank::Spi0;
    const PERIPH_SEL: PeripheralSelect;
}

pub trait Spi1Instance: Sealed {
    const ID: Bank = Bank::Spi1;
    const PERIPH_SEL: PeripheralSelect;
}

pub trait Spi2Instance: Sealed {
    const ID: Bank = Bank::Spi2;
    const PERIPH_SEL: PeripheralSelect;
}

#[cfg(feature = "vor4x")]
pub trait Spi3Instance: Sealed {
    const ID: Bank = Bank::Spi3;
    const PERIPH_SEL: PeripheralSelect;
}

#[cfg(feature = "vor1x")]
pub type Spi0 = pac::Spia;
#[cfg(feature = "vor4x")]
pub type Spi0 = pac::Spi0;

impl Spi0Instance for Spi0 {
    const ID: Bank = Bank::Spi0;
    const PERIPH_SEL: PeripheralSelect = PeripheralSelect::Spi0;
}
impl Sealed for Spi0 {}

#[cfg(feature = "vor1x")]
pub type Spi1 = pac::Spib;
#[cfg(feature = "vor4x")]
pub type Spi1 = pac::Spi1;

impl Spi1Instance for Spi1 {
    const ID: Bank = Bank::Spi1;
    const PERIPH_SEL: PeripheralSelect = PeripheralSelect::Spi1;
}
impl Sealed for Spi1 {}

#[cfg(feature = "vor1x")]
pub type Spi2 = pac::Spic;
#[cfg(feature = "vor4x")]
pub type Spi2 = pac::Spi2;

impl Spi2Instance for Spi2 {
    const ID: Bank = Bank::Spi2;
    const PERIPH_SEL: PeripheralSelect = PeripheralSelect::Spi2;
}
impl Sealed for Spi2 {}

#[cfg(feature = "vor4x")]
impl Spi3Instance for pac::Spi3 {
    const ID: Bank = Bank::Spi3;
    const PERIPH_SEL: PeripheralSelect = PeripheralSelect::Spi3;
}
#[cfg(feature = "vor4x")]
impl Sealed for pac::Spi3 {}

//==================================================================================================
// Config
//==================================================================================================

pub trait TransferConfigProvider {
    fn sod(&mut self, sod: bool);
    fn blockmode(&mut self, blockmode: bool);
    fn mode(&mut self, mode: Mode);
    fn clk_cfg(&mut self, clk_cfg: SpiClockConfig);
    fn hw_cs_id(&self) -> u8;
}

/// Type erased variant of the transfer configuration. This is required to avoid generics in
/// the SPI constructor.
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct TransferConfig {
    pub clk_cfg: Option<SpiClockConfig>,
    pub mode: Option<Mode>,
    pub sod: bool,
    /// If this is enabled, all data in the FIFO is transmitted in a single frame unless
    /// the BMSTOP bit is set on a dataword. A frame is defined as CSn being active for the
    /// duration of multiple data words
    pub blockmode: bool,
    /// Only used when blockmode is used. The SCK will be stalled until an explicit stop bit
    /// is set on a written word.
    pub bmstall: bool,
    pub hw_cs: Option<HwChipSelectId>,
}

impl TransferConfig {
    pub fn new_with_hw_cs(
        clk_cfg: Option<SpiClockConfig>,
        mode: Option<Mode>,
        blockmode: bool,
        bmstall: bool,
        sod: bool,
        hw_cs_id: HwChipSelectId,
    ) -> Self {
        TransferConfig {
            clk_cfg,
            mode,
            sod,
            blockmode,
            bmstall,
            hw_cs: Some(hw_cs_id),
        }
    }
}

/// Configuration options for the whole SPI bus. See Programmer Guide p.92 for more details
#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct SpiConfig {
    clk: SpiClockConfig,
    // SPI mode configuration
    pub init_mode: Mode,
    /// If this is enabled, all data in the FIFO is transmitted in a single frame unless
    /// the BMSTOP bit is set on a dataword. A frame is defined as CSn being active for the
    /// duration of multiple data words. Defaults to true.
    pub blockmode: bool,
    /// This enables the stalling of the SPI SCK if in blockmode and the FIFO is empty.
    /// Currently enabled by default.
    pub bmstall: bool,
    /// Slave output disable. Useful if separate GPIO pins or decoders are used for CS control
    pub slave_output_disable: bool,
    /// Loopback mode. If you use this, don't connect MISO to MOSI, they will be tied internally
    pub loopback_mode: bool,
    /// Enable Master Delayer Capture Mode. See Programmers Guide p.92 for more details
    pub master_delayer_capture: bool,
}

impl Default for SpiConfig {
    fn default() -> Self {
        Self {
            init_mode: MODE_0,
            blockmode: true,
            bmstall: true,
            // Default value is definitely valid.
            clk: SpiClockConfig::from_div(DEFAULT_CLK_DIV).unwrap(),
            slave_output_disable: Default::default(),
            loopback_mode: Default::default(),
            master_delayer_capture: Default::default(),
        }
    }
}

impl SpiConfig {
    pub fn loopback(mut self, enable: bool) -> Self {
        self.loopback_mode = enable;
        self
    }

    pub fn blockmode(mut self, enable: bool) -> Self {
        self.blockmode = enable;
        self
    }

    pub fn bmstall(mut self, enable: bool) -> Self {
        self.bmstall = enable;
        self
    }

    pub fn mode(mut self, mode: Mode) -> Self {
        self.init_mode = mode;
        self
    }

    pub fn clk_cfg(mut self, clk_cfg: SpiClockConfig) -> Self {
        self.clk = clk_cfg;
        self
    }

    pub fn slave_output_disable(mut self, sod: bool) -> Self {
        self.slave_output_disable = sod;
        self
    }
}

//==================================================================================================
// Word Size
//==================================================================================================

/// Configuration trait for the Word Size
/// used by the SPI peripheral
pub trait SpiWord: Copy + Default + Into<u32> + TryFrom<u32> + 'static {
    const MASK: u32;
    const WORD_SIZE: regs::WordSize;
    fn word_reg() -> u8;
}

impl SpiWord for u8 {
    const MASK: u32 = 0xff;
    const WORD_SIZE: regs::WordSize = regs::WordSize::EightBits;
    fn word_reg() -> u8 {
        0x07
    }
}

impl SpiWord for u16 {
    const MASK: u32 = 0xffff;
    const WORD_SIZE: regs::WordSize = regs::WordSize::SixteenBits;
    fn word_reg() -> u8 {
        0x0f
    }
}

//==================================================================================================
// Spi
//==================================================================================================

/// Low level access trait for the SPI peripheral.
pub trait SpiLowLevel {
    /// Low level function to write a word to the SPI FIFO but also checks whether
    /// there is actually data in the FIFO.
    ///
    /// Uses the [nb] API to allow usage in blocking and non-blocking contexts.
    fn write_fifo(&mut self, data: u32) -> nb::Result<(), Infallible>;

    /// Low level function to write a word to the SPI FIFO without checking whether
    /// there FIFO is full.
    ///
    /// This does not necesarily mean there is a space in the FIFO available.
    /// Use [Self::write_fifo] function to write a word into the FIFO reliably.
    fn write_fifo_unchecked(&mut self, data: u32);

    /// Low level function to read a word from the SPI FIFO. Must be preceeded by a
    /// [Self::write_fifo] call.
    ///
    /// Uses the [nb] API to allow usage in blocking and non-blocking contexts.
    fn read_fifo(&mut self) -> nb::Result<u32, Infallible>;

    /// Low level function to read a word from from the SPI FIFO.
    ///
    /// This does not necesarily mean there is a word in the FIFO available.
    /// Use the [Self::read_fifo] function to read a word from the FIFO reliably using the [nb]
    /// API.
    /// You might also need to mask the value to ignore the BMSTART/BMSTOP bit.
    fn read_fifo_unchecked(&mut self) -> u32;
}

#[inline(always)]
pub fn mode_to_cpo_cph_bit(mode: embedded_hal::spi::Mode) -> (bool, bool) {
    match mode {
        embedded_hal::spi::MODE_0 => (false, false),
        embedded_hal::spi::MODE_1 => (false, true),
        embedded_hal::spi::MODE_2 => (true, false),
        embedded_hal::spi::MODE_3 => (true, true),
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct SpiClockConfig {
    prescale_val: u8,
    scrdv: u8,
}

impl SpiClockConfig {
    pub fn prescale_val(&self) -> u8 {
        self.prescale_val
    }
    pub fn scrdv(&self) -> u8 {
        self.scrdv
    }
}

impl SpiClockConfig {
    pub fn new(prescale_val: u8, scrdv: u8) -> Self {
        Self {
            prescale_val,
            scrdv,
        }
    }

    pub fn from_div(div: u16) -> Result<Self, SpiClockConfigError> {
        spi_clk_config_from_div(div)
    }

    #[cfg(feature = "vor1x")]
    pub fn from_clk(sys_clk: Hertz, spi_clk: Hertz) -> Option<Self> {
        clk_div_for_target_clock(sys_clk, spi_clk).map(|div| spi_clk_config_from_div(div).unwrap())
    }

    #[cfg(feature = "vor4x")]
    pub fn from_clks(clks: &crate::clock::Clocks, spi_clk: Hertz) -> Option<Self> {
        Self::from_apb1_clk(clks.apb1(), spi_clk)
    }

    #[cfg(feature = "vor4x")]
    pub fn from_apb1_clk(apb1_clk: Hertz, spi_clk: Hertz) -> Option<Self> {
        clk_div_for_target_clock(apb1_clk, spi_clk).map(|div| spi_clk_config_from_div(div).unwrap())
    }
}

#[derive(Debug, thiserror::Error)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum SpiClockConfigError {
    #[error("division by zero")]
    DivIsZero,
    #[error("divide value is not even")]
    DivideValueNotEven,
    #[error("scrdv value is too large")]
    ScrdvValueTooLarge,
}

#[inline]
pub fn spi_clk_config_from_div(mut div: u16) -> Result<SpiClockConfig, SpiClockConfigError> {
    if div == 0 {
        return Err(SpiClockConfigError::DivIsZero);
    }
    if !div.is_multiple_of(2) {
        return Err(SpiClockConfigError::DivideValueNotEven);
    }
    let mut prescale_val = 0;

    // find largest (even) prescale value that divides into div
    for i in (2..=0xfe).rev().step_by(2) {
        if div.is_multiple_of(i) {
            prescale_val = i;
            break;
        }
    }

    if prescale_val == 0 {
        return Err(SpiClockConfigError::DivideValueNotEven);
    }

    div /= prescale_val;
    if div > u8::MAX as u16 + 1 {
        return Err(SpiClockConfigError::ScrdvValueTooLarge);
    }
    Ok(SpiClockConfig {
        prescale_val: prescale_val as u8,
        scrdv: (div - 1) as u8,
    })
}

#[inline]
pub fn clk_div_for_target_clock(sys_clk: Hertz, spi_clk: Hertz) -> Option<u16> {
    if spi_clk > sys_clk {
        return None;
    }

    // Step 1: Calculate raw divider.
    let raw_div = sys_clk.to_raw() / spi_clk.to_raw();
    let remainder = sys_clk.to_raw() % spi_clk.to_raw();

    // Step 2: Round up if necessary.
    let mut rounded_div = if remainder * 2 >= spi_clk.to_raw() {
        raw_div + 1
    } else {
        raw_div
    };

    if !rounded_div.is_multiple_of(2) {
        // Take slower clock conservatively.
        rounded_div += 1;
    }
    if rounded_div > u16::MAX as u32 {
        return None;
    }
    Some(rounded_div as u16)
}

/// SPI peripheral driver structure.
pub struct Spi<Word = u8> {
    id: Bank,
    regs: regs::MmioSpi<'static>,
    /// Fill word for read-only SPI transactions.
    fill_word: Word,
    blockmode: bool,
    bmstall: bool,
    word: PhantomData<Word>,
}

impl<Word: SpiWord> Spi<Word>
where
    <Word as TryFrom<u32>>::Error: core::fmt::Debug,
{
    /// Create a new SPI struct for using SPI with the fixed ROM SPI pins.
    ///
    /// ## Arguments
    ///
    /// * `spi` - SPI bus to use
    /// * `spi_cfg` - Configuration specific to the SPI bus
    #[cfg(feature = "vor1x")]
    pub fn new_for_rom<Spi: Spi2Instance>(_spi: Spi, spi_cfg: SpiConfig) -> Self {
        Self::new_generic(Spi::ID, Spi::PERIPH_SEL, spi_cfg)
    }

    /// Create a new SPI struct for using SPI with the fixed ROM SPI pins.
    ///
    /// ## Arguments
    ///
    /// * `spi` - SPI bus to use
    /// * `spi_cfg` - Configuration specific to the SPI bus
    #[cfg(feature = "vor4x")]
    pub fn new_for_rom<Spi: Spi3Instance>(_spi: Spi, spi_cfg: SpiConfig) -> Self {
        Self::new_generic(Spi::ID, Spi::PERIPH_SEL, spi_cfg)
    }

    /// Create a new SPI peripheral driver for SPI 0.
    ///
    /// ## Arguments
    ///
    /// * `spi` - SPI bus to use
    /// * `pins` - Pins to be used for SPI transactions. These pins are consumed
    ///   to ensure the pins can not be used for other purposes anymore
    /// * `spi_cfg` - Configuration specific to the SPI bus
    pub fn new_for_spi0<Spi: Spi0Instance, Sck: PinSck0, Miso: PinMiso0, Mosi: PinMosi0>(
        _spi: Spi,
        _pins: (Sck, Miso, Mosi),
        spi_cfg: SpiConfig,
    ) -> Self {
        IoPeriphPin::new(Sck::ID, Sck::FUN_SEL, None);
        IoPeriphPin::new(Miso::ID, Miso::FUN_SEL, None);
        IoPeriphPin::new(Mosi::ID, Mosi::FUN_SEL, None);
        Self::new_generic(Spi::ID, Spi::PERIPH_SEL, spi_cfg)
    }

    /// Create a new SPI peripheral driver for SPI 1.
    ///
    /// ## Arguments
    ///
    /// * `spi` - SPI bus to use
    /// * `pins` - Pins to be used for SPI transactions. These pins are consumed
    ///   to ensure the pins can not be used for other purposes anymore
    /// * `spi_cfg` - Configuration specific to the SPI bus
    pub fn new_for_spi1<Spi: Spi1Instance, Sck: PinSck1, Miso: PinMiso1, Mosi: PinMosi1>(
        _spi: Spi,
        _pins: (Sck, Miso, Mosi),
        spi_cfg: SpiConfig,
    ) -> Self {
        IoPeriphPin::new(Sck::ID, Sck::FUN_SEL, None);
        IoPeriphPin::new(Miso::ID, Miso::FUN_SEL, None);
        IoPeriphPin::new(Mosi::ID, Mosi::FUN_SEL, None);
        Self::new_generic(Spi::ID, Spi::PERIPH_SEL, spi_cfg)
    }

    /// Create a new SPI peripheral driver for SPI 2.
    ///
    /// ## Arguments
    ///
    /// * `spi` - SPI bus to use
    /// * `pins` - Pins to be used for SPI transactions. These pins are consumed
    ///   to ensure the pins can not be used for other purposes anymore
    /// * `spi_cfg` - Configuration specific to the SPI bus
    pub fn new_for_spi2<Spi: Spi2Instance, Sck: PinSck2, Miso: PinMiso2, Mosi: PinMosi2>(
        _spi: Spi,
        _pins: (Sck, Miso, Mosi),
        spi_cfg: SpiConfig,
    ) -> Self {
        IoPeriphPin::new(Sck::ID, Sck::FUN_SEL, None);
        IoPeriphPin::new(Miso::ID, Miso::FUN_SEL, None);
        IoPeriphPin::new(Mosi::ID, Mosi::FUN_SEL, None);
        Self::new_generic(Spi::ID, Spi::PERIPH_SEL, spi_cfg)
    }

    pub fn new_generic(spi_sel: Bank, periph_sel: PeripheralSelect, spi_cfg: SpiConfig) -> Self {
        enable_peripheral_clock(periph_sel);
        let mut regs = regs::Spi::new_mmio(spi_sel);
        let (cpo_bit, cph_bit) = mode_to_cpo_cph_bit(spi_cfg.init_mode);
        regs.write_ctrl0(
            regs::Control0::builder()
                .with_scrdv(spi_cfg.clk.scrdv)
                .with_sph(cph_bit)
                .with_spo(cpo_bit)
                .with_word_size(Word::WORD_SIZE)
                .build(),
        );
        regs.write_ctrl1(
            regs::Control1::builder()
                .with_mtxpause(false)
                .with_mdlycap(spi_cfg.master_delayer_capture)
                .with_bm_stall(spi_cfg.bmstall)
                .with_bm_start(false)
                .with_blockmode(spi_cfg.blockmode)
                .with_ss(HwChipSelectId::Id0)
                .with_sod(spi_cfg.slave_output_disable)
                .with_slave_mode(false)
                .with_enable(false)
                .with_lbm(spi_cfg.loopback_mode)
                .build(),
        );
        regs.write_clkprescale(ClockPrescaler::new(spi_cfg.clk.prescale_val));
        regs.write_fifo_clear(
            FifoClear::builder()
                .with_tx_fifo(true)
                .with_rx_fifo(true)
                .build(),
        );
        // Enable the peripheral as the last step as recommended in the
        // programmers guide
        regs.modify_ctrl1(|mut value| {
            value.set_enable(true);
            value
        });
        Spi {
            id: spi_sel,
            regs: regs::Spi::new_mmio(spi_sel),
            fill_word: Default::default(),
            bmstall: spi_cfg.bmstall,
            blockmode: spi_cfg.blockmode,
            word: PhantomData,
        }
    }

    #[inline]
    pub fn cfg_clock(&mut self, cfg: SpiClockConfig) {
        self.regs.modify_ctrl0(|mut value| {
            value.set_scrdv(cfg.scrdv);
            value
        });
        self.regs
            .write_clkprescale(regs::ClockPrescaler::new(cfg.prescale_val));
    }

    pub fn set_fill_word(&mut self, fill_word: Word) {
        self.fill_word = fill_word;
    }

    #[inline]
    pub fn configure_clock_from_div(&mut self, div: u16) -> Result<(), SpiClockConfigError> {
        let val = spi_clk_config_from_div(div)?;
        self.cfg_clock(val);
        Ok(())
    }

    #[inline]
    pub fn configure_mode(&mut self, mode: Mode) {
        let (cpo_bit, cph_bit) = mode_to_cpo_cph_bit(mode);
        self.regs.modify_ctrl0(|mut value| {
            value.set_spo(cpo_bit);
            value.set_sph(cph_bit);
            value
        });
    }

    #[inline]
    pub fn fill_word(&self) -> Word {
        self.fill_word
    }

    #[inline]
    pub fn clear_tx_fifo(&mut self) {
        self.regs.write_fifo_clear(
            regs::FifoClear::builder()
                .with_tx_fifo(true)
                .with_rx_fifo(false)
                .build(),
        );
    }

    #[inline]
    pub fn clear_rx_fifo(&mut self) {
        self.regs.write_fifo_clear(
            regs::FifoClear::builder()
                .with_tx_fifo(false)
                .with_rx_fifo(true)
                .build(),
        );
    }

    #[inline]
    pub fn peripheral_id(&self) -> u32 {
        self.regs.read_perid()
    }

    /// Configure the hardware chip select given a hardware chip select ID.
    ///
    /// The pin also needs to be configured to be used as a HW CS pin. This can be done
    /// by using the [configure_pin_as_hw_cs_pin] function which also returns the
    /// corresponding [HwChipSelectId].
    #[inline]
    pub fn configure_hw_cs(&mut self, hw_cs: HwChipSelectId) {
        self.regs.modify_ctrl1(|mut value| {
            value.set_sod(false);
            value.set_ss(hw_cs);
            value
        });
    }

    /// Disables the hardware chip select functionality. This can be used when performing
    /// external chip select handling, for example with GPIO pins.
    #[inline]
    pub fn disable_hw_cs(&mut self) {
        self.regs.modify_ctrl1(|mut value| {
            value.set_sod(true);
            value
        });
    }

    /// Utility function to configure all relevant transfer parameters in one go.
    /// This is useful if multiple devices with different clock and mode configurations
    /// are connected to one bus.
    pub fn configure_transfer(&mut self, transfer_cfg: &TransferConfig) {
        if let Some(trans_clk_div) = transfer_cfg.clk_cfg {
            self.cfg_clock(trans_clk_div);
        }
        if let Some(mode) = transfer_cfg.mode {
            self.configure_mode(mode);
        }
        self.blockmode = transfer_cfg.blockmode;
        self.regs.modify_ctrl1(|mut value| {
            if transfer_cfg.sod {
                value.set_sod(transfer_cfg.sod);
            } else {
                value.set_sod(false);
                if let Some(hw_cs) = transfer_cfg.hw_cs {
                    value.set_ss(hw_cs);
                }
            }
            value.set_blockmode(transfer_cfg.blockmode);
            value.set_bm_stall(transfer_cfg.bmstall);
            value
        });
    }

    fn flush_internal(&mut self) {
        let mut status_reg = self.regs.read_status();
        while !status_reg.tx_empty() || status_reg.rx_not_empty() || status_reg.busy() {
            if status_reg.rx_not_empty() {
                self.read_fifo_unchecked();
            }
            status_reg = self.regs.read_status();
        }
    }

    fn transfer_preparation(&mut self, words: &[Word]) {
        if words.is_empty() {
            return;
        }
        self.flush_internal();
    }

    // The FIFO can hold a guaranteed amount of data, so we can pump it on transfer
    // initialization. Returns the amount of written bytes.
    fn initial_send_fifo_pumping_with_words(&mut self, words: &[Word]) -> usize {
        //let reg_block = self.reg_block();
        if self.blockmode {
            self.regs.modify_ctrl1(|mut value| {
                value.set_mtxpause(true);
                value
            });
        }
        // Fill the first half of the write FIFO
        let mut current_write_idx = 0;
        let smaller_idx = core::cmp::min(FILL_DEPTH, words.len());
        for _ in 0..smaller_idx {
            if current_write_idx == smaller_idx.saturating_sub(1) && self.bmstall {
                self.write_fifo_unchecked(words[current_write_idx].into() | BMSTART_BMSTOP_MASK);
            } else {
                self.write_fifo_unchecked(words[current_write_idx].into());
            }
            current_write_idx += 1;
        }
        if self.blockmode {
            self.regs.modify_ctrl1(|mut value| {
                value.set_mtxpause(false);
                value
            });
        }
        current_write_idx
    }

    // The FIFO can hold a guaranteed amount of data, so we can pump it on transfer
    // initialization.
    fn initial_send_fifo_pumping_with_fill_words(&mut self, send_len: usize) -> usize {
        if self.blockmode {
            self.regs.modify_ctrl1(|mut value| {
                value.set_mtxpause(true);
                value
            });
        }
        // Fill the first half of the write FIFO
        let mut current_write_idx = 0;
        let smaller_idx = core::cmp::min(FILL_DEPTH, send_len);
        for _ in 0..smaller_idx {
            if current_write_idx == smaller_idx.saturating_sub(1) && self.bmstall {
                self.write_fifo_unchecked(self.fill_word.into() | BMSTART_BMSTOP_MASK);
            } else {
                self.write_fifo_unchecked(self.fill_word.into());
            }
            current_write_idx += 1;
        }
        if self.blockmode {
            self.regs.modify_ctrl1(|mut value| {
                value.set_mtxpause(false);
                value
            });
        }
        current_write_idx
    }

    pub fn read(&mut self, words: &mut [Word]) {
        self.transfer_preparation(words);
        let mut current_read_idx = 0;
        let mut current_write_idx = self.initial_send_fifo_pumping_with_fill_words(words.len());
        loop {
            if current_read_idx < words.len() {
                words[current_read_idx] = (nb::block!(self.read_fifo()).unwrap() & Word::MASK)
                    .try_into()
                    .unwrap();
                current_read_idx += 1;
            }
            if current_write_idx < words.len() {
                if current_write_idx == words.len() - 1 && self.bmstall {
                    nb::block!(self.write_fifo(self.fill_word.into() | BMSTART_BMSTOP_MASK))
                        .unwrap();
                } else {
                    nb::block!(self.write_fifo(self.fill_word.into())).unwrap();
                }
                current_write_idx += 1;
            }
            if current_read_idx >= words.len() && current_write_idx >= words.len() {
                break;
            }
        }
    }

    pub fn write(&mut self, words: &[Word]) {
        self.transfer_preparation(words);
        let mut current_write_idx = self.initial_send_fifo_pumping_with_words(words);
        while current_write_idx < words.len() {
            if current_write_idx == words.len() - 1 && self.bmstall {
                nb::block!(self.write_fifo(words[current_write_idx].into() | BMSTART_BMSTOP_MASK))
                    .unwrap();
            } else {
                nb::block!(self.write_fifo(words[current_write_idx].into())).unwrap();
            }
            current_write_idx += 1;
            // Ignore received words.
            if self.regs.read_status().rx_not_empty() {
                self.clear_rx_fifo();
            }
        }
    }

    pub fn transfer(&mut self, read: &mut [Word], write: &[Word]) {
        self.transfer_preparation(write);
        let mut current_read_idx = 0;
        let mut current_write_idx = self.initial_send_fifo_pumping_with_words(write);
        let max_idx = core::cmp::max(read.len(), write.len());
        while current_read_idx < read.len() || current_write_idx < write.len() {
            if current_write_idx < max_idx {
                if current_write_idx == write.len() - 1 && self.bmstall {
                    nb::block!(
                        self.write_fifo(write[current_write_idx].into() | BMSTART_BMSTOP_MASK)
                    )
                    .unwrap();
                } else if current_write_idx < write.len() {
                    nb::block!(self.write_fifo(write[current_write_idx].into())).unwrap();
                } else {
                    nb::block!(self.write_fifo(0)).unwrap();
                }
                current_write_idx += 1;
            }
            if current_read_idx < max_idx {
                if current_read_idx < read.len() {
                    read[current_read_idx] = (nb::block!(self.read_fifo()).unwrap() & Word::MASK)
                        .try_into()
                        .unwrap();
                } else {
                    nb::block!(self.read_fifo()).unwrap();
                }
                current_read_idx += 1;
            }
        }
    }

    pub fn transfer_in_place(&mut self, words: &mut [Word]) {
        self.transfer_preparation(words);
        let mut current_read_idx = 0;
        let mut current_write_idx = self.initial_send_fifo_pumping_with_words(words);

        while current_read_idx < words.len() || current_write_idx < words.len() {
            if current_write_idx < words.len() {
                if current_write_idx == words.len() - 1 && self.bmstall {
                    nb::block!(
                        self.write_fifo(words[current_write_idx].into() | BMSTART_BMSTOP_MASK)
                    )
                    .unwrap();
                } else {
                    nb::block!(self.write_fifo(words[current_write_idx].into())).unwrap();
                }
                current_write_idx += 1;
            }
            if current_read_idx < words.len() && current_read_idx < current_write_idx {
                words[current_read_idx] = (nb::block!(self.read_fifo()).unwrap() & Word::MASK)
                    .try_into()
                    .unwrap();
                current_read_idx += 1;
            }
        }
    }

    pub fn flush(&mut self) {
        self.flush_internal();
    }
}

impl<W: SpiWord> SpiLowLevel for Spi<W>
where
    <W as TryFrom<u32>>::Error: core::fmt::Debug,
{
    #[inline(always)]
    fn write_fifo(&mut self, data: u32) -> nb::Result<(), Infallible> {
        if !self.regs.read_status().tx_not_full() {
            return Err(nb::Error::WouldBlock);
        }
        self.write_fifo_unchecked(data);
        Ok(())
    }

    #[inline(always)]
    fn write_fifo_unchecked(&mut self, data: u32) {
        self.regs.write_data(Data::new_with_raw_value(data));
    }

    #[inline(always)]
    fn read_fifo(&mut self) -> nb::Result<u32, Infallible> {
        if !self.regs.read_status().rx_not_empty() {
            return Err(nb::Error::WouldBlock);
        }
        Ok(self.read_fifo_unchecked())
    }

    #[inline(always)]
    fn read_fifo_unchecked(&mut self) -> u32 {
        self.regs.read_data().raw_value()
    }
}

impl<Word: SpiWord> embedded_hal::spi::ErrorType for Spi<Word> {
    type Error = Infallible;
}

impl<Word: SpiWord> embedded_hal::spi::SpiBus<Word> for Spi<Word>
where
    <Word as TryFrom<u32>>::Error: core::fmt::Debug,
{
    fn read(&mut self, words: &mut [Word]) -> Result<(), Self::Error> {
        self.read(words);
        Ok(())
    }

    fn write(&mut self, words: &[Word]) -> Result<(), Self::Error> {
        self.write(words);
        Ok(())
    }

    fn transfer(&mut self, read: &mut [Word], write: &[Word]) -> Result<(), Self::Error> {
        self.transfer(read, write);
        Ok(())
    }

    fn transfer_in_place(&mut self, words: &mut [Word]) -> Result<(), Self::Error> {
        self.transfer_in_place(words);
        Ok(())
    }

    fn flush(&mut self) -> Result<(), Self::Error> {
        self.flush();
        Ok(())
    }
}

/// Changing the word size also requires a type conversion
impl From<Spi<u8>> for Spi<u16> {
    fn from(mut old_spi: Spi<u8>) -> Self {
        old_spi.regs.modify_ctrl0(|mut value| {
            value.set_word_size(WordSize::SixteenBits);
            value
        });
        Spi {
            id: old_spi.id,
            regs: old_spi.regs,
            blockmode: old_spi.blockmode,
            fill_word: Default::default(),
            bmstall: old_spi.bmstall,
            word: PhantomData,
        }
    }
}

impl From<Spi<u16>> for Spi<u8> {
    fn from(mut old_spi: Spi<u16>) -> Self {
        old_spi.regs.modify_ctrl0(|mut value| {
            value.set_word_size(WordSize::EightBits);
            value
        });
        Spi {
            id: old_spi.id,
            regs: old_spi.regs,
            blockmode: old_spi.blockmode,
            fill_word: Default::default(),
            bmstall: old_spi.bmstall,
            word: PhantomData,
        }
    }
}

/// This abstraction which can be used to map a hardware chip select pin
/// to [embedded_hal::digital::OutputPin]. This is useful for creating physical chip select
/// pins required by the [embedded_hal_bus](https://docs.rs/embedded-hal-bus/latest/embedded_hal_bus/)
/// API.
pub struct HwCsPin {
    regs: regs::MmioSpi<'static>,
    id: HwChipSelectId,
}

impl HwCsPin {
    pub fn new<P: HwCsProvider + AnyPin>(pin: P) -> Self {
        configure_pin_as_hw_cs_pin(pin);
        Self {
            regs: unsafe { P::SPI_ID.steal_regs() },
            id: P::CS_ID,
        }
    }
}

impl embedded_hal::digital::ErrorType for HwCsPin {
    type Error = Infallible;
}

impl embedded_hal::digital::OutputPin for HwCsPin {
    fn set_low(&mut self) -> Result<(), Self::Error> {
        self.regs
            .modify_ctrl1(|value| value.with_sod(false).with_ss(self.id));
        Ok(())
    }

    fn set_high(&mut self) -> Result<(), Self::Error> {
        self.regs.modify_ctrl1(|value| value.with_sod(true));
        Ok(())
    }
}