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
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
//! Low-power serial peripheral interface.
//!
//! [`Lpspi`] implements select embedded HAL SPI traits for coordinating SPI I/O.
//! When using the trait implementations, make sure that [`set_bit_order`](Lpspi::set_bit_order)
//! is correct for your device. These settings apply when the driver internally defines the transaction.
//!
//! This driver also exposes the peripheral's lower-level, hardware-dependent transaction interface.
//! Create a [`Transaction`], then [`enqueue_transaction`](Lpspi::enqueue_transaction) before
//! sending data with [`enqueue_data`](Lpspi::enqueue_data). When using the transaction interface,
//! you're responsible for serializing your data into `u32` SPI words.
//!
//! # Chip selects (CS) for SPI peripherals
//!
//! The iMXRT SPI peripherals have one or more peripheral-controlled chip selects (CS). Using
//! the peripheral-controlled CS means that you do not need a GPIO to coordinate SPI operations.
//! Blocking full-duplex transfers and writes will observe an asserted chip select while data
//! frames are exchanged / written.
//!
//! This driver generally assumes that you're using the peripheral-controlled chip select. If
//! you instead want to manage chip select in software, you should be able to multiplex your own
//! pins, then construct the driver [`without_pins`](Lpspi::without_pins).
//!
//! # Example
//!
//! Initialize an LPSPI with a 1MHz SCK. To understand how to configure the LPSPI
//! peripheral clock, see the [`ccm::lpspi_clk`](crate::ccm::lpspi_clk) documentation.
//!
//! ```no_run
//! use imxrt_hal as hal;
//! use imxrt_ral as ral;
//! # use eh02 as embedded_hal;
//! use embedded_hal::blocking::spi::Transfer;
//! use hal::lpspi::{Lpspi, Pins, SamplePoint};
//! use ral::lpspi::LPSPI4;
//!
//! let mut pads = // Handle to all processor pads...
//!     # unsafe { imxrt_iomuxc::imxrt1060::Pads::new() };
//!
//! # || -> Option<()> {
//! let spi_pins = Pins {
//!     sdo: pads.gpio_b0.p02,
//!     sdi: pads.gpio_b0.p01,
//!     sck: pads.gpio_b0.p03,
//!     pcs0: pads.gpio_b0.p00,
//! };
//!
//! let mut spi4 = unsafe { LPSPI4::instance() };
//! let mut spi = Lpspi::new(
//!     spi4,
//!     spi_pins,
//! );
//!
//! # const LPSPI_CLK_HZ: u32 = 1;
//! spi.disabled(|spi| {
//!     spi.set_clock_hz(LPSPI_CLK_HZ, 1_000_000);
//!     spi.set_sample_point(SamplePoint::Edge);
//! });
//!
//! let mut buffer: [u8; 3] = [1, 2, 3];
//! spi.transfer(&mut buffer).ok()?;
//!
//! let (spi4, pins) = spi.release();
//!
//! // Re-construct without pins:
//! let mut spi = Lpspi::without_pins(spi4);
//! # Some(()) }();
//! ```
//!
//! # Limitations
//!
//! Due to [a hardware defect][1], this driver does not yet support the EH02 SPI transaction API.
//! An early iteration of this driver reproduced the issue discussed in that forum. This driver may
//! be able to work around the defect in software, but it hasn't been explored.
//!
//! [1]: https://community.nxp.com/t5/i-MX-RT/RT1050-LPSPI-last-bit-not-completing-in-continuous-mode/m-p/898460
//!
//! [`Transaction`] exposes the continuous / continuing flags, so you're free to model advanced
//! transactions. However, keep in mind that disabling the receiver during a continuous transaction
//! may not work as expected.

use core::marker::PhantomData;
use core::task::Poll;

use crate::iomuxc::{consts, lpspi};
use crate::ral;

pub use eh02::spi::{Mode, Phase, Polarity, MODE_0, MODE_1, MODE_2, MODE_3};

/// Data direction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Direction {
    /// Transmit direction (leaving the peripheral).
    Tx,
    /// Receive direction (entering the peripheral).
    Rx,
}

/// Bit order.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum BitOrder {
    /// Data is transferred most significant bit first (default).
    #[default]
    Msb,
    /// Data is transferred least significant bit first.
    Lsb,
}

/// Receive sample point behavior.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SamplePoint {
    /// Input data is sampled on SCK edge.
    Edge,
    /// Input data is sampled on delayed SCK edge.
    DelayedEdge,
}

/// Possible errors when interfacing the LPSPI.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LpspiError {
    /// The transaction frame size is incorrect.
    ///
    /// The frame size, in bits, must be between 8 bits and
    /// 4095 bits.
    FrameSize,
    /// FIFO error in the given direction.
    Fifo(Direction),
    /// Bus is busy at the start of a transfer.
    Busy,
    /// Caller provided no data.
    NoData,
}

/// An LPSPI transaction definition.
///
/// The transaction defines how many bits the driver sends or recieves.
/// It also describes
///
/// - endianness
/// - bit order
/// - transmit and receive masking
/// - continuous and continuing transfers (default: both disabled)
///
/// The LPSPI enqueues the transaction data into the transmit
/// FIFO. When it pops the values from the FIFO, the values take
/// effect immediately. This may affect, or abort, any ongoing
/// transactions. Consult the reference manual to understand when
/// you should enqueue transaction definitions, since it may only
/// be supported on word / frame boundaries.
///
/// Construct `Transaction` with [`new`](Self::new), and supply
/// the number of **bits** to transmit per frame.
///
/// ```
/// use imxrt_hal as hal;
/// use hal::lpspi::Transaction;
///
/// // Send one u32.
/// let mut transaction
///     = Transaction::new(8 * core::mem::size_of::<u32>() as u16);
/// ```
///
/// Once constructed, manipulate the public members to change the
/// configuration.
///
/// # Continuous transactions
///
/// The pseudo-code below shows how to set [`continuous`](Self::continuous) and
/// [`continuing`](Self::continuing) to model a continuous transaction. Keep in
/// mind the hardware limitations; see the [module-level docs](crate::lpspi#limitations) for
/// details.
///
/// ```
/// use imxrt_hal as hal;
/// use hal::lpspi::Transaction;
///
/// // Skipping LPSPI initialization; see module-level example.
///
/// // Start byte exchange as a continuous transaction. Each frame
/// // exchanges one byte (eight bits) with a device.
/// # || -> Result<(), hal::lpspi::LpspiError> {
/// let mut transaction = Transaction::new(8)?;
/// transaction.continuous = true;
/// // Enqueue transaction with LPSPI...
/// // Enqueue one byte with LPSPI...   <-- PCS asserts here.
///
/// # let buffer: [u8; 5] = [0; 5];
/// for byte in buffer {
///     // Set 'continuing' to indicate that the next
///     // transaction continues the previous one...
///     transaction.continuing = true;
///
///     // Enqueue transaction with LPSPI...
///     // Enqueue byte with LPSPI...
/// }
///
/// transaction.continuous = false;
/// transaction.continuing = false;
/// // Enqueue transaction with LPSPI... <-- PCS de-asserts here.
/// # Ok(()) }().unwrap();
/// ```
pub struct Transaction {
    /// Enable byte swap.
    ///
    /// When enabled (`true`), swap bytes within the `u32` word. This allows
    /// you to change the endianness of the 32-bit word transfer. The
    /// default is `false`.
    pub byte_swap: bool,
    /// Bit order.
    ///
    /// See [`BitOrder`] for details. The default is [`BitOrder::Msb`].
    pub bit_order: BitOrder,
    /// Mask the received data.
    ///
    /// If `true`, the peripheral discards received data. Use this
    /// when you only care about sending data. The default is `false`;
    /// the peripheral puts received data in the receive FIFO.
    pub receive_data_mask: bool,
    /// Mask the transmit data.
    ///
    /// If `true`, the peripheral doesn't send any data. Use this when
    /// you only care about receiving data. The default is `false`;
    /// the peripheral expects to send data using the transmit FIFO.
    pub transmit_data_mask: bool,
    /// Indicates (`true`) the start of a continuous transfer.
    ///
    /// If set, the peripherals chip select will remain asserted after
    /// exchanging the frame. This allows you to enqueue new commands
    /// and data words within the same transaction. Those new commands
    /// should have [`continuing`](Self::continuing) set to `true`.
    ///
    /// The default is `false`; chip select de-asserts after exchanging
    /// the frame. To stop a continuous transfer, enqueue a new `Transaction`
    /// in which this flag, and `continuing`, is false.
    pub continuous: bool,
    /// Indicates (`true`) that this command belongs to a previous transaction.
    ///
    /// Set this to indicate that this new `Transaction` belongs to a previous
    /// `Transaction`, one that had [`continuous`](Self::continuous) set.
    /// The default value is `false`.
    pub continuing: bool,

    frame_size: u16,
}

impl Transaction {
    /// Defines a transaction for a `u32` buffer.
    ///
    /// After successfully defining a transaction of this buffer,
    /// supply it to the LPSPI driver, then start sending the
    /// data.
    ///
    /// Returns an error if any are true:
    ///
    /// - the buffer is empty.
    /// - there's more than 128 elements in the buffer.
    pub fn new_u32s(data: &[u32]) -> Result<Self, LpspiError> {
        Transaction::new_words(data)
    }

    fn new_words<W>(data: &[W]) -> Result<Self, LpspiError> {
        if let Ok(frame_size) = u16::try_from(8 * core::mem::size_of_val(data)) {
            Transaction::new(frame_size)
        } else {
            Err(LpspiError::FrameSize)
        }
    }

    fn frame_size_valid(frame_size: u16) -> bool {
        const MIN_FRAME_SIZE: u16 = 8;
        const MAX_FRAME_SIZE: u16 = 1 << 12;
        const WORD_SIZE: u16 = 32;

        let last_frame_size = frame_size % WORD_SIZE;

        (MIN_FRAME_SIZE..=MAX_FRAME_SIZE).contains(&frame_size) && (1 != last_frame_size)
    }

    /// Define a transaction by specifying the frame size, in bits.
    ///
    /// The frame size describes the number of bits that will be transferred and
    /// received during the next transaction. Specifically, it describes the number
    /// of bits for which the PCS pin signals a transaction.
    ///
    /// # Requirements
    ///
    /// - `frame_size` fits within 12 bits; the implementation enforces this maximum value.
    /// - The minimum value for `frame_size` is 8; the implementation enforces this minimum
    ///   value.
    /// - The last 32-bit word in the frame is at least 2 bits long.
    pub fn new(frame_size: u16) -> Result<Self, LpspiError> {
        if Self::frame_size_valid(frame_size) {
            Ok(Self {
                byte_swap: false,
                bit_order: Default::default(),
                receive_data_mask: false,
                transmit_data_mask: false,
                frame_size: frame_size - 1,
                continuing: false,
                continuous: false,
            })
        } else {
            Err(LpspiError::FrameSize)
        }
    }
}

/// Sets the clock speed parameters.
///
/// This should only happen when the LPSPI peripheral is disabled.
fn set_spi_clock(source_clock_hz: u32, spi_clock_hz: u32, reg: &ral::lpspi::RegisterBlock) {
    // Round up, so we always get a resulting SPI clock that is
    // equal or less than the requested frequency.
    let half_div =
        u32::try_from(1 + u64::from(source_clock_hz - 1) / (u64::from(spi_clock_hz) * 2)).unwrap();

    // Make sure SCKDIV is between 0 and 255
    // For some reason SCK starts to misbehave in between frames
    // if half_div is less than 3.
    let half_div = half_div.clamp(3, 128);
    // Because half_div is in range [3,128], sckdiv is in range [4, 254].
    let sckdiv = 2 * (half_div - 1);

    ral::write_reg!(ral::lpspi, reg, CCR,
        // Delay between two clock transitions of two consecutive transfers
        // is exactly sckdiv/2, which causes the transfer to be seamless.
        DBT: half_div - 1,
        // Add one sckdiv/2 setup and hold time before and after the transfer,
        // to make sure the signal is stable at sample time
        PCSSCK: half_div - 1,
        SCKPCS: half_div - 1,
        SCKDIV: sckdiv
    );
}

/// An LPSPI driver.
///
/// The driver exposes low-level methods for coordinating
/// DMA transfers. However, you may find it easier to use the
/// [`dma`](crate::dma) interface to coordinate DMA transfers.
///
/// The driver implements `embedded-hal` SPI traits. You should prefer
/// these implementations for their ease of use.
///
/// See the [module-level documentation](crate::lpspi) for an example
/// of how to construct this driver.
pub struct Lpspi<P, const N: u8> {
    lpspi: ral::lpspi::Instance<N>,
    pins: P,
    bit_order: BitOrder,
    mode: Mode,
}

/// Pins for a LPSPI device.
///
/// Consider using type aliases to simplify your usage:
///
/// ```no_run
/// use imxrt_hal as hal;
/// use imxrt_iomuxc::imxrt1060::gpio_b0::*;
///
/// // SPI pins used in my application
/// type LpspiPins = hal::lpspi::Pins<
///     GPIO_B0_02,
///     GPIO_B0_01,
///     GPIO_B0_03,
///     GPIO_B0_00,
/// >;
///
/// // Helper type for your SPI peripheral
/// type Lpspi<const N: u8> = hal::lpspi::Lpspi<LpspiPins, N>;
/// ```
pub struct Pins<SDO, SDI, SCK, PCS0> {
    /// Serial data out
    ///
    /// Data travels from the SPI host controller to the SPI device.
    pub sdo: SDO,
    /// Serial data in
    ///
    /// Data travels from the SPI device to the SPI host controller.
    pub sdi: SDI,
    /// Serial clock
    pub sck: SCK,
    /// Chip select 0
    ///
    /// (PCSx) convention matches the hardware.
    pub pcs0: PCS0,
}

impl<SDO, SDI, SCK, PCS0, const N: u8> Lpspi<Pins<SDO, SDI, SCK, PCS0>, N>
where
    SDO: lpspi::Pin<Module = consts::Const<N>, Signal = lpspi::Sdo>,
    SDI: lpspi::Pin<Module = consts::Const<N>, Signal = lpspi::Sdi>,
    SCK: lpspi::Pin<Module = consts::Const<N>, Signal = lpspi::Sck>,
    PCS0: lpspi::Pin<Module = consts::Const<N>, Signal = lpspi::Pcs0>,
{
    /// Create a new LPSPI driver from the RAL LPSPI instance and a set of pins.
    ///
    /// When this call returns, the LPSPI pins are configured for their function.
    /// The peripheral is enabled after reset. The LPSPI clock speed is unspecified.
    /// The mode is [`MODE_0`]. The sample point is [`SamplePoint::DelayedEdge`].
    pub fn new(lpspi: ral::lpspi::Instance<N>, mut pins: Pins<SDO, SDI, SCK, PCS0>) -> Self {
        lpspi::prepare(&mut pins.sdo);
        lpspi::prepare(&mut pins.sdi);
        lpspi::prepare(&mut pins.sck);
        lpspi::prepare(&mut pins.pcs0);
        Self::init(lpspi, pins)
    }
}

impl<const N: u8> Lpspi<(), N> {
    /// Create a new LPSPI driver from the RAL LPSPI instance.
    ///
    /// This is similar to [`new()`](Self::new), but it does not configure
    /// pins. You're responsible for configuring pins, and for making sure
    /// the pin configuration doesn't change while this driver is in use.
    pub fn without_pins(lpspi: ral::lpspi::Instance<N>) -> Self {
        Self::init(lpspi, ())
    }
}

impl<P, const N: u8> Lpspi<P, N> {
    /// The peripheral instance.
    pub const N: u8 = N;

    fn init(lpspi: ral::lpspi::Instance<N>, pins: P) -> Self {
        let spi = Lpspi {
            lpspi,
            pins,
            bit_order: BitOrder::default(),
            mode: MODE_0,
        };

        // Reset and disable
        ral::modify_reg!(ral::lpspi, spi.lpspi, CR, MEN: MEN_0, RST: RST_1);
        while spi.is_enabled() {}
        ral::modify_reg!(ral::lpspi, spi.lpspi, CR, RST: RST_0);

        // Reset Fifos
        ral::modify_reg!(ral::lpspi, spi.lpspi, CR, RTF: RTF_1, RRF: RRF_1);

        // Configure master mode
        ral::write_reg!(
            ral::lpspi,
            spi.lpspi,
            CFGR1,
            MASTER: MASTER_1,
            SAMPLE: SAMPLE_1
        );

        let tx_fifo_size = spi.max_watermark(Direction::Tx);
        // Configure watermarks
        ral::write_reg!(ral::lpspi, spi.lpspi, FCR,
            RXWATER: 0,               // Notify when we have any data available
            TXWATER: u32::from(tx_fifo_size) / 2 // Nofify when we have at least tx_fifo_size/2 space available
        );

        ral::write_reg!(ral::lpspi, spi.lpspi, CR, MEN: MEN_1);

        spi
    }

    /// Indicates if the driver is (`true`) or is not (`false`) enabled.
    pub fn is_enabled(&self) -> bool {
        ral::read_reg!(ral::lpspi, self.lpspi, CR, MEN == MEN_1)
    }

    /// Enable (`true`) or disable (`false`) the peripheral.
    ///
    /// Note that disabling does not take effect immediately; instead the
    /// peripheral finishes the current transfer and then disables itself.
    /// It is required to check [`is_enabled()`](Self::is_enabled) repeatedly until the
    /// peripheral is actually disabled.
    pub fn set_enable(&mut self, enable: bool) {
        ral::modify_reg!(ral::lpspi, self.lpspi, CR, MEN: enable as u32)
    }

    /// Reset the driver.
    ///
    /// Note that this may not not reset all peripheral state, like the
    /// enabled state.
    pub fn reset(&mut self) {
        ral::modify_reg!(ral::lpspi, self.lpspi, CR, RST: RST_1);
        while ral::read_reg!(ral::lpspi, self.lpspi, CR, RST == RST_1) {
            ral::modify_reg!(ral::lpspi, self.lpspi, CR, RST: RST_0);
        }
    }

    /// Release the SPI driver components.
    ///
    /// This does not change any component state; it releases the components as-is.
    /// If you need to obtain the registers in a known, good state, consider calling
    /// methods like [`reset()`](Self::reset) before releasing the registers.
    pub fn release(self) -> (ral::lpspi::Instance<N>, P) {
        (self.lpspi, self.pins)
    }

    /// Returns the bit order configuration.
    ///
    /// See notes in [`set_bit_order`](Lpspi::set_bit_order) to
    /// understand when this configuration takes effect.
    pub fn bit_order(&self) -> BitOrder {
        self.bit_order
    }

    /// Set the bit order configuration.
    ///
    /// This applies to all higher-level write and transfer operations.
    /// If you're using the [`Transaction`] API with manual word reads
    /// and writes, set the configuration as part of the transaction.
    pub fn set_bit_order(&mut self, bit_order: BitOrder) {
        self.bit_order = bit_order;
    }

    /// Temporarily disable the LPSPI peripheral.
    ///
    /// The handle to a [`Disabled`](crate::lpspi::Disabled) driver lets you modify
    /// LPSPI settings that require a fully disabled peripheral.
    pub fn disabled<R>(&mut self, func: impl FnOnce(&mut Disabled<N>) -> R) -> R {
        let mut disabled = Disabled::new(&mut self.lpspi, &mut self.mode);
        func(&mut disabled)
    }

    /// Read the status register.
    pub fn status(&self) -> Status {
        Status::from_bits_truncate(ral::read_reg!(ral::lpspi, self.lpspi, SR))
    }

    /// Clear the status flags.
    ///
    /// To clear status flags, set them high, then call `clear_status()`.
    ///
    /// The implementation will ensure that only the W1C bits are written, so it's
    /// OK to supply `Status::all()` to clear all bits.
    pub fn clear_status(&self, flags: Status) {
        let flags = flags & Status::W1C;
        ral::write_reg!(ral::lpspi, self.lpspi, SR, flags.bits());
    }

    /// Read the interrupt enable bits.
    pub fn interrupts(&self) -> Interrupts {
        Interrupts::from_bits_truncate(ral::read_reg!(ral::lpspi, self.lpspi, IER))
    }

    /// Set the interrupt enable bits.
    ///
    /// This writes the bits described by `interrupts` as is to the register.
    /// To modify the existing interrupts flags, you should first call [`interrupts`](Lpspi::interrupts)
    /// to get the current state, then modify that state.
    pub fn set_interrupts(&self, interrupts: Interrupts) {
        ral::write_reg!(ral::lpspi, self.lpspi, IER, interrupts.bits());
    }

    /// Clear any existing data in the SPI receive or transfer FIFOs.
    #[inline]
    pub fn clear_fifo(&mut self, direction: Direction) {
        match direction {
            Direction::Tx => ral::modify_reg!(ral::lpspi, self.lpspi, CR, RTF: RTF_1),
            Direction::Rx => ral::modify_reg!(ral::lpspi, self.lpspi, CR, RRF: RRF_1),
        }
    }

    /// Clear both FIFOs.
    pub fn clear_fifos(&mut self) {
        ral::modify_reg!(ral::lpspi, self.lpspi, CR, RTF: RTF_1, RRF: RRF_1);
    }

    /// Returns the watermark level for the given direction.
    #[inline]
    pub fn watermark(&self, direction: Direction) -> u8 {
        (match direction {
            Direction::Rx => ral::read_reg!(ral::lpspi, self.lpspi, FCR, RXWATER),
            Direction::Tx => ral::read_reg!(ral::lpspi, self.lpspi, FCR, TXWATER),
        }) as u8
    }

    /// Returns the FIFO status.
    #[inline]
    pub fn fifo_status(&self) -> FifoStatus {
        let (rxcount, txcount) = ral::read_reg!(ral::lpspi, self.lpspi, FSR, RXCOUNT, TXCOUNT);
        FifoStatus {
            rxcount: rxcount as u16,
            txcount: txcount as u16,
        }
    }

    /// Simply read whatever is in the receiver data register.
    fn read_data_unchecked(&self) -> u32 {
        ral::read_reg!(ral::lpspi, self.lpspi, RDR)
    }

    /// Read the data register.
    ///
    /// Returns `None` if the receive FIFO is empty. Otherwise, returns the complete
    /// read of the register. You're reponsible for interpreting the raw value as
    /// a data word, depending on the frame size.
    pub fn read_data(&mut self) -> Option<u32> {
        if ral::read_reg!(ral::lpspi, self.lpspi, RSR, RXEMPTY == RXEMPTY_0) {
            Some(self.read_data_unchecked())
        } else {
            None
        }
    }

    /// Place `word` into the transmit FIFO.
    ///
    /// This will result in the value being sent from the LPSPI.
    /// You're responsible for making sure that the transmit FIFO can
    /// fit this word.
    pub fn enqueue_data(&self, word: u32) {
        ral::write_reg!(ral::lpspi, self.lpspi, TDR, word);
    }

    /// Wait for transmit FIFO space in a (concurrent) spin loop.
    ///
    /// This future does not care about the TX FIFO watermark. Instead, it
    /// checks the FIFO's size with an additional read.
    pub(crate) async fn spin_for_fifo_space(&self) -> Result<(), LpspiError> {
        core::future::poll_fn(|_| {
            let status = self.status();
            if status.intersects(Status::TRANSMIT_ERROR) {
                return Poll::Ready(Err(LpspiError::Fifo(Direction::Tx)));
            }
            let fifo_status = self.fifo_status();
            if !fifo_status.is_full(Direction::Tx) {
                Poll::Ready(Ok(()))
            } else {
                Poll::Pending
            }
        })
        .await
    }

    pub(crate) fn wait_for_transmit_fifo_space(&self) -> Result<(), LpspiError> {
        crate::spin_on(self.spin_for_fifo_space())
    }

    /// Wait for receive data in a (concurrent) spin loop.
    ///
    /// This future does not care about the RX FIFO watermark. Instead, it
    /// checks the FIFO's size with an additional read.
    async fn spin_for_word(&self) -> Result<u32, LpspiError> {
        core::future::poll_fn(|_| {
            let status = self.status();
            if status.intersects(Status::RECEIVE_ERROR) {
                return Poll::Ready(Err(LpspiError::Fifo(Direction::Rx)));
            }

            let fifo_status = self.fifo_status();
            if !fifo_status.is_empty(Direction::Rx) {
                let data = self.read_data_unchecked();
                Poll::Ready(Ok(data))
            } else {
                Poll::Pending
            }
        })
        .await
    }

    /// Send `len` LPSPI words (u32s) out of the peripheral.
    ///
    /// Expected to run in a (concurrent) spin loop, possibly with
    /// `spin_receive`.
    async fn spin_transmit(
        &self,
        mut data: impl TransmitData,
        len: usize,
    ) -> Result<(), LpspiError> {
        for _ in 0..len {
            self.spin_for_fifo_space().await?;
            let word = data.next_word(self.bit_order);
            self.enqueue_data(word);
        }
        Ok(())
    }

    /// Accept `len` LPSPI words (u32s) from the peripheral.
    ///
    /// Expected to run in a (concurrent) spin loop, possibly with
    /// `spin_transmit`.
    async fn spin_receive(&self, mut data: impl ReceiveData, len: usize) -> Result<(), LpspiError> {
        for _ in 0..len {
            let word = self.spin_for_word().await?;
            data.next_word(word);
        }
        Ok(())
    }

    /// Set the SPI mode for the peripheral.
    ///
    /// This only affects the next transfer; ongoing transfers
    /// will not be influenced.
    pub fn set_mode(&mut self, mode: Mode) {
        self.mode = mode;
    }

    /// Place a transaction definition into the transmit FIFO.
    ///
    /// Once this definition is popped from the transmit FIFO, this may
    /// affect, or abort, any ongoing transactions.
    ///
    /// You're responsible for making sure there's space in the transmit
    /// FIFO for this transaction command.
    pub fn enqueue_transaction(&mut self, transaction: &Transaction) {
        ral::write_reg!(ral::lpspi, self.lpspi, TCR,
            CPOL: if self.mode.polarity == Polarity::IdleHigh { CPOL_1 } else { CPOL_0 },
            CPHA: if self.mode.phase == Phase::CaptureOnSecondTransition { CPHA_1 } else { CPHA_0 },
            PRESCALE: PRESCALE_0,
            PCS: PCS_0,
            WIDTH: WIDTH_0,
            LSBF: transaction.bit_order as u32,
            BYSW: transaction.byte_swap as u32,
            RXMSK: transaction.receive_data_mask as u32,
            TXMSK: transaction.transmit_data_mask as u32,
            FRAMESZ: transaction.frame_size as u32,
            CONT: transaction.continuous as u32,
            CONTC: transaction.continuing as u32
        );
    }

    /// Wait for all ongoing transactions to be finished.
    pub fn flush(&mut self) -> Result<(), LpspiError> {
        loop {
            let status = self.status();

            if status.intersects(Status::RECEIVE_ERROR) {
                return Err(LpspiError::Fifo(Direction::Rx));
            }
            if status.intersects(Status::TRANSMIT_ERROR) {
                return Err(LpspiError::Fifo(Direction::Tx));
            }

            // Contributor testing reveals that the busy flag may not set once
            // the TX FIFO is filled. This means a sequence like
            //
            //     lpspi.write(&[...])?;
            //     lpspi.flush()?;
            //
            // could pass through flush without observing busy. Therefore, we
            // also check the FIFO contents. Even if the peripheral isn't
            // busy, the FIFO should be non-empty.
            //
            // We can't just rely on the FIFO contents, since the FIFO could be
            // empty while the transaction is completing. (There's data in the
            // shift register, and PCS is still asserted.)
            if !status.intersects(Status::BUSY) && self.fifo_status().is_empty(Direction::Tx) {
                return Ok(());
            }
        }
    }

    fn exchange<W: Word>(&mut self, data: &mut [W]) -> Result<(), LpspiError> {
        if data.is_empty() {
            return Ok(());
        }

        let mut transaction = Transaction::new_words(data)?;
        transaction.bit_order = self.bit_order();

        self.wait_for_transmit_fifo_space()?;
        self.enqueue_transaction(&transaction);

        let word_count = word_count(data);
        let (tx, rx) = transfer_in_place(data);

        crate::spin_on(futures::future::try_join(
            self.spin_transmit(tx, word_count),
            self.spin_receive(rx, word_count),
        ))
        .map_err(|err| {
            self.recover_from_error();
            err
        })?;

        self.flush()?;

        Ok(())
    }

    fn write_no_read<W: Word>(&mut self, data: &[W]) -> Result<(), LpspiError> {
        if data.is_empty() {
            return Ok(());
        }

        let mut transaction = Transaction::new_words(data)?;
        transaction.receive_data_mask = true;
        transaction.bit_order = self.bit_order();

        self.wait_for_transmit_fifo_space()?;
        self.enqueue_transaction(&transaction);

        let word_count = word_count(data);
        let tx = TransmitBuffer::new(data);

        crate::spin_on(self.spin_transmit(tx, word_count)).map_err(|err| {
            self.recover_from_error();
            err
        })?;

        self.flush()?;

        Ok(())
    }

    /// Let the peripheral act as a DMA source.
    ///
    /// After this call, the peripheral will signal to the DMA engine whenever
    /// it has data available to read.
    pub fn enable_dma_receive(&mut self) {
        ral::modify_reg!(ral::lpspi, self.lpspi, FCR, RXWATER: 0); // No watermarks; affects DMA signaling
        ral::modify_reg!(ral::lpspi, self.lpspi, DER, RDDE: 1);
    }

    /// Stop the peripheral from acting as a DMA source.
    ///
    /// See the DMA chapter in the reference manual to understand when this
    /// should be called in the DMA transfer lifecycle.
    pub fn disable_dma_receive(&mut self) {
        while ral::read_reg!(ral::lpspi, self.lpspi, DER, RDDE == 1) {
            ral::modify_reg!(ral::lpspi, self.lpspi, DER, RDDE: 0);
        }
    }

    /// Let the peripheral act as a DMA destination.
    ///
    /// After this call, the peripheral will signal to the DMA engine whenever
    /// it has free space in its transfer buffer.
    pub fn enable_dma_transmit(&mut self) {
        ral::modify_reg!(ral::lpspi, self.lpspi, FCR, TXWATER: 0); // No watermarks; affects DMA signaling
        ral::modify_reg!(ral::lpspi, self.lpspi, DER, TDDE: 1);
    }

    /// Stop the peripheral from acting as a DMA destination.
    ///
    /// See the DMA chapter in the reference manual to understand when this
    /// should be called in the DMA transfer lifecycle.
    pub fn disable_dma_transmit(&mut self) {
        while ral::read_reg!(ral::lpspi, self.lpspi, DER, TDDE == 1) {
            ral::modify_reg!(ral::lpspi, self.lpspi, DER, TDDE: 0);
        }
    }

    /// Produces a pointer to the receiver data register.
    ///
    /// You should use this pointer when coordinating a DMA transfer.
    /// You're not expected to read from this pointer in software.
    pub fn rdr(&self) -> *const ral::RORegister<u32> {
        core::ptr::addr_of!(self.lpspi.RDR)
    }

    /// Produces a pointer to the transfer data register.
    ///
    /// You should use this pointer when coordinating a DMA transfer.
    /// You're not expected to read from this pointer in software.
    pub fn tdr(&self) -> *const ral::WORegister<u32> {
        core::ptr::addr_of!(self.lpspi.TDR)
    }

    fn max_watermark(&self, direction: Direction) -> u8 {
        (match direction {
            Direction::Rx => 1 << ral::read_reg!(ral::lpspi, self.lpspi, PARAM, RXFIFO),
            Direction::Tx => 1 << ral::read_reg!(ral::lpspi, self.lpspi, PARAM, TXFIFO),
        }) as u8
    }

    /// Reset all internal logic while preserving the driver's configurations.
    ///
    /// Unlike [`reset()`](Self::reset), this preserves all peripheral registers.
    pub fn soft_reset(&mut self) {
        // Backup previous registers
        let ier = ral::read_reg!(ral::lpspi, self.lpspi, IER);
        let der = ral::read_reg!(ral::lpspi, self.lpspi, DER);
        let cfgr0 = ral::read_reg!(ral::lpspi, self.lpspi, CFGR0);
        let cfgr1 = ral::read_reg!(ral::lpspi, self.lpspi, CFGR1);
        let dmr0 = ral::read_reg!(ral::lpspi, self.lpspi, DMR0);
        let dmr1 = ral::read_reg!(ral::lpspi, self.lpspi, DMR1);
        let ccr = ral::read_reg!(ral::lpspi, self.lpspi, CCR);
        let fcr = ral::read_reg!(ral::lpspi, self.lpspi, FCR);

        // Backup enabled state
        let enabled = self.is_enabled();

        // Reset and disable
        ral::modify_reg!(ral::lpspi, self.lpspi, CR, MEN: MEN_0, RST: RST_1);
        while self.is_enabled() {}
        ral::modify_reg!(ral::lpspi, self.lpspi, CR, RST: RST_0);

        // Reset fifos
        ral::modify_reg!(ral::lpspi, self.lpspi, CR, RTF: RTF_1, RRF: RRF_1);

        // Restore settings
        ral::write_reg!(ral::lpspi, self.lpspi, IER, ier);
        ral::write_reg!(ral::lpspi, self.lpspi, DER, der);
        ral::write_reg!(ral::lpspi, self.lpspi, CFGR0, cfgr0);
        ral::write_reg!(ral::lpspi, self.lpspi, CFGR1, cfgr1);
        ral::write_reg!(ral::lpspi, self.lpspi, DMR0, dmr0);
        ral::write_reg!(ral::lpspi, self.lpspi, DMR1, dmr1);
        ral::write_reg!(ral::lpspi, self.lpspi, CCR, ccr);
        ral::write_reg!(ral::lpspi, self.lpspi, FCR, fcr);

        // Restore enabled state
        self.set_enable(enabled);
    }

    /// Set the watermark level for a given direction.
    ///
    /// Returns the watermark level committed to the hardware. This may be different
    /// than the supplied `watermark`, since it's limited by the hardware.
    ///
    /// When `direction == Direction::Rx`, the receive data flag is set whenever the
    /// number of words in the receive FIFO is greater than `watermark`.
    ///
    /// When `direction == Direction::Tx`, the transmit data flag is set whenever the
    /// the number of words in the transmit FIFO is less than, or equal, to `watermark`.
    #[inline]
    pub fn set_watermark(&mut self, direction: Direction, watermark: u8) -> u8 {
        set_watermark(&self.lpspi, direction, watermark)
    }

    /// Recover from a transaction error.
    fn recover_from_error(&mut self) {
        // Resets the peripheral and flushes whatever is in the FIFOs.
        self.soft_reset();

        // Reset the status flags, clearing the error condition for the next use.
        self.clear_status(Status::TRANSMIT_ERROR | Status::RECEIVE_ERROR);
    }
}

bitflags::bitflags! {
    /// Status flags for the LPSPI interface.
    pub struct Status : u32 {
        /// Module busy flag.
        ///
        /// This flag is read only.
        const BUSY = 1 << 24;

        //
        // Start W1C bits.
        //

        /// Data match flag.
        ///
        /// Indicates that received data has matched one or both of the match
        /// fields. To clear this flag, write this bit to the status register
        /// (W1C).
        const DATA_MATCH = 1 << 13;
        /// Receive error flag.
        ///
        /// Set when the receive FIFO has overflowed. Before clearing this bit,
        /// empty the receive FIFO. Then, write this bit to clear the flag (W1C).
        const RECEIVE_ERROR = 1 << 12;
        /// Transmit error flag.
        ///
        /// Set when the transmit FIFO has underruns. Before clearing this bit,
        /// end the transfer. Then, write this bit to clear the flag (W1C).
        const TRANSMIT_ERROR = 1 << 11;
        /// Transfer complete flag.
        ///
        /// Set when the LPSPI returns to an idle state, and the transmit FIFO
        /// is empty. To clear this flag, write this bit (W1C).
        const TRANSFER_COMPLETE = 1 << 10;
        /// Frame complete flag.
        ///
        /// Set at the end of each frame transfer, when PCS negates. To clear this
        /// flag, write this bit (W1C).
        const FRAME_COMPLETE = 1 << 9;
        /// Word complete flag.
        ///
        /// Set when the last bit of a received word is sampled. To clear this flag, write
        /// this bit (W1C).
        const WORD_COMPLETE = 1 << 8;

        //
        // End W1C bits.
        //

        /// Receive data flag.
        ///
        /// Set when the number of words in the receive FIFO is greater than the watermark.
        /// This flag is read only. To clear the flag, exhaust the receive FIFO.
        const RECEIVE_DATA = 1 << 1;
        /// Transmit data flag.
        ///
        /// Set when the number of words in the transmit FIFO is less than or equal to the
        /// watermark. This flag is read only. TO clear the flag, fill the transmit FIFO.
        const TRANSMIT_DATA = 1 << 0;
    }
}

impl Status {
    const W1C: Self = Self::from_bits_truncate(
        Self::DATA_MATCH.bits()
            | Self::RECEIVE_ERROR.bits()
            | Self::TRANSMIT_ERROR.bits()
            | Self::TRANSFER_COMPLETE.bits()
            | Self::FRAME_COMPLETE.bits()
            | Self::WORD_COMPLETE.bits(),
    );
}

/// The number of words in each FIFO.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FifoStatus {
    /// Number of words in the receive FIFO.
    pub rxcount: u16,
    /// Number of words in the transmit FIFO.
    pub txcount: u16,
}

impl FifoStatus {
    /// Indicates if the FIFO is full for the given direction.
    #[inline]
    pub const fn is_full(self, direction: Direction) -> bool {
        /// See PARAM register docs.
        const MAX_FIFO_SIZE: u16 = 16;
        let count = match direction {
            Direction::Tx => self.txcount,
            Direction::Rx => self.rxcount,
        };
        count >= MAX_FIFO_SIZE
    }
    /// Indicates if the FIFO is empty for the given direction.
    #[inline]
    const fn is_empty(self, direction: Direction) -> bool {
        0 == match direction {
            Direction::Tx => self.txcount,
            Direction::Rx => self.rxcount,
        }
    }
}

bitflags::bitflags! {
    /// Interrupt flags.
    ///
    /// A high bit indicates that the condition generates an interrupt.
    /// See the status bits for more information.
    pub struct Interrupts : u32 {
        /// Data match interrupt enable.
        const DATA_MATCH = 1 << 13;
        /// Receive error interrupt enable.
        const RECEIVE_ERROR = 1 << 12;
        /// Transmit error interrupt enable.
        const TRANSMIT_ERROR = 1 << 11;
        /// Transmit complete interrupt enable.
        const TRANSMIT_COMPLETE = 1 << 10;
        /// Frame complete interrupt enable.
        const FRAME_COMPLETE = 1 << 9;
        /// Word complete interrupt enable.
        const WORD_COMPLETE = 1 << 8;

        /// Receive data interrupt enable.
        const RECEIVE_DATA = 1 << 1;
        /// Transmit data interrupt enable.
        const TRANSMIT_DATA = 1 << 0;
    }
}

#[inline]
fn set_watermark(lpspi: &ral::lpspi::RegisterBlock, direction: Direction, watermark: u8) -> u8 {
    let max_watermark = match direction {
        Direction::Rx => 1 << ral::read_reg!(ral::lpspi, lpspi, PARAM, RXFIFO),
        Direction::Tx => 1 << ral::read_reg!(ral::lpspi, lpspi, PARAM, TXFIFO),
    };

    let watermark = watermark.min(max_watermark - 1);

    match direction {
        Direction::Rx => {
            ral::modify_reg!(ral::lpspi, lpspi, FCR, RXWATER: watermark as u32)
        }
        Direction::Tx => {
            ral::modify_reg!(ral::lpspi, lpspi, FCR, TXWATER: watermark as u32)
        }
    }

    watermark
}

/// An LPSPI peripheral which is temporarily disabled.
pub struct Disabled<'a, const N: u8> {
    lpspi: &'a ral::lpspi::Instance<N>,
    mode: &'a mut Mode,
    men: bool,
}

impl<'a, const N: u8> Disabled<'a, N> {
    fn new(lpspi: &'a mut ral::lpspi::Instance<N>, mode: &'a mut Mode) -> Self {
        let men = ral::read_reg!(ral::lpspi, lpspi, CR, MEN == MEN_1);

        // Request disable
        ral::modify_reg!(ral::lpspi, lpspi, CR, MEN: MEN_0);
        // Wait for the driver to finish its current transfer
        // and enter disabled state
        while ral::read_reg!(ral::lpspi, lpspi, CR, MEN == MEN_1) {}
        Self { lpspi, mode, men }
    }

    /// Set the SPI mode for the peripheral
    #[deprecated(
        since = "0.5.5",
        note = "Use Lpspi::set_mode to change modes while enabled."
    )]
    pub fn set_mode(&mut self, mode: Mode) {
        *self.mode = mode;
    }

    /// Set the LPSPI clock speed (Hz).
    ///
    /// `source_clock_hz` is the LPSPI peripheral clock speed. To specify the
    /// peripheral clock, see the [`ccm::lpspi_clk`](crate::ccm::lpspi_clk) documentation.
    pub fn set_clock_hz(&mut self, source_clock_hz: u32, clock_hz: u32) {
        set_spi_clock(source_clock_hz, clock_hz, self.lpspi);
    }

    /// Set the watermark level for a given direction.
    ///
    /// Returns the watermark level committed to the hardware. This may be different
    /// than the supplied `watermark`, since it's limited by the hardware.
    ///
    /// When `direction == Direction::Rx`, the receive data flag is set whenever the
    /// number of words in the receive FIFO is greater than `watermark`.
    ///
    /// When `direction == Direction::Tx`, the transmit data flag is set whenever the
    /// the number of words in the transmit FIFO is less than, or equal, to `watermark`.
    #[inline]
    #[deprecated(
        since = "0.5.5",
        note = "Use Lpspi::set_watermark to change watermark while enabled"
    )]
    pub fn set_watermark(&mut self, direction: Direction, watermark: u8) -> u8 {
        set_watermark(self.lpspi, direction, watermark)
    }

    /// Set the sampling point of the LPSPI peripheral.
    ///
    /// When set to `SamplePoint::DelayedEdge`, the LPSPI will sample the input data
    /// on a delayed LPSPI_SCK edge, which improves the setup time when sampling data.
    #[inline]
    pub fn set_sample_point(&mut self, sample_point: SamplePoint) {
        match sample_point {
            SamplePoint::Edge => ral::modify_reg!(ral::lpspi, self.lpspi, CFGR1, SAMPLE: SAMPLE_0),
            SamplePoint::DelayedEdge => {
                ral::modify_reg!(ral::lpspi, self.lpspi, CFGR1, SAMPLE: SAMPLE_1)
            }
        }
    }
}

impl<const N: u8> Drop for Disabled<'_, N> {
    fn drop(&mut self) {
        ral::modify_reg!(ral::lpspi, self.lpspi, CR, MEN: self.men as u32);
    }
}

impl<P, const N: u8> eh02::blocking::spi::Transfer<u8> for Lpspi<P, N> {
    type Error = LpspiError;

    fn transfer<'a>(&mut self, words: &'a mut [u8]) -> Result<&'a [u8], Self::Error> {
        self.exchange(words)?;
        Ok(words)
    }
}

impl<P, const N: u8> eh02::blocking::spi::Transfer<u16> for Lpspi<P, N> {
    type Error = LpspiError;

    fn transfer<'a>(&mut self, words: &'a mut [u16]) -> Result<&'a [u16], Self::Error> {
        self.exchange(words)?;
        Ok(words)
    }
}

impl<P, const N: u8> eh02::blocking::spi::Transfer<u32> for Lpspi<P, N> {
    type Error = LpspiError;

    fn transfer<'a>(&mut self, words: &'a mut [u32]) -> Result<&'a [u32], Self::Error> {
        self.exchange(words)?;
        Ok(words)
    }
}

impl<P, const N: u8> eh02::blocking::spi::Write<u8> for Lpspi<P, N> {
    type Error = LpspiError;

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

impl<P, const N: u8> eh02::blocking::spi::Write<u16> for Lpspi<P, N> {
    type Error = LpspiError;

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

impl<P, const N: u8> eh02::blocking::spi::Write<u32> for Lpspi<P, N> {
    type Error = LpspiError;

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

// Not supporting WriteIter right now. Since we don't know how many bytes we're
// going to write, we can't specify the frame size. There might be ways around
// this by playing with CONTC and CONT bits, but we can evaluate that later.

/// Describes SPI words that can participate in transactions.
trait Word: Copy + Into<u32> + TryFrom<u32> {
    const MAX: Self;
    const ZERO: Self;

    /// Repeatedly call `provider` to produce yourself,
    /// then turn yourself into a LPSPI word.
    fn pack_word(bit_order: BitOrder, provider: impl FnMut() -> Option<Self>) -> u32;

    /// Given a word, deconstruct the word and call the
    /// `sink` with those components.
    fn unpack_word(word: u32, sink: impl FnMut(Self));
}

impl Word for u8 {
    const MAX: u8 = u8::MAX;
    const ZERO: u8 = 0;
    fn pack_word(bit_order: BitOrder, mut provider: impl FnMut() -> Option<Self>) -> u32 {
        let mut word = 0;
        match bit_order {
            BitOrder::Msb => {
                for _ in 0..4 {
                    if let Some(byte) = provider() {
                        word <<= 8;
                        word |= u32::from(byte);
                    }
                }
            }
            BitOrder::Lsb => {
                for offset in 0..4 {
                    if let Some(byte) = provider() {
                        word |= u32::from(byte) << (8 * offset);
                    }
                }
            }
        }

        word
    }
    fn unpack_word(word: u32, mut sink: impl FnMut(Self)) {
        for offset in [0, 8, 16, 24] {
            sink((word >> offset) as u8);
        }
    }
}

impl Word for u16 {
    const MAX: u16 = u16::MAX;
    const ZERO: u16 = 0;
    fn pack_word(bit_order: BitOrder, mut provider: impl FnMut() -> Option<Self>) -> u32 {
        let mut word = 0;
        match bit_order {
            BitOrder::Msb => {
                for _ in 0..2 {
                    if let Some(half) = provider() {
                        word <<= 16;
                        word |= u32::from(half);
                    }
                }
            }
            BitOrder::Lsb => {
                for offset in 0..2 {
                    if let Some(half) = provider() {
                        word |= u32::from(half) << (16 * offset);
                    }
                }
            }
        }

        word
    }
    fn unpack_word(word: u32, mut sink: impl FnMut(Self)) {
        for offset in [0, 16] {
            sink((word >> offset) as u16);
        }
    }
}

impl Word for u32 {
    const MAX: u32 = u32::MAX;
    const ZERO: u32 = 0;
    fn pack_word(_: BitOrder, mut provider: impl FnMut() -> Option<Self>) -> u32 {
        provider().unwrap_or(0)
    }
    fn unpack_word(word: u32, mut sink: impl FnMut(Self)) {
        sink(word)
    }
}

/// Generalizes how we prepare LPSPI words for transmit.
trait TransmitData {
    /// Get the next word for the transmit FIFO.
    ///
    /// If you're out of words, return 0.
    fn next_word(&mut self, bit_order: BitOrder) -> u32;
}

/// Generalizes how we save LPSPI data into memory.
trait ReceiveData {
    /// Invoked each time we read data from the queue.
    fn next_word(&mut self, word: u32);
}

/// Transmit data from a buffer.
struct TransmitBuffer<'a, W> {
    /// The read position.
    ptr: *const W,
    /// One past the end of the buffer.
    end: *const W,
    _buffer: PhantomData<&'a [W]>,
}

impl<'a, W> TransmitBuffer<'a, W>
where
    W: Word,
{
    fn new(buffer: &'a [W]) -> Self {
        // Safety: pointer offset math meets expectations.
        unsafe { Self::from_raw(buffer.as_ptr(), buffer.len()) }
    }

    /// # Safety
    ///
    /// `ptr + len` must be in bounds, or one past the end of the
    /// allocation.
    unsafe fn from_raw(ptr: *const W, len: usize) -> Self {
        Self {
            ptr,
            end: unsafe { ptr.add(len) },
            _buffer: PhantomData,
        }
    }

    /// Read the next element from the buffer.
    fn next_read(&mut self) -> Option<W> {
        // Safety: read the next word only if we're in bounds.
        unsafe {
            (self.ptr != self.end).then(|| {
                let word = self.ptr.read();
                self.ptr = self.ptr.add(1);
                word
            })
        }
    }
}

impl<W> TransmitData for TransmitBuffer<'_, W>
where
    W: Word,
{
    fn next_word(&mut self, bit_order: BitOrder) -> u32 {
        W::pack_word(bit_order, || self.next_read())
    }
}

/// Transmits dummy values.
struct TransmitDummies;

impl TransmitData for TransmitDummies {
    fn next_word(&mut self, _: BitOrder) -> u32 {
        u32::MAX
    }
}

/// Receive data into a buffer.
struct ReceiveBuffer<'a, W> {
    /// The write position.
    ptr: *mut W,
    /// One past the end of the buffer.
    end: *const W,
    _buffer: PhantomData<&'a [W]>,
}

impl<'a, W> ReceiveBuffer<'a, W>
where
    W: Word,
{
    #[cfg(test)] // TODO(mciantyre) remove once needed in non-test code.
    fn new(buffer: &'a mut [W]) -> Self {
        // Safety: pointer offset math meets expectations.
        unsafe { Self::from_raw(buffer.as_mut_ptr(), buffer.len()) }
    }

    /// # Safety
    ///
    /// `ptr + len` must be in bounds, or one past the end of the
    /// allocation.
    unsafe fn from_raw(ptr: *mut W, len: usize) -> Self {
        Self {
            ptr,
            end: unsafe { ptr.cast_const().add(len) },
            _buffer: PhantomData,
        }
    }

    /// Put the next element into the buffer.
    fn next_write(&mut self, elem: W) {
        // Safety: write the next word only if we're in bounds.
        // Words are primitive types; we don't need to execute
        // a drop when we overwrite a value in memory.
        unsafe {
            if self.ptr.cast_const() != self.end {
                self.ptr.write(elem);
                self.ptr = self.ptr.add(1);
            }
        }
    }
}

impl<W> ReceiveData for ReceiveBuffer<'_, W>
where
    W: Word,
{
    fn next_word(&mut self, word: u32) {
        W::unpack_word(word, |elem| self.next_write(elem));
    }
}

/// Receive dummy data.
struct ReceiveDummies;

impl ReceiveData for ReceiveDummies {
    fn next_word(&mut self, _: u32) {}
}

/// Computes how may Ws fit inside a LPSPI word.
const fn per_word<W: Word>() -> usize {
    core::mem::size_of::<u32>() / core::mem::size_of::<W>()
}

/// Computes how many u32 words we need to transact this buffer.
const fn word_count<W: Word>(words: &[W]) -> usize {
    (words.len() + per_word::<W>() - 1) / per_word::<W>()
}

/// Creates the transmit and receive buffer objects for an
/// in-place transfer.
fn transfer_in_place<W: Word>(buffer: &mut [W]) -> (TransmitBuffer<'_, W>, ReceiveBuffer<'_, W>) {
    // Safety: pointer math meets expectation. This produces
    // a mutable and immutable pointer to the same mutable buffer.
    // Module inspection shows that these pointers never become
    // references. We maintain the lifetime across both objects,
    // so the buffer isn't dropped.
    unsafe {
        let len = buffer.len();
        let ptr = buffer.as_mut_ptr();
        (
            TransmitBuffer::from_raw(ptr, len),
            ReceiveBuffer::from_raw(ptr, len),
        )
    }
}

/// Tests try to approximate the way we'll use TransmitBuffer and ReceiveBuffer
/// in firmware. Consider running these with miri to evaluate unsafe usages.
#[cfg(test)]
mod tests {
    #[test]
    fn transfer_in_place_interleaved_read_write_u32() {
        const BUFFER: [u32; 9] = [42u32, 43, 44, 45, 46, 47, 48, 49, 50];
        let mut buffer = BUFFER;
        let (mut tx, mut rx) = super::transfer_in_place(&mut buffer);

        for elem in BUFFER {
            assert_eq!(elem, tx.next_read().unwrap());
            rx.next_write(elem + 1);
        }

        assert_eq!(buffer, [43, 44, 45, 46, 47, 48, 49, 50, 51]);
    }

    #[test]
    fn transfer_in_place_interleaved_write_read_u32() {
        const BUFFER: [u32; 9] = [42u32, 43, 44, 45, 46, 47, 48, 49, 50];
        let mut buffer = BUFFER;
        let (mut tx, mut rx) = super::transfer_in_place(&mut buffer);

        for elem in BUFFER {
            rx.next_write(elem + 1);
            assert_eq!(elem + 1, tx.next_read().unwrap());
        }

        assert_eq!(buffer, [43, 44, 45, 46, 47, 48, 49, 50, 51]);
    }

    #[test]
    fn transfer_in_place_bulk_read_write_u32() {
        const BUFFER: [u32; 9] = [42u32, 43, 44, 45, 46, 47, 48, 49, 50];
        let mut buffer = BUFFER;
        let (mut tx, mut rx) = super::transfer_in_place(&mut buffer);

        for elem in BUFFER {
            assert_eq!(elem, tx.next_read().unwrap());
        }
        for elem in BUFFER {
            rx.next_write(elem + 1);
        }

        assert_eq!(buffer, [43, 44, 45, 46, 47, 48, 49, 50, 51]);
    }

    #[test]
    fn transfer_in_place_bulk_write_read_u32() {
        const BUFFER: [u32; 9] = [42u32, 43, 44, 45, 46, 47, 48, 49, 50];
        let mut buffer = BUFFER;
        let (mut tx, mut rx) = super::transfer_in_place(&mut buffer);

        for elem in BUFFER {
            rx.next_write(elem + 1);
        }
        for elem in BUFFER {
            assert_eq!(elem + 1, tx.next_read().unwrap());
        }

        assert_eq!(buffer, [43, 44, 45, 46, 47, 48, 49, 50, 51]);
    }

    #[test]
    fn transmit_buffer() {
        use super::{BitOrder::*, TransmitBuffer, TransmitData};

        //
        // u32
        //
        // This is the easiest to understand w.r.t. the bit order, since this is the natural word
        // size of the peripheral. No matter the bit order, we produce the same word for the TX
        // FIFO. The hardware handles the MSB or LSB transform.

        let mut tx = TransmitBuffer::new(&[0xDEADBEEFu32, 0xAD1CAC1D]);
        assert_eq!(tx.next_word(Msb), 0xDEADBEEF);
        assert_eq!(tx.next_word(Msb), 0xAD1CAC1D);
        assert_eq!(tx.next_word(Msb), 0);

        let mut tx = TransmitBuffer::new(&[0xDEADBEEFu32, 0xAD1CAC1D]);
        assert_eq!(tx.next_word(Lsb), 0xDEADBEEF);
        assert_eq!(tx.next_word(Lsb), 0xAD1CAC1D);
        assert_eq!(tx.next_word(Lsb), 0);

        //
        // u8
        //
        // If the user prefers u8 words, then we should pack the bytes into a u32 such that the
        // hardware's MSB/LSB transform maintains the (literal) byte order.

        let mut tx = TransmitBuffer::new(&[0xDEu8, 0xAD, 0xBE, 0xEF, 0xA5, 0x00, 0x1D]);
        assert_eq!(tx.next_word(Msb), 0xDEADBEEF);
        assert_eq!(tx.next_word(Msb), 0x00A5001D);
        assert_eq!(tx.next_word(Msb), 0);
        assert_eq!(tx.next_word(Msb), 0);

        let mut tx = TransmitBuffer::new(&[0xDEu8, 0xAD, 0xBE, 0xEF, 0xA5, 0x00, 0x1D]);
        assert_eq!(tx.next_word(Lsb), 0xEFBEADDE);
        assert_eq!(tx.next_word(Lsb), 0x001D00A5);
        assert_eq!(tx.next_word(Lsb), 0);
        assert_eq!(tx.next_word(Lsb), 0);

        let mut tx = TransmitBuffer::new(&[0xDEu8, 0xAD, 0xBE, 0xEF]);
        assert_eq!(tx.next_word(Msb), 0xDEADBEEF);
        assert_eq!(tx.next_word(Msb), 0);
        assert_eq!(tx.next_word(Msb), 0);

        let mut tx = TransmitBuffer::new(&[0xDEu8, 0xAD, 0xBE, 0xEF]);
        assert_eq!(tx.next_word(Lsb), 0xEFBEADDE);
        assert_eq!(tx.next_word(Lsb), 0);
        assert_eq!(tx.next_word(Lsb), 0);

        let mut tx = TransmitBuffer::new(&[0xDEu8, 0xAD, 0xBE]);
        assert_eq!(tx.next_word(Msb), 0x00DEADBE);
        assert_eq!(tx.next_word(Msb), 0);
        assert_eq!(tx.next_word(Msb), 0);

        let mut tx = TransmitBuffer::new(&[0xDEu8, 0xAD, 0xBE]);
        assert_eq!(tx.next_word(Lsb), 0x00BEADDE);
        assert_eq!(tx.next_word(Lsb), 0);
        assert_eq!(tx.next_word(Lsb), 0);

        //
        // u16
        //
        // Same goes here: we should combine u16s such that the hardware transfers elements
        // in order while applying the MSB/LSB transform on each u16.

        let mut tx = TransmitBuffer::new(&[0xDEADu16, 0xBEEF, 0xA5A5]);
        assert_eq!(tx.next_word(Msb), 0xDEADBEEF);
        assert_eq!(tx.next_word(Msb), 0x0000A5A5);
        assert_eq!(tx.next_word(Msb), 0);
        assert_eq!(tx.next_word(Msb), 0);

        let mut tx = TransmitBuffer::new(&[0xDEADu16, 0xBEEF, 0xA5A5]);
        assert_eq!(tx.next_word(Lsb), 0xBEEFDEAD);
        assert_eq!(tx.next_word(Lsb), 0x0000A5A5);
        assert_eq!(tx.next_word(Lsb), 0);
        assert_eq!(tx.next_word(Lsb), 0);

        let mut tx = TransmitBuffer::new(&[0xDEADu16, 0xBEEF]);
        assert_eq!(tx.next_word(Msb), 0xDEADBEEF);
        assert_eq!(tx.next_word(Msb), 0);
        assert_eq!(tx.next_word(Msb), 0);

        let mut tx = TransmitBuffer::new(&[0xDEADu16, 0xBEEF]);
        assert_eq!(tx.next_word(Lsb), 0xBEEFDEAD);
        assert_eq!(tx.next_word(Lsb), 0);
        assert_eq!(tx.next_word(Lsb), 0);

        let mut tx = TransmitBuffer::new(&[0xDEADu16]);
        assert_eq!(tx.next_word(Msb), 0x0000DEAD);
        assert_eq!(tx.next_word(Msb), 0);
        assert_eq!(tx.next_word(Msb), 0);

        let mut tx = TransmitBuffer::new(&[0xDEADu16]);
        assert_eq!(tx.next_word(Lsb), 0x0000DEAD);
        assert_eq!(tx.next_word(Lsb), 0);
        assert_eq!(tx.next_word(Lsb), 0);
    }

    #[test]
    fn receive_buffer() {
        use super::{ReceiveBuffer, ReceiveData};

        //
        // u8
        //

        let mut buffer = [0u8; 9];
        let mut rx = ReceiveBuffer::new(&mut buffer);
        rx.next_word(0xDEADBEEF);
        rx.next_word(0xAD1CAC1D);
        rx.next_word(0x04030201);
        rx.next_word(0x55555555);
        assert_eq!(
            buffer,
            [0xEF, 0xBE, 0xAD, 0xDE, 0x1D, 0xAC, 0x1C, 0xAD, 0x01]
        );

        //
        // u16
        //

        let mut buffer = [0u16; 5];
        let mut rx = ReceiveBuffer::new(&mut buffer);
        rx.next_word(0xDEADBEEF);
        rx.next_word(0xAD1CAC1D);
        rx.next_word(0x04030201);
        rx.next_word(0x55555555);
        assert_eq!(buffer, [0xBEEF, 0xDEAD, 0xAC1D, 0xAD1C, 0x0201]);

        //
        // u32
        //

        let mut buffer = [0u32; 3];
        let mut rx = ReceiveBuffer::new(&mut buffer);
        rx.next_word(0xDEADBEEF);
        rx.next_word(0xAD1CAC1D);
        rx.next_word(0x77777777);
        rx.next_word(0x55555555);
        assert_eq!(buffer, [0xDEADBEEF, 0xAD1CAC1D, 0x77777777]);
    }

    #[test]
    fn transaction_frame_sizes() {
        assert!(super::Transaction::new_words(&[1u8]).is_ok());
        assert!(super::Transaction::new_words(&[1u8, 2]).is_ok());
        assert!(super::Transaction::new_words(&[1u8, 2, 3]).is_ok());
        assert!(super::Transaction::new_words(&[1u8, 2, 3, 4]).is_ok());
        assert!(super::Transaction::new_words(&[1u8, 2, 3, 4, 5]).is_ok());

        assert!(super::Transaction::new_words(&[1u16]).is_ok());
        assert!(super::Transaction::new_words(&[1u16, 2]).is_ok());
        assert!(super::Transaction::new_words(&[1u16, 2, 3]).is_ok());
        assert!(super::Transaction::new_words(&[1u16, 2, 3, 4]).is_ok());
        assert!(super::Transaction::new_words(&[1u16, 2, 3, 4, 5]).is_ok());

        assert!(super::Transaction::new_words(&[1u32]).is_ok());
        assert!(super::Transaction::new_words(&[1u32, 2]).is_ok());
        assert!(super::Transaction::new_words(&[1u32, 2, 3]).is_ok());
        assert!(super::Transaction::new_words(&[1u32, 2, 3, 4]).is_ok());
        assert!(super::Transaction::new_words(&[1u32, 2, 3, 4, 5]).is_ok());

        assert!(super::Transaction::new(7).is_err());
        assert!(super::Transaction::new(8).is_ok());
        assert!(super::Transaction::new(9).is_ok());
        assert!(super::Transaction::new(31).is_ok());
        assert!(super::Transaction::new(32).is_ok());
        assert!(super::Transaction::new(33).is_err());
        assert!(super::Transaction::new(34).is_ok());
        assert!(super::Transaction::new(95).is_ok());
        assert!(super::Transaction::new(96).is_ok());
        assert!(super::Transaction::new(97).is_err());
        assert!(super::Transaction::new(98).is_ok());
    }
}