~aleteoryx/muditaos

ref: 4b8543912a8c17f0563d7bd6fbe21bb9c143a153 muditaos/module-bsp/board/rt1051/common/fsl_drivers/fsl_usdhc.c -rw-r--r-- 60.1 KiB
4b854391 — rrandomsky [MOS-30] Fix for Alarm not being handled properly during a phone call 2 years ago
                                                                                
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
/*
 * The Clear BSD License
 * Copyright (c) 2016, Freescale Semiconductor, Inc.
 * Copyright 2016-2017 NXP
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted (subject to the limitations in the disclaimer below) provided
 *  that the following conditions are met:
 *
 * o Redistributions of source code must retain the above copyright notice, this list
 *   of conditions and the following disclaimer.
 *
 * o 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.
 *
 * o 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.
 *
 * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE.
 * 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.
 */

#include "fsl_usdhc.h"
#if defined(FSL_SDK_ENABLE_DRIVER_CACHE_CONTROL) && FSL_SDK_ENABLE_DRIVER_CACHE_CONTROL
#include "fsl_cache.h"
#endif /* FSL_SDK_ENABLE_DRIVER_CACHE_CONTROL */

/*******************************************************************************
 * Definitions
 ******************************************************************************/

/* Component ID definition, used by tools. */
#ifndef FSL_COMPONENT_ID
#define FSL_COMPONENT_ID "platform.drivers.usdhc"
#endif

/*! @brief Clock setting */
/* Max SD clock divisor from base clock */
#define USDHC_MAX_DVS          ((USDHC_SYS_CTRL_DVS_MASK >> USDHC_SYS_CTRL_DVS_SHIFT) + 1U)
#define USDHC_MAX_CLKFS        ((USDHC_SYS_CTRL_SDCLKFS_MASK >> USDHC_SYS_CTRL_SDCLKFS_SHIFT) + 1U)
#define USDHC_PREV_DVS(x)      ((x) -= 1U)
#define USDHC_PREV_CLKFS(x, y) ((x) >>= (y))

/* Typedef for interrupt handler. */
typedef void (*usdhc_isr_t)(USDHC_Type *base, usdhc_handle_t *handle);
/*! @brief Dummy data buffer for mmc boot mode  */
AT_NONCACHEABLE_SECTION_ALIGN(uint32_t s_usdhcBootDummy, USDHC_ADMA2_ADDRESS_ALIGN);
/*******************************************************************************
 * Prototypes
 ******************************************************************************/
/*!
 * @brief Get the instance.
 *
 * @param base USDHC peripheral base address.
 * @return Instance number.
 */
static uint32_t USDHC_GetInstance(USDHC_Type *base);

/*!
 * @brief Set transfer interrupt.
 *
 * @param base USDHC peripheral base address.
 * @param usingInterruptSignal True to use IRQ signal.
 */
static void USDHC_SetTransferInterrupt(USDHC_Type *base, bool usingInterruptSignal);

/*!
 * @brief Start transfer according to current transfer state
 *
 * @param base USDHC peripheral base address.
 * @param data Data to be transferred.
 * @param flag data present flag
 */
static status_t USDHC_SetDataTransferConfig(USDHC_Type *base, usdhc_data_t *data, uint32_t *dataPresentFlag);

/*!
 * @brief Receive command response
 *
 * @param base USDHC peripheral base address.
 * @param command Command to be sent.
 */
static status_t USDHC_ReceiveCommandResponse(USDHC_Type *base, usdhc_command_t *command);

/*!
 * @brief Read DATAPORT when buffer enable bit is set.
 *
 * @param base USDHC peripheral base address.
 * @param data Data to be read.
 * @param transferredWords The number of data words have been transferred last time transaction.
 * @return The number of total data words have been transferred after this time transaction.
 */
static uint32_t USDHC_ReadDataPort(USDHC_Type *base, usdhc_data_t *data, uint32_t transferredWords);

/*!
 * @brief Read data by using DATAPORT polling way.
 *
 * @param base USDHC peripheral base address.
 * @param data Data to be read.
 * @retval kStatus_Fail Read DATAPORT failed.
 * @retval kStatus_Success Operate successfully.
 */
static status_t USDHC_ReadByDataPortBlocking(USDHC_Type *base, usdhc_data_t *data);

/*!
 * @brief Write DATAPORT when buffer enable bit is set.
 *
 * @param base USDHC peripheral base address.
 * @param data Data to be read.
 * @param transferredWords The number of data words have been transferred last time.
 * @return The number of total data words have been transferred after this time transaction.
 */
static uint32_t USDHC_WriteDataPort(USDHC_Type *base, usdhc_data_t *data, uint32_t transferredWords);

/*!
 * @brief Write data by using DATAPORT polling way.
 *
 * @param base USDHC peripheral base address.
 * @param data Data to be transferred.
 * @retval kStatus_Fail Write DATAPORT failed.
 * @retval kStatus_Success Operate successfully.
 */
static status_t USDHC_WriteByDataPortBlocking(USDHC_Type *base, usdhc_data_t *data);

/*!
 * @brief Transfer data by polling way.
 *
 * @param base USDHC peripheral base address.
 * @param data Data to be transferred.
 * @param use DMA flag.
 * @retval kStatus_Fail Transfer data failed.
 * @retval kStatus_InvalidArgument Argument is invalid.
 * @retval kStatus_Success Operate successfully.
 */
static status_t USDHC_TransferDataBlocking(USDHC_Type *base, usdhc_data_t *data, bool enDMA);

/*!
 * @brief Handle card detect interrupt.
 *
 * @param base USDHC peripheral base address.
 * @param handle USDHC handle.
 * @param interruptFlags Card detect related interrupt flags.
 */
static void USDHC_TransferHandleCardDetect(USDHC_Type *base, usdhc_handle_t *handle, uint32_t interruptFlags);

/*!
 * @brief Handle command interrupt.
 *
 * @param base USDHC peripheral base address.
 * @param handle USDHC handle.
 * @param interruptFlags Command related interrupt flags.
 */
static void USDHC_TransferHandleCommand(USDHC_Type *base, usdhc_handle_t *handle, uint32_t interruptFlags);

/*!
 * @brief Handle data interrupt.
 *
 * @param base USDHC peripheral base address.
 * @param handle USDHC handle.
 * @param interruptFlags Data related interrupt flags.
 */
static void USDHC_TransferHandleData(USDHC_Type *base, usdhc_handle_t *handle, uint32_t interruptFlags);

/*!
 * @brief Handle SDIO card interrupt signal.
 *
 * @param base USDHC peripheral base address.
 * @param handle USDHC handle.
 */
static void USDHC_TransferHandleSdioInterrupt(USDHC_Type *base, usdhc_handle_t *handle);

/*!
 * @brief Handle SDIO block gap event.
 *
 * @param base USDHC peripheral base address.
 * @param handle USDHC handle.
 */
static void USDHC_TransferHandleBlockGap(USDHC_Type *base, usdhc_handle_t *handle);

/*!
 * @brief Handle retuning
 *
 * @param base USDHC peripheral base address.
 * @param handle USDHC handle.
 * @param interrupt flags
 */
static void USDHC_TransferHandleReTuning(USDHC_Type *base, usdhc_handle_t *handle, uint32_t interruptFlags);

/*!
 * @brief wait command done
 *
 * @param base USDHC peripheral base address.
 * @param command configuration
 * @param pollingCmdDone polling command done flag
 */
static status_t USDHC_WaitCommandDone(USDHC_Type *base, usdhc_command_t *command, bool pollingCmdDone);

/*******************************************************************************
 * Variables
 ******************************************************************************/
/*! @brief USDHC base pointer array */
static USDHC_Type *const s_usdhcBase[] = USDHC_BASE_PTRS;

/*! @brief USDHC internal handle pointer array */
static usdhc_handle_t *s_usdhcHandle[ARRAY_SIZE(s_usdhcBase)] = {NULL};

/*! @brief USDHC IRQ name array */
static const IRQn_Type s_usdhcIRQ[] = USDHC_IRQS;

#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
/*! @brief USDHC clock array name */
static const clock_ip_name_t s_usdhcClock[] = USDHC_CLOCKS;
#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */

/* USDHC ISR for transactional APIs. */
static usdhc_isr_t s_usdhcIsr;

/*******************************************************************************
 * Code
 ******************************************************************************/
static uint32_t USDHC_GetInstance(USDHC_Type *base)
{
    uint8_t instance = 0;

    while ((instance < ARRAY_SIZE(s_usdhcBase)) && (s_usdhcBase[instance] != base)) {
        instance++;
    }

    assert(instance < ARRAY_SIZE(s_usdhcBase));

    return instance;
}

static void USDHC_SetTransferInterrupt(USDHC_Type *base, bool usingInterruptSignal)
{
    uint32_t interruptEnabled; /* The Interrupt status flags to be enabled */

    /* Disable all interrupts */
    USDHC_DisableInterruptStatus(base, (uint32_t)kUSDHC_AllInterruptFlags);
    USDHC_DisableInterruptSignal(base, (uint32_t)kUSDHC_AllInterruptFlags);
    DisableIRQ(s_usdhcIRQ[USDHC_GetInstance(base)]);

    interruptEnabled = (kUSDHC_CommandFlag | kUSDHC_CardInsertionFlag | kUSDHC_DataFlag | kUSDHC_CardRemovalFlag |
                        kUSDHC_SDR104TuningFlag | kUSDHC_BlockGapEventFlag);

    USDHC_EnableInterruptStatus(base, interruptEnabled);

    if (usingInterruptSignal) {
        USDHC_EnableInterruptSignal(base, interruptEnabled);
    }
}

static status_t USDHC_SetDataTransferConfig(USDHC_Type *base, usdhc_data_t *data, uint32_t *dataPresentFlag)
{
    uint32_t mixCtrl = base->MIX_CTRL;

    if (data != NULL) {
        /* if transfer boot continous, only need set the CREQ bit, leave others as it is */
        if (data->dataType == kUSDHC_TransferDataBootcontinous) {
            /* clear stop at block gap request */
            base->PROT_CTRL &= ~USDHC_PROT_CTRL_SABGREQ_MASK;
            /* continous transfer data */
            base->PROT_CTRL |= USDHC_PROT_CTRL_CREQ_MASK;
            return kStatus_Success;
        }

        /* check data inhibit flag */
        if (base->PRES_STATE & kUSDHC_DataInhibitFlag) {
            return kStatus_USDHC_BusyTransferring;
        }
        /* check transfer block count */
        if ((data->blockCount > USDHC_MAX_BLOCK_COUNT) || ((data->txData == NULL) && (data->rxData == NULL))) {
            return kStatus_InvalidArgument;
        }

        /* config mix parameter */
        mixCtrl &= ~(USDHC_MIX_CTRL_MSBSEL_MASK | USDHC_MIX_CTRL_BCEN_MASK | USDHC_MIX_CTRL_DTDSEL_MASK |
                     USDHC_MIX_CTRL_AC12EN_MASK);

        if (data->rxData) {
            mixCtrl |= USDHC_MIX_CTRL_DTDSEL_MASK;
        }
        if (data->blockCount > 1U) {
            mixCtrl |= USDHC_MIX_CTRL_MSBSEL_MASK | USDHC_MIX_CTRL_BCEN_MASK;
            /* auto command 12 */
            if (data->enableAutoCommand12) {
                mixCtrl |= USDHC_MIX_CTRL_AC12EN_MASK;
            }
        }

        /* auto command 23, auto send set block count cmd before multiple read/write */
        if ((data->enableAutoCommand23)) {
            mixCtrl |= USDHC_MIX_CTRL_AC23EN_MASK;
            base->VEND_SPEC2 |= USDHC_VEND_SPEC2_ACMD23_ARGU2_EN_MASK;
            /* config the block count to DS_ADDR */
            base->DS_ADDR = data->blockCount;
        }
        else {
            mixCtrl &= ~USDHC_MIX_CTRL_AC23EN_MASK;
            base->VEND_SPEC2 &= ~USDHC_VEND_SPEC2_ACMD23_ARGU2_EN_MASK;
        }

        /* if transfer boot data, leave the block count to USDHC_SetMmcBootConfig function */
        if (data->dataType != kUSDHC_TransferDataBoot) {
            /* config data block size/block count */
            base->BLK_ATT = ((base->BLK_ATT & ~(USDHC_BLK_ATT_BLKSIZE_MASK | USDHC_BLK_ATT_BLKCNT_MASK)) |
                             (USDHC_BLK_ATT_BLKSIZE(data->blockSize) | USDHC_BLK_ATT_BLKCNT(data->blockCount)));
        }
        else {
            mixCtrl |= USDHC_MIX_CTRL_MSBSEL_MASK | USDHC_MIX_CTRL_BCEN_MASK;
            base->PROT_CTRL |= USDHC_PROT_CTRL_RD_DONE_NO_8CLK_MASK;
        }

        /* data present flag */
        *dataPresentFlag |= kUSDHC_DataPresentFlag;
    }
    else {
        /* clear data flags */
        mixCtrl &= ~(USDHC_MIX_CTRL_MSBSEL_MASK | USDHC_MIX_CTRL_BCEN_MASK | USDHC_MIX_CTRL_DTDSEL_MASK |
                     USDHC_MIX_CTRL_AC12EN_MASK);

        if (base->PRES_STATE & kUSDHC_CommandInhibitFlag) {
            return kStatus_USDHC_BusyTransferring;
        }
    }

    /* config the mix parameter */
    base->MIX_CTRL = mixCtrl;

    return kStatus_Success;
}

static status_t USDHC_ReceiveCommandResponse(USDHC_Type *base, usdhc_command_t *command)
{
    uint32_t i;

    if (command->responseType != kCARD_ResponseTypeNone) {
        command->response[0U] = base->CMD_RSP0;
        if (command->responseType == kCARD_ResponseTypeR2) {
            command->response[1U] = base->CMD_RSP1;
            command->response[2U] = base->CMD_RSP2;
            command->response[3U] = base->CMD_RSP3;

            i = 4U;
            /* R3-R2-R1-R0(lowest 8 bit is invalid bit) has the same format as R2 format in SD specification document
            after removed internal CRC7 and end bit. */
            do {
                command->response[i - 1U] <<= 8U;
                if (i > 1U) {
                    command->response[i - 1U] |= ((command->response[i - 2U] & 0xFF000000U) >> 24U);
                }
            } while (i--);
        }
    }
    /* check response error flag */
    if ((command->responseErrorFlags != 0U) &&
        ((command->responseType == kCARD_ResponseTypeR1) || (command->responseType == kCARD_ResponseTypeR1b) ||
         (command->responseType == kCARD_ResponseTypeR6) || (command->responseType == kCARD_ResponseTypeR5))) {
        if (((command->responseErrorFlags) & (command->response[0U])) != 0U) {
            return kStatus_USDHC_SendCommandFailed;
        }
    }

    return kStatus_Success;
}

static uint32_t USDHC_ReadDataPort(USDHC_Type *base, usdhc_data_t *data, uint32_t transferredWords)
{
    uint32_t i;
    uint32_t totalWords;
    uint32_t wordsCanBeRead; /* The words can be read at this time. */
    uint32_t readWatermark = ((base->WTMK_LVL & USDHC_WTMK_LVL_RD_WML_MASK) >> USDHC_WTMK_LVL_RD_WML_SHIFT);

    /* If DMA is enable, do not need to polling data port */
    if ((base->MIX_CTRL & USDHC_MIX_CTRL_DMAEN_MASK) == 0U) {
        /*
         * Add non aligned access support ,user need make sure your buffer size is big
         * enough to hold the data,in other words,user need make sure the buffer size
         * is 4 byte aligned
         */
        if (data->blockSize % sizeof(uint32_t) != 0U) {
            data->blockSize +=
                sizeof(uint32_t) - (data->blockSize % sizeof(uint32_t)); /* make the block size as word-aligned */
        }

        totalWords = ((data->blockCount * data->blockSize) / sizeof(uint32_t));

        /* If watermark level is equal or bigger than totalWords, transfers totalWords data. */
        if (readWatermark >= totalWords) {
            wordsCanBeRead = totalWords;
        }
        /* If watermark level is less than totalWords and left words to be sent is equal or bigger than readWatermark,
        transfers watermark level words. */
        else if ((readWatermark < totalWords) && ((totalWords - transferredWords) >= readWatermark)) {
            wordsCanBeRead = readWatermark;
        }
        /* If watermark level is less than totalWords and left words to be sent is less than readWatermark, transfers
        left
        words. */
        else {
            wordsCanBeRead = (totalWords - transferredWords);
        }

        i = 0U;
        while (i < wordsCanBeRead) {
            data->rxData[transferredWords++] = USDHC_ReadData(base);
            i++;
        }
    }

    return transferredWords;
}

static status_t USDHC_ReadByDataPortBlocking(USDHC_Type *base, usdhc_data_t *data)
{
    uint32_t totalWords;
    uint32_t transferredWords = 0U, interruptStatus = 0U;
    status_t error = kStatus_Success;

    /*
     * Add non aligned access support ,user need make sure your buffer size is big
     * enough to hold the data,in other words,user need make sure the buffer size
     * is 4 byte aligned
     */
    if (data->blockSize % sizeof(uint32_t) != 0U) {
        data->blockSize +=
            sizeof(uint32_t) - (data->blockSize % sizeof(uint32_t)); /* make the block size as word-aligned */
    }

    totalWords = ((data->blockCount * data->blockSize) / sizeof(uint32_t));

    while ((error == kStatus_Success) && (transferredWords < totalWords)) {
        while (!(interruptStatus & (kUSDHC_BufferReadReadyFlag | kUSDHC_DataErrorFlag | kUSDHC_TuningErrorFlag))) {
            interruptStatus = USDHC_GetInterruptStatusFlags(base);
        }

        /* during std tuning process, software do not need to read data, but wait BRR is enough */
        if ((data->dataType == kUSDHC_TransferDataTuning) && (interruptStatus & kUSDHC_BufferReadReadyFlag)) {
            USDHC_ClearInterruptStatusFlags(base, kUSDHC_BufferReadReadyFlag | kUSDHC_TuningPassFlag);

            return kStatus_Success;
        }
        else if ((interruptStatus & kUSDHC_TuningErrorFlag) != 0U) {
            USDHC_ClearInterruptStatusFlags(base, kUSDHC_TuningErrorFlag);
            /* if tuning error occur ,return directly */
            error = kStatus_USDHC_TuningError;
        }
        else if ((interruptStatus & kUSDHC_DataErrorFlag) != 0U) {
            if (!(data->enableIgnoreError)) {
                error = kStatus_Fail;
            }
            /* clear data error flag */
            USDHC_ClearInterruptStatusFlags(base, kUSDHC_DataErrorFlag);
        }
        else {
        }

        if (error == kStatus_Success) {
            transferredWords = USDHC_ReadDataPort(base, data, transferredWords);
            /* clear buffer read ready */
            USDHC_ClearInterruptStatusFlags(base, kUSDHC_BufferReadReadyFlag);
            interruptStatus = 0U;
        }
    }

    /* Clear data complete flag after the last read operation. */
    USDHC_ClearInterruptStatusFlags(base, kUSDHC_DataCompleteFlag);

    return error;
}

static uint32_t USDHC_WriteDataPort(USDHC_Type *base, usdhc_data_t *data, uint32_t transferredWords)
{
    uint32_t i;
    uint32_t totalWords;
    uint32_t wordsCanBeWrote; /* Words can be wrote at this time. */
    uint32_t writeWatermark = ((base->WTMK_LVL & USDHC_WTMK_LVL_WR_WML_MASK) >> USDHC_WTMK_LVL_WR_WML_SHIFT);

    /* If DMA is enable, do not need to polling data port */
    if ((base->MIX_CTRL & USDHC_MIX_CTRL_DMAEN_MASK) == 0U) {
        /*
         * Add non aligned access support ,user need make sure your buffer size is big
         * enough to hold the data,in other words,user need make sure the buffer size
         * is 4 byte aligned
         */
        if (data->blockSize % sizeof(uint32_t) != 0U) {
            data->blockSize +=
                sizeof(uint32_t) - (data->blockSize % sizeof(uint32_t)); /* make the block size as word-aligned */
        }

        totalWords = ((data->blockCount * data->blockSize) / sizeof(uint32_t));

        /* If watermark level is equal or bigger than totalWords, transfers totalWords data.*/
        if (writeWatermark >= totalWords) {
            wordsCanBeWrote = totalWords;
        }
        /* If watermark level is less than totalWords and left words to be sent is equal or bigger than watermark,
        transfers watermark level words. */
        else if ((writeWatermark < totalWords) && ((totalWords - transferredWords) >= writeWatermark)) {
            wordsCanBeWrote = writeWatermark;
        }
        /* If watermark level is less than totalWords and left words to be sent is less than watermark, transfers left
        words. */
        else {
            wordsCanBeWrote = (totalWords - transferredWords);
        }

        i = 0U;
        while (i < wordsCanBeWrote) {
            USDHC_WriteData(base, data->txData[transferredWords++]);
            i++;
        }
    }

    return transferredWords;
}

static status_t USDHC_WriteByDataPortBlocking(USDHC_Type *base, usdhc_data_t *data)
{
    uint32_t totalWords;

    uint32_t transferredWords = 0U, interruptStatus = 0U;
    status_t error = kStatus_Success;

    /*
     * Add non aligned access support ,user need make sure your buffer size is big
     * enough to hold the data,in other words,user need make sure the buffer size
     * is 4 byte aligned
     */
    if (data->blockSize % sizeof(uint32_t) != 0U) {
        data->blockSize +=
            sizeof(uint32_t) - (data->blockSize % sizeof(uint32_t)); /* make the block size as word-aligned */
    }

    totalWords = (data->blockCount * data->blockSize) / sizeof(uint32_t);

    while ((error == kStatus_Success) && (transferredWords < totalWords)) {
        while (!(interruptStatus & (kUSDHC_BufferWriteReadyFlag | kUSDHC_DataErrorFlag | kUSDHC_TuningErrorFlag))) {
            interruptStatus = USDHC_GetInterruptStatusFlags(base);
        }

        if ((interruptStatus & kUSDHC_TuningErrorFlag) != 0U) {
            USDHC_ClearInterruptStatusFlags(base, kUSDHC_TuningErrorFlag);
            /* if tuning error occur ,return directly */
            return kStatus_USDHC_TuningError;
        }
        else if ((interruptStatus & kUSDHC_DataErrorFlag) != 0U) {
            if (!(data->enableIgnoreError)) {
                error = kStatus_Fail;
            }
            /* clear data error flag */
            USDHC_ClearInterruptStatusFlags(base, kUSDHC_DataErrorFlag);
        }
        else {
        }

        if (error == kStatus_Success) {
            transferredWords = USDHC_WriteDataPort(base, data, transferredWords);
            /* clear buffer write ready */
            USDHC_ClearInterruptStatusFlags(base, kUSDHC_BufferWriteReadyFlag);
            interruptStatus = 0U;
        }
    }

    /* Wait write data complete or data transfer error after the last writing operation. */
    while (!(interruptStatus & (kUSDHC_DataCompleteFlag | kUSDHC_DataErrorFlag))) {
        interruptStatus = USDHC_GetInterruptStatusFlags(base);
    }

    if ((interruptStatus & kUSDHC_DataErrorFlag) != 0U) {
        if (!(data->enableIgnoreError)) {
            error = kStatus_Fail;
        }
    }
    USDHC_ClearInterruptStatusFlags(base, (kUSDHC_DataCompleteFlag | kUSDHC_DataErrorFlag));

    return error;
}

void USDHC_SendCommand(USDHC_Type *base, usdhc_command_t *command)
{
    assert(NULL != command);

    uint32_t xferType = base->CMD_XFR_TYP, flags = command->flags;

    if (((base->PRES_STATE & kUSDHC_CommandInhibitFlag) == 0U) && (command->type != kCARD_CommandTypeEmpty)) {
        /* Define the flag corresponding to each response type. */
        switch (command->responseType) {
        case kCARD_ResponseTypeNone:
            break;
        case kCARD_ResponseTypeR1: /* Response 1 */
        case kCARD_ResponseTypeR5: /* Response 5 */
        case kCARD_ResponseTypeR6: /* Response 6 */
        case kCARD_ResponseTypeR7: /* Response 7 */
            flags |= (kUSDHC_ResponseLength48Flag | kUSDHC_EnableCrcCheckFlag | kUSDHC_EnableIndexCheckFlag);
            break;

        case kCARD_ResponseTypeR1b: /* Response 1 with busy */
        case kCARD_ResponseTypeR5b: /* Response 5 with busy */
            flags |= (kUSDHC_ResponseLength48BusyFlag | kUSDHC_EnableCrcCheckFlag | kUSDHC_EnableIndexCheckFlag);
            break;

        case kCARD_ResponseTypeR2: /* Response 2 */
            flags |= (kUSDHC_ResponseLength136Flag | kUSDHC_EnableCrcCheckFlag);
            break;

        case kCARD_ResponseTypeR3: /* Response 3 */
        case kCARD_ResponseTypeR4: /* Response 4 */
            flags |= (kUSDHC_ResponseLength48Flag);
            break;

        default:
            break;
        }

        if (command->type == kCARD_CommandTypeAbort) {
            flags |= kUSDHC_CommandTypeAbortFlag;
        }

        /* config cmd index */
        xferType &= ~(USDHC_CMD_XFR_TYP_CMDINX_MASK | USDHC_CMD_XFR_TYP_CMDTYP_MASK | USDHC_CMD_XFR_TYP_CICEN_MASK |
                      USDHC_CMD_XFR_TYP_CCCEN_MASK | USDHC_CMD_XFR_TYP_RSPTYP_MASK | USDHC_CMD_XFR_TYP_DPSEL_MASK);

        xferType |=
            (((command->index << USDHC_CMD_XFR_TYP_CMDINX_SHIFT) & USDHC_CMD_XFR_TYP_CMDINX_MASK) |
             ((flags) & (USDHC_CMD_XFR_TYP_CMDTYP_MASK | USDHC_CMD_XFR_TYP_CICEN_MASK | USDHC_CMD_XFR_TYP_CCCEN_MASK |
                         USDHC_CMD_XFR_TYP_RSPTYP_MASK | USDHC_CMD_XFR_TYP_DPSEL_MASK)));

        /* config the command xfertype and argument */
        base->CMD_ARG     = command->argument;
        base->CMD_XFR_TYP = xferType;
    }

    if (command->type == kCARD_CommandTypeEmpty) {
        /* disable CMD done interrupt for empty command */
        base->INT_SIGNAL_EN &= ~USDHC_INT_SIGNAL_EN_CCIEN_MASK;
    }
}

static status_t USDHC_WaitCommandDone(USDHC_Type *base, usdhc_command_t *command, bool pollingCmdDone)
{
    assert(NULL != command);

    status_t error           = kStatus_Success;
    uint32_t interruptStatus = 0U;
    /* check if need polling command done or not */
    if (pollingCmdDone) {
        /* Wait command complete or USDHC encounters error. */
        while (!(interruptStatus & (kUSDHC_CommandCompleteFlag | kUSDHC_CommandErrorFlag))) {
            interruptStatus = USDHC_GetInterruptStatusFlags(base);
        }

        if ((interruptStatus & kUSDHC_TuningErrorFlag) != 0U) {
            error = kStatus_USDHC_TuningError;
        }
        else if ((interruptStatus & kUSDHC_CommandErrorFlag) != 0U) {
            error = kStatus_Fail;
        }
        else {
        }
        /* Receive response when command completes successfully. */
        if (error == kStatus_Success) {
            error = USDHC_ReceiveCommandResponse(base, command);
        }

        USDHC_ClearInterruptStatusFlags(
            base, (kUSDHC_CommandCompleteFlag | kUSDHC_CommandErrorFlag | kUSDHC_TuningErrorFlag));
    }

    return error;
}

static status_t USDHC_TransferDataBlocking(USDHC_Type *base, usdhc_data_t *data, bool enDMA)
{
    status_t error           = kStatus_Success;
    uint32_t interruptStatus = 0U;

    if (enDMA) {
        /* Wait data complete or USDHC encounters error. */
        while (!((interruptStatus &
                  (kUSDHC_DataCompleteFlag | kUSDHC_DataErrorFlag | kUSDHC_DmaErrorFlag | kUSDHC_TuningErrorFlag)))) {
            interruptStatus = USDHC_GetInterruptStatusFlags(base);
        }

        if ((interruptStatus & kUSDHC_TuningErrorFlag) != 0U) {
            error = kStatus_USDHC_TuningError;
        }
        else if (((interruptStatus & (kUSDHC_DataErrorFlag | kUSDHC_DmaErrorFlag)) != 0U)) {
            if ((!(data->enableIgnoreError)) || (interruptStatus & kUSDHC_DataTimeoutFlag)) {
                error = kStatus_Fail;
            }
        }
        else {
        }
        /* load dummy data */
        if ((data->dataType == kUSDHC_TransferDataBootcontinous) && (error == kStatus_Success)) {
            *(data->rxData) = s_usdhcBootDummy;
        }

        USDHC_ClearInterruptStatusFlags(base,
                                        (kUSDHC_DataCompleteFlag | kUSDHC_DataErrorFlag | kUSDHC_DmaErrorFlag |
                                         kUSDHC_TuningPassFlag | kUSDHC_TuningErrorFlag));
    }
    else {
        if (data->rxData) {
            error = USDHC_ReadByDataPortBlocking(base, data);
        }
        else {
            error = USDHC_WriteByDataPortBlocking(base, data);
        }
    }

    return error;
}

void USDHC_Init(USDHC_Type *base, const usdhc_config_t *config)
{
    assert(config);
    assert((config->writeWatermarkLevel >= 1U) && (config->writeWatermarkLevel <= 128U));
    assert((config->readWatermarkLevel >= 1U) && (config->readWatermarkLevel <= 128U));
    assert(config->writeBurstLen <= 16U);

    uint32_t proctl, sysctl, wml;

    /* Enable USDHC clock. */
    CLOCK_EnableClock(s_usdhcClock[USDHC_GetInstance(base)]);

    /* Reset USDHC. */
    USDHC_Reset(base, kUSDHC_ResetAll, 100U);

    proctl = base->PROT_CTRL;
    wml    = base->WTMK_LVL;
    sysctl = base->SYS_CTRL;

    proctl &= ~(USDHC_PROT_CTRL_EMODE_MASK | USDHC_PROT_CTRL_DMASEL_MASK);
    /* Endian mode*/
    proctl |= USDHC_PROT_CTRL_EMODE(config->endianMode);

    /* Watermark level */
    wml &= ~(USDHC_WTMK_LVL_RD_WML_MASK | USDHC_WTMK_LVL_WR_WML_MASK | USDHC_WTMK_LVL_RD_BRST_LEN_MASK |
             USDHC_WTMK_LVL_WR_BRST_LEN_MASK);
    wml |= (USDHC_WTMK_LVL_RD_WML(config->readWatermarkLevel) | USDHC_WTMK_LVL_WR_WML(config->writeWatermarkLevel) |
            USDHC_WTMK_LVL_RD_BRST_LEN(config->readBurstLen) | USDHC_WTMK_LVL_WR_BRST_LEN(config->writeBurstLen));

    /* config the data timeout value */
    sysctl &= ~USDHC_SYS_CTRL_DTOCV_MASK;
    sysctl |= USDHC_SYS_CTRL_DTOCV(config->dataTimeout);

    base->SYS_CTRL  = sysctl;
    base->WTMK_LVL  = wml;
    base->PROT_CTRL = proctl;

#if FSL_FEATURE_USDHC_HAS_EXT_DMA
    /* disable external DMA */
    base->VEND_SPEC &= ~USDHC_VEND_SPEC_EXT_DMA_EN_MASK;
#endif
    /* disable internal DMA and DDR mode */
    base->MIX_CTRL &= ~(USDHC_MIX_CTRL_DMAEN_MASK | USDHC_MIX_CTRL_DDR_EN_MASK);
    /* Enable interrupt status but doesn't enable interrupt signal. */
    USDHC_SetTransferInterrupt(base, false);
}

void USDHC_Deinit(USDHC_Type *base)
{
    /* Disable clock. */
    CLOCK_DisableClock(s_usdhcClock[USDHC_GetInstance(base)]);
}

bool USDHC_Reset(USDHC_Type *base, uint32_t mask, uint32_t timeout)
{
    base->SYS_CTRL |= (mask & (USDHC_SYS_CTRL_RSTA_MASK | USDHC_SYS_CTRL_RSTC_MASK | USDHC_SYS_CTRL_RSTD_MASK));
    /* Delay some time to wait reset success. */
    while ((base->SYS_CTRL & mask) != 0U) {
        if (timeout == 0U) {
            break;
        }
        timeout--;
    }

    return ((!timeout) ? false : true);
}

void USDHC_GetCapability(USDHC_Type *base, usdhc_capability_t *capability)
{
    assert(capability);

    uint32_t htCapability;
    uint32_t maxBlockLength;

    htCapability = base->HOST_CTRL_CAP;

    /* Get the capability of USDHC. */
    maxBlockLength             = ((htCapability & USDHC_HOST_CTRL_CAP_MBL_MASK) >> USDHC_HOST_CTRL_CAP_MBL_SHIFT);
    capability->maxBlockLength = (512U << maxBlockLength);
    /* Other attributes not in HTCAPBLT register. */
    capability->maxBlockCount = USDHC_MAX_BLOCK_COUNT;
    capability->flags = (htCapability & (kUSDHC_SupportAdmaFlag | kUSDHC_SupportHighSpeedFlag | kUSDHC_SupportDmaFlag |
                                         kUSDHC_SupportSuspendResumeFlag | kUSDHC_SupportV330Flag));
    capability->flags |= (htCapability & kUSDHC_SupportV300Flag);
    capability->flags |= (htCapability & kUSDHC_SupportV180Flag);
    capability->flags |=
        (htCapability & (kUSDHC_SupportDDR50Flag | kUSDHC_SupportSDR104Flag | kUSDHC_SupportSDR50Flag));
    /* USDHC support 4/8 bit data bus width. */
    capability->flags |= (kUSDHC_Support4BitFlag | kUSDHC_Support8BitFlag);
}

uint32_t USDHC_SetSdClock(USDHC_Type *base, uint32_t srcClock_Hz, uint32_t busClock_Hz)
{
    assert(srcClock_Hz != 0U);
    assert((busClock_Hz != 0U) && (busClock_Hz <= srcClock_Hz));

    uint32_t totalDiv         = 0U;
    uint32_t divisor          = 0U;
    uint32_t prescaler        = 0U;
    uint32_t sysctl           = 0U;
    uint32_t nearestFrequency = 0U;

    /* calucate total divisor first */
    if ((totalDiv = srcClock_Hz / busClock_Hz) > (USDHC_MAX_CLKFS * USDHC_MAX_DVS)) {
        return 0U;
    }

    if (totalDiv != 0U) {
        /* calucate the divisor (srcClock_Hz / divisor) <= busClock_Hz */
        if ((srcClock_Hz / totalDiv) > busClock_Hz) {
            totalDiv++;
        }

        /* divide the total divisor to div and prescaler */
        if (totalDiv > USDHC_MAX_DVS) {
            prescaler = totalDiv / USDHC_MAX_DVS;
            /* prescaler must be a value which equal 2^n and smaller than SDHC_MAX_CLKFS */
            while (((USDHC_MAX_CLKFS % prescaler) != 0U) || (prescaler == 1U)) {
                prescaler++;
            }
            /* calucate the divisor */
            divisor = totalDiv / prescaler;
            /* fine tuning the divisor until divisor * prescaler >= totalDiv */
            while ((divisor * prescaler) < totalDiv) {
                divisor++;
            }

            nearestFrequency = srcClock_Hz / (divisor == 0U ? 1U : divisor) / prescaler;
        }
        else {
            /* in this situation , divsior and SDCLKFS can generate same clock
            use SDCLKFS*/
            if ((USDHC_MAX_DVS % totalDiv) == 0U) {
                divisor   = 0U;
                prescaler = totalDiv;
            }
            else {
                divisor   = (totalDiv / 2U) + 1U; /* make sure the output frequency not bigger than target value */
                prescaler = 2U;
            }
            nearestFrequency = srcClock_Hz / totalDiv;
        }
    }
    /* in this condition , srcClock_Hz = busClock_Hz, */
    else {
        /* in DDR mode , set SDCLKFS to 0, divisor = 0, actually the
        totoal divider = 2U */
        divisor          = 0U;
        prescaler        = 0U;
        nearestFrequency = srcClock_Hz;
    }

    /* calucate the value write to register */
    if (divisor != 0U) {
        USDHC_PREV_DVS(divisor);
    }
    /* calucate the value write to register */
    if (prescaler != 0U) {
        USDHC_PREV_CLKFS(prescaler, 1U);
    }

    /* Set the SD clock frequency divisor, SD clock frequency select, data timeout counter value. */
    sysctl = base->SYS_CTRL;
    sysctl &= ~(USDHC_SYS_CTRL_DVS_MASK | USDHC_SYS_CTRL_SDCLKFS_MASK);
    sysctl |= (USDHC_SYS_CTRL_DVS(divisor) | USDHC_SYS_CTRL_SDCLKFS(prescaler));
    base->SYS_CTRL = sysctl;

    /* Wait until the SD clock is stable. */
    while (!(base->PRES_STATE & USDHC_PRES_STATE_SDSTB_MASK)) {}

    return nearestFrequency;
}

bool USDHC_SetCardActive(USDHC_Type *base, uint32_t timeout)
{
    base->SYS_CTRL |= USDHC_SYS_CTRL_INITA_MASK;
    /* Delay some time to wait card become active state. */
    while ((base->SYS_CTRL & USDHC_SYS_CTRL_INITA_MASK) == USDHC_SYS_CTRL_INITA_MASK) {
        if (!timeout) {
            break;
        }
        timeout--;
    }

    return ((!timeout) ? false : true);
}

void USDHC_EnableDDRMode(USDHC_Type *base, bool enable, uint32_t nibblePos)
{
    uint32_t prescaler = (base->SYS_CTRL & USDHC_SYS_CTRL_SDCLKFS_MASK) >> USDHC_SYS_CTRL_SDCLKFS_SHIFT;

    if (enable) {
        base->MIX_CTRL &= ~USDHC_MIX_CTRL_NIBBLE_POS_MASK;
        base->MIX_CTRL |= (USDHC_MIX_CTRL_DDR_EN_MASK | USDHC_MIX_CTRL_NIBBLE_POS(nibblePos));
        prescaler >>= 1U;
    }
    else {
        base->MIX_CTRL &= ~USDHC_MIX_CTRL_DDR_EN_MASK;

        if (prescaler == 0U) {
            prescaler += 1U;
        }
        else {
            prescaler <<= 1U;
        }
    }

    base->SYS_CTRL = (base->SYS_CTRL & (~USDHC_SYS_CTRL_SDCLKFS_MASK)) | USDHC_SYS_CTRL_SDCLKFS(prescaler);
}

void USDHC_SetMmcBootConfig(USDHC_Type *base, const usdhc_boot_config_t *config)
{
    assert(config);
    assert(config->ackTimeoutCount <= (USDHC_MMC_BOOT_DTOCV_ACK_MASK >> USDHC_MMC_BOOT_DTOCV_ACK_SHIFT));
    assert(config->blockCount <= (USDHC_MMC_BOOT_BOOT_BLK_CNT_MASK >> USDHC_MMC_BOOT_BOOT_BLK_CNT_SHIFT));

    uint32_t mmcboot = base->MMC_BOOT;

    mmcboot &= ~(USDHC_MMC_BOOT_DTOCV_ACK_MASK | USDHC_MMC_BOOT_BOOT_MODE_MASK | USDHC_MMC_BOOT_BOOT_BLK_CNT_MASK);
    mmcboot |= USDHC_MMC_BOOT_DTOCV_ACK(config->ackTimeoutCount) | USDHC_MMC_BOOT_BOOT_MODE(config->bootMode);

    if (config->enableBootAck) {
        mmcboot |= USDHC_MMC_BOOT_BOOT_ACK_MASK;
    }
    if (config->enableAutoStopAtBlockGap) {
        mmcboot |=
            USDHC_MMC_BOOT_AUTO_SABG_EN_MASK | USDHC_MMC_BOOT_BOOT_BLK_CNT(USDHC_MAX_BLOCK_COUNT - config->blockCount);
        /* always set the block count to USDHC_MAX_BLOCK_COUNT to use auto stop at block gap feature */
        base->BLK_ATT = ((base->BLK_ATT & ~(USDHC_BLK_ATT_BLKSIZE_MASK | USDHC_BLK_ATT_BLKCNT_MASK)) |
                         (USDHC_BLK_ATT_BLKSIZE(config->blockSize) | USDHC_BLK_ATT_BLKCNT(USDHC_MAX_BLOCK_COUNT)));
    }
    else {
        base->BLK_ATT = ((base->BLK_ATT & ~(USDHC_BLK_ATT_BLKSIZE_MASK | USDHC_BLK_ATT_BLKCNT_MASK)) |
                         (USDHC_BLK_ATT_BLKSIZE(config->blockSize) | USDHC_BLK_ATT_BLKCNT(config->blockCount)));
    }

    base->MMC_BOOT = mmcboot;
}

status_t USDHC_SetADMA1Descriptor(
    uint32_t *admaTable, uint32_t admaTableWords, const uint32_t *dataBufferAddr, uint32_t dataBytes, uint32_t flags)
{
    assert(NULL != admaTable);
    assert(NULL != dataBufferAddr);

    uint32_t miniEntries, startEntries = 0U,
                          maxEntries = (admaTableWords * sizeof(uint32_t)) / sizeof(usdhc_adma1_descriptor_t);
    usdhc_adma1_descriptor_t *adma1EntryAddress = (usdhc_adma1_descriptor_t *)(admaTable);
    uint32_t i, dmaBufferLen = 0U;
    const uint32_t *data = dataBufferAddr;

    if (((uint32_t)data % USDHC_ADMA1_ADDRESS_ALIGN) != 0U) {
        return kStatus_USDHC_DMADataAddrNotAlign;
    }

    if (flags == kUSDHC_AdmaDescriptorMultipleFlag) {
        return kStatus_USDHC_NotSupport;
    }
    /*
     * Add non aligned access support ,user need make sure your buffer size is big
     * enough to hold the data,in other words,user need make sure the buffer size
     * is 4 byte aligned
     */
    if (dataBytes % sizeof(uint32_t) != 0U) {
        /* make the data length as word-aligned */
        dataBytes += sizeof(uint32_t) - (dataBytes % sizeof(uint32_t));
    }

    /* Check if ADMA descriptor's number is enough. */
    if ((dataBytes % USDHC_ADMA1_DESCRIPTOR_MAX_LENGTH_PER_ENTRY) == 0U) {
        miniEntries = dataBytes / USDHC_ADMA1_DESCRIPTOR_MAX_LENGTH_PER_ENTRY;
    }
    else {
        miniEntries = ((dataBytes / USDHC_ADMA1_DESCRIPTOR_MAX_LENGTH_PER_ENTRY) + 1U);
    }

    /* ADMA1 needs two descriptors to finish a transfer */
    miniEntries <<= 1U;

    if (miniEntries + startEntries > maxEntries) {
        return kStatus_OutOfRange;
    }

    for (i = startEntries; i < (miniEntries + startEntries); i += 2U) {
        if (dataBytes > USDHC_ADMA1_DESCRIPTOR_MAX_LENGTH_PER_ENTRY) {
            dmaBufferLen = USDHC_ADMA1_DESCRIPTOR_MAX_LENGTH_PER_ENTRY;
        }
        else {
            dmaBufferLen = dataBytes;
        }

        adma1EntryAddress[i] = (dmaBufferLen << USDHC_ADMA1_DESCRIPTOR_LENGTH_SHIFT);
        adma1EntryAddress[i] |= kUSDHC_Adma1DescriptorTypeSetLength;
        adma1EntryAddress[i + 1U] = (uint32_t)(data);
        adma1EntryAddress[i + 1U] |= kUSDHC_Adma1DescriptorTypeTransfer;
        data += dmaBufferLen / sizeof(uint32_t);
        dataBytes -= dmaBufferLen;
    }
    /* the end of the descriptor */
    adma1EntryAddress[i - 1U] |= kUSDHC_Adma1DescriptorEndFlag;

    return kStatus_Success;
}

status_t USDHC_SetADMA2Descriptor(
    uint32_t *admaTable, uint32_t admaTableWords, const uint32_t *dataBufferAddr, uint32_t dataBytes, uint32_t flags)
{
    assert(NULL != admaTable);
    assert(NULL != dataBufferAddr);

    uint32_t miniEntries, startEntries = 0U,
                          maxEntries = (admaTableWords * sizeof(uint32_t)) / sizeof(usdhc_adma2_descriptor_t);
    usdhc_adma2_descriptor_t *adma2EntryAddress = (usdhc_adma2_descriptor_t *)(admaTable);
    uint32_t i, dmaBufferLen = 0U;
    const uint32_t *data = dataBufferAddr;

    if (((uint32_t)data % USDHC_ADMA2_ADDRESS_ALIGN) != 0U) {
        return kStatus_USDHC_DMADataAddrNotAlign;
    }
    /*
     * Add non aligned access support ,user need make sure your buffer size is big
     * enough to hold the data,in other words,user need make sure the buffer size
     * is 4 byte aligned
     */
    if (dataBytes % sizeof(uint32_t) != 0U) {
        /* make the data length as word-aligned */
        dataBytes += sizeof(uint32_t) - (dataBytes % sizeof(uint32_t));
    }

    /* Check if ADMA descriptor's number is enough. */
    if ((dataBytes % USDHC_ADMA2_DESCRIPTOR_MAX_LENGTH_PER_ENTRY) == 0U) {
        miniEntries = dataBytes / USDHC_ADMA2_DESCRIPTOR_MAX_LENGTH_PER_ENTRY;
    }
    else {
        miniEntries = ((dataBytes / USDHC_ADMA2_DESCRIPTOR_MAX_LENGTH_PER_ENTRY) + 1U);
    }
    /* calucate the start entry for multiple descriptor mode, ADMA engine is not stop, so update the descriptor
    data adress and data size is enough */
    if (flags == kUSDHC_AdmaDescriptorMultipleFlag) {
        for (i = 0U; i < maxEntries; i++) {
            if ((adma2EntryAddress[i].attribute & kUSDHC_Adma2DescriptorValidFlag) == 0U) {
                break;
            }
        }
        startEntries = i;
        /* add one entry for dummy entry */
        miniEntries += 1U;
    }

    if ((miniEntries + startEntries) > maxEntries) {
        return kStatus_OutOfRange;
    }

    for (i = startEntries; i < (miniEntries + startEntries); i++) {
        if (dataBytes > USDHC_ADMA2_DESCRIPTOR_MAX_LENGTH_PER_ENTRY) {
            dmaBufferLen = USDHC_ADMA2_DESCRIPTOR_MAX_LENGTH_PER_ENTRY;
        }
        else {
            dmaBufferLen = (dataBytes == 0U ? sizeof(uint32_t)
                                            : dataBytes); /* adma don't support 0 data length transfer descriptor */
        }

        /* Each descriptor for ADMA2 is 64-bit in length */
        adma2EntryAddress[i].address   = (dataBytes == 0U) ? &s_usdhcBootDummy : data;
        adma2EntryAddress[i].attribute = (dmaBufferLen << USDHC_ADMA2_DESCRIPTOR_LENGTH_SHIFT);
        adma2EntryAddress[i].attribute |=
            (dataBytes == 0U) ? 0U : (kUSDHC_Adma2DescriptorTypeTransfer | kUSDHC_Adma2DescriptorInterruptFlag);
        data += (dmaBufferLen / sizeof(uint32_t));

        if (dataBytes != 0U) {
            dataBytes -= dmaBufferLen;
        }
    }

    /* add a dummy valid ADMA descriptor for multiple descriptor mode, this is useful when transfer boot data, the ADMA
    engine
    will not stop at block gap */
    if (flags == kUSDHC_AdmaDescriptorMultipleFlag) {
        adma2EntryAddress[startEntries + 1U].attribute |= kUSDHC_Adma2DescriptorTypeTransfer;
    }
    else {
        /* set the end bit */
        adma2EntryAddress[i - 1U].attribute |= kUSDHC_Adma2DescriptorEndFlag;
    }

    return kStatus_Success;
}

status_t USDHC_SetInternalDmaConfig(USDHC_Type *base,
                                    usdhc_adma_config_t *dmaConfig,
                                    const uint32_t *dataAddr,
                                    bool enAutoCmd23)
{
    assert(dmaConfig);
    assert(dataAddr);

#if FSL_FEATURE_USDHC_HAS_EXT_DMA
    /* disable the external DMA if support */
    base->VEND_SPEC &= ~USDHC_VEND_SPEC_EXT_DMA_EN_MASK;
#endif

    if (dmaConfig->dmaMode == kUSDHC_DmaModeSimple) {
        /* check DMA data buffer address align or not */
        if (((uint32_t)dataAddr % USDHC_ADMA2_ADDRESS_ALIGN) != 0U) {
            return kStatus_USDHC_DMADataAddrNotAlign;
        }
        /* in simple DMA mode if use auto CMD23, address should load to ADMA addr,
             and block count should load to DS_ADDR*/
        if (enAutoCmd23) {
            base->ADMA_SYS_ADDR = (uint32_t)dataAddr;
        }
        else {
            base->DS_ADDR = (uint32_t)dataAddr;
        }
    }
    else {
        /* When use ADMA, disable simple DMA */
        base->DS_ADDR       = 0U;
        base->ADMA_SYS_ADDR = (uint32_t)(dmaConfig->admaTable);
    }

    /* select DMA mode and config the burst length */
    base->PROT_CTRL &= ~(USDHC_PROT_CTRL_DMASEL_MASK | USDHC_PROT_CTRL_BURST_LEN_EN_MASK);
    base->PROT_CTRL |= USDHC_PROT_CTRL_DMASEL(dmaConfig->dmaMode) | USDHC_PROT_CTRL_BURST_LEN_EN(dmaConfig->burstLen);
    /* enable DMA */
    base->MIX_CTRL |= USDHC_MIX_CTRL_DMAEN_MASK;

    return kStatus_Success;
}

status_t USDHC_SetAdmaTableConfig(USDHC_Type *base,
                                  usdhc_adma_config_t *dmaConfig,
                                  usdhc_data_t *dataConfig,
                                  uint32_t flags)
{
    assert(NULL != dmaConfig);
    assert(NULL != dmaConfig->admaTable);
    assert(NULL != dataConfig);

    status_t error           = kStatus_Fail;
    uint32_t bootDummyOffset = dataConfig->dataType == kUSDHC_TransferDataBootcontinous ? sizeof(uint32_t) : 0U;
    const uint32_t *data =
        (const uint32_t *)((uint32_t)((dataConfig->rxData == NULL) ? dataConfig->txData : dataConfig->rxData) +
                           bootDummyOffset);
    uint32_t blockSize = dataConfig->blockSize * dataConfig->blockCount - bootDummyOffset;

    switch (dmaConfig->dmaMode) {
#if FSL_FEATURE_USDHC_HAS_EXT_DMA
    case kUSDHC_ExternalDMA:
        /* enable the external DMA */
        base->VEND_SPEC |= USDHC_VEND_SPEC_EXT_DMA_EN_MASK;
        break;
#endif
    case kUSDHC_DmaModeSimple:
        error = kStatus_Success;
        break;

    case kUSDHC_DmaModeAdma1:
        error = USDHC_SetADMA1Descriptor(dmaConfig->admaTable, dmaConfig->admaTableWords, data, blockSize, flags);
        break;

    case kUSDHC_DmaModeAdma2:
        error = USDHC_SetADMA2Descriptor(dmaConfig->admaTable, dmaConfig->admaTableWords, data, blockSize, flags);
        break;
    default:
        return kStatus_USDHC_PrepareAdmaDescriptorFailed;
    }

    /* for internal dma, internal DMA configurations should not update the configurations when continous transfer the
     * boot data, only the DMA descriptor need update */
    if ((dmaConfig->dmaMode != kUSDHC_ExternalDMA) && (error == kStatus_Success) &&
        (dataConfig->dataType != kUSDHC_TransferDataBootcontinous)) {
        error = USDHC_SetInternalDmaConfig(base, dmaConfig, data, dataConfig->enableAutoCommand23);
    }

    return error;
}

status_t USDHC_TransferBlocking(USDHC_Type *base, usdhc_adma_config_t *dmaConfig, usdhc_transfer_t *transfer)
{
    assert(transfer);

    status_t error           = kStatus_Fail;
    usdhc_command_t *command = transfer->command;
    usdhc_data_t *data       = transfer->data;
    bool enDMA               = true;
    bool executeTuning       = ((data == NULL) ? false : data->dataType == kUSDHC_TransferDataTuning);

    /*check re-tuning request*/
    if ((USDHC_GetInterruptStatusFlags(base) & kUSDHC_ReTuningEventFlag) != 0U) {
        USDHC_ClearInterruptStatusFlags(base, kUSDHC_ReTuningEventFlag);
        return kStatus_USDHC_ReTuningRequest;
    }

    /* Update ADMA descriptor table according to different DMA mode(no DMA, ADMA1, ADMA2).*/
    if ((data != NULL) && (dmaConfig != NULL) && (!executeTuning)) {
        error = USDHC_SetAdmaTableConfig(base,
                                         dmaConfig,
                                         data,
                                         (data->dataType & kUSDHC_TransferDataBoot) ? kUSDHC_AdmaDescriptorMultipleFlag
                                                                                    : kUSDHC_AdmaDescriptorSingleFlag);
    }

    /* if the DMA desciptor configure fail or not needed , disable it */
    if (error != kStatus_Success) {
        enDMA = false;
        /* disable DMA, using polling mode in this situation */
        USDHC_EnableInternalDMA(base, false);
    }
#if defined(FSL_SDK_ENABLE_DRIVER_CACHE_CONTROL) && FSL_SDK_ENABLE_DRIVER_CACHE_CONTROL
    else {
        if (data->txData != NULL) {
            /* clear the DCACHE */
            DCACHE_CleanByRange((uint32_t)data->txData, (data->blockSize) * (data->blockCount));
        }
        else if (data->rxData != NULL) {
            /* clear the DCACHE */
            DCACHE_CleanInvalidateByRange((uint32_t)data->rxData, (data->blockSize) * (data->blockCount));
        }
    }
#endif

    /* config the data transfer parameter */
    error = USDHC_SetDataTransferConfig(base, data, &(command->flags));
    if (kStatus_Success != error) {
        return error;
    }
    /* send command first */
    USDHC_SendCommand(base, command);
    /* wait command done */
    error = USDHC_WaitCommandDone(base, command, (data == NULL) || (data->dataType == kUSDHC_TransferDataNormal));

    /* wait transfer data finsih */
    if ((data != NULL) && (error == kStatus_Success)) {
        return USDHC_TransferDataBlocking(base, data, enDMA);
    }

    return error;
}

status_t USDHC_TransferNonBlocking(USDHC_Type *base,
                                   usdhc_handle_t *handle,
                                   usdhc_adma_config_t *dmaConfig,
                                   usdhc_transfer_t *transfer)
{
    assert(handle);
    assert(transfer);

    status_t error           = kStatus_Fail;
    usdhc_command_t *command = transfer->command;
    usdhc_data_t *data       = transfer->data;
    bool executeTuning       = ((data == NULL) ? false : data->dataType == kUSDHC_TransferDataTuning);

    /*check re-tuning request*/
    if ((USDHC_GetInterruptStatusFlags(base) & (kUSDHC_ReTuningEventFlag)) != 0U) {
        USDHC_ClearInterruptStatusFlags(base, kUSDHC_ReTuningEventFlag);
        return kStatus_USDHC_ReTuningRequest;
    }

    /* Save command and data into handle before transferring. */
    handle->command        = command;
    handle->data           = data;
    handle->interruptFlags = 0U;
    /* transferredWords will only be updated in ISR when transfer way is DATAPORT. */
    handle->transferredWords = 0U;

    /* Update ADMA descriptor table according to different DMA mode(no DMA, ADMA1, ADMA2).*/
    if ((data != NULL) && (dmaConfig != NULL) && (!executeTuning)) {
        error = USDHC_SetAdmaTableConfig(base,
                                         dmaConfig,
                                         data,
                                         (data->dataType & kUSDHC_TransferDataBoot) ? kUSDHC_AdmaDescriptorMultipleFlag
                                                                                    : kUSDHC_AdmaDescriptorSingleFlag);
    }

    /* if the DMA desciptor configure fail or not needed , disable it */
    if (error != kStatus_Success) {
        /* disable DMA, using polling mode in this situation */
        USDHC_EnableInternalDMA(base, false);
    }
#if defined(FSL_SDK_ENABLE_DRIVER_CACHE_CONTROL) && FSL_SDK_ENABLE_DRIVER_CACHE_CONTROL
    else {
        if (data->txData != NULL) {
            /* clear the DCACHE */
            DCACHE_CleanByRange((uint32_t)data->txData, (data->blockSize) * (data->blockCount));
        }
        else if (data->rxData != NULL) {
            /* clear the DCACHE */
            DCACHE_CleanInvalidateByRange((uint32_t)data->rxData, (data->blockSize) * (data->blockCount));
        }
    }
#endif

    error = USDHC_SetDataTransferConfig(base, data, &(command->flags));
    if (kStatus_Success != error) {
        return error;
    }

    /* send command first */
    USDHC_SendCommand(base, command);

    return kStatus_Success;
}

#if defined(FSL_FEATURE_USDHC_HAS_SDR50_MODE) && (FSL_FEATURE_USDHC_HAS_SDR50_MODE)
void USDHC_EnableManualTuning(USDHC_Type *base, bool enable)
{
    if (enable) {
        /* make sure std_tun_en bit is clear */
        base->TUNING_CTRL &= ~USDHC_TUNING_CTRL_STD_TUNING_EN_MASK;
        /* disable auto tuning here */
        base->MIX_CTRL &= ~USDHC_MIX_CTRL_AUTO_TUNE_EN_MASK;
        /* execute tuning for SDR104 mode */
        base->MIX_CTRL |=
            USDHC_MIX_CTRL_EXE_TUNE_MASK | USDHC_MIX_CTRL_SMP_CLK_SEL_MASK | USDHC_MIX_CTRL_FBCLK_SEL_MASK;
    }
    else { /* abort the tuning */
        base->MIX_CTRL &= ~(USDHC_MIX_CTRL_EXE_TUNE_MASK | USDHC_MIX_CTRL_SMP_CLK_SEL_MASK);
    }
}

status_t USDHC_AdjustDelayForManualTuning(USDHC_Type *base, uint32_t delay)
{
    uint32_t clkTuneCtrl = 0U;

    clkTuneCtrl = base->CLK_TUNE_CTRL_STATUS;

    clkTuneCtrl &= ~USDHC_CLK_TUNE_CTRL_STATUS_DLY_CELL_SET_PRE_MASK;

    clkTuneCtrl |= USDHC_CLK_TUNE_CTRL_STATUS_DLY_CELL_SET_PRE(delay);

    /* load the delay setting */
    base->CLK_TUNE_CTRL_STATUS = clkTuneCtrl;
    /* check delat setting error */
    if (base->CLK_TUNE_CTRL_STATUS &
        (USDHC_CLK_TUNE_CTRL_STATUS_PRE_ERR_MASK | USDHC_CLK_TUNE_CTRL_STATUS_NXT_ERR_MASK)) {
        return kStatus_Fail;
    }

    return kStatus_Success;
}

void USDHC_EnableStandardTuning(USDHC_Type *base, uint32_t tuningStartTap, uint32_t step, bool enable)
{
    uint32_t tuningCtrl = 0U;

    if (enable) {
        /* feedback clock */
        base->MIX_CTRL |= USDHC_MIX_CTRL_FBCLK_SEL_MASK;
        /* config tuning start and step */
        tuningCtrl = base->TUNING_CTRL;
        tuningCtrl &= ~(USDHC_TUNING_CTRL_TUNING_START_TAP_MASK | USDHC_TUNING_CTRL_TUNING_STEP_MASK);
        tuningCtrl |= (USDHC_TUNING_CTRL_TUNING_START_TAP(tuningStartTap) | USDHC_TUNING_CTRL_TUNING_STEP(step) |
                       USDHC_TUNING_CTRL_STD_TUNING_EN_MASK);
        base->TUNING_CTRL = tuningCtrl;

        /* excute tuning */
        base->AUTOCMD12_ERR_STATUS |=
            (USDHC_AUTOCMD12_ERR_STATUS_EXECUTE_TUNING_MASK | USDHC_AUTOCMD12_ERR_STATUS_SMP_CLK_SEL_MASK);
    }
    else {
        /* disable the standard tuning */
        base->TUNING_CTRL &= ~USDHC_TUNING_CTRL_STD_TUNING_EN_MASK;
        /* clear excute tuning */
        base->AUTOCMD12_ERR_STATUS &=
            ~(USDHC_AUTOCMD12_ERR_STATUS_EXECUTE_TUNING_MASK | USDHC_AUTOCMD12_ERR_STATUS_SMP_CLK_SEL_MASK);
    }
}

void USDHC_EnableAutoTuningForCmdAndData(USDHC_Type *base)
{
    uint32_t busWidth = 0U;

    base->VEND_SPEC2 |= USDHC_VEND_SPEC2_TUNING_CMD_EN_MASK;
    busWidth = (base->PROT_CTRL & USDHC_PROT_CTRL_DTW_MASK) >> USDHC_PROT_CTRL_DTW_SHIFT;
    if (busWidth == kUSDHC_DataBusWidth1Bit) {
        base->VEND_SPEC2 &= ~USDHC_VEND_SPEC2_TUNING_8bit_EN_MASK;
        base->VEND_SPEC2 |= USDHC_VEND_SPEC2_TUNING_1bit_EN_MASK;
    }
    else if (busWidth == kUSDHC_DataBusWidth4Bit) {
        base->VEND_SPEC2 &= ~USDHC_VEND_SPEC2_TUNING_8bit_EN_MASK;
        base->VEND_SPEC2 &= ~USDHC_VEND_SPEC2_TUNING_1bit_EN_MASK;
    }
    else if (busWidth == kUSDHC_DataBusWidth8Bit) {
        base->VEND_SPEC2 |= USDHC_VEND_SPEC2_TUNING_8bit_EN_MASK;
        base->VEND_SPEC2 &= ~USDHC_VEND_SPEC2_TUNING_1bit_EN_MASK;
    }
    else {
    }
}
#endif /* FSL_FEATURE_USDHC_HAS_SDR50_MODE */

static void USDHC_TransferHandleCardDetect(USDHC_Type *base, usdhc_handle_t *handle, uint32_t interruptFlags)
{
    if (interruptFlags & kUSDHC_CardInsertionFlag) {
        if (handle->callback.CardInserted) {
            handle->callback.CardInserted(base, handle->userData);
        }
    }
    else {
        if (handle->callback.CardRemoved) {
            handle->callback.CardRemoved(base, handle->userData);
        }
    }
}

static void USDHC_TransferHandleCommand(USDHC_Type *base, usdhc_handle_t *handle, uint32_t interruptFlags)
{
    assert(handle->command);

    if ((interruptFlags & kUSDHC_CommandErrorFlag) && (!(handle->data))) {
        if (handle->callback.TransferComplete) {
            handle->callback.TransferComplete(base, handle, kStatus_USDHC_SendCommandFailed, handle->userData);
        }
    }
    else {
        /* Receive response */
        if (kStatus_Success != USDHC_ReceiveCommandResponse(base, handle->command)) {
            if (handle->callback.TransferComplete) {
                handle->callback.TransferComplete(base, handle, kStatus_USDHC_SendCommandFailed, handle->userData);
            }
        }
        else if ((!(handle->data)) && (handle->callback.TransferComplete)) {
            if (handle->callback.TransferComplete) {
                handle->callback.TransferComplete(base, handle, kStatus_Success, handle->userData);
            }
        }
        else {
        }
    }
}

static void USDHC_TransferHandleData(USDHC_Type *base, usdhc_handle_t *handle, uint32_t interruptFlags)
{
    assert(handle->data);

    if ((!(handle->data->enableIgnoreError)) && ((interruptFlags & (kUSDHC_DataErrorFlag | kUSDHC_DmaErrorFlag)))) {
        if (handle->callback.TransferComplete) {
            handle->callback.TransferComplete(base, handle, kStatus_USDHC_TransferDataFailed, handle->userData);
        }
    }
    else {
        if (interruptFlags & kUSDHC_BufferReadReadyFlag) {
            /* std tuning process only need to wait BRR */
            if (handle->data->dataType == kUSDHC_TransferDataTuning) {
                if (handle->callback.TransferComplete) {
                    handle->callback.TransferComplete(base, handle, kStatus_Success, handle->userData);
                }
            }
            else {
                handle->transferredWords = USDHC_ReadDataPort(base, handle->data, handle->transferredWords);
            }
        }
        else if (interruptFlags & kUSDHC_BufferWriteReadyFlag) {
            handle->transferredWords = USDHC_WriteDataPort(base, handle->data, handle->transferredWords);
        }
        else {
            if ((interruptFlags & kUSDHC_DmaCompleteFlag) &&
                (handle->data->dataType == kUSDHC_TransferDataBootcontinous)) {
                *(handle->data->rxData) = s_usdhcBootDummy;
            }

            if ((handle->callback.TransferComplete) && (interruptFlags & kUSDHC_DataCompleteFlag)) {
                handle->callback.TransferComplete(base, handle, kStatus_Success, handle->userData);
            }
        }
    }
}

static void USDHC_TransferHandleSdioInterrupt(USDHC_Type *base, usdhc_handle_t *handle)
{
    if (handle->callback.SdioInterrupt) {
        handle->callback.SdioInterrupt(base, handle->userData);
    }
}

static void USDHC_TransferHandleReTuning(USDHC_Type *base, usdhc_handle_t *handle, uint32_t interruptFlags)
{
    assert(handle->callback.ReTuning);
    /* retuning request */
    if ((interruptFlags & kUSDHC_TuningErrorFlag) == kUSDHC_TuningErrorFlag) {
        handle->callback.ReTuning(base, handle->userData); /* retuning fail */
    }
}

static void USDHC_TransferHandleBlockGap(USDHC_Type *base, usdhc_handle_t *handle)
{
    if (handle->callback.BlockGap) {
        handle->callback.BlockGap(base, handle->userData);
    }
}

void USDHC_TransferCreateHandle(USDHC_Type *base,
                                usdhc_handle_t *handle,
                                const usdhc_transfer_callback_t *callback,
                                void *userData)
{
    assert(handle);
    assert(callback);

    /* Zero the handle. */
    memset(handle, 0, sizeof(*handle));

    /* Set the callback. */
    handle->callback.CardInserted     = callback->CardInserted;
    handle->callback.CardRemoved      = callback->CardRemoved;
    handle->callback.SdioInterrupt    = callback->SdioInterrupt;
    handle->callback.BlockGap         = callback->BlockGap;
    handle->callback.TransferComplete = callback->TransferComplete;
    handle->callback.ReTuning         = callback->ReTuning;
    handle->userData                  = userData;

    /* Save the handle in global variables to support the double weak mechanism. */
    s_usdhcHandle[USDHC_GetInstance(base)] = handle;

    /* Enable interrupt in NVIC. */
    USDHC_SetTransferInterrupt(base, true);
    /* disable the tuning pass interrupt */
    USDHC_DisableInterruptSignal(base, kUSDHC_TuningPassFlag | kUSDHC_ReTuningEventFlag);
    /* save IRQ handler */
    s_usdhcIsr = USDHC_TransferHandleIRQ;

    EnableIRQ(s_usdhcIRQ[USDHC_GetInstance(base)]);
}

void USDHC_TransferHandleIRQ(USDHC_Type *base, usdhc_handle_t *handle)
{
    assert(handle);

    uint32_t interruptFlags;

    interruptFlags         = USDHC_GetInterruptStatusFlags(base);
    handle->interruptFlags = interruptFlags;

    if (interruptFlags & kUSDHC_CardDetectFlag) {
        USDHC_TransferHandleCardDetect(base, handle, (interruptFlags & kUSDHC_CardDetectFlag));
    }
    if (interruptFlags & kUSDHC_CommandFlag) {
        USDHC_TransferHandleCommand(base, handle, (interruptFlags & kUSDHC_CommandFlag));
    }
    if (interruptFlags & kUSDHC_DataFlag) {
        USDHC_TransferHandleData(base, handle, (interruptFlags & kUSDHC_DataFlag));
    }
    if (interruptFlags & kUSDHC_CardInterruptFlag) {
        USDHC_TransferHandleSdioInterrupt(base, handle);
    }
    if (interruptFlags & kUSDHC_BlockGapEventFlag) {
        USDHC_TransferHandleBlockGap(base, handle);
    }
    if (interruptFlags & kUSDHC_SDR104TuningFlag) {
        USDHC_TransferHandleReTuning(base, handle, (interruptFlags & kUSDHC_SDR104TuningFlag));
    }
    USDHC_ClearInterruptStatusFlags(base, interruptFlags);
}

#ifdef USDHC0
void USDHC0_DriverIRQHandler(void)
{
    s_usdhcIsr(s_usdhcBase[0U], s_usdhcHandle[0U]);
/* Add for ARM errata 838869, affects Cortex-M4, Cortex-M4F Store immediate overlapping
  exception return operation might vector to incorrect interrupt */
#if defined __CORTEX_M && (__CORTEX_M == 4U)
    __DSB();
#endif
}
#endif

#ifdef USDHC1
void USDHC1_DriverIRQHandler(void)
{
    s_usdhcIsr(s_usdhcBase[1U], s_usdhcHandle[1U]);
/* Add for ARM errata 838869, affects Cortex-M4, Cortex-M4F Store immediate overlapping
  exception return operation might vector to incorrect interrupt */
#if defined __CORTEX_M && (__CORTEX_M == 4U)
    __DSB();
#endif
}
#endif

#ifdef USDHC2
void USDHC2_DriverIRQHandler(void)
{
    s_usdhcIsr(s_usdhcBase[2U], s_usdhcHandle[2U]);
/* Add for ARM errata 838869, affects Cortex-M4, Cortex-M4F Store immediate overlapping
  exception return operation might vector to incorrect interrupt */
#if defined __CORTEX_M && (__CORTEX_M == 4U)
    __DSB();
#endif
}

#endif