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