summaryrefslogtreecommitdiff
path: root/bsp/allwinner/libraries/sunxi-hal/hal/source/sdmmc/core.c
blob: a9fd3d604b26d876db622bdd8dd81b62a3e31bf0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
/*
 * Copyright (C) 2017 ALLWINNERTECH TECHNOLOGY CO., LTD. All rights reserved.
 *
 *  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 ALLWINNERTECH TECHNOLOGY CO., LTD. nor the names of
 *       its contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 *  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 *  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stddef.h>
#include <stdint.h>

#include "hal_sdhost.h"
#include "sdmmc.h"
#ifdef CONFIG_USE_SDIO
#include "sdio.h"
#endif

#include "hal/hal_base.h"

#include "_sd_define.h"

#include "_sdhost.h"
#include "_core.h"
#ifdef CONFIG_USE_SDIO
#include "_sdio.h"
#endif
#ifdef CONFIG_USE_SD
#include "_sd.h"
#endif
#ifdef CONFIG_USE_MMC
#include "_mmc.h"
#endif

hal_spinlock_t sdmmc_lock;

/**
 *  mmc_wait_for_req - start a request and wait for completion
 *  @host: MMC host to start command
 *  @mrq: MMC request to start
 *
 *  Start a new MMC custom command request for a host, and wait
 *  for the command to complete. Does not attempt to parse the
 *  response.
 */
int32_t mmc_wait_for_req(struct mmc_host *host, struct mmc_request *mrq)
{
    mrq->cmd->data = mrq->data;
    return HAL_SDC_Request(host, mrq);
}

/**
 *  mmc_wait_for_cmd - start a command and wait for completion
 *  @host: MMC host to start command
 *  @cmd: MMC command to start
 *  @retries: maximum number of retries
 *
 *  Start a new MMC command for a host, and wait for the command
 *  to complete.  Return any error that occurred while the command
 *  was executing.  Do not attempt to parse the response.
 */
int32_t mmc_wait_for_cmd(struct mmc_host *host, struct mmc_command *cmd)
{
    struct mmc_request mrq = {0};

    SDC_Memset(cmd->resp, 0, sizeof(cmd->resp));

    mrq.cmd = cmd;

    return mmc_wait_for_req(host, &mrq);
}

/**
 *  mmc_align_data_size - pads a transfer size to a more optimal value
 *  @card: the MMC card associated with the data transfer
 *  @sz: original transfer size
 *
 *  Pads the original data size with a number of extra bytes in
 *  order to avoid controller bugs and/or performance hits
 *  (e.g. some controllers revert to PIO for certain sizes).
 *
 *  Returns the improved size, which might be unmodified.
 *
 *  Note that this function is only relevant when issuing a
 *  single scatter gather entry.
 */
int32_t mmc_align_data_size(struct mmc_card *card, uint32_t sz)
{
    /*
     * FIXME: We don't have a system for the controller to tell
     * the core about its problems yet, so for now we just 32-bit
     * align the size.
     */
    sz = ((sz + 3) / 4) * 4;

    return sz;
}

static inline void mmc_host_clk_hold(struct mmc_host *host)
{
    HAL_SDC_Clk_PWR_Opt(host, 1, 0);
}

static inline void mmc_host_clk_release(struct mmc_host *host)
{
    HAL_SDC_Clk_PWR_Opt(host, 0, 0);
}

/*
 * Apply power to the MMC stack.  This is a two-stage process.
 * First, we enable power to the card without the clock running.
 * We then wait a bit for the power to stabilise.  Finally,
 * enable the bus drivers and clock to the card.
 *
 * We must _NOT_ enable the clock prior to power stablising.
 *
 * If a host does all the power sequencing itself, ignore the
 * initial MMC_POWER_UP stage.
 */
static void mmc_power_up(struct mmc_host *host)
{
    //int bit;

    mmc_host_clk_hold(host);

    /* If ocr is set, we use it */
    //if (host->ocr)
    //  bit = ffs(host->ocr) - 1;
    //else
    //  bit = fls(host->ocr_avail) - 1;

    /*This delay should be sufficient to allow the power supply
    *to reach the minimum voltage
    * according to figure 6-5 of sd3.0 spec,about 40 ms
    */
    mmc_mdelay(40);

    /*
     * This delay must be at least 74 clock sizes, or 1 ms, or the
     * time required to reach a stable voltage.
     */
    mmc_mdelay(5);
    HAL_SDC_PowerOn(host);

    mmc_host_clk_release(host);
}

static void mmc_power_off(struct mmc_host *host)
{
    mmc_host_clk_hold(host);

    /*
     * For eMMC 4.5 device send AWAKE command before
     * POWER_OFF_NOTIFY command, because in sleep state
     * eMMC 4.5 devices respond to only RESET and AWAKE cmd
     */
    //if (host->card && mmc_card_is_sleep(host->card)) {
    //  mmc_poweroff_notify(host);
    //}

    /*
     * Reset ocr mask to be the highest possible voltage supported for
     * this mmc host. This value will be used at next power up.
     */
    //host->ocr = 1 << (fls(host->ocr_avail) - 1);
    HAL_SDC_PowerOff(host);
    /*
     * Some configurations, such as the 802.11 SDIO card in the OLPC
     * XO-1.5, require a short delay after poweroff before the card
     * can be successfully turned on again.
     */
    mmc_mdelay(1);

    mmc_host_clk_release(host);
}

static int32_t mmc_go_idle(struct mmc_host *host)
{
    int32_t err;
    struct mmc_command cmd = {0};

    cmd.opcode = MMC_GO_IDLE_STATE;
    cmd.arg = 0;
    cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_NONE | MMC_CMD_BC;

    err = mmc_wait_for_cmd(host, &cmd);

    mmc_mdelay(1);

    return err;
}

int32_t mmc_send_status(struct mmc_card *card, uint32_t *status)
{
    int32_t err;
    struct mmc_command cmd = {0};

    cmd.opcode = MMC_SEND_STATUS;
    cmd.arg = card->rca << 16;
    cmd.flags = MMC_RSP_SPI_R2 | MMC_RSP_R1 | MMC_CMD_AC;

    err = mmc_wait_for_cmd(card->host, &cmd);
    if (err)
        return err;

    /* NOTE: callers are required to understand the difference
     * between "native" and SPI format status words!
     */
    if (status)
        *status = cmd.resp[0];

    return 0;
}

#if ((defined CONFIG_USE_SD) || (defined CONFIG_USE_MMC))
int32_t mmc_sd_switch(struct mmc_card *card, uint8_t mode, uint8_t group,
                             uint16_t value, uint8_t *resp)
{
    struct mmc_request mrq;
    struct mmc_command cmd = {0};
    struct mmc_data data = {0};
    struct scatterlist sg;

    /* NOTE: caller guarantees resp is heap-allocated */

    mode = !!mode;
    value &= 0xF;

    mrq.cmd = &cmd;
    mrq.data = &data;

    cmd.opcode = SD_SWITCH;
    cmd.arg = mode << 31 | 0x00FFFFFF;
    cmd.arg &= ~(0xF << (group * 4));
    cmd.arg |= value << (group * 4);
    cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;

    data.blksz = 64;
    data.blocks = 1;
    data.flags = MMC_DATA_READ;
    data.sg = &sg;
    data.sg_len = 1;

    sg.len = 64;
    sg.buffer = resp;

    if (mmc_wait_for_req(card->host, &mrq)) {
        return -1;
    }

    return 0;
}

static int32_t mmc_switch(struct mmc_card *card, uint8_t set, uint8_t index, uint8_t value)
{
    struct mmc_command cmd = {0};
    int32_t ret;
    uint32_t status = 0;

    cmd.opcode = MMC_SWITCH;
    cmd.arg = (MMC_SWITCH_MODE_WRITE_BYTE << 24) | (index << 16) | (value << 8) | set;
    cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;

    if (mmc_wait_for_cmd(card->host, &cmd)) {
        return -1;
    }

    /* Must check status to be sure of no errors */
    do {
        ret = mmc_send_status(card, &status);
        if (ret)
            return ret;
    } while (R1_CURRENT_STATE(status) == R1_STATE_PRG);

    if (status & 0xFDFFA000)
        SD_LOGW("unexpected status %x after switch", (unsigned int)status);
    if (status & R1_SWITCH_ERROR)
        return -1;

    return 0;
}

int32_t mmc_app_cmd(struct mmc_host *host, struct mmc_card *card)
{
    int32_t err;
    struct mmc_command cmd = {0};

    if (!host || (card && (card->host != host))) {
        SD_LOGE_RAW(ROM_ERR_MASK, "%s,%d err", __func__, __LINE__);
        return -1;
    }

    cmd.opcode = MMC_APP_CMD;

    if (card) {
        cmd.arg = card->rca << 16;
        cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
    } else {
        cmd.arg = 0;
        cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_BCR;
    }

    err = mmc_wait_for_cmd(host, &cmd);
    if (err)
        return err;

    /* Check that card supported application commands */
    if (!(cmd.resp[0] & R1_APP_CMD))
        return -1;

    return 0;
}

/**
 *  mmc_wait_for_app_cmd - start an application command and wait for
 *                 completion
 *  @host: MMC host to start command
 *  @card: Card to send MMC_APP_CMD to
 *  @cmd: MMC command to start
 *
 *  Sends a MMC_APP_CMD, checks the card response, sends the command
 *  in the parameter and waits for it to complete. Return any error
 *  that occurred while the command was executing.  Do not attempt to
 *  parse the response.
 */
int32_t mmc_wait_for_app_cmd(struct mmc_host *host, struct mmc_card *card,
                             struct mmc_command *cmd)
{
    struct mmc_request mrq = {NULL};

    int32_t i, err;

    if (!cmd) {
        SD_LOGE("%s,%d err", __func__, __LINE__);
        return -1;
    }

    err = -1;

    /*
     * We have to resend MMC_APP_CMD for each attempt so
     * we cannot use the retries field in mmc_command.
     */
    for (i = 0; i <= MMC_CMD_RETRIES; i++) {
        err = mmc_app_cmd(host, card);
        if (err) {
            continue;
        }

        SDC_Memset(&mrq, 0, sizeof(struct mmc_request));

        SDC_Memset(cmd->resp, 0, sizeof(cmd->resp));

        mrq.cmd = cmd;
        cmd->data = NULL;

        err = mmc_wait_for_req(host, &mrq);
        if (!err)
            break;
    }

    return err;
}

int32_t mmc_app_set_bus_width(struct mmc_card *card, uint32_t width)
{
    struct mmc_command cmd = {0};

    cmd.opcode = SET_BUS_WIDTH;
    cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;

    switch (width) {
        case MMC_BUS_WIDTH_1:
            cmd.arg = SD_BUS_WIDTH_1;
            break;
        case MMC_BUS_WIDTH_4:
            cmd.arg = SD_BUS_WIDTH_4;
            break;
        default:
            cmd.arg = SD_BUS_WIDTH_1;
    }

    if (mmc_wait_for_app_cmd(card->host, card, &cmd)) {
        return -1;
    }
    card->bus_width = width;

    return 0;
}

int32_t mmc_switch_to_high_speed(struct mmc_card *card)
{
    int32_t err;

#ifdef CONFIG_USE_MMC
    if (card->csd.mmc_spec_ver < MMC_CSD_SPEC_VER_4) {
        SD_LOGD("MMC card doesn't support to switch to high speed mode !!\n");
        return -1;
    }
#endif

    err = mmc_switch(card, MMC_EXT_CSD_CMD_SET_NORMAL, MMC_EXT_CSD_HS_TIMING, 1);
    if (err) {
        SD_LOGD("MMC card failed to switch to high speed mode !!\n");
        return err;
    }

    SD_LOGD("MMC card is switched to high speed!!\n");

    return 0;
}

int32_t __sdmmc_block_rw(struct mmc_card *card, uint32_t blk_num, uint32_t blk_cnt,
                           uint32_t sg_len, struct scatterlist *sg, int write)
{
    struct mmc_command cmd = {0};
    struct mmc_data data = {0};
    struct mmc_request mrq;
    uint32_t status = 0;

    SD_LOGD("%s %s blk_num:%u, blk_cnt:%u, sg_len:%u sg->len:%u\n", __func__,
            write?"wirte":"read", (unsigned int)blk_num, (unsigned int)blk_cnt, (unsigned int)sg_len, (unsigned int)sg->len);

    if (blk_cnt > 1) {
        cmd.opcode = write ? MMC_WRITE_MULTIPLE_BLOCK : MMC_READ_MULTIPLE_BLOCK;
    } else {
        cmd.opcode = write ? MMC_WRITE_SINGLE_BLOCK : MMC_READ_SINGLE_BLOCK;
    }
    cmd.arg = blk_num;
    if (!mmc_card_blockaddr(card))
        cmd.arg <<= 9;
    cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
    cmd.stop = (blk_cnt == 1) ? 0 : 1;

    data.blksz = 512;
    data.flags = write ? MMC_DATA_WRITE : MMC_DATA_READ;
    data.blocks = blk_cnt;

    data.sg = sg;
    data.sg_len = sg_len;

    mrq.cmd = &cmd;
    mrq.data = &data;

    SD_LOGD("starting CMD%u arg 0x%08x flags %x\n", (unsigned int)cmd.opcode, (unsigned int)cmd.arg, (unsigned int)cmd.flags);
    SD_LOGD("  blksz %u blocks %u flags %x\n", (unsigned int)data.blksz, (unsigned int)data.blocks, (unsigned int)data.flags);
    if (mmc_wait_for_req(card->host, &mrq)) {
        SD_LOGE("%s,%d %s sector:%x BSZ:%u Err!!\n", __func__, __LINE__,
            write?"W":"R", (unsigned int)blk_num, (unsigned int)blk_cnt);

        return -1;
    }
    if (write) {
        uint32_t timeout = 0x3ff;
        do {
            if (HAL_SDC_Is_Busy(card->host) && timeout) {
                timeout--;
                continue;
            } else if (HAL_SDC_Is_Busy(card->host)) {
                goto mdelay;
            }
            if (mmc_send_status(card, &status)) {
                break;
            }
mdelay:
            timeout = 0x3ff;
            /* mmc_mdelay(1); // no mdelay will be faster */
        } while (!(status & 0x100));
    }
    return 0;
}
#endif

void mmc_add_card(struct mmc_card *card)
{
    uint8_t spec_ver = 0;
    uint32_t speed_hz = 0;
    const char *type = NULL;
    const char *speed_mode = "";
#if SD_DEBUG
#ifdef SD_SUPPORT_VERSION3
    static const char *const uhs_speeds[] = {
        [UHS_SDR12_BUS_SPEED] = "SDR12 ",
        [UHS_SDR25_BUS_SPEED] = "SDR25 ",
        [UHS_SDR50_BUS_SPEED] = "SDR50 ",
        [UHS_SDR104_BUS_SPEED] = "SDR104 ",
        [UHS_DDR50_BUS_SPEED] = "DDR50 ",
    };
#endif
#endif

    switch (card->type) {
#ifdef CONFIG_USE_MMC
    case MMC_TYPE_MMC:
        type = "MMC";
        if (card->csd.mmc_spec_ver == 4)
            spec_ver = 0x40;
        else
            spec_ver = 0x31;
        speed_hz = mmc_mmc_get_max_clock(card);
        break;
#endif
#ifdef CONFIG_USE_SD
    case MMC_TYPE_SD:
        type = "SD";
        if (mmc_card_blockaddr(card)) {
            if (mmc_card_ext_capacity(card))
                type = "SDXC";
            else
                type = "SDHC";
        }
        if (card->scr.sda_vsn == 0)
            spec_ver = 0x10;
        else if (card->scr.sda_vsn == 1)
            spec_ver = 0x11;
        else if (card->scr.sda_vsn == 2 && card->scr.sda_spec3)
            spec_ver = 0x30;
        else
            spec_ver = 0x20;
        if (card->scr.sda_vsn == 2 && card->scr.sda_spec3 && card->scr.sda_spec4)
            spec_ver = 0x40;
        if (card->scr.sda_vsn == 2 && card->scr.sda_spec3 && card->scr.sda_spec5)
            spec_ver = 0x50;
        speed_hz = mmc_sd_get_max_clock(card);
        break;
#endif
#ifdef CONFIG_USE_SDIO
    case MMC_TYPE_SDIO:
        type = "SDIO";
        spec_ver = 0x10;
        speed_hz = mmc_sdio_get_max_clock(card);
        break;
#endif
#ifdef CONFIG_USE_SD_COMBO
    case MMC_TYPE_SD_COMBO:
        type = "SD-combo";
        if (mmc_card_blockaddr(card))
            type = "SDHC-combo";
        break;
#endif
    default:
        type = "?";
        break;
    }

#ifdef SD_SUPPORT_VERSION3
    if (mmc_sd_card_uhs(card) &&
        (card->sd_bus_speed < ARRAY_SIZE(uhs_speeds)))
        speed_mode = uhs_speeds[card->sd_bus_speed];
    else
#endif
    if (card->sd_bus_speed == HIGH_SPEED_BUS_SPEED)
        speed_mode = "HS: 50 MHz";
    else
        speed_mode = "DS: 25 MHz";

    SD_LOGN("\n============= card information ==============\n");
    SD_LOGN("Card Type     : %s\n", type);
    SD_LOGN("Card Spec Ver : %x.%x\n", spec_ver>>4, spec_ver&0xf);
    SD_LOGN("Card RCA      : 0x%04x \n", (unsigned int)card->rca);
    SD_LOGN("Card OCR      : 0x%x\n", (unsigned int)card->ocr.ocr);
    SD_LOGN("    vol_window  : 0x%08x\n", (unsigned int)card->ocr.vol_window);
    SD_LOGN("    to_1v8_acpt : %x\n", (unsigned int)card->ocr.to_1v8_acpt);
    SD_LOGN("    high_capac  : %x\n", (unsigned int)card->ocr.high_capacity);
    SD_LOGN("Card CSD      :\n");
    SD_LOGN("    speed       : %u KHz\n", (unsigned int)speed_hz/1000);
#if ((defined CONFIG_USE_SD) || (defined CONFIG_USE_MMC))
    SD_LOGN("    cmd class   : 0x%x\n", (unsigned int)card->csd.cmdclass);
    SD_LOGN("    capacity    : %dMB\n", (unsigned int)card->csd.capacity/1024);
    SD_LOGN("Card CUR_STA  :\n");
    SD_LOGN("    speed_mode  : %s\n", speed_mode);
    SD_LOGN("    bus_width   : %d\n", (unsigned int)card->bus_width);
    SD_LOGN("    speed_class : %d\n", (unsigned int)card->speed_class);
#else
    (void)speed_mode;
#endif
    SD_LOGN("=============================================\n");
    (void)spec_ver;
    (void)type;
    (void)speed_hz;
    (void)speed_mode;

    mmc_card_set_present(card);
}

#if ((defined CONFIG_USE_SD) || (defined CONFIG_USE_MMC))
int mmc_set_blocklen(struct mmc_card *card, unsigned int blocklen)
{
    struct mmc_command cmd = {0};

    if (mmc_card_blockaddr(card) || mmc_card_ddr_mode(card))
        return 0;

    cmd.opcode = MMC_SET_BLOCKLEN;
    cmd.arg = blocklen;
    cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
    return mmc_wait_for_cmd(card->host, &cmd);
}

/**
 * @brief read SD card.
 * @param card:
 *        @arg card->card handler.
 * @param buf:
 *        @arg buf->for store readed data.
 * @param sblk:
 *        @arg sblk->start block num.
 * @param nblk:
 *        @arg nblk->number of blocks.
 * @retval  0 if success or other if failed.
 */
int32_t mmc_block_read(struct mmc_card *card, uint8_t *buf, uint64_t sblk, uint32_t nblk)
{
    int32_t err;
    struct scatterlist sg = {0};

    if (!card || !card->host) {
        SD_LOGE_RAW(ROM_ERR_MASK, "%s,%d err", __func__, __LINE__);
        return -1;
    }

    if (nblk > SDXC_MAX_TRANS_LEN/512) {
        SD_LOGW("%s only support len < %d\n", __func__, SDXC_MAX_TRANS_LEN/512);
        return -1;
    }

    if (card->suspend) {
        SD_LOGW("%s id:%d has suspend\n", __func__, (unsigned int)card->id);
        return -1;
    }

    mmc_claim_host(card->host);

    err = mmc_set_blocklen(card, 512);
    if (err)
        goto out;

    sg.len = 512 * nblk;
    sg.buffer = buf;
    //if ((unsigned int)buf & 0x03) {
    //  SD_LOGW("%s buf not align 4!!!\n", __func__);
    //  return -1;
    //}

    err = __sdmmc_block_rw(card, sblk, nblk, 1, &sg, 0);

out:
    mmc_release_host(card->host);
    return err;
}

/**
 * @brief write SD card.
 * @param card:
 *        @arg card->card handler.
 * @param buf:
 *        @arg buf->data will be write.
 * @param sblk:
 *        @arg sblk->start block num.
 * @param nblk:
 *        @arg nblk->number of blocks.
 * @retval  0 if success or other if failed.
 */
int32_t mmc_block_write(struct mmc_card *card, const uint8_t *buf, uint64_t sblk, uint32_t nblk)
{
    int32_t err;
    struct scatterlist sg = {0};

    if (!card || !card->host) {
        SD_LOGE_RAW(ROM_ERR_MASK, "%s,%d err", __func__, __LINE__);
        return -1;
    }

    if (nblk > SDXC_MAX_TRANS_LEN/512) {
        SD_LOGW("%s only support block number < %d\n", __func__, SDXC_MAX_TRANS_LEN/512);
        return -1;
    }

    if (card->suspend) {
        SD_LOGW("%s id:%d has suspend\n", __func__, (unsigned int)card->id);
        return -1;
    }

    mmc_claim_host(card->host);

    err = mmc_set_blocklen(card, 512);
    if (err)
        goto out;

    sg.len = 512 * nblk;
    sg.buffer = (uint8_t *)buf;
    //if ((unsigned int)buf & 0x03) {
    //  SD_LOGW("%s buf not align 4!!!\n", __func__);
    //  return -1;
    //}

    err = __sdmmc_block_rw(card, sblk, nblk, 1, &sg, 1);

out:
    mmc_release_host(card->host);
    return err;
}
#endif

int32_t mmc_send_relative_addr(struct mmc_host *host, uint32_t *rca)
{
    struct mmc_command cmd = {0};

    cmd.opcode = SD_SEND_RELATIVE_ADDR;
    cmd.arg = 0;
    cmd.flags = MMC_RSP_R6 | MMC_CMD_BCR;

    do {
        if (mmc_wait_for_cmd(host, &cmd)) {
            return -1;
        }
        *rca = cmd.resp[0] >> 16;
    } while (!*rca);

    return 0;
}

int32_t mmc_send_if_cond(struct mmc_host *host, uint32_t ocr)
{
    struct mmc_command cmd = {0};
    int32_t err;
    static const uint8_t test_pattern = 0xAA;
    uint8_t result_pattern;

    /*
     * To support SD 2.0 cards, we must always invoke SD_SEND_IF_COND
     * before SD_APP_OP_COND. This command will harmlessly fail for
     * SD 1.0 cards.
     */
    cmd.opcode = SD_SEND_IF_COND;
    cmd.arg = ((ocr & 0xFF8000) != 0) << 8 | test_pattern;
    cmd.flags = MMC_RSP_SPI_R7 | MMC_RSP_R7 | MMC_CMD_BCR;

    err = mmc_wait_for_cmd(host, &cmd);
    if (err)
        return err;

    result_pattern = cmd.resp[0] & 0xFF;

    if (result_pattern != test_pattern)
        return -1;

    return 0;
}

int32_t mmc_select_card(struct mmc_card *card, uint32_t select)
{
    struct mmc_command cmd = {0};

    cmd.opcode = MMC_SELECT_CARD;
    if (select) {
        cmd.arg = card->rca << 16;
        cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
    } else {
        cmd.arg = 0;
        cmd.flags = MMC_RSP_NONE | MMC_CMD_AC;
    }

    if (mmc_wait_for_cmd(card->host, &cmd)) {
        return -1;
    }

    return 0;
}

int32_t mmc_all_send_cid(struct mmc_host *host, uint32_t *cid)
{
    int32_t err;
    struct mmc_command cmd = {0};

    if (!host || !cid) {
        SDC_LOGE_RAW(ROM_ERR_MASK, "%s,%d err", __func__, __LINE__);
        return -1;
    }

    cmd.opcode = MMC_ALL_SEND_CID;
    cmd.arg = 0;
    cmd.flags = MMC_RSP_R2 | MMC_CMD_BCR;

    err = mmc_wait_for_cmd(host, &cmd);
    if (err)
        return err;

    HAL_Memcpy(cid, cmd.resp, sizeof(uint32_t) * 4);

    return 0;
}

#ifdef CONFIG_SD_PM
/*
 * Assign a mmc bus handler to a host. Only one bus handler may control a
 * host at any given time.
 */
void mmc_attach_bus(struct mmc_host *host, const struct mmc_bus_ops *ops)
{
    unsigned long flags;

    if (!host || !ops) {
        SDC_LOGE_RAW(ROM_ERR_MASK, "%s,%d err", __func__, __LINE__);
        return ;
    }

    flags = HAL_EnterCriticalSection();
    SD_WARN_ON(host->bus_ops);
    host->bus_ops = ops;
    HAL_ExitCriticalSection(flags);
}

/*
 * Remove the current bus handler from a host.
 */
void mmc_detach_bus(struct mmc_host *host)
{
    unsigned long flags;

    if (!host) {
        SDC_LOGE_RAW(ROM_ERR_MASK, "%s err\n", __func__);
        return ;
    }

    if (!host->bus_ops)
        return ;

    flags = HAL_EnterCriticalSection();
    host->bus_ops = NULL;
    HAL_ExitCriticalSection(flags);
}

#endif

/**
 * @brief scan or rescan SD card.
 * @param card:
 *        @arg card->card handler.
 * @param sdc_id:
 *        @arg sdc_id->SDC ID which card on.
 * @retval  0 if success or other if failed.
 */
int32_t mmc_rescan(struct mmc_card *card, uint32_t sdc_id)
{
    int32_t err = -1;
    struct mmc_host *host = hal_sdc_open(sdc_id);

    if (!host) {
        SD_LOGE_RAW(ROM_ERR_MASK, "%s init sdc host first!!\n", __func__);
        return -1;
    }

    card->host = host;

    mmc_claim_host(host);

    mmc_power_up(host);

    /* set identification clock 400KHz */
    HAL_SDC_Update_Clk(card->host, 400000);

    /* Initialization should be done at 3.3 V I/O voltage. */
    //mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_330, 0);

    /*
     * sdio_reset sends CMD52 to reset card.  Since we do not know
     * if the card is being re-initialized, just send it.  CMD52
     * should be ignored by SD/eMMC cards.
     */
#ifdef CONFIG_USE_SDIO
    if (!card->type || card->type == MMC_TYPE_SDIO || card->type == MMC_TYPE_SD_COMBO)
        sdio_reset(host);
#endif
    mmc_go_idle(host);

#ifdef CONFIG_USE_SD
    /* cmd8 for SD2.0 */
    if (mmc_send_if_cond(host, host->ocr_avail)) {
        SD_LOGN("sd1.0 or mmc\n");
    }
#endif

    /* Order's important: probe SDIO, then SD, then MMC */
#ifdef CONFIG_USE_SDIO
    if (!card->type || card->type == MMC_TYPE_SDIO || card->type == MMC_TYPE_SD_COMBO) {
        SD_LOGN("***** Try sdio *****\n");
        if (!mmc_attach_sdio(card, host)){
            SD_LOGN("***** sdio init ok *****\n");
            err = 0;
            goto out;
        }
    }
#endif
#ifdef CONFIG_USE_SD
    if (!card->type || card->type == MMC_TYPE_SD) {
        SD_LOGN("***** Try sd *****\n");
        if (!mmc_attach_sd(card, host)){
            SD_LOGN("***** sd init ok *****\n");
            err = 0;
            goto out;
        }
    }
#endif
#ifdef CONFIG_USE_MMC
    if (!card->type || card->type == MMC_TYPE_MMC) {
        SD_LOGN("***** Try mmc *****\n");
        if (!mmc_attach_mmc(card, host)){
            SD_LOGN("***** mmc init ok *****\n");
            err = 0;
            goto out;
        }
    }
#endif

    SD_LOGD("Undown Card Detected!!\n");

#ifdef CONFIG_USE_SD
    mmc_deattach_sd(card, host);
#endif

    mmc_power_off(host);

out:
    mmc_release_host(host);
    return err;
}

/**
 * @brief deinit SD card.
 * @param card:
 *        @arg card->card handler.
 * @retval  0 if success or other if failed.
 */
int32_t mmc_card_deinit(struct mmc_card *card)
{
    struct mmc_host *host;

    if (!card || !card->host) {
        SD_LOGE_RAW(ROM_ERR_MASK, "%s err\n", __func__);
        return -1;
    }

    host = card->host;

#ifdef CONFIG_USE_SDIO
    if (mmc_card_sdio(card) || mmc_card_sd_combo(card))
        mmc_deattach_sdio(card, host);
#endif
#ifdef CONFIG_USE_SD
    if (mmc_card_sd(card))
        mmc_deattach_sd(card, host);
#endif

    mmc_power_off(host);
    hal_sdc_close(host->sdc_id);

    return 0;
}

static struct mmc_card *card_info[SDC_NUM];

struct sdio_func ** get_mmc_card_func(uint8_t card_id)
{
    struct mmc_card *card = card_info[card_id];
    if(card == NULL) {
        return NULL;
    }else {
        return card->sdio_func;
    }
}

/**
 * @brief malloc for card_info.
 * @param card_id:
 *        @arg card ID.
 * @retval  0 if success or other if failed.
 */
int32_t mmc_card_create(uint8_t card_id, SDCard_InitTypeDef *param)
{
    int ret = 0;
    struct mmc_card *card = card_info[card_id];

    if (card != NULL) {
        if (card->id == card_id) {
            SD_LOGW_RAW(param->debug_mask, "%s id:%d already!!\n", __func__, card_id);
            return 0;
        } else {
            SD_LOGE_RAW(param->debug_mask, "%s id:%d unvalid card id!!\n", __func__, card_id);
            return -1;
        }
    }

    card = HAL_Malloc(sizeof(struct mmc_card));
    if (card == NULL) {
        SD_LOGE_RAW(param->debug_mask, "%s malloc fail\n", __func__);
        ret = -1;
    } else {
        SDC_Memset(card, 0, sizeof(struct mmc_card));
        SDC_MutexCreate(&card->mutex);
        SDC_MutexLock(&card->mutex, OS_WAIT_FOREVER);
        card->id = card_id;
        printf("card id is %d\n", (unsigned int)card->id);
        card->ref = 0;
        card->debug_mask = param->debug_mask;
        if (param->type < MMC_TYPE_MAX)
            card->type = param->type;
        card_info[card_id] = card;
        SDC_MutexUnlock(&card->mutex);
        SD_LOGN("%s card:%p id:%d\n", __func__, card, (unsigned int)card->id);
    }

    return ret;
}

/**
 * @brief free for card_info.
 * @param card_id:
 *        @arg card ID.
 * @retval  0 if success or other if failed.
 */
int32_t mmc_card_delete(uint8_t card_id)
{
    int ret = -1;
    struct mmc_card *card = card_info[card_id];

    if (card == NULL || card->id != card_id) {
        SD_LOGW_RAW(ROM_WRN_MASK, "%s card not exit! card:%p id:%d del_id:%d\n", \
                __func__, card, (unsigned int)card->id, (unsigned int)card_id);
        return -1;
    }

    SDC_MutexLock(&card->mutex, OS_WAIT_FOREVER);
    if (card->ref != 0) {
        SDC_MutexUnlock(&card->mutex);
        SD_LOGW("%s fail, ref:%d\n", __func__, (unsigned int)card->ref);
        goto out;
    }
    card_info[card_id] = NULL;
    SDC_MutexUnlock(&card->mutex);
    SDC_MutexDelete(&card->mutex);
    SD_LOGN("%s card:%p id:%d\n", __func__, card, (unsigned int)card->id);
    HAL_Free(card);
    ret = 0;

out:

    return ret;
}

/**
 * @brief get pointer of mmc_card.
 * @param card_id:
 *        @arg card ID.
 * @retval  pointer of mmc_card if success or NULL if failed.
 */
struct mmc_card *mmc_card_open(uint8_t card_id)
{
    struct mmc_card *card = card_info[card_id];

    if (card == NULL || card->id != card_id) {
        SD_LOGW_RAW(ROM_WRN_MASK, "%s card not exit! id:%d\n",  __func__, card_id);
        return NULL;
    }

    SDC_MutexLock(&card->mutex, OS_WAIT_FOREVER);
    card->ref++;
    SDC_MutexUnlock(&card->mutex);
    SD_LOGD("%s card:%p id:%d\n", __func__, card, (unsigned int)card->id);

    return card;
}

/**
 * @brief close mmc_card.
 * @param card_id:
 *        @arg card ID.
 * @retval  0 if success or other if failed.
 */
int32_t mmc_card_close(uint8_t card_id)
{
    struct mmc_card *card = card_info[card_id];

    if (card == NULL || card->id != card_id || card->ref <= 0) {
        SD_LOGW_RAW(ROM_WRN_MASK, "%s fail! id:%d\n",  __func__, card_id);
        return -1;
    }

    SDC_MutexLock(&card->mutex, OS_WAIT_FOREVER);
    card->ref--;
    SDC_MutexUnlock(&card->mutex);
    SD_LOGD("%s card:%p id:%d\n", __func__, card, (unsigned int)card->id);

    return 0;
}

extern struct sdio_func *sdio_alloc_func(struct mmc_card *card);
extern int32_t sdio_add_func(struct sdio_func *func, uint32_t id);
extern int mmc_sdio_remove(struct mmc_host *host);
#define SDIO_DEBUG_SAVE_CARD
/**
 * @brief save mmc_card.
 * @param card_id:
 *        @arg card ID.
 * @retval  0 if success or other if failed.
 */
struct mmc_card_info* mmc_card_save(uint8_t card_id)
{
    struct mmc_card_info *s_card_info;
    struct mmc_card *card = card_info[card_id];
    int32_t funcs;
    int32_t i;

    s_card_info = HAL_Malloc(sizeof(struct mmc_card_info));
    if (s_card_info == NULL) {
        SD_LOGE("%s malloc fail\n", __func__);
        goto out;
    }
    //mmc_card_create(uint8_t card_id, SDCard_InitTypeDef *param);
    memcpy(&(s_card_info->card), card, sizeof(struct mmc_card));
#ifdef CONFIG_SDIO_USE_FUNS
    for (i = 0; i < card->sdio_funcs; i++) {
        memcpy(&s_card_info->sdio_func[i], card->sdio_func[i], sizeof(struct sdio_func));
    }
#else
    (void)funcs;
#endif
    s_card_info->sdc_id = card->host->sdc_id;

out:
    return s_card_info;
}

static int32_t sdio_init_func_by_func(struct mmc_card *card, uint32_t fn, struct sdio_func *sdio_func)
{
    int32_t ret;
    struct sdio_func *func;

    if (fn > SDIO_MAX_FUNCS)
        SD_LOGE("%s,%d wrong fn:%ld!\n", __func__, __LINE__, HAL_PR_SZ_L(fn));

    func = sdio_alloc_func(card);
    if (!func)
        return -1;

    func->num = fn;
    memcpy(func, sdio_func, sizeof(struct sdio_func));

    card->sdio_func[fn - 1] = func;
    printf("func address %p\n",func);
    return 0;
}
/**
 * @brief restore mmc_card.
 * @param card_id:
 *        @arg card ID.
 * @retval  0 if success or other if failed.
 */
int32_t mmc_card_restore(struct mmc_card_info *s_card_info)
{
    OS_Mutex_t *tmp_mutex;
    uint32_t card_id = s_card_info->card.id;
    uint32_t sdc_id = s_card_info->sdc_id;
    struct mmc_card *card = card_info[card_id];
    int32_t ret;
    struct mmc_host *host = hal_sdc_open(sdc_id);
    int32_t funcs;
    int32_t i;
    int err = -1;
    SDCard_InitTypeDef card_param;

    card_param.debug_mask = (ROM_INF_MASK | \
                         ROM_WRN_MASK | ROM_ERR_MASK | ROM_ANY_MASK);
    if (!host) {
        SD_LOGE_RAW(ROM_ERR_MASK, "%s init sdc host first!!\n", __func__);
        return -1;
    }

    /********reinit mmc_card struct*******/
    if (mmc_card_create(card_id, &card_param))
        goto create_fail;
    card = card_info[card_id];
    tmp_mutex = &card->mutex;
    s_card_info->card.mutex = *tmp_mutex;
    s_card_info->card.ref = 0;
    memcpy(card, &(s_card_info->card), sizeof(struct mmc_card));
    card->host = host;
    /********restore host config*********/
    mmc_claim_host(host);

    mmc_power_up(host);

    {
        /*
         * Switch to high-speed (if supported).
         * state have been restore
         */
        //mmc_card_set_highspeed(card);
        //SD_LOGN("sdio highspeed \n");

        /*
         * Change to the card's maximum speed.
         */
        HAL_SDC_Update_Clk(card->host, mmc_sdio_get_max_clock(card));

    /*
         * Switch to wider bus (if supported).
        */
    /* sd Host Controller Register SDXC_REG_WIDTH */
        HAL_SDC_Set_BusWidth(card->host, MMC_BUS_WIDTH_4);
        SD_LOGN("%s bus width type:%d\n", __func__, MMC_BUS_WIDTH_4);
    }
    card->host->card = card;
    funcs = (card->ocr.ocr >> 28) & 0x7;

    SD_LOGD("Number of I/O Functions: %02lx\n", HAL_PR_SZ_L(funcs));
    /*
     * Initialize (but don't add) all present functions.
     */
#ifdef CONFIG_SDIO_USE_FUNS
    card->sdio_funcs = 0;
    for (i = 0; i < funcs; i++, card->sdio_funcs++) {
        err = sdio_init_func_by_func(card, i + 1, &(s_card_info->sdio_func[i]));
    if (err)
            goto remove;
    }
#endif
    /*
     * First add the card to the driver model...
     */
    mmc_release_host(host);

    if (host->caps & MMC_CAP_SDIO_IRQ) {
        int ret =  OS_SemaphoreCreateBinary(&host->sdio_irq_signal);
        SDC_BUG_ON(ret!=OS_OK);
    }
    mmc_add_card(card_info[card_id]);
#ifdef CONFIG_SDIO_USE_FUNS
    for (i = 0; i < funcs; i++) {
        err = sdio_add_func(host->card->sdio_func[i], i);
        if (err)
            goto remove_added;
    }
#else
    (void)funcs;
#endif

    mmc_claim_host(host);
#ifdef CONFIG_SD_PM
    if (!card->suspend) {
        mmc_attach_bus(host, &sdio_bus_ops);
    }
#endif
    return 0;

#ifdef CONFIG_SDIO_USE_FUNS
remove_added:
    /* Remove without lock if the device has been added. */
    mmc_sdio_remove(host);
#endif
    card->host->card = NULL;
    mmc_claim_host(host);

#ifdef CONFIG_SDIO_USE_FUNS
remove:
    /* And with lock if it hasn't been added. */
    mmc_release_host(host);
    if (host->card) {
        mmc_sdio_remove(host);
        card->host->card = NULL;
    }
    mmc_claim_host(host);
#else
    card->host->card = NULL;
#endif
create_fail:
    SD_LOGE("%s: error %d whilst initialising SDIO card\n", __func__, err);

    return err;
}