summaryrefslogtreecommitdiff
path: root/memories/sdmmc/sdmmc_mci.c
blob: 3202945cd8d7de64b47105e29c83ff94e07ffaf2 (plain)
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
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
/* ----------------------------------------------------------------------------
 *         ATMEL Microcontroller Software Support
 * ----------------------------------------------------------------------------
 * Copyright (c) 2008, Atmel Corporation

 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the disclaimer below.
 *
 * Atmel's name may not be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
 * DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
 * ----------------------------------------------------------------------------
 */

//------------------------------------------------------------------------------
//         Headers
//------------------------------------------------------------------------------

#include "sdmmc_mci.h"

#include <utility/assert.h>
#include <utility/trace.h>

#include <pio/pio.h>

#include <string.h>

//------------------------------------------------------------------------------
//         Global variables
//------------------------------------------------------------------------------

#if defined(MCI2_INTERFACE)
unsigned char gSdmmcAutoHsEnable = 1;
#else
unsigned char gSdmmcAutoHsEnable = 0;
#endif

//------------------------------------------------------------------------------
//         Local constants
//------------------------------------------------------------------------------

//#define SINGLE_READ
//#define SINGLE_WRITE

// Timeout wait loop
#define TO_LOOP             0x10000

// SD card operation states
#define SD_STATE_IDLE        0
#define SD_STATE_INIT        1
#define SD_STATE_READY       2
#define SD_STATE_READ     0x10
#define SD_STATE_RD_RDY   0x11
#define SD_STATE_RD_BSY   0x12
#define SD_STATE_WRITE    0x20
#define SD_STATE_WR_RDY   0x21
#define SD_STATE_WR_BSY   0x22
#define SD_STATE_BOOT     0x30

// Delay between sending MMC commands
#define MMC_DELAY     0x4FF

#define SD_ADDRESS(pSd, address) \
    ( ((pSd)->totalSize == 0xFFFFFFFF) ? \
                            (address):((address) << SD_BLOCK_SIZE_BIT) )

//-----------------------------------------------------------------------------
/// MMC/SD in SPI mode reports R1 status always, and R2 for SEND_STATUS
/// R1 is the low order byte; R2 is the next highest byte, when present.
//-----------------------------------------------------------------------------
#define R1_SPI_IDLE             (1 << 0)
#define R1_SPI_ERASE_RESET      (1 << 1)
#define R1_SPI_ILLEGAL_COMMAND  (1 << 2)
#define R1_SPI_COM_CRC          (1 << 3)
#define R1_SPI_ERASE_SEQ        (1 << 4)
#define R1_SPI_ADDRESS          (1 << 5)
#define R1_SPI_PARAMETER        (1 << 6)
// R1 bit 7 is always zero
#define R2_SPI_CARD_LOCKED      (1 << 0)
#define R2_SPI_WP_ERASE_SKIP    (1 << 1)
#define R2_SPI_LOCK_UNLOCK_FAIL R2_SPI_WP_ERASE_SKIP
#define R2_SPI_ERROR            (1 << 2)
#define R2_SPI_CC_ERROR         (1 << 3)
#define R2_SPI_CARD_ECC_ERROR   (1 << 4)
#define R2_SPI_WP_VIOLATION     (1 << 5)
#define R2_SPI_ERASE_PARAM      (1 << 6)
#define R2_SPI_OUT_OF_RANGE     (1 << 7)
#define R2_SPI_CSD_OVERWRITE    R2_SPI_OUT_OF_RANGE

// Status register constants
#define STATUS_APP_CMD          (1UL << 5)
#define STATUS_SWITCH_ERROR     (1UL << 7)
#define STATUS_READY_FOR_DATA   (1UL << 8)
#define STATUS_IDLE             (0UL << 9)
#define STATUS_READY            (1UL << 9)
#define STATUS_IDENT            (2UL << 9)
#define STATUS_STBY             (3UL << 9)
#define STATUS_TRAN             (4UL << 9)
#define STATUS_DATA             (5UL << 9)
#define STATUS_RCV              (6UL << 9)
#define STATUS_PRG              (7UL << 9)
#define STATUS_DIS              (8UL << 9)
#define STATUS_STATE          (0xFUL << 9)
#define STATUS_ERASE_RESET       (1UL << 13)
#define STATUS_WP_ERASE_SKIP     (1UL << 15)
#define STATUS_CIDCSD_OVERWRITE  (1UL << 16)
#define STATUS_OVERRUN           (1UL << 17)
#define STATUS_UNERRUN           (1UL << 18)
#define STATUS_ERROR             (1UL << 19)
#define STATUS_CC_ERROR          (1UL << 20)
#define STATUS_CARD_ECC_FAILED   (1UL << 21)
#define STATUS_ILLEGAL_COMMAND   (1UL << 22)
#define STATUS_COM_CRC_ERROR     (1UL << 23)
#define STATUS_UN_LOCK_FAILED    (1UL << 24)
#define STATUS_CARD_IS_LOCKED    (1UL << 25)
#define STATUS_WP_VIOLATION      (1UL << 26)
#define STATUS_ERASE_PARAM       (1UL << 27)
#define STATUS_ERASE_SEQ_ERROR   (1UL << 28)
#define STATUS_BLOCK_LEN_ERROR   (1UL << 29)
#define STATUS_ADDRESS_MISALIGN  (1UL << 30)
#define STATUS_ADDR_OUT_OR_RANGE (1UL << 31)

#define STATUS_STOP ( STATUS_CARD_IS_LOCKED \
                        | STATUS_COM_CRC_ERROR \
                        | STATUS_ILLEGAL_COMMAND \
                        | STATUS_CC_ERROR \
                        | STATUS_ERROR \
                        | STATUS_STATE \
                        | STATUS_READY_FOR_DATA )

#define STATUS_WRITE ( STATUS_ADDR_OUT_OR_RANGE \
                        | STATUS_ADDRESS_MISALIGN \
                        | STATUS_BLOCK_LEN_ERROR \
                        | STATUS_WP_VIOLATION \
                        | STATUS_CARD_IS_LOCKED \
                        | STATUS_COM_CRC_ERROR \
                        | STATUS_ILLEGAL_COMMAND \
                        | STATUS_CC_ERROR \
                        | STATUS_ERROR \
                        | STATUS_ERASE_RESET \
                        | STATUS_STATE \
                        | STATUS_READY_FOR_DATA )

#define STATUS_READ  ( STATUS_ADDR_OUT_OR_RANGE \
                        | STATUS_ADDRESS_MISALIGN \
                        | STATUS_BLOCK_LEN_ERROR \
                        | STATUS_CARD_IS_LOCKED \
                        | STATUS_COM_CRC_ERROR \
                        | STATUS_ILLEGAL_COMMAND \
                        | STATUS_CARD_ECC_FAILED \
                        | STATUS_CC_ERROR \
                        | STATUS_ERROR \
                        | STATUS_ERASE_RESET \
                        | STATUS_STATE \
                        | STATUS_READY_FOR_DATA )

#define STATUS_SD_SWITCH ( STATUS_ADDR_OUT_OR_RANGE \
                            | STATUS_CARD_IS_LOCKED \
                            | STATUS_COM_CRC_ERROR \
                            | STATUS_ILLEGAL_COMMAND \
                            | STATUS_CARD_ECC_FAILED \
                            | STATUS_CC_ERROR \
                            | STATUS_ERROR \
                            | STATUS_UNERRUN \
                            | STATUS_OVERRUN \
                            | STATUS_STATE)

#define STATUS_MMC_SWITCH ( STATUS_CARD_IS_LOCKED \
                            | STATUS_COM_CRC_ERROR \
                            | STATUS_ILLEGAL_COMMAND \
                            | STATUS_CC_ERROR \
                            | STATUS_ERROR \
                            | STATUS_ERASE_RESET \
                            | STATUS_STATE \
                            | STATUS_READY_FOR_DATA \
                            | STATUS_SWITCH_ERROR )

//                            | (0x3UL << 12) /* IO_CURRENT_STATE */
#define STATUS_SDIO_CMD52 ( (1UL << 15) /* COM_CRC_ERROR */ \
                            | (1UL << 14) /* ILLEGAL_COMMAND */ \
                            | (1UL << 11) /* ERRIR */ \
                            | (1UL <<  9) /* FUNCTION_NUMBER */ \
                            | (1UL <<  8) /* OUT_OF_RANGE */)

//-----------------------------------------------------------------------------
/// OCR Register
//-----------------------------------------------------------------------------
#define AT91C_VDD_16_17          (1UL << 4)
#define AT91C_VDD_17_18          (1UL << 5)
#define AT91C_VDD_18_19          (1UL << 6)
#define AT91C_VDD_19_20          (1UL << 7)
#define AT91C_VDD_20_21          (1UL << 8)
#define AT91C_VDD_21_22          (1UL << 9)
#define AT91C_VDD_22_23          (1UL << 10)
#define AT91C_VDD_23_24          (1UL << 11)
#define AT91C_VDD_24_25          (1UL << 12)
#define AT91C_VDD_25_26          (1UL << 13)
#define AT91C_VDD_26_27          (1UL << 14)
#define AT91C_VDD_27_28          (1UL << 15)
#define AT91C_VDD_28_29          (1UL << 16)
#define AT91C_VDD_29_30          (1UL << 17)
#define AT91C_VDD_30_31          (1UL << 18)
#define AT91C_VDD_31_32          (1UL << 19)
#define AT91C_VDD_32_33          (1UL << 20)
#define AT91C_VDD_33_34          (1UL << 21)
#define AT91C_VDD_34_35          (1UL << 22)
#define AT91C_VDD_35_36          (1UL << 23)
#define AT91C_SDIO_MP            (1UL << 27)
#define AT91C_SDIO_NF            (7UL << 28)
#define AT91C_MMC_OCR_BIT2930    (3UL << 29)
#define AT91C_CARD_POWER_UP_BUSY (1UL << 31)

#define AT91C_MMC_HOST_VOLTAGE_RANGE     (AT91C_VDD_27_28 +\
                                          AT91C_VDD_28_29 +\
                                          AT91C_VDD_29_30 +\
                                          AT91C_VDD_30_31 +\
                                          AT91C_VDD_31_32 +\
                                          AT91C_VDD_32_33)

// MMC OCR response for Bit 29, 30
#define AT91C_MMC_NORM_DENSITY   (0x0UL << 29)
#define AT91C_MMC_HIGH_DENSITY   (0x2UL << 29)

#define AT91C_CCS    (1 << 30)

// MCI_CMD Register Value
#define AT91C_POWER_ON_INIT      (0 | AT91C_MCI_TRCMD_NO    \
                                    | AT91C_MCI_SPCMD_INIT  \
                                    | AT91C_MCI_OPDCMD)

//-----------------------------------------------------------------------------
/// eMMC CMD6
//-----------------------------------------------------------------------------
#define AT91C_EMMC_CMD6ARG_ACCESS_BITS        (0x3UL << 24)
#define AT91C_EMMC_CMD6ARG_ACCESS_SHIFT       (24)
// change command sets
#define AT91C_EMMC_CMD6ARG_ACCESS_CMDSETS     (0x0UL << 24)
// set bits in the value field
#define AT91C_EMMC_CMD6ARG_ACCESS_SETBITS     (0x1UL << 24)
// clear bits in the value field
#define AT91C_EMMC_CMD6ARG_ACCESS_CLRBITS     (0x2UL << 24)
// the value field is written into the pointed byte
#define AT91C_EMMC_CMD6ARG_ACCESS_WRBYTES     (0x3UL << 24) 
#define AT91C_EMMC_CMD6ARG_INDEX_BITS         (0xffUL << 16)
#define AT91C_EMMC_CMD6ARG_INDEX_SHIFT        (16)
#define AT91C_EMMC_CMD6ARG_VALUE_BITS         (0xffUL << 8)
#define AT91C_EMMC_CMD6ARG_VALUE_SHIFT        (8)
#define AT91C_EMMC_CMD6ARG_CMDSET_BITS        (0x7UL << 0)
#define AT91C_EMMC_CMD6ARG_CMDSET_SHIFT       (0)

//-----------------------------------------------------------------------------
// Command Classes
//-----------------------------------------------------------------------------
//
// Class 0, 2, 4, 5, 7 and 8 are mandatory and shall be supported by
// all SD Memory Cards.
//
// Basic Commands (class 0)
//
// Cmd0 MCI + SPI
#define   AT91C_GO_IDLE_STATE_CMD     (0 | AT91C_MCI_TRCMD_NO \
                                         | AT91C_MCI_SPCMD_NONE )
// Cmd1 SPI
#define   AT91C_MMC_SEND_OP_COND_CMD  (1 | AT91C_MCI_TRCMD_NO \
                                         | AT91C_MCI_SPCMD_NONE \
                                         | AT91C_MCI_RSPTYP_48 \
                                         | AT91C_MCI_OPDCMD)
// Cmd2 MCI
#define   AT91C_ALL_SEND_CID_CMD      (2 | AT91C_MCI_TRCMD_NO \
                                         | AT91C_MCI_SPCMD_NONE \
                                         | AT91C_MCI_OPDCMD \
                                         | AT91C_MCI_RSPTYP_136 )
// Cmd3 MCI
#define   AT91C_SET_RELATIVE_ADDR_CMD (3 | AT91C_MCI_TRCMD_NO \
                                         | AT91C_MCI_SPCMD_NONE \
                                         | AT91C_MCI_RSPTYP_48 \
                                         | AT91C_MCI_OPDCMD \
                                         | AT91C_MCI_MAXLAT )
// Cmd4 MCI
#define AT91C_SET_DSR_CMD             (4 | AT91C_MCI_TRCMD_NO \
                                         | AT91C_MCI_SPCMD_NONE \
                                         | AT91C_MCI_RSPTYP_NO \
                                         | AT91C_MCI_MAXLAT )
// Cmd5 MCI
#define AT91C_IO_SEND_OP_COND_CMD     (5 | AT91C_MCI_TRCMD_NO \
                                         | AT91C_MCI_SPCMD_NONE \
                                         | AT91C_MCI_RSPTYP_48 \
                                         | AT91C_MCI_OPDCMD )
// Cmd6 SD/MMC
#if defined(MCI2_INTERFACE)
#define AT91C_MMC_SWITCH_CMD          (6 | AT91C_MCI_TRCMD_NO \
                                         | AT91C_MCI_SPCMD_NONE \
                                         | AT91C_MCI_RSPTYP_R1B \
                                         | AT91C_MCI_MAXLAT )
#else
#define AT91C_MMC_SWITCH_CMD          (6 | AT91C_MCI_TRCMD_NO \
                                         | AT91C_MCI_SPCMD_NONE \
                                         | AT91C_MCI_RSPTYP_48 \
                                         | AT91C_MCI_MAXLAT )
#endif
#define AT91C_SD_SWITCH_CMD           (6 | AT91C_MCI_TRCMD_START \
                                         | AT91C_MCI_TRTYP_BLOCK \
                                         | AT91C_MCI_TRDIR_READ \
                                         | AT91C_MCI_SPCMD_NONE \
                                         | AT91C_MCI_RSPTYP_48 \
                                         | AT91C_MCI_MAXLAT )
// cmd7 MCI
#define   AT91C_SEL_DESEL_CARD_CMD    (7 | AT91C_MCI_TRCMD_NO \
                                         | AT91C_MCI_SPCMD_NONE \
                                         | AT91C_MCI_RSPTYP_48 \
                                         | AT91C_MCI_MAXLAT )
#define   AT91C_SEL_CARD_CMD          (7 | AT91C_MCI_TRCMD_NO \
                                         | AT91C_MCI_SPCMD_NONE \
                                         | AT91C_MCI_RSPTYP_48 \
                                         | AT91C_MCI_MAXLAT )
#define   AT91C_DESEL_CARD_CMD        (7 | AT91C_MCI_TRCMD_NO \
                                         | AT91C_MCI_SPCMD_NONE \
                                         | AT91C_MCI_RSPTYP_NO \
                                         | AT91C_MCI_MAXLAT )
// Cmd8 MCI + SPI
#define   AT91C_SEND_IF_COND          (8  | AT91C_MCI_TRCMD_NO \
                                          | AT91C_MCI_SPCMD_NONE \
                                          | AT91C_MCI_RSPTYP_48 \
                                          | AT91C_MCI_MAXLAT )
// Cmd9 MCI + SPI
#define   AT91C_SEND_CSD_CMD          (9  | AT91C_MCI_TRCMD_NO \
                                          | AT91C_MCI_SPCMD_NONE \
                                          | AT91C_MCI_RSPTYP_136 \
                                          | AT91C_MCI_MAXLAT )
// Cmd10 MCI + SPI
#define   AT91C_SEND_CID_CMD          (10 | AT91C_MCI_TRCMD_NO \
                                          | AT91C_MCI_SPCMD_NONE \
                                          | AT91C_MCI_RSPTYP_136 \
                                          | AT91C_MCI_MAXLAT )
// Cmd12 MCI + SPI
#if defined(MCI2_INTERFACE)
#define   AT91C_STOP_TRANSMISSION_CMD (12 | AT91C_MCI_TRCMD_STOP \
                                          | AT91C_MCI_SPCMD_NONE \
                                          | AT91C_MCI_RSPTYP_R1B \
                                          | AT91C_MCI_MAXLAT )
#else
#define   AT91C_STOP_TRANSMISSION_CMD (12 | AT91C_MCI_TRCMD_STOP \
                                          | AT91C_MCI_SPCMD_NONE \
                                          | AT91C_MCI_RSPTYP_48 \
                                          | AT91C_MCI_MAXLAT )
#endif
// Cmd13 MCI + SPI
#define   AT91C_SEND_STATUS_CMD       (13 | AT91C_MCI_TRCMD_NO \
                                          | AT91C_MCI_SPCMD_NONE \
                                          | AT91C_MCI_RSPTYP_48 \
                                          | AT91C_MCI_MAXLAT )
// Cmd15 MCI
#define AT91C_GO_INACTIVE_STATE_CMD   (15 | AT91C_MCI_RSPTYP_NO )

// Cmd58 SPI
#define   AT91C_READ_OCR_CMD          (58 | AT91C_MCI_RSPTYP_48 \
                                          | AT91C_MCI_SPCMD_NONE \
                                          | AT91C_MCI_MAXLAT )
// Cmd59 SPI
#define   AT91C_CRC_ON_OFF_CMD        (59 | AT91C_MCI_RSPTYP_48 \
                                          | AT91C_MCI_SPCMD_NONE \
                                          | AT91C_MCI_MAXLAT )

//*------------------------------------------------
//* Class 2 commands: Block oriented Read commands
//*------------------------------------------------

// Cmd8 for MMC
#define AT91C_SEND_EXT_CSD_CMD          (8 | AT91C_MCI_SPCMD_NONE \
                                           | AT91C_MCI_OPDCMD_PUSHPULL \
                                           | AT91C_MCI_RSPTYP_48 \
                                           | AT91C_MCI_TRCMD_START \
                                           | AT91C_MCI_TRTYP_BLOCK \
                                           | AT91C_MCI_TRDIR \
                                           | AT91C_MCI_MAXLAT)

// Cmd16
#define AT91C_SET_BLOCKLEN_CMD          (16 | AT91C_MCI_TRCMD_NO \
                                            | AT91C_MCI_SPCMD_NONE \
                                            | AT91C_MCI_RSPTYP_48 \
                                            | AT91C_MCI_MAXLAT )
// Cmd17
#define AT91C_READ_SINGLE_BLOCK_CMD     (17 | AT91C_MCI_SPCMD_NONE \
                                            | AT91C_MCI_RSPTYP_48 \
                                            | AT91C_MCI_TRCMD_START \
                                            | AT91C_MCI_TRTYP_BLOCK \
                                            | AT91C_MCI_TRDIR \
                                            | AT91C_MCI_MAXLAT)
// Cmd18
#define AT91C_READ_MULTIPLE_BLOCK_CMD   (18 | AT91C_MCI_SPCMD_NONE \
                                            | AT91C_MCI_RSPTYP_48 \
                                            | AT91C_MCI_TRCMD_START \
                                            | AT91C_MCI_TRTYP_MULTIPLE \
                                            | AT91C_MCI_TRDIR \
                                            | AT91C_MCI_MAXLAT)

//*------------------------------------------------
//* Class 4 commands: Block oriented write commands
//*------------------------------------------------
// Cmd24
#define AT91C_WRITE_BLOCK_CMD           (24 | AT91C_MCI_SPCMD_NONE \
                                            | AT91C_MCI_RSPTYP_48 \
                                            | AT91C_MCI_TRCMD_START \
                                            | (AT91C_MCI_TRTYP_BLOCK \
                                                & ~(AT91C_MCI_TRDIR)) \
                                            | AT91C_MCI_MAXLAT)
// Cmd25
#define AT91C_WRITE_MULTIPLE_BLOCK_CMD  (25 | AT91C_MCI_SPCMD_NONE \
                                            | AT91C_MCI_RSPTYP_48 \
                                            | AT91C_MCI_TRCMD_START \
                                            | (AT91C_MCI_TRTYP_MULTIPLE \
                                                & ~(AT91C_MCI_TRDIR)) \
                                            | AT91C_MCI_MAXLAT)
// Cmd27
#define AT91C_PROGRAM_CSD_CMD           (27 | AT91C_MCI_RSPTYP_48 )

//*----------------------------------------
//* Class 5 commands: Erase commands
//*----------------------------------------
// Cmd32
//#define AT91C_TAG_SECTOR_START_CMD          (32 | AT91C_MCI_SPCMD_NONE  | AT91C_MCI_RSPTYP_48   | AT91C_MCI_TRCMD_NO    | AT91C_MCI_MAXLAT)
// Cmd33
//#define AT91C_TAG_SECTOR_END_CMD            (33 | AT91C_MCI_SPCMD_NONE  | AT91C_MCI_RSPTYP_48   | AT91C_MCI_TRCMD_NO    | AT91C_MCI_MAXLAT)
// Cmd38
//#define AT91C_ERASE_CMD                     (38 | AT91C_MCI_SPCMD_NONE  | AT91C_MCI_RSPTYP_48   | AT91C_MCI_TRCMD_NO    | AT91C_MCI_MAXLAT )

//*----------------------------------------
//* Class 7 commands: Lock commands
//*----------------------------------------
// Cmd42
//#define AT91C_LOCK_UNLOCK           (42 | AT91C_MCI_SPCMD_NONE  | AT91C_MCI_RSPTYP_48   | AT91C_MCI_TRCMD_NO    | AT91C_MCI_MAXLAT) // not tested

//*-----------------------------------------------
// Class 8 commands: Application specific commands
//*-----------------------------------------------
// Cmd55
#define AT91C_APP_CMD               (55 | AT91C_MCI_SPCMD_NONE \
                                        | AT91C_MCI_RSPTYP_48 \
                                        | AT91C_MCI_TRCMD_NO \
                                        | AT91C_MCI_MAXLAT)
// cmd 56
//#define AT91C_GEN_CMD               (56 | AT91C_MCI_SPCMD_NONE  | AT91C_MCI_RSPTYP_48   | AT91C_MCI_TRCMD_NO | AT91C_MCI_MAXLAT)    // not tested
// ACMD6
#define AT91C_SD_SET_BUS_WIDTH_CMD          (6  | AT91C_MCI_SPCMD_NONE \
                                                | AT91C_MCI_RSPTYP_48 \
                                                | AT91C_MCI_TRCMD_NO \
                                                | AT91C_MCI_MAXLAT)
// ACMD13
#define AT91C_SD_STATUS_CMD                 (13 | AT91C_MCI_SPCMD_NONE \
                                                | AT91C_MCI_RSPTYP_48 \
                                                | AT91C_MCI_TRCMD_START \
                                                | AT91C_MCI_TRTYP_BLOCK \
                                                | AT91C_MCI_TRDIR_READ \
                                                | AT91C_MCI_MAXLAT)
// ACMD22
//#define AT91C_SD_SEND_NUM_WR_BLOCKS_CMD     (22 | AT91C_MCI_SPCMD_NONE  | AT91C_MCI_RSPTYP_48   | AT91C_MCI_TRCMD_NO    | AT91C_MCI_MAXLAT)
// ACMD23
//#define AT91C_SD_SET_WR_BLK_ERASE_COUNT_CMD (23 | AT91C_MCI_SPCMD_NONE  | AT91C_MCI_RSPTYP_48   | AT91C_MCI_TRCMD_NO    | AT91C_MCI_MAXLAT)
// ACMD41
#define AT91C_SD_APP_OP_COND_CMD            (41 | AT91C_MCI_SPCMD_NONE \
                                                | AT91C_MCI_RSPTYP_48 \
                                                | AT91C_MCI_TRCMD_NO )
// ACMD42
//#define AT91C_SD_SET_CLR_CARD_DETECT_CMD    (42 | AT91C_MCI_SPCMD_NONE  | AT91C_MCI_RSPTYP_48   | AT91C_MCI_TRCMD_NO    | AT91C_MCI_MAXLAT)
// ACMD51
#define AT91C_SD_SEND_SCR_CMD               (51 | AT91C_MCI_SPCMD_NONE \
                                                | AT91C_MCI_RSPTYP_48 \
                                                | AT91C_MCI_TRCMD_START \
                                                | AT91C_MCI_TRDIR_READ \
                                                | AT91C_MCI_TRTYP_BLOCK \
                                                | AT91C_MCI_MAXLAT)

// SDIO commands
// CMD5, R4
#define AT91C_SDIO_SEND_OP_COND (5 | AT91C_MCI_TRCMD_NO \
                                   | AT91C_MCI_SPCMD_NONE \
                                   | AT91C_MCI_RSPTYP_48 \
                                   | AT91C_MCI_OPDCMD)

// CMD52, R5
#define AT91C_SDIO_IO_RW_DIRECT (52| AT91C_MCI_TRCMD_NO \
                                   | AT91C_MCI_SPCMD_NONE \
                                   | AT91C_MCI_RSPTYP_48 \
                                   | AT91C_MCI_MAXLAT )

// CMD53, R5
#define AT91C_SDIO_IO_RW_EXTENDED (53 | AT91C_MCI_SPCMD_NONE \
                                      | AT91C_MCI_RSPTYP_48 \
                                      | AT91C_MCI_TRCMD_START \
                                      | AT91C_MCI_MAXLAT)

#ifdef AT91C_MCI_SPCMD_BOOTREQ
// BOOTREQ
#define AT91C_BOOTREQ           (AT91C_MCI_SPCMD_BOOTREQ \
                                    | AT91C_MCI_TRDIR_READ \
                                    | AT91C_MCI_TRCMD_START \
                                    | AT91C_MCI_MAXLAT)
// BOOTEND
#define AT91C_BOOTEND           (AT91C_MCI_SPCMD_BOOTEND \
                                    | AT91C_MCI_OPDCMD_PUSHPULL)
#endif
// Optional commands
#define SD_ACMD6_SUPPORT        (1UL << 0)
#define SD_ACMD13_SUPPORT       (1UL << 1)
#define SD_ACMD41_SUPPORT       (1UL << 2)
#define SD_ACMD51_SUPPORT       (1UL << 3)

#define SD_CMD16_SUPPORT        (1UL << 8)

//------------------------------------------------------------------------------
//         Local functions
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
/// DecodeR1
/// \param R1  
//------------------------------------------------------------------------------
void DecodeR1(unsigned char R1)
{
    if( (R1 & R1_SPI_IDLE)==R1_SPI_IDLE) {
        TRACE_DEBUG("R1_SPI_IDLE\n\r");
    }
    if( (R1 & R1_SPI_ERASE_RESET)==R1_SPI_ERASE_RESET) {
        TRACE_DEBUG("R1_SPI_ERASE_RESET\n\r");
    }
    if( (R1 & R1_SPI_ILLEGAL_COMMAND)==R1_SPI_ILLEGAL_COMMAND) {
        TRACE_DEBUG("R1_SPI_ILLEGAL_COMMAND\n\r");
    }
    if( (R1 & R1_SPI_COM_CRC)==R1_SPI_COM_CRC) {
        TRACE_DEBUG("R1_SPI_COM_CRC\n\r");
    }
    if( (R1 & R1_SPI_ERASE_SEQ)==R1_SPI_ERASE_SEQ) {
        TRACE_DEBUG("R1_SPI_ERASE_SEQ\n\r");
    }
    if( (R1 & R1_SPI_ADDRESS)==R1_SPI_ADDRESS) {
        TRACE_DEBUG("R1_SPI_ADDRESS\n\r");
    }
    if( (R1 & R1_SPI_PARAMETER)==R1_SPI_PARAMETER) {
        TRACE_DEBUG("R1_SPI_PARAMETER\n\r");
    }
}

//------------------------------------------------------------------------------
/// DecodeR2
/// \param R2  
//------------------------------------------------------------------------------
void DecodeR2(unsigned char R2)
{
    if( (R2 & R2_SPI_CARD_LOCKED)==R2_SPI_CARD_LOCKED) {
        TRACE_DEBUG("R2_SPI_CARD_LOCKED\n\r");
    }
    if( (R2 & R2_SPI_WP_ERASE_SKIP)==R2_SPI_WP_ERASE_SKIP) {
        TRACE_DEBUG("R2_SPI_WP_ERASE_SKIP/R2_SPI_LOCK_UNLOCK_FAIL\n\r");
    }
    if( (R2 & R2_SPI_ERROR)==R2_SPI_ERROR) {
        TRACE_DEBUG("R2_SPI_ERROR\n\r");
    }
    if( (R2 & R2_SPI_CC_ERROR)==R2_SPI_CC_ERROR) {
        TRACE_DEBUG("R2_SPI_CC_ERROR\n\r");
    }
    if( (R2 & R2_SPI_CARD_ECC_ERROR)==R2_SPI_CARD_ECC_ERROR) {
        TRACE_DEBUG("R2_SPI_CARD_ECC_ERROR\n\r");
    }
    if( (R2 & R2_SPI_WP_VIOLATION)==R2_SPI_WP_VIOLATION) {
        TRACE_DEBUG("R2_SPI_WP_VIOLATION\n\r");
    }
    if( (R2 & R2_SPI_ERASE_PARAM)==R2_SPI_ERASE_PARAM) {
        TRACE_DEBUG("R2_SPI_ERASE_PARAM\n\r");
    }
    if( (R2 & R2_SPI_OUT_OF_RANGE)==R2_SPI_OUT_OF_RANGE) {
        TRACE_DEBUG("R2_SPI_OUT_OF_RANGE/R2_SPI_CSD_OVERWRITE\n\r");
    }
}

//------------------------------------------------------------------------------
/// Get Trans Speed Value (Kbit/s)
/// \param tranSpeed The TRAN_SPEED value from SD(IO)/MMC enum information.
/// \param unitList  Transfer rate units (Kbit/s), 4 units listed.
/// \param nbUnits   Transfer rate units list size.
/// \param codeList  Time value codes list, 16 codes listed.
//------------------------------------------------------------------------------
static unsigned int MmcGetTranSpeed(unsigned int tranSpeed,
                            const unsigned int* unitList, unsigned int nbUnits,
                            const unsigned int* codeList)
{
    unsigned int unit, value;
    unit = tranSpeed & 0x7;
    if (unit < nbUnits) unit = unitList[unit];
    else                return 0;
    value = (tranSpeed >> 3) & 0xF;
    if (value < 16)   value = codeList[value];
    else                return 0;
    return (unit * value);
}

//------------------------------------------------------------------------------
/// Get Trans Speed Value
/// \param pSd    
//------------------------------------------------------------------------------
void GetTransSpeedValue(SdCard *pSd)
{
    // CSD register, TRANS_SPEED bit
    const unsigned int units[4] = {10, 100, 1000, 10000 }; // *Kbit/s 
    const unsigned int values_emmc[16] = {0, 10, 12, 13, 15, 20,
                                          26, 30, 35, 40, 45, 52,
                                          55, 60, 70, 80};
    const unsigned int values_sdmmc[16] = {0, 10, 12, 13, 15, 20,
                                           25, 30, 35, 40, 45, 50,
                                           55, 60, 70, 80};
  #if 0
    unsigned int unit, value;
    unit = (SD_CSD_TRAN_SPEED(pSd) & 0x7);
    if(unit < 4)    unit  = units[unit];
    else            return;
    value = (SD_CSD_TRAN_SPEED(pSd) >> 3) & 0xF;
    if (value < 16) {
        if (pSd->cardType >= CARD_MMC && SD_CID_BGA(pSd) == 1) {
            value = values_emmc[value];
        }
        else
            value = values_sdmmc[value];
    }
    else            return;
    pSd->transSpeed = (unit * value);
  #else
    pSd->transSpeed = MmcGetTranSpeed(SD_CSD_TRAN_SPEED(pSd),
                                      units, 4,
                                      (pSd->cardType >= CARD_MMC
                                       && SD_CID_BGA(pSd) == 1) ?
                                       values_emmc : values_sdmmc);
  #endif
    if (pSd->cardType >= CARD_MMC && SD_EXTCSD_HS_TIMING(pSd)) {
        pSd->transSpeed *= 2;
    }
    TRACE_WARNING_WP("-I- SD/MMC TRANS SPEED %d KBit/s\r\n", pSd->transSpeed);
    pSd->transSpeed *= 1000;  
}

#if 1
//------------------------------------------------------------------------------
/// Reset the SdCmd
//------------------------------------------------------------------------------
static void ResetCommand(SdCmd *pCommand)
{
  #if 0
    unsigned char* p = (unsigned char*)pCommand;
    unsigned int   l = sizeof(SdCmd);
    while(l --) *p++ = 0;
  #else
    pCommand->cmd       = 0;
    pCommand->arg       = 0;
    pCommand->pData     = 0;
    pCommand->blockSize = 0;
    pCommand->nbBlock   = 0;
    pCommand->pResp     = 0;
    pCommand->callback  = 0;
    pCommand->pArg      = 0;
    pCommand->resType   = 0;
    pCommand->dataTran  = 0;
    pCommand->tranType  = 0;
    pCommand->isRead    = 0;
    pCommand->status    = 0;
  #endif
}
#else
// GNU halt on memset now
# define ResetCommand(pCommand) memset(pCommand, 0, sizeof(SdCmd))
#endif

//------------------------------------------------------------------------------
/// Delay some loop
//------------------------------------------------------------------------------
static void Delay(volatile unsigned int loop)
{
    for(;loop > 0; loop --);
}

//------------------------------------------------------------------------------
/// Sends the current SD card driver command to the card.
/// Returns 0 if successful; Otherwise, returns the transfer status code or
/// SD_ERROR_DRIVER if there was a problem with the SD transfer.
/// \param pSd  Pointer to a SdCard driver instance.
//------------------------------------------------------------------------------
static unsigned char SendCommand(SdCard *pSd)
{
    SdCmd *pCommand = &(pSd->command);
    SdDriver *pSdDriver = pSd->pSdDriver;
    unsigned char error;

    // Send command
    error = MCI_SendCommand((Mci *)pSdDriver, (MciCmd *)pCommand);
    if (error) {
        TRACE_ERROR("MCI SendCommand: Failed to send command (%d)\n\r", error);
        return SD_ERROR_DRIVER;
    }

    // Wait for command to complete (if no callback defined)
    if (pCommand->callback == 0) {
        while (!MCI_IsTxComplete((Mci *)pSdDriver));
    }

    // Check for using fifo to transfer data
  #if !defined(MCI_DMA_ENABLE) && defined(MCI2_INTERFACE)
    if (pCommand->dataTran && pCommand->nbBlock) {
        MCI_FifoTransfer((Mci *)pSdDriver, (MciCmd *)pCommand);
    }
  #endif

    return pCommand->status;
}

//------------------------------------------------------------------------------
/// Initialization delay: The maximum of 1 msec, 74 clock cycles and supply ramp
/// up time.
/// Returns the command transfer result (see SendCommand).
/// \param pSd  Pointer to a SdCard driver instance.
//------------------------------------------------------------------------------
static unsigned char Pon(SdCard *pSd)
{
    SdCmd *pCommand = &(pSd->command);
    unsigned int response;
    unsigned char error;

    ResetCommand(pCommand);
    // Fill command information
    pCommand->cmd = AT91C_POWER_ON_INIT;
    pCommand->pResp = &response;

    // Send command
    error =  SendCommand(pSd);
    return error;
}

#if defined(MCI2_INTERFACE) && defined(AT91C_MCI_SPCMD_BOOTREQ)
//------------------------------------------------------------------------------
/// Initialization delay: The maximum of 1 msec, 74 clock cycles and supply ramp
/// up time, CMD keeps low so that the device run in boot mode.
/// Returns the command transfer result (see SendCommand).
/// \param pSd  Pointer to a SdCard driver instance.
//------------------------------------------------------------------------------
static unsigned char PonBoot(SdCard *pSd)
{
    SdCmd *pCommand = &(pSd->command);
    unsigned int response;
    unsigned char error;

    ResetCommand(pCommand);
    // Fill command information
    pCommand->cmd = AT91C_POWER_ON_INIT;
    pCommand->pResp = &response;

    // Send command
    error =  SendCommand(pSd);
    return error;
}
#endif

//------------------------------------------------------------------------------
/// Resets all cards to idle state
/// \param pSd  Pointer to a SdCard driver instance.
/// \param arg  Argument used.
/// \return the command transfer result (see SendCommand).
//------------------------------------------------------------------------------
static unsigned char Cmd0(SdCard *pSd, unsigned int arg)
{
    SdCmd *pCommand = &(pSd->command);
    unsigned int response;
    unsigned char error;

    TRACE_DEBUG("Cmd0()\n\r");
    ResetCommand(pCommand);
    // Fill command information
    pCommand->cmd = AT91C_GO_IDLE_STATE_CMD;
    pCommand->arg = arg;
    pCommand->pResp = &response;

    // send command
    error =  SendCommand(pSd);
    return error;
}

//------------------------------------------------------------------------------
/// MMC send operation condition command.
/// Sends host capacity support information and activates the card's
/// initialization process.
/// Returns the command transfer result (see SendCommand).
/// \param pSd  Pointer to a SdCard driver instance.
/// \param hdSupport  Indicate whether the host support high density MMC.
/// \param pHdSupport  Indicate whether the card is a high density MMC.
//------------------------------------------------------------------------------
static unsigned char Cmd1(SdCard *pSd,
                          unsigned char hdSupport,
                          unsigned char *pHdSupport)
{
    SdCmd *pCommand = &(pSd->command);
    unsigned char error;
    unsigned int response;

    TRACE_DEBUG("Cmd1()\n\r");
    ResetCommand(pCommand);
    // Fill command information
    pCommand->cmd = AT91C_MMC_SEND_OP_COND_CMD;
    pCommand->arg = AT91C_MMC_HOST_VOLTAGE_RANGE;
    if(hdSupport) {
        pCommand->arg |= AT91C_MMC_HIGH_DENSITY;
    }
    else {
        pCommand->arg |= AT91C_MMC_NORM_DENSITY;
    }
    pCommand->resType = 3;
    pCommand->pResp = &response;

    // send command
    *pHdSupport = 0; 
    error = SendCommand(pSd);
    if (error) {
        return error;
    }
    if ((response & AT91C_CARD_POWER_UP_BUSY) == AT91C_CARD_POWER_UP_BUSY) {        if((response & AT91C_MMC_OCR_BIT2930) == AT91C_MMC_HIGH_DENSITY) {
            *pHdSupport = 1;
        }
        return 0;
    }
    else {
        return SD_ERROR_DRIVER;
    }
}

//------------------------------------------------------------------------------
/// Asks any card to send the CID numbers
/// on the CMD line (any card that is
/// connected to the host will respond)
/// Returns the command transfer result (see SendCommand).
/// \param pSd  Pointer to a SD card driver instance.
/// \param pCid  Buffer for storing the CID numbers.
//------------------------------------------------------------------------------
static unsigned char Cmd2(SdCard *pSd)
{
    SdCmd *pCommand = &(pSd->command);

    TRACE_DEBUG("Cmd2()\n\r");
    ResetCommand(pCommand);
    // Fill the command information
    pCommand->cmd = AT91C_ALL_SEND_CID_CMD;
    pCommand->resType = 2;
    pCommand->pResp = pSd->cid;

    // Send the command
    return SendCommand(pSd);
}

//------------------------------------------------------------------------------
/// Ask the card to publish a new relative address (RCA)
/// Returns the command transfer result (see SendCommand).
/// \param pSd  Pointer to a SD card driver instance.
//------------------------------------------------------------------------------
static unsigned char Cmd3(SdCard *pSd)
{
    SdCmd *pCommand = &(pSd->command);
    unsigned int cardAddress;
    unsigned char error;

    TRACE_DEBUG("Cmd3()\n\r");
    ResetCommand(pCommand);
    // Fill command information
    pCommand->cmd = AT91C_SET_RELATIVE_ADDR_CMD;

    // Assign relative address to MMC card
    if ((pSd->cardType == CARD_MMC) || (pSd->cardType == CARD_MMCHD)) {
        pCommand->arg = (0x1 << 16);
    }
    pCommand->resType = 1;
    pCommand->pResp = &cardAddress;

    // Send command
    error = SendCommand(pSd);
    if (error) {
        return error;
    }

    // Save card address in driver
    if ( (pSd->cardType == CARD_SD)
        || (pSd->cardType == CARD_SDHC)) {
        pSd->cardAddress = (cardAddress >> 16) & 0xFFFF;
    }
    else if (pSd->cardType >= CARD_SDIO) {
        pSd->cardAddress = (cardAddress >> 16) & 0xFFFF;
    }
    else {
        // Default MMC RCA is 0x0001
        pSd->cardAddress = 1;
    }

    return 0;
}

#if MCI_SDIO_ENABLE
//------------------------------------------------------------------------------
/// SDIO send operation condition command.
/// Sends host capacity support information and activates the card's
/// initialization process.
/// Returns the command transfer result (see SendCommand).
/// \param pSd  Pointer to a SdCard driver instance.
/// \param pIo  Pointer to data send as well as response buffer.
//------------------------------------------------------------------------------
static unsigned char Cmd5(SdCard *pSd,
                          unsigned int *pIo)
{
    SdCmd *pCommand = &(pSd->command);
    unsigned char error;

    TRACE_DEBUG("Cmd5()\n\r");
    ResetCommand(pCommand);
    // Fill command information
    pCommand->cmd = AT91C_IO_SEND_OP_COND_CMD;
    pCommand->arg = *pIo;
    pCommand->resType = 4;
    pCommand->pResp = pIo;

    // send command
    error = SendCommand(pSd);
    return error;
}
#endif

//------------------------------------------------------------------------------
/// Command toggles a card between the
/// stand-by and transfer states or between
/// the programming and disconnect states.
/// Returns the command transfer result (see SendCommand).
/// \param pSd  Pointer to a SD card driver instance.
/// \param address  Relative Card Address (0 deselects all).
//------------------------------------------------------------------------------
static unsigned char Cmd7(SdCard *pSd, unsigned int address)
{
    SdCmd *pCommand = &(pSd->command);

    TRACE_DEBUG("Cmd7()\n\r");
    ResetCommand(pCommand);
    // Fill command information
    pCommand->cmd = AT91C_SEL_DESEL_CARD_CMD;
    pCommand->arg = address << 16;
    pCommand->resType = 1;

    // Send command
    return SendCommand(pSd);
}

//------------------------------------------------------------------------------
/// Switches the mode of operation of the selected card (SD/MMC) or
/// modifies the EXT_CSD registers (for MMC only).
/// CMD6 is valid under the "trans" state.
/// \return The command transfer result (see SendCommand).
/// \param  pSd         Pointer to a SD/MMC card driver instance.
/// \param  pSwitchArg  Pointer to a MmcCmd6Arg instance.
/// \param  pStatus     Pointer to where the 512bit status is returned.
/// \param  pResp       Pointer to where the response is returned.
//------------------------------------------------------------------------------
static unsigned char Cmd6(SdCard *pSd,
                          const void * pSwitchArg,
                          unsigned int  * pStatus,
                          unsigned int  * pResp)
{
    SdCmd *pCommand = &(pSd->command);
    unsigned int  response;
    unsigned char error;
    SdCmd6Arg  * pSdSwitch;
    MmcCmd6Arg * pMmcSwitch;

    SANITY_CHECK(pSd);
    SANITY_CHECK(pSwitchArg);

    TRACE_DEBUG("CMD6()\n\r");

    ResetCommand(pCommand);

    if (pSd->cardType >= CARD_MMC) {
        pMmcSwitch = (MmcCmd6Arg*)pSwitchArg;
        // R1b response
        pCommand->cmd = AT91C_MMC_SWITCH_CMD;
        pCommand->resType = 1;
        pCommand->arg =   (pMmcSwitch->access << 24)
                        | (pMmcSwitch->index  << 16)
                        | (pMmcSwitch->value  <<  8)
                        | (pMmcSwitch->cmdSet <<  0);
    }
    else if (pSd->cardType >= CARD_SD) {

        pSdSwitch = (SdCmd6Arg*)pSwitchArg;
        // R1 response & 512 bits of status on DAT
        pCommand->cmd = AT91C_SD_SWITCH_CMD;
        pCommand->resType = 1;
        pCommand->arg =   (pSdSwitch->mode << 31)
                        | (pSdSwitch->reserved << 30)
                        | (pSdSwitch->reserveFG6 << 20)
                        | (pSdSwitch->reserveFG5 << 16)
                        | (pSdSwitch->reserveFG4 << 12)
                        | (pSdSwitch->reserveFG3 <<  8)
                        | (pSdSwitch->command << 4)
                        | (pSdSwitch->accessMode << 0);
        if (pStatus) {
            pCommand->blockSize = 512 / 8;
            pCommand->nbBlock = 1;
            pCommand->pData = (unsigned char*)pStatus;

            pCommand->dataTran = 1;
            pCommand->isRead = 1;
            pCommand->tranType = MCI_NEW_TRANSFER;
        }
    }
    pCommand->pResp = &response;

    TRACE_INFO("CMD6(%d) arg 0x%X\n\r", pSd->cardType, pCommand->arg);

    error = SendCommand(pSd);

    if (error)
        return error;
    else if (pResp)
        *pResp = response;

    return 0;
}

//------------------------------------------------------------------------------
/// SD:  Sends SD Memory Card interface condition, which includes host supply
///      voltage information and asks the card whether card supports voltage.
///      Should be performed at initialization time to detect the card type.
/// MMC: SEND_EXT_CSD, to get EXT_CSD register as a block of data.
///      Valid under "trans" state.
/// \param pSd   Pointer to a SD card driver instance.
/// \param sdCmd For SD Memory Card interface condition 
/// \param arg   Expected supply voltage(SD) or 512 byte buffer pointer (MMC).
/// \return 0 if successful;
///         otherwise returns SD_ERROR_NORESPONSE if the card did not answer
///         the command, or SD_ERROR_DRIVER.
//------------------------------------------------------------------------------
static unsigned char Cmd8(SdCard *pSd,
                          unsigned char sdCmd,
                          void* arg)
{
    SdCmd *pCommand = &(pSd->command);
    unsigned int response;
    unsigned char error;
    unsigned char supplyVoltage = (unsigned char)((unsigned int)arg);

    TRACE_DEBUG("Cmd8()\n\r");
    ResetCommand(pCommand);

    if (sdCmd) {

        // Fill command information
        pCommand->cmd = AT91C_SEND_IF_COND;
        pCommand->arg = (supplyVoltage << 8) | (0xAA);
        pCommand->resType = 7;

        TRACE_DEBUG("supplyVoltage: 0x%x\n\r", supplyVoltage);
    }
    else {

        pCommand->cmd = AT91C_SEND_EXT_CSD_CMD;
        pCommand->resType = 1;

        pCommand->blockSize = SD_BLOCK_SIZE;
        pCommand->nbBlock = 512 / SD_BLOCK_SIZE;
        pCommand->pData = arg;

        pCommand->dataTran = 1;
        pCommand->isRead = 1;
        pCommand->tranType = MCI_NEW_TRANSFER;
    }
    pCommand->pResp = &response;

    // Send command
    error = SendCommand(pSd);

    if (sdCmd) {

        // Check result
        if (error == MCI_STATUS_NORESPONSE) {

            return SD_ERROR_NORESPONSE;
        }
        // SD_R7
        // Bit 0 - 7: check pattern (echo-back)
        // Bit 8 -11: voltage accepted
        else if (!error &&
                ((response & 0x00000FFF) == ((supplyVoltage << 8) | 0xAA))) {
            return 0;
        }
        else {
            return SD_ERROR_DRIVER;
        }
    }

    return error;
}

//------------------------------------------------------------------------------
/// Addressed card sends its card-specific
/// data (CSD) on the CMD line.
/// Returns the command transfer result (see SendCommand).
/// \param pSd  Pointer to a SD card driver instance.
//------------------------------------------------------------------------------
static unsigned char Cmd9(SdCard *pSd)
{
    SdCmd *pCommand = &(pSd->command);
    unsigned char error;

    TRACE_DEBUG("Cmd9()\n\r");
    ResetCommand(pCommand);
    // Fill command information
    pCommand->cmd = AT91C_SEND_CSD_CMD;
    pCommand->arg = pSd->cardAddress << 16;
    pCommand->resType = 2;
    pCommand->pResp = pSd->csd;

    // Send command
    error = SendCommand(pSd);
    return error;
}

//------------------------------------------------------------------------------
/// Forces the card to stop transmission
/// \param pSd      Pointer to a SD card driver instance.
/// \param stopRead Stop reading stream/writing stream.
/// \param pStatus  Pointer to a status variable.
//------------------------------------------------------------------------------
static unsigned char Cmd12(SdCard *pSd,
                           unsigned char stopRead,
                           unsigned int *pStatus)
{
    SdCmd *pCommand = &(pSd->command);
    unsigned char error;
    unsigned int response;

    TRACE_DEBUG("Cmd12()\n\r");
    ResetCommand(pCommand);
    // Fill command information
    pCommand->cmd = AT91C_STOP_TRANSMISSION_CMD;
    pCommand->isRead = stopRead;
    pCommand->tranType = MCI_STOP_TRANSFER;
    pCommand->resType = 1;
    pCommand->pResp = &response;

    // Send command
    error = SendCommand(pSd);
    if (pStatus) *pStatus = response;
    return error;
}

//------------------------------------------------------------------------------
/// Addressed card sends its status register.
/// Returns the command transfer result (see SendCommand).
/// \param pSd  Pointer to a SD card driver instance.
/// \param pStatus  Pointer to a status variable.
//------------------------------------------------------------------------------
static unsigned char Cmd13(SdCard *pSd, unsigned int *pStatus)
{
    SdCmd *pCommand = &(pSd->command);
    unsigned char error;

    TRACE_DEBUG("Cmd13()\n\r");
    ResetCommand(pCommand);
    // Fill command information
    pCommand->cmd = AT91C_SEND_STATUS_CMD;
    pCommand->arg = pSd->cardAddress << 16;
    pCommand->resType = 1;
    pCommand->pResp = pStatus;

    // Send command
    error = SendCommand(pSd);

    return error;
}

//------------------------------------------------------------------------------
/// In the case of a Standard Capacity SD Memory Card, this command sets the
/// block length (in bytes) for all following block commands
/// (read, write, lock).
/// Default block length is fixed to 512 Bytes.
/// Set length is valid for memory access commands only if partial block read
/// operation are allowed in CSD.
/// In the case of a High Capacity SD Memory Card, block length set by CMD16
/// command does not affect the memory read and write commands. Always 512
/// Bytes fixed block length is used. This command is effective for LOCK_UNLOCK
/// command. In both cases, if block length is set larger than 512Bytes, the
/// card sets the BLOCK_LEN_ERROR bit.
/// \param pSd  Pointer to a SD card driver instance.
/// \param blockLength  Block length in bytes.
//------------------------------------------------------------------------------
static unsigned char Cmd16(SdCard *pSd, unsigned short blockLength)
{
    SdCmd *pCommand = &(pSd->command);
    unsigned char error;
    unsigned int response;

    TRACE_DEBUG("Cmd16()\n\r");
    ResetCommand(pCommand);
    // Fill command information
    pCommand->cmd = AT91C_SET_BLOCKLEN_CMD;
    pCommand->arg = blockLength;
    pCommand->resType = 1;
    pCommand->pResp = &response;

    // Send command
    error = SendCommand(pSd);

    return error;
}

#ifdef SINGLE_READ
static unsigned char Cmd17(SdCard *pSd,
                           unsigned char  *pData,
                           unsigned int   address,
                           unsigned int   *pStatus)
{
    SdCmd *pCommand = &(pSd->command);
    unsigned char error;
    unsigned int response;

    TRACE_DEBUG("Cmd17()\n\r");
    ResetCommand(pCommand);
    // Fill command information
    pCommand->cmd = AT91C_READ_SINGLE_BLOCK_CMD;
    pCommand->arg = address;
    pCommand->resType = 1;
    pCommand->pResp = &response;

    pCommand->blockSize = SD_BLOCK_SIZE;
    pCommand->nbBlock = 1;
    pCommand->pData = pData;

    pCommand->dataTran = 1;
    pCommand->isRead = 1;
    pCommand->tranType = MCI_NEW_TRANSFER;

    // Send command
    error = SendCommand(pSd);

    if (pStatus) *pStatus = response;
    return error;
}
#endif

//------------------------------------------------------------------------------
/// Continously transfers datablocks from card to host until interrupted by a
/// STOP_TRANSMISSION command.
/// \param pSd        Pointer to a SD card driver instance.
/// \param blockSize  Block size (shall be set to 512 in case of high capacity).
/// \param pData      Pointer to the DW aligned buffer to be filled.
/// \param address    SD card address.
//------------------------------------------------------------------------------
static unsigned char Cmd18(SdCard *pSd,
                           unsigned short nbBlock,
                           unsigned char *pData,
                           unsigned int address,
                           unsigned int *pStatus)
{
    SdCmd *pCommand = &(pSd->command);
    unsigned char error;
    unsigned int response;

    TRACE_DEBUG("Cmd18()\n\r");
    ResetCommand(pCommand);
    // Fill command information
    pCommand->cmd = AT91C_READ_MULTIPLE_BLOCK_CMD;
    pCommand->arg = address;
    pCommand->resType = 1;
    pCommand->pResp = &response;

    pCommand->blockSize = SD_BLOCK_SIZE;
    pCommand->nbBlock = nbBlock;
    pCommand->pData = pData;

    pCommand->dataTran = 1;
    pCommand->isRead = 1;
    pCommand->tranType = MCI_NEW_TRANSFER;

    // Send command
    error = SendCommand(pSd);

    if (pStatus) *pStatus = response;

    return error;
}
#ifdef SINGLE_WRITE
static unsigned char Cmd24(SdCard *pSd,
                           unsigned char  *pData,
                           unsigned int   address,
                           unsigned int   *pStatus)
{
    SdCmd *pCommand = &(pSd->command);
    unsigned char error;
    unsigned int response;

    TRACE_DEBUG("Cmd24()\n\r");
    ResetCommand(pCommand);
    // Fill command information
    pCommand->cmd = AT91C_WRITE_BLOCK_CMD;
    pCommand->arg = address;
    pCommand->resType = 1;
    pCommand->pResp = &response;

    pCommand->blockSize = SD_BLOCK_SIZE;
    pCommand->nbBlock = 1;
    pCommand->pData = pData;

    pCommand->dataTran = 1;
    pCommand->isRead = 0;
    pCommand->tranType = MCI_NEW_TRANSFER;

    // Send command
    error = SendCommand(pSd);

    if (pStatus) *pStatus = response;
    return error;
}
#endif
//------------------------------------------------------------------------------
/// Write block command
/// \param pSd  Pointer to a SD card driver instance.
/// \param blockSize  Block size (shall be set to 512 in case of high capacity).
/// \param pData  Pointer to the DW aligned buffer to be filled.
/// \param address  SD card address.
//------------------------------------------------------------------------------
static unsigned char Cmd25(SdCard *pSd,
                           unsigned short nbBlock,
                           unsigned char *pData,
                           unsigned int address,
                           unsigned int *pStatus)
{
    SdCmd *pCommand = &(pSd->command);
    unsigned char error;
    unsigned int response;

    TRACE_DEBUG("Cmd25()\n\r");
    ResetCommand(pCommand);
    // Fill command information
    pCommand->cmd = AT91C_WRITE_MULTIPLE_BLOCK_CMD;
    pCommand->arg = address;
    pCommand->resType = 1;
    pCommand->pResp = &response;

    pCommand->blockSize = SD_BLOCK_SIZE;
    pCommand->nbBlock = nbBlock;
    pCommand->pData = pData;

    pCommand->dataTran = 1;
    pCommand->tranType = MCI_NEW_TRANSFER;

    // Send command
    error = SendCommand(pSd);
    if (pStatus) *pStatus = response;

    return error;
}

#if MCI_SDIO_ENABLE
//------------------------------------------------------------------------------
/// SDIO R/W Byte Direct, response R5
/// \param pSd Pointer to SdCard instance.
/// \param func Number of function.
/// \param rw   The direction of IO operation, 1 for write.
/// \param raw  Read after write
/// \param addr The register address to access.
/// \param pIoData Pointer to fill written data and response.
//------------------------------------------------------------------------------
static unsigned char Cmd52(SdCard *pSd,
                           unsigned char func,
                           unsigned char rw,
                           unsigned char raw,
                           unsigned int addr,
                           unsigned int *pIoData)
{
    SdCmd *pCommand = &(pSd->command);
    unsigned char error;
    unsigned int response;
    unsigned char byte = 0;

    TRACE_DEBUG("Cmd52()\n\r");
    ResetCommand(pCommand);
    // Fill command information
    pCommand->cmd = AT91C_SDIO_IO_RW_DIRECT;
    // - argument
    if (pIoData) byte = *pIoData;
    pCommand->arg = byte
                   | (addr << 9)    // register address 25: 9
                   | (raw  << 27)   // ReadAfterWrite   27
                   | (func << 28)   // FunctionNumber   30:28
                   | (rw << 31);    // R/W              31
    pCommand->resType = 5;
    pCommand->pResp = &response;
    // Send command
    error = SendCommand(pSd);
    if (pIoData) *pIoData = response;
    return error;
}

//------------------------------------------------------------------------------
/// SDIO R/W Extended, response R5
/// \param pSd Pointer to SdCard instance.
/// \param func Number of function.
/// \param rw   The direction of IO operation, 1 for write.
/// \param blockMode  R/O on a block basis
/// \param incAddress R/W to incrementing address (1) or fixed address (0)
/// \param addr The register address to access.
/// \param pIoData Pointer to fill written data and response.
/// \param size    Data size base on bytes or blocks depending on blockMode
/// \param pResp   Pointer to response buffer
//------------------------------------------------------------------------------
static unsigned char Cmd53(SdCard *pSd,
                           unsigned char func,
                           unsigned char rw,
                           unsigned char blockMode,
                           unsigned char incAddress,
                           unsigned int  addr,
                           unsigned char *pIoData,
                           unsigned short size,
                           unsigned int *pResp)
{
    SdCmd *pCommand = &(pSd->command);
    unsigned char error;

    TRACE_DEBUG("Cmd53()\n\r");
    ResetCommand(pCommand);
    // Fill command information
    pCommand->cmd = AT91C_SDIO_IO_RW_EXTENDED;
    // - argument
    pCommand->arg = size
                   | (addr << 9)        // register address 25: 9
                   | (incAddress << 26) // OP Code          26
                   | (blockMode << 27)  // ReadAfterWrite   27
                   | (func << 28)       // FunctionNumber   30:28
                   | (rw << 31);        // R/W              31
    pCommand->resType = 5;
    pCommand->pResp   = pResp;
    
    // - Write...
    if (rw) {}
    else {
        pCommand->cmd |= AT91C_MCI_TRDIR_READ;
        pCommand->isRead = 1;
    }
    // - Block...
    if (blockMode) {
        pCommand->cmd |= AT91C_MCI_TRTYP_SDIO_BLOCK
                       | AT91C_MCI_TRCMD_START;
        pCommand->blockSize = SD_BLOCK_SIZE;
    }
    else {
        pCommand->cmd |= AT91C_MCI_TRTYP_SDIO_BYTE
                       | AT91C_MCI_TRCMD_START;
        pCommand->blockSize = 1;
    }
    pCommand->nbBlock  = size;
    pCommand->pData    = pIoData;
    pCommand->dataTran = 1;
    pCommand->tranType = MCI_NEW_TRANSFER;

    // Send command
    error = SendCommand(pSd);
    return error;
}
#endif

//------------------------------------------------------------------------------
/// Initialization delay: The maximum of 1 msec, 74 clock cycles and supply
/// ramp up time.
/// Returns the command transfer result (see SendCommand).
/// \param pSd  Pointer to a SD card driver instance.
//------------------------------------------------------------------------------
static unsigned char Cmd55(SdCard *pSd)
{
    SdCmd *pCommand = &(pSd->command);
    unsigned char error;
    unsigned int response;

    TRACE_DEBUG("Cmd55()\n\r");
    ResetCommand(pCommand);
    // Fill command information
    pCommand->cmd = AT91C_APP_CMD;
    pCommand->arg = (pSd->cardAddress << 16);
    pCommand->resType = 1;
    pCommand->pResp = &response;

    // Send command
    error = SendCommand(pSd);

    return error;
}

/*
//------------------------------------------------------------------------------
/// SPI Mode, Reads the OCR register of a card
/// Returns the command transfer result (see SendCommand).
/// \param pSd  Pointer to a SD card driver instance.
/// \param pOcr   OCR value of the card
//------------------------------------------------------------------------------
static unsigned char Cmd58(SdCard *pSd, unsigned int *pOcr)
{
    SdCmd *pCommand = &(pSd->command);
    unsigned char error;
    unsigned int response[2];

    TRACE_DEBUG("Cmd58()\n\r");
    ResetCommand(pCommand);
    // Fill command information
    pCommand->cmd = AT91C_READ_OCR_CMD;
    pCommand->resType = 3;
    pCommand->pResp = &response[0];

    // Send command
    error = SendCommand(pSd);
    return error;
}

//------------------------------------------------------------------------------
/// SPI Mode, Set CRC option of a card
/// Returns the command transfer result (see SendCommand).
/// \param pSd  Pointer to a SD card driver instance.
/// \param option  CRC option, 1 to turn on, 0 to trun off
//------------------------------------------------------------------------------
static unsigned char Cmd59(SdCard *pSd, unsigned char option)
{
    SdCmd *pCommand = &(pSd->command);
    unsigned char error;
    unsigned int response;

    TRACE_DEBUG("Cmd59()\n\r");
    ResetCommand(pCommand);
    // Fill command information
    pCommand->cmd = AT91C_CRC_ON_OFF_CMD;
    pCommand->arg = (option & 0x1);
    pCommand->resType = 1;
    pCommand->pResp = &response;

    // Send command
    error = SendCommand(pSd);

    return error;
}
*/

//------------------------------------------------------------------------------
/// Defines the data bus width (00=1bit or 10=4 bits bus) to be used for data
/// transfer.
/// The allowed data bus widths are given in SCR register.
/// \param pSd  Pointer to a SD card driver instance.
/// \param busWidth  Bus width in bits.
/// \return the command transfer result (see SendCommand).
//------------------------------------------------------------------------------
static unsigned char Acmd6(SdCard *pSd, unsigned char busWidth)
{
    SdCmd *pCommand = &(pSd->command);
    unsigned char error;
    unsigned int response;

    TRACE_DEBUG("Acmd6()\n\r");

    error = Cmd55(pSd);
    if (error) {
        TRACE_ERROR("Acmd6.Cmd55: %d\n\r", error);
        return error;
    }

    ResetCommand(pCommand);
    // Fill command information
    pCommand->cmd = AT91C_SD_SET_BUS_WIDTH_CMD;
    pCommand->arg = (busWidth == 4) ? SD_STAT_DATA_BUS_WIDTH_4BIT :
                                      SD_STAT_DATA_BUS_WIDTH_1BIT;
    pCommand->resType = 1;
    pCommand->pResp = &response;

    // Send command
    return SendCommand(pSd);
}

//------------------------------------------------------------------------------
/// The SD Status contains status bits that are related to the SD memory Card
/// proprietary features and may be used for future application-specific usage.
/// Can be sent to a card only in 'tran_state'.
//------------------------------------------------------------------------------
static unsigned char Acmd13(SdCard *pSd, unsigned int * pSdSTAT)
{
    SdCmd *pCommand = &(pSd->command);
    unsigned char error;
    unsigned int response[1];

    TRACE_DEBUG("Acmd13()\n\r");

    error = Cmd55(pSd);
    if (error) {
        TRACE_ERROR("Acmd13.Cmd55: %d\n\r", error);
        return error;
    }

    ResetCommand(pCommand);
    // Fill command information
    pCommand->cmd = AT91C_SD_STATUS_CMD;
    pCommand->resType = 1;
    pCommand->pResp = response;

    pCommand->blockSize = 512 / 8;
    pCommand->nbBlock = 1;
    pCommand->pData = (unsigned char*)pSdSTAT;

    pCommand->dataTran = 1;
    pCommand->isRead = 1;
    pCommand->tranType = MCI_NEW_TRANSFER;

    // Send command
    error = SendCommand(pSd);

    return error;
}

//------------------------------------------------------------------------------
/// Asks to all cards to send their operations conditions.
/// Returns the command transfer result (see SendCommand).
/// \param pSd  Pointer to a SD card driver instance.
/// \param hcs  Shall be true if Host support High capacity.
/// \param pCCS  Set the pointed flag to 1 if hcs != 0 and SD OCR CCS flag is set.
//------------------------------------------------------------------------------
static unsigned char Acmd41(SdCard *pSd, unsigned char hcs, unsigned char *pCCS)
{
    SdCmd *pCommand = &(pSd->command);
    unsigned char error;
    unsigned int  response;

    do {
        error = Cmd55(pSd);
        if (error) {
            return error;
        }

        ResetCommand(pCommand);
        // Fill command information
        pCommand->cmd = AT91C_SD_APP_OP_COND_CMD;
        pCommand->arg = AT91C_MMC_HOST_VOLTAGE_RANGE;
        if (hcs) {
            pCommand->arg |= AT91C_CCS;
        }

        pCommand->resType = 3;
        pCommand->pResp = &response;

        // Send command
        TRACE_DEBUG("Acmd41()\n\r");
        error = SendCommand(pSd);
        if (error) {
            return error;
        }
        *pCCS  = ((response & AT91C_CCS) != 0);
    }
    while ((response & AT91C_CARD_POWER_UP_BUSY) != AT91C_CARD_POWER_UP_BUSY);

    return 0;
}

//------------------------------------------------------------------------------
/// SD Card Configuration Register (SCR) provides information on the SD Memory
/// Card's special features that were configured into the given card. The size
/// of SCR register is 64 bits.
//------------------------------------------------------------------------------
static unsigned char Acmd51(SdCard *pSd, unsigned int * pSCR)
{
    SdCmd *pCommand = &(pSd->command);
    unsigned char error;
    unsigned int response[1];

    TRACE_DEBUG("Acmd51()\n\r");

    error = Cmd55(pSd);
    if (error) {
        TRACE_ERROR("Acmd51.Cmd55: %d\n\r", error);
        return error;
    }

    ResetCommand(pCommand);
    // Fill command information
    pCommand->cmd = AT91C_SD_SEND_SCR_CMD;
    pCommand->resType = 1;
    pCommand->pResp = response;

    pCommand->blockSize = 64 / 8;
    pCommand->nbBlock = 1;
    pCommand->pData = (unsigned char*)pSCR;

    pCommand->dataTran = 1;
    pCommand->isRead = 1;
    pCommand->tranType = MCI_NEW_TRANSFER;

    // Send command
    error = SendCommand(pSd);

    //if (!error) Int2MsbFirstStream((unsigned char*)pSCR, 8 / 4);

    return error;
}

#if defined(MCI2_INTERFACE) && defined(AT91C_MCI_SPCMD_BOOTREQ)
//------------------------------------------------------------------------------
/// Terminate boot stream.
/// \param pSd      Pointer to SdCard instance.
//------------------------------------------------------------------------------
static unsigned char BootEnd(SdCard *pSd)
{
    SdCmd * pCommand = &(pSd->command);

    TRACE_DEBUG("BootEnd()\n\r");
    ResetCommand(pCommand);

    // Send boot end
    pCommand->cmd = AT91C_BOOTEND;

    return SendCommand(pSd);
}

//------------------------------------------------------------------------------
/// In boot operation mode, the processor can read boot data from the slave,
/// by keeping the CMD line low after power-on before issuing CMD1.
/// BootEnd() must be invoked after the boot request done.
/// \param pSd      Pointer to SdCard instance.
/// \param pBuffer  The buffer holding received data.
/// \param length   The buffer length.
//------------------------------------------------------------------------------
static unsigned char BootREQ(SdCard *pSd,
                             unsigned char* pBuffer,
                             unsigned int   nbBlocks,
                             unsigned char  ackEnable)
{
    SdCmd * pCommand = &(pSd->command);
    unsigned char error;

    TRACE_DEBUG("BootREQ()\n\r");
    ResetCommand(pCommand);

    // Send boot request
    pCommand->cmd = ackEnable ? (AT91C_BOOTREQ | AT91C_MCI_BOOTACK)
                              :  AT91C_BOOTREQ;
    pCommand->blockSize = SD_BLOCK_SIZE;
    pCommand->nbBlock   = nbBlocks;
    pCommand->pData     = pBuffer;
    pCommand->isRead    = 1;
    pCommand->tranType = MCI_NEW_TRANSFER;

    error = SendCommand(pSd);
    if (error) {
        TRACE_ERROR("BootOperation.BootReq: %d\n\r", error);
        return error;
    }
    return error;
}
#endif

//------------------------------------------------------------------------------
/// Continue to transfer datablocks from card to host until interrupted by a
/// STOP_TRANSMISSION command.
/// \param pSd  Pointer to a SD card driver instance.
/// \param blockSize  Block size (shall be set to 512 in case of high capacity).
/// \param pData  Pointer to the application buffer to be filled.
/// \param address  SD card address.
//------------------------------------------------------------------------------
static unsigned char ContinuousRead(SdCard *pSd,
                                    unsigned short nbBlock,
                                    unsigned char *pData,
                                    SdCallback     pCb,
                                    void          *pArg)
{
    SdCmd *pCommand = &(pSd->command);

    TRACE_DEBUG("Read()\n\r");
    ResetCommand(pCommand);
    // Fill command information
    pCommand->blockSize = SD_BLOCK_SIZE;
    pCommand->nbBlock   = nbBlock;
    pCommand->pData     = pData;

    pCommand->dataTran = 1;
    pCommand->tranType = MCI_CONTINUE_TRANSFER;
    pCommand->isRead = 1;
    
    pCommand->callback = pCb;
    pCommand->pArg     = pArg;

    // Send command
    return SendCommand(pSd);
}

//------------------------------------------------------------------------------
/// Continue to transfer datablocks from host to card until interrupted by a
/// STOP_TRANSMISSION command.
/// \param pSd  Pointer to a SD card driver instance.
/// \param blockSize  Block size (shall be set to 512 in case of high capacity).
/// \param pData  Pointer to the application buffer to be filled.
//------------------------------------------------------------------------------
static unsigned char ContinuousWrite(SdCard *pSd,
                                     unsigned short nbBlock,
                                     const unsigned char *pData,
                                     SdCallback     pCb,
                                     void          *pArg)
{
    SdCmd *pCommand = &(pSd->command);

    TRACE_DEBUG("Write()\n\r");
    ResetCommand(pCommand);
    // Fill command information
    pCommand->blockSize = SD_BLOCK_SIZE;
    pCommand->nbBlock   = nbBlock;
    pCommand->pData     = (unsigned char*)pData;

    pCommand->dataTran = 1;
    pCommand->tranType = MCI_CONTINUE_TRANSFER;
    
    pCommand->callback = pCb;
    pCommand->pArg     = pArg;

    // Send command
    return SendCommand(pSd);
}

//------------------------------------------------------------------------------
/// Try SW Reset several times (CMD0 with ARG 0)
/// \param pSd      Pointer to a SD card driver instance.
/// \param retry    Retry times.
/// \return 0 or MCI error code.
//------------------------------------------------------------------------------
static unsigned char SwReset(SdCard *pSd, unsigned int retry)
{
    unsigned int i;
    unsigned char error = 0;

    for (i = 0; i < retry; i ++) {
        error = Cmd0(pSd, 0);
        if (error != MCI_STATUS_NORESPONSE)
            break;
    }
    return error;
}
/*
//------------------------------------------------------------------------------
/// Re-init card to trans state.
//------------------------------------------------------------------------------
static unsigned char ReInit(SdCard *pSd)
{
    #if 0
    unsigned char error;
    error = SwReset(pSd, 1);
    if (error) {
        TRACE_ERROR("ReInit.Cmd0: %d\n\r", error);
        return error;
    }
    error = Cmd1(pSd);
    if (error) {
        TRACE_ERROR("ReInit.Cmd1: %d\n\r", error);
        return error;
    }
    error = Cmd2(pSd);
    if (error) {
        TRACE_ERROR("ReInit.Cmd2: %d\n\r", error);
        return error;
    }
    error = Cmd3(pSd);
    if (error) {
        TRACE_ERROR("ReInit.Cmd3: %d\n\r", error);
        return error;
    }
    error = Cmd7(pSd, pSd->cardAddress);
    if (error) {
        TRACE_ERROR("ReInit.Cmd7: %d\n\r", error);
        return error;
    }
    #endif
    return 0;
}
*/
//------------------------------------------------------------------------------
/// Move SD card to transfer state.
//------------------------------------------------------------------------------
static unsigned char MoveToTranState(SdCard * pSd)
{
    unsigned char error;
    unsigned int  status;

    // Quit transfer state
    if((pSd->state == SD_STATE_READ)
    || (pSd->state == SD_STATE_WRITE)) {

        error = Cmd12(pSd,
                      (pSd->state == SD_STATE_READ),
                      &status);
        if (error) {
            TRACE_ERROR("MvToTran.Cmd12: %d\n\r", error);
            return error;
        }
    }

    // Put device into tran state
    error = Cmd13(pSd, &status);
    if (error) {
        TRACE_ERROR("MvToTran.Cmd13: %d\n\r", error);
        return error;
    }
    if ((status & STATUS_STATE) == STATUS_STBY) {
        error = Cmd7(pSd, pSd->cardAddress);
        if (error) {
            TRACE_ERROR("MvToTran.Cmd7: %d\n\r", error);
            return error;
        }
    }

    return 0;
}

#if defined(SINGLE_READ) || defined(SINGLE_WRITE)
static unsigned char PerformSingleTransfer(SdCard *pSd,
                                           unsigned int address,
                                           unsigned char *pData,
                                           unsigned char isRead)
{
    unsigned int status;
    unsigned char error = 0;

    /* Reset transfer state if previous in multi- mode */
    if(    (pSd->state == SD_STATE_READ)
        || (pSd->state == SD_STATE_WRITE)) {
        /* Stop transfer */
        error = Cmd12(pSd, (pSd->state == SD_STATE_READ), &status);
        if (error) {
            TRACE_ERROR("SingleTx.Cmd12: st%x, er%d\n\r", pSd->state, error);
        }
        pSd->state = SD_STATE_READY;
        pSd->preBlock = 0xFFFFFFFF;
    }

#ifdef SINGLE_READ
    if(isRead) {
        // Wait for card to be ready for data transfers
        do {
            error = Cmd13(pSd, &status);
            if (error) {
                TRACE_ERROR("SingleTx.RD.Cmd13: %d\n\r", error);
                return error;
            }
            if(  ((status & STATUS_STATE) == STATUS_IDLE)
               ||((status & STATUS_STATE) == STATUS_READY)
               ||((status & STATUS_STATE) == STATUS_IDENT)) {
                TRACE_ERROR("SingleTx.mode\n\r");
                return SD_ERROR_NOT_INITIALIZED;
            }
            // If the card is in sending data state or in receivce data state
            if (  ((status & STATUS_STATE) == STATUS_RCV)
                ||((status & STATUS_STATE) == STATUS_DATA) ){

                TRACE_DEBUG("SingleTx.state = 0x%X\n\r", (status & STATUS_STATE) >> 9);
            }
        }
        while (    ((status & STATUS_READY_FOR_DATA) == 0)
                || ((status & STATUS_STATE) != STATUS_TRAN) );
        ASSERT((status & STATUS_STATE) == STATUS_TRAN,
                "SD Card can't be configured in transfer state 0x%X\n\r",
                (status & STATUS_STATE)>>9);
        // Read data
        // Move to Sending data state
        error = Cmd17(pSd, pData, SD_ADDRESS(pSd,address), &status);
        if (error) {
            TRACE_ERROR("SingleTx.Cmd17: %d\n\r", error);
            return error;
        }
        if (status & ~(STATUS_READY_FOR_DATA | STATUS_STATE)) {
            TRACE_ERROR("CMD17.stat: %x\n\r",
                status & ~(STATUS_READY_FOR_DATA | STATUS_STATE));
            return SD_ERROR_DRIVER;
        }
        return error;
    }
#endif
#ifdef SINGLE_WRITE
    // Write
    {
        // Wait for card to be ready for data transfers
        do {
            error = Cmd13(pSd, &status);
            if (error) {
                TRACE_ERROR("SingleTx.WR.Cmd13: %d\n\r", error);
                return error;
            }
        }
        while ((status & STATUS_READY_FOR_DATA) == 0);
        // Move to Sending data state
        error = Cmd24(pSd, pData, SD_ADDRESS(pSd,address), &status);
        if (error) {
            TRACE_DEBUG("SingleTx.Cmd25: %d\n\r", error);
            return error;
        }
        if (status & (STATUS_WRITE & ~(STATUS_READY_FOR_DATA | STATUS_STATE))) {
            TRACE_ERROR("CMD24(0x%x).stat: %x\n\r",
                SD_ADDRESS(pSd,address), 
                status & (STATUS_WRITE
                            & ~(STATUS_READY_FOR_DATA | STATUS_STATE)));
            return SD_ERROR_DRIVER;
        }
    }
    return error;
#endif
}
#endif

//------------------------------------------------------------------------------
/// Move SD card to transfer state. The buffer size must be at
/// least 512 byte long. This function checks the SD card status register and
/// address the card if required before sending the transfer command.
/// Returns 0 if successful; otherwise returns an code describing the error.
/// \param pSd      Pointer to a SD card driver instance.
/// \param address  Address of the block to transfer.
/// \param nbBlocks Number of blocks to be transfer, 0 for infinite transfer.
/// \param pData    Data buffer whose size is at least the block size.
/// \param isRead   1 for read data and 0 for write data.
//------------------------------------------------------------------------------
static unsigned char MoveToTransferState(SdCard *pSd,
                                         unsigned int address,
                                         unsigned short nbBlocks,
                                         unsigned char *pData,
                                         unsigned char isRead)
{
    unsigned int status;
    unsigned char error;

    if(    (pSd->state == SD_STATE_READ)
        || (pSd->state == SD_STATE_WRITE)) {
#if 1//!defined(MCI2_INTERFACE)
        if (pSd->state == SD_STATE_WRITE) {
            DBGU_PutChar(0);
            DBGU_PutChar(0);
            DBGU_PutChar(0);
            DBGU_PutChar(0);
        }
#endif
        // RW MULTI with length
        error = Cmd12(pSd,
                      (pSd->state == SD_STATE_READ),
                      &status);
        if (error) {
            TRACE_ERROR("MTTranState.Cmd12: st%x, er%d\n\r", pSd->state, error);
            return error;
        }
#if !defined(MCI2_INTERFACE)
        // RW MULTI Infinite
        if (pSd->state == SD_STATE_WRITE) {
            while(MCI_CheckBusy((Mci *)pSd->pSdDriver) != 0);
        }
#endif
    }

    if(isRead) {
        // Wait for card to be ready for data transfers
        do {
            error = Cmd13(pSd, &status);
            if (error) {
                TRACE_ERROR("MTTranState.RD.Cmd13: %d\n\r", error);
                return error;
            }
            if(  ((status & STATUS_STATE) == STATUS_IDLE)
               ||((status & STATUS_STATE) == STATUS_READY)
               ||((status & STATUS_STATE) == STATUS_IDENT)) {
                TRACE_ERROR("Pb Card Identification mode\n\r");
                return SD_ERROR_NOT_INITIALIZED;
            }
            // If the card is in sending data state or in receivce data state
            if (  ((status & STATUS_STATE) == STATUS_RCV)
                ||((status & STATUS_STATE) == STATUS_DATA) ){

                TRACE_DEBUG("state = 0x%X\n\r", (status & STATUS_STATE) >> 9);
            }
        }
        while (    ((status & STATUS_READY_FOR_DATA) == 0)
                || ((status & STATUS_STATE) != STATUS_TRAN) );
        ASSERT((status & STATUS_STATE) == STATUS_TRAN,
                "SD Card can't be configured in transfer state 0x%X\n\r",
                (status & STATUS_STATE)>>9);
        // Read data
        // Move to Sending data state
        error = Cmd18(pSd, nbBlocks, pData, SD_ADDRESS(pSd,address), &status);
        if (error) {
            TRACE_ERROR("MTTranState.Cmd18: %d\n\r", error);
            return error;
        }
        if (status & ~(STATUS_READY_FOR_DATA | STATUS_STATE)) {
            TRACE_ERROR("CMD18.stat: %x\n\r",
                status & ~(STATUS_READY_FOR_DATA | STATUS_STATE));
            return SD_ERROR_DRIVER;
        }
    }
    else {
        // Wait for card to be ready for data transfers
        do {
            error = Cmd13(pSd, &status);
            if (error) {
                TRACE_ERROR("MoveToTransferState.WR.Cmd13: %d\n\r", error);
                return error;
            }
        }
        while ((status & STATUS_READY_FOR_DATA) == 0);
        // Move to Sending data state
        error = Cmd25(pSd, nbBlocks, pData, SD_ADDRESS(pSd,address), &status);
        if (error) {
            TRACE_DEBUG("MoveToTransferState.Cmd25: %d\n\r", error);
            return error;
        }
        if (status & (STATUS_WRITE & ~(STATUS_READY_FOR_DATA | STATUS_STATE))) {
            TRACE_ERROR("CMD25(0x%x, %d).stat: %x\n\r",
                SD_ADDRESS(pSd,address), nbBlocks,
                status & (STATUS_WRITE
                            & ~(STATUS_READY_FOR_DATA | STATUS_STATE)));
            return SD_ERROR_DRIVER;
        }
    }

    if (!error) pSd->preBlock = address + (nbBlocks-1);
    return error;
}

//------------------------------------------------------------------------------
/// Switch the bus width of card
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
/// Switch the HS mode of card
/// \param pSd      Pointer to SdCard instance.
/// \param hsEnable 1 to enable, 0 to disable.
//------------------------------------------------------------------------------
static unsigned char SdMmcSwitchHsMode(SdCard *pSd, unsigned char hsEnable)
{
    unsigned int status;
    unsigned char error = SD_ERROR_DRIVER;
    if (pSd->mode == hsEnable)
        return 0;
    if (pSd->cardType >= CARD_MMC) {
        MmcCmd6Arg cmd6Arg;
        cmd6Arg.access = 0x3;
        cmd6Arg.index  = SD_EXTCSD_HS_TIMING_INDEX;
        cmd6Arg.value  = hsEnable ? SD_EXTCSD_HS_TIMING_ENABLE
                                  : SD_EXTCSD_HS_TIMING_DISABLE;
        cmd6Arg.cmdSet = 0;
        error = Cmd6(pSd, &cmd6Arg, 0, &status);
        if (error) {
            TRACE_ERROR("MMC SwitchHs.Cmd6: %d\n\r", error);
        }
        else if (status & STATUS_SWITCH_ERROR) {
            TRACE_WARNING("MMC HS SW Fail\n\r");
            error = SD_ERROR_DRIVER;
        }
        else {
            TRACE_WARNING_WP("-I- MMC HS %d\n\r", hsEnable);
            pSd->mode = hsEnable;
        }
    }
    else if (pSd->cardType >= CARD_SD) {
        SdCmd6Arg cmd6Arg;
        unsigned int switchStatus[512/32];
        cmd6Arg.mode = 1;
        cmd6Arg.reserved = 0;
        cmd6Arg.reserveFG6 = 0xF;
        cmd6Arg.reserveFG5 = 0xF;
        cmd6Arg.reserveFG4 = 0xF;
        cmd6Arg.reserveFG3 = 0xF;
        cmd6Arg.command = 0;
        cmd6Arg.accessMode = 1;
        error = Cmd6(pSd,
                     &cmd6Arg,
                     switchStatus,
                     &status);
      #if 0
        unsigned int i;
        printf("SD Switch status:");
        for(i = 0; i < 512 / 8; i ++) {
            if ((i % 8) == 0) printf("\n\r[%3d]", i);
            printf(" %02x", ((char*)switchStatus)[i]);
        }
        printf("\n\r");
        printf(" _FG1_INFO %x\n\r",
            SD_SW_STAT_FUN_GRP1_INFO(switchStatus));
        printf(" _FG1_RC   %x\n\r",
            SD_SW_STAT_FUN_GRP1_RC(switchStatus));
        printf(" _FG1_BUSY %x\n\r",
            SD_SW_STAT_FUN_GRP1_BUSY(switchStatus));
        printf(" _FG1_DS_V %x\n\r",
            SD_SW_STAT_DATA_STRUCT_VER(switchStatus));
      #endif
        if (error) {
            TRACE_ERROR("SD SwitchHs.Cmd6: %d\n\r", error);
        }
        else if (status & STATUS_SWITCH_ERROR) {
            TRACE_WARNING("SD HS SW Fail\n\r");
            error = SD_ERROR_DRIVER;
        }
        else if (SD_SW_STAT_FUN_GRP1_RC(switchStatus)
                        == SD_SW_STAT_FUN_GRP_RC_ERROR) {
            TRACE_ERROR_WP("-I- SD HS Not Supported\n\r");
            error = SD_ERROR_DRIVER;
        }
        else if (SD_SW_STAT_FUN_GRP1_BUSY(switchStatus)) {
            TRACE_WARNING("SD HS Busy\n\r");
            error = SD_ERROR_DRIVER;
        }
        else {
            TRACE_WARNING_WP("-I- SD HS %d\n\r", hsEnable);
            pSd->mode = hsEnable;
        }
    }

    return error;
}

#if defined(MCI2_INTERFACE) && defined(AT91C_MCI_SPCMD_BOOTREQ)
//------------------------------------------------------------------------------
/// Process a list of SWITCH command
/// \param  pSd      Pointer to SdCard instance.
/// \param  pArgList Argument list.
/// \param  listSize Number of arguments listed.
/// \return 0, or error code and argument index.
//------------------------------------------------------------------------------
static unsigned short MmcSwitchSettings(SdCard *pSd,
                                       const MmcCmd6Arg * pArgList,
                                       unsigned int listSize,
                                       unsigned int * pErrSta)
{
    unsigned int i, status;
    unsigned char error;

    SANITY_CHECK(pSd);
    SANITY_CHECK(pArgList);

    for (i = 0; i < listSize; i ++) {
        error = Cmd6(pSd, &pArgList[i], 0, &status);
        if (pErrSta) *pErrSta = status;
        if (error) {
            return (error | (i << 8));
        }
        if (status & ~(STATUS_STATE | STATUS_READY_FOR_DATA)) {
            TRACE_WARNING("Error in SWITCH.%d, 0x%x\n\r",
                          pArgList[i].index, status);
        }
        else {
            TRACE_INFO("SWITCH.%d: 0x%x\n\r",
                       pArgList[i].index, status);
        }
    }
    return 0;
}
#endif

//------------------------------------------------------------------------------
/// Switch card state between STBY and TRAN
/// \param pSd      Pointer to a SD card driver instance.
/// \param address  Card address to TRAN, 0 to STBY
/// \param check    Whether to check the state
//------------------------------------------------------------------------------
static unsigned char MmcSelectCard(SdCard *pSd,
                                   unsigned short address,
                                   unsigned char check)
{
    unsigned char error;
    unsigned int  status;
    unsigned int  targetState = address ? STATUS_TRAN : STATUS_STBY;
    unsigned int  srcState    = address ? STATUS_STBY : STATUS_TRAN;
    if (pSd->cardType == CARD_SDIO) check = 0;

    // At this stage the Initialization and identification process is achieved
    // The SD card is supposed to be in Stand-by State
    while(check) {
        error = Cmd13(pSd, &status);
        if (error) {
            TRACE_ERROR("MmcSelectCard.Cmd13 (%d)\n\r", error);
            return error;
        }
        if ((status & STATUS_READY_FOR_DATA)) {
            unsigned int currState = status & STATUS_STATE;
            if (currState == targetState) return 0;
            if (currState != srcState) {
                TRACE_ERROR("MmcSelectCard, wrong state %x\n\r", currState);
                return SD_ERROR_DRIVER;
            }
            break;
        }
    }

    // witch to TRAN mode to Select the current SD/MMC
    // so that SD ACMD6 can process or EXT_CSD can read.
    error = Cmd7(pSd, address);
    if (error == SD_ERROR_NOT_INITIALIZED && address == 0) {}
    else if (error) {
        TRACE_ERROR("MmcSelectCard.Cmd7 (%d)\n\r", error);
    }

    return error;
}

//------------------------------------------------------------------------------
/// Get EXT_CSD information
/// \param pSd      Pointer to a SD card driver instance.
//------------------------------------------------------------------------------
static unsigned char MmcGetExtInformation(SdCard *pSd)
{
    unsigned char error;
    unsigned int i;

    // CSD 1.2 or Higher version
    if(SD_CSD_STRUCTURE(pSd) >= 2) {

        /* Clear EXT_CSD data */
        for (i = 0;i < 512/4; i ++) pSd->extData[i] = 0;
        error = Cmd8(pSd, 0, pSd->extData);
        if (error) {
            TRACE_ERROR("MmcGetExt.Cmd8: %d\n\r", error);
        }
    }
    return 0;
}

//------------------------------------------------------------------------------
/// Get SCR and SD Status information
/// \param pSd      Pointer to a SD card driver instance.
//------------------------------------------------------------------------------
static unsigned char SdGetExtInformation(SdCard *pSd)
{
    unsigned char error;

    // Reset data (64 + 512 bits, 8 + 64 bytes)
    // memset(pSd->extData, 0x00, 512);

    // SD Status
    if (pSd->optCmdBitMap & SD_ACMD13_SUPPORT) {
        error = Acmd13(pSd, &pSd->extData[SD_EXT_OFFSET_SD_STAT]);
        if (error) {
            TRACE_ERROR("SdGetExt.Acmd13: %d\n\r", error);
            pSd->optCmdBitMap &= ~SD_ACMD13_SUPPORT;
        }
    }

    // SD SCR
    error = Acmd51(pSd, &pSd->extData[SD_EXT_OFFSET_SD_SCR]);
    if (error) {
        TRACE_ERROR("SdGetExt.Acmd51: %d\n\r", error);
    }

    return 0;
}

//------------------------------------------------------------------------------
/// Update SD/MMC information.
/// Update CSD for card speed switch.
/// Update ExtDATA for any card function switch.
/// \param pSd      Pointer to a SD card driver instance.
/// \return error code when update CSD error.
//------------------------------------------------------------------------------
static unsigned char SdMmcUpdateInformation(SdCard *pSd,
                                            unsigned char csd,
                                            unsigned char extData)
{
    unsigned char error;

    // Update CSD for new TRAN_SPEED value
    if (csd) {
        MmcSelectCard(pSd, 0, 1);
        Delay(800);
        error = Cmd9(pSd);
        if (error ) {
            TRACE_ERROR("SdMmcUpdateInfo.Cmd9 (%d)\n\r", error);
            return error;
        }
        error = MmcSelectCard(pSd, pSd->cardAddress, 1);
    }
    if (pSd->cardType >= CARD_MMC)     MmcGetExtInformation(pSd);
    else if (pSd->cardType >= CARD_SD) SdGetExtInformation(pSd);
    GetTransSpeedValue(pSd);

    return 0;
}

#if MCI_SDIO_ENABLE
//------------------------------------------------------------------------------
/// Find ManfID, Func0 tuple.
//------------------------------------------------------------------------------
static unsigned char SdioFindTuples(SdCard * pSd,
                                    unsigned int address, unsigned int size,
                                    unsigned int *pAddrManfID,
                                    unsigned int *pAddrFunc0)
{
    unsigned char error, tmp[3];
    unsigned int addr = address;
    unsigned char nbFound = 0;
    for (;;) {
        error = SDIO_ReadDirect(pSd, 0, addr, tmp, 3);
        if (error)
            return error;
        // ManfID
        if (tmp[0] == CISTPL_MANFID) {
            if (pAddrManfID) *pAddrManfID = addr;
            nbFound ++;
        }
        // Func0
        if (tmp[0] == CISTPL_FUNCE && tmp[2] == 0x00) {
            if (pAddrFunc0) *pAddrFunc0 = addr;
            nbFound ++;
        }
        // END
        if (tmp[0] == CISTPL_END) break;

        // All found
        if (nbFound >= 2)         break;
        // Not tuple?
        if (tmp[1] == 0)          break;

        // Next address
        addr += (tmp[1] + 2);
        if (addr > (address + size))
            break;
    }
    return 0;
}
#endif

//------------------------------------------------------------------------------
//         Global functions
//------------------------------------------------------------------------------

#if MCI_SDIO_ENABLE
//------------------------------------------------------------------------------
/// Read at least one byte from SDIO card, using RW_DIRECT command.
/// \param pSd      Pointer to SdCard instance.
/// \param funNb    Function number.
/// \param address  First byte address of data in SDIO card.
/// \param pBytes   Pointer to data buffer.
/// \param size     Buffer size.
//------------------------------------------------------------------------------
unsigned char SDIO_ReadDirect(SdCard *pSd,
                              unsigned char funNb,
                              unsigned int  address,
                              unsigned char *pBytes,
                              unsigned int  size)
{
    unsigned char error;
    unsigned int status;
    if (pSd->cardType < CARD_SDIO) {
        return SD_ERROR_NOT_SUPPORT;
    }
    if (size == 0)
        return SD_ERROR_DRIVER;

    while(size --) {
        status = 0;
        error = Cmd52(pSd, funNb, 0, 0, address ++, &status);
        if (pBytes) *pBytes ++ = (unsigned char)status;
        if (error) {
            TRACE_ERROR("SDIO_ReadDirect.Cmd52: %d, %x\n\r", error, status);
            return SD_ERROR_DRIVER;
        }
    }

    return 0;
}

//------------------------------------------------------------------------------
/// Write one byte to SDIO card, using RW_DIRECT command.
/// \param pSd      Pointer to SdCard instance.
/// \param funNb    Function number.
/// \param address  First byte address of data in SDIO card.
/// \param pBytes   Pointer to data buffer.
/// \param size     Buffer size.
//------------------------------------------------------------------------------
unsigned char SDIO_WriteDirect(SdCard *pSd,
                               unsigned char funNb,
                               unsigned int address,
                               unsigned char byte)
{
    if (pSd->cardType < CARD_SDIO) {
        return SD_ERROR_NOT_SUPPORT;
    }
    unsigned char error;
    unsigned int status;
    status = byte;
    error = Cmd52(pSd, funNb, 1, 0, address, &status);
    if (error) {
        TRACE_ERROR("SDIO_ReadDirect.Cmd52: %d, %x\n\r", error, status);
        return SD_ERROR_DRIVER;
    }

    return 0;
}

//------------------------------------------------------------------------------
/// Read byte by byte from SDIO card, using RW_EXT command.
/// \param pSd          Pointer to SdCard instance.
/// \param funNb        Function number.
/// \param address      First byte address of data in SDIO card.
/// \param isFixedAddr  Address not increased.
/// \param pBytes       Pointer to data buffer.
/// \param size         Buffer size.
//------------------------------------------------------------------------------
unsigned char SDIO_ReadBytes(SdCard *pSd,
                             unsigned char funNb,
                             unsigned int  address,
                             unsigned char isFixedAddr,
                             unsigned char *pBytes,
                             unsigned int   size)
{
    unsigned char error;
    unsigned int status;
    if (pSd->cardType < CARD_SDIO) {
        return SD_ERROR_NOT_SUPPORT;
    }

    if (size == 0)
        return SD_ERROR_DRIVER;

    error = Cmd53(pSd, funNb,
                  0, 0, !isFixedAddr,
                  address, pBytes, size, &status);
    if (error || (status & STATUS_SDIO_CMD52)) {
        TRACE_ERROR("SDIO_ReadBytes.Cmd53: %d, %x\n\r", error, status);
        return SD_ERROR_DRIVER;
    }

    return 0;
}

//------------------------------------------------------------------------------
/// Write byte by byte to SDIO card, using RW_EXT command.
/// \param pSd          Pointer to SdCard instance.
/// \param funNb        Function number.
/// \param address      First byte address of data in SDIO card.
/// \param isFixedAddr  Address not increased.
/// \param pBytes       Pointer to data buffer.
/// \param size         Buffer size.
//------------------------------------------------------------------------------
unsigned char SDIO_WriteBytes(SdCard *pSd,
                              unsigned char funNb,
                              unsigned int  address,
                              unsigned char isFixedAddr,
                              unsigned char *pBytes,
                              unsigned int   size)
{
    unsigned char error;
    unsigned int status;
    if (pSd->cardType < CARD_SDIO) {
        return SD_ERROR_NOT_SUPPORT;
    }
    if (size == 0)
        return SD_ERROR_DRIVER;

    error = Cmd53(pSd, funNb,
                  1, 0, !isFixedAddr,
                  address, pBytes, size, &status);
    if (error || (status & STATUS_SDIO_CMD52)) {
        TRACE_ERROR("SDIO_ReadBytes.Cmd53: %d, %x\n\r", error, status);
        return SD_ERROR_DRIVER;
    }

    return 0;
}
#endif

//------------------------------------------------------------------------------
/// Read Block of data in a buffer pointed by pData. The buffer size must be at
/// least 512 byte long. This function checks the SD card status register and
/// address the card if required before sending the read command.
/// Returns 0 if successful; otherwise returns an code describing the error.
/// \param pSd      Pointer to a SD card driver instance.
/// \param address  Address of the block to read.
/// \param pData    Data buffer whose size is at least the block size, it can
///            be 1,2 or 4-bytes aligned when used with DMA.
/// \param length   Number of blocks to be read.
/// \param pCallback Pointer to callback function that invoked when read done.
///                  0 to start a blocked read.
/// \param pArgs     Pointer to callback function arguments.
//------------------------------------------------------------------------------
unsigned char SD_Read(SdCard        *pSd,
                      unsigned int   address,
                      void          *pData,
                      unsigned short length,
                      SdCallback     pCallback,
                      void          *pArgs)
{
    unsigned char error;

    // If callback is defined, performe none blocked reading
    if (pCallback) {
        if (MCI_IsTxComplete((Mci *)pSd) == 0) {
            return SD_ERROR_BUSY;
        }
    }

    if (   pSd->state != SD_STATE_READ
        || pSd->preBlock + 1 != address ) {
        // Start infinite block reading
        error = MoveToTransferState(pSd, address, 0, 0, 1);
    }
    else    error = 0;
    if (!error) {
        pSd->state = SD_STATE_READ;
        pSd->preBlock = address + (length - 1);
        error = ContinuousRead(pSd,
                               length,
                               pData,
                               pCallback, pArgs);
    }
    TRACE_DEBUG("SDrd(%u,%u):%u\n\r", address, length, error);

    return 0;    
}

//------------------------------------------------------------------------------
/// Write Block of data in a buffer pointed by pData. The buffer size must be at
/// least 512 byte long. This function checks the SD card status register and
/// address the card if required before sending the read command.
/// Returns 0 if successful; otherwise returns an code describing the error.
/// \param pSd      Pointer to a SD card driver instance.
/// \param address  Address of the block to read.
/// \param pData    Data buffer whose size is at least the block size, it can
///            be 1,2 or 4-bytes aligned when used with DMA.
/// \param length   Number of blocks to be read.
/// \param pCallback Pointer to callback function that invoked when read done.
///                  0 to start a blocked read.
/// \param pArgs     Pointer to callback function arguments.
//------------------------------------------------------------------------------
unsigned char SD_Write(SdCard        *pSd,
                       unsigned int   address,
                       void          *pData,
                       unsigned short length,
                       SdCallback     pCallback,
                       void          *pArgs)
{
    unsigned char error;
    // If callback is defined, performe none blocked writing
    if (pCallback) {
        if (MCI_IsTxComplete((Mci *)pSd) == 0) {
            return SD_ERROR_BUSY;
        }
    }
    if (   pSd->state != SD_STATE_WRITE
        || pSd->preBlock + 1 != address ) {
        // Start infinite block writing
        error = MoveToTransferState(pSd, address, 0, 0, 0);
    }
    else    error = 0;
    if (!error) {
        pSd->state = SD_STATE_WRITE;
        error = ContinuousWrite(pSd,
                                length,
                                pData,
                                pCallback, pArgs);
        pSd->preBlock = address + (length - 1);
    }
    TRACE_DEBUG("SDwr(%u,%u):%u\n\r", address, length, error);
    
    return 0;
}

//------------------------------------------------------------------------------
/// Read Block of data in a buffer pointed by pData. The buffer size must be at
/// least 512 byte long. This function checks the SD card status register and
/// address the card if required before sending the read command.
/// Returns 0 if successful; otherwise returns an code describing the error.
/// \param pSd  Pointer to a SD card driver instance.
/// \param address  Address of the block to read.
/// \param nbBlocks Number of blocks to be read.
/// \param pData    Data buffer whose size is at least the block size, it can
///            be 1,2 or 4-bytes aligned when used with DMA.
//------------------------------------------------------------------------------
unsigned char SD_ReadBlock(SdCard *pSd,
                           unsigned int address,
                           unsigned short nbBlocks,
                           unsigned char *pData)
{
    unsigned char error = 0;

    SANITY_CHECK(pSd);
    SANITY_CHECK(pData);
    SANITY_CHECK(nbBlocks);

    TRACE_DEBUG("ReadBlk(%d,%d)\n\r", address, nbBlocks);
#if defined(SINGLE_READ)
    while(nbBlocks --) {
        error = PerformSingleTransfer(pSd, address, pData, 1);
        if (error)
            break;
        // SDHC
        if (pSd->totalSize == 0xFFFFFFFF) {
            address += 1;
            pData = &pData[512];
        }
        else {
            address += 1;
            pData = &pData[512];
        }
    }
    return error;
#endif
#if !defined(MCI2_INTERFACE)
  #if !defined(AT91C_MCI_RDPROOF)
    error = MoveToTransferState(pSd, address, nbBlocks, pData, 1);
    pSd->state = SD_STATE_READ;
  #else
    if((pSd->state == SD_STATE_READ)
        && ((pSd->preBlock + 1) == address)) {

      #if defined(at91rm9200)
        error = Cmd12(pSd, 0);
        if (error) {
            return error;
        }
      #else
        TRACE_DEBUG("SD_ReadBlock:ContinuousRead\n\r");
        error = ContinuousRead(pSd,
                               nbBlocks,
                               pData,
                               0, 0);
        pSd->preBlock = address + (nbBlocks-1);
      #endif
    }
    else {
        error = MoveToTransferState(pSd, address, nbBlocks, pData, 1);
        pSd->state = SD_STATE_READ;
    }
  #endif
#else
    if (   pSd->state != SD_STATE_READ
        || pSd->preBlock + 1 != address ) {
        // Start infinite block reading
        error = MoveToTransferState(pSd, address, 0, 0, 1);
    }
    if (!error) {
        pSd->state = SD_STATE_READ;
        error = ContinuousRead(pSd,
                               nbBlocks,
                               pData,
                               0, 0);
        if (!error) pSd->preBlock = address + (nbBlocks - 1);
    }
#endif
    return error;
}

//------------------------------------------------------------------------------
/// Write Block of data pointed by pData. The buffer size must be at
/// least 512 byte long. This function checks the SD card status register and
/// address the card if required before sending the read command.
/// Returns 0 if successful; otherwise returns an SD_ERROR code.
/// \param pSd  Pointer to a SD card driver instance.
/// \param address  Address of block to write.
/// \param nbBlocks Number of blocks to be read
/// \param pData    Data buffer whose size is at least the block size, it can
///            be 1,2 or 4-bytes aligned when used with DMA.
//------------------------------------------------------------------------------
unsigned char SD_WriteBlock(SdCard *pSd,
                            unsigned int address,
                            unsigned short nbBlocks,
                            const unsigned char *pData)
{
    unsigned char error = 0;

    SANITY_CHECK(pSd);
    SANITY_CHECK(pData);
    SANITY_CHECK(nbBlocks);

    TRACE_DEBUG("WriteBlk(%d,%d)\n\r", address, nbBlocks);

#if defined(SINGLE_WRITE)
    unsigned char *pB = (unsigned char*)pData;
    while(nbBlocks --) {
        error = PerformSingleTransfer(pSd, address, pB, 0);
        if (error)
            break;
        // SDHC
        if (pSd->totalSize == 0xFFFFFFFF) {
            address += 1;
            pB = &pB[512];
        }
        else {
            address += 1;
            pB = &pB[512];
        }
    }
    return error;
#endif
#if !defined(MCI2_INTERFACE)
  #if !defined(AT91C_MCI_WRPROOF)
    error = MoveToTransferState(pSd, address, nbBlocks,
                                (unsigned char *)pData, 0);
    pSd->state = SD_STATE_WRITE;
  #else
    if((pSd->state == SD_STATE_WRITE)
        && ((pSd->preBlock + 1) == address)) {

        TRACE_DEBUG("SD_WriteBlock:ContinuousWrite\n\r");
        error = ContinuousWrite(pSd,
                                nbBlocks,
                                pData,
                                0, 0);
        pSd->preBlock = address + (nbBlocks-1);
    }
    else {

        //TRACE_FATAL("SD_WriteBlock:MoveToTransferState\n\r");
        error = MoveToTransferState(pSd, address, nbBlocks,
                                    (unsigned char *)pData, 0);
        pSd->state = SD_STATE_WRITE;
    }
  #endif
#else
    if (   pSd->state != SD_STATE_WRITE
        || pSd->preBlock + 1 != address ) {
        // Start infinite block writing
        error = MoveToTransferState(pSd, address, 0, 0, 0);
    }
    if (!error) {
        pSd->state = SD_STATE_WRITE;
        error = ContinuousWrite(pSd,
                                nbBlocks,
                                pData,
                                0, 0);
        if (!error) pSd->preBlock = address + (nbBlocks - 1);
    }
#endif

    return error;
}

//------------------------------------------------------------------------------
/// Run the SDcard SD/MMC/SDIO Mode initialization sequence.
/// This function resets both IO and memory controller, runs the initialisation
/// procedure and the identification process. Then it leaves the card in ready
/// state. The following command must check the card type and continue to put
/// the card into tran(for memory card) or cmd(for io card) state for data
/// exchange.
/// Returns 0 if successful; otherwise returns an SD_ERROR code.
/// \param pSd  Pointer to a SD card driver instance.
//------------------------------------------------------------------------------
static unsigned char SdMmcIdentify(SdCard *pSd)
{
    unsigned char mem = 0, io = 0, f8 = 0, mp = 1, ccs = 0;
    unsigned char error = 0;
#if MCI_SDIO_ENABLE
    unsigned int  status;
#endif

    // Reset HC to default HS and BusMode
    MCI_EnableHsMode(pSd->pSdDriver, 0);
    MCI_SetBusWidth(pSd->pSdDriver, MCI_SDCBUS_1BIT);

#if MCI_SDIO_ENABLE
    // Reset SDIO
    // CMD52, write 1 to RES bit in the CCCR (bit 3 of register 6)
    status = (0x1 << 3);
    error = Cmd52(pSd, 0, 1, 0, 6, &status);
    if (!error && ((status & STATUS_SDIO_CMD52) == 0)) {}
    else if (error == MCI_STATUS_NORESPONSE) {}
    else {
        TRACE_DEBUG("SdMmcIdentify.Cmd52 fail: %d, %x\n\r", error, status);
    }
#endif

    // Reset MEM
    error = SwReset(pSd, 1);
    if (error) {
        TRACE_DEBUG("SdMmcIdentify.SwReset: %d\n\r", error)
    }

    // CMD8 is newly added in the Physical Layer Specification Version 2.00 to
    // support multiple voltage ranges and used to check whether the card
    // supports supplied voltage. The version 2.00 host shall issue CMD8 and
    // verify voltage before card initialization.
    // The host that does not support CMD8 shall supply high voltage range...
    error = Cmd8(pSd, 1, (void*)1);
    if (error == 0) {
        f8 = 1;
    }
    else if (error != SD_ERROR_NORESPONSE) {
        TRACE_ERROR("SdMmcIdentify.Cmd8: %d\n\r", error);
        return SD_ERROR_DRIVER;
    }
    else {
        // Delay after "no response"
        Delay(800);
    }

#if MCI_SDIO_ENABLE
    // CMD5 is added for SDIO OCR check
    status = 0;
    error = Cmd5(pSd, &status);
    if (error) {
        TRACE_WARNING("SdMmcIdentify.Cmd5: %d\n\r", error);
    }
    // SDIO or SD COMBO: FN > 0
    else if ((status & AT91C_SDIO_NF) > 0) {
        // Set New Voltage
        unsigned int   cmd5Retries = 10000;
        do {
            status &= AT91C_MMC_HOST_VOLTAGE_RANGE;
            error = Cmd5(pSd, &status);
            if (status & AT91C_CARD_POWER_UP_BUSY)
                break;
        } while(!error && cmd5Retries --);
        if (error) {
            TRACE_ERROR("SdMmcIdentify.Cmd5 V: %d\n\r", error);
            return SD_ERROR_DRIVER;
        }
        TRACE_INFO("SDIO\n\r");
        io = 1;
        // SDIO only?
        if ((status & AT91C_SDIO_MP) == 0) mp = 0;
    }
#endif
    // SD or MMC or COMBO: mp is 1
    if (mp) {
        // Try SD memory initialize
        error = Acmd41(pSd, f8, &ccs);
        if (error) {
            unsigned int   cmd1Retries = 10000;
            TRACE_DEBUG("SdMmcIdentify.Acmd41: %d, try MMC\n\r", error);

            // Try MMC initialize
            error = SwReset(pSd, 10);
            if (error) {
                TRACE_ERROR("SdMmcIdentify.Mmc.SwReset: %d\n\r", error);
                return SD_ERROR_DRIVER;
            }
            // - Set Voltage
            do {
                error = Cmd1(pSd, 1, &ccs);
            }
            while ((error) && (cmd1Retries-- > 0));
            if (error) {
                TRACE_ERROR("SdMmcIdentify.Cmd1: %d\n\r", error);
                return SD_ERROR_DRIVER;
            }
            else if (ccs) {
                pSd->cardType = CARD_MMCHD;
            }
            else {
                pSd->cardType = CARD_MMC;
            }

            // MMC Identified OK
            return 0;
        }
        else if (ccs) {
            TRACE_INFO("SDHC MEM\n\r");
        }
        else {
            TRACE_INFO("SD MEM\n\r");
        }
        mem = 1;
    }

    // SD(IO)+MEM ?
    if (!mem) {
        // SDIO only
        if (io) {
            pSd->cardType = CARD_SDIO;
            return 0;
        }
    }
    // SD COMBO, continue with memory initialize
    else if (io) {
        if (ccs) pSd->cardType = CARD_SDHCCOMBO;
        else     pSd->cardType = CARD_SDCOMBO;
    }
    // SD(HC), continue with memory initialize
    else {
        if (ccs) pSd->cardType = CARD_SDHC;
        else     pSd->cardType = CARD_SD;
    }
    return 0;
}

//------------------------------------------------------------------------------
/// Run the SDcard SD Mode enumeration sequence. This function runs after the
/// initialisation procedure and the identification process. It sets the
/// SD card in transfer state to set the block length and the bus width.
/// Returns 0 if successful; otherwise returns an SD_ERROR code.
/// \param pSd  Pointer to a SD card driver instance.
//------------------------------------------------------------------------------
static unsigned char SdMmcEnum(SdCard *pSd)
{
    unsigned char mem = 0, io = 0;
    unsigned int   status;
    unsigned short error;
    unsigned char  isHsSupport = 0;
    unsigned char  updateInformation = 0;

    if (pSd->cardType & CARD_TYPE_bmSDMMC) mem = 1;
    if (pSd->cardType & CARD_TYPE_bmSDIO)  io = 1;

    // For MEM
    // The host then issues the command ALL_SEND_CID (CMD2) to the card to get
    // its unique card identification (CID) number.
    // Card that is unidentified (i.e. which is in Ready State) sends its CID
    // number as the response (on the CMD line).
    if (mem) {
        error = Cmd2(pSd);
        if (error) {
            TRACE_ERROR("SdMmcEnum.Cmd2: %d\n\r", error);
            return SD_ERROR_DRIVER;
        }
    }

    // For SDIO & MEM
    // Thereafter, the host issues CMD3 (SEND_RELATIVE_ADDR) asks the
    // card to publish a new relative card address (RCA), which is shorter than
    // CID and which is used to address the card in the future data transfer
    // mode. Once the RCA is received the card state changes to the Stand-by
    // State. At this point, if the host wants to assign another RCA number, it
    // can ask the card to publish a new number by sending another CMD3 command
    // to the card. The last published RCA is the actual RCA number of the card.
    error = Cmd3(pSd);
    if (error) {
        TRACE_ERROR("SdMmcInit.Cmd3 %d\n\r", error);
        return SD_ERROR_DRIVER;
    }

    // For MEM
    // SEND_CSD (CMD9) to obtain the Card Specific Data (CSD register),
    // e.g. block length, card storage capacity, etc...
    if (mem) {
        error = Cmd9(pSd);
        if (error) {
            TRACE_ERROR("SdMmcInit.Cmd9 %d\n\r", error);
            return SD_ERROR_DRIVER;
        }
    }

    // For SDIO & MEM
    // Now select the card, to TRAN state
    error = MmcSelectCard(pSd, pSd->cardAddress, 0);
    if (error) {
        TRACE_ERROR("SdMmcInit.Sel %d\n\r", error);
        return SD_ERROR_DRIVER;
    }
    // SDIO only card, enumeration done
    if (!mem && io) {
        // Default tranSpeed: 25MHz
        pSd->transSpeed = 25000000;
        return 0;
    }

    // For MEM cards or combo
    // If the card support EXT_CSD, read it!
    TRACE_INFO("Card Type %d, CSD_STRUCTURE %d\n\r",
               pSd->cardType, SD_CSD_STRUCTURE(pSd));

    // Get extended information of the card
    SdMmcUpdateInformation(pSd, 0, 0);

    // Advanced settings for HD & HS card
    if (pSd->cardType >= CARD_MMC){

        MmcCmd6Arg cmd6Arg;

        // MMC4 or later
        if (SD_CSD_SPEC_VERS(pSd) >= 4) {

            unsigned char busWidth, widthMode;

            // Calculate MMC busWidth (limited by slot information)
            switch (pSd->pSdDriver->mciMode & AT91C_MCI_SCDBUS) {
              #if defined(AT91C_MCI_SCDBUS_8BITS)
                case AT91C_MCI_SCDBUS_8BITS:
                    busWidth = 8;
                    widthMode = MCI_SDCBUS_8BIT;
                    break;
              #endif

              #if defined(AT91C_MCI_SCDBUS_4BITS)
                case AT91C_MCI_SCDBUS_4BITS:
                    busWidth = 4;
                    widthMode = MCI_SDCBUS_4BIT;
                    break;
              #endif

                default:
                    busWidth = 1;
                    widthMode = MCI_SDCBUS_1BIT;
            }

            // Switch to max bus width (4 now)
            cmd6Arg.access = 0x1;
            cmd6Arg.index  = SD_EXTCSD_BUS_WIDTH_INDEX;
            cmd6Arg.value  = SD_EXTCSD_BUS_WIDTH_4BIT;
            cmd6Arg.cmdSet = 0;
            error = Cmd6(pSd, &cmd6Arg, 0, &status);
            if (!error) {
                
              TRACE_WARNING_WP("-I- MMC %d-BIT BUS\n\r", busWidth);
              if (status
                  & (STATUS_MMC_SWITCH
                     & ~(STATUS_STATE | STATUS_READY_FOR_DATA))) {
                  printf("-E- Status %x\n\r", status);
              }
              else {
                  MCI_SetBusWidth(pSd->pSdDriver, widthMode);
                  updateInformation = 1;
              }
            }
            else {
                TRACE_WARNING("MMC %d-BIT not supported\n\r", busWidth)
            }
        }
        
        // CARD_TYPE 3
        if (SD_CSD_STRUCTURE(pSd) >= 2
            && (SD_EXTCSD_CARD_TYPE(pSd) & 0x2)) {

            #if !defined(OP_BOOTSTRAP_MCI_on)
            // Switch to HS mode
            if (gSdmmcAutoHsEnable) {
                cmd6Arg.access = 0x3;
                cmd6Arg.index  = SD_EXTCSD_HS_TIMING_INDEX;
                cmd6Arg.value  = SD_EXTCSD_HS_TIMING_ENABLE;
                cmd6Arg.cmdSet = 0;
                error = Cmd6(pSd, &cmd6Arg, 0, &status);
                if (error
                    || (status
                        & (STATUS_MMC_SWITCH
                            & ~(STATUS_STATE | STATUS_READY_FOR_DATA)))) {
                    TRACE_WARNING("MMC HS Fail, st %x\n\r", status);
                }
                else {
                    MCI_EnableHsMode(pSd->pSdDriver, 1);
                    TRACE_WARNING_WP("-I- MMC HS Enabled\n\r");
                    isHsSupport = 1;
                    updateInformation = 1;
                }
            }
            #endif // end of OP_BOOTSTRAP_MCI_on
        }
    }
    else if (pSd->cardType >= CARD_SD) {
      #if 1
        // Switch to 4-bits bus width
        // (All SD Card shall support 1-bit, 4 bitswidth)
        error = Acmd6(pSd, 4);
        TRACE_WARNING_WP("-I- SD 4-BITS BUS\n\r");
        if (error) {
            TRACE_ERROR("SdMmcInit.12 (%d)\n\r", error);
            return error;
        }
        MCI_SetBusWidth(pSd->pSdDriver, MCI_SDCBUS_4BIT);

        #if !defined(OP_BOOTSTRAP_MCI_on)
        // SD Spec V1.10 or higher, switch to high-speed mode
        if (gSdmmcAutoHsEnable) {
            if (SD_SCR_SD_SPEC(pSd) >= SD_SCR_SD_SPEC_1_10) {
                SdCmd6Arg cmd6Arg;
                unsigned int switchStatus[512/32];
                cmd6Arg.mode = 1;
                cmd6Arg.reserved = 0;
                cmd6Arg.reserveFG6 = 0xF;
                cmd6Arg.reserveFG5 = 0xF;
                cmd6Arg.reserveFG4 = 0xF;
                cmd6Arg.reserveFG3 = 0xF;
                cmd6Arg.command = 0;
                cmd6Arg.accessMode = 1;
                error = Cmd6(pSd,
                             &cmd6Arg,
                             switchStatus,
                             &status);
              #if 0
                unsigned int i;
                printf("SD Switch status:");
                for(i = 0; i < 512 / 8; i ++) {
                    if ((i % 8) == 0) printf("\n\r[%3d]", i);
                    printf(" %02x", ((char*)switchStatus)[i]);
                }
                printf("\n\r");
                printf(" _FG1_INFO %x\n\r",
                    SD_SW_STAT_FUN_GRP1_INFO(switchStatus));
                printf(" _FG1_RC   %x\n\r",
                    SD_SW_STAT_FUN_GRP1_RC(switchStatus));
                printf(" _FG1_BUSY %x\n\r",
                    SD_SW_STAT_FUN_GRP1_BUSY(switchStatus));
                printf(" _FG1_DS_V %x\n\r",
                    SD_SW_STAT_DATA_STRUCT_VER(switchStatus));
              #endif
                if (error || (status & STATUS_SWITCH_ERROR)) {
                    TRACE_WARNING("SD HS Fail\n\r");
                }
                else if (SD_SW_STAT_FUN_GRP1_RC(switchStatus)
                                == SD_SW_STAT_FUN_GRP_RC_ERROR) {
                    TRACE_ERROR_WP("-I- SD HS Not Supported\n\r");
                }
                else if (SD_SW_STAT_FUN_GRP1_BUSY(switchStatus)) {
                    TRACE_WARNING("SD HS Busy\n\r")
                }
                else {
                    MCI_EnableHsMode(pSd->pSdDriver, 1);
                    TRACE_WARNING_WP("-I- SD HS Enable\n\r");
                    isHsSupport = 1;
                }
            }
        }
        #endif
        // Update
        updateInformation = 1;
      #endif
    }

    if (updateInformation) {

        SdMmcUpdateInformation(pSd, isHsSupport, 1);
    }
    return 0;
}

//------------------------------------------------------------------------------
/// Run the SDcard initialization sequence. This function runs the
/// initialisation procedure and the identification process, then it sets the
/// SD card in transfer state to set the block length and the bus width.
/// Returns 0 if successful; otherwise returns an SD_ERROR code.
/// \param pSd  Pointer to a SD card driver instance.
/// \param pSdDriver  Pointer to SD driver already initialized.
//------------------------------------------------------------------------------
unsigned char SD_Init(SdCard *pSd, SdDriver *pSdDriver)
{
    unsigned char error;

    //TRACE_DEBUG("SD_Init()\n\r");

    // Initialize SdCard structure
    pSd->pSdDriver = pSdDriver;
    pSd->cardAddress = 0;
    pSd->preBlock = 0xffffffff;
    pSd->state = SD_STATE_INIT;
    pSd->cardType = CARD_UNKNOWN;
    pSd->optCmdBitMap = 0xFFFFFFFF;
    pSd->mode = 0;
    ResetCommand(&pSd->command);

    // Initialization delay: The maximum of 1 msec, 74 clock cycles and supply
    // ramp up time. Supply ramp up time provides the time that the power is
    // built up to the operating level (the bus master supply voltage) and the
    // time to wait until the SD card can accept the first command.

    // Power On Init Special Command
    //TRACE_DEBUG("Pon()\n\r");
    error = Pon(pSd);
    if (error) {
        TRACE_ERROR("SD_Init.1 (%d)\n\r", error);
        return error;
    }
    // After power-on or CMD0, all cards?CMD lines are in input mode, waiting
    // for start bit of the next command.
    // The cards are initialized with a default relative card address
    // (RCA=0x0000) and with a default driver stage register setting
    // (lowest speed, highest driving current capability).
    error = SdMmcIdentify(pSd);
    if (error) {
        TRACE_ERROR("SD_Init.Identify\n\r");
        return error;
    }
    error = SdMmcEnum(pSd);
    if (error) {
        TRACE_ERROR("SD_Init.Enum\n\r");
        return error;
    }

    // In the case of a Standard Capacity SD Memory Card, this command sets the
    // block length (in bytes) for all following block commands
    // (read, write, lock).
    // Default block length is fixed to 512 Bytes.
    // Set length is valid for memory access commands only if partial block read
    // operation are allowed in CSD.
    // In the case of a High Capacity SD Memory Card, block length set by CMD16
    // command does not affect the memory read and write commands. Always 512
    // Bytes fixed block length is used. This command is effective for
    // LOCK_UNLOCK command.
    // In both cases, if block length is set larger than 512Bytes, the card sets
    // the BLOCK_LEN_ERROR bit.
    if (pSd->cardType == CARD_SD) {
        error = Cmd16(pSd, SD_BLOCK_SIZE);
        if (error) {
            pSd->optCmdBitMap &= ~SD_CMD16_SUPPORT;
            TRACE_INFO("SD_Init.Cmd16 (%d)\n\r", error);
            TRACE_INFO("Fail to set BLK_LEN, default is 512\n\r");
        }
    }

    // Reset status for R/W
    pSd->state = SD_STATE_READY;

    // If SDIO Card
    if (pSd->cardType == CARD_SDIO) {
        pSd->blockNr = 0;
        pSd->totalSize = 0;
    }
    // If MMC Card & get size from EXT_CSD
    else if (pSd->cardType >= CARD_MMC && SD_CSD_C_SIZE(pSd) == 0xFFF) {
        pSd->blockNr = SD_EXTCSD_BLOCKNR(pSd);
        // Block number less than 0x100000000/512
        if (pSd->blockNr > 0x800000)
            pSd->totalSize = 0xFFFFFFFF;
        else
            pSd->totalSize = SD_EXTCSD_TOTAL_SIZE(pSd);
    }
    // If SD CSD v2.0
    else if(pSd->cardType >= CARD_SD
            && pSd->cardType < CARD_MMC
            && SD_CSD_STRUCTURE(pSd) >= 1) {
        pSd->blockNr   = SD_CSD_BLOCKNR_HC(pSd);
        pSd->totalSize = 0xFFFFFFFF;
    }
    // Normal card
    else {
        pSd->totalSize = SD_CSD_TOTAL_SIZE(pSd);
        pSd->blockNr = SD_CSD_BLOCKNR(pSd);
    }

    if (pSd->cardType == CARD_UNKNOWN) {
        return SD_ERROR_NOT_INITIALIZED;
    }
    else {
        return 0;
    }
}

//------------------------------------------------------------------------------
/// Stop the SDcard. This function stops all SD operations.
/// Returns 0 if successful; otherwise returns an SD_ERROR code.
/// \param pSd  Pointer to a SD card driver instance.
/// \param pSdDriver  Pointer to MCI driver already initialized.
//------------------------------------------------------------------------------
unsigned char SD_Stop(SdCard *pSd, SdDriver *pSdDriver)
{
    unsigned char error;
    SdCmd *pCommand = &(pSd->command);

    if (pSd == 0 || pSdDriver == 0)
        return 0;

    if(pCommand->tranType == MCI_CONTINUE_TRANSFER)
    {
        TRACE_DEBUG("SD_StopTransmission()\n\r");

        error = Cmd12(pSd, (pSd->state != SD_STATE_WRITE), 0);
        if(error) {
            return error;
        }
    }

    MCI_Close((Mci *)pSdDriver);
    return 0;
}

//------------------------------------------------------------------------------
/// Switch the SD/MMC card to High-Speed mode.
/// pSd->transSpeed will change to new speed limit.
/// Invoke MCI_SetSpeed() and MCI_EnableHsMode() to change MCI timing after.
/// For SD/MMC card, the speed mode will not change back until another init.
/// \param pSd      Pointer to a SD card driver instance.
/// \param hsMode   1 to enable HS mode, 0 to disable
///                 0xFF to return current mode.
/// \return current mode is hsMode is 0xFF;
///         error code if hsMode is 0 or 1.
//------------------------------------------------------------------------------
unsigned char SD_HighSpeedMode(SdCard *pSd,
                               unsigned char hsMode)
{
    unsigned char error = 0;

    if (hsMode == 0xFF)
        return pSd->mode;
    if (hsMode == 0) {
        TRACE_WARNING("Can not switch, do re-init to disable HS mode\n\r");
        return SD_ERROR_DRIVER;
    }

    // Quit transfer state
    error = MoveToTranState(pSd);
    if (error) {
        TRACE_ERROR("SD_HighSpeedMode.Tran: %d\n\r", error);
        return error;
    }

    if (pSd->mode != hsMode) {
        error = SdMmcSwitchHsMode(pSd, hsMode);
        if (error == 0)
            error = SdMmcUpdateInformation(pSd, 1, 1);
    }
    // Reset state for data R/W
    pSd->state = SD_STATE_READY;

    return error;
}

unsigned char SD_BusWidth(SdCard *pSd,
                          unsigned char busWidth)
{
    return 0;
}

#if defined(MCI2_INTERFACE) && defined(AT91C_MCI_SPCMD_BOOTREQ)
//------------------------------------------------------------------------------
/// Read Block of data in a buffer pointed by pData. The buffer size must be at
/// least 512 byte long. This function checks the SD card status register and
/// address the card if required before sending the read command.
/// Returns 0 if successful; otherwise returns an code describing the error.
/// \param pSd  Pointer to a SD card driver instance.
/// \param address  Address of the block to read.
/// \param nbBlocks Number of blocks to be read.
/// \param pData  Data buffer whose size is at least the block size.
//------------------------------------------------------------------------------
unsigned char MMC_BootRead(SdCard *pSd,
                           unsigned int   nbBlocks,
                           unsigned char *pData)
{
    unsigned char error;
    unsigned char bootAck  = 0;
    unsigned char busWidth = MCI_SDCBUS_4BIT;

    SANITY_CHECK(pSd);

    if (pSd->state != SD_STATE_BOOT)
        return SD_ERROR_DRIVER;

  #if 0
    switch(SD_EXTCSD_BOOT_BUS_WIDTH(pSd)) {
        case SD_EXTCSD_BOOT_BUS_1BIT:
            busWidth = MCI_SDCBUS_1BIT;
            break;
        case SD_EXTCSD_BOOT_BUS_8BIT:
            busWidth = MCI_SDCBUS_8BIT;
            break;
    }

    if (SD_EXTCSD_BOOT_CONFIG(pSd) & SD_EXTCSD_BOOT_PARTITION_ACK)
        bootAck = 1;
  #endif

    MCI_SetBusWidth((Mci*)pSd->pSdDriver, busWidth);
    error = BootREQ(pSd, pData, nbBlocks, bootAck);
    pSd->state = SD_STATE_BOOT;

    return error;
}

//------------------------------------------------------------------------------
/// In boot operation mode, the master can read boot data from the slave.
/// By keeping CMD line low after power-on
/// \param pSd  Pointer to a SD card driver instance.
//------------------------------------------------------------------------------
unsigned char MMC_BootInit(SdCard *pSd)
{
    unsigned char error = 0;

    SANITY_CHECK(pSd);

    error = PonBoot(pSd);

    if (!error) {

        //error = BootREQ(pSd, 0, 0, 0);

        if (!error)
            pSd->state = SD_STATE_BOOT;
        else {
            TRACE_ERROR("MMC_BootInit.BootREQ: %d\n\r", error);
        }
    }
    else {
        TRACE_ERROR("MMC_BootInit.PonBoot: %d\n\r", error);
    }

    return error;
}

//------------------------------------------------------------------------------
/// In boot operation mode, the master can read boot data from the slave.
/// By sending CMD0 with argument + 0xFFFFFFFA
/// \param pSd  Pointer to a SD card driver instance.
//------------------------------------------------------------------------------
unsigned char MMC_BootStart(SdCard *pSd)
{
    unsigned char error;

    SANITY_CHECK(pSd);

    if (pSd->state == SD_STATE_BOOT)
        return 0;

    if (pSd->cardType >= CARD_MMC
        && SD_CSD_STRUCTURE(pSd) >= 2
        && SD_CID_BGA(pSd) == 1
        && SD_EXTCSD_BOOT_INFO(pSd) == 1) {}
    else
        return SD_ERROR_NOT_SUPPORT;

    error = Cmd0(pSd, 0xFFFFFFFA);
    pSd->state = SD_STATE_BOOT;

    return 0;
}

//------------------------------------------------------------------------------
/// Terminate the boot operation mode
/// \param pSd  Pointer to a SD card driver instance.
//------------------------------------------------------------------------------
unsigned char MMC_BootStop(SdCard *pSd)
{
    unsigned char error;

    SANITY_CHECK(pSd);

    if (pSd->state != SD_STATE_BOOT)
        return 0;

    error = BootEnd(pSd);

    if(!error)
        pSd->state = SD_STATE_IDLE;

    return error;
}

//------------------------------------------------------------------------------
/// Setup Boot Settings
/// \param resetBus Wether bus width is reset to 1-bit after quit boot mode.
/// \param busWidth The bus width in boot operation.
/// \param bootPart The partition used for boot operation.
/// \param accPart  The partition to access with normal read/write.
/// \param bootAck  Enable boot acknoledge.
/// \return 0 or error code.
//------------------------------------------------------------------------------
unsigned char MMC_SetupBootMode(SdCard *pSd,
                                unsigned char resetBus,
                                unsigned char busWidth,
                                unsigned char bootPart,
                                unsigned char accPart,
                                unsigned char bootAck)
{
    unsigned int   status;
    unsigned short error;
    const MmcCmd6Arg bootArgs[] = {
        // BOOT_CONFIG
        {3, 179, (bootAck << 6)|(bootPart << 3)|(accPart << 0), 0},
        // BOOT_BUS_WIDTH
        {3, 177, (busWidth << 2)|(resetBus << 0), 0}
    };

    SANITY_CHECK(pSd);
    if (    pSd->cardType >= CARD_MMC
        &&  SD_CSD_STRUCTURE(pSd) >= 2
        &&  SD_CID_CBS(pSd) == 1) {}
    else return SD_ERROR_NOT_SUPPORT;
    //if (MMC_GetBootSizeKB(pSd) == 0) return SD_ERROR_NOT_SUPPORT;

    // Quit transfer state
    error = MoveToTranState(pSd);
    if (error) {
        TRACE_ERROR("MMC_SetupBootMode.Tran: %d\n\r", error);
        return error;
    }

    // Setup all boot informations
    error = MmcSwitchSettings(pSd,
                              bootArgs,
                              sizeof(bootArgs)/sizeof(MmcCmd6Arg),
                              &status);
    if (error) {
        TRACE_ERROR("MMC_SetupBootMode.Cmd6: 0x%x, %x\n\r", error, status);
        return (unsigned char)error;
    }

    // Update the EXT_CSD
  #if 1
    error = Cmd8(pSd, 0, pSd->extData);
    if (error) {
        TRACE_ERROR("MMC_SetupBootMode.Cmd8 (%d)\n\r", error);
    }

   #if 0
    if (   SD_EXTCSD_BOOT_BUS_WIDTH(pSd) != bootArgs[0].value
        || SD_EXTCSD_BOOT_CONFIG(pSd) != bootArgs[1].value ) {

        TRACE_ERROR("MMC_SetupBootMode: ExtCSD not changed\n\r");

      #if 1
        Cmd13(pSd, &status);
        TRACE_INFO("  CARD status: 0x%x\n\r", status);
      #endif
        return SD_ERROR_DRIVER;
    }
   #endif
  #endif

    // Reset state for data R/W
    pSd->state = SD_STATE_READY;

    return 0;
}

//------------------------------------------------------------------------------
/// \return 0 or error code.
//------------------------------------------------------------------------------
unsigned char MMC_StopBootMode()
{
    return 0;
}
#endif


//------------------------------------------------------------------------------
/// \return size of the card in KB
//------------------------------------------------------------------------------
unsigned int MMC_GetTotalSizeKB(SdCard *pSd)
{
    SANITY_CHECK(pSd);

    if (pSd->totalSize == 0xFFFFFFFF) {

        return pSd->blockNr / 2;
    }
    
    return pSd->totalSize / 1024;
}


//------------------------------------------------------------------------------
/// \return size of boot area if the card support boot operation.
//------------------------------------------------------------------------------
unsigned int MMC_GetBootSizeKB(SdCard *pSd)
{
    SANITY_CHECK(pSd);
    if (   pSd->cardType >= CARD_MMC
        && SD_CSD_STRUCTURE(pSd) >= 2) {

        return SD_EXTCSD_BOOT_SIZE_MULTI(pSd) * 128;
    }
    return 0;
}

#if MCI_SDIO_ENABLE
//------------------------------------------------------------------------------
/// Display the content of the CCCR
//------------------------------------------------------------------------------
void SDIO_DisplayCardInformation(SdCard *pSd)
{
    unsigned int  tmp = 0, addrCIS = 0, addrManfID = 0, addrFunc0 = 0;
    unsigned char* p = (unsigned char*)&tmp;
    unsigned char  buf[8];

    switch(pSd->cardType) {
        case CARD_SDIO:
            TRACE_INFO("** SDIO ONLY card\n\r");
            break;
        case CARD_SDCOMBO:
        case CARD_SDHCCOMBO:
            TRACE_INFO("** SDIO Combo card\n\r");
            break;
        default:
            TRACE_INFO("** NO SDIO, CCCR not supported\n\r");
            return;
    }
    // CCCR
    TRACE_INFO("====== CCCR ======\n\r");
    SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_CCCR_REG, p, 1);
    TRACE_INFO(".SDIO       %02X\n\r", (tmp & SDIO_SDIO) >> 4);
    TRACE_INFO(".CCCR       %02X\n\r", (tmp & SDIO_CCCR) >> 0);
    SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_SD_REV_REG, p, 1);
    TRACE_INFO(".SD         %02X\n\r", (tmp & SDIO_SD) >> 0);
    SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_IOE_REG, p, 1);
    TRACE_INFO(".IOE        %02X\n\r", (tmp & SDIO_IOE) >> 0);
    SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_IOR_REG, p, 1);
    TRACE_INFO(".IOR        %02X\n\r", (tmp & SDIO_IOR) >> 0);
    SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_IEN_REG, p, 1);
    TRACE_INFO(".IEN        %02X\n\r", (tmp & SDIO_IEN) >> 0);
    SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_INT_REG, p, 1);
    TRACE_INFO(".INT        %02X\n\r", (tmp & SDIO_INT) >> 0);
    SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_BUS_CTRL_REG, p, 1);
    TRACE_INFO(".CD         %x\n\r", (tmp & SDIO_CD) >> 7);
    TRACE_INFO(".SCSI       %x\n\r", (tmp & SDIO_SCSI) >> 6);
    TRACE_INFO(".ECSI       %x\n\r", (tmp & SDIO_ECSI) >> 5);
    TRACE_INFO(".BUS_WIDTH  %x\n\r", (tmp & SDIO_BUSWIDTH) >> 0);
    SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_CAP_REG, p, 1);
    TRACE_INFO(".4BLS       %x\n\r", (tmp & SDIO_4BLS) >> 7);
    TRACE_INFO(".LSC        %x\n\r", (tmp & SDIO_LSC) >> 6);
    TRACE_INFO(".E4MI       %x\n\r", (tmp & SDIO_E4MI) >> 5);
    TRACE_INFO(".S4MI       %x\n\r", (tmp & SDIO_S4MI) >> 4);
    TRACE_INFO(".SBS        %x\n\r", (tmp & SDIO_SBS) >> 3);
    TRACE_INFO(".SRW        %x\n\r", (tmp & SDIO_SRW) >> 2);
    TRACE_INFO(".SMB        %x\n\r", (tmp & SDIO_SMB) >> 1);
    TRACE_INFO(".SDC        %x\n\r", (tmp & SDIO_SDC) >> 0);
    SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_CIS_PTR_REG, p, 3);
    TRACE_INFO(".CIS_PTR    %06X\n\r", tmp);
    addrCIS = tmp; tmp = 0;
    SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_BUS_SUSP_REG, p, 1);
    TRACE_INFO(".BR         %x\n\r", (tmp & SDIO_BR) >> 1);
    TRACE_INFO(".BS         %x\n\r", (tmp & SDIO_BS) >> 0);
    SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_FUN_SEL_REG, p, 1);
    TRACE_INFO(".DF         %x\n\r", (tmp & SDIO_DF) >> 7);
    TRACE_INFO(".FS         %x\n\r", (tmp & SDIO_FS) >> 0);
    SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_EXEC_REG, p, 1);
    TRACE_INFO(".EX         %x\n\r", (tmp & SDIO_EX));
    TRACE_INFO(".EXM        %x\n\r", (tmp & SDIO_EXM) >> 0);
    SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_READY_REG, p, 1);
    TRACE_INFO(".RF         %x\n\r", (tmp & SDIO_RF));
    TRACE_INFO(".RFM        %x\n\r", (tmp & SDIO_RFM) >> 0);
    SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_FN0_BLKSIZ_REG, p, 2);
    TRACE_INFO(".FN0_SIZE   %d(%04X)\n\r", tmp, tmp);
    tmp = 0;
    SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_POWER_REG, p, 1);
    TRACE_INFO(".EMPC       %x\n\r", (tmp & SDIO_EMPC) >> 1);
    TRACE_INFO(".SMPC       %x\n\r", (tmp & SDIO_SMPC) >> 0);
    SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_HS_REG, p, 1);
    TRACE_INFO(".EHS        %x\n\r", (tmp & SDIO_EHS) >> 1);
    TRACE_INFO(".SHS        %x\n\r", (tmp & SDIO_SHS) >> 0);
    // Metaformat
    SdioFindTuples(pSd, addrCIS, 128, &addrManfID, &addrFunc0);
    if (addrManfID != 0) {
        SDIO_ReadDirect(pSd, SDIO_CIA, addrManfID, buf, 6);
        TRACE_INFO("==== CISTPL_MANFID ====\n\r");
        TRACE_INFO("._MANF %04X\n\r", buf[2] + (buf[3] << 8));
        TRACE_INFO("._CARD %04X\n\r", buf[4] + (buf[5] << 8));
    }
    if (addrFunc0 != 0) {
        SDIO_ReadDirect(pSd, SDIO_CIA, addrFunc0, buf, 6);
        TRACE_INFO("== CISTPL_FUNCE Fun0 ==\n\r");
        TRACE_INFO("._FN0_BLK_SIZE   %d(0x%04X)\n\r",
            buf[3] + (buf[4] << 8), buf[3] + (buf[4] << 8));
        TRACE_INFO("._MAX_TRAN_SPEED %02X\n\r", buf[5]);
    }
}
#endif

//------------------------------------------------------------------------------
/// Display the content of the CID register
/// \param pCid  Pointer to the Cid register value
//------------------------------------------------------------------------------
void SD_DisplayRegisterCID(SdCard *pSd)
{
    // CID for memory card only
    if (pSd->cardType == CARD_UNKNOWN || pSd->cardType >= CARD_SDIO)
        return;

    TRACE_INFO("======= CID =======\n\r");
  #if 0
    TRACE_INFO(" .Card/BGA         %X\n\r", SD_CID_BGA(pSd));
  #else
    TRACE_INFO("CID MID Manufacturer ID       %02X\n\r",
        SD_CID_MID(pSd));
    
    TRACE_INFO("CID OID OEM/Application ID    %c%c\n\r",
        (char)SD_CID_OID_BYTE_1(pSd),
        (char)SD_CID_OID_BYTE_0(pSd));
    
    TRACE_INFO("CID PNM Product revision      %c%c%c%c%c\n\r",
        (char)SD_CID_PNM_BYTE_4(pSd),
        (char)SD_CID_PNM_BYTE_3(pSd),
        (char)SD_CID_PNM_BYTE_2(pSd),
        (char)SD_CID_PNM_BYTE_1(pSd),
        (char)SD_CID_PNM_BYTE_0(pSd));
    
    TRACE_INFO("CID PRV Product serial number %02X%04X\n\r", 
         SD_CID_PRV_2(pSd),
         SD_CID_PRV_1(pSd));

    TRACE_INFO("CID MDT Manufacturing date    %04d/%02d\n\r",
        (unsigned short)SD_CID_MDT_YEAR(pSd),
        (unsigned char)SD_CID_MDT_MONTH(pSd));               
    
    TRACE_INFO("CID CRC checksum              %02X\n\r",   
         SD_CID_CRC(pSd));
  #endif
}

//------------------------------------------------------------------------------
/// Display the content of the CSD register
/// \param pSd  
//------------------------------------------------------------------------------
void SD_DisplayRegisterCSD(SdCard *pSd)
{ 
    // CID for memory card only
    if (pSd->cardType == CARD_UNKNOWN || pSd->cardType >= CARD_SDIO)
        return;

    TRACE_INFO("======== CSD ========");
  #if 0
  {
    unsigned int i;
    unsigned char *p = (unsigned char *)pSd->csd;
    for(i = 0; i < 128 / 8; i++) {
        if ((i % 16) == 0) TRACE_INFO_WP("\n\r [%3d]:", i);
        TRACE_INFO_WP(" %2x", p[i]);
    }
    TRACE_INFO_WP("\n\r");
    TRACE_INFO("------------------------\n\r");
  }
  #else
    TRACE_INFO_WP("\n\r");
  #endif
    TRACE_INFO(" .CSD_STRUCTURE      0x%x\r\n", SD_CSD_STRUCTURE(pSd));
    TRACE_INFO(" .SPEC_VERS          0x%x\r\n", SD_CSD_SPEC_VERS(pSd));
    TRACE_INFO(" .TAAC               0x%X\r\n", SD_CSD_TAAC(pSd)              );
    TRACE_INFO(" .NSAC               0x%X\r\n", SD_CSD_NSAC(pSd)              );
    TRACE_INFO(" .TRAN_SPEED         0x%X\r\n", SD_CSD_TRAN_SPEED(pSd)        );
    TRACE_INFO(" .CCC                0x%X\r\n", SD_CSD_CCC(pSd)               );
    TRACE_INFO(" .READ_BL_LEN        0x%X\r\n", SD_CSD_READ_BL_LEN(pSd)       );
    TRACE_INFO(" .READ_BL_PARTIAL    0x%X\r\n", SD_CSD_READ_BL_PARTIAL(pSd)   );
    TRACE_INFO(" .WRITE_BLK_MISALIGN 0x%X\r\n", SD_CSD_WRITE_BLK_MISALIGN(pSd));
    TRACE_INFO(" .READ_BLK_MISALIGN  0x%X\r\n", SD_CSD_READ_BLK_MISALIGN(pSd) );
    TRACE_INFO(" .DSR_IMP            0x%X\r\n", SD_CSD_DSR_IMP(pSd)           );
    TRACE_INFO(" .C_SIZE             0x%X\r\n", SD_CSD_C_SIZE(pSd)            );
    TRACE_INFO(" .C_SIZE_HC          0x%X\r\n", SD_CSD_C_SIZE_HC(pSd)         );
    TRACE_INFO(" .VDD_R_CURR_MIN     0x%X\r\n", SD_CSD_VDD_R_CURR_MIN(pSd)    );
    TRACE_INFO(" .VDD_R_CURR_MAX     0x%X\r\n", SD_CSD_VDD_R_CURR_MAX(pSd)    );
    TRACE_INFO(" .VDD_W_CURR_MIN     0x%X\r\n", SD_CSD_VDD_W_CURR_MIN(pSd)    );
    TRACE_INFO(" .VDD_W_CURR_MAX     0x%X\r\n", SD_CSD_VDD_W_CURR_MAX(pSd)    );
    TRACE_INFO(" .C_SIZE_MULT        0x%X\r\n", SD_CSD_C_SIZE_MULT(pSd)       );
    TRACE_INFO(" .ERASE_BLK_EN       0x%X\r\n", SD_CSD_ERASE_BLK_EN(pSd)      );
    TRACE_INFO(" .SECTOR_SIZE        0x%X\r\n", SD_CSD_SECTOR_SIZE(pSd)       );
    TRACE_INFO(" .WP_GRP_SIZE        0x%X\r\n", SD_CSD_WP_GRP_SIZE(pSd)       );
    TRACE_INFO(" .WP_GRP_ENABLE      0x%X\r\n", SD_CSD_WP_GRP_ENABLE(pSd)     );
    TRACE_INFO(" .R2W_FACTOR         0x%X\r\n", SD_CSD_R2W_FACTOR(pSd)        );
    TRACE_INFO(" .WRITE_BL_LEN       0x%X\r\n", SD_CSD_WRITE_BL_LEN(pSd)      );
    TRACE_INFO(" .WRITE_BL_PARTIAL   0x%X\r\n", SD_CSD_WRITE_BL_PARTIAL(pSd)  );
    TRACE_INFO(" .FILE_FORMAT_GRP    0x%X\r\n", SD_CSD_FILE_FORMAT_GRP(pSd)   );
    TRACE_INFO(" .COPY               0x%X\r\n", SD_CSD_COPY(pSd)              );
    TRACE_INFO(" .PERM_WRITE_PROTECT 0x%X\r\n", SD_CSD_PERM_WRITE_PROTECT(pSd));
    TRACE_INFO(" .TMP_WRITE_PROTECT  0x%X\r\n", SD_CSD_TMP_WRITE_PROTECT(pSd) );
    TRACE_INFO(" .FILE_FORMAT        0x%X\r\n", SD_CSD_FILE_FORMAT(pSd)       );
    TRACE_INFO(" .ECC                0x%X\r\n", SD_CSD_ECC(pSd)               );
    TRACE_INFO(" .CRC                0x%X\r\n", SD_CSD_CRC(pSd)               );
    TRACE_INFO(" .MULT               0x%X\r\n", SD_CSD_MULT(pSd)              );
    TRACE_INFO(" .BLOCKNR            0x%X\r\n", SD_CSD_BLOCKNR(pSd)           );
    TRACE_INFO(" .BLOCKNR_HC         0x%X\r\n", SD_CSD_BLOCKNR_HC(pSd)        );
    TRACE_INFO(" .BLOCK_LEN          0x%X\r\n", SD_CSD_BLOCK_LEN(pSd)         );
    TRACE_INFO(" .TOTAL_SIZE         0x%X\r\n", SD_CSD_TOTAL_SIZE(pSd)        );
    TRACE_INFO(" .TOTAL_SIZE_HC      0x%X\r\n", SD_CSD_TOTAL_SIZE_HC(pSd)     );
    TRACE_INFO(" -SD_TOTAL_SIZE      0x%X\r\n", SD_TOTAL_SIZE(pSd)            );
    TRACE_INFO(" -SD_TOTAL_BLOCK     0x%X\r\n", SD_TOTAL_BLOCK(pSd)           );
}   

//------------------------------------------------------------------------------
/// Display the content of the EXT_CSD register
/// \param pSd  
//------------------------------------------------------------------------------
void SD_DisplayRegisterECSD(SdCard *pSd)
{
    if (pSd->cardType >= CARD_MMC && pSd->cardType <= CARD_MMCHD
        && SD_CSD_STRUCTURE(pSd) >= 2) {}
    else {
        TRACE_INFO("** EXT_CSD NOT SUPPORTED\n\r");
        return;
    }
    TRACE_INFO("======= EXT_CSD =======");
  #if 0
  {
    unsigned int i;
    unsigned char *p = (unsigned char *)pSd->extData;
    for(i = 0; i < 512; i++) {
        if ((i % 16) == 0) TRACE_INFO_WP("\n\r [%3d]:", i);
        TRACE_INFO_WP(" %2x", p[i]);
    }
    TRACE_INFO_WP("\n\r");
    TRACE_INFO("------------------------\n\r");
  }
  #else
    TRACE_INFO_WP("\n\r");
  #endif
    TRACE_INFO(" .S_CMD_SET            : 0x%X\n\r",
        SD_EXTCSD_S_CMD_SET(pSd));
    TRACE_INFO(" .BOOT_INFO            : 0x%X\n\r",
        SD_EXTCSD_BOOT_INFO(pSd));
    TRACE_INFO(" .BOOT_SIZE_MULTI      : 0x%X\n\r",
        SD_EXTCSD_BOOT_SIZE_MULTI(pSd));
    TRACE_INFO(" .ACC_SIZE             : 0x%X\n\r",
        SD_EXTCSD_ACC_SIZE(pSd));
    TRACE_INFO(" .HC_ERASE_GRP_SIZE    : 0x%X\n\r",
        SD_EXTCSD_HC_ERASE_GRP_SIZE(pSd));
    TRACE_INFO(" .ERASE_TIMEOUT_MULT   : 0x%X\n\r",
        SD_EXTCSD_ERASE_TIMEOUT_MULT(pSd));
    TRACE_INFO(" .REL_WR_SEC_C         : 0x%X\n\r",
        SD_EXTCSD_REL_WR_SEC_C(pSd));
    TRACE_INFO(" .HC_WP_GRP_SIZE       : 0x%X\n\r",
        SD_EXTCSD_HC_WP_GRP_SIZE(pSd));
    TRACE_INFO(" .S_C_VCC              : 0x%X\n\r",
        SD_EXTCSD_S_C_VCC(pSd));
    TRACE_INFO(" .S_C_VCCQ             : 0x%X\n\r",
        SD_EXTCSD_S_C_VCCQ(pSd));
    TRACE_INFO(" .S_A_TIMEOUT          : 0x%X\n\r",
        SD_EXTCSD_S_A_TIMEOUT(pSd));
    TRACE_INFO(" .SEC_COUNT            : 0x%X\n\r",
        SD_EXTCSD_SEC_COUNT(pSd));
    TRACE_INFO(" .MIN_PERF_W_8_52      : 0x%X\n\r",
        SD_EXTCSD_MIN_PERF_W_8_52(pSd));
    TRACE_INFO(" .MIN_PERF_R_8_52      : 0x%X\n\r",
        SD_EXTCSD_MIN_PERF_R_8_52(pSd));
    TRACE_INFO(" .MIN_PERF_W_8_26_4_52 : 0x%X\n\r",
        SD_EXTCSD_MIN_PERF_W_8_26_4_52(pSd));
    TRACE_INFO(" .MIN_PERF_R_8_26_4_52 : 0x%X\n\r",
        SD_EXTCSD_MIN_PERF_R_8_26_4_52(pSd));
    TRACE_INFO(" .MIN_PERF_W_4_26      : 0x%X\n\r",
        SD_EXTCSD_MIN_PERF_W_4_26(pSd));
    TRACE_INFO(" .MIN_PERF_R_4_26      : 0x%X\n\r",
        SD_EXTCSD_MIN_PERF_R_4_26(pSd));
    TRACE_INFO(" .PWR_CL_26_360        : 0x%X\n\r",
        SD_EXTCSD_PWR_CL_26_360(pSd));
    TRACE_INFO(" .PWR_CL_52_360        : 0x%X\n\r",
        SD_EXTCSD_PWR_CL_52_360(pSd));
    TRACE_INFO(" .PWR_CL_26_195        : 0x%X\n\r",
        SD_EXTCSD_PWR_CL_26_195(pSd));
    TRACE_INFO(" .PWR_CL_52_195        : 0x%X\n\r",
        SD_EXTCSD_PWR_CL_52_195(pSd));
    TRACE_INFO(" .CARD_TYPE            : 0x%X\n\r",
        SD_EXTCSD_CARD_TYPE(pSd));
    TRACE_INFO(" .CSD_STRUCTURE        : 0x%X\n\r",
        SD_EXTCSD_CSD_STRUCTURE(pSd));
    TRACE_INFO(" .EXT_CSD_REV          : 0x%X\n\r",
        SD_EXTCSD_EXT_CSD_REV(pSd));
    TRACE_INFO(" .CMD_SET              : 0x%X\n\r",
        SD_EXTCSD_CMD_SET(pSd));
    TRACE_INFO(" .CMD_SET_REV          : 0x%X\n\r",
        SD_EXTCSD_CMD_SET_REV(pSd));
    TRACE_INFO(" .POWER_CLASS          : 0x%X\n\r",
        SD_EXTCSD_POWER_CLASS(pSd));
    TRACE_INFO(" .HS_TIMING            : 0x%X\n\r",
        SD_EXTCSD_HS_TIMING(pSd));
    TRACE_INFO(" .BUS_WIDTH            : 0x%X\n\r",
        SD_EXTCSD_BUS_WIDTH(pSd));
    TRACE_INFO(" .ERASED_MEM_CONT      : 0x%X\n\r",
        SD_EXTCSD_ERASED_MEM_CONT(pSd));
    TRACE_INFO(" .BOOT_CONFIG          : 0x%X\n\r",
        SD_EXTCSD_BOOT_CONFIG(pSd));
    TRACE_INFO(" .BOOT_BUS_WIDTH       : 0x%X\n\r",
        SD_EXTCSD_BOOT_BUS_WIDTH(pSd));
    TRACE_INFO(" .ERASE_GROUP_DEF      : 0x%X\n\r",
        SD_EXTCSD_ERASE_GROUP_DEF(pSd));
}

//------------------------------------------------------------------------------
/// Display the content of the SCR register
/// \param pSd  Pointer to SdCard instance.
//------------------------------------------------------------------------------
void SD_DisplayRegisterSCR(SdCard *pSd)
{ 
    if (pSd->cardType >= CARD_SD && pSd->cardType <= CARD_SDHC) {}
    else {
        TRACE_INFO("** SCR NOT Supported!\n\r");
        return;
    }
    TRACE_INFO("========== SCR ==========");
  #if 0
  {
    unsigned int i;
    unsigned char *p = (unsigned char*)pSd->extData;
    //TRACE_INFO_WP("\n\r");
    //TRACE_INFO("DATA @ 0x%X", (unsigned int)p);
    for(i = 0; i < 16; i ++) {
        if ((i % 8) == 0) TRACE_INFO_WP("\n\r [%3d]:", i);
        TRACE_INFO_WP(" %02x", p[i]);
    }
    TRACE_INFO_WP("\n\r");
    TRACE_INFO("------------------------\n\r");
  }
  #else
    TRACE_INFO_WP("\n\r");
  #endif

    TRACE_INFO(" .SCR_STRUCTURE         :0x%X\n\r",
        SD_SCR_SCR_STRUCTURE(pSd));
    TRACE_INFO(" .SD_SPEC               :0x%X\n\r",
        SD_SCR_SD_SPEC(pSd));
    TRACE_INFO(" .DATA_STAT_AFTER_ERASE :0x%X\n\r",
        SD_SCR_DATA_STAT_AFTER_ERASE(pSd));
    TRACE_INFO(" .SD_SECURITY           :0x%X\n\r",
        SD_SCR_SD_SECURITY(pSd));
    TRACE_INFO(" .SD_BUS_WIDTHS         :0x%X\n\r",
        SD_SCR_SD_BUS_WIDTHS(pSd));
}

//------------------------------------------------------------------------------
/// Display the content of the SD Status
/// \param pSd  Pointer to SdCard instance.
//------------------------------------------------------------------------------
void SD_DisplaySdStatus(SdCard *pSd)
{
    if (   pSd->cardType >= CARD_SD
        && pSd->cardType <= CARD_SDHC
        && (pSd->optCmdBitMap & SD_ACMD13_SUPPORT) ) {}
    else {
        TRACE_INFO("** SD Status NOT Supported!\n\r");
        return;
    }
    TRACE_INFO("=========== STAT ============");
  #if 0
  {
    unsigned int i;
    unsigned char *p = (unsigned char*)pSd->extData;
    //TRACE_INFO_WP("\n\r");
    //TRACE_INFO("DATA @ 0x%X", (unsigned int)p);
    for(i = 0; i < 72; i ++) {
        if ((i % 8) == 0) TRACE_INFO_WP("\n\r [%3d]:", i);
        TRACE_INFO_WP(" %02x", p[i]);
    }
    TRACE_INFO_WP("\n\r");
    TRACE_INFO("------------------------\n\r");
  }
  #else
    TRACE_INFO_WP("\n\r");
  #endif

    TRACE_INFO(" .DAT_BUS_WIDTH          :0x%X\n\r",
        SD_STAT_DAT_BUS_WIDTH(pSd));
    TRACE_INFO(" .SECURED_MODE           :0x%X\n\r",
        SD_STAT_SECURED_MODE(pSd));
    TRACE_INFO(" .SD_CARD_TYPE           :0x%X\n\r",
        SD_STAT_SD_CARD_TYPE(pSd));
    TRACE_INFO(" .SIZE_OF_PROTECTED_AREA :0x%X\n\r",
        SD_STAT_SIZE_OF_PROTECTED_AREA(pSd));
    TRACE_INFO(" .SPEED_CLASS            :0x%X\n\r",
        SD_STAT_SPEED_CLASS(pSd));
    TRACE_INFO(" .PERFORMANCE_MOVE       :0x%X\n\r",
        SD_STAT_PERFORMANCE_MOVE(pSd));
    TRACE_INFO(" .AU_SIZE                :0x%X\n\r",
        SD_STAT_AU_SIZE(pSd));
    TRACE_INFO(" .ERASE_SIZE             :0x%X\n\r",
        SD_STAT_ERASE_SIZE(pSd));
    TRACE_INFO(" .ERASE_TIMEOUT          :0x%X\n\r",
        SD_STAT_ERASE_TIMEOUT(pSd));
    TRACE_INFO(" .ERASE_OFFSET           :0x%X\n\r",
        SD_STAT_ERASE_OFFSET(pSd));
}
personal git repositories of Harald Welte. Your mileage may vary