summaryrefslogtreecommitdiff
path: root/nuttx/arch/arm/src/sama5/sam_xdmac.c
blob: fd0118cb8872c06a30e65b2e129533f2367b934d (plain) (blame)
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
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
/****************************************************************************
 * arch/arm/src/sama5/sam_xdmac.c
 *
 *   Copyright (C) 2014 Gregory Nutt. All rights reserved.
 *   Author: Gregory Nutt <gnutt@nuttx.org>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name NuttX nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <nuttx/config.h>

#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <semaphore.h>
#include <debug.h>
#include <errno.h>

#include <nuttx/irq.h>
#include <nuttx/arch.h>
#include <arch/irq.h>

#include "up_arch.h"
#include "cache.h"
#include "up_internal.h"
#include "os_internal.h"

#include "chip.h"
#include "sam_dmac.h"
#include "sam_periphclks.h"
#include "sam_memories.h"
#include "chip/sam_pmc.h"
#include "chip/sam_xdmac.h"

/****************************************************************************
 * Pre-processor Definitions
 ****************************************************************************/

/* Configuration ************************************************************/

/* All of the currently supported SAMA5 chips support two DMA controllers
 * of 8 DMA Channels each.
 */

#if SAM_NDMAC < 1
#  undef CONFIG_SAMA5_XDMAC1
#  undef CONFIG_SAMA5_XDMAC0
#elif SAM_NDMAC < 2
#  undef CONFIG_SAMA5_XDMAC1
#endif

/* Condition out the whole file unless DMA is selected in the configuration */

#if defined(CONFIG_SAMA5_XDMAC0) || defined(CONFIG_SAMA5_XDMAC1)

/* If SAMA5 DMA support is enabled, then OS DMA support should also be
 * enabled
 */

#ifndef CONFIG_ARCH_DMA
#  warning "SAMA5 DMA enabled but CONFIG_ARCH_DMA disabled"
#endif

/* Check the number of link list descriptors to allocate */

#ifndef CONFIG_SAMA5_NLLDESC
#  define CONFIG_SAMA5_NLLDESC SAM_NDMACHAN
#endif

#if CONFIG_SAMA5_NLLDESC < SAM_NDMACHAN
#  warning "At least SAM_NDMACHAN descriptors must be allocated"

#  undef CONFIG_SAMA5_NLLDESC
#  define CONFIG_SAMA5_NLLDESC SAM_NDMACHAN
#endif

/* Register values **********************************************************/

#define XDMAC_CH_CTRLB_BOTHDSCR \
  (XDMAC_CH_CTRLB_SRCDSCR | XDMAC_CH_CTRLB_DSTDSCR)

/****************************************************************************
 * Private Types
 ****************************************************************************/
/* This structure maps a peripheral ID to an DMA channel */

struct sam_pidmap_s
{
  uint8_t pid;                    /* Peripheral identifier */
  uint8_t pchan;                  /* DMA channel */
};

/* This structure descibes one DMA channel */

struct sam_xdmach_s
{
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
  uint8_t xdmac;                  /* DMA controller number (0-1) */
#endif
  uint8_t chan;                   /* DMA channel number (0-15) */
  bool inuse;                     /* TRUE: The DMA channel is in use */
  bool rx;                        /* TRUE: Peripheral to memory transfer */
  uint32_t flags;                 /* DMA channel flags */
  uint32_t base;                  /* DMA register channel base address */
  uint32_t cfg;                   /* Pre-calculated CFG register for transfer */
  dma_callback_t callback;        /* Callback invoked when the DMA completes */
  void *arg;                      /* Argument passed to callback function */
  uint32_t rxaddr;                /* RX memory address */
  size_t rxsize;                  /* Size of RX memory region */
  struct dma_linklist_s *llhead;  /* DMA link list head */
  struct dma_linklist_s *lltail;  /* DMA link list head */
};

/* This structure describes the stae of one DMA controller */

struct sam_xdmac_s
{
  /* These semaphores protect the DMA channel and descriptor tables */

  sem_t chsem;                       /* Protects channel table */
  sem_t dsem;                        /* Protects descriptor table */
  uint32_t base;                     /* DMA register channel base address */

  /* This array describes the available link list descriptors */

  struct dma_linklist_s *desc;

  /* This array describes each DMA channel */

  struct sam_xdmach_s *xdmach;
};

/****************************************************************************
 * Private Data
 ****************************************************************************/

/* CTRLA field lookups */

static const uint32_t g_chanwidth[4] =
{
  XDMACH_CC_DWIDTH_BYTE,
  XDMACH_CC_DWIDTH_HWORD,
  XDMACH_CC_DWIDTH_WORD,
  XDMACH_CC_DWIDTH_DWORD
};

static const uint32_t g_fifocfg[3] =
{
  XDMAC_CH_CFG_FIFOCFG_ALAP,
  XDMAC_CH_CFG_FIFOCFG_HALF,
  XDMAC_CH_CFG_FIFOCFG_ASAP
};

/* These tables map peripheral IDs to channels.  A lookup is performed
 * before each DMA transfer in order to map the peripheral IDs to the
 * correct channel.  This must be done because the channel can change with
 * the direction of the transfer.
 */

#ifdef CONFIG_SAMA5_XDMAC0
/* DMA controller 0, RX DMA: */

static const struct sam_pidmap_s g_xdmac0_rxchan[] =
{
  { SAM_PID_HSMCI0, XDMAC0_CH_HSMCI0    }, /* HSMCI0 Receive/Transmit */
  { SAM_PID_HSMCI1, XDMAC0_CH_HSMCI1    }, /* HSMCI1 Receive/Transmit */
  { SAM_PID_TWI0,   XDMAC0_CH_TWI0_RX   }, /* TWI0 Receive */
  { SAM_PID_TWI1,   XDMAC0_CH_TWI1_RX   }, /* TWI1 Receive */
  { SAM_PID_TWI2,   XDMAC0_CH_TWI2_RX   }, /* TWI2 Receive */
  { SAM_PID_TWI3,   XDMAC0_CH_TWI3_RX   }, /* TWI3 Receive */
  { SAM_PID_SPI0,   XDMAC0_CH_SPI0_RX   }, /* SPI0 Receive */
  { SAM_PID_SPI1,   XDMAC0_CH_SPI1_RX   }, /* SPI1 Receive */
  { SAM_PID_SPI2,   XDMAC0_CH_SPI2_RX   }, /* SPI2 Receive */
  { SAM_PID_USART2, XDMAC0_CH_USART2_RX }, /* USART2 Receive */
  { SAM_PID_USART3, XDMAC0_CH_USART3_RX }, /* USART3 Receive */
  { SAM_PID_USART4, XDMAC0_CH_USART4_RX }, /* USART4 Receive */
  { SAM_PID_UART0,  XDMAC0_CH_UART0_RX  }, /* UART0 Receive */
  { SAM_PID_UART1,  XDMAC0_CH_UART1_RX  }, /* UART1 Receive */
  { SAM_PID_SSC0,   XDMAC0_CH_SSC0_RX   }, /* SSC0 Receive */
  { SAM_PID_SSC1,   XDMAC0_CH_SSC1_RX   }, /* SSC1 Receive */
  { SAM_PID_DBGU,   XDMAC0_CH_DBGU_RX   }, /* DBGU Receive */
  { SAM_PID_ADC,    XDMAC0_CH_ADC_RX    }, /* ADC Receive */
  { SAM_PID_SMD,    XDMAC0_CH_SMD_RX    }, /* SMD Receive */
  { SAM_PID_USART0, XDMAC0_CH_USART0_RX }, /* USART0 Receive */
  { SAM_PID_USART1, XDMAC0_CH_USART1_RX }, /* USART1 Receive */
  { SAM_PID_AES,    XDMAC0_CH_AES_RX    }, /* AES Receive */
  { SAM_PID_TDES,   XDMAC0_CH_TDES_RX   }, /* TDES Receive */
  { SAM_PID_CATB,   XDMAC0_CH_CATB_RX   }, /* CATB Receive */
};
#define NXDMAC0_RXCHANNELS (sizeof(g_xdmac0_rxchan) / sizeof(struct sam_pidmap_s))

/* DMA controller 0, TX DMA: */

static const struct sam_pidmap_s g_xdmac0_txchan[] =
{
  { SAM_PID_HSMCI0, XDMAC0_CH_HSMCI0    }, /* HSMCI0 Receive/Transmit */
  { SAM_PID_HSMCI1, XDMAC0_CH_HSMCI1    }, /* HSMCI1 Receive/Transmit */
  { SAM_PID_TWI0,   XDMAC0_CH_TWI0_TX   }, /* TWI0 Transmit */
  { SAM_PID_TWI1,   XDMAC0_CH_TWI1_TX   }, /* TWI1 Transmit */
  { SAM_PID_TWI2,   XDMAC0_CH_TWI2_TX   }, /* TWI2 Transmit */
  { SAM_PID_TWI3,   XDMAC0_CH_TWI3_TX   }, /* TWI3 Transmit */
  { SAM_PID_SPI0,   XDMAC0_CH_SPI0_TX   }, /* SPI0 Transmit */
  { SAM_PID_SPI1,   XDMAC0_CH_SPI1_TX   }, /* SPI1 Transmit */
  { SAM_PID_SPI2,   XDMAC0_CH_SPI2_TX   }, /* SPI2 Transmit */
  { SAM_PID_USART2, XDMAC0_CH_USART2_TX }, /* USART2 Transmit */
  { SAM_PID_USART3, XDMAC0_CH_USART3_TX }, /* USART3 Transmit */
  { SAM_PID_USART4, XDMAC0_CH_USART4_TX }, /* USART4 Transmit */
  { SAM_PID_UART0,  XDMAC0_CH_UART0_TX  }, /* UART0 Transmit */
  { SAM_PID_UART1,  XDMAC0_CH_UART1_TX  }, /* UART1 Transmit */
  { SAM_PID_SSC0,   XDMAC0_CH_SSC0_TX   }, /* SSC0 Transmit */
  { SAM_PID_SSC1,   XDMAC0_CH_SSC1_TX   }, /* SSC1 Transmit */
  { SAM_PID_DBGU,   XDMAC0_CH_DBGU_TX   }, /* DBGU Transmit */
  { SAM_PID_SMD,    XDMAC0_CH_SMD_TX    }, /* SMD Transmit */
  { SAM_PID_USART0, XDMAC0_CH_USART0_TX }, /* USART0 Transmit */
  { SAM_PID_USART1, XDMAC0_CH_USART1_TX }, /* USART1 Transmit */
  { SAM_PID_AES,    XDMAC0_CH_AES_TX    }, /* AES Transmit */
  { SAM_PID_TDES,   XDMAC0_CH_TDES_TX   }, /* TDES Transmit */
  { SAM_PID_SHA,    XDMAC0_CH_SHA_TX    }, /* SHA Transmit */
  { SAM_PID_CATB,   XDMAC0_CH_CATB_TX   }, /* CATB Transmit */
};
#define NXDMAC0_TXCHANNELS (sizeof(g_xdmac0_txchan) / sizeof(struct sam_pidmap_s))
#endif

#ifdef CONFIG_SAMA5_XDMAC1
/* DMA controller 1, RX DMA: */

static const struct sam_pidmap_s g_xdmac1_rxchan[] =
{
  { SAM_PID_HSMCI0, XDMAC1_CH_HSMCI0    }, /* HSMCI0 Receive/Transmit */
  { SAM_PID_HSMCI1, XDMAC1_CH_HSMCI1    }, /* HSMCI1 Receive/Transmit */
  { SAM_PID_TWI0,   XDMAC1_CH_TWI0_RX   }, /* TWI0 Receive */
  { SAM_PID_TWI1,   XDMAC1_CH_TWI1_RX   }, /* TWI1 Receive */
  { SAM_PID_TWI2,   XDMAC1_CH_TWI2_RX   }, /* TWI2 Receive */
  { SAM_PID_TWI3,   XDMAC1_CH_TWI3_RX   }, /* TWI3 Receive */
  { SAM_PID_SPI0,   XDMAC1_CH_SPI0_RX   }, /* SPI0 Receive */
  { SAM_PID_SPI1,   XDMAC1_CH_SPI1_RX   }, /* SPI1 Receive */
  { SAM_PID_SPI2,   XDMAC1_CH_SPI2_RX   }, /* SPI2 Receive */
  { SAM_PID_USART2, XDMAC1_CH_USART2_RX }, /* USART2 Receive */
  { SAM_PID_USART3, XDMAC1_CH_USART3_RX }, /* USART3 Receive */
  { SAM_PID_USART4, XDMAC1_CH_USART4_RX }, /* USART4 Receive */
  { SAM_PID_UART0,  XDMAC1_CH_UART0_RX  }, /* UART0 Receive */
  { SAM_PID_UART1,  XDMAC1_CH_UART1_RX  }, /* UART1 Receive */
  { SAM_PID_SSC0,   XDMAC1_CH_SSC0_RX   }, /* SSC0 Receive */
  { SAM_PID_SSC1,   XDMAC1_CH_SSC1_RX   }, /* SSC1 Receive */
  { SAM_PID_DBGU,   XDMAC1_CH_DBGU_RX   }, /* DBGU Receive */
  { SAM_PID_ADC,    XDMAC1_CH_ADC_RX    }, /* ADC Receive */
  { SAM_PID_SMD,    XDMAC1_CH_SMD_RX    }, /* SMD Receive */

};
#define NXDMAC1_RXCHANNELS (sizeof(g_xdmac1_rxchan) / sizeof(struct sam_pidmap_s))

/* DMA controller 1, TX DMA: */

static const struct sam_pidmap_s g_xdmac1_txchan[] =
{
  { SAM_PID_HSMCI0, XDMAC1_CH_HSMCI0    }, /* HSMCI0 Receive/Transmit */
  { SAM_PID_HSMCI1, XDMAC1_CH_HSMCI1    }, /* HSMCI1 Receive/Transmit */
  { SAM_PID_TWI0,   XDMAC1_CH_TWI0_TX   }, /* TWI0 Transmit */
  { SAM_PID_TWI1,   XDMAC1_CH_TWI1_TX   }, /* TWI1 Transmit */
  { SAM_PID_TWI2,   XDMAC1_CH_TWI2_TX   }, /* TWI2 Transmit */
  { SAM_PID_TWI3,   XDMAC1_CH_TWI3_TX   }, /* TWI3 Transmit */
  { SAM_PID_SPI0,   XDMAC1_CH_SPI0_TX   }, /* SPI0 Transmit */
  { SAM_PID_SPI1,   XDMAC1_CH_SPI1_TX   }, /* SPI1 Transmit */
  { SAM_PID_SPI2,   XDMAC1_CH_SPI2_TX   }, /* SPI2 Transmit */
  { SAM_PID_USART2, XDMAC1_CH_USART2_TX }, /* USART2 Transmit */
  { SAM_PID_USART3, XDMAC1_CH_USART3_TX }, /* USART3 Transmit */
  { SAM_PID_USART4, XDMAC1_CH_USART4_TX }, /* USART4 Transmit */
  { SAM_PID_UART0,  XDMAC1_CH_UART0_TX  }, /* UART0 Transmit */
  { SAM_PID_UART1,  XDMAC1_CH_UART1_TX  }, /* UART1 Transmit */
  { SAM_PID_SSC0,   XDMAC1_CH_SSC0_TX   }, /* SSC0 Transmit */
  { SAM_PID_SSC1,   XDMAC1_CH_SSC1_TX   }, /* SSC1 Transmit */
  { SAM_PID_DBGU,   XDMAC1_CH_DBGU_TX   }, /* DBGU Transmit */
  { SAM_PID_SMD,    XDMAC1_CH_SMD_TX    }, /* SMD Transmit */
};
#define NXDMAC1_TXCHANNELS (sizeof(g_xdmac1_txchan) / sizeof(struct sam_pidmap_s))
#endif

#ifdef CONFIG_SAMA5_XDMAC0

/* This array describes the available link list descriptors */

struct dma_linklist_s g_desc0[CONFIG_SAMA5_NLLDESC];

/* This array describes the state of each XDMAC0 channel 0 */

static struct sam_xdmach_s g_xdmach0[SAM_NDMACHAN] =
{
#if SAM_NDMACHAN > 0
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 0,
#endif
    .chan     = 0,
    .base     = SAM_XDMAC0_CH0_BASE,
  },
#endif
#if SAM_NDMACHAN > 1
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 0,
#endif
    .chan     = 1,
    .base     = SAM_XDMAC0_CH1_BASE,
  },
#endif
#if SAM_NDMACHAN > 2
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 0,
#endif
    .chan     = 2,
    .base     = SAM_XDMAC0_CH2_BASE,
  },
#endif
#if SAM_NDMACHAN > 3
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 0,
#endif
    .chan     = 3,
    .base     = SAM_XDMAC0_CH3_BASE,
  },
#endif
#if SAM_NDMACHAN > 4
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 0,
#endif
    .chan     = 4,
    .base     = SAM_XDMAC0_CH4_BASE,
  },
#endif
#if SAM_NDMACHAN > 5
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 0,
#endif
    .chan     = 5,
    .base     = SAM_XDMAC0_CH5_BASE,
  },
#endif
#if SAM_NDMACHAN > 6
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 0,
#endif
    .chan     = 6,
    .base     = SAM_XDMAC0_CH6_BASE,
  },
#endif
#if SAM_NDMACHAN > 7
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 0,
#endif
    .chan     = 7,
    .base     = SAM_XDMAC0_CH7_BASE,
  },
#endif
#if SAM_NDMACHAN > 8
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 0,
#endif
    .chan     = 8,
    .base     = SAM_XDMAC0_CH8_BASE,
  },
#endif
#if SAM_NDMACHAN > 9
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 0,
#endif
    .chan     = 9,
    .base     = SAM_XDMAC0_CH9_BASE,
  },
#endif
#if SAM_NDMACHAN > 10
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 0,
#endif
    .chan     = 10,
    .base     = SAM_XDMAC0_CH10_BASE,
  },
#endif
#if SAM_NDMACHAN > 11
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 0,
#endif
    .chan     = 11,
    .base     = SAM_XDMAC0_CH11_BASE,
  },
#endif
#if SAM_NDMACHAN > 12
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 0,
#endif
    .chan     = 12,
    .base     = SAM_XDMAC0_CH12_BASE,
  },
#endif
#if SAM_NDMACHAN > 13
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 0,
#endif
    .chan     = 13,
    .base     = SAM_XDMAC0_CH13_BASE,
  },
#endif
#if SAM_NDMACHAN > 14
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 0,
#endif
    .chan     = 14,
    .base     = SAM_XDMAC0_CH14_BASE,
  },
#endif
#if SAM_NDMACHAN > 15
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 0,
#endif
    .chan     = 15,
    .base     = SAM_XDMAC0_CH15_BASE,
  }
#endif
};

/* This describes the overall state of DMA controller 0 */

static struct sam_xdmac_s g_xdmac0 =
{
  /* XDMAC 0 base address */

  .base       = SAM_XDMAC0_VBASE,

  /* This array describes the available link list descriptors */

  .desc       = g_desc0,

  /* This array describes each DMA channel */

  .xdmach     = g_xdmach0,
};

#endif /* CONFIG_SAMA5_XDMAC0 */

/* This array describes the state of DMA controller 1 */

#ifdef CONFIG_SAMA5_XDMAC1
/* This array describes the available link list descriptors */

struct dma_linklist_s g_desc1[CONFIG_SAMA5_NLLDESC];

static struct sam_xdmach_s g_xdmach1[SAM_NDMACHAN] =
{
#if SAM_NDMACHAN > 0
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 1,
#endif
    .chan     = 0,
    .base     = SAM_XDMAC1_CH0_BASE,
  },
#endif
#if SAM_NDMACHAN > 1
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 1,
#endif
    .chan     = 1,
    .base     = SAM_XDMAC1_CH1_BASE,
  },
#endif
#if SAM_NDMACHAN > 2
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 1,
#endif
    .chan     = 2,
    .base     = SAM_XDMAC1_CH2_BASE,
  },
#endif
#if SAM_NDMACHAN > 3
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 1,
#endif
    .chan     = 3,
    .base     = SAM_XDMAC1_CH3_BASE,
  },
#endif
#if SAM_NDMACHAN > 4
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 1,
#endif
    .chan     = 4,
    .base     = SAM_XDMAC1_CH4_BASE,
  },
#endif
#if SAM_NDMACHAN > 5
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 1,
#endif
    .chan     = 5,
    .base     = SAM_XDMAC1_CH5_BASE,
  },
#endif
#if SAM_NDMACHAN > 6
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 1,
#endif
    .chan     = 6,
    .base     = SAM_XDMAC1_CH6_BASE,
  },
#endif
#if SAM_NDMACHAN > 7
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 1,
#endif
    .chan     = 7,
    .base     = SAM_XDMAC1_CH7_BASE,
  },
#endif
#if SAM_NDMACHAN > 8
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 1,
#endif
    .chan     = 8,
    .base     = SAM_XDMAC1_CH8_BASE,
  },
#endif
#if SAM_NDMACHAN > 9
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 1,
#endif
    .chan     = 9,
    .base     = SAM_XDMAC1_CH9_BASE,
  },
#endif
#if SAM_NDMACHAN > 10
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 1,
#endif
    .chan     = 10,
    .base     = SAM_XDMAC1_CH10_BASE,
  },
#endif
#if SAM_NDMACHAN > 11
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 1,
#endif
    .chan     = 11,
    .base     = SAM_XDMAC1_CH11_BASE,
  },
#endif
#if SAM_NDMACHAN > 12
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 1,
#endif
    .chan     = 12,
    .base     = SAM_XDMAC1_CH12_BASE,
  },
#endif
#if SAM_NDMACHAN > 13
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 1,
#endif
    .chan     = 13,
    .base     = SAM_XDMAC1_CH13_BASE,
  },
#endif
#if SAM_NDMACHAN > 14
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 1,
#endif
    .chan     = 14,
    .base     = SAM_XDMAC1_CH14_BASE,
  },
#endif
#if SAM_NDMACHAN > 15
  {
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
    .xdmac    = 1,
#endif
    .chan     = 15,
    .base     = SAM_XDMAC1_CH15_BASE,
  }
#endif
};

/* This describes the overall state of DMA controller 1 */

static struct sam_xdmac_s g_xdmac1 =
{
  /* XDMAC 0 base address */

  .base       = SAM_XDMAC1_VBASE,

  /* This array describes the available link list descriptors */

  .desc       = g_desc1,

  /* This array describes each DMA channel */

  .xdmach     = g_xdmach1,
};

#endif /* CONFIG_SAMA5_XDMAC1 */

/****************************************************************************
 * Private Functions
 ****************************************************************************/

/****************************************************************************
 * Name: sam_takechsem() and sam_givechsem()
 *
 * Description:
 *   Used to get exclusive access to the DMA channel table
 *
 ****************************************************************************/

static void sam_takechsem(struct sam_xdmac_s *xdmac)
{
  /* Take the semaphore (perhaps waiting) */

  while (sem_wait(&xdmac->chsem) != 0)
    {
      /* The only case that an error should occur here is if the wait was
       * awakened by a signal.
       */

      ASSERT(errno == EINTR);
    }
}

static inline void sam_givechsem(struct sam_xdmac_s *xdmac)
{
  (void)sem_post(&xdmac->chsem);
}

/****************************************************************************
 * Name: sam_takedsem() and sam_givedsem()
 *
 * Description:
 *   Used to wait for availability of descriptors in the descriptor table.
 *
 ****************************************************************************/

static void sam_takedsem(struct sam_xdmac_s *xdmac)
{
  /* Take the semaphore (perhaps waiting) */

  while (sem_wait(&xdmac->dsem) != 0)
    {
      /* The only case that an error should occur here is if the wait was
       * awakened by a signal.
       */

      ASSERT(errno == EINTR);
    }
}

static inline void sam_givedsem(struct sam_xdmac_s *xdmac)
{
  (void)sem_post(&xdmac->dsem);
}

/****************************************************************************
 * Name: sam_getdmac
 *
 * Description:
 *  Read a global XDMAC register
 *
 ****************************************************************************/

static inline uint32_t sam_getdmac(struct sam_xdmac_s *xdmac,
                                   unsigned int offset)
{
  return getreg32(xdmac->base + offset);
}

/****************************************************************************
 * Name: sam_putdmac
 *
 * Description:
 *  Write a value to a global XDMAC register
 *
 ****************************************************************************/

static inline void sam_putdmac(struct sam_xdmac_s *xdmac, uint32_t value,
                               unsigned int offset)
{
  putreg32(value, xdmac->base + offset);
}

/****************************************************************************
 * Name: sam_getdmach
 *
 * Description:
 *  Read a XDMAC channel register
 *
 ****************************************************************************/

static inline uint32_t sam_getdmach(struct sam_xdmach_s *xdmach,
                                    unsigned int offset)
{
  return getreg32(xdmach->base + offset);
}

/****************************************************************************
 * Name: sam_putdmach
 *
 * Description:
 *  Write a value to a XDMAC channel register
 *
 ****************************************************************************/

static inline void sam_putdmach(struct sam_xdmach_s *xdmach, uint32_t value,
                                unsigned int offset)
{
  putreg32(value, xdmach->base + offset);
}

/****************************************************************************
 * Name: sam_controller
 *
 * Description:
 *    Given a DMA channel instance, return a pointer to the parent DMA
 *    controller instance.
 *
 ****************************************************************************/

static inline struct sam_xdmac_s *sam_controller(struct sam_xdmach_s *xdmach)
{
#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
  return xdmach->xdmac ? &g_xdmac1 : &g_xdmac0;
#elif defined(CONFIG_SAMA5_XDMAC0)
  return &g_xdmac0;
#else
  return &g_xdmac1;
#endif
}

/****************************************************************************
 * Name: sam_channel, sam_source_channel, and sam_sink_channel
 *
 * Description:
 *   Return the RX or TX channel associated with a PID.  As a clarification:
 *
 *   The source channel refers to the source of data for the DMA.  This is,
 *   either (1) memory for a TX DMA or (2) a peripheral register for an RX
 *   DMA.
 *
 *   The sink channel is the recipient of the DMA data.  This is either
 *   (1) memory for an RX DMA, or (2) a peripheral register for a TX DMA.
 *
 ****************************************************************************/

static uint8_t sam_channel(uint8_t pid, const struct sam_pidmap_s *table,
                           unsigned int nentries)
{
  int i;

  /* Search until either the entry with the matching PID is found or until
   * all of the table entries have been examined without finding the PID.
   */

  for (i = 0; i < nentries; i++, table++)
    {
      if (table->pid == pid)
        {
          return table->pchan;
        }
    }

  dmadbg("No channel found for pid %d\n", pid);
  DEBUGPANIC();
  return 0x3f;
}

static uint32_t sam_source_channel(struct sam_xdmach_s *xdmach, uint8_t pid,
                                   bool isperiph)
{
  const struct sam_pidmap_s *table;
  unsigned int nentries;

  if (!isperiph)
    {
      /* The source is memory, not a peripheral. */

      return 0x3f;
    }
  else

#ifdef CONFIG_SAMA5_XDMAC0
#ifdef CONFIG_SAMA5_XDMAC1
  if (xdmach->xdmac == 0)
#endif
    {
      /* Use the XDMAC0 lookup table */

      table = g_xdmac0_rxchan;
      nentries = NXDMAC0_RXCHANNELS;
    }
#endif

#ifdef CONFIG_SAMA5_XDMAC1
#ifdef CONFIG_SAMA5_XDMAC0
  else
#endif
    {
      /* Use the XDMAC1 lookup table */

      table = g_xdmac1_rxchan;
      nentries = NXDMAC1_RXCHANNELS;
    }
#endif

  return (uint32_t)sam_channel(pid, table, nentries);
}

static uint32_t sam_sink_channel(struct sam_xdmach_s *xdmach, uint8_t pid,
                                 bool isperiph)
{
  const struct sam_pidmap_s *table;
  unsigned int nentries;

  if (!isperiph)
    {
      /* The source is memory, not a peripheral. */

      return 0x3f;
    }
  else

#ifdef CONFIG_SAMA5_XDMAC0
#ifdef CONFIG_SAMA5_XDMAC1
  if (xdmach->xdmac == 0)
#endif
    {
      /* Use the XDMAC0 lookup table */

      table = g_xdmac0_txchan;
      nentries = NXDMAC0_TXCHANNELS;
    }
#endif

#ifdef CONFIG_SAMA5_XDMAC1
#ifdef CONFIG_SAMA5_XDMAC0
  else
#endif
    {
      /* Use the XDMAC1 lookup table */

      table = g_xdmac1_txchan;
      nentries = NXDMAC1_TXCHANNELS;
    }
#endif

  return (uint32_t)sam_channel(pid, table, nentries);
}

/****************************************************************************
 * Name: sam_txcfg
 *
 * Description:
 *  Decode the flags to get the correct CFG register bit settings for
 *  a transmit (memory to peripheral) transfer.
 *
 ****************************************************************************/

static inline uint32_t sam_txcfg(struct sam_xdmach_s *xdmach)
{
  uint32_t regval;
  unsigned int pid;
  unsigned int pchan;
  bool isperiph;

  /* Set transfer (memory to peripheral) DMA channel configuration register */

  regval   = XDMAC_CH_CFG_SOD;

  pid      = (xdmach->flags & DMACH_FLAG_MEMPID_MASK) >> DMACH_FLAG_MEMPID_SHIFT;
  isperiph = ((xdmach->flags & DMACH_FLAG_MEMISPERIPH) != 0);
  pchan    = sam_source_channel(xdmach, pid, isperiph);

  regval  |= ((pchan & 0x0f) << XDMAC_CH_CFG_SRCPER_SHIFT);
  regval  |= ((pchan & 0x30) << (XDMAC_CH_CFG_SRCPERMSB_SHIFT-4));
  regval  |= (xdmach->flags & DMACH_FLAG_MEMH2SEL) != 0 ? XDMAC_CH_CFG_SRCH2SEL : 0;

  pid      = (xdmach->flags & DMACH_FLAG_PERIPHPID_MASK) >> DMACH_FLAG_PERIPHPID_SHIFT;
  isperiph = ((xdmach->flags & DMACH_FLAG_PERIPHISPERIPH) != 0);
  pchan    = sam_sink_channel(xdmach, pid, isperiph);

  regval  |= ((pchan & 0x0f) << XDMAC_CH_CFG_DSTPER_SHIFT);
  regval  |= ((pchan & 0x30) << (XDMAC_CH_CFG_DSTPERMSB_SHIFT-4));
  regval  |= (xdmach->flags & DMACH_FLAG_PERIPHH2SEL) != 0 ? XDMAC_CH_CFG_DSTH2SEL : 0;

  return regval;
}

/****************************************************************************
 * Name: sam_rxcfg
 *
 * Description:
 *  Decode the flags to get the correct CFG register bit settings for
 *  a receive (peripheral to memory) transfer.
 *
 ****************************************************************************/

static inline uint32_t sam_rxcfg(struct sam_xdmach_s *xdmach)
{
  uint32_t regval;
  unsigned int pid;
  unsigned int pchan;
  bool isperiph;

  /* Set received (peripheral to memory) DMA channel config */

  regval   = XDMAC_CH_CFG_SOD;

  pid      = (xdmach->flags & DMACH_FLAG_PERIPHPID_MASK) >> DMACH_FLAG_PERIPHPID_SHIFT;
  isperiph = ((xdmach->flags & DMACH_FLAG_PERIPHISPERIPH) != 0);
  pchan    = sam_source_channel(xdmach, pid, isperiph);

  regval  |= ((pchan & 0x0f) << XDMAC_CH_CFG_SRCPER_SHIFT);
  regval  |= ((pchan & 0x30) << (XDMAC_CH_CFG_SRCPERMSB_SHIFT-4));
  regval  |= (xdmach->flags & DMACH_FLAG_PERIPHH2SEL) != 0 ? XDMAC_CH_CFG_SRCH2SEL : 0;

  pid      = (xdmach->flags & DMACH_FLAG_MEMPID_MASK) >> DMACH_FLAG_MEMPID_SHIFT;
  isperiph = ((xdmach->flags & DMACH_FLAG_MEMISPERIPH) != 0);
  pchan    = sam_sink_channel(xdmach, pid, isperiph);

  regval  |= ((pchan & 0x0f) << XDMAC_CH_CFG_DSTPER_SHIFT);
  regval  |= ((pchan & 0x30) << (XDMAC_CH_CFG_DSTPERMSB_SHIFT-4));
  regval  |= (xdmach->flags & DMACH_FLAG_MEMH2SEL) != 0 ? XDMAC_CH_CFG_DSTH2SEL : 0;

  return regval;
}

/****************************************************************************
 * Name: sam_txctrlabits
 *
 * Description:
 *  Decode the flags to get the correct CTRLA register bit settings for
 *  a transmit (memory to peripheral) transfer.  These are only the "fixed"
 *  CTRLA values and  need to be updated with the actual transfer size before
 *  being written to CTRLA sam_txctrla).
 *
 ****************************************************************************/

static inline uint32_t sam_txctrlabits(struct sam_xdmach_s *xdmach)
{
  uint32_t regval;
  unsigned int ndx;
  unsigned int chunksize;

  DEBUGASSERT(xdmach);

  /* Since this is a transmit, the source is described by the memory selections.
   * Set the source width (memory width).
   */

  ndx = (xdmach->flags & DMACH_FLAG_MEMWIDTH_MASK) >> DMACH_FLAG_MEMWIDTH_SHIFT;
  DEBUGASSERT(ndx < 4);
  regval = g_chanwidth[ndx];

  /* Set the source chunk size (memory chunk size) */

  chunksize = (xdmach->flags & DMACH_FLAG_MEMCHUNKSIZE_MASK)
    >> DMACH_FLAG_MEMCHUNKSIZE_SHIFT;
  regval |= chunksize << XDMAC_CH_CTRLA_SCSIZE_SHIFT;

  /* Since this is a transmit, the destination is described by the peripheral selections.
   * Set the destination width (peripheral width).
   */

  ndx = (xdmach->flags & DMACH_FLAG_PERIPHWIDTH_MASK) >> DMACH_FLAG_PERIPHWIDTH_SHIFT;
  DEBUGASSERT(ndx < 4);
  regval |= g_chanwidth[ndx];

  /* Set the destination chunk size (peripheral chunk size) */

  chunksize = (xdmach->flags & DMACH_FLAG_PERIPHCHUNKSIZE_MASK)
    >> DMACH_FLAG_PERIPHCHUNKSIZE_SHIFT;
  regval |= chunksize << XDMAC_CH_CTRLA_DCSIZE_SHIFT;

  return regval;
}

/****************************************************************************
 * Name: sam_maxtxtransfer
 *
 * Description:
 *  Maximum number of bytes that can be sent in on transfer
 *
 ****************************************************************************/

static size_t sam_maxtxtransfer(struct sam_xdmach_s *xdmach)
{
  unsigned int srcwidth;
  size_t maxtransfer;

  /* Get the maximum transfer size in bytes.  BTSIZE is "the number of
   * transfers to be performed, that is, for writes it refers to the number
   * of source width transfers to perform when XDMAC is flow controller. For
   * Reads, BTSIZE refers to the number of transfers completed on the Source
   * Interface. ..."
   */

  srcwidth = (xdmach->flags & DMACH_FLAG_MEMWIDTH_MASK)
    >> DMACH_FLAG_MEMWIDTH_SHIFT;

  switch (srcwidth)
    {
      default:
      case 0: /* 8 bits, 1 byte */
        maxtransfer = XDMAC_CH_CTRLA_BTSIZE_MAX;
        break;

      case 1: /* 16 bits, 2 bytes */
        maxtransfer = 2 * XDMAC_CH_CTRLA_BTSIZE_MAX;
        break;

      case 2: /* 32 bits 4 bytes */
        maxtransfer = 4 * XDMAC_CH_CTRLA_BTSIZE_MAX;
        break;

      case 3: /* 64 bits, 8 bytes */
        maxtransfer = 8 * XDMAC_CH_CTRLA_BTSIZE_MAX;
        break;
    }

  return maxtransfer;
}

/****************************************************************************
 * Name: sam_ntxtransfers
 *
 * Description:
 *   Number of TX transfers via DMA
 *
 ****************************************************************************/

static uint32_t sam_ntxtransfers(struct sam_xdmach_s *xdmach, uint32_t dmasize)
{
  unsigned int srcwidth;

  /* Adjust the source transfer size for the source chunk size (memory
   * chunk size).  BTSIZE is "the number of transfers to be performed, that
   * is, for writes it refers to the number of source width transfers
   * to perform when XDMAC is flow controller. For Reads, BTSIZE refers to
   * the number of transfers completed on the Source Interface. ..."
   */

  srcwidth = (xdmach->flags & DMACH_FLAG_MEMWIDTH_MASK)
    >> DMACH_FLAG_MEMWIDTH_SHIFT;

  switch (srcwidth)
    {
      default:
      case 0: /* 8 bits, 1 byte */
        break;

      case 1: /* 16 bits, 2 bytes */
        dmasize = (dmasize + 1) >> 1;
        break;

      case 2: /* 32 bits, 4 bytes */
        dmasize = (dmasize + 3) >> 2;
        break;

      case 3: /* 64 bits, 8 bytes */
        dmasize = (dmasize + 7) >> 3;
        break;
    }

  return dmasize;
}

/****************************************************************************
 * Name: sam_txctrla
 *
 * Description:
 *  'OR' in the variable CTRLA bits
 *
 ****************************************************************************/

static inline uint32_t sam_txctrla(struct sam_xdmach_s *xdmach,
                                   uint32_t ctrla, uint32_t dmasize)
{
  uint32_t ntransfers;

  /* Set the buffer transfer size field.  This is the number of transfers to
   * be performed, that is, the number of source width transfers to perform.
   */

  ntransfers = sam_ntxtransfers(xdmach, dmasize);

  DEBUGASSERT(ntransfers <= XDMAC_CH_CTRLA_BTSIZE_MAX);
  return (ctrla & ~XDMAC_CH_CTRLA_BTSIZE_MASK) |
         (ntransfers << XDMAC_CH_CTRLA_BTSIZE_SHIFT);
}

/****************************************************************************
 * Name: sam_rxctrlabits
 *
 * Description:
 *  Decode the flags to get the correct CTRLA register bit settings for
 *  a read (peripheral to memory) transfer. These are only the "fixed" CTRLA
 *  values and need to be updated with the actual transfer size before being
 *  written to CTRLA sam_rxctrla).
 *
 ****************************************************************************/

static inline uint32_t sam_rxctrlabits(struct sam_xdmach_s *xdmach)
{
  uint32_t regval;
  unsigned int ndx;
  unsigned int chunksize;

  DEBUGASSERT(xdmach);

  /* Since this is a receive, the source is described by the peripheral
   * selections. Set the source width (peripheral width).
   */

  ndx = (xdmach->flags & DMACH_FLAG_PERIPHWIDTH_MASK)
    >> DMACH_FLAG_PERIPHWIDTH_SHIFT;

  DEBUGASSERT(ndx < 4);
  regval = g_chanwidth[ndx];

  /* Set the source chunk size (peripheral chunk size) */

  chunksize = (xdmach->flags & DMACH_FLAG_PERIPHCHUNKSIZE_MASK)
    >> DMACH_FLAG_PERIPHCHUNKSIZE_SHIFT;
  regval |= chunksize << XDMAC_CH_CTRLA_SCSIZE_SHIFT;

  /* Since this is a receive, the destination is described by the memory
   * selections. Set the destination width (memory width).
   */

  ndx = (xdmach->flags & DMACH_FLAG_MEMWIDTH_MASK)
    >> DMACH_FLAG_MEMWIDTH_SHIFT;

  DEBUGASSERT(ndx < 4);
  regval |= g_chanwidth[ndx];

  /* Set the destination chunk size (memory chunk size) */

  chunksize = (xdmach->flags & DMACH_FLAG_MEMCHUNKSIZE_MASK)
    >> DMACH_FLAG_MEMCHUNKSIZE_SHIFT;
  regval |= chunksize << XDMAC_CH_CTRLA_DCSIZE_SHIFT;

  return regval;
}

/****************************************************************************
 * Name: sam_maxrxtransfer
 *
 * Description:
 *  Maximum number of bytes that can be sent in on transfer
 *
 ****************************************************************************/

static size_t sam_maxrxtransfer(struct sam_xdmach_s *xdmach)
{
  unsigned int srcwidth;
  size_t maxtransfer;

  /* Get the maximum transfer size in bytes.  BTSIZE is "the number of
   * transfers to be performed, that is, for writes it refers to the number
   * of source width transfers to perform when XDMAC is flow controller. For
   * Reads, BTSIZE refers to the number of transfers completed on the Source
   * Interface. ..."
   */

  srcwidth = (xdmach->flags & DMACH_FLAG_PERIPHWIDTH_MASK)
    >> DMACH_FLAG_PERIPHWIDTH_SHIFT;

  switch (srcwidth)
    {
      default:
      case 0: /* 8 bits, 1 byte */
        maxtransfer = XDMAC_CH_CTRLA_BTSIZE_MAX;
        break;

      case 1: /* 16 bits, 2 bytes */
        maxtransfer = 2 * XDMAC_CH_CTRLA_BTSIZE_MAX;
        break;

      case 2: /* 32 bits, 4 bytes */
        maxtransfer = 4 * XDMAC_CH_CTRLA_BTSIZE_MAX;
        break;

      case 3: /* 64 bits, 8 bytes */
        maxtransfer = 8 * XDMAC_CH_CTRLA_BTSIZE_MAX;
        break;
    }

  return maxtransfer;
}

/****************************************************************************
 * Name: sam_nrxtransfers
 *
 * Description:
 *  Number of RX transfers via DMA
 *
 ****************************************************************************/

static uint32_t sam_nrxtransfers(struct sam_xdmach_s *xdmach, uint32_t dmasize)
{
  unsigned int srcwidth;

  /* Adjust the source transfer size for the source chunk size (peripheral
   * chunk size).  BTSIZE is "the number of transfers to be performed, that
   * is, for writes it refers to the number of source width transfers
   * to perform when XDMAC is flow controller. For Reads, BTSIZE refers to
   * the number of transfers completed on the Source Interface. ..."
   */

  srcwidth = (xdmach->flags & DMACH_FLAG_PERIPHWIDTH_MASK)
    >> DMACH_FLAG_PERIPHWIDTH_SHIFT;

  switch (srcwidth)
    {
      default:
      case 0: /* 8 bits, 1 byte */
        break;

      case 1: /* 16 bits, 2 bytes */
        dmasize = (dmasize + 1) >> 1;
        break;

      case 2: /* 32 bits, 4 bytes */
        dmasize = (dmasize + 3) >> 2;
        break;

      case 3: /* 64 bits, 8 bytes */
        dmasize = (dmasize + 7) >> 3;
        break;
    }

  return dmasize;
}

/****************************************************************************
 * Name: sam_rxctrla
 *
 * Description:
 *  'OR' in the variable CTRLA bits
 *
 ****************************************************************************/

static inline uint32_t sam_rxctrla(struct sam_xdmach_s *xdmach,
                                   uint32_t ctrla, uint32_t dmasize)
{
  uint32_t ntransfers;

  /* Set the buffer transfer size field.  This is the number of transfers to
   * be performed, that is, the number of source width transfers to perform.
   */

  ntransfers = sam_nrxtransfers(xdmach, dmasize);

  DEBUGASSERT(ntransfers <= XDMAC_CH_CTRLA_BTSIZE_MAX);
  return (ctrla & ~XDMAC_CH_CTRLA_BTSIZE_MASK) |
         (ntransfers << XDMAC_CH_CTRLA_BTSIZE_SHIFT);
}

/****************************************************************************
 * Name: sam_txctrlb
 *
 * Description:
 *  Decode the flags to get the correct CTRLB register bit settings for
 *  a transmit (memory to peripheral) transfer.
 *
 ****************************************************************************/

static inline uint32_t sam_txctrlb(struct sam_xdmach_s *xdmach)
{
  uint32_t regval;
  unsigned int ahbif;

  /* Assume that we will not be using the link list and disable the source
   * and destination descriptors.  The default will be single transfer mode.
   */

  regval = XDMAC_CH_CTRLB_BOTHDSCR | XDMAC_CH_CTRLB_IEN;

  /* Select flow control (even if the channel doesn't support it).  The
   * naming convention from TX is memory to peripheral, but that is really
   * be determined by bits in the DMA flags.
   */

  /* Is the memory source really a peripheral? */

  if ((xdmach->flags & DMACH_FLAG_MEMISPERIPH) != 0)
    {
      /* Yes.. is the peripheral destination also a peripheral? */

      if ((xdmach->flags & DMACH_FLAG_PERIPHISPERIPH) != 0)
        {
          /* Yes.. Use peripheral-to-peripheral flow control */

          regval |= XDMAC_CH_CTRLB_FC_P2P;
        }
      else
        {
          /* No.. Use peripheral-to-memory flow control */

          regval |= XDMAC_CH_CTRLB_FC_P2M;
        }
    }
  else
    {
      /* No, the source is memory.  Is the peripheral destination a
       * peripheral
       */

      if ((xdmach->flags & DMACH_FLAG_PERIPHISPERIPH) != 0)
        {
          /* Yes.. Use memory-to-peripheral flow control */

          regval |= XDMAC_CH_CTRLB_FC_M2P;
        }
      else
        {
          /* No.. Use memory-to-memory flow control */

          regval |= XDMAC_CH_CTRLB_FC_M2M;
        }
    }

  /* Source ABH layer */

  ahbif = (xdmach->flags & DMACH_FLAG_MEMAHB_MASK) >> DMACH_FLAG_MEMAHB_SHIFT;
  regval |= (ahbif << XDMAC_CH_CTRLB_SIF_SHIFT);

  /* Select source address incrementing */

  if ((xdmach->flags & DMACH_FLAG_MEMINCREMENT) == 0)
    {
      regval |= XDMAC_CH_CTRLB_SRCINCR_FIXED;
    }

  /* Destination ABH layer */

  ahbif = (xdmach->flags & DMACH_FLAG_PERIPHAHB_MASK) >> DMACH_FLAG_PERIPHAHB_SHIFT;
  regval |= (ahbif << XDMAC_CH_CTRLB_DIF_SHIFT);

  /* Select destination address incrementing */

  if ((xdmach->flags & DMACH_FLAG_PERIPHINCREMENT) == 0)
    {
      regval |= XDMAC_CH_CTRLB_DSTINCR_FIXED;
    }

  return regval;
}

/****************************************************************************
 * Name: sam_rxctrlb
 *
 * Description:
 *  Decode the flags to get the correct CTRLB register bit settings for
 *  a receive (peripheral to memory) transfer.
 *
 ****************************************************************************/

static inline uint32_t sam_rxctrlb(struct sam_xdmach_s *xdmach)
{
  uint32_t regval;
  unsigned int ahbif;

  /* Assume that we will not be using the link list and disable the source
   * and destination descriptors.  The default will be single transfer mode.
   */

  regval = XDMAC_CH_CTRLB_BOTHDSCR | XDMAC_CH_CTRLB_IEN;

  /* Select flow control (even if the channel doesn't support it).  The
   * naming convention from RX is peripheral to memory, but that is really
   * be determined by bits in the DMA flags.
   */

  /* Is the peripheral source really a peripheral? */

  if ((xdmach->flags & DMACH_FLAG_PERIPHISPERIPH) != 0)
    {
      /* Yes.. is the memory destination also a peripheral? */

      if ((xdmach->flags & DMACH_FLAG_MEMISPERIPH) != 0)
        {
          /* Yes.. Use peripheral-to-peripheral flow control */

          regval |= XDMAC_CH_CTRLB_FC_P2P;
        }
      else
        {
          /* No.. Use peripheral-to-memory flow control */

          regval |= XDMAC_CH_CTRLB_FC_P2M;
        }
    }
  else
    {
      /* No, the peripheral source is memory.  Is the memory destination
       * a peripheral
       */

      if ((xdmach->flags & DMACH_FLAG_MEMISPERIPH) != 0)
        {
          /* Yes.. Use memory-to-peripheral flow control */

          regval |= XDMAC_CH_CTRLB_FC_M2P;
        }
      else
        {
          /* No.. Use memory-to-memory flow control */

          regval |= XDMAC_CH_CTRLB_FC_M2M;
        }
    }

  /* Source ABH layer */

  ahbif = (xdmach->flags & DMACH_FLAG_PERIPHAHB_MASK) >> DMACH_FLAG_PERIPHAHB_SHIFT;
  regval |= (ahbif << XDMAC_CH_CTRLB_SIF_SHIFT);

  /* Select source address incrementing */

  if ((xdmach->flags & DMACH_FLAG_PERIPHINCREMENT) == 0)
    {
      regval |= XDMAC_CH_CTRLB_SRCINCR_FIXED;
    }

  /* Destination ABH layer */

  ahbif = (xdmach->flags & DMACH_FLAG_MEMAHB_MASK) >> DMACH_FLAG_MEMAHB_SHIFT;
  regval |= (ahbif << XDMAC_CH_CTRLB_DIF_SHIFT);

  /* Select address incrementing */

  if ((xdmach->flags & DMACH_FLAG_MEMINCREMENT) == 0)
    {
      regval |= XDMAC_CH_CTRLB_DSTINCR_FIXED;
    }

  return regval;
}

/****************************************************************************
 * Name: sam_allocdesc
 *
 * Description:
 *  Allocate and add one descriptor to the DMA channel's link list.
 *
 *  NOTE: link list entries are freed by the DMA interrupt handler.
 *  However, since the setting/clearing of the 'in use' indication is
 *  atomic, no special actions need be performed.  It would be a good thing
 *  to add logic to handle the case where all of the entries are exhausted
 *  and we could wait for some to be freed by the interrupt handler.
 *
 ****************************************************************************/

static struct dma_linklist_s *
sam_allocdesc(struct sam_xdmach_s *xdmach, struct dma_linklist_s *prev,
              uint32_t csa, uint32_t cda, uint32_t ctrla, uint32_t ctrlb)
{
  struct sam_xdmac_s *xdmac = sam_controller(xdmach);
  struct dma_linklist_s *desc = NULL;
  int i;

  /* Sanity check -- csa == 0 is the indication that the link is unused.
   * Obviously setting it to zero would break that usage.
   */

#ifdef CONFIG_DEBUG
  if (csa != 0)
#endif
    {
      /* Table a descriptor table semaphore count.  When we get one, then there
       * is at least one free descriptor in the table and it is ours.
       */

      sam_takedsem(xdmac);

      /* Examine each link list entry to find an available one -- i.e., one
       * with csa == 0.  That csa field is set to zero by the DMA transfer
       * complete interrupt handler.  The following should be safe because
       * that is an atomic operation.
       */

      sam_takechsem(xdmac);
      for (i = 0; i < CONFIG_SAMA5_NLLDESC; i++)
        {
          if (xdmac->desc[i].csa == 0)
            {
              /* We have it.  Initialize the new link list entry */

              desc        = &xdmac->desc[i];
              desc->csa   = csa;  /* Source address */
              desc->cda   = cda;  /* Destination address */
              desc->ctrla = ctrla;  /* Control A value */
              desc->ctrlb = ctrlb;  /* Control B value */
              desc->dscr  = 0;      /* Next descriptor address */

              /* And then hook it at the tail of the link list */

              if (!prev)
                {
                  /* There is no previous link.  This is the new head of
                   * the list
                   */

                  DEBUGASSERT(xdmach->llhead == NULL && xdmach->lltail == NULL);
                  xdmach->llhead = desc;
                }
              else
                {
                  DEBUGASSERT(xdmach->llhead != NULL && xdmach->lltail == prev);

                  /* When the second link is added to the list, that is the
                   * cue that we are going to do the link list transfer.
                   *
                   * Enable the source and destination descriptor in the link
                   * list entry just before this one.  We assume that both
                   * source and destination buffers are non-continuous, but
                   * this should work even if that is not the case.
                   */

                  prev->ctrlb &= ~XDMAC_CH_CTRLB_BOTHDSCR;

                  /* Link the previous tail to the new tail.
                   * REVISIT:  This assumes that the next description is fetched
                   * via AHB IF0.
                   */

                  prev->dscr = (uint32_t)desc;
                }

              /* In any event, this is the new tail of the list.  The source
               * and destination descriptors must be disabled for the last entry
               * in the link list. */

              desc->ctrlb  |= XDMAC_CH_CTRLB_BOTHDSCR;
              xdmach->lltail = desc;

              /* Assume that we will be doing multple buffer transfers and that
               * that hardware will be accessing the descriptor via DMA.
               */

              cp15_clean_dcache((uintptr_t)desc,
                                (uintptr_t)desc + sizeof(struct dma_linklist_s));
              break;
            }
        }

      /* Because we hold a count from the counting semaphore, the above
       * search loop should always be successful.
       */

      sam_givechsem(xdmac);
      DEBUGASSERT(desc != NULL);
    }

  return desc;
}

/****************************************************************************
 * Name: sam_freelinklist
 *
 * Description:
 *  Free all descriptors in the DMA channel's link list.
 *
 *  NOTE: Called from the DMA interrupt handler.
 *
 ****************************************************************************/

static void sam_freelinklist(struct sam_xdmach_s *xdmach)
{
  struct sam_xdmac_s *xdmac = sam_controller(xdmach);
  struct dma_linklist_s *desc;
  uintptr_t paddr;

  /* Get the head of the link list and detach the link list from the DMA
   * channel
   */

  desc           = xdmach->llhead;
  xdmach->llhead = NULL;
  xdmach->lltail = NULL;

  while (desc != NULL)
    {
      /* Valid, in-use descriptors never have csa == 0 */

      DEBUGASSERT(desc->csa != 0);

      /* Get the physical address of the next descriptor in the list */

      paddr = desc->dscr;

      /* Free the descriptor by simply nullifying it and bumping up the
       * semaphore count.
       */

      memset(desc, 0, sizeof(struct dma_linklist_s));
      sam_givedsem(xdmac);

      /* Get the virtual address of the next descriptor in the list */

      desc = (struct dma_linklist_s *)sam_virtramaddr(paddr);
    }
}

/****************************************************************************
 * Name: sam_txbuffer
 *
 * Description:
 *   Configure DMA for transmit of one buffer (memory to peripheral).  This
 *   function may be called multiple times to handle large and/or dis-
 *   continuous transfers.
 *
 ****************************************************************************/

static int sam_txbuffer(struct sam_xdmach_s *xdmach, uint32_t paddr,
                        uint32_t maddr, size_t nbytes)
{
  uint32_t regval;
  uint32_t ctrla;
  uint32_t ctrlb;

  /* If we are appending a buffer to a linklist, then re-use the CTRLA/B
   * values.  Otherwise, create them from the properties of the transfer.
   */

  if (xdmach->llhead)
    {
      regval = xdmach->llhead->ctrla;
      ctrlb  = xdmach->llhead->ctrlb;
    }
  else
    {
      regval = sam_txctrlabits(xdmach);
      ctrlb  = sam_txctrlb(xdmach);
    }

  ctrla = sam_txctrla(xdmach, regval, nbytes);

  /* Add the new link list entry */

  if (!sam_allocdesc(xdmach, xdmach->lltail, maddr, paddr, ctrla, ctrlb))
    {
      return -ENOMEM;
    }

  /* Pre-calculate the transmit CFG register setting (it won't be used until
   * the DMA is started).
   */

  xdmach->cfg = sam_txcfg(xdmach);
  return OK;
}

/****************************************************************************
 * Name: sam_rxbuffer
 *
 * Description:
 *   Configure DMA for receipt of one buffer (peripheral to memory).  This
 *   function may be called multiple times to handle large and/or dis-
 *   continuous transfers.
 *
 ****************************************************************************/

static int sam_rxbuffer(struct sam_xdmach_s *xdmach, uint32_t paddr,
                        uint32_t maddr, size_t nbytes)
{
  uint32_t regval;
  uint32_t ctrla;
  uint32_t ctrlb;

  /* If we are appending a buffer to a linklist, then re-use the CTRLA/B
   * values.  Otherwise, create them from the properties of the transfer.
   */

  if (xdmach->llhead)
    {
      regval = xdmach->llhead->ctrla;
      ctrlb  = xdmach->llhead->ctrlb;
    }
  else
    {
      regval = sam_rxctrlabits(xdmach);
      ctrlb  = sam_rxctrlb(xdmach);
    }

   ctrla = sam_rxctrla(xdmach, regval, nbytes);

  /* Add the new link list entry */

  if (!sam_allocdesc(xdmach, xdmach->lltail, paddr, maddr, ctrla, ctrlb))
    {
      return -ENOMEM;
    }

  /* Pre-calculate the receive CFG register setting (it won't be used until
   * the DMA is started).
   */

  xdmach->cfg = sam_rxcfg(xdmach);
  return OK;
}

/****************************************************************************
 * Name: sam_single
 *
 * Description:
 *   Start a single buffer DMA.
 *
 ****************************************************************************/

static inline int sam_single(struct sam_xdmach_s *xdmach)
{
  struct sam_xdmac_s *xdmac = sam_controller(xdmach);
  struct dma_linklist_s *llhead = xdmach->llhead;

  /* Clear any pending interrupts from any previous XDMAC transfer by
   * reading the XDMAC Channel Interrupt Status Register (CIS).
   */

  (void)sam_getdmach(xdmach, SAM_XDMACH_CIS_OFFSET);

  /* Write the starting source address in the Channel Source Address (CSA)
   * Register.
   */

  DEBUGASSERT(llhead != NULL && llhead->csa != 0);
  sam_putdmach(xdmach, llhead->csa, SAM_XDMACH_CSA_OFFSET);

  /* Write the starting destination address in the  Channel Destination
   * Address Register (CDA).
   */

  sam_putdmach(xdmach, llhead->cda, SAM_XDMACH_CDA_OFFSET);

  /* Clear the next descriptor address */

  sam_putdmach(xdmach, 0, SAM_XDMAC_CH_DSCR_OFFSET);

  /* Set up the CTRLA register */

  sam_putdmach(xdmach, llhead->ctrla, SAM_XDMAC_CH_CTRLA_OFFSET);

  /* Set up the CTRLB register */

  sam_putdmach(xdmach, llhead->ctrlb, SAM_XDMAC_CH_CTRLB_OFFSET);

  /* Both the DST and SRC DSCR bits should be '1' in CTRLB */

  DEBUGASSERT((llhead->ctrlb & XDMAC_CH_CTRLB_BOTHDSCR) ==
              XDMAC_CH_CTRLB_BOTHDSCR);

  /* Set up the CFG register */

  sam_putdmach(xdmach, xdmach->cfg, SAM_XDMAC_CH_CFG_OFFSET);

  /* Enable the channel by writing a �1� to the CHER enable bit */

  sam_putdmac(xdmac, XDMAC_CHER_ENA(xdmach->chan), SAM_XDMAC_CHER_OFFSET);

  /* The DMA has been started. Once the transfer completes, hardware sets
   * the interrupts and disables the channel.  We will receive buffer
   * complete and transfer complete interrupts.
   *
   * Enable error, buffer complete and transfer complete interrupts.
   * (Since there is only a single buffer, we don't need the buffer
   * complete interrupt).
   */

  sam_putdmac(xdmac, XDMAC_EBC_CBTCINTS(xdmach->chan), SAM_XDMAC_EBCIER_OFFSET);
  return OK;
}

/****************************************************************************
 * Name: sam_multiple
 *
 * Description:
 *   Start a multiple buffer DMA.
 *
 ****************************************************************************/

static inline int sam_multiple(struct sam_xdmach_s *xdmach)
{
  struct sam_xdmac_s *xdmac = sam_controller(xdmach);
  struct dma_linklist_s *llhead = xdmach->llhead;

  DEBUGASSERT(llhead != NULL && llhead->csa != 0);

  /* Check the first and last CTRLB values */

  DEBUGASSERT((llhead->ctrlb & XDMAC_CH_CTRLB_BOTHDSCR) == 0);
  DEBUGASSERT((xdmach->lltail->ctrlb & XDMAC_CH_CTRLB_BOTHDSCR) ==
              XDMAC_CH_CTRLB_BOTHDSCR);

  /* Clear any pending interrupts from any previous XDMAC transfer by
   * reading the XDMAC Channel Interrupt Status Register (CIS).
   */

  (void)sam_getdmach(xdmach, SAM_XDMACH_CIS_OFFSET);

  /* Set up the initial CTRLA register */

  sam_putdmach(xdmach, llhead->ctrla, SAM_XDMAC_CH_CTRLA_OFFSET);

  /* Set up the CTRLB register (will enable descriptors) */

  sam_putdmach(xdmach, llhead->ctrlb, SAM_XDMAC_CH_CTRLB_OFFSET);

  /* Write the channel configuration information into the CFG register */

  sam_putdmach(xdmach, xdmach->cfg, SAM_XDMAC_CH_CFG_OFFSET);

  /* Program the DSCR register with the pointer to the firstlink list entry. */

  sam_putdmach(xdmach, (uint32_t)llhead, SAM_XDMAC_CH_DSCR_OFFSET);

  /* Finally, enable the channel by writing a �1� to the CHER enable */

  sam_putdmac(xdmac, XDMAC_CHER_ENA(xdmach->chan), SAM_XDMAC_CHER_OFFSET);

  /* As each buffer of data is transferred, the CTRLA register is written
   * back into the link list entry.  The CTRLA contains updated BTSIZE and
   * DONE bits.  Additionally, the CTRLA DONE bit is asserted when the
   * buffer transfer has completed.
   *
   * The XDMAC transfer continues until the CTRLB register disables the
   * descriptor (DSCR bits) registers at the final buffer transfer.
   *
   * Enable error, buffer complete and transfer complete interrupts.  We
   * don't really need the buffer complete interrupts, but we will take them
   * just to handle stall conditions.
   */

  sam_putdmac(xdmac, XDMAC_EBC_CHANINTS(xdmach->chan), SAM_XDMAC_EBCIER_OFFSET);
  return OK;
}

/****************************************************************************
 * Name: sam_dmaterminate
 *
 * Description:
 *   Terminate the DMA transfer and disable the DMA channel
 *
 ****************************************************************************/

static void sam_dmaterminate(struct sam_xdmach_s *xdmach, int result)
{
  struct sam_xdmac_s *xdmac = sam_controller(xdmach);

  /* Disable all channel interrupts */

  sam_putdmac(xdmac, XDMAC_EBC_CHANINTS(xdmach->chan), SAM_XDMAC_EBCIDR_OFFSET);

  /* Disable the channel by writing one to the write-only channel disable
   * register.
   */

  sam_putdmac(xdmac, XDMAC_CHDR_DIS(xdmach->chan), SAM_XDMAC_CHDR_OFFSET);

  /* Free the linklist */

  sam_freelinklist(xdmach);

  /* If this was an RX DMA (peripheral-to-memory), then invalidate the cache
   * to force reloads from memory.
   */

  if (xdmach->rx)
    {
      cp15_invalidate_dcache(xdmach->rxaddr, xdmach->rxaddr + xdmach->rxsize);
    }

  /* Perform the DMA complete callback */

  if (xdmach->callback)
    {
      xdmach->callback((DMA_HANDLE)xdmach, xdmach->arg, result);
    }

  xdmach->callback = NULL;
  xdmach->arg      = NULL;
}

/****************************************************************************
 * Name: sam_xdmac_interrupt
 *
 * Description:
 *  DMA interrupt handler
 *
 ****************************************************************************/

static int sam_xdmac_interrupt(struct sam_xdmac_s *xdmac)
{
  struct sam_xdmach_s *xdmach;
  unsigned int chndx;
  uint32_t regval;

  /* Get the XDMAC status register value.  Ignore all masked interrupt
   * status bits.
   */

  regval = sam_getdmac(xdmac, SAM_XDMAC_EBCISR_OFFSET) &
           sam_getdmac(xdmac, SAM_XDMAC_EBCIMR_OFFSET);

  /* Check if the any transfer has completed or any errors have ocurred. */

  if (regval & XDMAC_EBC_ALLCHANINTS)
    {
      /* Yes.. Check each bit  to see which channel has interrupted */

      for (chndx = 0; chndx < SAM_NDMACHAN; chndx++)
        {
          /* Are any interrupts pending for this channel? */

          if ((regval & XDMAC_EBC_CHANINTS(chndx)) != 0)
            {
              xdmach = &xdmac->xdmach[chndx];

              /* Yes.. Did an error occur? */

              if ((regval & XDMAC_EBC_ERR(chndx)) != 0)
                {
                   /* Yes... Terminate the transfer with an error? */

                   dmalldbg("ERROR: DMA failed: %08x\n", regval);
                   sam_dmaterminate(xdmach, -EIO);
                }

              /* Is the transfer complete? */

              else if ((regval & XDMAC_EBC_CBTC(chndx)) != 0)
               {
                  /* Yes.. Terminate the transfer with success */

                  sam_dmaterminate(xdmach, OK);
                }

              /* Otherwise, this must be a Bufffer Transfer Complete (BTC)
               * interrupt as part of a multiple buffer transfer.
               */

              else /* if ((regval & XDMAC_EBC_BTC(chndx)) != 0) */
                {
                  /* Write the KEEPON field to clear the STALL states */

                  sam_putdmac(xdmac, XDMAC_CHER_KEEP(xdmach->chan),
                              SAM_XDMAC_CHER_OFFSET);
                }
            }
        }
    }

  return OK;
}

/****************************************************************************
 * Name: sam_xdmac0_interrupt and sam_xdmac1_interrupt
 *
 * Description:
 *  DMA interrupt handler
 *
 ****************************************************************************/

#ifdef CONFIG_SAMA5_XDMAC0
static int sam_xdmac0_interrupt(int irq, void *context)
{
  return sam_xdmac_interrupt(&g_xdmac0);
}
#endif

#ifdef CONFIG_SAMA5_XDMAC1
static int sam_xdmac1_interrupt(int irq, void *context)
{
  return sam_xdmac_interrupt(&g_xdmac1);
}
#endif

/****************************************************************************
 * Name: sam_dmainitialize
 *
 * Description:
 *   Initialize the DMA subsystem
 *
 * Returned Value:
 *   None
 *
 ****************************************************************************/

void sam_dmainitialize(struct sam_xdmac_s *xdmac)
{
  /* Disable all DMA interrupts */

  sam_putdmac(xdmac, XDMAC_EBC_ALLINTS, SAM_XDMAC_EBCIDR_OFFSET);

  /* Disable all DMA channels */

  sam_putdmac(xdmac, XDMAC_CHDR_DIS_ALL, SAM_XDMAC_CHDR_OFFSET);

  /* Enable the DMA controller */

  sam_putdmac(xdmac,XDMAC_EN_ENABLE, SAM_XDMAC_EN_OFFSET);

  /* Initialize semaphores */

  sem_init(&xdmac->chsem, 0, 1);
  sem_init(&xdmac->dsem, 0, SAM_NDMACHAN);
}

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: up_dmainitialize
 *
 * Description:
 *   Initialize the DMA subsystem
 *
 * Returned Value:
 *   None
 *
 ****************************************************************************/

void weak_function up_dmainitialize(void)
{
#ifdef CONFIG_SAMA5_XDMAC0
  dmallvdbg("Initialize XDMAC0\n");

  /* Enable peripheral clock */

  sam_xdmac0_enableclk();

  /* Attach DMA interrupt vector */

  (void)irq_attach(SAM_IRQ_XDMAC0, sam_xdmac0_interrupt);

  /* Initialize the controller */

  sam_dmainitialize(&g_xdmac0);

  /* Enable the IRQ at the AIC (still disabled at the DMA controller) */

  up_enable_irq(SAM_IRQ_XDMAC0);
#endif

#ifdef CONFIG_SAMA5_XDMAC1
  dmallvdbg("Initialize XDMAC1\n");

  /* Enable peripheral clock */

  sam_xdmac1_enableclk();

  /* Attach DMA interrupt vector */

  (void)irq_attach(SAM_IRQ_XDMAC1, sam_xdmac1_interrupt);

  /* Initialize the controller */

  sam_dmainitialize(&g_xdmac1);

  /* Enable the IRQ at the AIC (still disabled at the DMA controller) */

  up_enable_irq(SAM_IRQ_XDMAC1);
#endif
}

/****************************************************************************
 * Name: sam_xdmachannel
 *
 *   Allocate a DMA channel.  This function sets aside a DMA channel then
 *   gives the caller exclusive access to the DMA channel.
 *
 *   The naming convention in all of the DMA interfaces is that one side is
 *   the 'peripheral' and the other is 'memory'.  Howerver, the interface
 *   could still be used if, for example, both sides were memory although
 *   the naming would be awkward.
 *
 * Returned Value:
 *   If a DMA channel is available, this function returns a non-NULL, void*
 *   DMA channel handle.  NULL is returned on any failure.
 *
 ****************************************************************************/

DMA_HANDLE sam_xdmachannel(uint8_t dmacno, uint32_t chflags)
{
  struct sam_xdmac_s *xdmac;
  struct sam_xdmach_s *xdmach;
  unsigned int chndx;

  /* Pick the DMA controller */

#ifdef CONFIG_SAMA5_XDMAC0
  if (dmacno == 0)
    {
      xdmac = &g_xdmac0;
    }
  else
#endif

#ifdef CONFIG_SAMA5_XDMAC1
  if (dmacno == 1)
    {
      xdmac = &g_xdmac1;
    }
  else
#endif

    {
      dmadbg("ERROR: Bad XDMAC number: %d\n", dmacno);
      DEBUGPANIC();
      return (DMA_HANDLE)NULL;
    }

  /* Search for an available DMA channel with at least the requested FIFO
   * size.
   */

  xdmach = NULL;
  sam_takechsem(xdmac);
  for (chndx = 0; chndx < SAM_NDMACHAN; chndx++)
    {
      struct sam_xdmach_s *candidate = &xdmac->xdmach[chndx];
      if (!candidate->inuse)
        {
          xdmach        = candidate;
          xdmach->inuse = true;

          /* Clear the pending Interrupt Status bits by reading the XDMAC
           * Channel Interrupt Status (CIS) Register
           */

          (void)sam_getdmach(xdmach, SAM_XDMACH_CIS_OFFSET);

          /* Disable the channel by writing one to the write-only Global
           * Channel Disable (GD) Register
           */

          sam_putdmac(xdmac, XDMAC_CHAN(chndx), SAM_XDMAC_GD_OFFSET);

          /* Set the DMA channel flags. */

          xdmach->flags = chflags;
          break;
        }
    }

  sam_givechsem(xdmac);

  /* Show the result of the allocation */

  if (xdmach)
    {
      dmavdbg("XDMAC%d CH%d: chflags: %08x returning xdmach: %p\n",
              (int)dmacno, xdmach->chan, (int)chflags, xdmach);
    }
  else
    {
      dmadbg("ERROR: Failed allocate XDMAC%d channel\n", (int)dmacno);
    }

  return (DMA_HANDLE)xdmach;
}

/************************************************************************************
 * Name: sam_xdmaconfig
 *
 * Description:
 *   There are two channel usage models:  (1) The channel is allocated and configured
 *   in one step.  This is the typical case where a DMA channel performs a constant
 *   role.  The alternative is (2) where the DMA channel is reconfigured on the fly.
 *   In this case, the chflags provided to sam_xdmachannel are not used and
 *   sam_xdmaconfig() is called before each DMA to configure the DMA channel
 *   appropriately.
 *
 * Returned Value:
 *   None
 *
 ************************************************************************************/

void sam_xdmaconfig(DMA_HANDLE handle, uint32_t chflags)
{
  struct sam_xdmach_s *xdmach = (struct sam_xdmach_s *)handle;

  /* Set the new DMA channel flags. */

  xdmach->flags = chflags;

#if defined(CONFIG_SAMA5_XDMAC0) && defined(CONFIG_SAMA5_XDMAC1)
  dmavdbg("XDMAC%d CH%d: chflags: %08x\n",
          xdmach->xdmac, xdmach->chan, (int)chflags);
#elif defined(CONFIG_SAMA5_XDMAC0)
  dmavdbg("XDMAC0 CH%d: chflags: %08x\n",
          xdmach->chan, (int)chflags);
#else
  dmavdbg("XDMAC1 CH%d: chflags: %08x\n",
          xdmach->chan, (int)chflags);
#endif
}

/****************************************************************************
 * Name: sam_dmafree
 *
 * Description:
 *   Release a DMA channel.  NOTE:  The 'handle' used in this argument must
 *   NEVER be used again until sam_xdmachannel() is called again to re-gain
 *   a valid handle.
 *
 * Returned Value:
 *   None
 *
 ****************************************************************************/

void sam_dmafree(DMA_HANDLE handle)
{
  struct sam_xdmach_s *xdmach = (struct sam_xdmach_s *)handle;

  dmavdbg("xdmach: %p\n", xdmach);
  DEBUGASSERT((xdmach != NULL) && (xdmach->inuse));

  /* Make sure that the channel is disabled by writing one to the write-only
   * Global Channel Disable (GD) Register
   */

  sam_putdmac(xdmac, XDMAC_CHAN(xdmach->chan), SAM_XDMAC_GD_OFFSET);

  /* Mark the channel no longer in use.  Clearing the inuse flag is an atomic
   * operation and so should be safe.
   */

  xdmach->flags = 0;
  xdmach->inuse = false;                   /* No longer in use */
}

/****************************************************************************
 * Name: sam_dmatxsetup
 *
 * Description:
 *   Configure DMA for transmit of one buffer (memory to peripheral).  This
 *   function may be called multiple times to handle large and/or dis-
 *   continuous transfers.  Calls to sam_dmatxsetup() and sam_dmarxsetup()
 *   must not be intermixed on the same transfer, however.
 *
 ****************************************************************************/

int sam_dmatxsetup(DMA_HANDLE handle, uint32_t paddr, uint32_t maddr,
                   size_t nbytes)
{
  struct sam_xdmach_s *xdmach = (struct sam_xdmach_s *)handle;
  size_t maxtransfer;
  size_t remaining;
  int ret = OK;

  dmavdbg("xdmach: %p paddr: %08x maddr: %08x nbytes: %d\n",
          xdmach, (int)paddr, (int)maddr, (int)nbytes);
  DEBUGASSERT(xdmach);
  dmavdbg("llhead: %p lltail: %p\n", xdmach->llhead, xdmach->lltail);

  /* The maximum transfer size in bytes depends upon the maximum number of
   * transfers and the number of bytes per transfer.
   */

  maxtransfer = sam_maxtxtransfer(xdmach);
  remaining   = nbytes;

  /* If this is a large transfer, break it up into smaller buffers */

  while (remaining > maxtransfer)
    {
      /* Set up the maximum size transfer */

      ret = sam_txbuffer(xdmach, paddr, maddr, maxtransfer);
      if (ret == OK);
        {
          /* Decrement the number of bytes left to transfer */

          remaining -= maxtransfer;

          /* Increment the memory & peripheral address (if it is appropriate to
           * do so).
           */

          if ((xdmach->flags & DMACH_FLAG_PERIPHINCREMENT) != 0)
            {
              paddr += maxtransfer;
            }

          if ((xdmach->flags & DMACH_FLAG_MEMINCREMENT) != 0)
            {
              maddr += maxtransfer;
            }
        }
    }

  /* Then set up the final buffer transfer */

  if (ret == OK && remaining > 0)
    {
      ret = sam_txbuffer(xdmach, paddr, maddr, remaining);
    }

  /* Save an indication so that the DMA interrupt completion logic will know
   * that this was not an RX transfer.
   */

  xdmach->rx = false;

  /* Clean caches associated with the DMA memory */

  cp15_clean_dcache(maddr, maddr + nbytes);
  return ret;
}

/****************************************************************************
 * Name: sam_dmarxsetup
 *
 * Description:
 *   Configure DMA for receipt of one buffer (peripheral to memory).  This
 *   function may be called multiple times to handle large and/or dis-
 *   continuous transfers.  Calls to sam_dmatxsetup() and sam_dmarxsetup()
 *   must not be intermixed on the same transfer, however.
 *
 ****************************************************************************/

int sam_dmarxsetup(DMA_HANDLE handle, uint32_t paddr, uint32_t maddr,
                   size_t nbytes)
{
  struct sam_xdmach_s *xdmach = (struct sam_xdmach_s *)handle;
  size_t maxtransfer;
  size_t remaining;
  int ret = OK;

  dmavdbg("xdmach: %p paddr: %08x maddr: %08x nbytes: %d\n",
          xdmach, (int)paddr, (int)maddr, (int)nbytes);
  DEBUGASSERT(xdmach);
  dmavdbg("llhead: %p lltail: %p\n", xdmach->llhead, xdmach->lltail);

  /* The maximum transfer size in bytes depends upon the maximum number of
   * transfers and the number of bytes per transfer.
   */

  maxtransfer = sam_maxrxtransfer(xdmach);
  remaining   = nbytes;

  /* If this is a large transfer, break it up into smaller buffers */

  while (remaining > maxtransfer)
    {
      /* Set up the maximum size transfer */

      ret = sam_rxbuffer(xdmach, paddr, maddr, maxtransfer);
      if (ret == OK);
        {
          /* Decrement the number of bytes left to transfer */

          remaining -= maxtransfer;

          /* Increment the memory & peripheral address (if it is appropriate to
           * do so).
           */

          if ((xdmach->flags & DMACH_FLAG_PERIPHINCREMENT) != 0)
            {
              paddr += maxtransfer;
            }

          if ((xdmach->flags & DMACH_FLAG_MEMINCREMENT) != 0)
            {
              maddr += maxtransfer;
            }
        }
    }

  /* Then set up the final buffer transfer */

  if (ret == OK && remaining > 0)
    {
      ret = sam_rxbuffer(xdmach, paddr, maddr, remaining);
    }

  /* Save an indication so that the DMA interrupt completion logic will know
   * that this was an RX transfer and will invalidate the cache.
   */

  xdmach->rx     = true;
  xdmach->rxaddr = maddr;
  xdmach->rxsize = (xdmach->flags & DMACH_FLAG_MEMINCREMENT) != 0 ? nbytes : sizeof(uint32_t);

  /* Clean caches associated with the DMA memory */

  cp15_clean_dcache(maddr, maddr + nbytes);
  return ret;
}

/****************************************************************************
 * Name: sam_dmastart
 *
 * Description:
 *   Start the DMA transfer
 *
 ****************************************************************************/

int sam_dmastart(DMA_HANDLE handle, dma_callback_t callback, void *arg)
{
  struct sam_xdmach_s *xdmach = (struct sam_xdmach_s *)handle;
  int ret = -EINVAL;

  dmavdbg("xdmach: %p callback: %p arg: %p\n", xdmach, callback, arg);
  DEBUGASSERT(xdmach != NULL);

  /* Verify that the DMA has been setup (i.e., at least one entry in the
   * link list).
   */

  if (xdmach->llhead)
    {
      /* Save the callback info.  This will be invoked whent the DMA commpletes */

      xdmach->callback = callback;
      xdmach->arg      = arg;

      /* Is this a single block transfer?  Or a multiple block tranfer? */

      if (xdmach->llhead == xdmach->lltail)
        {
          ret = sam_single(xdmach);
        }
      else
        {
          ret = sam_multiple(xdmach);
        }
    }

  return ret;
}

/****************************************************************************
 * Name: sam_dmastop
 *
 * Description:
 *   Cancel the DMA.  After sam_dmastop() is called, the DMA channel is
 *   reset and sam_dmarx/txsetup() must be called before sam_dmastart() can be
 *   called again
 *
 ****************************************************************************/

void sam_dmastop(DMA_HANDLE handle)
{
  struct sam_xdmach_s *xdmach = (struct sam_xdmach_s *)handle;
  irqstate_t flags;

  dmavdbg("xdmach: %p\n", xdmach);
  DEBUGASSERT(xdmach != NULL);

  flags = irqsave();
  sam_dmaterminate(xdmach, -EINTR);
  irqrestore(flags);
}

/****************************************************************************
 * Name: sam_dmasample
 *
 * Description:
 *   Sample DMA register contents
 *
 * Assumptions:
 *   - DMA handle allocated by sam_xdmachannel()
 *
 ****************************************************************************/

#ifdef CONFIG_DEBUG_DMA
void sam_dmasample(DMA_HANDLE handle, struct sam_dmaregs_s *regs)
{
  struct sam_xdmach_s *xdmach = (struct sam_xdmach_s *)handle;
  struct sam_xdmac_s *xdmac = sam_controller(xdmach);
  irqstate_t flags;

  /* Sample global registers.  NOTE: reading GIS clears interrupts, but
   * that should be okay IF interrupts are enabled when this function is
   * called.  But there is a race condition where this instrumentation could
   * cause lost interrupts.
   */

  flags        = irqsave();

  regs->gtype  = sam_getdmac(xdmac, SAM_XDMAC_GTYPE_OFFSET);
  regs->gcfg   = sam_getdmac(xdmac, SAM_XDMAC_GCFG_OFFSET);
  regs->gwac   = sam_getdmac(xdmac, SAM_XDMAC_GWAC_OFFSET);
  regs->gim    = sam_getdmac(xdmac, SAM_XDMAC_GIM_OFFSET);
  regs->gis    = sam_getdmac(xdmac, SAM_XDMAC_GIS_OFFSET);
  regs->gs     = sam_getdmac(xdmac, SAM_XDMAC_GS_OFFSET);
  regs->grs    = sam_getdmac(xdmac, SAM_XDMAC_GRS_OFFSET);
  regs->gws    = sam_getdmac(xdmac, SAM_XDMAC_GWS_OFFSET);
  regs->gsws   = sam_getdmac(xdmac, SAM_XDMAC_GSWS_OFFSET);

  /* Sample channel registers */

  regs->cis    = sam_getdmach(xdmach, SAM_XDMACH_CIS_OFFSET);
  regs->csa    = sam_getdmach(xdmach, SAM_XDMACH_CSA_OFFSET);
  regs->cda    = sam_getdmach(xdmach, SAM_XDMACH_CDA_OFFSET);
  regs->cnda   = sam_getdmach(xdmach, SAM_XDMACH_CNDA_OFFSET);
  regs->cndc   = sam_getdmach(xdmach, SAM_XDMACH_CNDC_OFFSET);
  regs->cubc   = sam_getdmach(xdmach, SAM_XDMACH_CUBC_OFFSET);
  regs->cbc    = sam_getdmach(xdmach, SAM_XDMACH_CBC_OFFSET);
  regs->cc     = sam_getdmach(xdmach, SAM_XDMACH_CC_OFFSET);
  regs->cdsmsp = sam_getdmach(xdmach, SAM_XDMACH_CDSMSP_OFFSET);
  regs->csus   = sam_getdmach(xdmach, SAM_XDMACH_CSUS_OFFSET);
  regs->cdus   = sam_getdmach(xdmach, SAM_XDMACH_CDUS_OFFSET);

  irqrestore(flags);
}
#endif /* CONFIG_DEBUG_DMA */

/****************************************************************************
 * Name: sam_dmadump
 *
 * Description:
 *   Dump previously sampled DMA register contents
 *
 * Assumptions:
 *   - DMA handle allocated by sam_xdmachannel()
 *
 ****************************************************************************/

#ifdef CONFIG_DEBUG_DMA
void sam_dmadump(DMA_HANDLE handle, const struct sam_dmaregs_s *regs,
                 const char *msg)
{
  struct sam_xdmach_s *xdmach = (struct sam_xdmach_s *)handle;
  struct sam_xdmac_s *xdmac = sam_controller(xdmach);

  dmadbg("%s\n", msg);
  dmadbg("  DMA Global Registers:\n");
  dmadbg("     GTYPE[%08x]: %08x\n", xdmac->base + SAM_XDMAC_GTYPE_OFFSET, regs->gtype);
  dmadbg("      GCFG[%08x]: %08x\n", xdmac->base + SAM_XDMAC_GCFG_OFFSET, regs->gcfg);
  dmadbg("      GWAC[%08x]: %08x\n", xdmac->base + SAM_XDMAC_GWAC_OFFSET, regs->gwac);
  dmadbg("       GIM[%08x]: %08x\n", xdmac->base + SAM_XDMAC_GIM_OFFSET, regs->gim);
  dmadbg("       GIS[%08x]: %08x\n", xdmac->base + SAM_XDMAC_GIS_OFFSET, regs->gis);
  dmadbg("        GS[%08x]: %08x\n", xdmac->base + SAM_XDMAC_GS_OFFSET, regs->gs);
  dmadbg("       GRS[%08x]: %08x\n", xdmac->base + SAM_XDMAC_GRS_OFFSET, regs->grs);
  dmadbg("       GWS[%08x]: %08x\n", xdmac->base + SAM_XDMAC_GWS_OFFSET, regs->gws);
  dmadbg("      GSWS[%08x]: %08x\n", xdmac->base + SAM_XDMAC_GSWS_OFFSET, regs->gsws);
  dmadbg("  DMA Channel Registers:\n");
  dmadbg("       CIS[%08x]: %08x\n", xdmach->base + SAM_XDMACH_CIS_OFFSET, regs->cis);
  dmadbg("       CSA[%08x]: %08x\n", xdmach->base + SAM_XDMACH_CSA_OFFSET, regs->csa);
  dmadbg("       CDA[%08x]: %08x\n", xdmach->base + SAM_XDMACH_CDA_OFFSET, regs->cda);
  dmadbg("      CNDA[%08x]: %08x\n", xdmach->base + SAM_XDMACH_CNDA_OFFSET, regs->cnda);
  dmadbg("      CNDC[%08x]: %08x\n", xdmach->base + SAM_XDMACH_CNDC_OFFSET, regs->cndc);
  dmadbg("      CUBC[%08x]: %08x\n", xdmach->base + SAM_XDMACH_CUBC_OFFSET, regs->cubc);
  dmadbg("       CBC[%08x]: %08x\n", xdmach->base + SAM_XDMACH_CBC_OFFSET, regs->cbc);
  dmadbg("        CC[%08x]: %08x\n", xdmach->base + SAM_XDMACH_CC_OFFSET, regs->cc);
  dmadbg("    CDSMSP[%08x]: %08x\n", xdmach->base + SAM_XDMACH_CDSMSP_OFFSET, regs->cdsmsp);
  dmadbg("      CSUS[%08x]: %08x\n", xdmach->base + SAM_XDMACH_CSUS_OFFSET, regs->csus);
  dmadbg("      CDUS[%08x]: %08x\n", xdmach->base + SAM_XDMACH_CDUS_OFFSET, regs->cdus);
}
#endif /* CONFIG_DEBUG_DMA */
#endif /* CONFIG_SAMA5_XDMAC0 || CONFIG_SAMA5_XDMAC1 */