mmc: if possible, poll the busy state using DAT0
[platform/kernel/u-boot.git] / drivers / mmc / mmc.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright 2008, Freescale Semiconductor, Inc
4  * Andy Fleming
5  *
6  * Based vaguely on the Linux code
7  */
8
9 #include <config.h>
10 #include <common.h>
11 #include <command.h>
12 #include <dm.h>
13 #include <dm/device-internal.h>
14 #include <errno.h>
15 #include <mmc.h>
16 #include <part.h>
17 #include <power/regulator.h>
18 #include <malloc.h>
19 #include <memalign.h>
20 #include <linux/list.h>
21 #include <div64.h>
22 #include "mmc_private.h"
23
24 static int mmc_set_signal_voltage(struct mmc *mmc, uint signal_voltage);
25 static int mmc_power_cycle(struct mmc *mmc);
26 #if !CONFIG_IS_ENABLED(MMC_TINY)
27 static int mmc_select_mode_and_width(struct mmc *mmc, uint card_caps);
28 #endif
29
30 #if !CONFIG_IS_ENABLED(DM_MMC)
31
32 static int mmc_wait_dat0(struct mmc *mmc, int state, int timeout)
33 {
34         return -ENOSYS;
35 }
36
37 __weak int board_mmc_getwp(struct mmc *mmc)
38 {
39         return -1;
40 }
41
42 int mmc_getwp(struct mmc *mmc)
43 {
44         int wp;
45
46         wp = board_mmc_getwp(mmc);
47
48         if (wp < 0) {
49                 if (mmc->cfg->ops->getwp)
50                         wp = mmc->cfg->ops->getwp(mmc);
51                 else
52                         wp = 0;
53         }
54
55         return wp;
56 }
57
58 __weak int board_mmc_getcd(struct mmc *mmc)
59 {
60         return -1;
61 }
62 #endif
63
64 #ifdef CONFIG_MMC_TRACE
65 void mmmc_trace_before_send(struct mmc *mmc, struct mmc_cmd *cmd)
66 {
67         printf("CMD_SEND:%d\n", cmd->cmdidx);
68         printf("\t\tARG\t\t\t 0x%08x\n", cmd->cmdarg);
69 }
70
71 void mmmc_trace_after_send(struct mmc *mmc, struct mmc_cmd *cmd, int ret)
72 {
73         int i;
74         u8 *ptr;
75
76         if (ret) {
77                 printf("\t\tRET\t\t\t %d\n", ret);
78         } else {
79                 switch (cmd->resp_type) {
80                 case MMC_RSP_NONE:
81                         printf("\t\tMMC_RSP_NONE\n");
82                         break;
83                 case MMC_RSP_R1:
84                         printf("\t\tMMC_RSP_R1,5,6,7 \t 0x%08x \n",
85                                 cmd->response[0]);
86                         break;
87                 case MMC_RSP_R1b:
88                         printf("\t\tMMC_RSP_R1b\t\t 0x%08x \n",
89                                 cmd->response[0]);
90                         break;
91                 case MMC_RSP_R2:
92                         printf("\t\tMMC_RSP_R2\t\t 0x%08x \n",
93                                 cmd->response[0]);
94                         printf("\t\t          \t\t 0x%08x \n",
95                                 cmd->response[1]);
96                         printf("\t\t          \t\t 0x%08x \n",
97                                 cmd->response[2]);
98                         printf("\t\t          \t\t 0x%08x \n",
99                                 cmd->response[3]);
100                         printf("\n");
101                         printf("\t\t\t\t\tDUMPING DATA\n");
102                         for (i = 0; i < 4; i++) {
103                                 int j;
104                                 printf("\t\t\t\t\t%03d - ", i*4);
105                                 ptr = (u8 *)&cmd->response[i];
106                                 ptr += 3;
107                                 for (j = 0; j < 4; j++)
108                                         printf("%02x ", *ptr--);
109                                 printf("\n");
110                         }
111                         break;
112                 case MMC_RSP_R3:
113                         printf("\t\tMMC_RSP_R3,4\t\t 0x%08x \n",
114                                 cmd->response[0]);
115                         break;
116                 default:
117                         printf("\t\tERROR MMC rsp not supported\n");
118                         break;
119                 }
120         }
121 }
122
123 void mmc_trace_state(struct mmc *mmc, struct mmc_cmd *cmd)
124 {
125         int status;
126
127         status = (cmd->response[0] & MMC_STATUS_CURR_STATE) >> 9;
128         printf("CURR STATE:%d\n", status);
129 }
130 #endif
131
132 #if CONFIG_IS_ENABLED(MMC_VERBOSE) || defined(DEBUG)
133 const char *mmc_mode_name(enum bus_mode mode)
134 {
135         static const char *const names[] = {
136               [MMC_LEGACY]      = "MMC legacy",
137               [SD_LEGACY]       = "SD Legacy",
138               [MMC_HS]          = "MMC High Speed (26MHz)",
139               [SD_HS]           = "SD High Speed (50MHz)",
140               [UHS_SDR12]       = "UHS SDR12 (25MHz)",
141               [UHS_SDR25]       = "UHS SDR25 (50MHz)",
142               [UHS_SDR50]       = "UHS SDR50 (100MHz)",
143               [UHS_SDR104]      = "UHS SDR104 (208MHz)",
144               [UHS_DDR50]       = "UHS DDR50 (50MHz)",
145               [MMC_HS_52]       = "MMC High Speed (52MHz)",
146               [MMC_DDR_52]      = "MMC DDR52 (52MHz)",
147               [MMC_HS_200]      = "HS200 (200MHz)",
148               [MMC_HS_400]      = "HS400 (200MHz)",
149         };
150
151         if (mode >= MMC_MODES_END)
152                 return "Unknown mode";
153         else
154                 return names[mode];
155 }
156 #endif
157
158 static uint mmc_mode2freq(struct mmc *mmc, enum bus_mode mode)
159 {
160         static const int freqs[] = {
161               [MMC_LEGACY]      = 25000000,
162               [SD_LEGACY]       = 25000000,
163               [MMC_HS]          = 26000000,
164               [SD_HS]           = 50000000,
165               [MMC_HS_52]       = 52000000,
166               [MMC_DDR_52]      = 52000000,
167               [UHS_SDR12]       = 25000000,
168               [UHS_SDR25]       = 50000000,
169               [UHS_SDR50]       = 100000000,
170               [UHS_DDR50]       = 50000000,
171               [UHS_SDR104]      = 208000000,
172               [MMC_HS_200]      = 200000000,
173               [MMC_HS_400]      = 200000000,
174         };
175
176         if (mode == MMC_LEGACY)
177                 return mmc->legacy_speed;
178         else if (mode >= MMC_MODES_END)
179                 return 0;
180         else
181                 return freqs[mode];
182 }
183
184 static int mmc_select_mode(struct mmc *mmc, enum bus_mode mode)
185 {
186         mmc->selected_mode = mode;
187         mmc->tran_speed = mmc_mode2freq(mmc, mode);
188         mmc->ddr_mode = mmc_is_mode_ddr(mode);
189         pr_debug("selecting mode %s (freq : %d MHz)\n", mmc_mode_name(mode),
190                  mmc->tran_speed / 1000000);
191         return 0;
192 }
193
194 #if !CONFIG_IS_ENABLED(DM_MMC)
195 int mmc_send_cmd(struct mmc *mmc, struct mmc_cmd *cmd, struct mmc_data *data)
196 {
197         int ret;
198
199         mmmc_trace_before_send(mmc, cmd);
200         ret = mmc->cfg->ops->send_cmd(mmc, cmd, data);
201         mmmc_trace_after_send(mmc, cmd, ret);
202
203         return ret;
204 }
205 #endif
206
207 int mmc_send_status(struct mmc *mmc, unsigned int *status)
208 {
209         struct mmc_cmd cmd;
210         int err, retries = 5;
211
212         cmd.cmdidx = MMC_CMD_SEND_STATUS;
213         cmd.resp_type = MMC_RSP_R1;
214         if (!mmc_host_is_spi(mmc))
215                 cmd.cmdarg = mmc->rca << 16;
216
217         while (retries--) {
218                 err = mmc_send_cmd(mmc, &cmd, NULL);
219                 if (!err) {
220                         mmc_trace_state(mmc, &cmd);
221                         *status = cmd.response[0];
222                         return 0;
223                 }
224         }
225         mmc_trace_state(mmc, &cmd);
226         return -ECOMM;
227 }
228
229 int mmc_poll_for_busy(struct mmc *mmc, int timeout)
230 {
231         unsigned int status;
232         int err;
233
234         err = mmc_wait_dat0(mmc, 1, timeout);
235         if (err != -ENOSYS)
236                 return err;
237
238         while (1) {
239                 err = mmc_send_status(mmc, &status);
240                 if (err)
241                         return err;
242
243                 if ((status & MMC_STATUS_RDY_FOR_DATA) &&
244                     (status & MMC_STATUS_CURR_STATE) !=
245                      MMC_STATE_PRG)
246                         break;
247
248                 if (status & MMC_STATUS_MASK) {
249 #if !defined(CONFIG_SPL_BUILD) || defined(CONFIG_SPL_LIBCOMMON_SUPPORT)
250                         pr_err("Status Error: 0x%08x\n", status);
251 #endif
252                         return -ECOMM;
253                 }
254
255                 if (timeout-- <= 0)
256                         break;
257
258                 udelay(1000);
259         }
260
261         if (timeout <= 0) {
262 #if !defined(CONFIG_SPL_BUILD) || defined(CONFIG_SPL_LIBCOMMON_SUPPORT)
263                 pr_err("Timeout waiting card ready\n");
264 #endif
265                 return -ETIMEDOUT;
266         }
267
268         return 0;
269 }
270
271 int mmc_set_blocklen(struct mmc *mmc, int len)
272 {
273         struct mmc_cmd cmd;
274         int err;
275
276         if (mmc->ddr_mode)
277                 return 0;
278
279         cmd.cmdidx = MMC_CMD_SET_BLOCKLEN;
280         cmd.resp_type = MMC_RSP_R1;
281         cmd.cmdarg = len;
282
283         err = mmc_send_cmd(mmc, &cmd, NULL);
284
285 #ifdef CONFIG_MMC_QUIRKS
286         if (err && (mmc->quirks & MMC_QUIRK_RETRY_SET_BLOCKLEN)) {
287                 int retries = 4;
288                 /*
289                  * It has been seen that SET_BLOCKLEN may fail on the first
290                  * attempt, let's try a few more time
291                  */
292                 do {
293                         err = mmc_send_cmd(mmc, &cmd, NULL);
294                         if (!err)
295                                 break;
296                 } while (retries--);
297         }
298 #endif
299
300         return err;
301 }
302
303 #ifdef MMC_SUPPORTS_TUNING
304 static const u8 tuning_blk_pattern_4bit[] = {
305         0xff, 0x0f, 0xff, 0x00, 0xff, 0xcc, 0xc3, 0xcc,
306         0xc3, 0x3c, 0xcc, 0xff, 0xfe, 0xff, 0xfe, 0xef,
307         0xff, 0xdf, 0xff, 0xdd, 0xff, 0xfb, 0xff, 0xfb,
308         0xbf, 0xff, 0x7f, 0xff, 0x77, 0xf7, 0xbd, 0xef,
309         0xff, 0xf0, 0xff, 0xf0, 0x0f, 0xfc, 0xcc, 0x3c,
310         0xcc, 0x33, 0xcc, 0xcf, 0xff, 0xef, 0xff, 0xee,
311         0xff, 0xfd, 0xff, 0xfd, 0xdf, 0xff, 0xbf, 0xff,
312         0xbb, 0xff, 0xf7, 0xff, 0xf7, 0x7f, 0x7b, 0xde,
313 };
314
315 static const u8 tuning_blk_pattern_8bit[] = {
316         0xff, 0xff, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00,
317         0xff, 0xff, 0xcc, 0xcc, 0xcc, 0x33, 0xcc, 0xcc,
318         0xcc, 0x33, 0x33, 0xcc, 0xcc, 0xcc, 0xff, 0xff,
319         0xff, 0xee, 0xff, 0xff, 0xff, 0xee, 0xee, 0xff,
320         0xff, 0xff, 0xdd, 0xff, 0xff, 0xff, 0xdd, 0xdd,
321         0xff, 0xff, 0xff, 0xbb, 0xff, 0xff, 0xff, 0xbb,
322         0xbb, 0xff, 0xff, 0xff, 0x77, 0xff, 0xff, 0xff,
323         0x77, 0x77, 0xff, 0x77, 0xbb, 0xdd, 0xee, 0xff,
324         0xff, 0xff, 0xff, 0x00, 0xff, 0xff, 0xff, 0x00,
325         0x00, 0xff, 0xff, 0xcc, 0xcc, 0xcc, 0x33, 0xcc,
326         0xcc, 0xcc, 0x33, 0x33, 0xcc, 0xcc, 0xcc, 0xff,
327         0xff, 0xff, 0xee, 0xff, 0xff, 0xff, 0xee, 0xee,
328         0xff, 0xff, 0xff, 0xdd, 0xff, 0xff, 0xff, 0xdd,
329         0xdd, 0xff, 0xff, 0xff, 0xbb, 0xff, 0xff, 0xff,
330         0xbb, 0xbb, 0xff, 0xff, 0xff, 0x77, 0xff, 0xff,
331         0xff, 0x77, 0x77, 0xff, 0x77, 0xbb, 0xdd, 0xee,
332 };
333
334 int mmc_send_tuning(struct mmc *mmc, u32 opcode, int *cmd_error)
335 {
336         struct mmc_cmd cmd;
337         struct mmc_data data;
338         const u8 *tuning_block_pattern;
339         int size, err;
340
341         if (mmc->bus_width == 8) {
342                 tuning_block_pattern = tuning_blk_pattern_8bit;
343                 size = sizeof(tuning_blk_pattern_8bit);
344         } else if (mmc->bus_width == 4) {
345                 tuning_block_pattern = tuning_blk_pattern_4bit;
346                 size = sizeof(tuning_blk_pattern_4bit);
347         } else {
348                 return -EINVAL;
349         }
350
351         ALLOC_CACHE_ALIGN_BUFFER(u8, data_buf, size);
352
353         cmd.cmdidx = opcode;
354         cmd.cmdarg = 0;
355         cmd.resp_type = MMC_RSP_R1;
356
357         data.dest = (void *)data_buf;
358         data.blocks = 1;
359         data.blocksize = size;
360         data.flags = MMC_DATA_READ;
361
362         err = mmc_send_cmd(mmc, &cmd, &data);
363         if (err)
364                 return err;
365
366         if (memcmp(data_buf, tuning_block_pattern, size))
367                 return -EIO;
368
369         return 0;
370 }
371 #endif
372
373 static int mmc_read_blocks(struct mmc *mmc, void *dst, lbaint_t start,
374                            lbaint_t blkcnt)
375 {
376         struct mmc_cmd cmd;
377         struct mmc_data data;
378
379         if (blkcnt > 1)
380                 cmd.cmdidx = MMC_CMD_READ_MULTIPLE_BLOCK;
381         else
382                 cmd.cmdidx = MMC_CMD_READ_SINGLE_BLOCK;
383
384         if (mmc->high_capacity)
385                 cmd.cmdarg = start;
386         else
387                 cmd.cmdarg = start * mmc->read_bl_len;
388
389         cmd.resp_type = MMC_RSP_R1;
390
391         data.dest = dst;
392         data.blocks = blkcnt;
393         data.blocksize = mmc->read_bl_len;
394         data.flags = MMC_DATA_READ;
395
396         if (mmc_send_cmd(mmc, &cmd, &data))
397                 return 0;
398
399         if (blkcnt > 1) {
400                 cmd.cmdidx = MMC_CMD_STOP_TRANSMISSION;
401                 cmd.cmdarg = 0;
402                 cmd.resp_type = MMC_RSP_R1b;
403                 if (mmc_send_cmd(mmc, &cmd, NULL)) {
404 #if !defined(CONFIG_SPL_BUILD) || defined(CONFIG_SPL_LIBCOMMON_SUPPORT)
405                         pr_err("mmc fail to send stop cmd\n");
406 #endif
407                         return 0;
408                 }
409         }
410
411         return blkcnt;
412 }
413
414 #if CONFIG_IS_ENABLED(BLK)
415 ulong mmc_bread(struct udevice *dev, lbaint_t start, lbaint_t blkcnt, void *dst)
416 #else
417 ulong mmc_bread(struct blk_desc *block_dev, lbaint_t start, lbaint_t blkcnt,
418                 void *dst)
419 #endif
420 {
421 #if CONFIG_IS_ENABLED(BLK)
422         struct blk_desc *block_dev = dev_get_uclass_platdata(dev);
423 #endif
424         int dev_num = block_dev->devnum;
425         int err;
426         lbaint_t cur, blocks_todo = blkcnt;
427
428         if (blkcnt == 0)
429                 return 0;
430
431         struct mmc *mmc = find_mmc_device(dev_num);
432         if (!mmc)
433                 return 0;
434
435         if (CONFIG_IS_ENABLED(MMC_TINY))
436                 err = mmc_switch_part(mmc, block_dev->hwpart);
437         else
438                 err = blk_dselect_hwpart(block_dev, block_dev->hwpart);
439
440         if (err < 0)
441                 return 0;
442
443         if ((start + blkcnt) > block_dev->lba) {
444 #if !defined(CONFIG_SPL_BUILD) || defined(CONFIG_SPL_LIBCOMMON_SUPPORT)
445                 pr_err("MMC: block number 0x" LBAF " exceeds max(0x" LBAF ")\n",
446                        start + blkcnt, block_dev->lba);
447 #endif
448                 return 0;
449         }
450
451         if (mmc_set_blocklen(mmc, mmc->read_bl_len)) {
452                 pr_debug("%s: Failed to set blocklen\n", __func__);
453                 return 0;
454         }
455
456         do {
457                 cur = (blocks_todo > mmc->cfg->b_max) ?
458                         mmc->cfg->b_max : blocks_todo;
459                 if (mmc_read_blocks(mmc, dst, start, cur) != cur) {
460                         pr_debug("%s: Failed to read blocks\n", __func__);
461                         return 0;
462                 }
463                 blocks_todo -= cur;
464                 start += cur;
465                 dst += cur * mmc->read_bl_len;
466         } while (blocks_todo > 0);
467
468         return blkcnt;
469 }
470
471 static int mmc_go_idle(struct mmc *mmc)
472 {
473         struct mmc_cmd cmd;
474         int err;
475
476         udelay(1000);
477
478         cmd.cmdidx = MMC_CMD_GO_IDLE_STATE;
479         cmd.cmdarg = 0;
480         cmd.resp_type = MMC_RSP_NONE;
481
482         err = mmc_send_cmd(mmc, &cmd, NULL);
483
484         if (err)
485                 return err;
486
487         udelay(2000);
488
489         return 0;
490 }
491
492 #if CONFIG_IS_ENABLED(MMC_UHS_SUPPORT)
493 static int mmc_switch_voltage(struct mmc *mmc, int signal_voltage)
494 {
495         struct mmc_cmd cmd;
496         int err = 0;
497
498         /*
499          * Send CMD11 only if the request is to switch the card to
500          * 1.8V signalling.
501          */
502         if (signal_voltage == MMC_SIGNAL_VOLTAGE_330)
503                 return mmc_set_signal_voltage(mmc, signal_voltage);
504
505         cmd.cmdidx = SD_CMD_SWITCH_UHS18V;
506         cmd.cmdarg = 0;
507         cmd.resp_type = MMC_RSP_R1;
508
509         err = mmc_send_cmd(mmc, &cmd, NULL);
510         if (err)
511                 return err;
512
513         if (!mmc_host_is_spi(mmc) && (cmd.response[0] & MMC_STATUS_ERROR))
514                 return -EIO;
515
516         /*
517          * The card should drive cmd and dat[0:3] low immediately
518          * after the response of cmd11, but wait 100 us to be sure
519          */
520         err = mmc_wait_dat0(mmc, 0, 100);
521         if (err == -ENOSYS)
522                 udelay(100);
523         else if (err)
524                 return -ETIMEDOUT;
525
526         /*
527          * During a signal voltage level switch, the clock must be gated
528          * for 5 ms according to the SD spec
529          */
530         mmc_set_clock(mmc, mmc->clock, MMC_CLK_DISABLE);
531
532         err = mmc_set_signal_voltage(mmc, signal_voltage);
533         if (err)
534                 return err;
535
536         /* Keep clock gated for at least 10 ms, though spec only says 5 ms */
537         mdelay(10);
538         mmc_set_clock(mmc, mmc->clock, MMC_CLK_ENABLE);
539
540         /*
541          * Failure to switch is indicated by the card holding
542          * dat[0:3] low. Wait for at least 1 ms according to spec
543          */
544         err = mmc_wait_dat0(mmc, 1, 1000);
545         if (err == -ENOSYS)
546                 udelay(1000);
547         else if (err)
548                 return -ETIMEDOUT;
549
550         return 0;
551 }
552 #endif
553
554 static int sd_send_op_cond(struct mmc *mmc, bool uhs_en)
555 {
556         int timeout = 1000;
557         int err;
558         struct mmc_cmd cmd;
559
560         while (1) {
561                 cmd.cmdidx = MMC_CMD_APP_CMD;
562                 cmd.resp_type = MMC_RSP_R1;
563                 cmd.cmdarg = 0;
564
565                 err = mmc_send_cmd(mmc, &cmd, NULL);
566
567                 if (err)
568                         return err;
569
570                 cmd.cmdidx = SD_CMD_APP_SEND_OP_COND;
571                 cmd.resp_type = MMC_RSP_R3;
572
573                 /*
574                  * Most cards do not answer if some reserved bits
575                  * in the ocr are set. However, Some controller
576                  * can set bit 7 (reserved for low voltages), but
577                  * how to manage low voltages SD card is not yet
578                  * specified.
579                  */
580                 cmd.cmdarg = mmc_host_is_spi(mmc) ? 0 :
581                         (mmc->cfg->voltages & 0xff8000);
582
583                 if (mmc->version == SD_VERSION_2)
584                         cmd.cmdarg |= OCR_HCS;
585
586                 if (uhs_en)
587                         cmd.cmdarg |= OCR_S18R;
588
589                 err = mmc_send_cmd(mmc, &cmd, NULL);
590
591                 if (err)
592                         return err;
593
594                 if (cmd.response[0] & OCR_BUSY)
595                         break;
596
597                 if (timeout-- <= 0)
598                         return -EOPNOTSUPP;
599
600                 udelay(1000);
601         }
602
603         if (mmc->version != SD_VERSION_2)
604                 mmc->version = SD_VERSION_1_0;
605
606         if (mmc_host_is_spi(mmc)) { /* read OCR for spi */
607                 cmd.cmdidx = MMC_CMD_SPI_READ_OCR;
608                 cmd.resp_type = MMC_RSP_R3;
609                 cmd.cmdarg = 0;
610
611                 err = mmc_send_cmd(mmc, &cmd, NULL);
612
613                 if (err)
614                         return err;
615         }
616
617         mmc->ocr = cmd.response[0];
618
619 #if CONFIG_IS_ENABLED(MMC_UHS_SUPPORT)
620         if (uhs_en && !(mmc_host_is_spi(mmc)) && (cmd.response[0] & 0x41000000)
621             == 0x41000000) {
622                 err = mmc_switch_voltage(mmc, MMC_SIGNAL_VOLTAGE_180);
623                 if (err)
624                         return err;
625         }
626 #endif
627
628         mmc->high_capacity = ((mmc->ocr & OCR_HCS) == OCR_HCS);
629         mmc->rca = 0;
630
631         return 0;
632 }
633
634 static int mmc_send_op_cond_iter(struct mmc *mmc, int use_arg)
635 {
636         struct mmc_cmd cmd;
637         int err;
638
639         cmd.cmdidx = MMC_CMD_SEND_OP_COND;
640         cmd.resp_type = MMC_RSP_R3;
641         cmd.cmdarg = 0;
642         if (use_arg && !mmc_host_is_spi(mmc))
643                 cmd.cmdarg = OCR_HCS |
644                         (mmc->cfg->voltages &
645                         (mmc->ocr & OCR_VOLTAGE_MASK)) |
646                         (mmc->ocr & OCR_ACCESS_MODE);
647
648         err = mmc_send_cmd(mmc, &cmd, NULL);
649         if (err)
650                 return err;
651         mmc->ocr = cmd.response[0];
652         return 0;
653 }
654
655 static int mmc_send_op_cond(struct mmc *mmc)
656 {
657         int err, i;
658
659         /* Some cards seem to need this */
660         mmc_go_idle(mmc);
661
662         /* Asking to the card its capabilities */
663         for (i = 0; i < 2; i++) {
664                 err = mmc_send_op_cond_iter(mmc, i != 0);
665                 if (err)
666                         return err;
667
668                 /* exit if not busy (flag seems to be inverted) */
669                 if (mmc->ocr & OCR_BUSY)
670                         break;
671         }
672         mmc->op_cond_pending = 1;
673         return 0;
674 }
675
676 static int mmc_complete_op_cond(struct mmc *mmc)
677 {
678         struct mmc_cmd cmd;
679         int timeout = 1000;
680         ulong start;
681         int err;
682
683         mmc->op_cond_pending = 0;
684         if (!(mmc->ocr & OCR_BUSY)) {
685                 /* Some cards seem to need this */
686                 mmc_go_idle(mmc);
687
688                 start = get_timer(0);
689                 while (1) {
690                         err = mmc_send_op_cond_iter(mmc, 1);
691                         if (err)
692                                 return err;
693                         if (mmc->ocr & OCR_BUSY)
694                                 break;
695                         if (get_timer(start) > timeout)
696                                 return -EOPNOTSUPP;
697                         udelay(100);
698                 }
699         }
700
701         if (mmc_host_is_spi(mmc)) { /* read OCR for spi */
702                 cmd.cmdidx = MMC_CMD_SPI_READ_OCR;
703                 cmd.resp_type = MMC_RSP_R3;
704                 cmd.cmdarg = 0;
705
706                 err = mmc_send_cmd(mmc, &cmd, NULL);
707
708                 if (err)
709                         return err;
710
711                 mmc->ocr = cmd.response[0];
712         }
713
714         mmc->version = MMC_VERSION_UNKNOWN;
715
716         mmc->high_capacity = ((mmc->ocr & OCR_HCS) == OCR_HCS);
717         mmc->rca = 1;
718
719         return 0;
720 }
721
722
723 static int mmc_send_ext_csd(struct mmc *mmc, u8 *ext_csd)
724 {
725         struct mmc_cmd cmd;
726         struct mmc_data data;
727         int err;
728
729         /* Get the Card Status Register */
730         cmd.cmdidx = MMC_CMD_SEND_EXT_CSD;
731         cmd.resp_type = MMC_RSP_R1;
732         cmd.cmdarg = 0;
733
734         data.dest = (char *)ext_csd;
735         data.blocks = 1;
736         data.blocksize = MMC_MAX_BLOCK_LEN;
737         data.flags = MMC_DATA_READ;
738
739         err = mmc_send_cmd(mmc, &cmd, &data);
740
741         return err;
742 }
743
744 static int __mmc_switch(struct mmc *mmc, u8 set, u8 index, u8 value,
745                         bool send_status)
746 {
747         struct mmc_cmd cmd;
748         int timeout = 1000;
749         int retries = 3;
750         int ret;
751
752         cmd.cmdidx = MMC_CMD_SWITCH;
753         cmd.resp_type = MMC_RSP_R1b;
754         cmd.cmdarg = (MMC_SWITCH_MODE_WRITE_BYTE << 24) |
755                                  (index << 16) |
756                                  (value << 8);
757
758         while (retries > 0) {
759                 ret = mmc_send_cmd(mmc, &cmd, NULL);
760
761                 if (ret) {
762                         retries--;
763                         continue;
764                 }
765
766                 if (!send_status) {
767                         mdelay(50);
768                         return 0;
769                 }
770
771                 /* Waiting for the ready status */
772                 return mmc_poll_for_busy(mmc, timeout);
773         }
774
775         return ret;
776
777 }
778
779 int mmc_switch(struct mmc *mmc, u8 set, u8 index, u8 value)
780 {
781         return __mmc_switch(mmc, set, index, value, true);
782 }
783
784 #if !CONFIG_IS_ENABLED(MMC_TINY)
785 static int mmc_set_card_speed(struct mmc *mmc, enum bus_mode mode,
786                               bool hsdowngrade)
787 {
788         int err;
789         int speed_bits;
790
791         ALLOC_CACHE_ALIGN_BUFFER(u8, test_csd, MMC_MAX_BLOCK_LEN);
792
793         switch (mode) {
794         case MMC_HS:
795         case MMC_HS_52:
796         case MMC_DDR_52:
797                 speed_bits = EXT_CSD_TIMING_HS;
798                 break;
799 #if CONFIG_IS_ENABLED(MMC_HS200_SUPPORT)
800         case MMC_HS_200:
801                 speed_bits = EXT_CSD_TIMING_HS200;
802                 break;
803 #endif
804 #if CONFIG_IS_ENABLED(MMC_HS400_SUPPORT)
805         case MMC_HS_400:
806                 speed_bits = EXT_CSD_TIMING_HS400;
807                 break;
808 #endif
809         case MMC_LEGACY:
810                 speed_bits = EXT_CSD_TIMING_LEGACY;
811                 break;
812         default:
813                 return -EINVAL;
814         }
815
816         err = __mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_HS_TIMING,
817                            speed_bits, !hsdowngrade);
818         if (err)
819                 return err;
820
821 #if CONFIG_IS_ENABLED(MMC_HS200_SUPPORT) || \
822     CONFIG_IS_ENABLED(MMC_HS400_SUPPORT)
823         /*
824          * In case the eMMC is in HS200/HS400 mode and we are downgrading
825          * to HS mode, the card clock are still running much faster than
826          * the supported HS mode clock, so we can not reliably read out
827          * Extended CSD. Reconfigure the controller to run at HS mode.
828          */
829         if (hsdowngrade) {
830                 mmc_select_mode(mmc, MMC_HS);
831                 mmc_set_clock(mmc, mmc_mode2freq(mmc, MMC_HS), false);
832         }
833 #endif
834
835         if ((mode == MMC_HS) || (mode == MMC_HS_52)) {
836                 /* Now check to see that it worked */
837                 err = mmc_send_ext_csd(mmc, test_csd);
838                 if (err)
839                         return err;
840
841                 /* No high-speed support */
842                 if (!test_csd[EXT_CSD_HS_TIMING])
843                         return -ENOTSUPP;
844         }
845
846         return 0;
847 }
848
849 static int mmc_get_capabilities(struct mmc *mmc)
850 {
851         u8 *ext_csd = mmc->ext_csd;
852         char cardtype;
853
854         mmc->card_caps = MMC_MODE_1BIT | MMC_CAP(MMC_LEGACY);
855
856         if (mmc_host_is_spi(mmc))
857                 return 0;
858
859         /* Only version 4 supports high-speed */
860         if (mmc->version < MMC_VERSION_4)
861                 return 0;
862
863         if (!ext_csd) {
864                 pr_err("No ext_csd found!\n"); /* this should enver happen */
865                 return -ENOTSUPP;
866         }
867
868         mmc->card_caps |= MMC_MODE_4BIT | MMC_MODE_8BIT;
869
870         cardtype = ext_csd[EXT_CSD_CARD_TYPE];
871         mmc->cardtype = cardtype;
872
873 #if CONFIG_IS_ENABLED(MMC_HS200_SUPPORT)
874         if (cardtype & (EXT_CSD_CARD_TYPE_HS200_1_2V |
875                         EXT_CSD_CARD_TYPE_HS200_1_8V)) {
876                 mmc->card_caps |= MMC_MODE_HS200;
877         }
878 #endif
879 #if CONFIG_IS_ENABLED(MMC_HS400_SUPPORT)
880         if (cardtype & (EXT_CSD_CARD_TYPE_HS400_1_2V |
881                         EXT_CSD_CARD_TYPE_HS400_1_8V)) {
882                 mmc->card_caps |= MMC_MODE_HS400;
883         }
884 #endif
885         if (cardtype & EXT_CSD_CARD_TYPE_52) {
886                 if (cardtype & EXT_CSD_CARD_TYPE_DDR_52)
887                         mmc->card_caps |= MMC_MODE_DDR_52MHz;
888                 mmc->card_caps |= MMC_MODE_HS_52MHz;
889         }
890         if (cardtype & EXT_CSD_CARD_TYPE_26)
891                 mmc->card_caps |= MMC_MODE_HS;
892
893         return 0;
894 }
895 #endif
896
897 static int mmc_set_capacity(struct mmc *mmc, int part_num)
898 {
899         switch (part_num) {
900         case 0:
901                 mmc->capacity = mmc->capacity_user;
902                 break;
903         case 1:
904         case 2:
905                 mmc->capacity = mmc->capacity_boot;
906                 break;
907         case 3:
908                 mmc->capacity = mmc->capacity_rpmb;
909                 break;
910         case 4:
911         case 5:
912         case 6:
913         case 7:
914                 mmc->capacity = mmc->capacity_gp[part_num - 4];
915                 break;
916         default:
917                 return -1;
918         }
919
920         mmc_get_blk_desc(mmc)->lba = lldiv(mmc->capacity, mmc->read_bl_len);
921
922         return 0;
923 }
924
925 #if CONFIG_IS_ENABLED(MMC_HS200_SUPPORT) || CONFIG_IS_ENABLED(MMC_HS400_SUPPORT)
926 static int mmc_boot_part_access_chk(struct mmc *mmc, unsigned int part_num)
927 {
928         int forbidden = 0;
929         bool change = false;
930
931         if (part_num & PART_ACCESS_MASK)
932                 forbidden = MMC_CAP(MMC_HS_200) | MMC_CAP(MMC_HS_400);
933
934         if (MMC_CAP(mmc->selected_mode) & forbidden) {
935                 pr_debug("selected mode (%s) is forbidden for part %d\n",
936                          mmc_mode_name(mmc->selected_mode), part_num);
937                 change = true;
938         } else if (mmc->selected_mode != mmc->best_mode) {
939                 pr_debug("selected mode is not optimal\n");
940                 change = true;
941         }
942
943         if (change)
944                 return mmc_select_mode_and_width(mmc,
945                                                  mmc->card_caps & ~forbidden);
946
947         return 0;
948 }
949 #else
950 static inline int mmc_boot_part_access_chk(struct mmc *mmc,
951                                            unsigned int part_num)
952 {
953         return 0;
954 }
955 #endif
956
957 int mmc_switch_part(struct mmc *mmc, unsigned int part_num)
958 {
959         int ret;
960
961         ret = mmc_boot_part_access_chk(mmc, part_num);
962         if (ret)
963                 return ret;
964
965         ret = mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_PART_CONF,
966                          (mmc->part_config & ~PART_ACCESS_MASK)
967                          | (part_num & PART_ACCESS_MASK));
968
969         /*
970          * Set the capacity if the switch succeeded or was intended
971          * to return to representing the raw device.
972          */
973         if ((ret == 0) || ((ret == -ENODEV) && (part_num == 0))) {
974                 ret = mmc_set_capacity(mmc, part_num);
975                 mmc_get_blk_desc(mmc)->hwpart = part_num;
976         }
977
978         return ret;
979 }
980
981 #if CONFIG_IS_ENABLED(MMC_HW_PARTITIONING)
982 int mmc_hwpart_config(struct mmc *mmc,
983                       const struct mmc_hwpart_conf *conf,
984                       enum mmc_hwpart_conf_mode mode)
985 {
986         u8 part_attrs = 0;
987         u32 enh_size_mult;
988         u32 enh_start_addr;
989         u32 gp_size_mult[4];
990         u32 max_enh_size_mult;
991         u32 tot_enh_size_mult = 0;
992         u8 wr_rel_set;
993         int i, pidx, err;
994         ALLOC_CACHE_ALIGN_BUFFER(u8, ext_csd, MMC_MAX_BLOCK_LEN);
995
996         if (mode < MMC_HWPART_CONF_CHECK || mode > MMC_HWPART_CONF_COMPLETE)
997                 return -EINVAL;
998
999         if (IS_SD(mmc) || (mmc->version < MMC_VERSION_4_41)) {
1000                 pr_err("eMMC >= 4.4 required for enhanced user data area\n");
1001                 return -EMEDIUMTYPE;
1002         }
1003
1004         if (!(mmc->part_support & PART_SUPPORT)) {
1005                 pr_err("Card does not support partitioning\n");
1006                 return -EMEDIUMTYPE;
1007         }
1008
1009         if (!mmc->hc_wp_grp_size) {
1010                 pr_err("Card does not define HC WP group size\n");
1011                 return -EMEDIUMTYPE;
1012         }
1013
1014         /* check partition alignment and total enhanced size */
1015         if (conf->user.enh_size) {
1016                 if (conf->user.enh_size % mmc->hc_wp_grp_size ||
1017                     conf->user.enh_start % mmc->hc_wp_grp_size) {
1018                         pr_err("User data enhanced area not HC WP group "
1019                                "size aligned\n");
1020                         return -EINVAL;
1021                 }
1022                 part_attrs |= EXT_CSD_ENH_USR;
1023                 enh_size_mult = conf->user.enh_size / mmc->hc_wp_grp_size;
1024                 if (mmc->high_capacity) {
1025                         enh_start_addr = conf->user.enh_start;
1026                 } else {
1027                         enh_start_addr = (conf->user.enh_start << 9);
1028                 }
1029         } else {
1030                 enh_size_mult = 0;
1031                 enh_start_addr = 0;
1032         }
1033         tot_enh_size_mult += enh_size_mult;
1034
1035         for (pidx = 0; pidx < 4; pidx++) {
1036                 if (conf->gp_part[pidx].size % mmc->hc_wp_grp_size) {
1037                         pr_err("GP%i partition not HC WP group size "
1038                                "aligned\n", pidx+1);
1039                         return -EINVAL;
1040                 }
1041                 gp_size_mult[pidx] = conf->gp_part[pidx].size / mmc->hc_wp_grp_size;
1042                 if (conf->gp_part[pidx].size && conf->gp_part[pidx].enhanced) {
1043                         part_attrs |= EXT_CSD_ENH_GP(pidx);
1044                         tot_enh_size_mult += gp_size_mult[pidx];
1045                 }
1046         }
1047
1048         if (part_attrs && ! (mmc->part_support & ENHNCD_SUPPORT)) {
1049                 pr_err("Card does not support enhanced attribute\n");
1050                 return -EMEDIUMTYPE;
1051         }
1052
1053         err = mmc_send_ext_csd(mmc, ext_csd);
1054         if (err)
1055                 return err;
1056
1057         max_enh_size_mult =
1058                 (ext_csd[EXT_CSD_MAX_ENH_SIZE_MULT+2] << 16) +
1059                 (ext_csd[EXT_CSD_MAX_ENH_SIZE_MULT+1] << 8) +
1060                 ext_csd[EXT_CSD_MAX_ENH_SIZE_MULT];
1061         if (tot_enh_size_mult > max_enh_size_mult) {
1062                 pr_err("Total enhanced size exceeds maximum (%u > %u)\n",
1063                        tot_enh_size_mult, max_enh_size_mult);
1064                 return -EMEDIUMTYPE;
1065         }
1066
1067         /* The default value of EXT_CSD_WR_REL_SET is device
1068          * dependent, the values can only be changed if the
1069          * EXT_CSD_HS_CTRL_REL bit is set. The values can be
1070          * changed only once and before partitioning is completed. */
1071         wr_rel_set = ext_csd[EXT_CSD_WR_REL_SET];
1072         if (conf->user.wr_rel_change) {
1073                 if (conf->user.wr_rel_set)
1074                         wr_rel_set |= EXT_CSD_WR_DATA_REL_USR;
1075                 else
1076                         wr_rel_set &= ~EXT_CSD_WR_DATA_REL_USR;
1077         }
1078         for (pidx = 0; pidx < 4; pidx++) {
1079                 if (conf->gp_part[pidx].wr_rel_change) {
1080                         if (conf->gp_part[pidx].wr_rel_set)
1081                                 wr_rel_set |= EXT_CSD_WR_DATA_REL_GP(pidx);
1082                         else
1083                                 wr_rel_set &= ~EXT_CSD_WR_DATA_REL_GP(pidx);
1084                 }
1085         }
1086
1087         if (wr_rel_set != ext_csd[EXT_CSD_WR_REL_SET] &&
1088             !(ext_csd[EXT_CSD_WR_REL_PARAM] & EXT_CSD_HS_CTRL_REL)) {
1089                 puts("Card does not support host controlled partition write "
1090                      "reliability settings\n");
1091                 return -EMEDIUMTYPE;
1092         }
1093
1094         if (ext_csd[EXT_CSD_PARTITION_SETTING] &
1095             EXT_CSD_PARTITION_SETTING_COMPLETED) {
1096                 pr_err("Card already partitioned\n");
1097                 return -EPERM;
1098         }
1099
1100         if (mode == MMC_HWPART_CONF_CHECK)
1101                 return 0;
1102
1103         /* Partitioning requires high-capacity size definitions */
1104         if (!(ext_csd[EXT_CSD_ERASE_GROUP_DEF] & 0x01)) {
1105                 err = mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL,
1106                                  EXT_CSD_ERASE_GROUP_DEF, 1);
1107
1108                 if (err)
1109                         return err;
1110
1111                 ext_csd[EXT_CSD_ERASE_GROUP_DEF] = 1;
1112
1113                 /* update erase group size to be high-capacity */
1114                 mmc->erase_grp_size =
1115                         ext_csd[EXT_CSD_HC_ERASE_GRP_SIZE] * 1024;
1116
1117         }
1118
1119         /* all OK, write the configuration */
1120         for (i = 0; i < 4; i++) {
1121                 err = mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL,
1122                                  EXT_CSD_ENH_START_ADDR+i,
1123                                  (enh_start_addr >> (i*8)) & 0xFF);
1124                 if (err)
1125                         return err;
1126         }
1127         for (i = 0; i < 3; i++) {
1128                 err = mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL,
1129                                  EXT_CSD_ENH_SIZE_MULT+i,
1130                                  (enh_size_mult >> (i*8)) & 0xFF);
1131                 if (err)
1132                         return err;
1133         }
1134         for (pidx = 0; pidx < 4; pidx++) {
1135                 for (i = 0; i < 3; i++) {
1136                         err = mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL,
1137                                          EXT_CSD_GP_SIZE_MULT+pidx*3+i,
1138                                          (gp_size_mult[pidx] >> (i*8)) & 0xFF);
1139                         if (err)
1140                                 return err;
1141                 }
1142         }
1143         err = mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL,
1144                          EXT_CSD_PARTITIONS_ATTRIBUTE, part_attrs);
1145         if (err)
1146                 return err;
1147
1148         if (mode == MMC_HWPART_CONF_SET)
1149                 return 0;
1150
1151         /* The WR_REL_SET is a write-once register but shall be
1152          * written before setting PART_SETTING_COMPLETED. As it is
1153          * write-once we can only write it when completing the
1154          * partitioning. */
1155         if (wr_rel_set != ext_csd[EXT_CSD_WR_REL_SET]) {
1156                 err = mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL,
1157                                  EXT_CSD_WR_REL_SET, wr_rel_set);
1158                 if (err)
1159                         return err;
1160         }
1161
1162         /* Setting PART_SETTING_COMPLETED confirms the partition
1163          * configuration but it only becomes effective after power
1164          * cycle, so we do not adjust the partition related settings
1165          * in the mmc struct. */
1166
1167         err = mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL,
1168                          EXT_CSD_PARTITION_SETTING,
1169                          EXT_CSD_PARTITION_SETTING_COMPLETED);
1170         if (err)
1171                 return err;
1172
1173         return 0;
1174 }
1175 #endif
1176
1177 #if !CONFIG_IS_ENABLED(DM_MMC)
1178 int mmc_getcd(struct mmc *mmc)
1179 {
1180         int cd;
1181
1182         cd = board_mmc_getcd(mmc);
1183
1184         if (cd < 0) {
1185                 if (mmc->cfg->ops->getcd)
1186                         cd = mmc->cfg->ops->getcd(mmc);
1187                 else
1188                         cd = 1;
1189         }
1190
1191         return cd;
1192 }
1193 #endif
1194
1195 #if !CONFIG_IS_ENABLED(MMC_TINY)
1196 static int sd_switch(struct mmc *mmc, int mode, int group, u8 value, u8 *resp)
1197 {
1198         struct mmc_cmd cmd;
1199         struct mmc_data data;
1200
1201         /* Switch the frequency */
1202         cmd.cmdidx = SD_CMD_SWITCH_FUNC;
1203         cmd.resp_type = MMC_RSP_R1;
1204         cmd.cmdarg = (mode << 31) | 0xffffff;
1205         cmd.cmdarg &= ~(0xf << (group * 4));
1206         cmd.cmdarg |= value << (group * 4);
1207
1208         data.dest = (char *)resp;
1209         data.blocksize = 64;
1210         data.blocks = 1;
1211         data.flags = MMC_DATA_READ;
1212
1213         return mmc_send_cmd(mmc, &cmd, &data);
1214 }
1215
1216 static int sd_get_capabilities(struct mmc *mmc)
1217 {
1218         int err;
1219         struct mmc_cmd cmd;
1220         ALLOC_CACHE_ALIGN_BUFFER(__be32, scr, 2);
1221         ALLOC_CACHE_ALIGN_BUFFER(__be32, switch_status, 16);
1222         struct mmc_data data;
1223         int timeout;
1224 #if CONFIG_IS_ENABLED(MMC_UHS_SUPPORT)
1225         u32 sd3_bus_mode;
1226 #endif
1227
1228         mmc->card_caps = MMC_MODE_1BIT | MMC_CAP(SD_LEGACY);
1229
1230         if (mmc_host_is_spi(mmc))
1231                 return 0;
1232
1233         /* Read the SCR to find out if this card supports higher speeds */
1234         cmd.cmdidx = MMC_CMD_APP_CMD;
1235         cmd.resp_type = MMC_RSP_R1;
1236         cmd.cmdarg = mmc->rca << 16;
1237
1238         err = mmc_send_cmd(mmc, &cmd, NULL);
1239
1240         if (err)
1241                 return err;
1242
1243         cmd.cmdidx = SD_CMD_APP_SEND_SCR;
1244         cmd.resp_type = MMC_RSP_R1;
1245         cmd.cmdarg = 0;
1246
1247         timeout = 3;
1248
1249 retry_scr:
1250         data.dest = (char *)scr;
1251         data.blocksize = 8;
1252         data.blocks = 1;
1253         data.flags = MMC_DATA_READ;
1254
1255         err = mmc_send_cmd(mmc, &cmd, &data);
1256
1257         if (err) {
1258                 if (timeout--)
1259                         goto retry_scr;
1260
1261                 return err;
1262         }
1263
1264         mmc->scr[0] = __be32_to_cpu(scr[0]);
1265         mmc->scr[1] = __be32_to_cpu(scr[1]);
1266
1267         switch ((mmc->scr[0] >> 24) & 0xf) {
1268         case 0:
1269                 mmc->version = SD_VERSION_1_0;
1270                 break;
1271         case 1:
1272                 mmc->version = SD_VERSION_1_10;
1273                 break;
1274         case 2:
1275                 mmc->version = SD_VERSION_2;
1276                 if ((mmc->scr[0] >> 15) & 0x1)
1277                         mmc->version = SD_VERSION_3;
1278                 break;
1279         default:
1280                 mmc->version = SD_VERSION_1_0;
1281                 break;
1282         }
1283
1284         if (mmc->scr[0] & SD_DATA_4BIT)
1285                 mmc->card_caps |= MMC_MODE_4BIT;
1286
1287         /* Version 1.0 doesn't support switching */
1288         if (mmc->version == SD_VERSION_1_0)
1289                 return 0;
1290
1291         timeout = 4;
1292         while (timeout--) {
1293                 err = sd_switch(mmc, SD_SWITCH_CHECK, 0, 1,
1294                                 (u8 *)switch_status);
1295
1296                 if (err)
1297                         return err;
1298
1299                 /* The high-speed function is busy.  Try again */
1300                 if (!(__be32_to_cpu(switch_status[7]) & SD_HIGHSPEED_BUSY))
1301                         break;
1302         }
1303
1304         /* If high-speed isn't supported, we return */
1305         if (__be32_to_cpu(switch_status[3]) & SD_HIGHSPEED_SUPPORTED)
1306                 mmc->card_caps |= MMC_CAP(SD_HS);
1307
1308 #if CONFIG_IS_ENABLED(MMC_UHS_SUPPORT)
1309         /* Version before 3.0 don't support UHS modes */
1310         if (mmc->version < SD_VERSION_3)
1311                 return 0;
1312
1313         sd3_bus_mode = __be32_to_cpu(switch_status[3]) >> 16 & 0x1f;
1314         if (sd3_bus_mode & SD_MODE_UHS_SDR104)
1315                 mmc->card_caps |= MMC_CAP(UHS_SDR104);
1316         if (sd3_bus_mode & SD_MODE_UHS_SDR50)
1317                 mmc->card_caps |= MMC_CAP(UHS_SDR50);
1318         if (sd3_bus_mode & SD_MODE_UHS_SDR25)
1319                 mmc->card_caps |= MMC_CAP(UHS_SDR25);
1320         if (sd3_bus_mode & SD_MODE_UHS_SDR12)
1321                 mmc->card_caps |= MMC_CAP(UHS_SDR12);
1322         if (sd3_bus_mode & SD_MODE_UHS_DDR50)
1323                 mmc->card_caps |= MMC_CAP(UHS_DDR50);
1324 #endif
1325
1326         return 0;
1327 }
1328
1329 static int sd_set_card_speed(struct mmc *mmc, enum bus_mode mode)
1330 {
1331         int err;
1332
1333         ALLOC_CACHE_ALIGN_BUFFER(uint, switch_status, 16);
1334         int speed;
1335
1336         /* SD version 1.00 and 1.01 does not support CMD 6 */
1337         if (mmc->version == SD_VERSION_1_0)
1338                 return 0;
1339
1340         switch (mode) {
1341         case SD_LEGACY:
1342                 speed = UHS_SDR12_BUS_SPEED;
1343                 break;
1344         case SD_HS:
1345                 speed = HIGH_SPEED_BUS_SPEED;
1346                 break;
1347 #if CONFIG_IS_ENABLED(MMC_UHS_SUPPORT)
1348         case UHS_SDR12:
1349                 speed = UHS_SDR12_BUS_SPEED;
1350                 break;
1351         case UHS_SDR25:
1352                 speed = UHS_SDR25_BUS_SPEED;
1353                 break;
1354         case UHS_SDR50:
1355                 speed = UHS_SDR50_BUS_SPEED;
1356                 break;
1357         case UHS_DDR50:
1358                 speed = UHS_DDR50_BUS_SPEED;
1359                 break;
1360         case UHS_SDR104:
1361                 speed = UHS_SDR104_BUS_SPEED;
1362                 break;
1363 #endif
1364         default:
1365                 return -EINVAL;
1366         }
1367
1368         err = sd_switch(mmc, SD_SWITCH_SWITCH, 0, speed, (u8 *)switch_status);
1369         if (err)
1370                 return err;
1371
1372         if (((__be32_to_cpu(switch_status[4]) >> 24) & 0xF) != speed)
1373                 return -ENOTSUPP;
1374
1375         return 0;
1376 }
1377
1378 static int sd_select_bus_width(struct mmc *mmc, int w)
1379 {
1380         int err;
1381         struct mmc_cmd cmd;
1382
1383         if ((w != 4) && (w != 1))
1384                 return -EINVAL;
1385
1386         cmd.cmdidx = MMC_CMD_APP_CMD;
1387         cmd.resp_type = MMC_RSP_R1;
1388         cmd.cmdarg = mmc->rca << 16;
1389
1390         err = mmc_send_cmd(mmc, &cmd, NULL);
1391         if (err)
1392                 return err;
1393
1394         cmd.cmdidx = SD_CMD_APP_SET_BUS_WIDTH;
1395         cmd.resp_type = MMC_RSP_R1;
1396         if (w == 4)
1397                 cmd.cmdarg = 2;
1398         else if (w == 1)
1399                 cmd.cmdarg = 0;
1400         err = mmc_send_cmd(mmc, &cmd, NULL);
1401         if (err)
1402                 return err;
1403
1404         return 0;
1405 }
1406 #endif
1407
1408 #if CONFIG_IS_ENABLED(MMC_WRITE)
1409 static int sd_read_ssr(struct mmc *mmc)
1410 {
1411         static const unsigned int sd_au_size[] = {
1412                 0,              SZ_16K / 512,           SZ_32K / 512,
1413                 SZ_64K / 512,   SZ_128K / 512,          SZ_256K / 512,
1414                 SZ_512K / 512,  SZ_1M / 512,            SZ_2M / 512,
1415                 SZ_4M / 512,    SZ_8M / 512,            (SZ_8M + SZ_4M) / 512,
1416                 SZ_16M / 512,   (SZ_16M + SZ_8M) / 512, SZ_32M / 512,
1417                 SZ_64M / 512,
1418         };
1419         int err, i;
1420         struct mmc_cmd cmd;
1421         ALLOC_CACHE_ALIGN_BUFFER(uint, ssr, 16);
1422         struct mmc_data data;
1423         int timeout = 3;
1424         unsigned int au, eo, et, es;
1425
1426         cmd.cmdidx = MMC_CMD_APP_CMD;
1427         cmd.resp_type = MMC_RSP_R1;
1428         cmd.cmdarg = mmc->rca << 16;
1429
1430         err = mmc_send_cmd(mmc, &cmd, NULL);
1431         if (err)
1432                 return err;
1433
1434         cmd.cmdidx = SD_CMD_APP_SD_STATUS;
1435         cmd.resp_type = MMC_RSP_R1;
1436         cmd.cmdarg = 0;
1437
1438 retry_ssr:
1439         data.dest = (char *)ssr;
1440         data.blocksize = 64;
1441         data.blocks = 1;
1442         data.flags = MMC_DATA_READ;
1443
1444         err = mmc_send_cmd(mmc, &cmd, &data);
1445         if (err) {
1446                 if (timeout--)
1447                         goto retry_ssr;
1448
1449                 return err;
1450         }
1451
1452         for (i = 0; i < 16; i++)
1453                 ssr[i] = be32_to_cpu(ssr[i]);
1454
1455         au = (ssr[2] >> 12) & 0xF;
1456         if ((au <= 9) || (mmc->version == SD_VERSION_3)) {
1457                 mmc->ssr.au = sd_au_size[au];
1458                 es = (ssr[3] >> 24) & 0xFF;
1459                 es |= (ssr[2] & 0xFF) << 8;
1460                 et = (ssr[3] >> 18) & 0x3F;
1461                 if (es && et) {
1462                         eo = (ssr[3] >> 16) & 0x3;
1463                         mmc->ssr.erase_timeout = (et * 1000) / es;
1464                         mmc->ssr.erase_offset = eo * 1000;
1465                 }
1466         } else {
1467                 pr_debug("Invalid Allocation Unit Size.\n");
1468         }
1469
1470         return 0;
1471 }
1472 #endif
1473 /* frequency bases */
1474 /* divided by 10 to be nice to platforms without floating point */
1475 static const int fbase[] = {
1476         10000,
1477         100000,
1478         1000000,
1479         10000000,
1480 };
1481
1482 /* Multiplier values for TRAN_SPEED.  Multiplied by 10 to be nice
1483  * to platforms without floating point.
1484  */
1485 static const u8 multipliers[] = {
1486         0,      /* reserved */
1487         10,
1488         12,
1489         13,
1490         15,
1491         20,
1492         25,
1493         30,
1494         35,
1495         40,
1496         45,
1497         50,
1498         55,
1499         60,
1500         70,
1501         80,
1502 };
1503
1504 static inline int bus_width(uint cap)
1505 {
1506         if (cap == MMC_MODE_8BIT)
1507                 return 8;
1508         if (cap == MMC_MODE_4BIT)
1509                 return 4;
1510         if (cap == MMC_MODE_1BIT)
1511                 return 1;
1512         pr_warn("invalid bus witdh capability 0x%x\n", cap);
1513         return 0;
1514 }
1515
1516 #if !CONFIG_IS_ENABLED(DM_MMC)
1517 #ifdef MMC_SUPPORTS_TUNING
1518 static int mmc_execute_tuning(struct mmc *mmc, uint opcode)
1519 {
1520         return -ENOTSUPP;
1521 }
1522 #endif
1523
1524 static int mmc_set_ios(struct mmc *mmc)
1525 {
1526         int ret = 0;
1527
1528         if (mmc->cfg->ops->set_ios)
1529                 ret = mmc->cfg->ops->set_ios(mmc);
1530
1531         return ret;
1532 }
1533 #endif
1534
1535 int mmc_set_clock(struct mmc *mmc, uint clock, bool disable)
1536 {
1537         if (!disable) {
1538                 if (clock > mmc->cfg->f_max)
1539                         clock = mmc->cfg->f_max;
1540
1541                 if (clock < mmc->cfg->f_min)
1542                         clock = mmc->cfg->f_min;
1543         }
1544
1545         mmc->clock = clock;
1546         mmc->clk_disable = disable;
1547
1548         debug("clock is %s (%dHz)\n", disable ? "disabled" : "enabled", clock);
1549
1550         return mmc_set_ios(mmc);
1551 }
1552
1553 static int mmc_set_bus_width(struct mmc *mmc, uint width)
1554 {
1555         mmc->bus_width = width;
1556
1557         return mmc_set_ios(mmc);
1558 }
1559
1560 #if CONFIG_IS_ENABLED(MMC_VERBOSE) || defined(DEBUG)
1561 /*
1562  * helper function to display the capabilities in a human
1563  * friendly manner. The capabilities include bus width and
1564  * supported modes.
1565  */
1566 void mmc_dump_capabilities(const char *text, uint caps)
1567 {
1568         enum bus_mode mode;
1569
1570         pr_debug("%s: widths [", text);
1571         if (caps & MMC_MODE_8BIT)
1572                 pr_debug("8, ");
1573         if (caps & MMC_MODE_4BIT)
1574                 pr_debug("4, ");
1575         if (caps & MMC_MODE_1BIT)
1576                 pr_debug("1, ");
1577         pr_debug("\b\b] modes [");
1578         for (mode = MMC_LEGACY; mode < MMC_MODES_END; mode++)
1579                 if (MMC_CAP(mode) & caps)
1580                         pr_debug("%s, ", mmc_mode_name(mode));
1581         pr_debug("\b\b]\n");
1582 }
1583 #endif
1584
1585 struct mode_width_tuning {
1586         enum bus_mode mode;
1587         uint widths;
1588 #ifdef MMC_SUPPORTS_TUNING
1589         uint tuning;
1590 #endif
1591 };
1592
1593 #if CONFIG_IS_ENABLED(MMC_IO_VOLTAGE)
1594 int mmc_voltage_to_mv(enum mmc_voltage voltage)
1595 {
1596         switch (voltage) {
1597         case MMC_SIGNAL_VOLTAGE_000: return 0;
1598         case MMC_SIGNAL_VOLTAGE_330: return 3300;
1599         case MMC_SIGNAL_VOLTAGE_180: return 1800;
1600         case MMC_SIGNAL_VOLTAGE_120: return 1200;
1601         }
1602         return -EINVAL;
1603 }
1604
1605 static int mmc_set_signal_voltage(struct mmc *mmc, uint signal_voltage)
1606 {
1607         int err;
1608
1609         if (mmc->signal_voltage == signal_voltage)
1610                 return 0;
1611
1612         mmc->signal_voltage = signal_voltage;
1613         err = mmc_set_ios(mmc);
1614         if (err)
1615                 pr_debug("unable to set voltage (err %d)\n", err);
1616
1617         return err;
1618 }
1619 #else
1620 static inline int mmc_set_signal_voltage(struct mmc *mmc, uint signal_voltage)
1621 {
1622         return 0;
1623 }
1624 #endif
1625
1626 #if !CONFIG_IS_ENABLED(MMC_TINY)
1627 static const struct mode_width_tuning sd_modes_by_pref[] = {
1628 #if CONFIG_IS_ENABLED(MMC_UHS_SUPPORT)
1629 #ifdef MMC_SUPPORTS_TUNING
1630         {
1631                 .mode = UHS_SDR104,
1632                 .widths = MMC_MODE_4BIT | MMC_MODE_1BIT,
1633                 .tuning = MMC_CMD_SEND_TUNING_BLOCK
1634         },
1635 #endif
1636         {
1637                 .mode = UHS_SDR50,
1638                 .widths = MMC_MODE_4BIT | MMC_MODE_1BIT,
1639         },
1640         {
1641                 .mode = UHS_DDR50,
1642                 .widths = MMC_MODE_4BIT | MMC_MODE_1BIT,
1643         },
1644         {
1645                 .mode = UHS_SDR25,
1646                 .widths = MMC_MODE_4BIT | MMC_MODE_1BIT,
1647         },
1648 #endif
1649         {
1650                 .mode = SD_HS,
1651                 .widths = MMC_MODE_4BIT | MMC_MODE_1BIT,
1652         },
1653 #if CONFIG_IS_ENABLED(MMC_UHS_SUPPORT)
1654         {
1655                 .mode = UHS_SDR12,
1656                 .widths = MMC_MODE_4BIT | MMC_MODE_1BIT,
1657         },
1658 #endif
1659         {
1660                 .mode = SD_LEGACY,
1661                 .widths = MMC_MODE_4BIT | MMC_MODE_1BIT,
1662         }
1663 };
1664
1665 #define for_each_sd_mode_by_pref(caps, mwt) \
1666         for (mwt = sd_modes_by_pref;\
1667              mwt < sd_modes_by_pref + ARRAY_SIZE(sd_modes_by_pref);\
1668              mwt++) \
1669                 if (caps & MMC_CAP(mwt->mode))
1670
1671 static int sd_select_mode_and_width(struct mmc *mmc, uint card_caps)
1672 {
1673         int err;
1674         uint widths[] = {MMC_MODE_4BIT, MMC_MODE_1BIT};
1675         const struct mode_width_tuning *mwt;
1676 #if CONFIG_IS_ENABLED(MMC_UHS_SUPPORT)
1677         bool uhs_en = (mmc->ocr & OCR_S18R) ? true : false;
1678 #else
1679         bool uhs_en = false;
1680 #endif
1681         uint caps;
1682
1683 #ifdef DEBUG
1684         mmc_dump_capabilities("sd card", card_caps);
1685         mmc_dump_capabilities("host", mmc->host_caps);
1686 #endif
1687
1688         /* Restrict card's capabilities by what the host can do */
1689         caps = card_caps & mmc->host_caps;
1690
1691         if (!uhs_en)
1692                 caps &= ~UHS_CAPS;
1693
1694         for_each_sd_mode_by_pref(caps, mwt) {
1695                 uint *w;
1696
1697                 for (w = widths; w < widths + ARRAY_SIZE(widths); w++) {
1698                         if (*w & caps & mwt->widths) {
1699                                 pr_debug("trying mode %s width %d (at %d MHz)\n",
1700                                          mmc_mode_name(mwt->mode),
1701                                          bus_width(*w),
1702                                          mmc_mode2freq(mmc, mwt->mode) / 1000000);
1703
1704                                 /* configure the bus width (card + host) */
1705                                 err = sd_select_bus_width(mmc, bus_width(*w));
1706                                 if (err)
1707                                         goto error;
1708                                 mmc_set_bus_width(mmc, bus_width(*w));
1709
1710                                 /* configure the bus mode (card) */
1711                                 err = sd_set_card_speed(mmc, mwt->mode);
1712                                 if (err)
1713                                         goto error;
1714
1715                                 /* configure the bus mode (host) */
1716                                 mmc_select_mode(mmc, mwt->mode);
1717                                 mmc_set_clock(mmc, mmc->tran_speed,
1718                                                 MMC_CLK_ENABLE);
1719
1720 #ifdef MMC_SUPPORTS_TUNING
1721                                 /* execute tuning if needed */
1722                                 if (mwt->tuning && !mmc_host_is_spi(mmc)) {
1723                                         err = mmc_execute_tuning(mmc,
1724                                                                  mwt->tuning);
1725                                         if (err) {
1726                                                 pr_debug("tuning failed\n");
1727                                                 goto error;
1728                                         }
1729                                 }
1730 #endif
1731
1732 #if CONFIG_IS_ENABLED(MMC_WRITE)
1733                                 err = sd_read_ssr(mmc);
1734                                 if (err)
1735                                         pr_warn("unable to read ssr\n");
1736 #endif
1737                                 if (!err)
1738                                         return 0;
1739
1740 error:
1741                                 /* revert to a safer bus speed */
1742                                 mmc_select_mode(mmc, SD_LEGACY);
1743                                 mmc_set_clock(mmc, mmc->tran_speed,
1744                                                 MMC_CLK_ENABLE);
1745                         }
1746                 }
1747         }
1748
1749         pr_err("unable to select a mode\n");
1750         return -ENOTSUPP;
1751 }
1752
1753 /*
1754  * read the compare the part of ext csd that is constant.
1755  * This can be used to check that the transfer is working
1756  * as expected.
1757  */
1758 static int mmc_read_and_compare_ext_csd(struct mmc *mmc)
1759 {
1760         int err;
1761         const u8 *ext_csd = mmc->ext_csd;
1762         ALLOC_CACHE_ALIGN_BUFFER(u8, test_csd, MMC_MAX_BLOCK_LEN);
1763
1764         if (mmc->version < MMC_VERSION_4)
1765                 return 0;
1766
1767         err = mmc_send_ext_csd(mmc, test_csd);
1768         if (err)
1769                 return err;
1770
1771         /* Only compare read only fields */
1772         if (ext_csd[EXT_CSD_PARTITIONING_SUPPORT]
1773                 == test_csd[EXT_CSD_PARTITIONING_SUPPORT] &&
1774             ext_csd[EXT_CSD_HC_WP_GRP_SIZE]
1775                 == test_csd[EXT_CSD_HC_WP_GRP_SIZE] &&
1776             ext_csd[EXT_CSD_REV]
1777                 == test_csd[EXT_CSD_REV] &&
1778             ext_csd[EXT_CSD_HC_ERASE_GRP_SIZE]
1779                 == test_csd[EXT_CSD_HC_ERASE_GRP_SIZE] &&
1780             memcmp(&ext_csd[EXT_CSD_SEC_CNT],
1781                    &test_csd[EXT_CSD_SEC_CNT], 4) == 0)
1782                 return 0;
1783
1784         return -EBADMSG;
1785 }
1786
1787 #if CONFIG_IS_ENABLED(MMC_IO_VOLTAGE)
1788 static int mmc_set_lowest_voltage(struct mmc *mmc, enum bus_mode mode,
1789                                   uint32_t allowed_mask)
1790 {
1791         u32 card_mask = 0;
1792
1793         switch (mode) {
1794         case MMC_HS_400:
1795         case MMC_HS_200:
1796                 if (mmc->cardtype & (EXT_CSD_CARD_TYPE_HS200_1_8V |
1797                     EXT_CSD_CARD_TYPE_HS400_1_8V))
1798                         card_mask |= MMC_SIGNAL_VOLTAGE_180;
1799                 if (mmc->cardtype & (EXT_CSD_CARD_TYPE_HS200_1_2V |
1800                     EXT_CSD_CARD_TYPE_HS400_1_2V))
1801                         card_mask |= MMC_SIGNAL_VOLTAGE_120;
1802                 break;
1803         case MMC_DDR_52:
1804                 if (mmc->cardtype & EXT_CSD_CARD_TYPE_DDR_1_8V)
1805                         card_mask |= MMC_SIGNAL_VOLTAGE_330 |
1806                                      MMC_SIGNAL_VOLTAGE_180;
1807                 if (mmc->cardtype & EXT_CSD_CARD_TYPE_DDR_1_2V)
1808                         card_mask |= MMC_SIGNAL_VOLTAGE_120;
1809                 break;
1810         default:
1811                 card_mask |= MMC_SIGNAL_VOLTAGE_330;
1812                 break;
1813         }
1814
1815         while (card_mask & allowed_mask) {
1816                 enum mmc_voltage best_match;
1817
1818                 best_match = 1 << (ffs(card_mask & allowed_mask) - 1);
1819                 if (!mmc_set_signal_voltage(mmc,  best_match))
1820                         return 0;
1821
1822                 allowed_mask &= ~best_match;
1823         }
1824
1825         return -ENOTSUPP;
1826 }
1827 #else
1828 static inline int mmc_set_lowest_voltage(struct mmc *mmc, enum bus_mode mode,
1829                                          uint32_t allowed_mask)
1830 {
1831         return 0;
1832 }
1833 #endif
1834
1835 static const struct mode_width_tuning mmc_modes_by_pref[] = {
1836 #if CONFIG_IS_ENABLED(MMC_HS400_SUPPORT)
1837         {
1838                 .mode = MMC_HS_400,
1839                 .widths = MMC_MODE_8BIT,
1840                 .tuning = MMC_CMD_SEND_TUNING_BLOCK_HS200
1841         },
1842 #endif
1843 #if CONFIG_IS_ENABLED(MMC_HS200_SUPPORT)
1844         {
1845                 .mode = MMC_HS_200,
1846                 .widths = MMC_MODE_8BIT | MMC_MODE_4BIT,
1847                 .tuning = MMC_CMD_SEND_TUNING_BLOCK_HS200
1848         },
1849 #endif
1850         {
1851                 .mode = MMC_DDR_52,
1852                 .widths = MMC_MODE_8BIT | MMC_MODE_4BIT,
1853         },
1854         {
1855                 .mode = MMC_HS_52,
1856                 .widths = MMC_MODE_8BIT | MMC_MODE_4BIT | MMC_MODE_1BIT,
1857         },
1858         {
1859                 .mode = MMC_HS,
1860                 .widths = MMC_MODE_8BIT | MMC_MODE_4BIT | MMC_MODE_1BIT,
1861         },
1862         {
1863                 .mode = MMC_LEGACY,
1864                 .widths = MMC_MODE_8BIT | MMC_MODE_4BIT | MMC_MODE_1BIT,
1865         }
1866 };
1867
1868 #define for_each_mmc_mode_by_pref(caps, mwt) \
1869         for (mwt = mmc_modes_by_pref;\
1870             mwt < mmc_modes_by_pref + ARRAY_SIZE(mmc_modes_by_pref);\
1871             mwt++) \
1872                 if (caps & MMC_CAP(mwt->mode))
1873
1874 static const struct ext_csd_bus_width {
1875         uint cap;
1876         bool is_ddr;
1877         uint ext_csd_bits;
1878 } ext_csd_bus_width[] = {
1879         {MMC_MODE_8BIT, true, EXT_CSD_DDR_BUS_WIDTH_8},
1880         {MMC_MODE_4BIT, true, EXT_CSD_DDR_BUS_WIDTH_4},
1881         {MMC_MODE_8BIT, false, EXT_CSD_BUS_WIDTH_8},
1882         {MMC_MODE_4BIT, false, EXT_CSD_BUS_WIDTH_4},
1883         {MMC_MODE_1BIT, false, EXT_CSD_BUS_WIDTH_1},
1884 };
1885
1886 #if CONFIG_IS_ENABLED(MMC_HS400_SUPPORT)
1887 static int mmc_select_hs400(struct mmc *mmc)
1888 {
1889         int err;
1890
1891         /* Set timing to HS200 for tuning */
1892         err = mmc_set_card_speed(mmc, MMC_HS_200, false);
1893         if (err)
1894                 return err;
1895
1896         /* configure the bus mode (host) */
1897         mmc_select_mode(mmc, MMC_HS_200);
1898         mmc_set_clock(mmc, mmc->tran_speed, false);
1899
1900         /* execute tuning if needed */
1901         err = mmc_execute_tuning(mmc, MMC_CMD_SEND_TUNING_BLOCK_HS200);
1902         if (err) {
1903                 debug("tuning failed\n");
1904                 return err;
1905         }
1906
1907         /* Set back to HS */
1908         mmc_set_card_speed(mmc, MMC_HS, true);
1909
1910         err = mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_BUS_WIDTH,
1911                          EXT_CSD_BUS_WIDTH_8 | EXT_CSD_DDR_FLAG);
1912         if (err)
1913                 return err;
1914
1915         err = mmc_set_card_speed(mmc, MMC_HS_400, false);
1916         if (err)
1917                 return err;
1918
1919         mmc_select_mode(mmc, MMC_HS_400);
1920         err = mmc_set_clock(mmc, mmc->tran_speed, false);
1921         if (err)
1922                 return err;
1923
1924         return 0;
1925 }
1926 #else
1927 static int mmc_select_hs400(struct mmc *mmc)
1928 {
1929         return -ENOTSUPP;
1930 }
1931 #endif
1932
1933 #define for_each_supported_width(caps, ddr, ecbv) \
1934         for (ecbv = ext_csd_bus_width;\
1935             ecbv < ext_csd_bus_width + ARRAY_SIZE(ext_csd_bus_width);\
1936             ecbv++) \
1937                 if ((ddr == ecbv->is_ddr) && (caps & ecbv->cap))
1938
1939 static int mmc_select_mode_and_width(struct mmc *mmc, uint card_caps)
1940 {
1941         int err;
1942         const struct mode_width_tuning *mwt;
1943         const struct ext_csd_bus_width *ecbw;
1944
1945 #ifdef DEBUG
1946         mmc_dump_capabilities("mmc", card_caps);
1947         mmc_dump_capabilities("host", mmc->host_caps);
1948 #endif
1949
1950         /* Restrict card's capabilities by what the host can do */
1951         card_caps &= mmc->host_caps;
1952
1953         /* Only version 4 of MMC supports wider bus widths */
1954         if (mmc->version < MMC_VERSION_4)
1955                 return 0;
1956
1957         if (!mmc->ext_csd) {
1958                 pr_debug("No ext_csd found!\n"); /* this should enver happen */
1959                 return -ENOTSUPP;
1960         }
1961
1962 #if CONFIG_IS_ENABLED(MMC_HS200_SUPPORT) || \
1963     CONFIG_IS_ENABLED(MMC_HS400_SUPPORT)
1964         /*
1965          * In case the eMMC is in HS200/HS400 mode, downgrade to HS mode
1966          * before doing anything else, since a transition from either of
1967          * the HS200/HS400 mode directly to legacy mode is not supported.
1968          */
1969         if (mmc->selected_mode == MMC_HS_200 ||
1970             mmc->selected_mode == MMC_HS_400)
1971                 mmc_set_card_speed(mmc, MMC_HS, true);
1972         else
1973 #endif
1974                 mmc_set_clock(mmc, mmc->legacy_speed, MMC_CLK_ENABLE);
1975
1976         for_each_mmc_mode_by_pref(card_caps, mwt) {
1977                 for_each_supported_width(card_caps & mwt->widths,
1978                                          mmc_is_mode_ddr(mwt->mode), ecbw) {
1979                         enum mmc_voltage old_voltage;
1980                         pr_debug("trying mode %s width %d (at %d MHz)\n",
1981                                  mmc_mode_name(mwt->mode),
1982                                  bus_width(ecbw->cap),
1983                                  mmc_mode2freq(mmc, mwt->mode) / 1000000);
1984                         old_voltage = mmc->signal_voltage;
1985                         err = mmc_set_lowest_voltage(mmc, mwt->mode,
1986                                                      MMC_ALL_SIGNAL_VOLTAGE);
1987                         if (err)
1988                                 continue;
1989
1990                         /* configure the bus width (card + host) */
1991                         err = mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL,
1992                                     EXT_CSD_BUS_WIDTH,
1993                                     ecbw->ext_csd_bits & ~EXT_CSD_DDR_FLAG);
1994                         if (err)
1995                                 goto error;
1996                         mmc_set_bus_width(mmc, bus_width(ecbw->cap));
1997
1998                         if (mwt->mode == MMC_HS_400) {
1999                                 err = mmc_select_hs400(mmc);
2000                                 if (err) {
2001                                         printf("Select HS400 failed %d\n", err);
2002                                         goto error;
2003                                 }
2004                         } else {
2005                                 /* configure the bus speed (card) */
2006                                 err = mmc_set_card_speed(mmc, mwt->mode, false);
2007                                 if (err)
2008                                         goto error;
2009
2010                                 /*
2011                                  * configure the bus width AND the ddr mode
2012                                  * (card). The host side will be taken care
2013                                  * of in the next step
2014                                  */
2015                                 if (ecbw->ext_csd_bits & EXT_CSD_DDR_FLAG) {
2016                                         err = mmc_switch(mmc,
2017                                                          EXT_CSD_CMD_SET_NORMAL,
2018                                                          EXT_CSD_BUS_WIDTH,
2019                                                          ecbw->ext_csd_bits);
2020                                         if (err)
2021                                                 goto error;
2022                                 }
2023
2024                                 /* configure the bus mode (host) */
2025                                 mmc_select_mode(mmc, mwt->mode);
2026                                 mmc_set_clock(mmc, mmc->tran_speed,
2027                                               MMC_CLK_ENABLE);
2028 #ifdef MMC_SUPPORTS_TUNING
2029
2030                                 /* execute tuning if needed */
2031                                 if (mwt->tuning) {
2032                                         err = mmc_execute_tuning(mmc,
2033                                                                  mwt->tuning);
2034                                         if (err) {
2035                                                 pr_debug("tuning failed\n");
2036                                                 goto error;
2037                                         }
2038                                 }
2039 #endif
2040                         }
2041
2042                         /* do a transfer to check the configuration */
2043                         err = mmc_read_and_compare_ext_csd(mmc);
2044                         if (!err)
2045                                 return 0;
2046 error:
2047                         mmc_set_signal_voltage(mmc, old_voltage);
2048                         /* if an error occured, revert to a safer bus mode */
2049                         mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL,
2050                                    EXT_CSD_BUS_WIDTH, EXT_CSD_BUS_WIDTH_1);
2051                         mmc_select_mode(mmc, MMC_LEGACY);
2052                         mmc_set_bus_width(mmc, 1);
2053                 }
2054         }
2055
2056         pr_err("unable to select a mode\n");
2057
2058         return -ENOTSUPP;
2059 }
2060 #endif
2061
2062 #if CONFIG_IS_ENABLED(MMC_TINY)
2063 DEFINE_CACHE_ALIGN_BUFFER(u8, ext_csd_bkup, MMC_MAX_BLOCK_LEN);
2064 #endif
2065
2066 static int mmc_startup_v4(struct mmc *mmc)
2067 {
2068         int err, i;
2069         u64 capacity;
2070         bool has_parts = false;
2071         bool part_completed;
2072         static const u32 mmc_versions[] = {
2073                 MMC_VERSION_4,
2074                 MMC_VERSION_4_1,
2075                 MMC_VERSION_4_2,
2076                 MMC_VERSION_4_3,
2077                 MMC_VERSION_4_4,
2078                 MMC_VERSION_4_41,
2079                 MMC_VERSION_4_5,
2080                 MMC_VERSION_5_0,
2081                 MMC_VERSION_5_1
2082         };
2083
2084 #if CONFIG_IS_ENABLED(MMC_TINY)
2085         u8 *ext_csd = ext_csd_bkup;
2086
2087         if (IS_SD(mmc) || mmc->version < MMC_VERSION_4)
2088                 return 0;
2089
2090         if (!mmc->ext_csd)
2091                 memset(ext_csd_bkup, 0, sizeof(ext_csd_bkup));
2092
2093         err = mmc_send_ext_csd(mmc, ext_csd);
2094         if (err)
2095                 goto error;
2096
2097         /* store the ext csd for future reference */
2098         if (!mmc->ext_csd)
2099                 mmc->ext_csd = ext_csd;
2100 #else
2101         ALLOC_CACHE_ALIGN_BUFFER(u8, ext_csd, MMC_MAX_BLOCK_LEN);
2102
2103         if (IS_SD(mmc) || (mmc->version < MMC_VERSION_4))
2104                 return 0;
2105
2106         /* check  ext_csd version and capacity */
2107         err = mmc_send_ext_csd(mmc, ext_csd);
2108         if (err)
2109                 goto error;
2110
2111         /* store the ext csd for future reference */
2112         if (!mmc->ext_csd)
2113                 mmc->ext_csd = malloc(MMC_MAX_BLOCK_LEN);
2114         if (!mmc->ext_csd)
2115                 return -ENOMEM;
2116         memcpy(mmc->ext_csd, ext_csd, MMC_MAX_BLOCK_LEN);
2117 #endif
2118         if (ext_csd[EXT_CSD_REV] >= ARRAY_SIZE(mmc_versions))
2119                 return -EINVAL;
2120
2121         mmc->version = mmc_versions[ext_csd[EXT_CSD_REV]];
2122
2123         if (mmc->version >= MMC_VERSION_4_2) {
2124                 /*
2125                  * According to the JEDEC Standard, the value of
2126                  * ext_csd's capacity is valid if the value is more
2127                  * than 2GB
2128                  */
2129                 capacity = ext_csd[EXT_CSD_SEC_CNT] << 0
2130                                 | ext_csd[EXT_CSD_SEC_CNT + 1] << 8
2131                                 | ext_csd[EXT_CSD_SEC_CNT + 2] << 16
2132                                 | ext_csd[EXT_CSD_SEC_CNT + 3] << 24;
2133                 capacity *= MMC_MAX_BLOCK_LEN;
2134                 if ((capacity >> 20) > 2 * 1024)
2135                         mmc->capacity_user = capacity;
2136         }
2137
2138         /* The partition data may be non-zero but it is only
2139          * effective if PARTITION_SETTING_COMPLETED is set in
2140          * EXT_CSD, so ignore any data if this bit is not set,
2141          * except for enabling the high-capacity group size
2142          * definition (see below).
2143          */
2144         part_completed = !!(ext_csd[EXT_CSD_PARTITION_SETTING] &
2145                             EXT_CSD_PARTITION_SETTING_COMPLETED);
2146
2147         /* store the partition info of emmc */
2148         mmc->part_support = ext_csd[EXT_CSD_PARTITIONING_SUPPORT];
2149         if ((ext_csd[EXT_CSD_PARTITIONING_SUPPORT] & PART_SUPPORT) ||
2150             ext_csd[EXT_CSD_BOOT_MULT])
2151                 mmc->part_config = ext_csd[EXT_CSD_PART_CONF];
2152         if (part_completed &&
2153             (ext_csd[EXT_CSD_PARTITIONING_SUPPORT] & ENHNCD_SUPPORT))
2154                 mmc->part_attr = ext_csd[EXT_CSD_PARTITIONS_ATTRIBUTE];
2155
2156         mmc->capacity_boot = ext_csd[EXT_CSD_BOOT_MULT] << 17;
2157
2158         mmc->capacity_rpmb = ext_csd[EXT_CSD_RPMB_MULT] << 17;
2159
2160         for (i = 0; i < 4; i++) {
2161                 int idx = EXT_CSD_GP_SIZE_MULT + i * 3;
2162                 uint mult = (ext_csd[idx + 2] << 16) +
2163                         (ext_csd[idx + 1] << 8) + ext_csd[idx];
2164                 if (mult)
2165                         has_parts = true;
2166                 if (!part_completed)
2167                         continue;
2168                 mmc->capacity_gp[i] = mult;
2169                 mmc->capacity_gp[i] *=
2170                         ext_csd[EXT_CSD_HC_ERASE_GRP_SIZE];
2171                 mmc->capacity_gp[i] *= ext_csd[EXT_CSD_HC_WP_GRP_SIZE];
2172                 mmc->capacity_gp[i] <<= 19;
2173         }
2174
2175 #ifndef CONFIG_SPL_BUILD
2176         if (part_completed) {
2177                 mmc->enh_user_size =
2178                         (ext_csd[EXT_CSD_ENH_SIZE_MULT + 2] << 16) +
2179                         (ext_csd[EXT_CSD_ENH_SIZE_MULT + 1] << 8) +
2180                         ext_csd[EXT_CSD_ENH_SIZE_MULT];
2181                 mmc->enh_user_size *= ext_csd[EXT_CSD_HC_ERASE_GRP_SIZE];
2182                 mmc->enh_user_size *= ext_csd[EXT_CSD_HC_WP_GRP_SIZE];
2183                 mmc->enh_user_size <<= 19;
2184                 mmc->enh_user_start =
2185                         (ext_csd[EXT_CSD_ENH_START_ADDR + 3] << 24) +
2186                         (ext_csd[EXT_CSD_ENH_START_ADDR + 2] << 16) +
2187                         (ext_csd[EXT_CSD_ENH_START_ADDR + 1] << 8) +
2188                         ext_csd[EXT_CSD_ENH_START_ADDR];
2189                 if (mmc->high_capacity)
2190                         mmc->enh_user_start <<= 9;
2191         }
2192 #endif
2193
2194         /*
2195          * Host needs to enable ERASE_GRP_DEF bit if device is
2196          * partitioned. This bit will be lost every time after a reset
2197          * or power off. This will affect erase size.
2198          */
2199         if (part_completed)
2200                 has_parts = true;
2201         if ((ext_csd[EXT_CSD_PARTITIONING_SUPPORT] & PART_SUPPORT) &&
2202             (ext_csd[EXT_CSD_PARTITIONS_ATTRIBUTE] & PART_ENH_ATTRIB))
2203                 has_parts = true;
2204         if (has_parts) {
2205                 err = mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL,
2206                                  EXT_CSD_ERASE_GROUP_DEF, 1);
2207
2208                 if (err)
2209                         goto error;
2210
2211                 ext_csd[EXT_CSD_ERASE_GROUP_DEF] = 1;
2212         }
2213
2214         if (ext_csd[EXT_CSD_ERASE_GROUP_DEF] & 0x01) {
2215 #if CONFIG_IS_ENABLED(MMC_WRITE)
2216                 /* Read out group size from ext_csd */
2217                 mmc->erase_grp_size =
2218                         ext_csd[EXT_CSD_HC_ERASE_GRP_SIZE] * 1024;
2219 #endif
2220                 /*
2221                  * if high capacity and partition setting completed
2222                  * SEC_COUNT is valid even if it is smaller than 2 GiB
2223                  * JEDEC Standard JESD84-B45, 6.2.4
2224                  */
2225                 if (mmc->high_capacity && part_completed) {
2226                         capacity = (ext_csd[EXT_CSD_SEC_CNT]) |
2227                                 (ext_csd[EXT_CSD_SEC_CNT + 1] << 8) |
2228                                 (ext_csd[EXT_CSD_SEC_CNT + 2] << 16) |
2229                                 (ext_csd[EXT_CSD_SEC_CNT + 3] << 24);
2230                         capacity *= MMC_MAX_BLOCK_LEN;
2231                         mmc->capacity_user = capacity;
2232                 }
2233         }
2234 #if CONFIG_IS_ENABLED(MMC_WRITE)
2235         else {
2236                 /* Calculate the group size from the csd value. */
2237                 int erase_gsz, erase_gmul;
2238
2239                 erase_gsz = (mmc->csd[2] & 0x00007c00) >> 10;
2240                 erase_gmul = (mmc->csd[2] & 0x000003e0) >> 5;
2241                 mmc->erase_grp_size = (erase_gsz + 1)
2242                         * (erase_gmul + 1);
2243         }
2244 #endif
2245 #if CONFIG_IS_ENABLED(MMC_HW_PARTITIONING)
2246         mmc->hc_wp_grp_size = 1024
2247                 * ext_csd[EXT_CSD_HC_ERASE_GRP_SIZE]
2248                 * ext_csd[EXT_CSD_HC_WP_GRP_SIZE];
2249 #endif
2250
2251         mmc->wr_rel_set = ext_csd[EXT_CSD_WR_REL_SET];
2252
2253         return 0;
2254 error:
2255         if (mmc->ext_csd) {
2256 #if !CONFIG_IS_ENABLED(MMC_TINY)
2257                 free(mmc->ext_csd);
2258 #endif
2259                 mmc->ext_csd = NULL;
2260         }
2261         return err;
2262 }
2263
2264 static int mmc_startup(struct mmc *mmc)
2265 {
2266         int err, i;
2267         uint mult, freq;
2268         u64 cmult, csize;
2269         struct mmc_cmd cmd;
2270         struct blk_desc *bdesc;
2271
2272 #ifdef CONFIG_MMC_SPI_CRC_ON
2273         if (mmc_host_is_spi(mmc)) { /* enable CRC check for spi */
2274                 cmd.cmdidx = MMC_CMD_SPI_CRC_ON_OFF;
2275                 cmd.resp_type = MMC_RSP_R1;
2276                 cmd.cmdarg = 1;
2277                 err = mmc_send_cmd(mmc, &cmd, NULL);
2278                 if (err)
2279                         return err;
2280         }
2281 #endif
2282
2283         /* Put the Card in Identify Mode */
2284         cmd.cmdidx = mmc_host_is_spi(mmc) ? MMC_CMD_SEND_CID :
2285                 MMC_CMD_ALL_SEND_CID; /* cmd not supported in spi */
2286         cmd.resp_type = MMC_RSP_R2;
2287         cmd.cmdarg = 0;
2288
2289         err = mmc_send_cmd(mmc, &cmd, NULL);
2290
2291 #ifdef CONFIG_MMC_QUIRKS
2292         if (err && (mmc->quirks & MMC_QUIRK_RETRY_SEND_CID)) {
2293                 int retries = 4;
2294                 /*
2295                  * It has been seen that SEND_CID may fail on the first
2296                  * attempt, let's try a few more time
2297                  */
2298                 do {
2299                         err = mmc_send_cmd(mmc, &cmd, NULL);
2300                         if (!err)
2301                                 break;
2302                 } while (retries--);
2303         }
2304 #endif
2305
2306         if (err)
2307                 return err;
2308
2309         memcpy(mmc->cid, cmd.response, 16);
2310
2311         /*
2312          * For MMC cards, set the Relative Address.
2313          * For SD cards, get the Relatvie Address.
2314          * This also puts the cards into Standby State
2315          */
2316         if (!mmc_host_is_spi(mmc)) { /* cmd not supported in spi */
2317                 cmd.cmdidx = SD_CMD_SEND_RELATIVE_ADDR;
2318                 cmd.cmdarg = mmc->rca << 16;
2319                 cmd.resp_type = MMC_RSP_R6;
2320
2321                 err = mmc_send_cmd(mmc, &cmd, NULL);
2322
2323                 if (err)
2324                         return err;
2325
2326                 if (IS_SD(mmc))
2327                         mmc->rca = (cmd.response[0] >> 16) & 0xffff;
2328         }
2329
2330         /* Get the Card-Specific Data */
2331         cmd.cmdidx = MMC_CMD_SEND_CSD;
2332         cmd.resp_type = MMC_RSP_R2;
2333         cmd.cmdarg = mmc->rca << 16;
2334
2335         err = mmc_send_cmd(mmc, &cmd, NULL);
2336
2337         if (err)
2338                 return err;
2339
2340         mmc->csd[0] = cmd.response[0];
2341         mmc->csd[1] = cmd.response[1];
2342         mmc->csd[2] = cmd.response[2];
2343         mmc->csd[3] = cmd.response[3];
2344
2345         if (mmc->version == MMC_VERSION_UNKNOWN) {
2346                 int version = (cmd.response[0] >> 26) & 0xf;
2347
2348                 switch (version) {
2349                 case 0:
2350                         mmc->version = MMC_VERSION_1_2;
2351                         break;
2352                 case 1:
2353                         mmc->version = MMC_VERSION_1_4;
2354                         break;
2355                 case 2:
2356                         mmc->version = MMC_VERSION_2_2;
2357                         break;
2358                 case 3:
2359                         mmc->version = MMC_VERSION_3;
2360                         break;
2361                 case 4:
2362                         mmc->version = MMC_VERSION_4;
2363                         break;
2364                 default:
2365                         mmc->version = MMC_VERSION_1_2;
2366                         break;
2367                 }
2368         }
2369
2370         /* divide frequency by 10, since the mults are 10x bigger */
2371         freq = fbase[(cmd.response[0] & 0x7)];
2372         mult = multipliers[((cmd.response[0] >> 3) & 0xf)];
2373
2374         mmc->legacy_speed = freq * mult;
2375         mmc_select_mode(mmc, MMC_LEGACY);
2376
2377         mmc->dsr_imp = ((cmd.response[1] >> 12) & 0x1);
2378         mmc->read_bl_len = 1 << ((cmd.response[1] >> 16) & 0xf);
2379 #if CONFIG_IS_ENABLED(MMC_WRITE)
2380
2381         if (IS_SD(mmc))
2382                 mmc->write_bl_len = mmc->read_bl_len;
2383         else
2384                 mmc->write_bl_len = 1 << ((cmd.response[3] >> 22) & 0xf);
2385 #endif
2386
2387         if (mmc->high_capacity) {
2388                 csize = (mmc->csd[1] & 0x3f) << 16
2389                         | (mmc->csd[2] & 0xffff0000) >> 16;
2390                 cmult = 8;
2391         } else {
2392                 csize = (mmc->csd[1] & 0x3ff) << 2
2393                         | (mmc->csd[2] & 0xc0000000) >> 30;
2394                 cmult = (mmc->csd[2] & 0x00038000) >> 15;
2395         }
2396
2397         mmc->capacity_user = (csize + 1) << (cmult + 2);
2398         mmc->capacity_user *= mmc->read_bl_len;
2399         mmc->capacity_boot = 0;
2400         mmc->capacity_rpmb = 0;
2401         for (i = 0; i < 4; i++)
2402                 mmc->capacity_gp[i] = 0;
2403
2404         if (mmc->read_bl_len > MMC_MAX_BLOCK_LEN)
2405                 mmc->read_bl_len = MMC_MAX_BLOCK_LEN;
2406
2407 #if CONFIG_IS_ENABLED(MMC_WRITE)
2408         if (mmc->write_bl_len > MMC_MAX_BLOCK_LEN)
2409                 mmc->write_bl_len = MMC_MAX_BLOCK_LEN;
2410 #endif
2411
2412         if ((mmc->dsr_imp) && (0xffffffff != mmc->dsr)) {
2413                 cmd.cmdidx = MMC_CMD_SET_DSR;
2414                 cmd.cmdarg = (mmc->dsr & 0xffff) << 16;
2415                 cmd.resp_type = MMC_RSP_NONE;
2416                 if (mmc_send_cmd(mmc, &cmd, NULL))
2417                         pr_warn("MMC: SET_DSR failed\n");
2418         }
2419
2420         /* Select the card, and put it into Transfer Mode */
2421         if (!mmc_host_is_spi(mmc)) { /* cmd not supported in spi */
2422                 cmd.cmdidx = MMC_CMD_SELECT_CARD;
2423                 cmd.resp_type = MMC_RSP_R1;
2424                 cmd.cmdarg = mmc->rca << 16;
2425                 err = mmc_send_cmd(mmc, &cmd, NULL);
2426
2427                 if (err)
2428                         return err;
2429         }
2430
2431         /*
2432          * For SD, its erase group is always one sector
2433          */
2434 #if CONFIG_IS_ENABLED(MMC_WRITE)
2435         mmc->erase_grp_size = 1;
2436 #endif
2437         mmc->part_config = MMCPART_NOAVAILABLE;
2438
2439         err = mmc_startup_v4(mmc);
2440         if (err)
2441                 return err;
2442
2443         err = mmc_set_capacity(mmc, mmc_get_blk_desc(mmc)->hwpart);
2444         if (err)
2445                 return err;
2446
2447 #if CONFIG_IS_ENABLED(MMC_TINY)
2448         mmc_set_clock(mmc, mmc->legacy_speed, false);
2449         mmc_select_mode(mmc, IS_SD(mmc) ? SD_LEGACY : MMC_LEGACY);
2450         mmc_set_bus_width(mmc, 1);
2451 #else
2452         if (IS_SD(mmc)) {
2453                 err = sd_get_capabilities(mmc);
2454                 if (err)
2455                         return err;
2456                 err = sd_select_mode_and_width(mmc, mmc->card_caps);
2457         } else {
2458                 err = mmc_get_capabilities(mmc);
2459                 if (err)
2460                         return err;
2461                 mmc_select_mode_and_width(mmc, mmc->card_caps);
2462         }
2463 #endif
2464         if (err)
2465                 return err;
2466
2467         mmc->best_mode = mmc->selected_mode;
2468
2469         /* Fix the block length for DDR mode */
2470         if (mmc->ddr_mode) {
2471                 mmc->read_bl_len = MMC_MAX_BLOCK_LEN;
2472 #if CONFIG_IS_ENABLED(MMC_WRITE)
2473                 mmc->write_bl_len = MMC_MAX_BLOCK_LEN;
2474 #endif
2475         }
2476
2477         /* fill in device description */
2478         bdesc = mmc_get_blk_desc(mmc);
2479         bdesc->lun = 0;
2480         bdesc->hwpart = 0;
2481         bdesc->type = 0;
2482         bdesc->blksz = mmc->read_bl_len;
2483         bdesc->log2blksz = LOG2(bdesc->blksz);
2484         bdesc->lba = lldiv(mmc->capacity, mmc->read_bl_len);
2485 #if !defined(CONFIG_SPL_BUILD) || \
2486                 (defined(CONFIG_SPL_LIBCOMMON_SUPPORT) && \
2487                 !defined(CONFIG_USE_TINY_PRINTF))
2488         sprintf(bdesc->vendor, "Man %06x Snr %04x%04x",
2489                 mmc->cid[0] >> 24, (mmc->cid[2] & 0xffff),
2490                 (mmc->cid[3] >> 16) & 0xffff);
2491         sprintf(bdesc->product, "%c%c%c%c%c%c", mmc->cid[0] & 0xff,
2492                 (mmc->cid[1] >> 24), (mmc->cid[1] >> 16) & 0xff,
2493                 (mmc->cid[1] >> 8) & 0xff, mmc->cid[1] & 0xff,
2494                 (mmc->cid[2] >> 24) & 0xff);
2495         sprintf(bdesc->revision, "%d.%d", (mmc->cid[2] >> 20) & 0xf,
2496                 (mmc->cid[2] >> 16) & 0xf);
2497 #else
2498         bdesc->vendor[0] = 0;
2499         bdesc->product[0] = 0;
2500         bdesc->revision[0] = 0;
2501 #endif
2502
2503 #if !defined(CONFIG_DM_MMC) && (!defined(CONFIG_SPL_BUILD) || defined(CONFIG_SPL_LIBDISK_SUPPORT))
2504         part_init(bdesc);
2505 #endif
2506
2507         return 0;
2508 }
2509
2510 static int mmc_send_if_cond(struct mmc *mmc)
2511 {
2512         struct mmc_cmd cmd;
2513         int err;
2514
2515         cmd.cmdidx = SD_CMD_SEND_IF_COND;
2516         /* We set the bit if the host supports voltages between 2.7 and 3.6 V */
2517         cmd.cmdarg = ((mmc->cfg->voltages & 0xff8000) != 0) << 8 | 0xaa;
2518         cmd.resp_type = MMC_RSP_R7;
2519
2520         err = mmc_send_cmd(mmc, &cmd, NULL);
2521
2522         if (err)
2523                 return err;
2524
2525         if ((cmd.response[0] & 0xff) != 0xaa)
2526                 return -EOPNOTSUPP;
2527         else
2528                 mmc->version = SD_VERSION_2;
2529
2530         return 0;
2531 }
2532
2533 #if !CONFIG_IS_ENABLED(DM_MMC)
2534 /* board-specific MMC power initializations. */
2535 __weak void board_mmc_power_init(void)
2536 {
2537 }
2538 #endif
2539
2540 static int mmc_power_init(struct mmc *mmc)
2541 {
2542 #if CONFIG_IS_ENABLED(DM_MMC)
2543 #if CONFIG_IS_ENABLED(DM_REGULATOR)
2544         int ret;
2545
2546         ret = device_get_supply_regulator(mmc->dev, "vmmc-supply",
2547                                           &mmc->vmmc_supply);
2548         if (ret)
2549                 pr_debug("%s: No vmmc supply\n", mmc->dev->name);
2550
2551         ret = device_get_supply_regulator(mmc->dev, "vqmmc-supply",
2552                                           &mmc->vqmmc_supply);
2553         if (ret)
2554                 pr_debug("%s: No vqmmc supply\n", mmc->dev->name);
2555 #endif
2556 #else /* !CONFIG_DM_MMC */
2557         /*
2558          * Driver model should use a regulator, as above, rather than calling
2559          * out to board code.
2560          */
2561         board_mmc_power_init();
2562 #endif
2563         return 0;
2564 }
2565
2566 /*
2567  * put the host in the initial state:
2568  * - turn on Vdd (card power supply)
2569  * - configure the bus width and clock to minimal values
2570  */
2571 static void mmc_set_initial_state(struct mmc *mmc)
2572 {
2573         int err;
2574
2575         /* First try to set 3.3V. If it fails set to 1.8V */
2576         err = mmc_set_signal_voltage(mmc, MMC_SIGNAL_VOLTAGE_330);
2577         if (err != 0)
2578                 err = mmc_set_signal_voltage(mmc, MMC_SIGNAL_VOLTAGE_180);
2579         if (err != 0)
2580                 pr_warn("mmc: failed to set signal voltage\n");
2581
2582         mmc_select_mode(mmc, MMC_LEGACY);
2583         mmc_set_bus_width(mmc, 1);
2584         mmc_set_clock(mmc, 0, MMC_CLK_ENABLE);
2585 }
2586
2587 static int mmc_power_on(struct mmc *mmc)
2588 {
2589 #if CONFIG_IS_ENABLED(DM_MMC) && CONFIG_IS_ENABLED(DM_REGULATOR)
2590         if (mmc->vmmc_supply) {
2591                 int ret = regulator_set_enable(mmc->vmmc_supply, true);
2592
2593                 if (ret) {
2594                         puts("Error enabling VMMC supply\n");
2595                         return ret;
2596                 }
2597         }
2598 #endif
2599         return 0;
2600 }
2601
2602 static int mmc_power_off(struct mmc *mmc)
2603 {
2604         mmc_set_clock(mmc, 0, MMC_CLK_DISABLE);
2605 #if CONFIG_IS_ENABLED(DM_MMC) && CONFIG_IS_ENABLED(DM_REGULATOR)
2606         if (mmc->vmmc_supply) {
2607                 int ret = regulator_set_enable(mmc->vmmc_supply, false);
2608
2609                 if (ret) {
2610                         pr_debug("Error disabling VMMC supply\n");
2611                         return ret;
2612                 }
2613         }
2614 #endif
2615         return 0;
2616 }
2617
2618 static int mmc_power_cycle(struct mmc *mmc)
2619 {
2620         int ret;
2621
2622         ret = mmc_power_off(mmc);
2623         if (ret)
2624                 return ret;
2625         /*
2626          * SD spec recommends at least 1ms of delay. Let's wait for 2ms
2627          * to be on the safer side.
2628          */
2629         udelay(2000);
2630         return mmc_power_on(mmc);
2631 }
2632
2633 int mmc_get_op_cond(struct mmc *mmc)
2634 {
2635         bool uhs_en = supports_uhs(mmc->cfg->host_caps);
2636         int err;
2637
2638         if (mmc->has_init)
2639                 return 0;
2640
2641 #ifdef CONFIG_FSL_ESDHC_ADAPTER_IDENT
2642         mmc_adapter_card_type_ident();
2643 #endif
2644         err = mmc_power_init(mmc);
2645         if (err)
2646                 return err;
2647
2648 #ifdef CONFIG_MMC_QUIRKS
2649         mmc->quirks = MMC_QUIRK_RETRY_SET_BLOCKLEN |
2650                       MMC_QUIRK_RETRY_SEND_CID;
2651 #endif
2652
2653         err = mmc_power_cycle(mmc);
2654         if (err) {
2655                 /*
2656                  * if power cycling is not supported, we should not try
2657                  * to use the UHS modes, because we wouldn't be able to
2658                  * recover from an error during the UHS initialization.
2659                  */
2660                 pr_debug("Unable to do a full power cycle. Disabling the UHS modes for safety\n");
2661                 uhs_en = false;
2662                 mmc->host_caps &= ~UHS_CAPS;
2663                 err = mmc_power_on(mmc);
2664         }
2665         if (err)
2666                 return err;
2667
2668 #if CONFIG_IS_ENABLED(DM_MMC)
2669         /* The device has already been probed ready for use */
2670 #else
2671         /* made sure it's not NULL earlier */
2672         err = mmc->cfg->ops->init(mmc);
2673         if (err)
2674                 return err;
2675 #endif
2676         mmc->ddr_mode = 0;
2677
2678 retry:
2679         mmc_set_initial_state(mmc);
2680
2681         /* Reset the Card */
2682         err = mmc_go_idle(mmc);
2683
2684         if (err)
2685                 return err;
2686
2687         /* The internal partition reset to user partition(0) at every CMD0*/
2688         mmc_get_blk_desc(mmc)->hwpart = 0;
2689
2690         /* Test for SD version 2 */
2691         err = mmc_send_if_cond(mmc);
2692
2693         /* Now try to get the SD card's operating condition */
2694         err = sd_send_op_cond(mmc, uhs_en);
2695         if (err && uhs_en) {
2696                 uhs_en = false;
2697                 mmc_power_cycle(mmc);
2698                 goto retry;
2699         }
2700
2701         /* If the command timed out, we check for an MMC card */
2702         if (err == -ETIMEDOUT) {
2703                 err = mmc_send_op_cond(mmc);
2704
2705                 if (err) {
2706 #if !defined(CONFIG_SPL_BUILD) || defined(CONFIG_SPL_LIBCOMMON_SUPPORT)
2707                         pr_err("Card did not respond to voltage select!\n");
2708 #endif
2709                         return -EOPNOTSUPP;
2710                 }
2711         }
2712
2713         return err;
2714 }
2715
2716 int mmc_start_init(struct mmc *mmc)
2717 {
2718         bool no_card;
2719         int err = 0;
2720
2721         /*
2722          * all hosts are capable of 1 bit bus-width and able to use the legacy
2723          * timings.
2724          */
2725         mmc->host_caps = mmc->cfg->host_caps | MMC_CAP(SD_LEGACY) |
2726                          MMC_CAP(MMC_LEGACY) | MMC_MODE_1BIT;
2727
2728 #if !defined(CONFIG_MMC_BROKEN_CD)
2729         /* we pretend there's no card when init is NULL */
2730         no_card = mmc_getcd(mmc) == 0;
2731 #else
2732         no_card = 0;
2733 #endif
2734 #if !CONFIG_IS_ENABLED(DM_MMC)
2735         no_card = no_card || (mmc->cfg->ops->init == NULL);
2736 #endif
2737         if (no_card) {
2738                 mmc->has_init = 0;
2739 #if !defined(CONFIG_SPL_BUILD) || defined(CONFIG_SPL_LIBCOMMON_SUPPORT)
2740                 pr_err("MMC: no card present\n");
2741 #endif
2742                 return -ENOMEDIUM;
2743         }
2744
2745         err = mmc_get_op_cond(mmc);
2746
2747         if (!err)
2748                 mmc->init_in_progress = 1;
2749
2750         return err;
2751 }
2752
2753 static int mmc_complete_init(struct mmc *mmc)
2754 {
2755         int err = 0;
2756
2757         mmc->init_in_progress = 0;
2758         if (mmc->op_cond_pending)
2759                 err = mmc_complete_op_cond(mmc);
2760
2761         if (!err)
2762                 err = mmc_startup(mmc);
2763         if (err)
2764                 mmc->has_init = 0;
2765         else
2766                 mmc->has_init = 1;
2767         return err;
2768 }
2769
2770 int mmc_init(struct mmc *mmc)
2771 {
2772         int err = 0;
2773         __maybe_unused ulong start;
2774 #if CONFIG_IS_ENABLED(DM_MMC)
2775         struct mmc_uclass_priv *upriv = dev_get_uclass_priv(mmc->dev);
2776
2777         upriv->mmc = mmc;
2778 #endif
2779         if (mmc->has_init)
2780                 return 0;
2781
2782         start = get_timer(0);
2783
2784         if (!mmc->init_in_progress)
2785                 err = mmc_start_init(mmc);
2786
2787         if (!err)
2788                 err = mmc_complete_init(mmc);
2789         if (err)
2790                 pr_info("%s: %d, time %lu\n", __func__, err, get_timer(start));
2791
2792         return err;
2793 }
2794
2795 #if CONFIG_IS_ENABLED(MMC_UHS_SUPPORT) || \
2796     CONFIG_IS_ENABLED(MMC_HS200_SUPPORT) || \
2797     CONFIG_IS_ENABLED(MMC_HS400_SUPPORT)
2798 int mmc_deinit(struct mmc *mmc)
2799 {
2800         u32 caps_filtered;
2801
2802         if (!mmc->has_init)
2803                 return 0;
2804
2805         if (IS_SD(mmc)) {
2806                 caps_filtered = mmc->card_caps &
2807                         ~(MMC_CAP(UHS_SDR12) | MMC_CAP(UHS_SDR25) |
2808                           MMC_CAP(UHS_SDR50) | MMC_CAP(UHS_DDR50) |
2809                           MMC_CAP(UHS_SDR104));
2810
2811                 return sd_select_mode_and_width(mmc, caps_filtered);
2812         } else {
2813                 caps_filtered = mmc->card_caps &
2814                         ~(MMC_CAP(MMC_HS_200) | MMC_CAP(MMC_HS_400));
2815
2816                 return mmc_select_mode_and_width(mmc, caps_filtered);
2817         }
2818 }
2819 #endif
2820
2821 int mmc_set_dsr(struct mmc *mmc, u16 val)
2822 {
2823         mmc->dsr = val;
2824         return 0;
2825 }
2826
2827 /* CPU-specific MMC initializations */
2828 __weak int cpu_mmc_init(bd_t *bis)
2829 {
2830         return -1;
2831 }
2832
2833 /* board-specific MMC initializations. */
2834 __weak int board_mmc_init(bd_t *bis)
2835 {
2836         return -1;
2837 }
2838
2839 void mmc_set_preinit(struct mmc *mmc, int preinit)
2840 {
2841         mmc->preinit = preinit;
2842 }
2843
2844 #if CONFIG_IS_ENABLED(DM_MMC)
2845 static int mmc_probe(bd_t *bis)
2846 {
2847         int ret, i;
2848         struct uclass *uc;
2849         struct udevice *dev;
2850
2851         ret = uclass_get(UCLASS_MMC, &uc);
2852         if (ret)
2853                 return ret;
2854
2855         /*
2856          * Try to add them in sequence order. Really with driver model we
2857          * should allow holes, but the current MMC list does not allow that.
2858          * So if we request 0, 1, 3 we will get 0, 1, 2.
2859          */
2860         for (i = 0; ; i++) {
2861                 ret = uclass_get_device_by_seq(UCLASS_MMC, i, &dev);
2862                 if (ret == -ENODEV)
2863                         break;
2864         }
2865         uclass_foreach_dev(dev, uc) {
2866                 ret = device_probe(dev);
2867                 if (ret)
2868                         pr_err("%s - probe failed: %d\n", dev->name, ret);
2869         }
2870
2871         return 0;
2872 }
2873 #else
2874 static int mmc_probe(bd_t *bis)
2875 {
2876         if (board_mmc_init(bis) < 0)
2877                 cpu_mmc_init(bis);
2878
2879         return 0;
2880 }
2881 #endif
2882
2883 int mmc_initialize(bd_t *bis)
2884 {
2885         static int initialized = 0;
2886         int ret;
2887         if (initialized)        /* Avoid initializing mmc multiple times */
2888                 return 0;
2889         initialized = 1;
2890
2891 #if !CONFIG_IS_ENABLED(BLK)
2892 #if !CONFIG_IS_ENABLED(MMC_TINY)
2893         mmc_list_init();
2894 #endif
2895 #endif
2896         ret = mmc_probe(bis);
2897         if (ret)
2898                 return ret;
2899
2900 #ifndef CONFIG_SPL_BUILD
2901         print_mmc_devices(',');
2902 #endif
2903
2904         mmc_do_preinit();
2905         return 0;
2906 }
2907
2908 #ifdef CONFIG_CMD_BKOPS_ENABLE
2909 int mmc_set_bkops_enable(struct mmc *mmc)
2910 {
2911         int err;
2912         ALLOC_CACHE_ALIGN_BUFFER(u8, ext_csd, MMC_MAX_BLOCK_LEN);
2913
2914         err = mmc_send_ext_csd(mmc, ext_csd);
2915         if (err) {
2916                 puts("Could not get ext_csd register values\n");
2917                 return err;
2918         }
2919
2920         if (!(ext_csd[EXT_CSD_BKOPS_SUPPORT] & 0x1)) {
2921                 puts("Background operations not supported on device\n");
2922                 return -EMEDIUMTYPE;
2923         }
2924
2925         if (ext_csd[EXT_CSD_BKOPS_EN] & 0x1) {
2926                 puts("Background operations already enabled\n");
2927                 return 0;
2928         }
2929
2930         err = mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_BKOPS_EN, 1);
2931         if (err) {
2932                 puts("Failed to enable manual background operations\n");
2933                 return err;
2934         }
2935
2936         puts("Enabled manual background operations\n");
2937
2938         return 0;
2939 }
2940 #endif