xref: /netbsd-src/sys/arch/evbarm/stand/boot2440/dev_sdmmc.c (revision 6a493d6bc668897c91594964a732d38505b70cbb)
1 /*-
2  * Copyright (c) 2012 The NetBSD Foundation, Inc.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to The NetBSD Foundation
6  * by Paul Fleischer <paul@xpg.dk>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
18  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
21  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27  * POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 /*
31  * All SD/MMC code is taken from various files in sys/dev/sdmmc
32  */
33 /*
34  * Copyright (c) 2006 Uwe Stuehler <uwe@openbsd.org>
35  *
36  * Permission to use, copy, modify, and distribute this software for any
37  * purpose with or without fee is hereby granted, provided that the above
38  * copyright notice and this permission notice appear in all copies.
39  *
40  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
41  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
42  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
43  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
44  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
45  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
46  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
47  */
48 
49 /*-
50  * Copyright (c) 2007-2010 NONAKA Kimihiro <nonaka@netbsd.org>
51  * All rights reserved.
52  *
53  * Redistribution and use in source and binary forms, with or without
54  * modification, are permitted provided that the following conditions
55  * are met:
56  * 1. Redistributions of source code must retain the above copyright
57  *    notice, this list of conditions and the following disclaimer.
58  * 2. Redistributions in binary form must reproduce the above copyright
59  *    notice, this list of conditions and the following disclaimer in the
60  *    documentation and/or other materials provided with the distribution.
61  *
62  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
63  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
64  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
65  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
66  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
67  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
68  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
69  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
70  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
71  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
72  * SUCH DAMAGE.
73  */
74 
75 #include <machine/limits.h>
76 
77 #include <sys/param.h>
78 #include <sys/types.h>
79 #include <sys/disklabel.h>
80 
81 #include <netinet/in.h>
82 
83 #include <lib/libsa/stand.h>
84 
85 #include <lib/libkern/libkern.h>
86 #include <lib/libsa/stand.h>
87 #include <lib/libsa/iodesc.h>
88 
89 #include <dev/sdmmc/sdmmcreg.h>
90 #include "dev_sdmmc.h"
91 #include "s3csdi.h"
92 
93 #define SET(t, f)       ((t) |= (f))
94 #define ISSET(t, f)     ((t) & (f))
95 #define CLR(t, f)       ((t) &= ~(f))
96 
97 //#define SDMMC_DEBUG
98 #ifdef SDMMC_DEBUG
99 #define DPRINTF(s) do {printf s; } while (/*CONSTCOND*/0)
100 #else
101 #define DPRINTF(s) do {} while (/*CONSTCOND*/0)
102 #endif
103 
104 /* SD/MMC device driver structure */
105 struct sdifdv {
106 	char*			name;
107 	int			(*match)(unsigned);
108 	void*			(*init)(unsigned, uint32_t*);
109 	int			(*host_ocr)(void*);
110 	int			(*bus_clock)(void*, int);
111 	int			(*bus_power)(void*, int);
112 	int			(*bus_width)(void*, int);
113 	void			(*exec_cmd)(void*, struct sdmmc_command*);
114 	int			(*get_max_bus_clock)(void*);
115 	void*			priv;
116 };
117 
118 struct sdmmc_softc;
119 
120 /* Structure used for of->f_devdata */
121 struct sdmmc_part {
122 	struct sdmmc_softc	*sc;
123 	struct partition	*part;
124 };
125 
126 /* SD/MMC driver structure */
127 struct sdmmc_softc {
128 	uint32_t		flags;
129 	uint32_t		caps;
130 	uint16_t		rca;		/* relative card address */
131 	sdmmc_response		raw_cid;	/* temp. storage for decoding */
132 	uint32_t		raw_scr[2];
133 	struct sdmmc_csd	csd;		/* decoded CSD value */
134 	struct sdmmc_cid	cid;		/* decoded CID value */
135 	struct sdmmc_scr	scr;
136 	int			busclk;
137 	struct sdifdv		*sdifdv;
138 	struct disklabel	sc_label;
139 	int			npartitions;
140 	struct sdmmc_part	partitions[MAXPARTITIONS];
141 };
142 
143 static struct sdifdv vnifdv[] = {
144 	{"S3C SD/MMC", s3csd_match, s3csd_init, s3csd_host_ocr,
145 	 s3csd_bus_clock, s3csd_bus_power, s3csd_bus_width, s3csd_exec_cmd,
146 	 s3csd_get_max_bus_clock}
147 };
148 static int nnifdv = sizeof(vnifdv)/sizeof(vnifdv[0]);
149 
150 static struct sdmmc_softc sdmmc_softc;
151 static uint8_t sdmmc_initialized = FALSE;
152 
153 extern time_t getsecs();
154 extern time_t getusecs();
155 extern void usleep(int);
156 
157 /* Local functions */
158 static int sdmmc_getdisklabel(struct sdmmc_softc *sc);
159 static int sdmmc_init(unsigned int tag);
160 static int sdmmc_enable(struct sdmmc_softc*);
161 
162 static int sdmmc_mem_send_if_cond(struct sdmmc_softc*, uint32_t, uint32_t*);
163 static int sdmmc_mmc_command(struct sdmmc_softc*, struct sdmmc_command*);
164 static void sdmmc_go_idle_state(struct sdmmc_softc*);
165 static int sdmmc_mem_send_op_cond(struct sdmmc_softc*, uint32_t, uint32_t *);
166 static int sdmmc_set_bus_power(struct sdmmc_softc*, uint32_t, uint32_t);
167 static int sdmmc_app_command(struct sdmmc_softc*, uint16_t,
168 			     struct sdmmc_command*);
169 static int sdmmc_mmc_command(struct sdmmc_softc*, struct sdmmc_command*);
170 static int sdmmc_scan(struct sdmmc_softc*);
171 static void sdmmc_mem_scan(struct sdmmc_softc*);
172 static int sdmmc_set_relative_addr(struct sdmmc_softc*);
173 static int sdmmc_mem_send_cid(struct sdmmc_softc*, sdmmc_response*);
174 
175 static int sdmmc_mem_send_csd(struct sdmmc_softc*, sdmmc_response*);
176 static int sdmmc_decode_csd(struct sdmmc_softc*, sdmmc_response);
177 static int sdmmc_decode_cid(struct sdmmc_softc*, sdmmc_response);
178 
179 static int sdmmc_mem_read_block(struct sdmmc_softc*, uint32_t, u_char*, size_t);
180 static int sdmmc_select_card(struct sdmmc_softc*);
181 static int sdmmc_mem_set_blocklen(struct sdmmc_softc*);
182 
183 static int sdmmc_mem_send_scr(struct sdmmc_softc*, uint32_t[2]);
184 static int sdmmc_mem_decode_scr(struct sdmmc_softc*);
185 static int sdmmc_set_bus_width(struct sdmmc_softc*, int);
186 static int sdmmc_mem_sd_switch(struct sdmmc_softc *, int, int, int, void*);
187 
188 #ifdef SDMMC_DEBUG
189 static void sdmmc_dump_data(const char*, void*, size_t);
190 static void sdmmc_print_cid(struct sdmmc_cid*);
191 static void sdmmc_dump_command(struct sdmmc_softc*, struct sdmmc_command*);
192 #endif
193 
194 int
195 sdmmc_open(struct open_file *of, ...)
196 {
197 	va_list ap;
198 	int unit __unused, part;
199 
200 	va_start(ap, of);
201 	unit = va_arg(ap, u_int); /* Not used for now */
202 	part = va_arg(ap, u_int);
203 	va_end(ap);
204 
205 	/* Simply try to initialize SD mem sub system. */
206 	if( !sdmmc_init(0) ) {
207 		return 1;
208 	}
209 
210 	of->f_devdata = (void*)&sdmmc_softc.partitions[part];
211 
212 	return 0;
213 }
214 
215 int
216 sdmmc_close(struct open_file *f)
217 {
218 	return (0);
219 }
220 
221 int
222 sdmmc_get_fstype(void *p)  {
223 	struct sdmmc_part *part = (struct sdmmc_part*)p;
224 
225 	return part->part->p_fstype;
226 }
227 
228 
229 int
230 sdmmc_strategy(void *d, int f, daddr_t b, size_t s, void *buf, size_t *r)
231 {
232 	struct sdmmc_part *part = (struct sdmmc_part*)d;
233 	unsigned int offset;
234 	switch(f) {
235 	case F_READ:
236 		offset = part->part->p_offset + b;
237 		*r = s;
238 		if(sdmmc_mem_read_block(part->sc, offset, buf, s) == 0)
239 			return 0;
240 		else
241 			return EIO;
242 	default:
243 		printf("Unsupported operation\n");
244 		break;
245 	}
246 	return (EIO);
247 }
248 
249 int
250 sdmmc_getdisklabel(struct sdmmc_softc *sc)
251 {
252 	char *msg;
253 	int sector, i, n;
254 	size_t rsize;
255 	struct mbr_partition *dp, *bsdp;
256 	struct disklabel *lp;
257 	/*uint8_t *buf = wd->sc_buf;*/
258 	uint8_t buf[DEV_BSIZE];
259 
260 	lp = &sc->sc_label;
261 	memset(lp, 0, sizeof(struct disklabel));
262 
263 	sector = 0;
264 	if (sdmmc_strategy(&sc->partitions[0], F_READ, MBR_BBSECTOR, DEV_BSIZE,
265 			   buf, &rsize))
266 		return EOFFSET;
267 
268 	dp = (struct mbr_partition *)(buf + MBR_PART_OFFSET);
269 	bsdp = NULL;
270 	for (i = 0; i < MBR_PART_COUNT; i++, dp++) {
271 		if (dp->mbrp_type == MBR_PTYPE_NETBSD) {
272 			bsdp = dp;
273 			break;
274 		}
275 	}
276 	if (!bsdp) {
277 		/* generate fake disklabel */
278 		lp->d_secsize = DEV_BSIZE;
279 		/*lp->d_ntracks = wd->sc_params.atap_heads;
280 		lp->d_nsectors = wd->sc_params.atap_sectors;
281 		lp->d_ncylinders = wd->sc_params.atap_cylinders;*/
282 		lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
283 		lp->d_type = DTYPE_FLASH;
284 		/*strncpy(lp->d_typename, (char *)wd->sc_params.atap_model, 16);*/
285 		strncpy(lp->d_packname, "fictitious", 16);
286 		/*if (wd->sc_capacity > UINT32_MAX)
287 			lp->d_secperunit = UINT32_MAX;
288 		else
289 		lp->d_secperunit = wd->sc_capacity;*/
290 		lp->d_rpm = 3600;
291 		lp->d_interleave = 1;
292 		lp->d_flags = 0;
293 		lp->d_partitions[RAW_PART].p_offset = 0;
294 		lp->d_partitions[RAW_PART].p_size =
295 			lp->d_secperunit * (lp->d_secsize / DEV_BSIZE);
296 		lp->d_partitions[RAW_PART].p_fstype = FS_UNUSED;
297 		lp->d_magic = DISKMAGIC;
298 		lp->d_magic2 = DISKMAGIC;
299 		lp->d_checksum = dkcksum(lp);
300 
301 		dp = (struct mbr_partition *)(buf + MBR_PART_OFFSET);
302 		n = 'e' - 'a';
303 		for (i = 0; i < MBR_PART_COUNT; i++, dp++) {
304 			if (dp->mbrp_type == MBR_PTYPE_UNUSED)
305 				continue;
306 			lp->d_partitions[n].p_offset = bswap32(dp->mbrp_start);
307 			lp->d_partitions[n].p_size = bswap32(dp->mbrp_size);
308 			switch (dp->mbrp_type) {
309 			case MBR_PTYPE_FAT12:
310 			case MBR_PTYPE_FAT16S:
311 			case MBR_PTYPE_FAT16B:
312 			case MBR_PTYPE_FAT32:
313 			case MBR_PTYPE_FAT32L:
314 			case MBR_PTYPE_FAT16L:
315 				lp->d_partitions[n].p_fstype = FS_MSDOS;
316 				break;
317 			case MBR_PTYPE_LNXEXT2:
318 				lp->d_partitions[n].p_fstype = FS_EX2FS;
319 				break;
320 			default:
321 				lp->d_partitions[n].p_fstype = FS_OTHER;
322 				break;
323 			}
324 			n += 1;
325 		}
326 		lp->d_npartitions = n;
327 	}
328 	else {
329 		sector = bsdp->mbrp_start;
330 		if (sdmmc_strategy(&sc->partitions[0], F_READ,
331 				   sector + LABELSECTOR, DEV_BSIZE,
332 				   buf, &rsize))
333 			return EOFFSET;
334 		msg = getdisklabel((char *)buf + LABELOFFSET, &sc->sc_label);
335 		if (msg != NULL)
336 			printf("getdisklabel: %s\n", msg);
337 	}
338 	/*DPRINTF(("label info: d_secsize %d, d_nsectors %d, d_ncylinders %d,"
339 		 "d_ntracks %d, d_secpercyl %d\n",
340 		 wd->sc_label.d_secsize,
341 		 wd->sc_label.d_nsectors,
342 		 wd->sc_label.d_ncylinders,
343 		 wd->sc_label.d_ntracks,
344 		 wd->sc_label.d_secpercyl));*/
345 
346 	return 0;
347 }
348 
349 void
350 sdmmc_delay(int us) {
351 	usleep(us);
352 }
353 
354 /* Initialize the SD/MMC subsystem. Return 1 on success, and 0 on error.
355    In case of error, errno will be set to a sane value.
356  */
357 int
358 sdmmc_init(unsigned int tag)
359 {
360 	struct sdifdv *dv;
361 	int n;
362 	int error;
363 	struct sdmmc_softc *sc = &sdmmc_softc;
364 	char status[64];
365 
366 	if (sdmmc_initialized) {
367 		printf("SD/MMC already initialized\n");
368 		return 1;
369 	}
370 
371 	for (n = 0; n < nnifdv; n++) {
372 		dv = &vnifdv[n];
373 		if ((*dv->match)(tag) > 0)
374 			goto found;
375 	}
376 	errno = ENODEV;
377 	return 0;
378  found:
379 	sc->caps = 0;
380 	/* Init should return NULL if no card is present. */
381 	sc->sdifdv->priv = (*dv->init)(tag, &sc->caps);
382 	if (sc->sdifdv->priv == NULL) {
383 		/* We expect that the device initialization sets
384 		   errno properly */
385 		return 0;
386 	}
387 
388 	sc->flags = 0;
389 	sc->sdifdv = dv;
390 
391 	/* Perfom SD-card initialization. */
392 	if( sdmmc_enable(sc) ) {
393 		printf("Failed to enable SD interface\n");
394 		errno = EIO;
395 		return 0;
396 	}
397 	sc->busclk = sc->sdifdv->get_max_bus_clock(sc->sdifdv->priv);
398 
399 	if (sdmmc_scan(sc)) {
400 		printf("No functions\n");
401 		errno = EIO;
402 		return 0;
403 	}
404 
405 	if (sdmmc_select_card(sc)) {
406 		printf("Failed to select card\n");
407 		errno = EIO;
408 		return 0;
409 	}
410 
411 	if (!ISSET(sc->flags, SMF_CARD_SDHC)) {
412 		sdmmc_mem_set_blocklen(sc);
413 	}
414 
415 	/* change bus width if supported */
416 	if (ISSET(sc->flags, SMF_SD_MODE) ) {
417 		error = sdmmc_mem_send_scr(sc, sc->raw_scr);
418 		if (error) {
419 			DPRINTF(("SD_SEND_SCR send failed.\n"));
420 			errno = EIO;
421 			return 0;
422 		}
423 		error = sdmmc_mem_decode_scr(sc);
424 		if (error) {
425 			errno = EIO;
426 			return 0;
427 		}
428 
429 		if (ISSET(sc->caps, SMC_CAPS_4BIT_MODE) &&
430 		    ISSET(sc->scr.bus_width, SCR_SD_BUS_WIDTHS_4BIT)) {
431 			error = sdmmc_set_bus_width(sc, 4);
432 			if (error) {
433 				DPRINTF(("can't change bus width"
434 				    " (%d bit)\n", 4));
435 				errno = EIO;
436 				return 0;
437 			}
438 		}
439 
440 #if 1
441 		if (sc->scr.sd_spec >= SCR_SD_SPEC_VER_1_10 &&
442 		    ISSET(sc->csd.ccc, SD_CSD_CCC_SWITCH)) {
443 			DPRINTF(("switch func mode 0\n"));
444 			error = sdmmc_mem_sd_switch(sc, 0, 1, 0, status);
445 			if (error) {
446 				printf("switch func mode 0 failed\n");
447 				errno = error;
448 				return 0;
449 			}
450 		}
451 #endif
452 		sc->sdifdv->bus_clock(sc->sdifdv->priv, sc->busclk);
453 	}
454 
455 	/* Prepare dummy partition[0] entry used by sdmmc_getdisklabel() */
456 	sc->partitions[0].sc = sc;
457 	sc->partitions[0].part->p_offset = 0;
458 
459 	if(sdmmc_getdisklabel(sc)) {
460 		errno = EOFFSET;
461 		return 0;
462 	}
463 
464 	sc->npartitions = sc->sc_label.d_npartitions;
465 	for(n=0; n<sc->sc_label.d_npartitions; n++) {
466 		sc->partitions[n].part = &sc->sc_label.d_partitions[n];
467 		sc->partitions[n].sc = sc;
468 	}
469 
470 	sdmmc_initialized = TRUE;
471 
472 	return 1;
473 }
474 
475 int
476 sdmmc_enable(struct sdmmc_softc *sc)
477 {
478 	uint32_t card_ocr;
479 	uint32_t ocr = 0;
480 	uint32_t host_ocr;
481 	int error;
482 
483 	/* 1. Set the maximum power supported by bus */
484 	/* For now, we expect the init function to set the maximum
485 	   voltage. And if that is not supported by the SD-card we
486 	   just cannot work with it.
487 	 */
488 
489 	sc->busclk = 400;
490 	/* 2. Clock bus at minimum frequency */
491 	sc->sdifdv->bus_clock(sc->sdifdv->priv, 400);
492 
493 	/* We expect that the above call has performed any waiting needed.*/
494 
495 	/* Initialize SD/MMC memory card(s), which is the only thing
496 	   we support.
497 	 */
498 
499 	/* Set host mode to SD "combo" card or SD memory-only. */
500 	SET(sc->flags, SMF_SD_MODE|SMF_MEM_MODE);
501 
502 	sdmmc_go_idle_state(sc);
503 
504 	error = sdmmc_mem_send_if_cond(sc, 0x1aa, &card_ocr);
505 	if (error == 0 && card_ocr == 0x1aa)
506 		SET(ocr, MMC_OCR_HCS);
507 
508 	/*
509 	 * Read the SD/MMC memory OCR value by issuing CMD55 followed
510 	 * by ACMD41 to read the OCR value from memory-only SD cards.
511 	 * MMC cards will not respond to CMD55 or ACMD41 and this is
512 	 * how we distinguish them from SD cards.
513 	 */
514 mmc_mode:
515 	error = sdmmc_mem_send_op_cond(sc,
516 	  ISSET(sc->caps, SMC_CAPS_SPI_MODE) ? ocr : 0, &card_ocr);
517 	if (error) {
518 		if (ISSET(sc->flags, SMF_SD_MODE) &&
519 		    !ISSET(sc->flags, SMF_IO_MODE)) {
520 			/* Not a SD card, switch to MMC mode. */
521 			DPRINTF(("Switch to MMC mode\n"));
522 			CLR(sc->flags, SMF_SD_MODE);
523 			goto mmc_mode;
524 		}
525 		if (!ISSET(sc->flags, SMF_SD_MODE)) {
526 			DPRINTF(("couldn't read memory OCR\n"));
527 			goto out;
528 		} else {
529 			/* Not a "combo" card. */
530 			CLR(sc->flags, SMF_MEM_MODE);
531 			error = 0;
532 			goto out;
533 		}
534 	}
535 #if 0 /* SPI NOT SUPPORTED */
536 	if (ISSET(ssc->caps, SMC_CAPS_SPI_MODE)) {
537 		/* get card OCR */
538 		error = sdmmc_mem_spi_read_ocr(sc, ocr, &card_ocr);
539 		if (error) {
540 			DPRINTF(("%s: couldn't read SPI memory OCR\n",
541 			    SDMMCDEVNAME(sc)));
542 			goto out;
543 		}
544 	}
545 #endif
546 
547 	/* Set the lowest voltage supported by the card and host. */
548 	host_ocr = sc->sdifdv->host_ocr(sc->sdifdv->priv);
549 	error = sdmmc_set_bus_power(sc, host_ocr, card_ocr);
550 	if (error) {
551 		DPRINTF(("Couldn't supply voltage requested by card\n"));
552 		goto out;
553 	}
554 	host_ocr &= card_ocr;
555 	host_ocr |= ocr;
556 
557 	/* Send the new OCR value until all cards are ready. */
558 	error = sdmmc_mem_send_op_cond(sc, host_ocr, NULL);
559 	if (error) {
560 		DPRINTF(("Couldn't send memory OCR\n"));
561 		goto out;
562 	}
563 
564 out:
565 	return error;
566 }
567 
568 int
569 sdmmc_mem_send_if_cond(struct sdmmc_softc *sc, uint32_t ocr, uint32_t *ocrp)
570 {
571 	struct sdmmc_command cmd;
572 	int error;
573 
574 	memset(&cmd, 0, sizeof(cmd));
575 	cmd.c_arg = ocr;
576 	cmd.c_flags = SCF_CMD_BCR | SCF_RSP_R7 | SCF_RSP_SPI_R7;
577 	cmd.c_opcode = SD_SEND_IF_COND;
578 
579 	error = sdmmc_mmc_command(sc, &cmd);
580 	if (error == 0 && ocrp != NULL) {
581 		*ocrp = MMC_R7(cmd.c_resp);
582 	}
583 
584 	return error;
585 }
586 
587 void
588 sdmmc_go_idle_state(struct sdmmc_softc *sc)
589 {
590 	struct sdmmc_command cmd;
591 
592 	memset(&cmd, 0, sizeof(cmd));
593 	cmd.c_opcode = MMC_GO_IDLE_STATE;
594 	cmd.c_flags = SCF_CMD_BC | SCF_RSP_R0 | SCF_RSP_SPI_R1;
595 
596 	(void)sdmmc_mmc_command(sc, &cmd);
597 }
598 int
599 sdmmc_mem_send_op_cond(struct sdmmc_softc *sc, uint32_t ocr, uint32_t *ocrp)
600 {
601 	struct sdmmc_command cmd;
602 	int error;
603 	int retry;
604 
605 
606 	/*
607 	 * If we change the OCR value, retry the command until the OCR
608 	 * we receive in response has the "CARD BUSY" bit set, meaning
609 	 * that all cards are ready for identification.
610 	 */
611 	for (retry = 0; retry < 100; retry++) {
612 		memset(&cmd, 0, sizeof(cmd));
613 		cmd.c_arg = !ISSET(sc->caps, SMC_CAPS_SPI_MODE) ?
614 		    ocr : (ocr & MMC_OCR_HCS);
615 		cmd.c_flags = SCF_CMD_BCR | SCF_RSP_R3 | SCF_RSP_SPI_R1;
616 
617 		if (ISSET(sc->flags, SMF_SD_MODE)) {
618 			cmd.c_opcode = SD_APP_OP_COND;
619 			error = sdmmc_app_command(sc, 0, &cmd);
620 		} else {
621 			cmd.c_opcode = MMC_SEND_OP_COND;
622 			error = sdmmc_mmc_command(sc, &cmd);
623 		}
624 		if (error)
625 			break;
626 
627 		if (ISSET(sc->caps, SMC_CAPS_SPI_MODE)) {
628 			if (!ISSET(MMC_SPI_R1(cmd.c_resp), R1_SPI_IDLE))
629 				break;
630 		} else {
631 			if (ISSET(MMC_R3(cmd.c_resp), MMC_OCR_MEM_READY) ||
632 			    ocr == 0)
633 				break;
634 		}
635 
636 		error = ETIMEDOUT;
637 		sdmmc_delay(10000);
638 	}
639 	if (error == 0 &&
640 	    ocrp != NULL &&
641 	    !ISSET(sc->caps, SMC_CAPS_SPI_MODE))
642 		*ocrp = MMC_R3(cmd.c_resp);
643 	DPRINTF(("sdmmc_mem_send_op_cond: error=%d, ocr=%x\n",
644 		 error, MMC_R3(cmd.c_resp)));
645 	return error;
646 }
647 
648 /*
649  * Set the lowest bus voltage supported by the card and the host.
650  */
651 int
652 sdmmc_set_bus_power(struct sdmmc_softc *sc, uint32_t host_ocr,
653 		    uint32_t card_ocr)
654 {
655 	uint32_t bit;
656 
657 	/* Mask off unsupported voltage levels and select the lowest. */
658 	DPRINTF(("host_ocr=%x ", host_ocr));
659 	host_ocr &= card_ocr;
660 	for (bit = 4; bit < 23; bit++) {
661 		if (ISSET(host_ocr, (1 << bit))) {
662 			host_ocr &= (3 << bit);
663 			break;
664 		}
665 	}
666 	DPRINTF(("card_ocr=%x new_ocr=%x\n", card_ocr, host_ocr));
667 
668 	if (host_ocr == 0 ||
669 	    sc->sdifdv->bus_power(sc->sdifdv->priv, host_ocr) != 0)
670 		return 1;
671 	return 0;
672 }
673 
674 int
675 sdmmc_app_command(struct sdmmc_softc *sc, uint16_t rca,
676 		  struct sdmmc_command *cmd)
677 {
678 	struct sdmmc_command acmd;
679 	int error;
680 
681 	memset(&acmd, 0, sizeof(acmd));
682 	acmd.c_opcode = MMC_APP_CMD;
683 	if (rca != 0) {
684 		acmd.c_arg = rca << 16;
685 		acmd.c_flags = SCF_CMD_AC | SCF_RSP_R1 | SCF_RSP_SPI_R1;
686 	} else {
687 		acmd.c_arg = 0;
688 		acmd.c_flags = SCF_CMD_BCR | SCF_RSP_R1 | SCF_RSP_SPI_R1;
689 	}
690 
691 	error = sdmmc_mmc_command(sc, &acmd);
692 	if (error == 0) {
693 		if (!ISSET(sc->caps, SMC_CAPS_SPI_MODE) &&
694 		    !ISSET(MMC_R1(acmd.c_resp), MMC_R1_APP_CMD)) {
695 			/* Card does not support application commands. */
696 			error = ENODEV;
697 		} else {
698 			error = sdmmc_mmc_command(sc, cmd);
699 		}
700 	}
701 	DPRINTF(("sdmmc_app_command: done (error=%d)\n", error));
702 	return error;
703 }
704 
705 void
706 sdmmc_dump_command(struct sdmmc_softc *sc, struct sdmmc_command *cmd)
707 {
708 	int i;
709 
710 	printf("cmd %u arg=%x data=%p dlen=%d flags=%x (error %d)\n",
711 	    cmd->c_opcode, cmd->c_arg, cmd->c_data,
712 	    cmd->c_datalen, cmd->c_flags, cmd->c_error);
713 
714 	if (cmd->c_error )
715 		return;
716 
717 	printf("resp=");
718 	if (ISSET(cmd->c_flags, SCF_RSP_136))
719 		for (i = 0; i < sizeof cmd->c_resp; i++)
720 			printf("%02x ", ((uint8_t *)cmd->c_resp)[i]);
721 	else if (ISSET(cmd->c_flags, SCF_RSP_PRESENT))
722 		for (i = 0; i < 4; i++)
723 			printf("%02x ", ((uint8_t *)cmd->c_resp)[i]);
724 	else
725 		printf("none");
726 	printf("\n");
727 }
728 
729 int
730 sdmmc_mmc_command(struct sdmmc_softc *sc, struct sdmmc_command *cmd)
731 {
732 	int error;
733 
734 	DPRINTF(("sdmmc_mmc_command: cmd=%d, arg=%x, flags=%x\n",
735 		 cmd->c_opcode, cmd->c_arg, cmd->c_flags));
736 
737 #if 0
738 #if defined(DIAGNOSTIC) || defined(SDMMC_DEBUG)
739 	if (cmd->c_data && !ISSET(sc->caps, SMC_CAPS_SPI_MODE)) {
740 		if (sc->sc_card == NULL)
741 			panic("%s: deselected card\n", DEVNAME(sc));
742 	}
743 #endif
744 #endif
745 
746 	sc->sdifdv->exec_cmd(sc->sdifdv->priv, cmd);
747 
748 #ifdef SDMMC_DEBUG
749 
750 	sdmmc_dump_command(sc, cmd);
751 
752 #endif
753 
754 	error = cmd->c_error;
755 
756 	DPRINTF(("sdmmc_mmc_command: error=%d\n", error));
757 
758 	return error;
759 }
760 
761 /*
762  * Scan for I/O functions and memory cards on the bus, allocating a
763  * sdmmc_function structure for each.
764  */
765 int
766 sdmmc_scan(struct sdmmc_softc *sc)
767 {
768 
769 #if 0 /* SPI NOT SUPPORTED */
770 	if (!ISSET(sc->caps, SMC_CAPS_SPI_MODE)) {
771 		/* Scan for I/O functions. */
772 		if (ISSET(sc->sc_flags, SMF_IO_MODE))
773 			sdmmc_io_scan(sc);
774 	}
775 #endif
776 
777 	/* Scan for memory cards on the bus. */
778 	if (ISSET(sc->flags, SMF_MEM_MODE))
779 		sdmmc_mem_scan(sc);
780 
781 	DPRINTF(("Bus clock speed: %d\n", sc->busclk));
782 	return sc->sdifdv->bus_clock(sc->sdifdv->priv, sc->busclk);
783 }
784 
785 /*
786  * Read the CSD and CID from all cards and assign each card a unique
787  * relative card address (RCA).  CMD2 is ignored by SDIO-only cards.
788  */
789 void
790 sdmmc_mem_scan(struct sdmmc_softc *sc)
791 {
792 	sdmmc_response resp;
793 	//struct sdmmc_function *sf;
794 	//	uint16_t next_rca;
795 	int error;
796 	int retry;
797 
798 	/*
799 	 * CMD2 is a broadcast command understood by SD cards and MMC
800 	 * cards.  All cards begin to respond to the command, but back
801 	 * off if another card drives the CMD line to a different level.
802 	 * Only one card will get its entire response through.  That
803 	 * card remains silent once it has been assigned a RCA.
804 	 */
805 	for (retry = 0; retry < 100; retry++) {
806 		error = sdmmc_mem_send_cid(sc, &resp);
807 		if (error) {
808 			if (!ISSET(sc->caps, SMC_CAPS_SPI_MODE) &&
809 			    error == ETIMEDOUT) {
810 				/* No more cards there. */
811 				break;
812 			}
813 			DPRINTF(("Couldn't read CID\n"));
814 			break;
815 		}
816 
817 		/* In MMC mode, find the next available RCA. */
818 		/*next_rca = 1;
819 		if (!ISSET(dv->flags, SMF_SD_MODE)) {
820 			SIMPLEQ_FOREACH(sf, &sc->sf_head, sf_list)
821 				next_rca++;
822 				}*/
823 
824 		/* Allocate a sdmmc_function structure. */
825 		/*sf = sdmmc_function_alloc(sc);
826 		  sf->rca = next_rca;*/
827 
828 		/*
829 		 * Remember the CID returned in the CMD2 response for
830 		 * later decoding.
831 		 */
832 		memcpy(sc->raw_cid, resp, sizeof(sc->raw_cid));
833 
834 		/*
835 		 * Silence the card by assigning it a unique RCA, or
836 		 * querying it for its RCA in the case of SD.
837 		 */
838 		if (!ISSET(sc->caps, SMC_CAPS_SPI_MODE)) {
839 			if (sdmmc_set_relative_addr(sc) != 0) {
840 				DPRINTF(("couldn't set mem RCA\n"));
841 				break;
842 			}
843 		}
844 
845 		/*
846 		 * If this is a memory-only card, the card responding
847 		 * first becomes an alias for SDIO function 0.
848 		 */
849 		/*if (sc->sc_fn0 == NULL)
850 			sc->sc_fn0 = sf;
851 
852 			SIMPLEQ_INSERT_TAIL(&sc->sf_head, sf, sf_list);*/
853 
854 		/* only one function in SPI mode */
855 		/*if (ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE))
856 		  break;*/
857 	}
858 
859 	/*
860 	 * All cards are either inactive or awaiting further commands.
861 	 * Read the CSDs and decode the raw CID for each card.
862 	 */
863 	/*	SIMPLEQ_FOREACH(sf, &sc->sf_head, sf_list) {*/
864 	error = sdmmc_mem_send_csd(sc, &resp);
865 	if (error) {
866 		/*SET(sf->flags, SFF_ERROR);
867 		  continue;*/
868 	}
869 
870 	if (sdmmc_decode_csd(sc, resp) != 0 ||
871 	    sdmmc_decode_cid(sc, sc->raw_cid) != 0) {
872 		/*SET(sf->flags, SFF_ERROR);
873 		  continue;*/
874 	}
875 
876 #ifdef SDMMC_DEBUG
877 	printf("CID: ");
878 	sdmmc_print_cid(&sc->cid);
879 #endif
880 		/*	}*/
881 }
882 
883 /*
884  * Retrieve (SD) or set (MMC) the relative card address (RCA).
885  */
886 int
887 sdmmc_set_relative_addr(struct sdmmc_softc *sc)
888 {
889 	struct sdmmc_command cmd;
890 	int error;
891 
892 	/* Don't lock */
893 
894 	if (ISSET(sc->caps, SMC_CAPS_SPI_MODE))
895 		return EIO;
896 
897 	memset(&cmd, 0, sizeof(cmd));
898 	if (ISSET(sc->flags, SMF_SD_MODE)) {
899 		cmd.c_opcode = SD_SEND_RELATIVE_ADDR;
900 		cmd.c_flags = SCF_CMD_BCR | SCF_RSP_R6;
901 	} else {
902 		cmd.c_opcode = MMC_SET_RELATIVE_ADDR;
903 		cmd.c_arg = MMC_ARG_RCA(sc->rca);
904 		cmd.c_flags = SCF_CMD_AC | SCF_RSP_R1;
905 	}
906 	error = sdmmc_mmc_command(sc, &cmd);
907 	if (error)
908 		return error;
909 
910 	if (ISSET(sc->flags, SMF_SD_MODE))
911 		sc->rca = SD_R6_RCA(cmd.c_resp);
912 
913 	return 0;
914 }
915 
916 int
917 sdmmc_mem_send_cid(struct sdmmc_softc *sc, sdmmc_response *resp)
918 {
919 	struct sdmmc_command cmd;
920 	int error;
921 
922 
923 	memset(&cmd, 0, sizeof cmd);
924 	cmd.c_opcode = MMC_ALL_SEND_CID;
925 	cmd.c_flags = SCF_CMD_BCR | SCF_RSP_R2;
926 
927 	error = sdmmc_mmc_command(sc, &cmd);
928 
929 #ifdef SDMMC_DEBUG
930 	sdmmc_dump_data("CID", cmd.c_resp, sizeof(cmd.c_resp));
931 #endif
932 	if (error == 0 && resp != NULL)
933 		memcpy(resp, &cmd.c_resp, sizeof(*resp));
934 	return error;
935 }
936 
937 void
938 sdmmc_dump_data(const char *title, void *ptr, size_t size)
939 {
940 	char buf[16];
941 	uint8_t *p = ptr;
942 	int i, j;
943 
944 	printf("sdmmc_dump_data: %s\n", title ? title : "");
945 	printf("--------+--------------------------------------------------+------------------+\n");
946 	printf("offset  | +0 +1 +2 +3 +4 +5 +6 +7  +8 +9 +a +b +c +d +e +f | data             |\n");
947 	printf("--------+--------------------------------------------------+------------------+\n");
948 	for (i = 0; i < (int)size; i++) {
949 		if ((i % 16) == 0) {
950 			printf("%08x| ", i);
951 		} else if ((i % 16) == 8) {
952 			printf(" ");
953 		}
954 
955 		printf("%02x ", p[i]);
956 		buf[i % 16] = p[i];
957 
958 		if ((i % 16) == 15) {
959 			printf("| ");
960 			for (j = 0; j < 16; j++) {
961 				if (buf[j] >= 0x20 && buf[j] <= 0x7e) {
962 					printf("%c", buf[j]);
963 				} else {
964 					printf(".");
965 				}
966 			}
967 			printf(" |\n");
968 		}
969 	}
970 	if ((i % 16) != 0) {
971 		j = (i % 16);
972 		for (; j < 16; j++) {
973 			printf("   ");
974 			if ((j % 16) == 8) {
975 				printf(" ");
976 			}
977 		}
978 
979 		printf("| ");
980 		for (j = 0; j < (i % 16); j++) {
981 			if (buf[j] >= 0x20 && buf[j] <= 0x7e) {
982 				printf("%c", buf[j]);
983 			} else {
984 				printf(".");
985 			}
986 		}
987 		for (; j < 16; j++) {
988 			printf(" ");
989 		}
990 		printf(" |\n");
991 	}
992 	printf("--------+--------------------------------------------------+------------------+\n");
993 }
994 
995 int
996 sdmmc_mem_send_csd(struct sdmmc_softc *sc, sdmmc_response *resp)
997 {
998 	struct sdmmc_command cmd;
999 	int error;
1000 
1001 	memset(&cmd, 0, sizeof cmd);
1002 	cmd.c_opcode = MMC_SEND_CSD;
1003 	cmd.c_arg = MMC_ARG_RCA(sc->rca);
1004 	cmd.c_flags = SCF_CMD_AC | SCF_RSP_R2;
1005 
1006 	error = sdmmc_mmc_command(sc, &cmd);
1007 
1008 #ifdef SDMMC_DEBUG
1009 	sdmmc_dump_data("CSD", cmd.c_resp, sizeof(cmd.c_resp));
1010 #endif
1011 	if (error == 0 && resp != NULL)
1012 		memcpy(resp, &cmd.c_resp, sizeof(*resp));
1013 	return error;
1014 }
1015 
1016 int
1017 sdmmc_decode_csd(struct sdmmc_softc *sc, sdmmc_response resp)
1018 {
1019 	/* TRAN_SPEED(2:0): transfer rate exponent */
1020 	static const int speed_exponent[8] = {
1021 		100 *    1,	/* 100 Kbits/s */
1022 		  1 * 1000,	/*   1 Mbits/s */
1023 		 10 * 1000,	/*  10 Mbits/s */
1024 		100 * 1000,	/* 100 Mbits/s */
1025 			 0,
1026 			 0,
1027 			 0,
1028 			 0,
1029 	};
1030 	/* TRAN_SPEED(6:3): time mantissa */
1031 	static const int speed_mantissa[16] = {
1032 		0, 10, 12, 13, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 70, 80,
1033 	};
1034 	struct sdmmc_csd *csd = &sc->csd;
1035 	int e, m;
1036 
1037 	if (ISSET(sc->flags, SMF_SD_MODE)) {
1038 		/*
1039 		 * CSD version 1.0 corresponds to SD system
1040 		 * specification version 1.0 - 1.10. (SanDisk, 3.5.3)
1041 		 */
1042 		csd->csdver = SD_CSD_CSDVER(resp);
1043 		switch (csd->csdver) {
1044 		case SD_CSD_CSDVER_2_0:
1045 			DPRINTF(("SD Ver.2.0\n"));
1046 			SET(sc->flags, SMF_CARD_SDHC);
1047 			csd->capacity = SD_CSD_V2_CAPACITY(resp);
1048 			csd->read_bl_len = SD_CSD_V2_BL_LEN;
1049                         csd->ccc = SD_CSD_CCC(resp);
1050 			break;
1051 
1052 		case SD_CSD_CSDVER_1_0:
1053 			DPRINTF(("SD Ver.1.0\n"));
1054 			csd->capacity = SD_CSD_CAPACITY(resp);
1055 			csd->read_bl_len = SD_CSD_READ_BL_LEN(resp);
1056 			break;
1057 
1058 		default:
1059 			printf("unknown SD CSD structure version 0x%x\n",
1060 			    csd->csdver);
1061 			return 1;
1062 		}
1063 
1064 		csd->mmcver = SD_CSD_MMCVER(resp);
1065 		csd->write_bl_len = SD_CSD_WRITE_BL_LEN(resp);
1066 		csd->r2w_factor = SD_CSD_R2W_FACTOR(resp);
1067 		e = SD_CSD_SPEED_EXP(resp);
1068 		m = SD_CSD_SPEED_MANT(resp);
1069 		csd->tran_speed = speed_exponent[e] * speed_mantissa[m] / 10;
1070 	} else {
1071 		csd->csdver = MMC_CSD_CSDVER(resp);
1072 		if (csd->csdver == MMC_CSD_CSDVER_1_0 ) {
1073 			printf("unknown MMC CSD structure version 0x%x\n",
1074 			    csd->csdver);
1075 			return 1;
1076 		}
1077 
1078 		csd->mmcver = MMC_CSD_MMCVER(resp);
1079 		csd->capacity = MMC_CSD_CAPACITY(resp);
1080 		csd->read_bl_len = MMC_CSD_READ_BL_LEN(resp);
1081 		csd->write_bl_len = MMC_CSD_WRITE_BL_LEN(resp);
1082 		csd->r2w_factor = MMC_CSD_R2W_FACTOR(resp);
1083 		e = MMC_CSD_TRAN_SPEED_EXP(resp);
1084 		m = MMC_CSD_TRAN_SPEED_MANT(resp);
1085 		csd->tran_speed = speed_exponent[e] * speed_mantissa[m] / 10;
1086 	}
1087 	if ((1 << csd->read_bl_len) > SDMMC_SECTOR_SIZE)
1088 		csd->capacity *= (1 << csd->read_bl_len) / SDMMC_SECTOR_SIZE;
1089 
1090 
1091 	if (sc->busclk > csd->tran_speed)
1092 		sc->busclk = csd->tran_speed;
1093 
1094 #ifdef SDMMC_DUMP_CSD
1095 	sdmmc_print_csd(resp, csd);
1096 #endif
1097 
1098 	return 0;
1099 }
1100 
1101 int
1102 sdmmc_decode_cid(struct sdmmc_softc *sc, sdmmc_response resp)
1103 {
1104 	struct sdmmc_cid *cid = &sc->cid;
1105 
1106 	if (ISSET(sc->flags, SMF_SD_MODE)) {
1107 		cid->mid = SD_CID_MID(resp);
1108 		cid->oid = SD_CID_OID(resp);
1109 		SD_CID_PNM_CPY(resp, cid->pnm);
1110 		cid->rev = SD_CID_REV(resp);
1111 		cid->psn = SD_CID_PSN(resp);
1112 		cid->mdt = SD_CID_MDT(resp);
1113 	} else {
1114 		switch(sc->csd.mmcver) {
1115 		case MMC_CSD_MMCVER_1_0:
1116 		case MMC_CSD_MMCVER_1_4:
1117 			cid->mid = MMC_CID_MID_V1(resp);
1118 			MMC_CID_PNM_V1_CPY(resp, cid->pnm);
1119 			cid->rev = MMC_CID_REV_V1(resp);
1120 			cid->psn = MMC_CID_PSN_V1(resp);
1121 			cid->mdt = MMC_CID_MDT_V1(resp);
1122 			break;
1123 		case MMC_CSD_MMCVER_2_0:
1124 		case MMC_CSD_MMCVER_3_1:
1125 		case MMC_CSD_MMCVER_4_0:
1126 			cid->mid = MMC_CID_MID_V2(resp);
1127 			cid->oid = MMC_CID_OID_V2(resp);
1128 			MMC_CID_PNM_V2_CPY(resp, cid->pnm);
1129 			cid->psn = MMC_CID_PSN_V2(resp);
1130 			break;
1131 		default:
1132 			printf("unknown MMC version %d\n",
1133 			    sc->csd.mmcver);
1134 			return 1;
1135 		}
1136 	}
1137 	return 0;
1138 }
1139 
1140 void
1141 sdmmc_print_cid(struct sdmmc_cid *cid)
1142 {
1143 
1144 	printf("mid=0x%02x oid=0x%04x pnm=\"%s\" rev=0x%02x psn=0x%08x"
1145 	    " mdt=%03x\n", cid->mid, cid->oid, cid->pnm, cid->rev, cid->psn,
1146 	    cid->mdt);
1147 }
1148 
1149 int
1150 sdmmc_mem_read_block(struct sdmmc_softc *sc, uint32_t blkno,
1151     u_char *data, size_t datalen)
1152 {
1153 	struct sdmmc_command cmd;
1154 	int error;
1155 
1156 	memset(&cmd, 0, sizeof(cmd));
1157 	cmd.c_data = data;
1158 	cmd.c_datalen = datalen;
1159 	cmd.c_blklen = SDMMC_SECTOR_SIZE;
1160 	cmd.c_opcode = (cmd.c_datalen / cmd.c_blklen) > 1 ?
1161 	    MMC_READ_BLOCK_MULTIPLE : MMC_READ_BLOCK_SINGLE;
1162 	cmd.c_arg = blkno;
1163 	if (!ISSET(sc->flags, SMF_CARD_SDHC))
1164 	  cmd.c_arg <<= SDMMC_SECTOR_SIZE_SB;
1165 	DPRINTF(("Reading block %d (%d)\n", blkno, cmd.c_arg));
1166 	cmd.c_flags = SCF_CMD_ADTC | SCF_CMD_READ | SCF_RSP_R1 | SCF_RSP_SPI_R1;
1167 
1168 	error = sdmmc_mmc_command(sc, &cmd);
1169 	if (error)
1170 		goto out;
1171 
1172 	if (!ISSET(sc->caps, SMC_CAPS_AUTO_STOP)) {
1173 		if (cmd.c_opcode == MMC_READ_BLOCK_MULTIPLE) {
1174 			memset(&cmd, 0, sizeof cmd);
1175 			cmd.c_opcode = MMC_STOP_TRANSMISSION;
1176 			cmd.c_arg = MMC_ARG_RCA(sc->rca);
1177 			cmd.c_flags = SCF_CMD_AC | SCF_RSP_R1B | SCF_RSP_SPI_R1B;
1178 			error = sdmmc_mmc_command(sc, &cmd);
1179 			if (error)
1180 				goto out;
1181 		}
1182 	}
1183 
1184 	/*if (!ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE)) {*/
1185 	do {
1186 		memset(&cmd, 0, sizeof(cmd));
1187 		cmd.c_opcode = MMC_SEND_STATUS;
1188 		cmd.c_arg = MMC_ARG_RCA(sc->rca);
1189 		cmd.c_flags = SCF_CMD_AC | SCF_RSP_R1 | SCF_RSP_SPI_R2;
1190 		error = sdmmc_mmc_command(sc, &cmd);
1191 		if (error)
1192 			break;
1193 		/* XXX time out */
1194 	} while (!ISSET(MMC_R1(cmd.c_resp), MMC_R1_READY_FOR_DATA));
1195 		/*}*/
1196 
1197 out:
1198 	return error;
1199 }
1200 
1201 int
1202 sdmmc_select_card(struct sdmmc_softc *sc)
1203 {
1204 	struct sdmmc_command cmd;
1205 	int error;
1206 
1207 	/* Don't lock */
1208 
1209 	/*	if (ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE))
1210 		return EIO;*/
1211 
1212 	/*if (sc->sc_card == sf
1213 	 || (sf && sc->sc_card && sc->sc_card->rca == sf->rca)) {
1214 		sc->sc_card = sf;
1215 		return 0;
1216 		}*/
1217 
1218 	memset(&cmd, 0, sizeof(cmd));
1219 	cmd.c_opcode = MMC_SELECT_CARD;
1220 	cmd.c_arg = (sc == NULL) ? 0 : MMC_ARG_RCA(sc->rca);
1221 	cmd.c_flags = SCF_CMD_AC | ((sc == NULL) ? SCF_RSP_R0 : SCF_RSP_R1);
1222 	error = sdmmc_mmc_command(sc, &cmd);
1223 	/*if (error == 0 || sf == NULL)
1224 	  sc->sc_card = sf;*/
1225 
1226 	return error;
1227 }
1228 
1229 /*
1230  * Set the read block length appropriately for this card, according to
1231  * the card CSD register value.
1232  */
1233 int
1234 sdmmc_mem_set_blocklen(struct sdmmc_softc *sc)
1235 {
1236 	struct sdmmc_command cmd;
1237 	int error;
1238 
1239 	/* Don't lock */
1240 
1241 	memset(&cmd, 0, sizeof(cmd));
1242 	cmd.c_opcode = MMC_SET_BLOCKLEN;
1243 	cmd.c_arg = SDMMC_SECTOR_SIZE;
1244 	cmd.c_flags = SCF_CMD_AC | SCF_RSP_R1 | SCF_RSP_SPI_R1;
1245 
1246 	error = sdmmc_mmc_command(sc, &cmd);
1247 
1248 	DPRINTF(("sdmmc_mem_set_blocklen: read_bl_len=%d sector_size=%d\n",
1249 		 1 << sc->csd.read_bl_len, SDMMC_SECTOR_SIZE));
1250 
1251 	return error;
1252 }
1253 
1254 int
1255 sdmmc_mem_send_scr(struct sdmmc_softc *sc, uint32_t scr[2])
1256 {
1257 	struct sdmmc_command cmd;
1258 	void *ptr = NULL;
1259 	int datalen = 8;
1260 	int error = 0;
1261 
1262 	ptr = alloc(datalen); //malloc(datalen, M_DEVBUF, M_NOWAIT | M_ZERO);
1263 	if (ptr == NULL)
1264 		goto out;
1265 
1266 	memset(&cmd, 0, sizeof(cmd));
1267 	cmd.c_data = ptr;
1268 	cmd.c_datalen = datalen;
1269 	cmd.c_blklen = datalen;
1270 	cmd.c_arg = 0;
1271 	cmd.c_flags = SCF_CMD_ADTC | SCF_CMD_READ | SCF_RSP_R1 | SCF_RSP_SPI_R1;
1272 	cmd.c_opcode = SD_APP_SEND_SCR;
1273 
1274 	error = sdmmc_app_command(sc, sc->rca, &cmd);
1275 	if (error == 0) {
1276 		memcpy(scr, ptr, datalen);
1277 	}
1278 
1279 out:
1280 	if (ptr != NULL) {
1281 		dealloc(ptr, datalen);
1282 	}
1283 	DPRINTF(("sdmem_mem_send_scr: error = %d\n",
1284 	    error));
1285 	if (error)
1286 		return error;
1287 #ifdef SDMMC_DEBUG
1288 	sdmmc_dump_data("SCR", scr, 8);
1289 #endif
1290 	return error;
1291 }
1292 
1293 int
1294 sdmmc_mem_decode_scr(struct sdmmc_softc *sc)
1295 {
1296 	sdmmc_response resp;
1297 	int ver;
1298 
1299 	memset(resp, 0, sizeof(resp));
1300 	/*resp[0] = sc->raw_scr[1];
1301 	resp[1] = sc->raw_scr[0];*/
1302 	/*
1303 	 * Change the raw-scr received from the DMA stream to resp.
1304 	 */
1305 	resp[0] = be32toh(sc->raw_scr[1]) >> 8;		// LSW
1306 	resp[1] = be32toh(sc->raw_scr[0]);		// MSW
1307 	resp[0] |= (resp[1] & 0xff) << 24;
1308 	resp[1] >>= 8;
1309 	resp[0] = htole32(resp[0]);
1310 	resp[1] = htole32(resp[1]);
1311 
1312 	ver = SCR_STRUCTURE(resp);
1313 	sc->scr.sd_spec = SCR_SD_SPEC(resp);
1314 	sc->scr.bus_width = SCR_SD_BUS_WIDTHS(resp);
1315 
1316 	DPRINTF(("sdmmc_mem_decode_scr: spec=%d, bus width=%d\n",
1317 	    sc->scr.sd_spec, sc->scr.bus_width));
1318 
1319 	if (ver != 0) {
1320 		DPRINTF(("unknown structure version: %d\n",
1321 		    ver));
1322 		return EINVAL;
1323 	}
1324 	return 0;
1325 }
1326 
1327 int
1328 sdmmc_set_bus_width(struct sdmmc_softc *sc, int width)
1329 {
1330 	struct sdmmc_command cmd;
1331 	int error;
1332 
1333 	if (ISSET(sc->caps, SMC_CAPS_SPI_MODE))
1334 		return ENODEV;
1335 
1336 	memset(&cmd, 0, sizeof(cmd));
1337 	cmd.c_opcode = SD_APP_SET_BUS_WIDTH;
1338 	cmd.c_flags = SCF_RSP_R1 | SCF_CMD_AC;
1339 
1340 	switch (width) {
1341 	case 1:
1342 		cmd.c_arg = SD_ARG_BUS_WIDTH_1;
1343 		break;
1344 
1345 	case 4:
1346 		cmd.c_arg = SD_ARG_BUS_WIDTH_4;
1347 		break;
1348 
1349 	default:
1350 		return EINVAL;
1351 	}
1352 
1353 	error = sdmmc_app_command(sc, sc->rca, &cmd);
1354 	if (error == 0)
1355 		error = sc->sdifdv->bus_width(sc->sdifdv->priv, width);
1356 	return error;
1357 }
1358 
1359 #if 1
1360 static int
1361 sdmmc_mem_sd_switch(struct sdmmc_softc *sc, int mode, int group,
1362     int function, void *status)
1363 {
1364 	struct sdmmc_command cmd;
1365 	void *ptr = NULL;
1366 	int gsft, error = 0;
1367 	const int statlen = 64;
1368 
1369 	if (sc->scr.sd_spec >= SCR_SD_SPEC_VER_1_10 &&
1370 	    !ISSET(sc->csd.ccc, SD_CSD_CCC_SWITCH))
1371 		return EINVAL;
1372 
1373 	if (group <= 0 || group > 6 ||
1374 	    function < 0 || function > 16)
1375 		return EINVAL;
1376 
1377 	gsft = (group - 1) << 2;
1378 
1379 	ptr = alloc(statlen);
1380 	if (ptr == NULL)
1381 		goto out;
1382 
1383 	memset(&cmd, 0, sizeof(cmd));
1384 	cmd.c_data = ptr;
1385 	cmd.c_datalen = statlen;
1386 	cmd.c_blklen = statlen;
1387 	cmd.c_opcode = SD_SEND_SWITCH_FUNC;
1388 	cmd.c_arg =
1389 	    (!!mode << 31) | (function << gsft) | (0x00ffffff & ~(0xf << gsft));
1390 	cmd.c_flags = SCF_CMD_ADTC | SCF_CMD_READ | SCF_RSP_R1 | SCF_RSP_SPI_R1;
1391 
1392 	error = sdmmc_mmc_command(sc, &cmd);
1393 	if (error == 0) {
1394 		memcpy(status, ptr, statlen);
1395 	}
1396 
1397 out:
1398 	if (ptr != NULL) {
1399 		dealloc(ptr, statlen);
1400 	}
1401 	return error;
1402 }
1403 #endif
1404