block: pass block dev not num to read/write/erase()
[oweals/u-boot.git] / drivers / mmc / mmc.c
1 /*
2  * Copyright 2008, Freescale Semiconductor, Inc
3  * Andy Fleming
4  *
5  * Based vaguely on the Linux code
6  *
7  * SPDX-License-Identifier:     GPL-2.0+
8  */
9
10 #include <config.h>
11 #include <common.h>
12 #include <command.h>
13 #include <dm.h>
14 #include <dm/device-internal.h>
15 #include <errno.h>
16 #include <mmc.h>
17 #include <part.h>
18 #include <malloc.h>
19 #include <memalign.h>
20 #include <linux/list.h>
21 #include <div64.h>
22 #include "mmc_private.h"
23
24 static struct list_head mmc_devices;
25 static int cur_dev_num = -1;
26
27 __weak int board_mmc_getwp(struct mmc *mmc)
28 {
29         return -1;
30 }
31
32 int mmc_getwp(struct mmc *mmc)
33 {
34         int wp;
35
36         wp = board_mmc_getwp(mmc);
37
38         if (wp < 0) {
39                 if (mmc->cfg->ops->getwp)
40                         wp = mmc->cfg->ops->getwp(mmc);
41                 else
42                         wp = 0;
43         }
44
45         return wp;
46 }
47
48 __weak int board_mmc_getcd(struct mmc *mmc)
49 {
50         return -1;
51 }
52
53 int mmc_send_cmd(struct mmc *mmc, struct mmc_cmd *cmd, struct mmc_data *data)
54 {
55         int ret;
56
57 #ifdef CONFIG_MMC_TRACE
58         int i;
59         u8 *ptr;
60
61         printf("CMD_SEND:%d\n", cmd->cmdidx);
62         printf("\t\tARG\t\t\t 0x%08X\n", cmd->cmdarg);
63         ret = mmc->cfg->ops->send_cmd(mmc, cmd, data);
64         switch (cmd->resp_type) {
65                 case MMC_RSP_NONE:
66                         printf("\t\tMMC_RSP_NONE\n");
67                         break;
68                 case MMC_RSP_R1:
69                         printf("\t\tMMC_RSP_R1,5,6,7 \t 0x%08X \n",
70                                 cmd->response[0]);
71                         break;
72                 case MMC_RSP_R1b:
73                         printf("\t\tMMC_RSP_R1b\t\t 0x%08X \n",
74                                 cmd->response[0]);
75                         break;
76                 case MMC_RSP_R2:
77                         printf("\t\tMMC_RSP_R2\t\t 0x%08X \n",
78                                 cmd->response[0]);
79                         printf("\t\t          \t\t 0x%08X \n",
80                                 cmd->response[1]);
81                         printf("\t\t          \t\t 0x%08X \n",
82                                 cmd->response[2]);
83                         printf("\t\t          \t\t 0x%08X \n",
84                                 cmd->response[3]);
85                         printf("\n");
86                         printf("\t\t\t\t\tDUMPING DATA\n");
87                         for (i = 0; i < 4; i++) {
88                                 int j;
89                                 printf("\t\t\t\t\t%03d - ", i*4);
90                                 ptr = (u8 *)&cmd->response[i];
91                                 ptr += 3;
92                                 for (j = 0; j < 4; j++)
93                                         printf("%02X ", *ptr--);
94                                 printf("\n");
95                         }
96                         break;
97                 case MMC_RSP_R3:
98                         printf("\t\tMMC_RSP_R3,4\t\t 0x%08X \n",
99                                 cmd->response[0]);
100                         break;
101                 default:
102                         printf("\t\tERROR MMC rsp not supported\n");
103                         break;
104         }
105 #else
106         ret = mmc->cfg->ops->send_cmd(mmc, cmd, data);
107 #endif
108         return ret;
109 }
110
111 int mmc_send_status(struct mmc *mmc, int timeout)
112 {
113         struct mmc_cmd cmd;
114         int err, retries = 5;
115 #ifdef CONFIG_MMC_TRACE
116         int status;
117 #endif
118
119         cmd.cmdidx = MMC_CMD_SEND_STATUS;
120         cmd.resp_type = MMC_RSP_R1;
121         if (!mmc_host_is_spi(mmc))
122                 cmd.cmdarg = mmc->rca << 16;
123
124         while (1) {
125                 err = mmc_send_cmd(mmc, &cmd, NULL);
126                 if (!err) {
127                         if ((cmd.response[0] & MMC_STATUS_RDY_FOR_DATA) &&
128                             (cmd.response[0] & MMC_STATUS_CURR_STATE) !=
129                              MMC_STATE_PRG)
130                                 break;
131                         else if (cmd.response[0] & MMC_STATUS_MASK) {
132 #if !defined(CONFIG_SPL_BUILD) || defined(CONFIG_SPL_LIBCOMMON_SUPPORT)
133                                 printf("Status Error: 0x%08X\n",
134                                         cmd.response[0]);
135 #endif
136                                 return COMM_ERR;
137                         }
138                 } else if (--retries < 0)
139                         return err;
140
141                 if (timeout-- <= 0)
142                         break;
143
144                 udelay(1000);
145         }
146
147 #ifdef CONFIG_MMC_TRACE
148         status = (cmd.response[0] & MMC_STATUS_CURR_STATE) >> 9;
149         printf("CURR STATE:%d\n", status);
150 #endif
151         if (timeout <= 0) {
152 #if !defined(CONFIG_SPL_BUILD) || defined(CONFIG_SPL_LIBCOMMON_SUPPORT)
153                 printf("Timeout waiting card ready\n");
154 #endif
155                 return TIMEOUT;
156         }
157         if (cmd.response[0] & MMC_STATUS_SWITCH_ERROR)
158                 return SWITCH_ERR;
159
160         return 0;
161 }
162
163 int mmc_set_blocklen(struct mmc *mmc, int len)
164 {
165         struct mmc_cmd cmd;
166
167         if (mmc->ddr_mode)
168                 return 0;
169
170         cmd.cmdidx = MMC_CMD_SET_BLOCKLEN;
171         cmd.resp_type = MMC_RSP_R1;
172         cmd.cmdarg = len;
173
174         return mmc_send_cmd(mmc, &cmd, NULL);
175 }
176
177 struct mmc *find_mmc_device(int dev_num)
178 {
179         struct mmc *m;
180         struct list_head *entry;
181
182         list_for_each(entry, &mmc_devices) {
183                 m = list_entry(entry, struct mmc, link);
184
185                 if (m->block_dev.dev == dev_num)
186                         return m;
187         }
188
189 #if !defined(CONFIG_SPL_BUILD) || defined(CONFIG_SPL_LIBCOMMON_SUPPORT)
190         printf("MMC Device %d not found\n", dev_num);
191 #endif
192
193         return NULL;
194 }
195
196 static int mmc_read_blocks(struct mmc *mmc, void *dst, lbaint_t start,
197                            lbaint_t blkcnt)
198 {
199         struct mmc_cmd cmd;
200         struct mmc_data data;
201
202         if (blkcnt > 1)
203                 cmd.cmdidx = MMC_CMD_READ_MULTIPLE_BLOCK;
204         else
205                 cmd.cmdidx = MMC_CMD_READ_SINGLE_BLOCK;
206
207         if (mmc->high_capacity)
208                 cmd.cmdarg = start;
209         else
210                 cmd.cmdarg = start * mmc->read_bl_len;
211
212         cmd.resp_type = MMC_RSP_R1;
213
214         data.dest = dst;
215         data.blocks = blkcnt;
216         data.blocksize = mmc->read_bl_len;
217         data.flags = MMC_DATA_READ;
218
219         if (mmc_send_cmd(mmc, &cmd, &data))
220                 return 0;
221
222         if (blkcnt > 1) {
223                 cmd.cmdidx = MMC_CMD_STOP_TRANSMISSION;
224                 cmd.cmdarg = 0;
225                 cmd.resp_type = MMC_RSP_R1b;
226                 if (mmc_send_cmd(mmc, &cmd, NULL)) {
227 #if !defined(CONFIG_SPL_BUILD) || defined(CONFIG_SPL_LIBCOMMON_SUPPORT)
228                         printf("mmc fail to send stop cmd\n");
229 #endif
230                         return 0;
231                 }
232         }
233
234         return blkcnt;
235 }
236
237 static ulong mmc_bread(block_dev_desc_t *block_dev, lbaint_t start,
238                        lbaint_t blkcnt, void *dst)
239 {
240         int dev_num = block_dev->dev;
241         lbaint_t cur, blocks_todo = blkcnt;
242
243         if (blkcnt == 0)
244                 return 0;
245
246         struct mmc *mmc = find_mmc_device(dev_num);
247         if (!mmc)
248                 return 0;
249
250         if ((start + blkcnt) > mmc->block_dev.lba) {
251 #if !defined(CONFIG_SPL_BUILD) || defined(CONFIG_SPL_LIBCOMMON_SUPPORT)
252                 printf("MMC: block number 0x" LBAF " exceeds max(0x" LBAF ")\n",
253                         start + blkcnt, mmc->block_dev.lba);
254 #endif
255                 return 0;
256         }
257
258         if (mmc_set_blocklen(mmc, mmc->read_bl_len)) {
259                 debug("%s: Failed to set blocklen\n", __func__);
260                 return 0;
261         }
262
263         do {
264                 cur = (blocks_todo > mmc->cfg->b_max) ?
265                         mmc->cfg->b_max : blocks_todo;
266                 if (mmc_read_blocks(mmc, dst, start, cur) != cur) {
267                         debug("%s: Failed to read blocks\n", __func__);
268                         return 0;
269                 }
270                 blocks_todo -= cur;
271                 start += cur;
272                 dst += cur * mmc->read_bl_len;
273         } while (blocks_todo > 0);
274
275         return blkcnt;
276 }
277
278 static int mmc_go_idle(struct mmc *mmc)
279 {
280         struct mmc_cmd cmd;
281         int err;
282
283         udelay(1000);
284
285         cmd.cmdidx = MMC_CMD_GO_IDLE_STATE;
286         cmd.cmdarg = 0;
287         cmd.resp_type = MMC_RSP_NONE;
288
289         err = mmc_send_cmd(mmc, &cmd, NULL);
290
291         if (err)
292                 return err;
293
294         udelay(2000);
295
296         return 0;
297 }
298
299 static int sd_send_op_cond(struct mmc *mmc)
300 {
301         int timeout = 1000;
302         int err;
303         struct mmc_cmd cmd;
304
305         while (1) {
306                 cmd.cmdidx = MMC_CMD_APP_CMD;
307                 cmd.resp_type = MMC_RSP_R1;
308                 cmd.cmdarg = 0;
309
310                 err = mmc_send_cmd(mmc, &cmd, NULL);
311
312                 if (err)
313                         return err;
314
315                 cmd.cmdidx = SD_CMD_APP_SEND_OP_COND;
316                 cmd.resp_type = MMC_RSP_R3;
317
318                 /*
319                  * Most cards do not answer if some reserved bits
320                  * in the ocr are set. However, Some controller
321                  * can set bit 7 (reserved for low voltages), but
322                  * how to manage low voltages SD card is not yet
323                  * specified.
324                  */
325                 cmd.cmdarg = mmc_host_is_spi(mmc) ? 0 :
326                         (mmc->cfg->voltages & 0xff8000);
327
328                 if (mmc->version == SD_VERSION_2)
329                         cmd.cmdarg |= OCR_HCS;
330
331                 err = mmc_send_cmd(mmc, &cmd, NULL);
332
333                 if (err)
334                         return err;
335
336                 if (cmd.response[0] & OCR_BUSY)
337                         break;
338
339                 if (timeout-- <= 0)
340                         return UNUSABLE_ERR;
341
342                 udelay(1000);
343         }
344
345         if (mmc->version != SD_VERSION_2)
346                 mmc->version = SD_VERSION_1_0;
347
348         if (mmc_host_is_spi(mmc)) { /* read OCR for spi */
349                 cmd.cmdidx = MMC_CMD_SPI_READ_OCR;
350                 cmd.resp_type = MMC_RSP_R3;
351                 cmd.cmdarg = 0;
352
353                 err = mmc_send_cmd(mmc, &cmd, NULL);
354
355                 if (err)
356                         return err;
357         }
358
359         mmc->ocr = cmd.response[0];
360
361         mmc->high_capacity = ((mmc->ocr & OCR_HCS) == OCR_HCS);
362         mmc->rca = 0;
363
364         return 0;
365 }
366
367 static int mmc_send_op_cond_iter(struct mmc *mmc, int use_arg)
368 {
369         struct mmc_cmd cmd;
370         int err;
371
372         cmd.cmdidx = MMC_CMD_SEND_OP_COND;
373         cmd.resp_type = MMC_RSP_R3;
374         cmd.cmdarg = 0;
375         if (use_arg && !mmc_host_is_spi(mmc))
376                 cmd.cmdarg = OCR_HCS |
377                         (mmc->cfg->voltages &
378                         (mmc->ocr & OCR_VOLTAGE_MASK)) |
379                         (mmc->ocr & OCR_ACCESS_MODE);
380
381         err = mmc_send_cmd(mmc, &cmd, NULL);
382         if (err)
383                 return err;
384         mmc->ocr = cmd.response[0];
385         return 0;
386 }
387
388 static int mmc_send_op_cond(struct mmc *mmc)
389 {
390         int err, i;
391
392         /* Some cards seem to need this */
393         mmc_go_idle(mmc);
394
395         /* Asking to the card its capabilities */
396         for (i = 0; i < 2; i++) {
397                 err = mmc_send_op_cond_iter(mmc, i != 0);
398                 if (err)
399                         return err;
400
401                 /* exit if not busy (flag seems to be inverted) */
402                 if (mmc->ocr & OCR_BUSY)
403                         break;
404         }
405         mmc->op_cond_pending = 1;
406         return 0;
407 }
408
409 static int mmc_complete_op_cond(struct mmc *mmc)
410 {
411         struct mmc_cmd cmd;
412         int timeout = 1000;
413         uint start;
414         int err;
415
416         mmc->op_cond_pending = 0;
417         if (!(mmc->ocr & OCR_BUSY)) {
418                 start = get_timer(0);
419                 while (1) {
420                         err = mmc_send_op_cond_iter(mmc, 1);
421                         if (err)
422                                 return err;
423                         if (mmc->ocr & OCR_BUSY)
424                                 break;
425                         if (get_timer(start) > timeout)
426                                 return UNUSABLE_ERR;
427                         udelay(100);
428                 }
429         }
430
431         if (mmc_host_is_spi(mmc)) { /* read OCR for spi */
432                 cmd.cmdidx = MMC_CMD_SPI_READ_OCR;
433                 cmd.resp_type = MMC_RSP_R3;
434                 cmd.cmdarg = 0;
435
436                 err = mmc_send_cmd(mmc, &cmd, NULL);
437
438                 if (err)
439                         return err;
440
441                 mmc->ocr = cmd.response[0];
442         }
443
444         mmc->version = MMC_VERSION_UNKNOWN;
445
446         mmc->high_capacity = ((mmc->ocr & OCR_HCS) == OCR_HCS);
447         mmc->rca = 1;
448
449         return 0;
450 }
451
452
453 static int mmc_send_ext_csd(struct mmc *mmc, u8 *ext_csd)
454 {
455         struct mmc_cmd cmd;
456         struct mmc_data data;
457         int err;
458
459         /* Get the Card Status Register */
460         cmd.cmdidx = MMC_CMD_SEND_EXT_CSD;
461         cmd.resp_type = MMC_RSP_R1;
462         cmd.cmdarg = 0;
463
464         data.dest = (char *)ext_csd;
465         data.blocks = 1;
466         data.blocksize = MMC_MAX_BLOCK_LEN;
467         data.flags = MMC_DATA_READ;
468
469         err = mmc_send_cmd(mmc, &cmd, &data);
470
471         return err;
472 }
473
474
475 static int mmc_switch(struct mmc *mmc, u8 set, u8 index, u8 value)
476 {
477         struct mmc_cmd cmd;
478         int timeout = 1000;
479         int ret;
480
481         cmd.cmdidx = MMC_CMD_SWITCH;
482         cmd.resp_type = MMC_RSP_R1b;
483         cmd.cmdarg = (MMC_SWITCH_MODE_WRITE_BYTE << 24) |
484                                  (index << 16) |
485                                  (value << 8);
486
487         ret = mmc_send_cmd(mmc, &cmd, NULL);
488
489         /* Waiting for the ready status */
490         if (!ret)
491                 ret = mmc_send_status(mmc, timeout);
492
493         return ret;
494
495 }
496
497 static int mmc_change_freq(struct mmc *mmc)
498 {
499         ALLOC_CACHE_ALIGN_BUFFER(u8, ext_csd, MMC_MAX_BLOCK_LEN);
500         char cardtype;
501         int err;
502
503         mmc->card_caps = 0;
504
505         if (mmc_host_is_spi(mmc))
506                 return 0;
507
508         /* Only version 4 supports high-speed */
509         if (mmc->version < MMC_VERSION_4)
510                 return 0;
511
512         mmc->card_caps |= MMC_MODE_4BIT | MMC_MODE_8BIT;
513
514         err = mmc_send_ext_csd(mmc, ext_csd);
515
516         if (err)
517                 return err;
518
519         cardtype = ext_csd[EXT_CSD_CARD_TYPE] & 0xf;
520
521         err = mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_HS_TIMING, 1);
522
523         if (err)
524                 return err == SWITCH_ERR ? 0 : err;
525
526         /* Now check to see that it worked */
527         err = mmc_send_ext_csd(mmc, ext_csd);
528
529         if (err)
530                 return err;
531
532         /* No high-speed support */
533         if (!ext_csd[EXT_CSD_HS_TIMING])
534                 return 0;
535
536         /* High Speed is set, there are two types: 52MHz and 26MHz */
537         if (cardtype & EXT_CSD_CARD_TYPE_52) {
538                 if (cardtype & EXT_CSD_CARD_TYPE_DDR_1_8V)
539                         mmc->card_caps |= MMC_MODE_DDR_52MHz;
540                 mmc->card_caps |= MMC_MODE_HS_52MHz | MMC_MODE_HS;
541         } else {
542                 mmc->card_caps |= MMC_MODE_HS;
543         }
544
545         return 0;
546 }
547
548 static int mmc_set_capacity(struct mmc *mmc, int part_num)
549 {
550         switch (part_num) {
551         case 0:
552                 mmc->capacity = mmc->capacity_user;
553                 break;
554         case 1:
555         case 2:
556                 mmc->capacity = mmc->capacity_boot;
557                 break;
558         case 3:
559                 mmc->capacity = mmc->capacity_rpmb;
560                 break;
561         case 4:
562         case 5:
563         case 6:
564         case 7:
565                 mmc->capacity = mmc->capacity_gp[part_num - 4];
566                 break;
567         default:
568                 return -1;
569         }
570
571         mmc->block_dev.lba = lldiv(mmc->capacity, mmc->read_bl_len);
572
573         return 0;
574 }
575
576 int mmc_select_hwpart(int dev_num, int hwpart)
577 {
578         struct mmc *mmc = find_mmc_device(dev_num);
579         int ret;
580
581         if (!mmc)
582                 return -ENODEV;
583
584         if (mmc->part_num == hwpart)
585                 return 0;
586
587         if (mmc->part_config == MMCPART_NOAVAILABLE) {
588                 printf("Card doesn't support part_switch\n");
589                 return -EMEDIUMTYPE;
590         }
591
592         ret = mmc_switch_part(dev_num, hwpart);
593         if (ret)
594                 return ret;
595
596         mmc->part_num = hwpart;
597
598         return 0;
599 }
600
601
602 int mmc_switch_part(int dev_num, unsigned int part_num)
603 {
604         struct mmc *mmc = find_mmc_device(dev_num);
605         int ret;
606
607         if (!mmc)
608                 return -1;
609
610         ret = mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_PART_CONF,
611                          (mmc->part_config & ~PART_ACCESS_MASK)
612                          | (part_num & PART_ACCESS_MASK));
613
614         /*
615          * Set the capacity if the switch succeeded or was intended
616          * to return to representing the raw device.
617          */
618         if ((ret == 0) || ((ret == -ENODEV) && (part_num == 0)))
619                 ret = mmc_set_capacity(mmc, part_num);
620
621         return ret;
622 }
623
624 int mmc_hwpart_config(struct mmc *mmc,
625                       const struct mmc_hwpart_conf *conf,
626                       enum mmc_hwpart_conf_mode mode)
627 {
628         u8 part_attrs = 0;
629         u32 enh_size_mult;
630         u32 enh_start_addr;
631         u32 gp_size_mult[4];
632         u32 max_enh_size_mult;
633         u32 tot_enh_size_mult = 0;
634         u8 wr_rel_set;
635         int i, pidx, err;
636         ALLOC_CACHE_ALIGN_BUFFER(u8, ext_csd, MMC_MAX_BLOCK_LEN);
637
638         if (mode < MMC_HWPART_CONF_CHECK || mode > MMC_HWPART_CONF_COMPLETE)
639                 return -EINVAL;
640
641         if (IS_SD(mmc) || (mmc->version < MMC_VERSION_4_41)) {
642                 printf("eMMC >= 4.4 required for enhanced user data area\n");
643                 return -EMEDIUMTYPE;
644         }
645
646         if (!(mmc->part_support & PART_SUPPORT)) {
647                 printf("Card does not support partitioning\n");
648                 return -EMEDIUMTYPE;
649         }
650
651         if (!mmc->hc_wp_grp_size) {
652                 printf("Card does not define HC WP group size\n");
653                 return -EMEDIUMTYPE;
654         }
655
656         /* check partition alignment and total enhanced size */
657         if (conf->user.enh_size) {
658                 if (conf->user.enh_size % mmc->hc_wp_grp_size ||
659                     conf->user.enh_start % mmc->hc_wp_grp_size) {
660                         printf("User data enhanced area not HC WP group "
661                                "size aligned\n");
662                         return -EINVAL;
663                 }
664                 part_attrs |= EXT_CSD_ENH_USR;
665                 enh_size_mult = conf->user.enh_size / mmc->hc_wp_grp_size;
666                 if (mmc->high_capacity) {
667                         enh_start_addr = conf->user.enh_start;
668                 } else {
669                         enh_start_addr = (conf->user.enh_start << 9);
670                 }
671         } else {
672                 enh_size_mult = 0;
673                 enh_start_addr = 0;
674         }
675         tot_enh_size_mult += enh_size_mult;
676
677         for (pidx = 0; pidx < 4; pidx++) {
678                 if (conf->gp_part[pidx].size % mmc->hc_wp_grp_size) {
679                         printf("GP%i partition not HC WP group size "
680                                "aligned\n", pidx+1);
681                         return -EINVAL;
682                 }
683                 gp_size_mult[pidx] = conf->gp_part[pidx].size / mmc->hc_wp_grp_size;
684                 if (conf->gp_part[pidx].size && conf->gp_part[pidx].enhanced) {
685                         part_attrs |= EXT_CSD_ENH_GP(pidx);
686                         tot_enh_size_mult += gp_size_mult[pidx];
687                 }
688         }
689
690         if (part_attrs && ! (mmc->part_support & ENHNCD_SUPPORT)) {
691                 printf("Card does not support enhanced attribute\n");
692                 return -EMEDIUMTYPE;
693         }
694
695         err = mmc_send_ext_csd(mmc, ext_csd);
696         if (err)
697                 return err;
698
699         max_enh_size_mult =
700                 (ext_csd[EXT_CSD_MAX_ENH_SIZE_MULT+2] << 16) +
701                 (ext_csd[EXT_CSD_MAX_ENH_SIZE_MULT+1] << 8) +
702                 ext_csd[EXT_CSD_MAX_ENH_SIZE_MULT];
703         if (tot_enh_size_mult > max_enh_size_mult) {
704                 printf("Total enhanced size exceeds maximum (%u > %u)\n",
705                        tot_enh_size_mult, max_enh_size_mult);
706                 return -EMEDIUMTYPE;
707         }
708
709         /* The default value of EXT_CSD_WR_REL_SET is device
710          * dependent, the values can only be changed if the
711          * EXT_CSD_HS_CTRL_REL bit is set. The values can be
712          * changed only once and before partitioning is completed. */
713         wr_rel_set = ext_csd[EXT_CSD_WR_REL_SET];
714         if (conf->user.wr_rel_change) {
715                 if (conf->user.wr_rel_set)
716                         wr_rel_set |= EXT_CSD_WR_DATA_REL_USR;
717                 else
718                         wr_rel_set &= ~EXT_CSD_WR_DATA_REL_USR;
719         }
720         for (pidx = 0; pidx < 4; pidx++) {
721                 if (conf->gp_part[pidx].wr_rel_change) {
722                         if (conf->gp_part[pidx].wr_rel_set)
723                                 wr_rel_set |= EXT_CSD_WR_DATA_REL_GP(pidx);
724                         else
725                                 wr_rel_set &= ~EXT_CSD_WR_DATA_REL_GP(pidx);
726                 }
727         }
728
729         if (wr_rel_set != ext_csd[EXT_CSD_WR_REL_SET] &&
730             !(ext_csd[EXT_CSD_WR_REL_PARAM] & EXT_CSD_HS_CTRL_REL)) {
731                 puts("Card does not support host controlled partition write "
732                      "reliability settings\n");
733                 return -EMEDIUMTYPE;
734         }
735
736         if (ext_csd[EXT_CSD_PARTITION_SETTING] &
737             EXT_CSD_PARTITION_SETTING_COMPLETED) {
738                 printf("Card already partitioned\n");
739                 return -EPERM;
740         }
741
742         if (mode == MMC_HWPART_CONF_CHECK)
743                 return 0;
744
745         /* Partitioning requires high-capacity size definitions */
746         if (!(ext_csd[EXT_CSD_ERASE_GROUP_DEF] & 0x01)) {
747                 err = mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL,
748                                  EXT_CSD_ERASE_GROUP_DEF, 1);
749
750                 if (err)
751                         return err;
752
753                 ext_csd[EXT_CSD_ERASE_GROUP_DEF] = 1;
754
755                 /* update erase group size to be high-capacity */
756                 mmc->erase_grp_size =
757                         ext_csd[EXT_CSD_HC_ERASE_GRP_SIZE] * 1024;
758
759         }
760
761         /* all OK, write the configuration */
762         for (i = 0; i < 4; i++) {
763                 err = mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL,
764                                  EXT_CSD_ENH_START_ADDR+i,
765                                  (enh_start_addr >> (i*8)) & 0xFF);
766                 if (err)
767                         return err;
768         }
769         for (i = 0; i < 3; i++) {
770                 err = mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL,
771                                  EXT_CSD_ENH_SIZE_MULT+i,
772                                  (enh_size_mult >> (i*8)) & 0xFF);
773                 if (err)
774                         return err;
775         }
776         for (pidx = 0; pidx < 4; pidx++) {
777                 for (i = 0; i < 3; i++) {
778                         err = mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL,
779                                          EXT_CSD_GP_SIZE_MULT+pidx*3+i,
780                                          (gp_size_mult[pidx] >> (i*8)) & 0xFF);
781                         if (err)
782                                 return err;
783                 }
784         }
785         err = mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL,
786                          EXT_CSD_PARTITIONS_ATTRIBUTE, part_attrs);
787         if (err)
788                 return err;
789
790         if (mode == MMC_HWPART_CONF_SET)
791                 return 0;
792
793         /* The WR_REL_SET is a write-once register but shall be
794          * written before setting PART_SETTING_COMPLETED. As it is
795          * write-once we can only write it when completing the
796          * partitioning. */
797         if (wr_rel_set != ext_csd[EXT_CSD_WR_REL_SET]) {
798                 err = mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL,
799                                  EXT_CSD_WR_REL_SET, wr_rel_set);
800                 if (err)
801                         return err;
802         }
803
804         /* Setting PART_SETTING_COMPLETED confirms the partition
805          * configuration but it only becomes effective after power
806          * cycle, so we do not adjust the partition related settings
807          * in the mmc struct. */
808
809         err = mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL,
810                          EXT_CSD_PARTITION_SETTING,
811                          EXT_CSD_PARTITION_SETTING_COMPLETED);
812         if (err)
813                 return err;
814
815         return 0;
816 }
817
818 int mmc_getcd(struct mmc *mmc)
819 {
820         int cd;
821
822         cd = board_mmc_getcd(mmc);
823
824         if (cd < 0) {
825                 if (mmc->cfg->ops->getcd)
826                         cd = mmc->cfg->ops->getcd(mmc);
827                 else
828                         cd = 1;
829         }
830
831         return cd;
832 }
833
834 static int sd_switch(struct mmc *mmc, int mode, int group, u8 value, u8 *resp)
835 {
836         struct mmc_cmd cmd;
837         struct mmc_data data;
838
839         /* Switch the frequency */
840         cmd.cmdidx = SD_CMD_SWITCH_FUNC;
841         cmd.resp_type = MMC_RSP_R1;
842         cmd.cmdarg = (mode << 31) | 0xffffff;
843         cmd.cmdarg &= ~(0xf << (group * 4));
844         cmd.cmdarg |= value << (group * 4);
845
846         data.dest = (char *)resp;
847         data.blocksize = 64;
848         data.blocks = 1;
849         data.flags = MMC_DATA_READ;
850
851         return mmc_send_cmd(mmc, &cmd, &data);
852 }
853
854
855 static int sd_change_freq(struct mmc *mmc)
856 {
857         int err;
858         struct mmc_cmd cmd;
859         ALLOC_CACHE_ALIGN_BUFFER(uint, scr, 2);
860         ALLOC_CACHE_ALIGN_BUFFER(uint, switch_status, 16);
861         struct mmc_data data;
862         int timeout;
863
864         mmc->card_caps = 0;
865
866         if (mmc_host_is_spi(mmc))
867                 return 0;
868
869         /* Read the SCR to find out if this card supports higher speeds */
870         cmd.cmdidx = MMC_CMD_APP_CMD;
871         cmd.resp_type = MMC_RSP_R1;
872         cmd.cmdarg = mmc->rca << 16;
873
874         err = mmc_send_cmd(mmc, &cmd, NULL);
875
876         if (err)
877                 return err;
878
879         cmd.cmdidx = SD_CMD_APP_SEND_SCR;
880         cmd.resp_type = MMC_RSP_R1;
881         cmd.cmdarg = 0;
882
883         timeout = 3;
884
885 retry_scr:
886         data.dest = (char *)scr;
887         data.blocksize = 8;
888         data.blocks = 1;
889         data.flags = MMC_DATA_READ;
890
891         err = mmc_send_cmd(mmc, &cmd, &data);
892
893         if (err) {
894                 if (timeout--)
895                         goto retry_scr;
896
897                 return err;
898         }
899
900         mmc->scr[0] = __be32_to_cpu(scr[0]);
901         mmc->scr[1] = __be32_to_cpu(scr[1]);
902
903         switch ((mmc->scr[0] >> 24) & 0xf) {
904                 case 0:
905                         mmc->version = SD_VERSION_1_0;
906                         break;
907                 case 1:
908                         mmc->version = SD_VERSION_1_10;
909                         break;
910                 case 2:
911                         mmc->version = SD_VERSION_2;
912                         if ((mmc->scr[0] >> 15) & 0x1)
913                                 mmc->version = SD_VERSION_3;
914                         break;
915                 default:
916                         mmc->version = SD_VERSION_1_0;
917                         break;
918         }
919
920         if (mmc->scr[0] & SD_DATA_4BIT)
921                 mmc->card_caps |= MMC_MODE_4BIT;
922
923         /* Version 1.0 doesn't support switching */
924         if (mmc->version == SD_VERSION_1_0)
925                 return 0;
926
927         timeout = 4;
928         while (timeout--) {
929                 err = sd_switch(mmc, SD_SWITCH_CHECK, 0, 1,
930                                 (u8 *)switch_status);
931
932                 if (err)
933                         return err;
934
935                 /* The high-speed function is busy.  Try again */
936                 if (!(__be32_to_cpu(switch_status[7]) & SD_HIGHSPEED_BUSY))
937                         break;
938         }
939
940         /* If high-speed isn't supported, we return */
941         if (!(__be32_to_cpu(switch_status[3]) & SD_HIGHSPEED_SUPPORTED))
942                 return 0;
943
944         /*
945          * If the host doesn't support SD_HIGHSPEED, do not switch card to
946          * HIGHSPEED mode even if the card support SD_HIGHSPPED.
947          * This can avoid furthur problem when the card runs in different
948          * mode between the host.
949          */
950         if (!((mmc->cfg->host_caps & MMC_MODE_HS_52MHz) &&
951                 (mmc->cfg->host_caps & MMC_MODE_HS)))
952                 return 0;
953
954         err = sd_switch(mmc, SD_SWITCH_SWITCH, 0, 1, (u8 *)switch_status);
955
956         if (err)
957                 return err;
958
959         if ((__be32_to_cpu(switch_status[4]) & 0x0f000000) == 0x01000000)
960                 mmc->card_caps |= MMC_MODE_HS;
961
962         return 0;
963 }
964
965 /* frequency bases */
966 /* divided by 10 to be nice to platforms without floating point */
967 static const int fbase[] = {
968         10000,
969         100000,
970         1000000,
971         10000000,
972 };
973
974 /* Multiplier values for TRAN_SPEED.  Multiplied by 10 to be nice
975  * to platforms without floating point.
976  */
977 static const int multipliers[] = {
978         0,      /* reserved */
979         10,
980         12,
981         13,
982         15,
983         20,
984         25,
985         30,
986         35,
987         40,
988         45,
989         50,
990         55,
991         60,
992         70,
993         80,
994 };
995
996 static void mmc_set_ios(struct mmc *mmc)
997 {
998         if (mmc->cfg->ops->set_ios)
999                 mmc->cfg->ops->set_ios(mmc);
1000 }
1001
1002 void mmc_set_clock(struct mmc *mmc, uint clock)
1003 {
1004         if (clock > mmc->cfg->f_max)
1005                 clock = mmc->cfg->f_max;
1006
1007         if (clock < mmc->cfg->f_min)
1008                 clock = mmc->cfg->f_min;
1009
1010         mmc->clock = clock;
1011
1012         mmc_set_ios(mmc);
1013 }
1014
1015 static void mmc_set_bus_width(struct mmc *mmc, uint width)
1016 {
1017         mmc->bus_width = width;
1018
1019         mmc_set_ios(mmc);
1020 }
1021
1022 static int mmc_startup(struct mmc *mmc)
1023 {
1024         int err, i;
1025         uint mult, freq;
1026         u64 cmult, csize, capacity;
1027         struct mmc_cmd cmd;
1028         ALLOC_CACHE_ALIGN_BUFFER(u8, ext_csd, MMC_MAX_BLOCK_LEN);
1029         ALLOC_CACHE_ALIGN_BUFFER(u8, test_csd, MMC_MAX_BLOCK_LEN);
1030         int timeout = 1000;
1031         bool has_parts = false;
1032         bool part_completed;
1033
1034 #ifdef CONFIG_MMC_SPI_CRC_ON
1035         if (mmc_host_is_spi(mmc)) { /* enable CRC check for spi */
1036                 cmd.cmdidx = MMC_CMD_SPI_CRC_ON_OFF;
1037                 cmd.resp_type = MMC_RSP_R1;
1038                 cmd.cmdarg = 1;
1039                 err = mmc_send_cmd(mmc, &cmd, NULL);
1040
1041                 if (err)
1042                         return err;
1043         }
1044 #endif
1045
1046         /* Put the Card in Identify Mode */
1047         cmd.cmdidx = mmc_host_is_spi(mmc) ? MMC_CMD_SEND_CID :
1048                 MMC_CMD_ALL_SEND_CID; /* cmd not supported in spi */
1049         cmd.resp_type = MMC_RSP_R2;
1050         cmd.cmdarg = 0;
1051
1052         err = mmc_send_cmd(mmc, &cmd, NULL);
1053
1054         if (err)
1055                 return err;
1056
1057         memcpy(mmc->cid, cmd.response, 16);
1058
1059         /*
1060          * For MMC cards, set the Relative Address.
1061          * For SD cards, get the Relatvie Address.
1062          * This also puts the cards into Standby State
1063          */
1064         if (!mmc_host_is_spi(mmc)) { /* cmd not supported in spi */
1065                 cmd.cmdidx = SD_CMD_SEND_RELATIVE_ADDR;
1066                 cmd.cmdarg = mmc->rca << 16;
1067                 cmd.resp_type = MMC_RSP_R6;
1068
1069                 err = mmc_send_cmd(mmc, &cmd, NULL);
1070
1071                 if (err)
1072                         return err;
1073
1074                 if (IS_SD(mmc))
1075                         mmc->rca = (cmd.response[0] >> 16) & 0xffff;
1076         }
1077
1078         /* Get the Card-Specific Data */
1079         cmd.cmdidx = MMC_CMD_SEND_CSD;
1080         cmd.resp_type = MMC_RSP_R2;
1081         cmd.cmdarg = mmc->rca << 16;
1082
1083         err = mmc_send_cmd(mmc, &cmd, NULL);
1084
1085         /* Waiting for the ready status */
1086         mmc_send_status(mmc, timeout);
1087
1088         if (err)
1089                 return err;
1090
1091         mmc->csd[0] = cmd.response[0];
1092         mmc->csd[1] = cmd.response[1];
1093         mmc->csd[2] = cmd.response[2];
1094         mmc->csd[3] = cmd.response[3];
1095
1096         if (mmc->version == MMC_VERSION_UNKNOWN) {
1097                 int version = (cmd.response[0] >> 26) & 0xf;
1098
1099                 switch (version) {
1100                         case 0:
1101                                 mmc->version = MMC_VERSION_1_2;
1102                                 break;
1103                         case 1:
1104                                 mmc->version = MMC_VERSION_1_4;
1105                                 break;
1106                         case 2:
1107                                 mmc->version = MMC_VERSION_2_2;
1108                                 break;
1109                         case 3:
1110                                 mmc->version = MMC_VERSION_3;
1111                                 break;
1112                         case 4:
1113                                 mmc->version = MMC_VERSION_4;
1114                                 break;
1115                         default:
1116                                 mmc->version = MMC_VERSION_1_2;
1117                                 break;
1118                 }
1119         }
1120
1121         /* divide frequency by 10, since the mults are 10x bigger */
1122         freq = fbase[(cmd.response[0] & 0x7)];
1123         mult = multipliers[((cmd.response[0] >> 3) & 0xf)];
1124
1125         mmc->tran_speed = freq * mult;
1126
1127         mmc->dsr_imp = ((cmd.response[1] >> 12) & 0x1);
1128         mmc->read_bl_len = 1 << ((cmd.response[1] >> 16) & 0xf);
1129
1130         if (IS_SD(mmc))
1131                 mmc->write_bl_len = mmc->read_bl_len;
1132         else
1133                 mmc->write_bl_len = 1 << ((cmd.response[3] >> 22) & 0xf);
1134
1135         if (mmc->high_capacity) {
1136                 csize = (mmc->csd[1] & 0x3f) << 16
1137                         | (mmc->csd[2] & 0xffff0000) >> 16;
1138                 cmult = 8;
1139         } else {
1140                 csize = (mmc->csd[1] & 0x3ff) << 2
1141                         | (mmc->csd[2] & 0xc0000000) >> 30;
1142                 cmult = (mmc->csd[2] & 0x00038000) >> 15;
1143         }
1144
1145         mmc->capacity_user = (csize + 1) << (cmult + 2);
1146         mmc->capacity_user *= mmc->read_bl_len;
1147         mmc->capacity_boot = 0;
1148         mmc->capacity_rpmb = 0;
1149         for (i = 0; i < 4; i++)
1150                 mmc->capacity_gp[i] = 0;
1151
1152         if (mmc->read_bl_len > MMC_MAX_BLOCK_LEN)
1153                 mmc->read_bl_len = MMC_MAX_BLOCK_LEN;
1154
1155         if (mmc->write_bl_len > MMC_MAX_BLOCK_LEN)
1156                 mmc->write_bl_len = MMC_MAX_BLOCK_LEN;
1157
1158         if ((mmc->dsr_imp) && (0xffffffff != mmc->dsr)) {
1159                 cmd.cmdidx = MMC_CMD_SET_DSR;
1160                 cmd.cmdarg = (mmc->dsr & 0xffff) << 16;
1161                 cmd.resp_type = MMC_RSP_NONE;
1162                 if (mmc_send_cmd(mmc, &cmd, NULL))
1163                         printf("MMC: SET_DSR failed\n");
1164         }
1165
1166         /* Select the card, and put it into Transfer Mode */
1167         if (!mmc_host_is_spi(mmc)) { /* cmd not supported in spi */
1168                 cmd.cmdidx = MMC_CMD_SELECT_CARD;
1169                 cmd.resp_type = MMC_RSP_R1;
1170                 cmd.cmdarg = mmc->rca << 16;
1171                 err = mmc_send_cmd(mmc, &cmd, NULL);
1172
1173                 if (err)
1174                         return err;
1175         }
1176
1177         /*
1178          * For SD, its erase group is always one sector
1179          */
1180         mmc->erase_grp_size = 1;
1181         mmc->part_config = MMCPART_NOAVAILABLE;
1182         if (!IS_SD(mmc) && (mmc->version >= MMC_VERSION_4)) {
1183                 /* check  ext_csd version and capacity */
1184                 err = mmc_send_ext_csd(mmc, ext_csd);
1185                 if (err)
1186                         return err;
1187                 if (ext_csd[EXT_CSD_REV] >= 2) {
1188                         /*
1189                          * According to the JEDEC Standard, the value of
1190                          * ext_csd's capacity is valid if the value is more
1191                          * than 2GB
1192                          */
1193                         capacity = ext_csd[EXT_CSD_SEC_CNT] << 0
1194                                         | ext_csd[EXT_CSD_SEC_CNT + 1] << 8
1195                                         | ext_csd[EXT_CSD_SEC_CNT + 2] << 16
1196                                         | ext_csd[EXT_CSD_SEC_CNT + 3] << 24;
1197                         capacity *= MMC_MAX_BLOCK_LEN;
1198                         if ((capacity >> 20) > 2 * 1024)
1199                                 mmc->capacity_user = capacity;
1200                 }
1201
1202                 switch (ext_csd[EXT_CSD_REV]) {
1203                 case 1:
1204                         mmc->version = MMC_VERSION_4_1;
1205                         break;
1206                 case 2:
1207                         mmc->version = MMC_VERSION_4_2;
1208                         break;
1209                 case 3:
1210                         mmc->version = MMC_VERSION_4_3;
1211                         break;
1212                 case 5:
1213                         mmc->version = MMC_VERSION_4_41;
1214                         break;
1215                 case 6:
1216                         mmc->version = MMC_VERSION_4_5;
1217                         break;
1218                 case 7:
1219                         mmc->version = MMC_VERSION_5_0;
1220                         break;
1221                 }
1222
1223                 /* The partition data may be non-zero but it is only
1224                  * effective if PARTITION_SETTING_COMPLETED is set in
1225                  * EXT_CSD, so ignore any data if this bit is not set,
1226                  * except for enabling the high-capacity group size
1227                  * definition (see below). */
1228                 part_completed = !!(ext_csd[EXT_CSD_PARTITION_SETTING] &
1229                                     EXT_CSD_PARTITION_SETTING_COMPLETED);
1230
1231                 /* store the partition info of emmc */
1232                 mmc->part_support = ext_csd[EXT_CSD_PARTITIONING_SUPPORT];
1233                 if ((ext_csd[EXT_CSD_PARTITIONING_SUPPORT] & PART_SUPPORT) ||
1234                     ext_csd[EXT_CSD_BOOT_MULT])
1235                         mmc->part_config = ext_csd[EXT_CSD_PART_CONF];
1236                 if (part_completed &&
1237                     (ext_csd[EXT_CSD_PARTITIONING_SUPPORT] & ENHNCD_SUPPORT))
1238                         mmc->part_attr = ext_csd[EXT_CSD_PARTITIONS_ATTRIBUTE];
1239
1240                 mmc->capacity_boot = ext_csd[EXT_CSD_BOOT_MULT] << 17;
1241
1242                 mmc->capacity_rpmb = ext_csd[EXT_CSD_RPMB_MULT] << 17;
1243
1244                 for (i = 0; i < 4; i++) {
1245                         int idx = EXT_CSD_GP_SIZE_MULT + i * 3;
1246                         uint mult = (ext_csd[idx + 2] << 16) +
1247                                 (ext_csd[idx + 1] << 8) + ext_csd[idx];
1248                         if (mult)
1249                                 has_parts = true;
1250                         if (!part_completed)
1251                                 continue;
1252                         mmc->capacity_gp[i] = mult;
1253                         mmc->capacity_gp[i] *=
1254                                 ext_csd[EXT_CSD_HC_ERASE_GRP_SIZE];
1255                         mmc->capacity_gp[i] *= ext_csd[EXT_CSD_HC_WP_GRP_SIZE];
1256                         mmc->capacity_gp[i] <<= 19;
1257                 }
1258
1259                 if (part_completed) {
1260                         mmc->enh_user_size =
1261                                 (ext_csd[EXT_CSD_ENH_SIZE_MULT+2] << 16) +
1262                                 (ext_csd[EXT_CSD_ENH_SIZE_MULT+1] << 8) +
1263                                 ext_csd[EXT_CSD_ENH_SIZE_MULT];
1264                         mmc->enh_user_size *= ext_csd[EXT_CSD_HC_ERASE_GRP_SIZE];
1265                         mmc->enh_user_size *= ext_csd[EXT_CSD_HC_WP_GRP_SIZE];
1266                         mmc->enh_user_size <<= 19;
1267                         mmc->enh_user_start =
1268                                 (ext_csd[EXT_CSD_ENH_START_ADDR+3] << 24) +
1269                                 (ext_csd[EXT_CSD_ENH_START_ADDR+2] << 16) +
1270                                 (ext_csd[EXT_CSD_ENH_START_ADDR+1] << 8) +
1271                                 ext_csd[EXT_CSD_ENH_START_ADDR];
1272                         if (mmc->high_capacity)
1273                                 mmc->enh_user_start <<= 9;
1274                 }
1275
1276                 /*
1277                  * Host needs to enable ERASE_GRP_DEF bit if device is
1278                  * partitioned. This bit will be lost every time after a reset
1279                  * or power off. This will affect erase size.
1280                  */
1281                 if (part_completed)
1282                         has_parts = true;
1283                 if ((ext_csd[EXT_CSD_PARTITIONING_SUPPORT] & PART_SUPPORT) &&
1284                     (ext_csd[EXT_CSD_PARTITIONS_ATTRIBUTE] & PART_ENH_ATTRIB))
1285                         has_parts = true;
1286                 if (has_parts) {
1287                         err = mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL,
1288                                 EXT_CSD_ERASE_GROUP_DEF, 1);
1289
1290                         if (err)
1291                                 return err;
1292                         else
1293                                 ext_csd[EXT_CSD_ERASE_GROUP_DEF] = 1;
1294                 }
1295
1296                 if (ext_csd[EXT_CSD_ERASE_GROUP_DEF] & 0x01) {
1297                         /* Read out group size from ext_csd */
1298                         mmc->erase_grp_size =
1299                                 ext_csd[EXT_CSD_HC_ERASE_GRP_SIZE] * 1024;
1300                         /*
1301                          * if high capacity and partition setting completed
1302                          * SEC_COUNT is valid even if it is smaller than 2 GiB
1303                          * JEDEC Standard JESD84-B45, 6.2.4
1304                          */
1305                         if (mmc->high_capacity && part_completed) {
1306                                 capacity = (ext_csd[EXT_CSD_SEC_CNT]) |
1307                                         (ext_csd[EXT_CSD_SEC_CNT + 1] << 8) |
1308                                         (ext_csd[EXT_CSD_SEC_CNT + 2] << 16) |
1309                                         (ext_csd[EXT_CSD_SEC_CNT + 3] << 24);
1310                                 capacity *= MMC_MAX_BLOCK_LEN;
1311                                 mmc->capacity_user = capacity;
1312                         }
1313                 } else {
1314                         /* Calculate the group size from the csd value. */
1315                         int erase_gsz, erase_gmul;
1316                         erase_gsz = (mmc->csd[2] & 0x00007c00) >> 10;
1317                         erase_gmul = (mmc->csd[2] & 0x000003e0) >> 5;
1318                         mmc->erase_grp_size = (erase_gsz + 1)
1319                                 * (erase_gmul + 1);
1320                 }
1321
1322                 mmc->hc_wp_grp_size = 1024
1323                         * ext_csd[EXT_CSD_HC_ERASE_GRP_SIZE]
1324                         * ext_csd[EXT_CSD_HC_WP_GRP_SIZE];
1325
1326                 mmc->wr_rel_set = ext_csd[EXT_CSD_WR_REL_SET];
1327         }
1328
1329         err = mmc_set_capacity(mmc, mmc->part_num);
1330         if (err)
1331                 return err;
1332
1333         if (IS_SD(mmc))
1334                 err = sd_change_freq(mmc);
1335         else
1336                 err = mmc_change_freq(mmc);
1337
1338         if (err)
1339                 return err;
1340
1341         /* Restrict card's capabilities by what the host can do */
1342         mmc->card_caps &= mmc->cfg->host_caps;
1343
1344         if (IS_SD(mmc)) {
1345                 if (mmc->card_caps & MMC_MODE_4BIT) {
1346                         cmd.cmdidx = MMC_CMD_APP_CMD;
1347                         cmd.resp_type = MMC_RSP_R1;
1348                         cmd.cmdarg = mmc->rca << 16;
1349
1350                         err = mmc_send_cmd(mmc, &cmd, NULL);
1351                         if (err)
1352                                 return err;
1353
1354                         cmd.cmdidx = SD_CMD_APP_SET_BUS_WIDTH;
1355                         cmd.resp_type = MMC_RSP_R1;
1356                         cmd.cmdarg = 2;
1357                         err = mmc_send_cmd(mmc, &cmd, NULL);
1358                         if (err)
1359                                 return err;
1360
1361                         mmc_set_bus_width(mmc, 4);
1362                 }
1363
1364                 if (mmc->card_caps & MMC_MODE_HS)
1365                         mmc->tran_speed = 50000000;
1366                 else
1367                         mmc->tran_speed = 25000000;
1368         } else if (mmc->version >= MMC_VERSION_4) {
1369                 /* Only version 4 of MMC supports wider bus widths */
1370                 int idx;
1371
1372                 /* An array of possible bus widths in order of preference */
1373                 static unsigned ext_csd_bits[] = {
1374                         EXT_CSD_DDR_BUS_WIDTH_8,
1375                         EXT_CSD_DDR_BUS_WIDTH_4,
1376                         EXT_CSD_BUS_WIDTH_8,
1377                         EXT_CSD_BUS_WIDTH_4,
1378                         EXT_CSD_BUS_WIDTH_1,
1379                 };
1380
1381                 /* An array to map CSD bus widths to host cap bits */
1382                 static unsigned ext_to_hostcaps[] = {
1383                         [EXT_CSD_DDR_BUS_WIDTH_4] =
1384                                 MMC_MODE_DDR_52MHz | MMC_MODE_4BIT,
1385                         [EXT_CSD_DDR_BUS_WIDTH_8] =
1386                                 MMC_MODE_DDR_52MHz | MMC_MODE_8BIT,
1387                         [EXT_CSD_BUS_WIDTH_4] = MMC_MODE_4BIT,
1388                         [EXT_CSD_BUS_WIDTH_8] = MMC_MODE_8BIT,
1389                 };
1390
1391                 /* An array to map chosen bus width to an integer */
1392                 static unsigned widths[] = {
1393                         8, 4, 8, 4, 1,
1394                 };
1395
1396                 for (idx=0; idx < ARRAY_SIZE(ext_csd_bits); idx++) {
1397                         unsigned int extw = ext_csd_bits[idx];
1398                         unsigned int caps = ext_to_hostcaps[extw];
1399
1400                         /*
1401                          * If the bus width is still not changed,
1402                          * don't try to set the default again.
1403                          * Otherwise, recover from switch attempts
1404                          * by switching to 1-bit bus width.
1405                          */
1406                         if (extw == EXT_CSD_BUS_WIDTH_1 &&
1407                                         mmc->bus_width == 1) {
1408                                 err = 0;
1409                                 break;
1410                         }
1411
1412                         /*
1413                          * Check to make sure the card and controller support
1414                          * these capabilities
1415                          */
1416                         if ((mmc->card_caps & caps) != caps)
1417                                 continue;
1418
1419                         err = mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL,
1420                                         EXT_CSD_BUS_WIDTH, extw);
1421
1422                         if (err)
1423                                 continue;
1424
1425                         mmc->ddr_mode = (caps & MMC_MODE_DDR_52MHz) ? 1 : 0;
1426                         mmc_set_bus_width(mmc, widths[idx]);
1427
1428                         err = mmc_send_ext_csd(mmc, test_csd);
1429
1430                         if (err)
1431                                 continue;
1432
1433                         /* Only compare read only fields */
1434                         if (ext_csd[EXT_CSD_PARTITIONING_SUPPORT]
1435                                 == test_csd[EXT_CSD_PARTITIONING_SUPPORT] &&
1436                             ext_csd[EXT_CSD_HC_WP_GRP_SIZE]
1437                                 == test_csd[EXT_CSD_HC_WP_GRP_SIZE] &&
1438                             ext_csd[EXT_CSD_REV]
1439                                 == test_csd[EXT_CSD_REV] &&
1440                             ext_csd[EXT_CSD_HC_ERASE_GRP_SIZE]
1441                                 == test_csd[EXT_CSD_HC_ERASE_GRP_SIZE] &&
1442                             memcmp(&ext_csd[EXT_CSD_SEC_CNT],
1443                                    &test_csd[EXT_CSD_SEC_CNT], 4) == 0)
1444                                 break;
1445                         else
1446                                 err = SWITCH_ERR;
1447                 }
1448
1449                 if (err)
1450                         return err;
1451
1452                 if (mmc->card_caps & MMC_MODE_HS) {
1453                         if (mmc->card_caps & MMC_MODE_HS_52MHz)
1454                                 mmc->tran_speed = 52000000;
1455                         else
1456                                 mmc->tran_speed = 26000000;
1457                 }
1458         }
1459
1460         mmc_set_clock(mmc, mmc->tran_speed);
1461
1462         /* Fix the block length for DDR mode */
1463         if (mmc->ddr_mode) {
1464                 mmc->read_bl_len = MMC_MAX_BLOCK_LEN;
1465                 mmc->write_bl_len = MMC_MAX_BLOCK_LEN;
1466         }
1467
1468         /* fill in device description */
1469         mmc->block_dev.lun = 0;
1470         mmc->block_dev.type = 0;
1471         mmc->block_dev.blksz = mmc->read_bl_len;
1472         mmc->block_dev.log2blksz = LOG2(mmc->block_dev.blksz);
1473         mmc->block_dev.lba = lldiv(mmc->capacity, mmc->read_bl_len);
1474 #if !defined(CONFIG_SPL_BUILD) || \
1475                 (defined(CONFIG_SPL_LIBCOMMON_SUPPORT) && \
1476                 !defined(CONFIG_USE_TINY_PRINTF))
1477         sprintf(mmc->block_dev.vendor, "Man %06x Snr %04x%04x",
1478                 mmc->cid[0] >> 24, (mmc->cid[2] & 0xffff),
1479                 (mmc->cid[3] >> 16) & 0xffff);
1480         sprintf(mmc->block_dev.product, "%c%c%c%c%c%c", mmc->cid[0] & 0xff,
1481                 (mmc->cid[1] >> 24), (mmc->cid[1] >> 16) & 0xff,
1482                 (mmc->cid[1] >> 8) & 0xff, mmc->cid[1] & 0xff,
1483                 (mmc->cid[2] >> 24) & 0xff);
1484         sprintf(mmc->block_dev.revision, "%d.%d", (mmc->cid[2] >> 20) & 0xf,
1485                 (mmc->cid[2] >> 16) & 0xf);
1486 #else
1487         mmc->block_dev.vendor[0] = 0;
1488         mmc->block_dev.product[0] = 0;
1489         mmc->block_dev.revision[0] = 0;
1490 #endif
1491 #if !defined(CONFIG_SPL_BUILD) || defined(CONFIG_SPL_LIBDISK_SUPPORT)
1492         init_part(&mmc->block_dev);
1493 #endif
1494
1495         return 0;
1496 }
1497
1498 static int mmc_send_if_cond(struct mmc *mmc)
1499 {
1500         struct mmc_cmd cmd;
1501         int err;
1502
1503         cmd.cmdidx = SD_CMD_SEND_IF_COND;
1504         /* We set the bit if the host supports voltages between 2.7 and 3.6 V */
1505         cmd.cmdarg = ((mmc->cfg->voltages & 0xff8000) != 0) << 8 | 0xaa;
1506         cmd.resp_type = MMC_RSP_R7;
1507
1508         err = mmc_send_cmd(mmc, &cmd, NULL);
1509
1510         if (err)
1511                 return err;
1512
1513         if ((cmd.response[0] & 0xff) != 0xaa)
1514                 return UNUSABLE_ERR;
1515         else
1516                 mmc->version = SD_VERSION_2;
1517
1518         return 0;
1519 }
1520
1521 /* not used any more */
1522 int __deprecated mmc_register(struct mmc *mmc)
1523 {
1524 #if !defined(CONFIG_SPL_BUILD) || defined(CONFIG_SPL_LIBCOMMON_SUPPORT)
1525         printf("%s is deprecated! use mmc_create() instead.\n", __func__);
1526 #endif
1527         return -1;
1528 }
1529
1530 struct mmc *mmc_create(const struct mmc_config *cfg, void *priv)
1531 {
1532         struct mmc *mmc;
1533
1534         /* quick validation */
1535         if (cfg == NULL || cfg->ops == NULL || cfg->ops->send_cmd == NULL ||
1536                         cfg->f_min == 0 || cfg->f_max == 0 || cfg->b_max == 0)
1537                 return NULL;
1538
1539         mmc = calloc(1, sizeof(*mmc));
1540         if (mmc == NULL)
1541                 return NULL;
1542
1543         mmc->cfg = cfg;
1544         mmc->priv = priv;
1545
1546         /* the following chunk was mmc_register() */
1547
1548         /* Setup dsr related values */
1549         mmc->dsr_imp = 0;
1550         mmc->dsr = 0xffffffff;
1551         /* Setup the universal parts of the block interface just once */
1552         mmc->block_dev.if_type = IF_TYPE_MMC;
1553         mmc->block_dev.dev = cur_dev_num++;
1554         mmc->block_dev.removable = 1;
1555         mmc->block_dev.block_read = mmc_bread;
1556         mmc->block_dev.block_write = mmc_bwrite;
1557         mmc->block_dev.block_erase = mmc_berase;
1558
1559         /* setup initial part type */
1560         mmc->block_dev.part_type = mmc->cfg->part_type;
1561
1562         INIT_LIST_HEAD(&mmc->link);
1563
1564         list_add_tail(&mmc->link, &mmc_devices);
1565
1566         return mmc;
1567 }
1568
1569 void mmc_destroy(struct mmc *mmc)
1570 {
1571         /* only freeing memory for now */
1572         free(mmc);
1573 }
1574
1575 #ifdef CONFIG_PARTITIONS
1576 block_dev_desc_t *mmc_get_dev(int dev)
1577 {
1578         struct mmc *mmc = find_mmc_device(dev);
1579         if (!mmc || mmc_init(mmc))
1580                 return NULL;
1581
1582         return &mmc->block_dev;
1583 }
1584 #endif
1585
1586 /* board-specific MMC power initializations. */
1587 __weak void board_mmc_power_init(void)
1588 {
1589 }
1590
1591 int mmc_start_init(struct mmc *mmc)
1592 {
1593         int err;
1594
1595         /* we pretend there's no card when init is NULL */
1596         if (mmc_getcd(mmc) == 0 || mmc->cfg->ops->init == NULL) {
1597                 mmc->has_init = 0;
1598 #if !defined(CONFIG_SPL_BUILD) || defined(CONFIG_SPL_LIBCOMMON_SUPPORT)
1599                 printf("MMC: no card present\n");
1600 #endif
1601                 return NO_CARD_ERR;
1602         }
1603
1604         if (mmc->has_init)
1605                 return 0;
1606
1607 #ifdef CONFIG_FSL_ESDHC_ADAPTER_IDENT
1608         mmc_adapter_card_type_ident();
1609 #endif
1610         board_mmc_power_init();
1611
1612         /* made sure it's not NULL earlier */
1613         err = mmc->cfg->ops->init(mmc);
1614
1615         if (err)
1616                 return err;
1617
1618         mmc->ddr_mode = 0;
1619         mmc_set_bus_width(mmc, 1);
1620         mmc_set_clock(mmc, 1);
1621
1622         /* Reset the Card */
1623         err = mmc_go_idle(mmc);
1624
1625         if (err)
1626                 return err;
1627
1628         /* The internal partition reset to user partition(0) at every CMD0*/
1629         mmc->part_num = 0;
1630
1631         /* Test for SD version 2 */
1632         err = mmc_send_if_cond(mmc);
1633
1634         /* Now try to get the SD card's operating condition */
1635         err = sd_send_op_cond(mmc);
1636
1637         /* If the command timed out, we check for an MMC card */
1638         if (err == TIMEOUT) {
1639                 err = mmc_send_op_cond(mmc);
1640
1641                 if (err) {
1642 #if !defined(CONFIG_SPL_BUILD) || defined(CONFIG_SPL_LIBCOMMON_SUPPORT)
1643                         printf("Card did not respond to voltage select!\n");
1644 #endif
1645                         return UNUSABLE_ERR;
1646                 }
1647         }
1648
1649         if (!err)
1650                 mmc->init_in_progress = 1;
1651
1652         return err;
1653 }
1654
1655 static int mmc_complete_init(struct mmc *mmc)
1656 {
1657         int err = 0;
1658
1659         mmc->init_in_progress = 0;
1660         if (mmc->op_cond_pending)
1661                 err = mmc_complete_op_cond(mmc);
1662
1663         if (!err)
1664                 err = mmc_startup(mmc);
1665         if (err)
1666                 mmc->has_init = 0;
1667         else
1668                 mmc->has_init = 1;
1669         return err;
1670 }
1671
1672 int mmc_init(struct mmc *mmc)
1673 {
1674         int err = 0;
1675         unsigned start;
1676
1677         if (mmc->has_init)
1678                 return 0;
1679
1680         start = get_timer(0);
1681
1682         if (!mmc->init_in_progress)
1683                 err = mmc_start_init(mmc);
1684
1685         if (!err)
1686                 err = mmc_complete_init(mmc);
1687         debug("%s: %d, time %lu\n", __func__, err, get_timer(start));
1688         return err;
1689 }
1690
1691 int mmc_set_dsr(struct mmc *mmc, u16 val)
1692 {
1693         mmc->dsr = val;
1694         return 0;
1695 }
1696
1697 /* CPU-specific MMC initializations */
1698 __weak int cpu_mmc_init(bd_t *bis)
1699 {
1700         return -1;
1701 }
1702
1703 /* board-specific MMC initializations. */
1704 __weak int board_mmc_init(bd_t *bis)
1705 {
1706         return -1;
1707 }
1708
1709 #if !defined(CONFIG_SPL_BUILD) || defined(CONFIG_SPL_LIBCOMMON_SUPPORT)
1710
1711 void print_mmc_devices(char separator)
1712 {
1713         struct mmc *m;
1714         struct list_head *entry;
1715         char *mmc_type;
1716
1717         list_for_each(entry, &mmc_devices) {
1718                 m = list_entry(entry, struct mmc, link);
1719
1720                 if (m->has_init)
1721                         mmc_type = IS_SD(m) ? "SD" : "eMMC";
1722                 else
1723                         mmc_type = NULL;
1724
1725                 printf("%s: %d", m->cfg->name, m->block_dev.dev);
1726                 if (mmc_type)
1727                         printf(" (%s)", mmc_type);
1728
1729                 if (entry->next != &mmc_devices) {
1730                         printf("%c", separator);
1731                         if (separator != '\n')
1732                                 puts (" ");
1733                 }
1734         }
1735
1736         printf("\n");
1737 }
1738
1739 #else
1740 void print_mmc_devices(char separator) { }
1741 #endif
1742
1743 int get_mmc_num(void)
1744 {
1745         return cur_dev_num;
1746 }
1747
1748 void mmc_set_preinit(struct mmc *mmc, int preinit)
1749 {
1750         mmc->preinit = preinit;
1751 }
1752
1753 static void do_preinit(void)
1754 {
1755         struct mmc *m;
1756         struct list_head *entry;
1757
1758         list_for_each(entry, &mmc_devices) {
1759                 m = list_entry(entry, struct mmc, link);
1760
1761 #ifdef CONFIG_FSL_ESDHC_ADAPTER_IDENT
1762                 mmc_set_preinit(m, 1);
1763 #endif
1764                 if (m->preinit)
1765                         mmc_start_init(m);
1766         }
1767 }
1768
1769 #if defined(CONFIG_DM_MMC) && defined(CONFIG_SPL_BUILD)
1770 static int mmc_probe(bd_t *bis)
1771 {
1772         return 0;
1773 }
1774 #elif defined(CONFIG_DM_MMC)
1775 static int mmc_probe(bd_t *bis)
1776 {
1777         int ret;
1778         struct uclass *uc;
1779         struct udevice *m;
1780
1781         ret = uclass_get(UCLASS_MMC, &uc);
1782         if (ret)
1783                 return ret;
1784
1785         uclass_foreach_dev(m, uc) {
1786                 ret = device_probe(m);
1787                 if (ret)
1788                         printf("%s - probe failed: %d\n", m->name, ret);
1789         }
1790
1791         return 0;
1792 }
1793 #else
1794 static int mmc_probe(bd_t *bis)
1795 {
1796         if (board_mmc_init(bis) < 0)
1797                 cpu_mmc_init(bis);
1798
1799         return 0;
1800 }
1801 #endif
1802
1803 int mmc_initialize(bd_t *bis)
1804 {
1805         static int initialized = 0;
1806         int ret;
1807         if (initialized)        /* Avoid initializing mmc multiple times */
1808                 return 0;
1809         initialized = 1;
1810
1811         INIT_LIST_HEAD (&mmc_devices);
1812         cur_dev_num = 0;
1813
1814         ret = mmc_probe(bis);
1815         if (ret)
1816                 return ret;
1817
1818 #ifndef CONFIG_SPL_BUILD
1819         print_mmc_devices(',');
1820 #endif
1821
1822         do_preinit();
1823         return 0;
1824 }
1825
1826 #ifdef CONFIG_SUPPORT_EMMC_BOOT
1827 /*
1828  * This function changes the size of boot partition and the size of rpmb
1829  * partition present on EMMC devices.
1830  *
1831  * Input Parameters:
1832  * struct *mmc: pointer for the mmc device strcuture
1833  * bootsize: size of boot partition
1834  * rpmbsize: size of rpmb partition
1835  *
1836  * Returns 0 on success.
1837  */
1838
1839 int mmc_boot_partition_size_change(struct mmc *mmc, unsigned long bootsize,
1840                                 unsigned long rpmbsize)
1841 {
1842         int err;
1843         struct mmc_cmd cmd;
1844
1845         /* Only use this command for raw EMMC moviNAND. Enter backdoor mode */
1846         cmd.cmdidx = MMC_CMD_RES_MAN;
1847         cmd.resp_type = MMC_RSP_R1b;
1848         cmd.cmdarg = MMC_CMD62_ARG1;
1849
1850         err = mmc_send_cmd(mmc, &cmd, NULL);
1851         if (err) {
1852                 debug("mmc_boot_partition_size_change: Error1 = %d\n", err);
1853                 return err;
1854         }
1855
1856         /* Boot partition changing mode */
1857         cmd.cmdidx = MMC_CMD_RES_MAN;
1858         cmd.resp_type = MMC_RSP_R1b;
1859         cmd.cmdarg = MMC_CMD62_ARG2;
1860
1861         err = mmc_send_cmd(mmc, &cmd, NULL);
1862         if (err) {
1863                 debug("mmc_boot_partition_size_change: Error2 = %d\n", err);
1864                 return err;
1865         }
1866         /* boot partition size is multiple of 128KB */
1867         bootsize = (bootsize * 1024) / 128;
1868
1869         /* Arg: boot partition size */
1870         cmd.cmdidx = MMC_CMD_RES_MAN;
1871         cmd.resp_type = MMC_RSP_R1b;
1872         cmd.cmdarg = bootsize;
1873
1874         err = mmc_send_cmd(mmc, &cmd, NULL);
1875         if (err) {
1876                 debug("mmc_boot_partition_size_change: Error3 = %d\n", err);
1877                 return err;
1878         }
1879         /* RPMB partition size is multiple of 128KB */
1880         rpmbsize = (rpmbsize * 1024) / 128;
1881         /* Arg: RPMB partition size */
1882         cmd.cmdidx = MMC_CMD_RES_MAN;
1883         cmd.resp_type = MMC_RSP_R1b;
1884         cmd.cmdarg = rpmbsize;
1885
1886         err = mmc_send_cmd(mmc, &cmd, NULL);
1887         if (err) {
1888                 debug("mmc_boot_partition_size_change: Error4 = %d\n", err);
1889                 return err;
1890         }
1891         return 0;
1892 }
1893
1894 /*
1895  * Modify EXT_CSD[177] which is BOOT_BUS_WIDTH
1896  * based on the passed in values for BOOT_BUS_WIDTH, RESET_BOOT_BUS_WIDTH
1897  * and BOOT_MODE.
1898  *
1899  * Returns 0 on success.
1900  */
1901 int mmc_set_boot_bus_width(struct mmc *mmc, u8 width, u8 reset, u8 mode)
1902 {
1903         int err;
1904
1905         err = mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_BOOT_BUS_WIDTH,
1906                          EXT_CSD_BOOT_BUS_WIDTH_MODE(mode) |
1907                          EXT_CSD_BOOT_BUS_WIDTH_RESET(reset) |
1908                          EXT_CSD_BOOT_BUS_WIDTH_WIDTH(width));
1909
1910         if (err)
1911                 return err;
1912         return 0;
1913 }
1914
1915 /*
1916  * Modify EXT_CSD[179] which is PARTITION_CONFIG (formerly BOOT_CONFIG)
1917  * based on the passed in values for BOOT_ACK, BOOT_PARTITION_ENABLE and
1918  * PARTITION_ACCESS.
1919  *
1920  * Returns 0 on success.
1921  */
1922 int mmc_set_part_conf(struct mmc *mmc, u8 ack, u8 part_num, u8 access)
1923 {
1924         int err;
1925
1926         err = mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_PART_CONF,
1927                          EXT_CSD_BOOT_ACK(ack) |
1928                          EXT_CSD_BOOT_PART_NUM(part_num) |
1929                          EXT_CSD_PARTITION_ACCESS(access));
1930
1931         if (err)
1932                 return err;
1933         return 0;
1934 }
1935
1936 /*
1937  * Modify EXT_CSD[162] which is RST_n_FUNCTION based on the given value
1938  * for enable.  Note that this is a write-once field for non-zero values.
1939  *
1940  * Returns 0 on success.
1941  */
1942 int mmc_set_rst_n_function(struct mmc *mmc, u8 enable)
1943 {
1944         return mmc_switch(mmc, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_RST_N_FUNCTION,
1945                           enable);
1946 }
1947 #endif