enet_1.0.0_54410889/Ada_Drivers_Library/arch/ARM/STM32/drivers/sd/stm32-sdmmc.adb

   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
------------------------------------------------------------------------------
--                                                                          --
--                     Copyright (C) 2015-2016, AdaCore                     --
--                                                                          --
--  Redistribution and use in source and binary forms, with or without      --
--  modification, are permitted provided that the following conditions are  --
--  met:                                                                    --
--     1. Redistributions of source code must retain the above copyright    --
--        notice, this list of conditions and the following disclaimer.     --
--     2. Redistributions in binary form must reproduce the above copyright --
--        notice, this list of conditions and the following disclaimer in   --
--        the documentation and/or other materials provided with the        --
--        distribution.                                                     --
--     3. Neither the name of the copyright holder nor the names of its     --
--        contributors may be used to endorse or promote products derived   --
--        from this software without specific prior written permission.     --
--                                                                          --
--   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS    --
--   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT      --
--   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR  --
--   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT   --
--   HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
--   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT       --
--   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,  --
--   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY  --
--   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT    --
--   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE  --
--   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.   --
--                                                                          --
------------------------------------------------------------------------------

with Ada.Unchecked_Conversion;
with Ada.Real_Time;          use Ada.Real_Time;
with System;                 use System;
with System.Machine_Code;

with SDMMC_SVD;              use SDMMC_SVD;
with STM32.Device;           use STM32.Device;
with STM32_SVD.RCC;          use STM32_SVD.RCC;
with SDMMC_Init;
with STM32.DMA;              use STM32.DMA;
with Cortex_M.Cache;         use Cortex_M.Cache;
with STM32.DMA.Interrupts;   use STM32.DMA.Interrupts;
with STM32.SDMMC_Interrupt;  use STM32.SDMMC_Interrupt;

package body STM32.SDMMC is

   --  Mask for errors Card Status R1 (OCR Register)
   SD_OCR_ADDR_OUT_OF_RANGE     : constant := 16#8000_0000#;
   SD_OCR_ADDR_MISALIGNED       : constant := 16#4000_0000#;
   SD_OCR_BLOCK_LEN_ERR         : constant := 16#2000_0000#;
   SD_OCR_ERASE_SEQ_ERR         : constant := 16#1000_0000#;
   SD_OCR_BAD_ERASE_PARAM       : constant := 16#0800_0000#;
   SD_OCR_WRITE_PROT_VIOLATION  : constant := 16#0400_0000#;
   SD_OCR_LOCK_UNLOCK_FAILED    : constant := 16#0100_0000#;
   SD_OCR_COM_CRC_FAILED        : constant := 16#0080_0000#;
   SD_OCR_ILLEGAL_CMD           : constant := 16#0040_0000#;
   SD_OCR_CARD_ECC_FAILED       : constant := 16#0020_0000#;
   SD_OCR_CC_ERROR              : constant := 16#0010_0000#;
   SD_OCR_GENERAL_UNKNOWN_ERROR : constant := 16#0008_0000#;
   SD_OCR_STREAM_READ_UNDERRUN  : constant := 16#0004_0000#;
   SD_OCR_STREAM_WRITE_UNDERRUN : constant := 16#0002_0000#;
   SD_OCR_CID_CSD_OVERWRITE     : constant := 16#0001_0000#;
   SD_OCR_WP_ERASE_SKIP         : constant := 16#0000_8000#;
   SD_OCR_CARD_ECC_DISABLED     : constant := 16#0000_4000#;
   SD_OCR_ERASE_RESET           : constant := 16#0000_2000#;
   SD_OCR_AKE_SEQ_ERROR         : constant := 16#0000_0008#;
   SD_OCR_ERRORMASK             : constant := 16#FDFF_E008#;

   --  Masks for R6 responses.
   SD_R6_General_Unknown_Error : constant := 16#0000_2000#;
   SD_R6_Illegal_Cmd           : constant := 16#0000_4000#;
   SD_R6_Com_CRC_Failed        : constant := 16#0000_8000#;

   SD_DATATIMEOUT              : constant := 16#FFFF_FFFF#;

   procedure Configure_Data
     (Controller         : in out SDMMC_Controller;
      Data_Length        : UInt25;
      Data_Block_Size    : DCTRL_DBLOCKSIZE_Field;
      Transfer_Direction : Data_Direction;
      Transfer_Mode      : DCTRL_DTMODE_Field;
      DPSM               : Boolean;
      DMA_Enabled        : Boolean);

   function Read_FIFO
     (Controller : in out SDMMC_Controller) return UInt32;

   function Response_R1_Error
     (Controller    : in out SDMMC_Controller;
      Command_Index : SD_Command) return SD_Error;
   --  Checks for error conditions for R1 response

   function Response_R2_Error
     (Controller : in out SDMMC_Controller) return SD_Error;
   --  Checks for error conditions for R2 (CID or CSD) response.

   function Response_R3_Error
     (Controller : in out SDMMC_Controller) return SD_Error;
   --  Checks for error conditions for R3 (OCR) response.

   function Response_R6_Error
     (Controller    : in out SDMMC_Controller;
      Command_Index : SD_Command;
      RCA           :    out UInt32) return SD_Error;

   function Response_R7_Error
     (Controller : in out SDMMC_Controller) return SD_Error;
   --  Checks for error conditions for R7 response.

   procedure DCTRL_Write_Delay with Inline_Always;
   --  The DCFGR register cannot be written 2 times in a row: we need to
   --  wait 3 48MHz periods + 2 90MHz periods. So instead of inserting a 1ms
   --  delay statement (which would be overkill), we just issue a few
   --  nop instructions to let the CPU wait this period.

   -----------------------
   -- DCTRL_Write_Delay --
   -----------------------

   procedure DCTRL_Write_Delay
   is
      use System.Machine_Code;
   begin
      for J in 1 .. 20 loop
         Asm ("nop", Volatile => True);
      end loop;
   end DCTRL_Write_Delay;

   ------------------------------
   -- Ensure_Card_Informations --
   ------------------------------

   procedure Ensure_Card_Informations
     (This : in out SDMMC_Controller)
   is
      Ret : SD_Error;
   begin
      if This.Has_Info then
         return;
      end if;

      Ret := STM32.SDMMC.Initialize (This);

      if Ret = OK then
         This.Has_Info := True;
      else
         This.Has_Info := False;
      end if;
   end Ensure_Card_Informations;
   ------------------------
   -- Clear_Static_Flags --
   ------------------------

   procedure Clear_Static_Flags (This : in out SDMMC_Controller)
   is
   begin
      This.Periph.ICR :=
        (CCRCFAILC => True,
         DCRCFAILC => True,
         CTIMEOUTC => True,
         DTIMEOUTC => True,
         TXUNDERRC => True,
         RXOVERRC  => True,
         CMDRENDC  => True,
         CMDSENTC  => True,
         DATAENDC  => True,
         STBITERRC => True,
         DBCKENDC  => True,
         SDIOITC   => True,
         CEATAENDC => True,
         others    => <>);
   end Clear_Static_Flags;

   ----------------
   -- Clear_Flag --
   ----------------

   procedure Clear_Flag
     (This : in out SDMMC_Controller;
      Flag       : SDMMC_Clearable_Flags)
   is
   begin
      case Flag is
         when Data_End =>
            This.Periph.ICR.DATAENDC  := True;
         when Data_CRC_Fail =>
            This.Periph.ICR.DCRCFAILC := True;
         when Data_Timeout =>
            This.Periph.ICR.DTIMEOUTC := True;
         when RX_Overrun =>
            This.Periph.ICR.RXOVERRC  := True;
         when TX_Underrun =>
            This.Periph.ICR.TXUNDERRC := True;
      end case;
   end Clear_Flag;

   ----------------------
   -- Enable_Interrupt --
   ----------------------

   procedure Enable_Interrupt
     (This : in out SDMMC_Controller;
      Interrupt  : SDMMC_Interrupts)
   is
   begin
      case Interrupt is
         when Data_End_Interrupt =>
            This.Periph.MASK.DATAENDIE   := True;
         when Data_CRC_Fail_Interrupt =>
            This.Periph.MASK.DCRCFAILIE  := True;
         when Data_Timeout_Interrupt =>
            This.Periph.MASK.DTIMEOUTIE  := True;
         when TX_FIFO_Empty_Interrupt =>
            This.Periph.MASK.TXFIFOEIE   := True;
         when RX_FIFO_Full_Interrupt =>
            This.Periph.MASK.RXFIFOFIE   := True;
         when TX_Underrun_Interrupt =>
            This.Periph.MASK.TXUNDERRIE  := True;
         when RX_Overrun_Interrupt =>
            This.Periph.MASK.RXOVERRIE   := True;
      end case;
   end Enable_Interrupt;

   -----------------------
   -- Disable_Interrupt --
   -----------------------

   procedure Disable_Interrupt
     (This : in out SDMMC_Controller;
      Interrupt  : SDMMC_Interrupts)
   is
   begin
      case Interrupt is
         when Data_End_Interrupt =>
            This.Periph.MASK.DATAENDIE   := False;
         when Data_CRC_Fail_Interrupt =>
            This.Periph.MASK.DCRCFAILIE  := False;
         when Data_Timeout_Interrupt =>
            This.Periph.MASK.DTIMEOUTIE  := False;
         when TX_FIFO_Empty_Interrupt =>
            This.Periph.MASK.TXFIFOEIE   := False;
         when RX_FIFO_Full_Interrupt =>
            This.Periph.MASK.RXFIFOFIE   := False;
         when TX_Underrun_Interrupt =>
            This.Periph.MASK.TXUNDERRIE  := False;
         when RX_Overrun_Interrupt =>
            This.Periph.MASK.RXOVERRIE   := False;
      end case;
   end Disable_Interrupt;

   ------------------------
   -- Delay_Milliseconds --
   ------------------------

   overriding procedure Delay_Milliseconds
     (This   : SDMMC_Controller;
      Amount : Natural)
   is
      pragma Unreferenced (This);
   begin
      delay until Clock + Milliseconds (Amount);
   end Delay_Milliseconds;

   -----------
   -- Reset --
   -----------

   overriding procedure Reset
     (This   : in out SDMMC_Controller;
      Status : out SD_Error)
   is
   begin
      --  Make sure the POWER register is writable by waiting a bit after
      --  the Power_Off command
      DCTRL_Write_Delay;

      This.Periph.POWER.PWRCTRL := Power_Off;

      --  Use the Default SDMMC peripheral configuration for SD card init
      This.Periph.CLKCR := (others => <>);
      This.Set_Clock (400_000);
      This.Periph.DTIMER := SD_DATATIMEOUT;

      This.Periph.CLKCR.CLKEN   := False;
      DCTRL_Write_Delay;
      This.Periph.POWER.PWRCTRL := Power_On;

      --  Wait for the clock to stabilize.
      DCTRL_Write_Delay;

      This.Periph.CLKCR.CLKEN := True;

      delay until Clock + Milliseconds (20);

      Status := OK;
   end Reset;

   ---------------
   -- Set_Clock --
   ---------------

   overriding procedure Set_Clock
     (This   : in out SDMMC_Controller;
      Freq   : Natural)
   is
      Div : UInt32;
      CLKCR : CLKCR_Register;
   begin
      Div := (This.CLK_In + UInt32 (Freq) - 1) / UInt32 (Freq);

      --  Make sure the POWER register is writable by waiting a bit after
      --  the Power_Off command
      DCTRL_Write_Delay;

      if Div <= 1 then
         This.Periph.CLKCR.BYPASS := True;
      else
         Div := Div - 2;
         CLKCR := This.Periph.CLKCR;
         CLKCR.BYPASS := False;

         if Div > UInt32 (CLKCR_CLKDIV_Field'Last) then
            CLKCR.CLKDIV := CLKCR_CLKDIV_Field'Last;
         else
            CLKCR.CLKDIV := CLKCR_CLKDIV_Field (Div);
         end if;

         This.Periph.CLKCR := CLKCR;
      end if;
   end Set_Clock;

   ------------------
   -- Set_Bus_Size --
   ------------------

   overriding procedure Set_Bus_Size
     (This : in out SDMMC_Controller;
      Mode : Wide_Bus_Mode)
   is
      function To_WIDBUS_Field is new Ada.Unchecked_Conversion
        (Wide_Bus_Mode, CLKCR_WIDBUS_Field);
   begin
      This.Periph.CLKCR.WIDBUS := To_WIDBUS_Field (Mode);
   end Set_Bus_Size;

   ------------------
   -- Send_Command --
   ------------------

   overriding procedure Send_Cmd
     (This   : in out SDMMC_Controller;
      Cmd    : Cmd_Desc_Type;
      Arg    : UInt32;
      Status : out SD_Error)
   is
      CMD_Reg : CMD_Register  := This.Periph.CMD;
   begin
      if Cmd.Rsp = Rsp_Invalid or else Cmd.Tfr = Tfr_Invalid then
         raise Program_Error with "Not implemented";
      end if;

      This.Periph.ARG := Arg;
      CMD_Reg.CMDINDEX := CMD_CMDINDEX_Field (Cmd.Cmd);
      CMD_Reg.WAITRESP := (case Cmd.Rsp is
                              when Rsp_No => No_Response,
                              when Rsp_R2 => Long_Response,
                              when others => Short_Response);
      CMD_Reg.WAITINT  := False;
      CMD_Reg.CPSMEN   := True;
      This.Periph.CMD := CMD_Reg;

      case Cmd.Rsp is
         when Rsp_No =>
            Status := This.Command_Error;

         when Rsp_R1 | Rsp_R1B =>
            Status := This.Response_R1_Error (Cmd.Cmd);

         when Rsp_R2 =>
            Status := This.Response_R2_Error;

         when Rsp_R3 =>
            Status := This.Response_R3_Error;

         when Rsp_R6 =>
            declare
               RCA : UInt32;
            begin
               Status := This.Response_R6_Error (Cmd.Cmd, RCA);
               This.RCA := UInt16 (Shift_Right (RCA, 16));
            end;

         when Rsp_R7 =>
            Status := This.Response_R7_Error;

         when Rsp_Invalid =>
            Status := HAL.SDMMC.Error;
      end case;
   end Send_Cmd;

   --------------
   -- Read_Cmd --
   --------------

   overriding procedure Read_Cmd
     (This   : in out SDMMC_Controller;
      Cmd    : Cmd_Desc_Type;
      Arg    : UInt32;
      Buf    : out UInt32_Array;
      Status : out SD_Error)
   is
      Block_Size : DCTRL_DBLOCKSIZE_Field;
      BS         : UInt32;
      Dead       : UInt32 with Unreferenced;
      Idx        : Natural;

   begin
      if Buf'Length = 0 then
         Status := Error;

         return;
      end if;

      for J in DCTRL_DBLOCKSIZE_Field'Range loop
         BS := 2 ** J'Enum_Rep;
         exit when Buf'Length * 4 < BS;
         if Buf'Length * 4 mod BS = 0 then
            Block_Size := J;
         end if;
      end loop;

      Configure_Data
        (This,
         Data_Length        => UInt25 (Buf'Length * 4),
         Data_Block_Size    => Block_Size,
         Transfer_Direction => Read,
         Transfer_Mode      => Block,
         DPSM               => True,
         DMA_Enabled        => False);

      This.Send_Cmd (Cmd, Arg, Status);

      if Status /= OK then
         return;
      end if;

      Idx := Buf'First;

      while not This.Periph.STA.RXOVERR
        and then not This.Periph.STA.DCRCFAIL
        and then not This.Periph.STA.DTIMEOUT
        and then not This.Periph.STA.DBCKEND
      loop
         if Buf'Last - Idx >= 8
           and then This.Periph.STA.RXFIFOHF
         then
            --  The FIFO is 16 words. So with RXFIFO Half full, we can read
            --  8 consecutive words
            for J in 0 .. 7 loop
               Buf (Idx + J) := Read_FIFO (This);
            end loop;

            Idx := Idx + 8;

         elsif Idx <= Buf'Last
           and then This.Periph.STA.RXDAVL
         then
            Buf (Idx) := Read_FIFO (This);
            Idx := Idx + 1;
         end if;
      end loop;

      while This.Periph.STA.RXDAVL loop
         --  Empty the FIFO if needed
         if Idx <= Buf'Last then
            Buf (Idx) := Read_FIFO (This);
            Idx := Idx + 1;
         else
            Dead := Read_FIFO (This);
         end if;
      end loop;

      if This.Periph.STA.DTIMEOUT then
         This.Periph.ICR.DTIMEOUTC := True;

         Status := Timeout_Error;

      elsif This.Periph.STA.DCRCFAIL then
         This.Periph.ICR.DCRCFAILC := True;

         Status := CRC_Check_Fail;

      elsif This.Periph.STA.RXOVERR then
         This.Periph.ICR.RXOVERRC := True;

         Status := Rx_Overrun;

      else
         Status := OK;
      end if;

      Clear_Static_Flags (This);
   end Read_Cmd;

   ----------------
   -- Read_Rsp48 --
   ----------------

   overriding procedure Read_Rsp48
     (This : in out SDMMC_Controller;
      Rsp  : out UInt32)
   is
   begin
      Rsp := This.Periph.RESP1;
   end Read_Rsp48;


   overriding procedure Read_Rsp136
     (This           : in out SDMMC_Controller;
      W0, W1, W2, W3 : out UInt32)
   is
   begin
      W0 := This.Periph.RESP1;
      W1 := This.Periph.RESP2;
      W2 := This.Periph.RESP3;
      W3 := This.Periph.RESP4;
   end Read_Rsp136;

   --------------------
   -- Configure_Data --
   --------------------

   procedure Configure_Data
     (Controller         : in out SDMMC_Controller;
      Data_Length        : UInt25;
      Data_Block_Size    : DCTRL_DBLOCKSIZE_Field;
      Transfer_Direction : Data_Direction;
      Transfer_Mode      : DCTRL_DTMODE_Field;
      DPSM               : Boolean;
      DMA_Enabled        : Boolean)
   is
      Tmp : DCTRL_Register;
   begin
      Controller.Periph.DLEN.DATALENGTH  := Data_Length;

      --  DCTRL cannot be written during 3 SDMMCCLK (48MHz) clock periods
      --  Minimum wait time is 1 Milliseconds, so let's do that
      DCTRL_Write_Delay;

      Tmp := Controller.Periph.DCTRL;
      Tmp.DTDIR      :=
        (if Transfer_Direction = Read then Card_To_Controller
         else Controller_To_Card);
      Tmp.DTMODE     := Transfer_Mode;
      Tmp.DBLOCKSIZE := Data_Block_Size;
      Tmp.DTEN       := DPSM;
      Tmp.DMAEN      := DMA_Enabled;
      Controller.Periph.DCTRL := Tmp;
   end Configure_Data;

   ------------------
   -- Disable_Data --
   ------------------

   procedure Disable_Data
     (This : in out SDMMC_Controller)
   is
   begin
      This.Periph.DCTRL := (others => <>);
   end Disable_Data;

   --------------------------
   -- Enable_DMA_Transfers --
   --------------------------

   procedure Enable_DMA_Transfers
     (This   : in out SDMMC_Controller;
      RX_Int : not null STM32.DMA.Interrupts.DMA_Interrupt_Controller_Access;
      TX_Int : not null STM32.DMA.Interrupts.DMA_Interrupt_Controller_Access;
      SD_Int : not null STM32.SDMMC_Interrupt.SDMMC_Interrupt_Handler_Access)
   is
   begin
      This.TX_DMA_Int := TX_Int;
      This.RX_DMA_Int := RX_Int;
      This.SD_Int     := SD_Int;
   end Enable_DMA_Transfers;

   --------------------------
   -- Has_Card_Information --
   --------------------------

   function Has_Card_Information
     (This : SDMMC_Controller)
      return Boolean
   is (This.Has_Info);

   ----------------------
   -- Card_Information --
   ----------------------

   function Card_Information
     (This : SDMMC_Controller)
      return HAL.SDMMC.Card_Information
   is
   begin
      return This.Info;
   end Card_Information;

   ----------------------------
   -- Clear_Card_Information --
   ----------------------------

   procedure Clear_Card_Information
     (This : in out SDMMC_Controller)
   is
   begin
      This.Has_Info := False;
   end Clear_Card_Information;

   ---------------
   -- Read_FIFO --
   ---------------

   function Read_FIFO
     (Controller : in out SDMMC_Controller) return UInt32
   is
   begin
      return Controller.Periph.FIFO;
   end Read_FIFO;

   -------------------
   -- Command_Error --
   -------------------

   function Command_Error
     (Controller : in out SDMMC_Controller) return SD_Error
   is
      Start : constant Time := Clock;
   begin
      while not Controller.Periph.STA.CMDSENT loop
         if Clock - Start > Milliseconds (1000) then
            return Timeout_Error;
         end if;
      end loop;

      Clear_Static_Flags (Controller);

      return OK;
   end Command_Error;

   -----------------------
   -- Response_R1_Error --
   -----------------------

   function Response_R1_Error
     (Controller    : in out SDMMC_Controller;
      Command_Index : SD_Command) return SD_Error
   is
      Start   : constant Time := Clock;
      Timeout : Boolean := False;
      R1      : UInt32;
   begin
      while not Controller.Periph.STA.CCRCFAIL
        and then not Controller.Periph.STA.CMDREND
        and then not Controller.Periph.STA.CTIMEOUT
      loop
         if Clock - Start > Milliseconds (1000) then
            Timeout := True;

            exit;
         end if;
      end loop;

      if Timeout or else Controller.Periph.STA.CTIMEOUT then
         --  Card is not v2.0 compliant or card does not support the set
         --  voltage range
         Controller.Periph.ICR.CTIMEOUTC := True;

         return Timeout_Error;

      elsif Controller.Periph.STA.CCRCFAIL then
         Controller.Periph.ICR.CCRCFAILC := True;

         return CRC_Check_Fail;
      end if;

      if SD_Command (Controller.Periph.RESPCMD.RESPCMD) /=
        Command_Index
      then
         return Illegal_Cmd;
      end if;

      Clear_Static_Flags (Controller);

      R1 := Controller.Periph.RESP1;

      if (R1 and SD_OCR_ERRORMASK) = 0 then
         return OK;
      end if;

      if (R1 and SD_OCR_ADDR_OUT_OF_RANGE) /= 0 then
         return Address_Out_Of_Range;
      elsif (R1 and SD_OCR_ADDR_MISALIGNED) /= 0 then
         return Address_Missaligned;
      elsif (R1 and SD_OCR_BLOCK_LEN_ERR) /= 0 then
         return Block_Length_Error;
      elsif (R1 and SD_OCR_ERASE_SEQ_ERR) /= 0 then
         return Erase_Seq_Error;
      elsif (R1 and SD_OCR_BAD_ERASE_PARAM) /= 0 then
         return Bad_Erase_Parameter;
      elsif (R1 and SD_OCR_WRITE_PROT_VIOLATION) /= 0 then
         return Write_Protection_Violation;
      elsif (R1 and SD_OCR_LOCK_UNLOCK_FAILED) /= 0 then
         return Lock_Unlock_Failed;
      elsif (R1 and SD_OCR_COM_CRC_FAILED) /= 0 then
         return CRC_Check_Fail;
      elsif (R1 and SD_OCR_ILLEGAL_CMD) /= 0 then
         return Illegal_Cmd;
      elsif (R1 and SD_OCR_CARD_ECC_FAILED) /= 0 then
         return Card_ECC_Failed;
      elsif (R1 and SD_OCR_CC_ERROR) /= 0 then
         return CC_Error;
      elsif (R1 and SD_OCR_GENERAL_UNKNOWN_ERROR) /= 0 then
         return General_Unknown_Error;
      elsif (R1 and SD_OCR_STREAM_READ_UNDERRUN) /= 0 then
         return Stream_Read_Underrun;
      elsif (R1 and SD_OCR_STREAM_WRITE_UNDERRUN) /= 0 then
         return Stream_Write_Underrun;
      elsif (R1 and SD_OCR_CID_CSD_OVERWRITE) /= 0 then
         return CID_CSD_Overwrite;
      elsif (R1 and SD_OCR_WP_ERASE_SKIP) /= 0 then
         return WP_Erase_Skip;
      elsif (R1 and SD_OCR_CARD_ECC_DISABLED) /= 0 then
         return Card_ECC_Disabled;
      elsif (R1 and SD_OCR_ERASE_RESET) /= 0 then
         return Erase_Reset;
      elsif (R1 and SD_OCR_AKE_SEQ_ERROR) /= 0 then
         return AKE_SEQ_Error;
      else
         return General_Unknown_Error;
      end if;
   end Response_R1_Error;

   -----------------------
   -- Response_R2_Error --
   -----------------------

   function Response_R2_Error
     (Controller : in out SDMMC_Controller) return SD_Error
   is
   begin
      while not Controller.Periph.STA.CCRCFAIL
        and then not Controller.Periph.STA.CMDREND
        and then not Controller.Periph.STA.CTIMEOUT
      loop
         null;
      end loop;

      if Controller.Periph.STA.CTIMEOUT then
         --  Card is not v2.0 compliant or card does not support the set
         --  voltage range
         Controller.Periph.ICR.CTIMEOUTC := True;

         return Timeout_Error;

      elsif Controller.Periph.STA.CCRCFAIL then
         Controller.Periph.ICR.CCRCFAILC := True;

         return CRC_Check_Fail;
      end if;

      Clear_Static_Flags (Controller);

      return OK;
   end Response_R2_Error;

   -----------------------
   -- Response_R3_Error --
   -----------------------

   function Response_R3_Error
     (Controller : in out SDMMC_Controller) return SD_Error
   is
   begin
      while not Controller.Periph.STA.CCRCFAIL
        and then not Controller.Periph.STA.CMDREND
        and then not Controller.Periph.STA.CTIMEOUT
      loop
         null;
      end loop;

      if Controller.Periph.STA.CTIMEOUT then
         --  Card is not v2.0 compliant or card does not support the set
         --  voltage range
         Controller.Periph.ICR.CTIMEOUTC := True;

         return Timeout_Error;
      end if;

      Clear_Static_Flags (Controller);

      return OK;
   end Response_R3_Error;

   -----------------------
   -- Response_R6_Error --
   -----------------------

   function Response_R6_Error
     (Controller    : in out SDMMC_Controller;
      Command_Index : SD_Command;
      RCA           :    out UInt32) return SD_Error
   is
      Response : UInt32;
   begin
      while not Controller.Periph.STA.CCRCFAIL
        and then not Controller.Periph.STA.CMDREND
        and then not Controller.Periph.STA.CTIMEOUT
      loop
         null;
      end loop;

      if Controller.Periph.STA.CTIMEOUT then
         --  Card is not v2.0 compliant or card does not support the set
         --  voltage range
         Controller.Periph.ICR.CTIMEOUTC := True;

         return Timeout_Error;

      elsif Controller.Periph.STA.CCRCFAIL then
         Controller.Periph.ICR.CCRCFAILC := True;

         return CRC_Check_Fail;
      end if;

      if SD_Command (Controller.Periph.RESPCMD.RESPCMD) /=
        Command_Index
      then
         return Illegal_Cmd;
      end if;

      Clear_Static_Flags (Controller);

      Response := Controller.Periph.RESP1;

      if (Response and SD_R6_Illegal_Cmd) = SD_R6_Illegal_Cmd then
         return Illegal_Cmd;

      elsif (Response and SD_R6_General_Unknown_Error) =
        SD_R6_General_Unknown_Error
      then
         return General_Unknown_Error;

      elsif (Response and SD_R6_Com_CRC_Failed) = SD_R6_Com_CRC_Failed then
         return CRC_Check_Fail;
      end if;

      RCA := Response and 16#FFFF_0000#;

      return OK;
   end Response_R6_Error;

   -----------------------
   -- Response_R7_Error --
   -----------------------

   function Response_R7_Error
     (Controller : in out SDMMC_Controller) return SD_Error
   is
      Start : constant Time := Clock;
      Timeout : Boolean := False;
   begin
      while not Controller.Periph.STA.CCRCFAIL
        and then not Controller.Periph.STA.CMDREND
        and then not Controller.Periph.STA.CTIMEOUT
      loop
         if Clock - Start > Milliseconds (1000) then
            Timeout := True;

            exit;
         end if;
      end loop;

      if Timeout or else Controller.Periph.STA.CTIMEOUT then
         --  Card is not v2.0 compliant or card does not support the set
         --  voltage range
         Controller.Periph.ICR.CTIMEOUTC := True;

         return Timeout_Error;

      elsif Controller.Periph.STA.CCRCFAIL then
         Controller.Periph.ICR.CCRCFAILC := True;

         return CRC_Check_Fail;

      elsif Controller.Periph.STA.CMDREND then
         Controller.Periph.ICR.CMDRENDC := True;

         return OK;

      else
         return Error;
      end if;
   end Response_R7_Error;

   -------------------
   -- Stop_Transfer --
   -------------------

   function Stop_Transfer
     (This : in out SDMMC_Controller) return SD_Error
   is
      Ret : SD_Error;
   begin
      Send_Cmd (This, Cmd_Desc (Stop_Transmission), 0, Ret);

      return Ret;
   end Stop_Transfer;

   -----------------------
   -- Set_Clk_Src_Speed --
   -----------------------

   procedure Set_Clk_Src_Speed
     (This : in out SDMMC_Controller;
      CLK  : UInt32)
   is
   begin
      This.CLK_In := CLK;
   end Set_Clk_Src_Speed;

   ----------------
   -- Initialize --
   ----------------

   function Initialize
     (This      : in out SDMMC_Controller) return SD_Error
   is
      Ret : SD_Error;
   begin
      SDMMC_Init.Card_Identification_Process (This, This.Info, Ret);
      This.Card_Type := This.Info.Card_Type;
      This.RCA       := This.Info.RCA;

      return Ret;
   end Initialize;

   ----------
   -- Read --
   ----------

   overriding
   function Read
     (This         : in out SDMMC_Controller;
      Block_Number : UInt64;
      Data         : out HAL.Block_Drivers.Block) return Boolean
   is
      Ret     : Boolean;
      SD_Err  : SD_Error;
      DMA_Err : DMA_Error_Code;
   begin

      Ensure_Card_Informations (This);

      if This.RX_DMA_Int = null or else This.SD_Int = null then
         SD_Err := Read_Blocks
           (This,
            Block_Number * 512,
            Data);
         return SD_Err = OK;
      end if;

      This.SD_Int.Set_Transfer_State (This);

      SD_Err := Read_Blocks_DMA
        (This,
         Block_Number * 512,
         Data);

      if SD_Err /= OK then
         This.RX_DMA_Int.Clear_Transfer_State;
         This.SD_Int.Clear_Transfer_State;
         This.RX_DMA_Int.Abort_Transfer (DMA_Err);

         return False;
      end if;

      This.SD_Int.Wait_Transfer (SD_Err);

      if SD_Err /= OK then
         This.RX_DMA_Int.Clear_Transfer_State;
      else
         This.RX_DMA_Int.Wait_For_Completion (DMA_Err);

         loop
            exit when not Get_Flag (This, RX_Active);
         end loop;
      end if;

      Ret := SD_Err = OK and then DMA_Err = DMA_No_Error;

      if Last_Operation (This) =
        Read_Multiple_Blocks_Operation
      then
         SD_Err := Stop_Transfer (This);
         Ret := Ret and then SD_Err = OK;
      end if;

      Clear_All_Status (This.RX_DMA_Int.Controller.all, This.RX_DMA_Int.Stream);
      Disable (This.RX_DMA_Int.Controller.all, This.RX_DMA_Int.Stream);
      Disable_Data (This);
      Clear_Static_Flags (This);

      Cortex_M.Cache.Invalidate_DCache
        (Start => Data'Address,
         Len   => Data'Length);

      return Ret;
   end Read;

   -----------
   -- Write --
   -----------

   overriding
   function Write
     (This         : in out SDMMC_Controller;
      Block_Number : UInt64;
      Data         : HAL.Block_Drivers.Block) return Boolean
   is
      Ret     : SD_Error;
      DMA_Err : DMA_Error_Code;
   begin
      if This.TX_DMA_Int = null then
         raise Program_Error with "No TX DMA controller";
      end if;

      if This.SD_Int = null then
         raise Program_Error with "No SD interrupt controller";
      end if;

      Ensure_Card_Informations (This);

      --  Flush the data cache
      Cortex_M.Cache.Clean_DCache
        (Start => Data (Data'First)'Address,
         Len   => Data'Length);

      This.SD_Int.Set_Transfer_State (This);

      Ret := Write_Blocks_DMA
        (This,
         Block_Number * 512,
         Data);
      --  this always leaves the last 12 byte standing. Why?
      --  also...NDTR is not what it should be.

      if Ret /= OK then
         This.TX_DMA_Int.Clear_Transfer_State;
         This.SD_Int.Clear_Transfer_State;
         This.TX_DMA_Int.Abort_Transfer (DMA_Err);

         return False;
      end if;

      This.TX_DMA_Int.Wait_For_Completion (DMA_Err); -- this unblocks
      This.SD_Int.Wait_Transfer (Ret); -- TX underrun!

      --  this seems slow. Do we have to wait?
      loop
         --  FIXME: some people claim, that this goes wrong with multiblock, see
         --  http://blog.frankvh.com/2011/09/04/stm32f2xx-sdio-sd-card-interface/
         exit when not Get_Flag (This, TX_Active);
      end loop;

      if Last_Operation (This) =
        Write_Multiple_Blocks_Operation
      then
         Ret := Stop_Transfer (This);
      end if;

      Clear_All_Status (This.TX_DMA_Int.Controller.all, This.TX_DMA_Int.Stream);
      Disable (This.TX_DMA_Int.Controller.all, This.TX_DMA_Int.Stream);

      declare
         Data_Incomplete : constant Boolean :=
                             This.TX_DMA_Int.Buffer_Error and then
                                 Items_Transferred (This.TX_DMA_Int.Controller.all, This.TX_DMA_Int.Stream)
                                 /= Data'Length / 4;
      begin
         return Ret = OK
           and then DMA_Err = DMA_No_Error
           and then not Data_Incomplete;
      end;
   end Write;


   -----------------
   -- Read_Blocks --
   -----------------

   function Read_Blocks
     (This : in out SDMMC_Controller;
      Addr : UInt64;
      Data : out HAL.Block_Drivers.Block) return SD_Error
   is
      subtype UInt32_Data is HAL.Block_Drivers.Block (1 .. 4);
      function To_Data is new Ada.Unchecked_Conversion
        (UInt32, UInt32_Data);
      R_Addr   : UInt64 := Addr;
      N_Blocks : Positive;
      Err      : SD_Error;
      Idx      : Natural := Data'First;
      Dead     : UInt32 with Unreferenced;

   begin
      DCTRL_Write_Delay;
      This.Periph.DCTRL := (others => <>);

      if This.Card_Type = High_Capacity_SD_Card then
         R_Addr := Addr / 512;
      end if;

      N_Blocks := Data'Length / 512;

      Send_Cmd
        (This,
         Cmd    => Set_Blocklen,
         Arg    => 512,
         Status => Err);

      if Err /= OK then
         return Err;
      end if;

      Configure_Data
        (This,
         Data_Length        => Data'Length,
         Data_Block_Size    => Block_512B,
         Transfer_Direction => Read,
         Transfer_Mode      => Block,
         DPSM               => True,
         DMA_Enabled        => False);

      if N_Blocks > 1 then
         This.Operation := Read_Multiple_Blocks_Operation;
         Send_Cmd (This, Read_Multi_Block, UInt32 (R_Addr), Err);
      else
         This.Operation := Read_Single_Block_Operation;
         Send_Cmd (This, Read_Single_Block, UInt32 (R_Addr), Err);
      end if;

      if Err /= OK then
         return Err;
      end if;

      if N_Blocks > 1 then
         --  Poll on SDMMC flags
         while not This.Periph.STA.RXOVERR
           and then not This.Periph.STA.DCRCFAIL
           and then not This.Periph.STA.DTIMEOUT
           and then not This.Periph.STA.DATAEND
         loop
            if This.Periph.STA.RXFIFOHF then
               for J in 1 .. 8 loop
                  Data (Idx .. Idx + 3) :=
                    To_Data (Read_FIFO (This));
                  Idx := Idx + 4;
               end loop;
            end if;
         end loop;

      else
         --  Poll on SDMMC flags
         while not This.Periph.STA.RXOVERR
           and then not This.Periph.STA.DCRCFAIL
           and then not This.Periph.STA.DTIMEOUT
           and then not This.Periph.STA.DBCKEND
         loop
            if This.Periph.STA.RXFIFOHF then
               for J in 1 .. 8 loop
                  Data (Idx .. Idx + 3) :=
                    To_Data (Read_FIFO (This));
                  Idx := Idx + 4;
               end loop;
            end if;
         end loop;
      end if;

      if N_Blocks > 1 and then This.Periph.STA.DATAEND then
         Err := Stop_Transfer (This);
      end if;

      if This.Periph.STA.DTIMEOUT then
         This.Periph.ICR.DTIMEOUTC := True;
         return Timeout_Error;

      elsif This.Periph.STA.DCRCFAIL then
         This.Periph.ICR.DCRCFAILC := True;
         return CRC_Check_Fail;

      elsif This.Periph.STA.RXOVERR then
         This.Periph.ICR.RXOVERRC := True;
         return Rx_Overrun;

      elsif This.Periph.STA.STBITERR then
         This.Periph.ICR.STBITERRC := True;
         return Startbit_Not_Detected;
      end if;

      for J in UInt32'(1) .. SD_DATATIMEOUT loop
         exit when not This.Periph.STA.RXDAVL;
         Dead := Read_FIFO (This);
      end loop;

      Clear_Static_Flags (This);

      return Err;
   end Read_Blocks;

   ---------------------
   -- Read_Blocks_DMA --
   ---------------------

   function Read_Blocks_DMA
     (This : in out SDMMC_Controller;
      Addr :        UInt64;
      Data :    out HAL.Block_Drivers.Block) return SD_Error
   is
      Read_Address : constant UInt64 :=
                       (if This.Card_Type = High_Capacity_SD_Card
                        then Addr / 512 else Addr);

      Data_Len_Bytes : constant Natural := (Data'Length / 512) * 512;
      Data_Len_Words : constant Natural := Data_Len_Bytes / 4;
      N_Blocks       : constant Natural := Data_Len_Bytes / 512;
      Data_Addr      : constant Address := Data (Data'First)'Address;

      Err            : SD_Error;
      Command        : SD_Command;
   begin
      if not STM32.DMA.Compatible_Alignments
        (This.RX_DMA_Int.Controller.all,
         This.RX_DMA_Int.Stream,
         This.Periph.FIFO'Address,
         Data_Addr)
      then
         return DMA_Alignment_Error;
      end if;

      --  After a data write, data cannot be written to this register
      --  for three SDMMCCLK (@ 48 MHz) clock periods plus two PCLK2 clock
      --  periods (@ ~90MHz).
      --  So here we make sure the DCTRL is writable
      DCTRL_Write_Delay;
      This.Periph.DCTRL := (DTEN   => False,
                            others => <>);

      Enable_Interrupt (This, Data_CRC_Fail_Interrupt);
      Enable_Interrupt (This, Data_Timeout_Interrupt);
      Enable_Interrupt (This, Data_End_Interrupt);
      Enable_Interrupt (This, RX_Overrun_Interrupt);

      This.RX_DMA_Int.Start_Transfer (Source      => This.Periph.FIFO'Address,
                                      Destination => Data_Addr,
                                      Data_Count  => UInt16 (Data_Len_Words)); -- because DMA is set up with words

      Send_Cmd (This, Set_Blocklen, 512, Err);

      if Err /= OK then
         return Err;
      end if;

      Configure_Data
        (This,
         Data_Length        => UInt25 (N_Blocks) * 512,
         Data_Block_Size    => Block_512B,
         Transfer_Direction => Read,
         Transfer_Mode      => Block,
         DPSM               => True,
         DMA_Enabled        => True);

      if N_Blocks > 1 then
         Command := Read_Multi_Block;
         This.Operation := Read_Multiple_Blocks_Operation;
      else
         Command := Read_Single_Block;
         This.Operation := Read_Single_Block_Operation;
      end if;

      Send_Cmd (This, Command, UInt32 (Read_Address), Err);

      return Err;
   end Read_Blocks_DMA;

   ----------------------
   -- Write_Blocks_DMA --
   ----------------------

   function Write_Blocks_DMA
     (This : in out SDMMC_Controller;
      Addr :        UInt64;
      Data :        HAL.Block_Drivers.Block) return SD_Error
   is
      Write_Address : constant UInt64 :=
                       (if This.Card_Type = High_Capacity_SD_Card
                        then Addr / 512 else Addr);
      --  512 is the min. block size of SD 2.0 card

      Data_Len_Bytes : constant Natural := (Data'Length / 512) * 512;
      Data_Len_Words : constant Natural := Data_Len_Bytes / 4;
      N_Blocks       : constant Natural := Data_Len_Bytes / 512;
      Data_Addr      : constant Address := Data (Data'First)'Address;

      Err        : SD_Error;
      Cardstatus : HAL.UInt32;
      Start      : constant Time := Clock;
      Timeout    : Boolean := False;
      Command    : SD_Command;
      Rca        : constant UInt32 := Shift_Left (UInt32 (This.RCA), 16);
   begin

      if not STM32.DMA.Compatible_Alignments
        (This.TX_DMA_Int.Controller.all,
         This.TX_DMA_Int.Stream,
         This.Periph.FIFO'Address,
         Data_Addr)
      then
         return DMA_Alignment_Error;
      end if;

      DCTRL_Write_Delay;
      This.Periph.DCTRL := (DTEN   => False,
                                  others => <>);
      --  After a data write, data cannot be written to this register
      --  for three SDMMCCLK (48 MHz) clock periods plus two PCLK2 clock
      --  periods.
      DCTRL_Write_Delay;

      Clear_Static_Flags (This);

      --  wait until card is ready for data added
      Wait_Ready_Loop :
      loop
         if Clock - Start > Milliseconds (100) then
            Timeout := True;
            exit Wait_Ready_Loop;
         end if;

         Send_Cmd (This, Send_Status, Rca, Err);

         if Err /= OK then
            return Err;
         end if;

         Cardstatus := This.Periph.RESP1;
         exit Wait_Ready_Loop when (Cardstatus and 16#100#) /= 0;
      end loop Wait_Ready_Loop;

      if Timeout then
         return Timeout_Error;
      end if;

      Enable_Interrupt (This, Data_CRC_Fail_Interrupt);
      Enable_Interrupt (This, Data_Timeout_Interrupt);
      Enable_Interrupt (This, Data_End_Interrupt);
      Enable_Interrupt (This, TX_Underrun_Interrupt);

      This.TX_DMA_Int.Start_Transfer (Source      => Data_Addr,
                                      Destination => This.Periph.FIFO'Address,
                                      Data_Count  => UInt16 (Data_Len_Words)); -- DMA uses words

      --  set block size
      Send_Cmd (This, Set_Blocklen, 512, Err);

      if Err /= OK then
         return Err;
      end if;

      --  set write address & single/multi mode
      if N_Blocks > 1 then
         Command := Write_Multi_Block;
         This.Operation := Write_Multiple_Blocks_Operation;
      else
         Command := Write_Single_Block;
         This.Operation := Write_Single_Block_Operation;
      end if;

      Send_Cmd (This, Command, UInt32 (Write_Address), Err);

      if Err /= OK then
         return Err;
      end if;

      --  and now enable the card with DTEN, which is this:
      Configure_Data
        (This,
         Data_Length        => UInt25 (N_Blocks) * 512,
         Data_Block_Size    => Block_512B,
         Transfer_Direction => Write,
         Transfer_Mode      => Block,
         DPSM               => True,
         DMA_Enabled        => True);

      --  according to RM0090: wait for STA[10]=DBCKEND
      --  check that no channels are still enabled by polling DMA Enabled
      --  Channel Status Reg

      return Err;
   end Write_Blocks_DMA;

   -------------------------
   -- Get_Transfer_Status --
   -------------------------

   function Get_Transfer_Status
     (This : in out SDMMC_Controller) return SD_Error
   is
   begin
      if This.Periph.STA.DTIMEOUT then
         This.Periph.ICR.DTIMEOUTC := True;
         return Timeout_Error;

      elsif This.Periph.STA.DCRCFAIL then
         This.Periph.ICR.DCRCFAILC := True; -- clear
         return CRC_Check_Fail;

      elsif This.Periph.STA.TXUNDERR then
         This.Periph.ICR.TXUNDERRC := True;
         return Tx_Underrun;

      elsif This.Periph.STA.STBITERR then
         This.Periph.ICR.STBITERRC := True;
         return Startbit_Not_Detected;

      elsif This.Periph.STA.RXOVERR then
         This.Periph.ICR.RXOVERRC := True;
         return Rx_Overrun;
      end if;

      return OK;
   end Get_Transfer_Status;

end STM32.SDMMC;