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
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
//! Support for the Direct Memory Access (DMA) peripheral. This module handles initialization, and transfer
//! configuration for DMA. The `Dma::cfg_channel` method is called by modules that use DMA.

// todo: This module could be greatly simplified if [this issue](https://github.com/stm32-rs/stm32-rs/issues/610)
// todo is addressed: Ie H7 PAC approach adopted by other modules.

// todo: Use this clip or something similar to end terminate while loops, as in other modules.
// let mut i = 0;
// while asdf {
//     i += 1;
//     if i >= MAX_ITERS {
//         return Err(Error::Hardware);
//     }
// }

use core::{
    ops::Deref,
    sync::atomic::{self, Ordering},
};

use crate::{
    pac::{self, RCC},
    util::rcc_en_reset,
    MAX_ITERS,
};

cfg_if! {
    if #[cfg(all(feature = "g0", not(any(feature = "g0b1", feature = "g0c1"))))] {
        use crate::pac::{dma as dma1, DMA as DMA1};
    } else if #[cfg(feature = "f3x4")] {
        use crate::pac::{dma1, DMA1};
    }
    else {
        use crate::pac::{dma1, dma2, DMA1, DMA2};
    }
}

// use embedded_dma::{ReadBuffer, WriteBuffer};
use cfg_if::cfg_if;
#[cfg(any(feature = "g0", feature = "g4", feature = "wl"))]
use pac::DMAMUX;
// todo: DMAMUX2 support (Not sure if WB has it, but H7 has both).
#[cfg(any(feature = "l5", feature = "wb", feature = "h7"))]
use pac::DMAMUX1 as DMAMUX;
#[cfg(feature = "h7")]
use pac::DMAMUX2;
use paste::paste;

// todo: Several sections of this are only correct for DMA1.

#[derive(Clone, Copy)]
pub enum DmaPeriph {
    Dma1,
    #[cfg(not(any(
        feature = "f3x4",
        all(feature = "g0", not(any(feature = "g0b1", feature = "g0c1"))),
        feature = "wb",
    )))] // todo: f3x4 too
    Dma2,
}

#[derive(Copy, Clone)]
#[repr(usize)]
#[cfg(not(feature = "h7"))]
/// A list of DMA input sources. The integer values represent their DMAMUX register value, on
/// MCUs that use this. G4 RM, Table 91: DMAMUX: Assignment of multiplexer inputs to resources.
pub enum DmaInput {
    // This (on G4) goes up to 115. For now, just implement things we're likely
    // to use in this HAL. Make sure this is compatible beyond G4.
    Adc1 = 5,
    Dac1Ch1 = 6,
    Dac1Ch2 = 7,
    Tim6Up = 8,
    Tim7Up = 9,
    Spi1Rx = 10,
    Spi1Tx = 11,
    Spi2Rx = 12,
    Spi2Tx = 13,
    Spi3Rx = 14,
    Spi3Tx = 15,
    I2c1Rx = 16,
    I2c1Tx = 17,
    I2c2Rx = 18,
    I2c2Tx = 19,
    I2c3Rx = 20,
    I2c3Tx = 21,
    I2c4Rx = 22,
    I2c4Tx = 23,
    Usart1Rx = 24,
    Usart1Tx = 25,
    Usart2Rx = 26,
    Usart2Tx = 27,
    Usart3Rx = 28,
    Usart3Tx = 29,
    Uart4Rx = 30,
    Uart4Tx = 31,
    Uart5Rx = 32,
    Uart5Tx = 33,
    Lpuart1Rx = 34,
    Lpuart1Tx = 35,
    Adc2 = 36,
    Adc3 = 37,
    Adc4 = 38,
    Adc5 = 39,
    Quadspi = 40,
    Dac2Ch1 = 41,
    Tim1Ch1 = 42,
    Tim1Ch2 = 43,
    Tim1Ch3 = 44,
    Tim1Ch4 = 45,
    TimUp = 46,
    Tim1Trig = 47,
    Tim1Com = 48,
    Tim8Ch1 = 49,
    Tim8Ch2 = 50,
    Tim8Ch3 = 51,
    Tim8Ch4 = 52,
    Tim8Up = 53,
    Tim8Trig = 54,
    Tim8Com = 55,
    Tim2Ch1 = 56,
    Tim2Ch2 = 57,
    Tim2Ch3 = 58,
    Tim2Ch4 = 59,
    Tim2Up = 60,
    Tim3Ch1 = 61,
    Tim3Ch2 = 62,
    Tim3Ch3 = 63,
    Tim3Ch4 = 64,
    Tim3Up = 65,
    Tim3Trig = 66,
    Tim4Ch1 = 67,
    Tim4Ch2 = 68,
    Tim4Ch3 = 69,
    Tim4Ch4 = 70,
    Tim4Up = 71,
    Sai1A = 108,
    Sai1B = 109,
    // todo: These SAI2 values are bogus; can't find on G4 DMA mux.
    Sai2A = 203,
    Sai2B = 204,
    // todo: Can't find DFSDM periph on G4 rm: These assigned values are bogus.
    Dfsdm1F0 = 200,
    Dfsdm1F1 = 201,
    Dfsdm1F2 = 205,
    Dfsdm1F3 = 206,
}

// todo: Trigger, synchronization etc mappings. Perhaps DmaTrigger, DmaSync enums etc.

#[derive(Copy, Clone)]
#[repr(usize)]
#[cfg(feature = "h7")]
/// A list of DMA input sources. The integer values represent their DMAMUX register value, on
/// MCUs that use this. H743 RM, Table 121: DMAMUX1: Assignment of multiplexer inputs to resources.
/// (Table 118 in RM0468)
/// Note that this is only for DMAMUX1
pub enum DmaInput {
    Adc1 = 9,
    Adc2 = 10,
    Tim1Ch1 = 11,
    Tim1Ch2 = 12,
    Tim1Ch3 = 13,
    Tim1Ch4 = 14,
    Tim1Up = 15,
    Tim1Trig = 16,
    Tim1Com = 17,
    Tim2Ch1 = 18,
    Tim2Ch2 = 19,
    Tim2Ch3 = 20,
    Tim2Ch4 = 21,
    Tim2Up = 22,
    Tim3Ch1 = 23,
    Tim3Ch2 = 24,
    Tim3Ch3 = 25,
    Tim3Ch4 = 26,
    Tim3Up = 27,
    Tim3Trig = 28,
    Tim4Ch1 = 29,
    Tim4Ch2 = 30,
    Tim4Ch3 = 31,
    Tim4Up = 32,
    I2c1Rx = 33,
    I2c1Tx = 34,
    I2c2Rx = 35,
    I2c2Tx = 36,
    Spi1Rx = 37,
    Spi1Tx = 38,
    Spi2Rx = 39,
    Spi2Tx = 40,
    Usart1Rx = 41,
    Usart1Tx = 42,
    Usart2Rx = 43,
    Usart2Tx = 44,
    Usart3Rx = 45,
    Usart3Tx = 46,
    Tim5Ch1 = 55,
    Tim5Ch2 = 56,
    Tim5Ch3 = 57,
    Tim5Ch4 = 58,
    Tim5Up = 59,
    Tim5Trig = 60,
    Spi3Rx = 61,
    Spi3Tx = 62,
    Uart4Rx = 63,
    Uart4Tx = 64,
    Uart5Rx = 65,
    Uart5Tx = 66,
    DacCh1 = 67,
    DacCh2 = 68,
    Tim6Up = 69,
    Tim7Up = 70,
    Uart6Rx = 71,
    Uart6Tx = 72,
    I2c3Rx = 73,
    I2c3Tx = 74,
    Dcmi = 75,
    CrypIn = 76,
    CrypOut = 77,
    HashIn = 78,
    Uart7Rx = 79,
    Uart7Tx = 80,
    Uart8Rx = 81,
    Uart8Tx = 82,
    Sai1A = 87,
    Sai1B = 88,
    Sai2A = 89,
    Sai2B = 90,
    Dfsdm1F0 = 101,
    Dfsdm1F1 = 102,
    Dfsdm1F2 = 103,
    Dfsdm1F3 = 104,
    Sai3A = 113,
    Sai3B = 114,
    Adc3 = 115,
    Uart9Rx = 116,
    Uart9Tx = 117,
    Uart10Rx = 118,
    Uart10Tx = 119,
}

#[derive(Copy, Clone)]
#[repr(usize)]
#[cfg(feature = "h7")]
/// A list of DMA input sources for DMAMUX2. Used for BDMA. See H742 RM, Table 124.
pub enum DmaInput2 {
    Lpuart1Rx = 9,
    Lpuart1Tx = 10,
    Spi6Rx = 11,
    Spi6Tx = 12,
    I2c4Rx = 13,
    I3crTx = 14,
    Sai4A = 15,
    Sai4B = 16,
}

impl DmaInput {
    #[cfg(any(feature = "f3", feature = "l4"))]
    /// Select the hard set channel associated with a given input source. See L44 RM, Table 41.
    pub fn dma1_channel(&self) -> DmaChannel {
        match self {
            Self::Adc1 => DmaChannel::C1,
            Self::Dac1Ch1 => DmaChannel::C3,
            Self::Dac1Ch2 => DmaChannel::C4,
            // Self::Tim6Up => 8,
            // Self::Tim7Up => 9,
            Self::Spi1Rx => DmaChannel::C2,
            Self::Spi1Tx => DmaChannel::C3,
            Self::Spi2Rx => DmaChannel::C4,
            Self::Spi2Tx => DmaChannel::C5,
            // Self::Spi3Rx => 14,
            // Self::Spi3Tx => 15,
            Self::I2c1Rx => DmaChannel::C7,
            Self::I2c1Tx => DmaChannel::C6,
            Self::I2c2Rx => DmaChannel::C5,
            Self::I2c2Tx => DmaChannel::C4,
            Self::I2c3Rx => DmaChannel::C3,
            // Self::I2c3Tx => 21,
            // Self::I2c4Rx => 22,
            // Self::I2c4Tx => 23,
            Self::Usart1Rx => DmaChannel::C5,
            Self::Usart1Tx => DmaChannel::C4,
            Self::Usart2Rx => DmaChannel::C6,
            Self::Usart2Tx => DmaChannel::C7,
            Self::Usart3Rx => DmaChannel::C3,
            Self::Usart3Tx => DmaChannel::C2,
            // Self::Uart4Rx => 30,
            // Self::Uart4Tx => 31,
            // Self::Uart5Rx => 32,
            // Self::Uart5Tx => 33,
            // Self::Lpuart1Rx => 34,
            // Self::Lpuart1Tx => 35,
            Self::Adc2 => DmaChannel::C2,
            // Self::Adc3 => 37,
            // Self::Adc4 => 38,
            // Self::Adc5 => 39,
            // Note: Sai1 appears to be DMA2 only.
            Self::Sai2A => DmaChannel::C6,
            Self::Sai2B => DmaChannel::C7,
            Self::Dfsdm1F0 => DmaChannel::C4,
            Self::Dfsdm1F1 => DmaChannel::C5,
            Self::Dfsdm1F2 => DmaChannel::C6,
            Self::Dfsdm1F3 => DmaChannel::C7,
            _ => unimplemented!(),
        }
    }

    #[cfg(feature = "l4")]
    /// Find the value to set in the DMA_CSELR register, for L4. Ie, channel select value for a given DMA input.
    /// See L44 RM, Table 41.
    pub fn dma1_channel_select(&self) -> u8 {
        match self {
            Self::Adc1 => 0b000,
            Self::Dac1Ch1 => 0b0110,
            Self::Dac1Ch2 => 0b0101,
            // Self::Tim6Up => 8,
            // Self::Tim7Up => 9,
            Self::Spi1Rx => 0b001,
            Self::Spi1Tx => 0b001,
            Self::Spi2Rx => 0b001,
            Self::Spi2Tx => 0b001,
            // Self::Spi3Rx => 14,
            // Self::Spi3Tx => 15,
            Self::I2c1Rx => 0b011,
            Self::I2c1Tx => 0b011,
            Self::I2c2Rx => 0b011,
            Self::I2c2Tx => 0b011,
            Self::I2c3Rx => 0b011,
            // Self::I2c3Tx => 21,
            // Self::I2c4Rx => 22,
            // Self::I2c4Tx => 23,
            Self::Usart1Rx => 0b010,
            Self::Usart1Tx => 0b010,
            Self::Usart2Rx => 0b010,
            Self::Usart2Tx => 0b010,
            Self::Usart3Rx => 0b010,
            Self::Usart3Tx => 0b010,
            // Self::Uart4Rx => 30,
            // Self::Uart4Tx => 31,
            // Self::Uart5Rx => 32,
            // Self::Uart5Tx => 33,
            // Self::Lpuart1Rx => 34,
            // Self::Lpuart1Tx => 35,
            Self::Adc2 => 0b000,
            // Self::Adc3 => 37,
            // Self::Adc4 => 38,
            // Self::Adc5 => 39,
            Self::Dfsdm1F0 => 0b0000,
            Self::Dfsdm1F1 => 0b0000,
            Self::Dfsdm1F2 => 0b0000, // todo: QC?
            Self::Dfsdm1F3 => 0b0000,
            _ => unimplemented!(),
        }
    }
}

#[derive(Copy, Clone)]
#[repr(u8)]
/// L4 RM, 11.4.3, "DMA arbitration":
/// The priorities are managed in two stages:
/// • software: priority of each channel is configured in the DMA_CCRx register, to one of
/// the four different levels:
/// – very high
/// – high
/// – medium
/// – low
/// • hardware: if two requests have the same software priority level, the channel with the
/// lowest index gets priority. For example, channel 2 gets priority over channel 4.
/// Only write to this when the channel is disabled.
pub enum Priority {
    Low = 0b00,
    Medium = 0b01,
    High = 0b10,
    VeryHigh = 0b11,
}

#[derive(Copy, Clone)]
#[repr(u8)]
/// Represents a DMA channel to select, eg when configuring for use with a peripheral.
/// u8 representation is used to index registers on H7 PAC (And hopefully on future PACs if they
/// adopt H7's approach)
pub enum DmaChannel {
    // H7 calls these Streams. We use the `Channel` name for consistency.
    #[cfg(feature = "h7")]
    C0 = 0,
    C1 = 1,
    C2 = 2,
    C3 = 3,
    C4 = 4,
    C5 = 5,
    // todo: Some G0 variants have channels 6 and 7 and DMA1. (And up to 5 channels on DMA2)
    #[cfg(not(feature = "g0"))]
    C6 = 6,
    #[cfg(not(feature = "g0"))]
    C7 = 7,
    // todo: Which else have 8? Also, note that some have diff amounts on dma1 vs 2.
    #[cfg(any(feature = "l5", feature = "g4"))]
    C8 = 8,
}

#[derive(Copy, Clone)]
#[repr(u8)]
/// Set in CCR.
/// Can only be set when channel is disabled.
pub enum Direction {
    /// DIR = 0 defines typically a peripheral-to-memory transfer
    ReadFromPeriph = 0,
    /// DIR = 1 defines typically a memory-to-peripheral transfer.
    ReadFromMem = 1,
    MemToMem = 2,
}

#[derive(Copy, Clone, PartialEq)]
#[repr(u8)]
/// Set in CCR.
/// Can only be set when channel is disabled.
pub enum Circular {
    Disabled = 0,
    Enabled = 1,
}

#[derive(Copy, Clone)]
#[repr(u8)]
/// Peripheral and memory increment mode. (CCR PINC and MINC bits)
/// Can only be set when channel is disabled.
pub enum IncrMode {
    // Can only be set when channel is disabled.
    Disabled = 0,
    Enabled = 1,
}

#[derive(Copy, Clone)]
#[repr(u8)]
/// Peripheral and memory increment mode. (CCR PSIZE and MSIZE bits)
/// Can only be set when channel is disabled.
pub enum DataSize {
    S8 = 0b00, // ie 8 bits
    S16 = 0b01,
    S32 = 0b10,
}

#[derive(Copy, Clone)]
/// Interrupt type. Set in CCR using TEIE, HTIE, and TCIE bits.
/// Can only be set when channel is disabled.
pub enum DmaInterrupt {
    TransferError,
    HalfTransfer,
    TransferComplete,
    #[cfg(feature = "h7")]
    DirectModeError,
    #[cfg(feature = "h7")]
    FifoError,
}

/// Reduce DRY over channels when configuring a channel's CCR.
/// We must use a macro here, since match arms balk at the incompatible
/// types of `CCR1`, `CCR2` etc.
#[cfg(not(feature = "h7"))]
macro_rules! set_ccr {
    ($ccr:expr, $priority:expr, $direction:expr, $circular:expr, $periph_incr:expr, $mem_incr:expr, $periph_size:expr, $mem_size:expr) => {
        // "The register fields/bits MEM2MEM, PL[1:0], MSIZE[1:0], PSIZE[1:0], MINC, PINC, and DIR
        // are read-only when EN = 1"
        let originally_enabled = $ccr.read().en().bit_is_set();
        if originally_enabled {
            $ccr.modify(|_, w| w.en().clear_bit());
            while $ccr.read().en().bit_is_set() {}
        }

        if let Circular::Enabled = $circular {
            $ccr.modify(|_, w| w.mem2mem().clear_bit());
        }

        $ccr.modify(|_, w| unsafe {
            // – the channel priority
            w.pl().bits($priority as u8);
            // – the data transfer direction
            // This bit [DIR] must be set only in memory-to-peripheral and peripheral-to-memory modes.
            // 0: read from peripheral
            w.dir().bit($direction as u8 != 0);
            // – the circular mode
            w.circ().bit($circular as u8 != 0);
            // – the peripheral and memory incremented mode
            w.pinc().bit($periph_incr as u8 != 0);
            w.minc().bit($mem_incr as u8 != 0);
            // – the peripheral and memory data size
            w.psize().bits($periph_size as u8);
            w.msize().bits($mem_size as u8);
            // – the interrupt enable at half and/or full transfer and/or transfer error
            w.tcie().set_bit();
            // (See `Step 5` above.)
            w.en().set_bit()
        });

        if originally_enabled {
            $ccr.modify(|_, w| w.en().set_bit());
            while $ccr.read().en().bit_is_clear() {}
        }
    }
}

/// Reduce DRY over channels when configuring a channel's interrupts.
#[cfg(not(feature = "h7"))]
macro_rules! enable_interrupt {
    ($ccr:expr, $interrupt_type:expr) => {
        // "It must not be written when the channel is enabled (EN = 1)."
        let originally_enabled = $ccr.read().en().bit_is_set();
        if originally_enabled {
            $ccr.modify(|_, w| w.en().clear_bit());
            while $ccr.read().en().bit_is_set() {}
        }

        $ccr.modify(|_, w| match $interrupt_type {
            DmaInterrupt::TransferError => w.teie().set_bit(),
            DmaInterrupt::HalfTransfer => w.htie().set_bit(),
            DmaInterrupt::TransferComplete => w.tcie().set_bit(),
        });

        if originally_enabled {
            $ccr.modify(|_, w| w.en().set_bit());
            while $ccr.read().en().bit_is_clear() {}
        }
    };
}

/// Reduce DRY over channels when configuring a channel's interrupts.
#[cfg(not(feature = "h7"))]
macro_rules! disable_interrupt {
    ($ccr:expr, $interrupt_type:expr) => {
        // "It must not be written when the channel is disabled (EN = 1)."
        let originally_disabled = $ccr.read().en().bit_is_set();
        if originally_disabled {
            $ccr.modify(|_, w| w.en().clear_bit());
            while $ccr.read().en().bit_is_set() {}
        }

        $ccr.modify(|_, w| match $interrupt_type {
            DmaInterrupt::TransferError => w.teie().clear_bit(),
            DmaInterrupt::HalfTransfer => w.htie().clear_bit(),
            DmaInterrupt::TransferComplete => w.tcie().clear_bit(),
        });

        if originally_disabled {
            $ccr.modify(|_, w| w.en().set_bit());
            while $ccr.read().en().bit_is_clear() {}
        }
    };
}

/// This struct is used to pass common (non-peripheral and non-use-specific) data when configuring
/// a channel.
#[derive(Clone)]
pub struct ChannelCfg {
    /// Channel priority compared to other channels; can be low, medium, high, or very high. Defaults
    /// to medium.
    pub priority: Priority,
    /// Enable or disable circular DMA. If enabled, the transfer continues after reaching the end of
    /// the buffer, looping to the beginning. A TC interrupt first each time the end is reached, if
    /// set. Defaults to disabled.
    pub circular: Circular,
    /// Whether we increment the peripheral address on data word transfer; generally (and by default)
    /// disabled.
    pub periph_incr: IncrMode,
    /// Whether we increment the buffer address on data word transfer; generally (and by default)
    /// enabled.
    pub mem_incr: IncrMode,
}

impl Default for ChannelCfg {
    fn default() -> Self {
        Self {
            priority: Priority::Medium,
            circular: Circular::Disabled,
            // Increment the buffer address, not the peripheral address.
            periph_incr: IncrMode::Disabled,
            mem_incr: IncrMode::Enabled,
        }
    }
}

/// Represents a Direct Memory Access (DMA) peripheral.
pub struct Dma<D> {
    pub regs: D,
}

impl<D> Dma<D>
where
    D: Deref<Target = dma1::RegisterBlock>,
{
    /// Initialize a DMA peripheral, including enabling and resetting
    /// its RCC peripheral clock.
    pub fn new(regs: D) -> Self {
        // todo: Enable RCC for DMA 2 etc!
        let rcc = unsafe { &(*RCC::ptr()) };
        cfg_if! {
            if #[cfg(feature = "f3")] {
                rcc.ahbenr.modify(|_, w| w.dma1en().set_bit()); // no dmarst on F3.
            } else if #[cfg(feature = "g0")] {
                rcc_en_reset!(ahb1, dma, rcc);
            } else {
                rcc_en_reset!(ahb1, dma1, rcc);
            }
        }

        Self { regs }
    }

    #[cfg(not(feature = "h7"))] // due to num_data size diff
    /// Configure a DMA channel. See L4 RM 0394, section 11.4.4. Sets the Transfer Complete
    /// interrupt. Note that this fn has been (perhaps) depreciated by the standalone fn.
    pub fn cfg_channel(
        &mut self,
        channel: DmaChannel,
        periph_addr: u32,
        mem_addr: u32,
        num_data: u16,
        direction: Direction,
        periph_size: DataSize,
        mem_size: DataSize,
        cfg: ChannelCfg,
    ) {
        cfg_channel(
            &mut self.regs,
            channel,
            periph_addr,
            mem_addr,
            num_data,
            direction,
            periph_size,
            mem_size,
            cfg,
        )
    }

    #[cfg(feature = "h7")]
    /// Configure a DMA channel. See L4 RM 0394, section 11.4.4. Sets the Transfer Complete
    /// interrupt. Note that this fn has been (perhaps) depreciated by the standalone fn.
    pub fn cfg_channel(
        &mut self,
        channel: DmaChannel,
        periph_addr: u32,
        mem_addr: u32,
        num_data: u32,
        direction: Direction,
        periph_size: DataSize,
        mem_size: DataSize,
        cfg: ChannelCfg,
    ) {
        cfg_channel(
            &mut self.regs,
            channel,
            periph_addr,
            mem_addr,
            num_data,
            direction,
            periph_size,
            mem_size,
            cfg,
        )
    }

    #[cfg(feature = "l4")]
    pub(crate) fn channel_select(&mut self, input: DmaInput) {
        channel_select(&mut self.regs, input);
    }

    /// Stop a DMA transfer, if in progress.
    pub fn stop(&mut self, channel: DmaChannel) {
        stop_internal(&mut self.regs, channel);
    }

    /// Clear an interrupt flag.
    pub fn clear_interrupt(&mut self, channel: DmaChannel, interrupt: DmaInterrupt) {
        clear_interrupt_internal(&mut self.regs, channel, interrupt);
    }

    // todo: G0 removed from this fn due to a bug introduced in PAC 0.13
    #[cfg(not(any(feature = "h7", feature = "g0")))]
    pub fn transfer_is_complete(&mut self, channel: DmaChannel) -> bool {
        let isr_val = self.regs.isr.read();
        match channel {
            DmaChannel::C1 => isr_val.tcif1().bit_is_set(),
            DmaChannel::C2 => isr_val.tcif2().bit_is_set(),
            DmaChannel::C3 => isr_val.tcif3().bit_is_set(),
            DmaChannel::C4 => isr_val.tcif4().bit_is_set(),
            DmaChannel::C5 => isr_val.tcif5().bit_is_set(),
            #[cfg(not(feature = "g0"))]
            DmaChannel::C6 => isr_val.tcif6().bit_is_set(),
            #[cfg(not(feature = "g0"))]
            DmaChannel::C7 => isr_val.tcif7().bit_is_set(),
            #[cfg(any(feature = "l5", feature = "g4"))]
            DmaChannel::C8 => isr_val.tcif8().bit_is_set(),
        }
    }

    #[cfg(feature = "h7")]
    pub fn transfer_is_complete(&mut self, channel: DmaChannel) -> bool {
        match channel {
            DmaChannel::C0 => self.regs.lisr.read().tcif0().bit_is_set(),
            DmaChannel::C1 => self.regs.lisr.read().tcif1().bit_is_set(),
            DmaChannel::C2 => self.regs.lisr.read().tcif2().bit_is_set(),
            DmaChannel::C3 => self.regs.lisr.read().tcif3().bit_is_set(),
            DmaChannel::C4 => self.regs.hisr.read().tcif4().bit_is_set(),
            DmaChannel::C5 => self.regs.hisr.read().tcif5().bit_is_set(),
            DmaChannel::C6 => self.regs.hisr.read().tcif6().bit_is_set(),
            DmaChannel::C7 => self.regs.hisr.read().tcif7().bit_is_set(),
        }
    }

    /// Enable a specific type of interrupt.
    pub fn enable_interrupt(&mut self, channel: DmaChannel, interrupt: DmaInterrupt) {
        enable_interrupt_internal(&mut self.regs, channel, interrupt);
    }

    /// Disable a specific type of interrupt.
    /// todo: Non-H7 version too!
    #[cfg(feature = "h7")]
    pub fn disable_interrupt(&mut self, channel: DmaChannel, interrupt: DmaInterrupt) {
        // Can only be set when the channel is disabled.
        // todo: Is this true for disabling interrupts true, re the channel must be disabled?
        let cr = &self.regs.st[channel as usize].cr;

        let originally_enabled = cr.read().en().bit_is_set();

        if originally_enabled {
            cr.modify(|_, w| w.en().clear_bit());
            while cr.read().en().bit_is_set() {}
        }

        match interrupt {
            DmaInterrupt::TransferError => cr.modify(|_, w| w.teie().clear_bit()),
            DmaInterrupt::HalfTransfer => cr.modify(|_, w| w.htie().clear_bit()),
            DmaInterrupt::TransferComplete => cr.modify(|_, w| w.tcie().clear_bit()),
            DmaInterrupt::DirectModeError => cr.modify(|_, w| w.dmeie().clear_bit()),
            DmaInterrupt::FifoError => self.regs.st[channel as usize]
                .fcr
                .modify(|_, w| w.feie().clear_bit()),
        }

        if originally_enabled {
            cr.modify(|_, w| w.en().set_bit());
            while cr.read().en().bit_is_clear() {}
        }
    }
}

/// Configure a DMA channel. See L4 RM 0394, section 11.4.4. Sets the Transfer Complete
/// interrupt. This is the function called by various module `read_dma` and `write_dma` functions.
#[cfg(not(feature = "h7"))]
pub fn cfg_channel<D>(
    regs: &mut D,
    channel: DmaChannel,
    periph_addr: u32,
    mem_addr: u32,
    num_data: u16,
    direction: Direction,
    periph_size: DataSize,
    mem_size: DataSize,
    cfg: ChannelCfg,
) where
    D: Deref<Target = dma1::RegisterBlock>,
{
    // See the comments in the H7 variant for a description of what's going on.

    unsafe {
        match channel {
            DmaChannel::C1 => {
                cfg_if! {
                    if #[cfg(any(feature = "f3", feature = "g0"))] {
                        let cpar = &regs.ch1.par;
                    } else {
                        let cpar = &regs.cpar1;
                    }
                }
                cpar.write(|w| w.bits(periph_addr));
            }
            DmaChannel::C2 => {
                cfg_if! {
                    if #[cfg(any(feature = "f3", feature = "g0"))] {
                        let cpar = &regs.ch2.par;
                    } else {
                        let cpar = &regs.cpar2;
                    }
                }
                cpar.write(|w| w.bits(periph_addr));
            }
            DmaChannel::C3 => {
                cfg_if! {
                    if #[cfg(any(feature = "f3", feature = "g0"))] {
                        let cpar = &regs.ch3.par;
                    } else {
                        let cpar = &regs.cpar3;
                    }
                }
                cpar.write(|w| w.bits(periph_addr));
            }
            DmaChannel::C4 => {
                cfg_if! {
                    if #[cfg(any(feature = "f3", feature = "g0"))] {
                        let cpar = &regs.ch4.par;
                    } else {
                        let cpar = &regs.cpar4;
                    }
                }
                cpar.write(|w| w.bits(periph_addr));
            }
            DmaChannel::C5 => {
                cfg_if! {
                    if #[cfg(any(feature = "f3", feature = "g0"))] {
                        let cpar = &regs.ch5.par;
                    } else {
                        let cpar = &regs.cpar5;
                    }
                }
                cpar.write(|w| w.bits(periph_addr));
            }
            #[cfg(not(feature = "g0"))]
            DmaChannel::C6 => {
                cfg_if! {
                    if #[cfg(any(feature = "f3", feature = "g0"))] {
                        let cpar = &regs.ch6.par;
                    } else {
                        let cpar = &regs.cpar6;
                    }
                }
                cpar.write(|w| w.bits(periph_addr));
            }
            #[cfg(not(feature = "g0"))]
            DmaChannel::C7 => {
                cfg_if! {
                    if #[cfg(any(feature = "f3", feature = "g0"))] {
                        let cpar = &regs.ch7.par;
                    } else {
                        let cpar = &regs.cpar7;
                    }
                }
                cpar.write(|w| w.bits(periph_addr));
            }
            #[cfg(any(feature = "l5", feature = "g4"))]
            DmaChannel::C8 => {
                let cpar = &regs.cpar8;
                cpar.write(|w| w.bits(periph_addr));
            }
        }
    }

    atomic::compiler_fence(Ordering::SeqCst);
    unsafe {
        match channel {
            DmaChannel::C1 => {
                cfg_if! {
                    if #[cfg(any(feature = "f3", feature = "g0"))] {
                        let cmar = &regs.ch1.mar;
                    } else if #[cfg(feature = "l5")] {
                        let cmar = &regs.cm0ar1;
                    } else {
                        let cmar = &regs.cmar1;
                    }
                }
                cmar.write(|w| w.bits(mem_addr));
            }
            DmaChannel::C2 => {
                cfg_if! {
                    if #[cfg(any(feature = "f3", feature = "g0"))] {
                        let cmar = &regs.ch2.mar;
                    } else if #[cfg(feature = "l5")] {
                        let cmar = &regs.cm0ar2;
                    } else {
                        let cmar = &regs.cmar2;
                    }
                }
                cmar.write(|w| w.bits(mem_addr));
            }
            DmaChannel::C3 => {
                cfg_if! {
                    if #[cfg(any(feature = "f3", feature = "g0"))] {
                        let cmar = &regs.ch3.mar;
                    } else if #[cfg(feature = "l5")] {
                        let cmar = &regs.cm0ar3;
                    } else {
                        let cmar = &regs.cmar3;
                    }
                }
                cmar.write(|w| w.bits(mem_addr));
            }
            DmaChannel::C4 => {
                cfg_if! {
                    if #[cfg(any(feature = "f3", feature = "g0"))] {
                        let cmar = &regs.ch4.mar;
                    } else if #[cfg(feature = "l5")] {
                        let cmar = &regs.cm0ar4;
                    } else {
                        let cmar = &regs.cmar4;
                    }
                }
                cmar.write(|w| w.bits(mem_addr));
            }
            DmaChannel::C5 => {
                cfg_if! {
                    if #[cfg(any(feature = "f3", feature = "g0"))] {
                        let cmar = &regs.ch5.mar;
                    } else if #[cfg(feature = "l5")] {
                        let cmar = &regs.cm0ar5;
                    } else {
                        let cmar = &regs.cmar5;
                    }
                }
                cmar.write(|w| w.bits(mem_addr));
            }
            #[cfg(not(feature = "g0"))]
            DmaChannel::C6 => {
                cfg_if! {
                    if #[cfg(any(feature = "f3", feature = "g0"))] {
                        let cmar = &regs.ch6.mar;
                    } else if #[cfg(feature = "l5")] {
                        let cmar = &regs.cm0ar6;
                    } else {
                        let cmar = &regs.cmar6;
                    }
                }
                cmar.write(|w| w.bits(mem_addr));
            }
            #[cfg(not(feature = "g0"))]
            DmaChannel::C7 => {
                cfg_if! {
                    if #[cfg(any(feature = "f3", feature = "g0"))] {
                        let cmar = &regs.ch7.mar;
                    } else if #[cfg(feature = "l5")] {
                        let cmar = &regs.cm0ar7;
                    } else {
                        let cmar = &regs.cmar7;
                    }
                }
                cmar.write(|w| w.bits(mem_addr));
            }
            #[cfg(any(feature = "l5", feature = "g4"))]
            DmaChannel::C8 => {
                #[cfg(feature = "l5")]
                let cmar = &regs.cm0ar8;
                #[cfg(feature = "g4")]
                let cmar = &regs.cmar8;
                cmar.write(|w| w.bits(mem_addr));
            }
        }
    }

    #[cfg(any(feature = "l5", feature = "wl"))]
    let num_data = num_data as u32;

    #[cfg(not(feature = "l5"))] // todo: PAC ommission? ndt fields missing for diff ndt regs.
    unsafe {
        match channel {
            DmaChannel::C1 => {
                cfg_if! {
                    if #[cfg(any(feature = "f3", feature = "g0"))] {
                        let cndtr = &regs.ch1.ndtr;
                    } else {
                        let cndtr = &regs.cndtr1;
                    }
                }
                cndtr.write(|w| w.ndt().bits(num_data));
            }
            DmaChannel::C2 => {
                cfg_if! {
                    if #[cfg(any(feature = "f3", feature = "g0"))] {
                        let cndtr = &regs.ch2.ndtr;
                    } else {
                        let cndtr = &regs.cndtr2;
                    }
                }
                cndtr.write(|w| w.ndt().bits(num_data));
            }
            DmaChannel::C3 => {
                cfg_if! {
                    if #[cfg(any(feature = "f3", feature = "g0"))] {
                        let cndtr = &regs.ch3.ndtr;
                    } else {
                        let cndtr = &regs.cndtr3;
                    }
                }
                cndtr.write(|w| w.ndt().bits(num_data));
            }
            DmaChannel::C4 => {
                cfg_if! {
                    if #[cfg(any(feature = "f3", feature = "g0"))] {
                        let cndtr = &regs.ch4.ndtr;
                    } else {
                        let cndtr = &regs.cndtr4;
                    }
                }
                cndtr.write(|w| w.ndt().bits(num_data));
            }
            DmaChannel::C5 => {
                cfg_if! {
                    if #[cfg(any(feature = "f3", feature = "g0"))] {
                        let cndtr = &regs.ch5.ndtr;
                    } else {
                        let cndtr = &regs.cndtr5;
                    }
                }
                cndtr.write(|w| w.ndt().bits(num_data));
            }
            #[cfg(not(feature = "g0"))]
            DmaChannel::C6 => {
                cfg_if! {
                    if #[cfg(any(feature = "f3", feature = "g0"))] {
                        let cndtr = &regs.ch6.ndtr;
                    } else {
                        let cndtr = &regs.cndtr6;
                    }
                }
                cndtr.write(|w| w.ndt().bits(num_data));
            }
            #[cfg(not(feature = "g0"))]
            DmaChannel::C7 => {
                cfg_if! {
                    if #[cfg(any(feature = "f3", feature = "g0"))] {
                        let cndtr = &regs.ch7.ndtr;
                    } else {
                        let cndtr = &regs.cndtr7;
                    }
                }
                cndtr.write(|w| w.ndt().bits(num_data));
            }
            #[cfg(any(feature = "l5", feature = "g4"))]
            DmaChannel::C8 => {
                let cndtr = &regs.cndtr8;
                cndtr.write(|w| w.ndt().bits(num_data));
            }
        }
    }

    match channel {
        DmaChannel::C1 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch1.cr;
                } else {
                    let ccr = &regs.ccr1;
                }
            }
            set_ccr!(
                ccr,
                cfg.priority,
                direction,
                cfg.circular,
                cfg.periph_incr,
                cfg.mem_incr,
                periph_size,
                mem_size
            );
        }
        DmaChannel::C2 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch2.cr;
                } else {
                    let ccr = &regs.ccr2;
                }
            }
            set_ccr!(
                ccr,
                cfg.priority,
                direction,
                cfg.circular,
                cfg.periph_incr,
                cfg.mem_incr,
                periph_size,
                mem_size
            );
        }
        DmaChannel::C3 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch3.cr;
                } else {
                    let ccr = &regs.ccr3;
                }
            }
            set_ccr!(
                ccr,
                cfg.priority,
                direction,
                cfg.circular,
                cfg.periph_incr,
                cfg.mem_incr,
                periph_size,
                mem_size
            );
        }
        DmaChannel::C4 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch4.cr;
                } else {
                    let ccr = &regs.ccr4;
                }
            }
            set_ccr!(
                ccr,
                cfg.priority,
                direction,
                cfg.circular,
                cfg.periph_incr,
                cfg.mem_incr,
                periph_size,
                mem_size
            );
        }
        DmaChannel::C5 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch5.cr;
                } else {
                    let ccr = &regs.ccr5;
                }
            }
            set_ccr!(
                ccr,
                cfg.priority,
                direction,
                cfg.circular,
                cfg.periph_incr,
                cfg.mem_incr,
                periph_size,
                mem_size
            );
        }
        #[cfg(not(feature = "g0"))]
        DmaChannel::C6 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch6.cr;
                } else {
                    let ccr = &regs.ccr6;
                }
            }
            set_ccr!(
                ccr,
                cfg.priority,
                direction,
                cfg.circular,
                cfg.periph_incr,
                cfg.mem_incr,
                periph_size,
                mem_size
            );
        }
        #[cfg(not(feature = "g0"))]
        DmaChannel::C7 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch7.cr;
                } else {
                    let ccr = &regs.ccr7;
                }
            }
            set_ccr!(
                ccr,
                cfg.priority,
                direction,
                cfg.circular,
                cfg.periph_incr,
                cfg.mem_incr,
                periph_size,
                mem_size
            );
        }
        #[cfg(any(feature = "l5", feature = "g4"))]
        DmaChannel::C8 => {
            let ccr = &regs.ccr8;
            set_ccr!(
                ccr,
                cfg.priority,
                direction,
                cfg.circular,
                cfg.periph_incr,
                cfg.mem_incr,
                periph_size,
                mem_size
            );
        }
    }
}

/// Configure a DMA channel. See L4 RM 0394, section 11.4.4. Sets the Transfer Complete
/// interrupt. This is the function called by various module `read_dma` and `write_dma` functions.
#[cfg(feature = "h7")]
pub fn cfg_channel<D>(
    regs: &mut D,
    channel: DmaChannel,
    periph_addr: u32,
    mem_addr: u32,
    num_data: u32,
    direction: Direction,
    periph_size: DataSize,
    mem_size: DataSize,
    cfg: ChannelCfg,
) where
    D: Deref<Target = dma1::RegisterBlock>,
{
    // todo: The H7 sections are different, but we consolidated the comments. Figure out
    // todo what's different and fix it by following the steps

    regs.st[channel as usize]
        .cr
        .modify(|_, w| w.en().clear_bit());
    while regs.st[channel as usize].cr.read().en().bit_is_set() {}

    // H743 RM Section 15.3.19 The following sequence is needed to configure a DMA stream x:
    // 1. Set the peripheral register address in the DMA_CPARx register.
    // The data is moved from/to this address to/from the memory after the peripheral event,
    // or after the channel is enabled in memory-to-memory mode.
    regs.st[channel as usize]
        .par
        .write(|w| unsafe { w.bits(periph_addr) });

    atomic::compiler_fence(Ordering::SeqCst);

    // 2. Set the memory address in the DMA_CMARx register.
    // The data is written to/read from the memory after the peripheral event or after the
    // channel is enabled in memory-to-memory mode.
    regs.st[channel as usize]
        .m0ar
        .write(|w| unsafe { w.bits(mem_addr) });

    // todo: m1ar too, if in double-buffer mode.

    // 3. Configure the total number of data to transfer in the DMA_CNDTRx register.
    // After each data transfer, this value is decremented.
    regs.st[channel as usize]
        .ndtr
        .write(|w| unsafe { w.bits(num_data) });

    // 4. Configure the parameters listed below in the DMA_CCRx register:
    // (These are listed below by their corresponding reg write code)

    // todo: See note about sep reg writes to disable channel, and when you need to do this.

    // 5. Activate the channel by setting the EN bit in the DMA_CCRx register.
    // A channel, as soon as enabled, may serve any DMA request from the peripheral connected
    // to this channel, or may start a memory-to-memory block transfer.
    // Note: The two last steps of the channel configuration procedure may be merged into a single
    // access to the DMA_CCRx register, to configure and enable the channel.
    // When a channel is enabled and still active (not completed), the software must perform two
    // separate write accesses to the DMA_CCRx register, to disable the channel, then to
    // reprogram the channel for another next block transfer.
    // Some fields of the DMA_CCRx register are read-only when the EN bit is set to 1

    // (later): The circular mode must not be used in memory-to-memory mode. Before enabling a
    // channel in circular mode (CIRC = 1), the software must clear the MEM2MEM bit of the
    // DMA_CCRx register. When the circular mode is activated, the amount of data to transfer is
    // automatically reloaded with the initial value programmed during the channel configuration
    // phase, and the DMA requests continue to be served

    // (See remainder of steps in `set_ccr()!` macro.

    // todo: Let user set mem2mem mode?

    // See the [Embedonomicon section on DMA](https://docs.rust-embedded.org/embedonomicon/dma.html)
    // for info on why we use `compiler_fence` here:
    // "We use Ordering::Release to prevent all preceding memory operations from being moved
    // after [starting DMA], which performs a volatile write."

    let cr = &regs.st[channel as usize].cr;

    let originally_enabled = cr.read().en().bit_is_set();
    if originally_enabled {
        cr.modify(|_, w| w.en().clear_bit());
        while cr.read().en().bit_is_set() {}
    }

    cr.modify(|_, w| unsafe {
        // – the channel priority
        w.pl().bits(cfg.priority as u8);
        // – the data transfer direction
        // This bit [DIR] must be set only in memory-to-peripheral and peripheral-to-memory modes.
        // 0: read from peripheral
        w.dir().bits(direction as u8);
        // – the circular mode
        w.circ().bit(cfg.circular as u8 != 0);
        // – the peripheral and memory incremented mode
        w.pinc().bit(cfg.periph_incr as u8 != 0);
        w.minc().bit(cfg.mem_incr as u8 != 0);
        // – the peripheral and memory data size
        w.psize().bits(periph_size as u8);
        w.msize().bits(mem_size as u8);
        // – the interrupt enable at half and/or full transfer and/or transfer error
        w.tcie().set_bit();
        // (See `Step 5` above.)
        w.en().set_bit()
    });

    if originally_enabled {
        cr.modify(|_, w| w.en().set_bit());
        while cr.read().en().bit_is_clear() {}
    }
}

/// Stop a DMA transfer, if in progress.
#[cfg(not(feature = "h7"))]
fn stop_internal<D>(regs: &mut D, channel: DmaChannel)
where
    D: Deref<Target = dma1::RegisterBlock>,
{
    // L4 RM:
    // Once the software activates a channel, it waits for the completion of the programmed
    // transfer. The DMA controller is not able to resume an aborted active channel with a possible
    // suspended bus transfer.
    // To correctly stop and disable a channel, the software clears the EN bit of the DMA_CCRx
    // register.

    match channel {
        DmaChannel::C1 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch1.cr;
                } else {
                    let ccr = &regs.ccr1;
                }
            }
            ccr.modify(|_, w| w.en().clear_bit());
            while ccr.read().en().bit_is_set() {}
        }
        DmaChannel::C2 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch2.cr;
                } else {
                    let ccr = &regs.ccr2;
                }
            }
            ccr.modify(|_, w| w.en().clear_bit());
            while ccr.read().en().bit_is_set() {}
        }
        DmaChannel::C3 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch3.cr;
                } else {
                    let ccr = &regs.ccr3;
                }
            }
            ccr.modify(|_, w| w.en().clear_bit());
            while ccr.read().en().bit_is_set() {}
        }
        DmaChannel::C4 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch4.cr;
                } else {
                    let ccr = &regs.ccr4;
                }
            }
            ccr.modify(|_, w| w.en().clear_bit());
            while ccr.read().en().bit_is_set() {}
        }
        DmaChannel::C5 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch5.cr;
                } else {
                    let ccr = &regs.ccr5;
                }
            }
            ccr.modify(|_, w| w.en().clear_bit());
            while ccr.read().en().bit_is_set() {}
        }
        #[cfg(not(feature = "g0"))]
        DmaChannel::C6 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch6.cr;
                } else {
                    let ccr = &regs.ccr6;
                }
            }
            ccr.modify(|_, w| w.en().clear_bit());
            while ccr.read().en().bit_is_set() {}
        }
        #[cfg(not(feature = "g0"))]
        DmaChannel::C7 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch7.cr;
                } else {
                    let ccr = &regs.ccr7;
                }
            }
            ccr.modify(|_, w| w.en().clear_bit());
            while ccr.read().en().bit_is_set() {}
        }
        #[cfg(any(feature = "l5", feature = "g4"))]
        DmaChannel::C8 => {
            let ccr = &regs.ccr8;
            ccr.modify(|_, w| w.en().clear_bit());
            while ccr.read().en().bit_is_set() {}
        }
    };

    // The software secures that no pending request from the peripheral is served by the
    // DMA controller before the transfer completion.
    // todo?

    // The software waits for the transfer complete or transfer error interrupt.
    // (Handed by calling code)

    // (todo: set ifcr.cficx bit to clear all interrupts?)

    // When a channel transfer error occurs, the EN bit of the DMA_CCRx register is cleared by
    // hardware. This EN bit can not be set again by software to re-activate the channel x, until the
    // TEIFx bit of the DMA_ISR register is set
}

/// Stop a DMA transfer, if in progress.
#[cfg(feature = "h7")]
fn stop_internal<D>(regs: &mut D, channel: DmaChannel)
where
    D: Deref<Target = dma1::RegisterBlock>,
{
    // L4 RM:
    // Once the software activates a channel, it waits for the completion of the programmed
    // transfer. The DMA controller is not able to resume an aborted active channel with a possible
    // suspended bus transfer.
    // To correctly stop and disable a channel, the software clears the EN bit of the DMA_CCRx
    // register.

    // The software secures that no pending request from the peripheral is served by the
    // DMA controller before the transfer completion.
    // todo?

    let cr = &regs.st[channel as usize].cr;
    cr.modify(|_, w| w.en().clear_bit());
    while cr.read().en().bit_is_set() {}

    // The software waits for the transfer complete or transfer error interrupt.
    // (Handed by calling code)

    // (todo: set ifcr.cficx bit to clear all interrupts?)

    // When a channel transfer error occurs, the EN bit of the DMA_CCRx register is cleared by
    // hardware. This EN bit can not be set again by software to re-activate the channel x, until the
    // TEIFx bit of the DMA_ISR register is set
}

/// Stop a DMA transfer, if in progress.
pub fn stop(periph: DmaPeriph, channel: DmaChannel) {
    match periph {
        DmaPeriph::Dma1 => {
            let mut regs = unsafe { &(*DMA1::ptr()) };
            stop_internal(&mut regs, channel);
        }
        #[cfg(not(any(feature = "f3x4", feature = "g0", feature = "wb")))]
        DmaPeriph::Dma2 => {
            let mut regs = unsafe { &(*pac::DMA2::ptr()) };
            stop_internal(&mut regs, channel);
        }
    }
}

fn clear_interrupt_internal<D>(regs: &mut D, channel: DmaChannel, interrupt: DmaInterrupt)
where
    D: Deref<Target = dma1::RegisterBlock>,
{
    cfg_if! {
        if #[cfg(any(feature = "g4", feature = "wl"))] {
            regs.ifcr.write(|w| match channel {
                DmaChannel::C1 => match interrupt {
                    DmaInterrupt::TransferError => w.teif1().set_bit(),
                    DmaInterrupt::HalfTransfer => w.htif1().set_bit(),
                    DmaInterrupt::TransferComplete => w.tcif1().set_bit(),
                }
                DmaChannel::C2 => match interrupt {
                    DmaInterrupt::TransferError => w.teif2().set_bit(),
                    DmaInterrupt::HalfTransfer => w.htif2().set_bit(),
                    DmaInterrupt::TransferComplete => w.tcif2().set_bit(),
                }
                DmaChannel::C3 => match interrupt {
                    DmaInterrupt::TransferError => w.teif3().set_bit(),
                    DmaInterrupt::HalfTransfer => w.htif3().set_bit(),
                    DmaInterrupt::TransferComplete => w.tcif3().set_bit(),
                }
                DmaChannel::C4 => match interrupt {
                    DmaInterrupt::TransferError => w.teif4().set_bit(),
                    DmaInterrupt::HalfTransfer => w.htif4().set_bit(),
                    DmaInterrupt::TransferComplete => w.tcif4().set_bit(),
                }
                DmaChannel::C5 => match interrupt {
                    DmaInterrupt::TransferError => w.teif5().set_bit(),
                    DmaInterrupt::HalfTransfer => w.htif5().set_bit(),
                    DmaInterrupt::TransferComplete => w.tcif5().set_bit(),
                }
                DmaChannel::C6 => match interrupt {
                    DmaInterrupt::TransferError => w.teif6().set_bit(),
                    DmaInterrupt::HalfTransfer => w.htif6().set_bit(),
                    DmaInterrupt::TransferComplete => w.tcif6().set_bit(),
                }
                DmaChannel::C7 => match interrupt {
                    DmaInterrupt::TransferError => w.teif7().set_bit(),
                    DmaInterrupt::HalfTransfer => w.htif7().set_bit(),
                    DmaInterrupt::TransferComplete => w.tcif7().set_bit(),
                }
                #[cfg(not(feature = "wl"))]
                DmaChannel::C8 => match interrupt {
                    DmaInterrupt::TransferError => w.teif8().set_bit(),
                    DmaInterrupt::HalfTransfer => w.htif8().set_bit(),
                    DmaInterrupt::TransferComplete => w.tcif8().set_bit(),
                }
            });
        } else if #[cfg(feature = "h7")] {
            match channel {
                DmaChannel::C0 => match interrupt {
                    DmaInterrupt::TransferError => regs.lifcr.write(|w| w.cteif0().set_bit()),
                    DmaInterrupt::HalfTransfer => regs.lifcr.write(|w| w.chtif0().set_bit()),
                    DmaInterrupt::TransferComplete => regs.lifcr.write(|w| w.ctcif0().set_bit()),
                    DmaInterrupt::DirectModeError => regs.lifcr.write(|w| w.cdmeif0().set_bit()),
                    DmaInterrupt::FifoError => regs.lifcr.write(|w| w.cfeif0().set_bit()),
                }
                DmaChannel::C1 => match interrupt {
                    DmaInterrupt::TransferError => regs.lifcr.write(|w| w.cteif1().set_bit()),
                    DmaInterrupt::HalfTransfer => regs.lifcr.write(|w| w.chtif1().set_bit()),
                    DmaInterrupt::TransferComplete => regs.lifcr.write(|w| w.ctcif1().set_bit()),
                    DmaInterrupt::DirectModeError => regs.lifcr.write(|w| w.cdmeif1().set_bit()),
                    DmaInterrupt::FifoError => regs.lifcr.write(|w| w.cfeif1().set_bit()),
                }
                DmaChannel::C2 => match interrupt {
                    DmaInterrupt::TransferError => regs.lifcr.write(|w| w.cteif2().set_bit()),
                    DmaInterrupt::HalfTransfer => regs.lifcr.write(|w| w.chtif2().set_bit()),
                    DmaInterrupt::TransferComplete => regs.lifcr.write(|w| w.ctcif2().set_bit()),
                    DmaInterrupt::DirectModeError => regs.lifcr.write(|w| w.cdmeif2().set_bit()),
                    DmaInterrupt::FifoError => regs.lifcr.write(|w| w.cfeif2().set_bit()),
                }
                DmaChannel::C3 => match interrupt {
                    DmaInterrupt::TransferError => regs.lifcr.write(|w| w.cteif3().set_bit()),
                    DmaInterrupt::HalfTransfer => regs.lifcr.write(|w| w.chtif3().set_bit()),
                    DmaInterrupt::TransferComplete => regs.lifcr.write(|w| w.ctcif3().set_bit()),
                    DmaInterrupt::DirectModeError => regs.lifcr.write(|w| w.cdmeif3().set_bit()),
                    DmaInterrupt::FifoError => regs.lifcr.write(|w| w.cfeif3().set_bit()),
                }
                DmaChannel::C4 => match interrupt {
                    DmaInterrupt::TransferError => regs.hifcr.write(|w| w.cteif4().set_bit()),
                    DmaInterrupt::HalfTransfer => regs.hifcr.write(|w| w.chtif4().set_bit()),
                    DmaInterrupt::TransferComplete => regs.hifcr.write(|w| w.ctcif4().set_bit()),
                    DmaInterrupt::DirectModeError => regs.hifcr.write(|w| w.cdmeif4().set_bit()),
                    DmaInterrupt::FifoError => regs.hifcr.write(|w| w.cfeif4().set_bit()),
                }
                DmaChannel::C5 => match interrupt {
                    DmaInterrupt::TransferError => regs.hifcr.write(|w| w.cteif5().set_bit()),
                    DmaInterrupt::HalfTransfer => regs.hifcr.write(|w| w.chtif5().set_bit()),
                    DmaInterrupt::TransferComplete => regs.hifcr.write(|w| w.ctcif5().set_bit()),
                    DmaInterrupt::DirectModeError => regs.hifcr.write(|w| w.cdmeif5().set_bit()),
                    DmaInterrupt::FifoError => regs.hifcr.write(|w| w.cfeif5().set_bit()),
                }
                DmaChannel::C6 => match interrupt {
                    DmaInterrupt::TransferError => regs.hifcr.write(|w| w.cteif6().set_bit()),
                    DmaInterrupt::HalfTransfer => regs.hifcr.write(|w| w.chtif6().set_bit()),
                    DmaInterrupt::TransferComplete => regs.hifcr.write(|w| w.ctcif6().set_bit()),
                    DmaInterrupt::DirectModeError => regs.hifcr.write(|w| w.cdmeif6().set_bit()),
                    DmaInterrupt::FifoError => regs.hifcr.write(|w| w.cfeif6().set_bit()),
                }
                DmaChannel::C7 => match interrupt {
                    DmaInterrupt::TransferError => regs.hifcr.write(|w| w.cteif7().set_bit()),
                    DmaInterrupt::HalfTransfer => regs.hifcr.write(|w| w.chtif7().set_bit()),
                    DmaInterrupt::TransferComplete => regs.hifcr.write(|w| w.ctcif7().set_bit()),
                    DmaInterrupt::DirectModeError => regs.hifcr.write(|w| w.cdmeif7().set_bit()),
                    DmaInterrupt::FifoError => regs.hifcr.write(|w| w.cfeif7().set_bit()),
                }
            }
            // todo: G0 PAC 0.14 had a reversion where these flags used to work, but now don't.
        } else if #[cfg(not(feature = "g0"))] {
            regs.ifcr.write(|w| match channel {
                DmaChannel::C1 => match interrupt {
                    DmaInterrupt::TransferError => w.cteif1().set_bit(),
                    DmaInterrupt::HalfTransfer => w.chtif1().set_bit(),
                    DmaInterrupt::TransferComplete => w.ctcif1().set_bit(),
                }
                DmaChannel::C2 => match interrupt {
                    DmaInterrupt::TransferError => w.cteif2().set_bit(),
                    DmaInterrupt::HalfTransfer => w.chtif2().set_bit(),
                    DmaInterrupt::TransferComplete => w.ctcif2().set_bit(),
                }
                DmaChannel::C3 => match interrupt {
                    DmaInterrupt::TransferError => w.cteif3().set_bit(),
                    DmaInterrupt::HalfTransfer => w.chtif3().set_bit(),
                    DmaInterrupt::TransferComplete => w.ctcif3().set_bit(),
                }
                DmaChannel::C4 => match interrupt {
                    DmaInterrupt::TransferError => w.cteif4().set_bit(),
                    DmaInterrupt::HalfTransfer => w.chtif4().set_bit(),
                    DmaInterrupt::TransferComplete => w.ctcif4().set_bit(),
                }
                DmaChannel::C5 => match interrupt {
                    DmaInterrupt::TransferError => w.cteif5().set_bit(),
                    DmaInterrupt::HalfTransfer => w.chtif5().set_bit(),
                    DmaInterrupt::TransferComplete => w.ctcif5().set_bit(),
                }
                #[cfg(not(feature = "g0"))]
                DmaChannel::C6 => match interrupt {
                    DmaInterrupt::TransferError => w.cteif6().set_bit(),
                    DmaInterrupt::HalfTransfer => w.chtif6().set_bit(),
                    DmaInterrupt::TransferComplete => w.ctcif6().set_bit(),
                }
                #[cfg(not(feature = "g0"))]
                DmaChannel::C7 => match interrupt {
                    DmaInterrupt::TransferError => w.cteif7().set_bit(),
                    DmaInterrupt::HalfTransfer => w.chtif7().set_bit(),
                    DmaInterrupt::TransferComplete => w.ctcif7().set_bit(),
                }
                #[cfg(any(feature = "l5", feature = "g4"))]
                DmaChannel::C8 => match interrupt {
                    DmaInterrupt::TransferError => w.cteif8().set_bit(),
                    DmaInterrupt::HalfTransfer => w.chtif8().set_bit(),
                    DmaInterrupt::TransferComplete => w.ctcif8().set_bit(),
                }
            });
        }
    }
}

/// Enable an interrupt.
#[cfg(not(feature = "h7"))]
fn enable_interrupt_internal<D>(regs: &mut D, channel: DmaChannel, interrupt: DmaInterrupt)
where
    D: Deref<Target = dma1::RegisterBlock>,
{
    // Can only be set when the channel is disabled.
    match channel {
        DmaChannel::C1 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch1.cr;
                } else {
                    let ccr = &regs.ccr1;
                }
            }
            enable_interrupt!(ccr, interrupt);
        }
        DmaChannel::C2 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch2.cr;
                } else {
                    let ccr = &regs.ccr2;
                }
            }
            enable_interrupt!(ccr, interrupt);
        }
        DmaChannel::C3 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch3.cr;
                } else {
                    let ccr = &regs.ccr3;
                }
            }
            enable_interrupt!(ccr, interrupt);
        }
        DmaChannel::C4 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch4.cr;
                } else {
                    let ccr = &regs.ccr4;
                }
            }
            enable_interrupt!(ccr, interrupt);
        }
        DmaChannel::C5 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch5.cr;
                } else {
                    let ccr = &regs.ccr5;
                }
            }
            enable_interrupt!(ccr, interrupt);
        }
        #[cfg(not(feature = "g0"))]
        DmaChannel::C6 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch6.cr;
                } else {
                    let ccr = &regs.ccr6;
                }
            }
            enable_interrupt!(ccr, interrupt);
        }
        #[cfg(not(feature = "g0"))]
        DmaChannel::C7 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch7.cr;
                } else {
                    let ccr = &regs.ccr7;
                }
            }
            enable_interrupt!(ccr, interrupt);
        }
        #[cfg(any(feature = "l5", feature = "g4"))]
        DmaChannel::C8 => {
            let ccr = &regs.ccr8;
            enable_interrupt!(ccr, interrupt);
        }
    };
}

/// Disable an interrupt.
#[cfg(not(feature = "h7"))]
fn disable_interrupt_internal<D>(regs: &mut D, channel: DmaChannel, interrupt: DmaInterrupt)
where
    D: Deref<Target = dma1::RegisterBlock>,
{
    // Can only be set when the channel is disabled.
    match channel {
        DmaChannel::C1 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch1.cr;
                } else {
                    let ccr = &regs.ccr1;
                }
            }
            disable_interrupt!(ccr, interrupt);
        }
        DmaChannel::C2 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch2.cr;
                } else {
                    let ccr = &regs.ccr2;
                }
            }
            disable_interrupt!(ccr, interrupt);
        }
        DmaChannel::C3 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch3.cr;
                } else {
                    let ccr = &regs.ccr3;
                }
            }
            disable_interrupt!(ccr, interrupt);
        }
        DmaChannel::C4 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch4.cr;
                } else {
                    let ccr = &regs.ccr4;
                }
            }
            disable_interrupt!(ccr, interrupt);
        }
        DmaChannel::C5 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch5.cr;
                } else {
                    let ccr = &regs.ccr5;
                }
            }
            disable_interrupt!(ccr, interrupt);
        }
        #[cfg(not(feature = "g0"))]
        DmaChannel::C6 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch6.cr;
                } else {
                    let ccr = &regs.ccr6;
                }
            }
            disable_interrupt!(ccr, interrupt);
        }
        #[cfg(not(feature = "g0"))]
        DmaChannel::C7 => {
            cfg_if! {
                if #[cfg(any(feature = "f3", feature = "g0"))] {
                    let ccr = &regs.ch7.cr;
                } else {
                    let ccr = &regs.ccr7;
                }
            }
            disable_interrupt!(ccr, interrupt);
        }
        #[cfg(any(feature = "l5", feature = "g4"))]
        DmaChannel::C8 => {
            let ccr = &regs.ccr8;
            disable_interrupt!(ccr, interrupt);
        }
    };
}

#[cfg(feature = "h7")]
fn enable_interrupt_internal<D>(regs: &mut D, channel: DmaChannel, interrupt: DmaInterrupt)
where
    D: Deref<Target = dma1::RegisterBlock>,
{
    // Can only be set when the channel is disabled.
    let cr = &regs.st[channel as usize].cr;

    match interrupt {
        DmaInterrupt::TransferError => cr.modify(|_, w| w.teie().set_bit()),
        DmaInterrupt::HalfTransfer => cr.modify(|_, w| w.htie().set_bit()),
        DmaInterrupt::TransferComplete => cr.modify(|_, w| w.tcie().set_bit()),
        DmaInterrupt::DirectModeError => cr.modify(|_, w| w.dmeie().set_bit()),
        DmaInterrupt::FifoError => regs.st[channel as usize]
            .fcr
            .modify(|_, w| w.feie().set_bit()),
    }
}

#[cfg(feature = "h7")]
fn disable_interrupt_internal<D>(regs: &mut D, channel: DmaChannel, interrupt: DmaInterrupt)
where
    D: Deref<Target = dma1::RegisterBlock>,
{
    // Can only be set when the channel is disabled.
    let cr = &regs.st[channel as usize].cr;

    // todo DRY

    match interrupt {
        DmaInterrupt::TransferError => cr.modify(|_, w| w.teie().clear_bit()),
        DmaInterrupt::HalfTransfer => cr.modify(|_, w| w.htie().clear_bit()),
        DmaInterrupt::TransferComplete => cr.modify(|_, w| w.tcie().clear_bit()),
        DmaInterrupt::DirectModeError => cr.modify(|_, w| w.dmeie().clear_bit()),
        DmaInterrupt::FifoError => regs.st[channel as usize]
            .fcr
            .modify(|_, w| w.feie().clear_bit()),
    }
}

/// Enable a specific type of interrupt.
pub fn enable_interrupt(periph: DmaPeriph, channel: DmaChannel, interrupt: DmaInterrupt) {
    match periph {
        DmaPeriph::Dma1 => {
            let mut regs = unsafe { &(*DMA1::ptr()) };
            enable_interrupt_internal(&mut regs, channel, interrupt);
        }
        #[cfg(not(any(feature = "f3x4", feature = "g0", feature = "wb")))]
        DmaPeriph::Dma2 => {
            let mut regs = unsafe { &(*pac::DMA2::ptr()) };
            enable_interrupt_internal(&mut regs, channel, interrupt);
        }
    }
}

/// Disable a specific type of interrupt.
pub fn disable_interrupt(periph: DmaPeriph, channel: DmaChannel, interrupt: DmaInterrupt) {
    match periph {
        DmaPeriph::Dma1 => {
            let mut regs = unsafe { &(*DMA1::ptr()) };
            disable_interrupt_internal(&mut regs, channel, interrupt);
        }
        #[cfg(not(any(feature = "f3x4", feature = "g0", feature = "wb")))]
        DmaPeriph::Dma2 => {
            let mut regs = unsafe { &(*pac::DMA2::ptr()) };
            disable_interrupt_internal(&mut regs, channel, interrupt);
        }
    }
}

/// Clear an interrupt flag.
pub fn clear_interrupt(periph: DmaPeriph, channel: DmaChannel, interrupt: DmaInterrupt) {
    match periph {
        DmaPeriph::Dma1 => {
            let mut regs = unsafe { &(*DMA1::ptr()) };
            clear_interrupt_internal(&mut regs, channel, interrupt);
        }
        #[cfg(not(any(feature = "f3x4", feature = "g0", feature = "wb")))]
        DmaPeriph::Dma2 => {
            let mut regs = unsafe { &(*pac::DMA2::ptr()) };
            clear_interrupt_internal(&mut regs, channel, interrupt);
        }
    }
}

#[cfg(any(
    feature = "l5",
    feature = "g0",
    feature = "g4",
    feature = "h7",
    feature = "wb",
    feature = "wl",
))]
/// Configure a specific DMA channel to work with a specific peripheral.
pub fn mux(periph: DmaPeriph, channel: DmaChannel, input: DmaInput) {
    // Note: This is similar in API and purpose to `channel_select` above,
    // for different families. We're keeping it as a separate function instead
    // of feature-gating within the same function so the name can be recognizable
    // from the RM etc.

    // G4 example:
    // "The mapping of resources to DMAMUX is hardwired.
    // DMAMUX is used with DMA1 and DMA2:
    // For category 3 and category 4 devices:
    // •
    // DMAMUX channels 0 to 7 are connected to DMA1 channels 1 to 8
    // •
    // DMAMUX channels 8 to 15 are connected to DMA2 channels 1 to 8
    // For category 2 devices:
    // •
    // DMAMUX channels 0 to 5 are connected to DMA1 channels 1 to 6
    // •
    // DMAMUX channels 6 to 11 are connected to DMA2 channels 1 to 6"
    //
    // H723/25/33/35"
    // DMAMUX1 is used with DMA1 and DMA2 in D2 domain
    // •
    // DMAMUX1 channels 0 to 7 are connected to DMA1 channels 0 to 7
    // •
    // DMAMUX1 channels 8 to 15 are connected to DMA2 channels 0 to 7
    // (Note: The H7 and G4 cat 3/4 mappings are the same, except for H7's use of 0-7, and G4's use of 1-8.)

    // todo: With this in mind, some of the mappings below are not correct on some G4 variants.

    unsafe {
        let mux = unsafe { &(*DMAMUX::ptr()) };

        match periph {
            DmaPeriph::Dma1 => {
                #[cfg(not(feature = "h7"))]
                match channel {
                    // Note the offset by 1, due to mismatch in DMA channels starting at 1, and DMAMUX
                    // channels starting at 0. Ops tested this is correct on G4.
                    DmaChannel::C1 => mux.c0cr.modify(|_, w| w.dmareq_id().bits(input as u8)),
                    DmaChannel::C2 => mux.c1cr.modify(|_, w| w.dmareq_id().bits(input as u8)),
                    DmaChannel::C3 => mux.c2cr.modify(|_, w| w.dmareq_id().bits(input as u8)),
                    DmaChannel::C4 => mux.c3cr.modify(|_, w| w.dmareq_id().bits(input as u8)),
                    DmaChannel::C5 => mux.c4cr.modify(|_, w| w.dmareq_id().bits(input as u8)),
                    #[cfg(not(feature = "g0"))]
                    DmaChannel::C6 => mux.c5cr.modify(|_, w| w.dmareq_id().bits(input as u8)),
                    #[cfg(not(feature = "g0"))]
                    DmaChannel::C7 => mux.c6cr.modify(|_, w| w.dmareq_id().bits(input as u8)),
                    #[cfg(any(feature = "l5", feature = "g4"))]
                    DmaChannel::C8 => mux.c7cr.modify(|_, w| w.dmareq_id().bits(input as u8)),
                }

                #[cfg(feature = "h7")]
                mux.ccr[channel as usize].modify(|_, w| w.dmareq_id().bits(input as u8));
            }
            #[cfg(not(any(
                all(feature = "g0", not(any(feature = "g0b1", feature = "g0c1"))),
                feature = "wb"
            )))]
            DmaPeriph::Dma2 => {
                #[cfg(not(feature = "h7"))]
                match channel {
                    DmaChannel::C1 => mux.c8cr.modify(|_, w| w.dmareq_id().bits(input as u8)),
                    DmaChannel::C2 => mux.c9cr.modify(|_, w| w.dmareq_id().bits(input as u8)),
                    DmaChannel::C3 => mux.c10cr.modify(|_, w| w.dmareq_id().bits(input as u8)),
                    DmaChannel::C4 => mux.c11cr.modify(|_, w| w.dmareq_id().bits(input as u8)),
                    DmaChannel::C5 => mux.c12cr.modify(|_, w| w.dmareq_id().bits(input as u8)),
                    #[cfg(not(feature = "g0"))]
                    DmaChannel::C6 => mux.c13cr.modify(|_, w| w.dmareq_id().bits(input as u8)),
                    #[cfg(not(any(feature = "g0", feature = "wb", feature = "wl")))]
                    DmaChannel::C7 => mux.c14cr.modify(|_, w| w.dmareq_id().bits(input as u8)),
                    #[cfg(any(feature = "wb", feature = "wl"))]
                    DmaChannel::C7 => (), // Maybe no channel 7 on DMA2 on these platforms.
                    #[cfg(any(feature = "l5", feature = "g4"))]
                    DmaChannel::C8 => mux.c15cr.modify(|_, w| w.dmareq_id().bits(input as u8)),
                }

                #[cfg(feature = "h7")]
                mux.ccr[channel as usize + 8].modify(|_, w| w.dmareq_id().bits(input as u8));
            }
        }
    }
}

#[cfg(feature = "h7")]
/// Configure a specific DMA channel to work with a specific peripheral, on DMAMUX2.
pub fn mux2(periph: DmaPeriph, channel: DmaChannel, input: DmaInput2, mux: &mut DMAMUX2) {
    mux.ccr[channel as usize].modify(|_, w| unsafe { w.dmareq_id().bits(input as u8) });
}

// todo: Enable this for other MCUs as requried
/// Enable the DMA mux RCC clock. Applicable to some variants, but no others. (H7 and G0 don't use it,
/// for example)
#[cfg(any(feature = "g4", feature = "wb"))]
pub fn enable_mux1() {
    let rcc = unsafe { &(*RCC::ptr()) };

    cfg_if! {
        if #[cfg(feature = "g4")] {
            // Note inconsistency between `dmamux` and `dmamux`; can't use macro here.
            rcc.ahb1enr.modify(|_, w| w.dmamuxen().set_bit());
            rcc.ahb1rstr.modify(|_, w| w.dmamux1rst().set_bit());
            rcc.ahb1rstr.modify(|_, w| w.dmamux1rst().clear_bit());
        } else {
            rcc_en_reset!(ahb1, dmamux, rcc);
        }
    }
}

#[cfg(feature = "l4")] // Only required on L4
/// Select which peripheral on a given channel we're using.
/// See L44 RM, Table 41.
pub(crate) fn channel_select<D>(regs: &mut D, input: DmaInput)
where
    D: Deref<Target = dma1::RegisterBlock>,
{
    // todo: Allow selecting channels in pairs to save a write.
    let val = input.dma1_channel_select();
    regs.cselr.modify(|_, w| match input.dma1_channel() {
        DmaChannel::C1 => w.c1s().bits(val),
        DmaChannel::C2 => w.c2s().bits(val),
        DmaChannel::C3 => w.c3s().bits(val),
        DmaChannel::C4 => w.c4s().bits(val),
        DmaChannel::C5 => w.c5s().bits(val),
        DmaChannel::C6 => w.c6s().bits(val),
        DmaChannel::C7 => w.c7s().bits(val),
    });
}

// todo: Code below is for experimental struct-per-channel API
macro_rules! make_chan_struct {
    // ($Periph:ident, $PERIPH:ident, $periph:ident, $ch:expr) => {
    ($periph: expr, $ch:expr) => {
        paste! {
            /// Experimental/WIP channel-based DMA struct.
            pub struct [<Dma $periph Ch $ch>] {
                // #[cfg(feature = "h7")]
                // regs: dma1::st // todo?
            }

            impl [<Dma $periph Ch $ch>] {
                /// Initialize a DMA peripheral, including enabling and resetting
                /// its RCC peripheral clock.
                /// Note that the clock may have already been enabled by a different channel's
                /// constructor.
                pub fn new() -> Self {
                    // todo: Enable RCC for DMA 2 etc!
                    let rcc = unsafe { &(*RCC::ptr()) };
                    cfg_if! {
                        if #[cfg(feature = "f3")] {
                            rcc.ahbenr.modify(|_, w| w.dma1en().set_bit()); // no dmarst on F3.
                        } else if #[cfg(feature = "g0")] {
                            rcc_en_reset!(ahb1, dma, rcc);
                        } else {
                            rcc_en_reset!(ahb1, [<dma $periph>], rcc);
                        }
                    }

                    Self { }
                }

                fn regs(&self) -> &[<dma $periph>]::RegisterBlock {
                    unsafe { &(*[<DMA $periph>]::ptr())}
                }

                #[cfg(feature = "h7")]
                fn ccr(&self) -> &[<dma $periph>]::st::CR {
                // fn ccr(&self) -> &u8 {
                    &self.regs().st[$ch].cr
                }

                #[cfg(not(any(feature = "h7", feature = "f3", feature = "g0")))]
                fn ccr(&self) -> &[<dma $periph>]::[<CCR $ch>] {
                    &self.regs().[<ccr $ch>]
                }

                #[cfg(any(feature = "f3", feature = "g0"))]
                // fn ccr(&self) -> &[<dma $periph>]::ch::cr {
                 fn ccr(&self) -> i8 {
                    &self.regs().[<ch $ch>].cr
                }

                #[cfg(not(feature = "h7"))] // due to num_data size diff
                /// Configure a DMA channel. See L4 RM 0394, section 11.4.4. Sets the Transfer Complete
                /// interrupt. Note that this fn has been (perhaps) depreciated by the standalone fn.
                pub fn cfg_channel(
                    &mut self,
                    periph_addr: u32,
                    mem_addr: u32,
                    num_data: u16,
                    direction: Direction,
                    periph_size: DataSize,
                    mem_size: DataSize,
                    cfg: ChannelCfg,
                ) {
                    cfg_channel(
                        &mut self.regs(),
                        DmaChannel::[<C $ch>],
                        periph_addr,
                        mem_addr,
                        num_data,
                        direction,
                        periph_size,
                        mem_size,
                        cfg,
                    )
                }

                #[cfg(feature = "h7")]
                /// Configure a DMA channel. See L4 RM 0394, section 11.4.4. Sets the Transfer Complete
                /// interrupt. Note that this fn has been (perhaps) depreciated by the standalone fn.
                pub fn cfg_channel(
                    &mut self,
                    periph_addr: u32,
                    mem_addr: u32,
                    num_data: u32,
                    direction: Direction,
                    periph_size: DataSize,
                    mem_size: DataSize,
                    cfg: ChannelCfg,
                ) {
                    cfg_channel(
                        &mut self.regs(),
                        DmaChannel::[<C $ch>],
                        periph_addr,
                        mem_addr,
                        num_data,
                        direction,
                        periph_size,
                        mem_size,
                        cfg,
                    )
                }

                /// Stop a DMA transfer, if in progress.
                pub fn stop(&mut self) {
                    let ccr = self.ccr();

                    ccr.modify(|_, w| w.en().clear_bit());
                    while ccr.read().en().bit_is_set() {}
                }

                /// Enable a specific type of interrupt.
                pub fn enable_interrupt(&mut self, interrupt: DmaInterrupt) {
                    enable_interrupt_internal(&mut self.regs(), DmaChannel::[<C $ch>], interrupt);
                }

                /// Clear an interrupt flag.
                pub fn clear_interrupt(&mut self, interrupt: DmaInterrupt) {
                    clear_interrupt_internal(&mut self.regs(), DmaChannel::[<C $ch>], interrupt);
                }
                // todo: Other methods.
            }
        }
    };
}

// todo: As above, you may need more feature-gating, esp on
// todo DMA2.
// Note: G0 is limited, eg for some variants only up to DMA1, ch5.
cfg_if! {
    if #[cfg(not(any(feature = "f3", feature = "g0")))] {
        #[cfg(feature = "h7")]
        make_chan_struct!(1, 0);
        make_chan_struct!(1, 1);
        make_chan_struct!(1, 2);
        make_chan_struct!(1, 3);
        make_chan_struct!(1, 4);
        make_chan_struct!(1, 5);
        #[cfg(not(feature = "g0"))]
        make_chan_struct!(1, 6);
        #[cfg(not(feature = "g0"))]
        make_chan_struct!(1, 7);
        #[cfg(any(feature = "l5", feature = "g4"))]
        make_chan_struct!(1, 8);

        #[cfg(feature = "h7")]
        make_chan_struct!(2, 0);
        #[cfg(not(any(feature = "g0", feature = "wb")))]
        make_chan_struct!(2, 1);
        #[cfg(not(any(feature = "g0", feature = "wb")))]
        make_chan_struct!(2, 2);
        #[cfg(not(any(feature = "g0", feature = "wb")))]
        make_chan_struct!(2, 3);
        #[cfg(not(any(feature = "g0", feature = "wb")))]
        make_chan_struct!(2, 4);
        #[cfg(not(any(feature = "g0", feature = "wb")))]
        make_chan_struct!(2, 5);
        #[cfg(not(any(feature = "g0", feature = "wb")))]
        make_chan_struct!(2, 6);
        #[cfg(not(any(feature = "g0", feature = "wb")))]
        make_chan_struct!(2, 7);
        #[cfg(any(feature = "l5", feature = "g4"))]
        make_chan_struct!(2, 8);
    }
}