xref: /netbsd-src/sys/dev/sdmmc/sdmmc_mem.c (revision b7b7574d3bf8eeb51a1fa3977b59142ec6434a55)
1 /*	$NetBSD: sdmmc_mem.c,v 1.31 2014/03/19 15:26:42 nonaka Exp $	*/
2 /*	$OpenBSD: sdmmc_mem.c,v 1.10 2009/01/09 10:55:22 jsg Exp $	*/
3 
4 /*
5  * Copyright (c) 2006 Uwe Stuehler <uwe@openbsd.org>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 /*-
21  * Copyright (C) 2007, 2008, 2009, 2010 NONAKA Kimihiro <nonaka@netbsd.org>
22  * All rights reserved.
23  *
24  * Redistribution and use in source and binary forms, with or without
25  * modification, are permitted provided that the following conditions
26  * are met:
27  * 1. Redistributions of source code must retain the above copyright
28  *    notice, this list of conditions and the following disclaimer.
29  * 2. Redistributions in binary form must reproduce the above copyright
30  *    notice, this list of conditions and the following disclaimer in the
31  *    documentation and/or other materials provided with the distribution.
32  *
33  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
34  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
35  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
36  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
37  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
38  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
39  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
40  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
41  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
42  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43  */
44 
45 /* Routines for SD/MMC memory cards. */
46 
47 #include <sys/cdefs.h>
48 __KERNEL_RCSID(0, "$NetBSD: sdmmc_mem.c,v 1.31 2014/03/19 15:26:42 nonaka Exp $");
49 
50 #ifdef _KERNEL_OPT
51 #include "opt_sdmmc.h"
52 #endif
53 
54 #include <sys/param.h>
55 #include <sys/kernel.h>
56 #include <sys/malloc.h>
57 #include <sys/systm.h>
58 #include <sys/device.h>
59 
60 #include <dev/sdmmc/sdmmcchip.h>
61 #include <dev/sdmmc/sdmmcreg.h>
62 #include <dev/sdmmc/sdmmcvar.h>
63 
64 #ifdef SDMMC_DEBUG
65 #define DPRINTF(s)	do { printf s; } while (/*CONSTCOND*/0)
66 #else
67 #define DPRINTF(s)	do {} while (/*CONSTCOND*/0)
68 #endif
69 
70 typedef struct { uint32_t _bits[512/32]; } __packed __aligned(4) sdmmc_bitfield512_t;
71 
72 static int sdmmc_mem_sd_init(struct sdmmc_softc *, struct sdmmc_function *);
73 static int sdmmc_mem_mmc_init(struct sdmmc_softc *, struct sdmmc_function *);
74 static int sdmmc_mem_send_cid(struct sdmmc_softc *, sdmmc_response *);
75 static int sdmmc_mem_send_csd(struct sdmmc_softc *, struct sdmmc_function *,
76     sdmmc_response *);
77 static int sdmmc_mem_send_scr(struct sdmmc_softc *, struct sdmmc_function *,
78     uint32_t *scr);
79 static int sdmmc_mem_decode_scr(struct sdmmc_softc *, struct sdmmc_function *);
80 static int sdmmc_mem_send_cxd_data(struct sdmmc_softc *, int, void *, size_t);
81 static int sdmmc_set_bus_width(struct sdmmc_function *, int);
82 static int sdmmc_mem_sd_switch(struct sdmmc_function *, int, int, int, sdmmc_bitfield512_t *);
83 static int sdmmc_mem_mmc_switch(struct sdmmc_function *, uint8_t, uint8_t,
84     uint8_t);
85 static int sdmmc_mem_spi_read_ocr(struct sdmmc_softc *, uint32_t, uint32_t *);
86 static int sdmmc_mem_single_read_block(struct sdmmc_function *, uint32_t,
87     u_char *, size_t);
88 static int sdmmc_mem_single_write_block(struct sdmmc_function *, uint32_t,
89     u_char *, size_t);
90 static int sdmmc_mem_read_block_subr(struct sdmmc_function *, uint32_t,
91     u_char *, size_t);
92 static int sdmmc_mem_write_block_subr(struct sdmmc_function *, uint32_t,
93     u_char *, size_t);
94 
95 /*
96  * Initialize SD/MMC memory cards and memory in SDIO "combo" cards.
97  */
98 int
99 sdmmc_mem_enable(struct sdmmc_softc *sc)
100 {
101 	uint32_t host_ocr;
102 	uint32_t card_ocr;
103 	uint32_t ocr = 0;
104 	int error;
105 
106 	SDMMC_LOCK(sc);
107 
108 	/* Set host mode to SD "combo" card or SD memory-only. */
109 	SET(sc->sc_flags, SMF_SD_MODE|SMF_MEM_MODE);
110 
111 	if (ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE))
112 		sdmmc_spi_chip_initialize(sc->sc_spi_sct, sc->sc_sch);
113 
114 	/* Reset memory (*must* do that before CMD55 or CMD1). */
115 	sdmmc_go_idle_state(sc);
116 
117 	if (ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE)) {
118 		/* Check SD Ver.2 */
119 		error = sdmmc_mem_send_if_cond(sc, 0x1aa, &card_ocr);
120 		if (error == 0 && card_ocr == 0x1aa)
121 			SET(ocr, MMC_OCR_HCS);
122 	}
123 
124 	/*
125 	 * Read the SD/MMC memory OCR value by issuing CMD55 followed
126 	 * by ACMD41 to read the OCR value from memory-only SD cards.
127 	 * MMC cards will not respond to CMD55 or ACMD41 and this is
128 	 * how we distinguish them from SD cards.
129 	 */
130 mmc_mode:
131 	error = sdmmc_mem_send_op_cond(sc,
132 	    ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE) ? ocr : 0, &card_ocr);
133 	if (error) {
134 		if (ISSET(sc->sc_flags, SMF_SD_MODE) &&
135 		    !ISSET(sc->sc_flags, SMF_IO_MODE)) {
136 			/* Not a SD card, switch to MMC mode. */
137 			DPRINTF(("%s: switch to MMC mode\n", SDMMCDEVNAME(sc)));
138 			CLR(sc->sc_flags, SMF_SD_MODE);
139 			goto mmc_mode;
140 		}
141 		if (!ISSET(sc->sc_flags, SMF_SD_MODE)) {
142 			DPRINTF(("%s: couldn't read memory OCR\n",
143 			    SDMMCDEVNAME(sc)));
144 			goto out;
145 		} else {
146 			/* Not a "combo" card. */
147 			CLR(sc->sc_flags, SMF_MEM_MODE);
148 			error = 0;
149 			goto out;
150 		}
151 	}
152 	if (ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE)) {
153 		/* get card OCR */
154 		error = sdmmc_mem_spi_read_ocr(sc, ocr, &card_ocr);
155 		if (error) {
156 			DPRINTF(("%s: couldn't read SPI memory OCR\n",
157 			    SDMMCDEVNAME(sc)));
158 			goto out;
159 		}
160 	}
161 
162 	/* Set the lowest voltage supported by the card and host. */
163 	host_ocr = sdmmc_chip_host_ocr(sc->sc_sct, sc->sc_sch);
164 	error = sdmmc_set_bus_power(sc, host_ocr, card_ocr);
165 	if (error) {
166 		DPRINTF(("%s: couldn't supply voltage requested by card\n",
167 		    SDMMCDEVNAME(sc)));
168 		goto out;
169 	}
170 
171 	/* Tell the card(s) to enter the idle state (again). */
172 	sdmmc_go_idle_state(sc);
173 
174 	host_ocr &= card_ocr; /* only allow the common voltages */
175 	if (!ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE)) {
176 		/* Check SD Ver.2 */
177 		error = sdmmc_mem_send_if_cond(sc, 0x1aa, &card_ocr);
178 		if (error == 0 && card_ocr == 0x1aa)
179 			SET(ocr, MMC_OCR_HCS);
180 	}
181 	host_ocr |= ocr;
182 
183 	/* Send the new OCR value until all cards are ready. */
184 	error = sdmmc_mem_send_op_cond(sc, host_ocr, NULL);
185 	if (error) {
186 		DPRINTF(("%s: couldn't send memory OCR\n", SDMMCDEVNAME(sc)));
187 		goto out;
188 	}
189 
190 out:
191 	SDMMC_UNLOCK(sc);
192 
193 	return error;
194 }
195 
196 /*
197  * Read the CSD and CID from all cards and assign each card a unique
198  * relative card address (RCA).  CMD2 is ignored by SDIO-only cards.
199  */
200 void
201 sdmmc_mem_scan(struct sdmmc_softc *sc)
202 {
203 	sdmmc_response resp;
204 	struct sdmmc_function *sf;
205 	uint16_t next_rca;
206 	int error;
207 	int retry;
208 
209 	SDMMC_LOCK(sc);
210 
211 	/*
212 	 * CMD2 is a broadcast command understood by SD cards and MMC
213 	 * cards.  All cards begin to respond to the command, but back
214 	 * off if another card drives the CMD line to a different level.
215 	 * Only one card will get its entire response through.  That
216 	 * card remains silent once it has been assigned a RCA.
217 	 */
218 	for (retry = 0; retry < 100; retry++) {
219 		error = sdmmc_mem_send_cid(sc, &resp);
220 		if (error) {
221 			if (!ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE) &&
222 			    error == ETIMEDOUT) {
223 				/* No more cards there. */
224 				break;
225 			}
226 			DPRINTF(("%s: couldn't read CID\n", SDMMCDEVNAME(sc)));
227 			break;
228 		}
229 
230 		/* In MMC mode, find the next available RCA. */
231 		next_rca = 1;
232 		if (!ISSET(sc->sc_flags, SMF_SD_MODE)) {
233 			SIMPLEQ_FOREACH(sf, &sc->sf_head, sf_list)
234 				next_rca++;
235 		}
236 
237 		/* Allocate a sdmmc_function structure. */
238 		sf = sdmmc_function_alloc(sc);
239 		sf->rca = next_rca;
240 
241 		/*
242 		 * Remember the CID returned in the CMD2 response for
243 		 * later decoding.
244 		 */
245 		memcpy(sf->raw_cid, resp, sizeof(sf->raw_cid));
246 
247 		/*
248 		 * Silence the card by assigning it a unique RCA, or
249 		 * querying it for its RCA in the case of SD.
250 		 */
251 		if (!ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE)) {
252 			if (sdmmc_set_relative_addr(sc, sf) != 0) {
253 				aprint_error_dev(sc->sc_dev,
254 				    "couldn't set mem RCA\n");
255 				sdmmc_function_free(sf);
256 				break;
257 			}
258 		}
259 
260 		/*
261 		 * If this is a memory-only card, the card responding
262 		 * first becomes an alias for SDIO function 0.
263 		 */
264 		if (sc->sc_fn0 == NULL)
265 			sc->sc_fn0 = sf;
266 
267 		SIMPLEQ_INSERT_TAIL(&sc->sf_head, sf, sf_list);
268 
269 		/* only one function in SPI mode */
270 		if (ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE))
271 			break;
272 	}
273 
274 	if (!ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE))
275 		/* Go to Data Transfer Mode, if possible. */
276 		sdmmc_chip_bus_rod(sc->sc_sct, sc->sc_sch, 0);
277 
278 	/*
279 	 * All cards are either inactive or awaiting further commands.
280 	 * Read the CSDs and decode the raw CID for each card.
281 	 */
282 	SIMPLEQ_FOREACH(sf, &sc->sf_head, sf_list) {
283 		error = sdmmc_mem_send_csd(sc, sf, &resp);
284 		if (error) {
285 			SET(sf->flags, SFF_ERROR);
286 			continue;
287 		}
288 
289 		if (sdmmc_decode_csd(sc, resp, sf) != 0 ||
290 		    sdmmc_decode_cid(sc, sf->raw_cid, sf) != 0) {
291 			SET(sf->flags, SFF_ERROR);
292 			continue;
293 		}
294 
295 #ifdef SDMMC_DEBUG
296 		printf("%s: CID: ", SDMMCDEVNAME(sc));
297 		sdmmc_print_cid(&sf->cid);
298 #endif
299 	}
300 
301 	SDMMC_UNLOCK(sc);
302 }
303 
304 int
305 sdmmc_decode_csd(struct sdmmc_softc *sc, sdmmc_response resp,
306     struct sdmmc_function *sf)
307 {
308 	/* TRAN_SPEED(2:0): transfer rate exponent */
309 	static const int speed_exponent[8] = {
310 		100 *    1,	/* 100 Kbits/s */
311 		  1 * 1000,	/*   1 Mbits/s */
312 		 10 * 1000,	/*  10 Mbits/s */
313 		100 * 1000,	/* 100 Mbits/s */
314 		         0,
315 		         0,
316 		         0,
317 		         0,
318 	};
319 	/* TRAN_SPEED(6:3): time mantissa */
320 	static const int speed_mantissa[16] = {
321 		0, 10, 12, 13, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 70, 80,
322 	};
323 	struct sdmmc_csd *csd = &sf->csd;
324 	int e, m;
325 
326 	if (ISSET(sc->sc_flags, SMF_SD_MODE)) {
327 		/*
328 		 * CSD version 1.0 corresponds to SD system
329 		 * specification version 1.0 - 1.10. (SanDisk, 3.5.3)
330 		 */
331 		csd->csdver = SD_CSD_CSDVER(resp);
332 		switch (csd->csdver) {
333 		case SD_CSD_CSDVER_2_0:
334 			DPRINTF(("%s: SD Ver.2.0\n", SDMMCDEVNAME(sc)));
335 			SET(sf->flags, SFF_SDHC);
336 			csd->capacity = SD_CSD_V2_CAPACITY(resp);
337 			csd->read_bl_len = SD_CSD_V2_BL_LEN;
338 			break;
339 
340 		case SD_CSD_CSDVER_1_0:
341 			DPRINTF(("%s: SD Ver.1.0\n", SDMMCDEVNAME(sc)));
342 			csd->capacity = SD_CSD_CAPACITY(resp);
343 			csd->read_bl_len = SD_CSD_READ_BL_LEN(resp);
344 			break;
345 
346 		default:
347 			aprint_error_dev(sc->sc_dev,
348 			    "unknown SD CSD structure version 0x%x\n",
349 			    csd->csdver);
350 			return 1;
351 		}
352 
353 		csd->mmcver = SD_CSD_MMCVER(resp);
354 		csd->write_bl_len = SD_CSD_WRITE_BL_LEN(resp);
355 		csd->r2w_factor = SD_CSD_R2W_FACTOR(resp);
356 		e = SD_CSD_SPEED_EXP(resp);
357 		m = SD_CSD_SPEED_MANT(resp);
358 		csd->tran_speed = speed_exponent[e] * speed_mantissa[m] / 10;
359 		csd->ccc = SD_CSD_CCC(resp);
360 	} else {
361 		csd->csdver = MMC_CSD_CSDVER(resp);
362 		if (csd->csdver == MMC_CSD_CSDVER_1_0) {
363 			aprint_error_dev(sc->sc_dev,
364 			    "unknown MMC CSD structure version 0x%x\n",
365 			    csd->csdver);
366 			return 1;
367 		}
368 
369 		csd->mmcver = MMC_CSD_MMCVER(resp);
370 		csd->capacity = MMC_CSD_CAPACITY(resp);
371 		csd->read_bl_len = MMC_CSD_READ_BL_LEN(resp);
372 		csd->write_bl_len = MMC_CSD_WRITE_BL_LEN(resp);
373 		csd->r2w_factor = MMC_CSD_R2W_FACTOR(resp);
374 		e = MMC_CSD_TRAN_SPEED_EXP(resp);
375 		m = MMC_CSD_TRAN_SPEED_MANT(resp);
376 		csd->tran_speed = speed_exponent[e] * speed_mantissa[m] / 10;
377 	}
378 	if ((1 << csd->read_bl_len) > SDMMC_SECTOR_SIZE)
379 		csd->capacity *= (1 << csd->read_bl_len) / SDMMC_SECTOR_SIZE;
380 
381 #ifdef SDMMC_DUMP_CSD
382 	sdmmc_print_csd(resp, csd);
383 #endif
384 
385 	return 0;
386 }
387 
388 int
389 sdmmc_decode_cid(struct sdmmc_softc *sc, sdmmc_response resp,
390     struct sdmmc_function *sf)
391 {
392 	struct sdmmc_cid *cid = &sf->cid;
393 
394 	if (ISSET(sc->sc_flags, SMF_SD_MODE)) {
395 		cid->mid = SD_CID_MID(resp);
396 		cid->oid = SD_CID_OID(resp);
397 		SD_CID_PNM_CPY(resp, cid->pnm);
398 		cid->rev = SD_CID_REV(resp);
399 		cid->psn = SD_CID_PSN(resp);
400 		cid->mdt = SD_CID_MDT(resp);
401 	} else {
402 		switch(sf->csd.mmcver) {
403 		case MMC_CSD_MMCVER_1_0:
404 		case MMC_CSD_MMCVER_1_4:
405 			cid->mid = MMC_CID_MID_V1(resp);
406 			MMC_CID_PNM_V1_CPY(resp, cid->pnm);
407 			cid->rev = MMC_CID_REV_V1(resp);
408 			cid->psn = MMC_CID_PSN_V1(resp);
409 			cid->mdt = MMC_CID_MDT_V1(resp);
410 			break;
411 		case MMC_CSD_MMCVER_2_0:
412 		case MMC_CSD_MMCVER_3_1:
413 		case MMC_CSD_MMCVER_4_0:
414 			cid->mid = MMC_CID_MID_V2(resp);
415 			cid->oid = MMC_CID_OID_V2(resp);
416 			MMC_CID_PNM_V2_CPY(resp, cid->pnm);
417 			cid->psn = MMC_CID_PSN_V2(resp);
418 			break;
419 		default:
420 			aprint_error_dev(sc->sc_dev, "unknown MMC version %d\n",
421 			    sf->csd.mmcver);
422 			return 1;
423 		}
424 	}
425 	return 0;
426 }
427 
428 void
429 sdmmc_print_cid(struct sdmmc_cid *cid)
430 {
431 
432 	printf("mid=0x%02x oid=0x%04x pnm=\"%s\" rev=0x%02x psn=0x%08x"
433 	    " mdt=%03x\n", cid->mid, cid->oid, cid->pnm, cid->rev, cid->psn,
434 	    cid->mdt);
435 }
436 
437 #ifdef SDMMC_DUMP_CSD
438 void
439 sdmmc_print_csd(sdmmc_response resp, struct sdmmc_csd *csd)
440 {
441 
442 	printf("csdver = %d\n", csd->csdver);
443 	printf("mmcver = %d\n", csd->mmcver);
444 	printf("capacity = 0x%08x\n", csd->capacity);
445 	printf("read_bl_len = %d\n", csd->read_bl_len);
446 	printf("write_bl_len = %d\n", csd->write_bl_len);
447 	printf("r2w_factor = %d\n", csd->r2w_factor);
448 	printf("tran_speed = %d\n", csd->tran_speed);
449 	printf("ccc = 0x%x\n", csd->ccc);
450 }
451 #endif
452 
453 /*
454  * Initialize a SD/MMC memory card.
455  */
456 int
457 sdmmc_mem_init(struct sdmmc_softc *sc, struct sdmmc_function *sf)
458 {
459 	int error = 0;
460 
461 	SDMMC_LOCK(sc);
462 
463 	if (!ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE)) {
464 		error = sdmmc_select_card(sc, sf);
465 		if (error)
466 			goto out;
467 	}
468 
469 	error = sdmmc_mem_set_blocklen(sc, sf, SDMMC_SECTOR_SIZE);
470 	if (error)
471 		goto out;
472 
473 	if (ISSET(sc->sc_flags, SMF_SD_MODE))
474 		error = sdmmc_mem_sd_init(sc, sf);
475 	else
476 		error = sdmmc_mem_mmc_init(sc, sf);
477 
478 out:
479 	SDMMC_UNLOCK(sc);
480 
481 	return error;
482 }
483 
484 /*
485  * Get or set the card's memory OCR value (SD or MMC).
486  */
487 int
488 sdmmc_mem_send_op_cond(struct sdmmc_softc *sc, uint32_t ocr, uint32_t *ocrp)
489 {
490 	struct sdmmc_command cmd;
491 	int error;
492 	int retry;
493 
494 	/* Don't lock */
495 
496 	/*
497 	 * If we change the OCR value, retry the command until the OCR
498 	 * we receive in response has the "CARD BUSY" bit set, meaning
499 	 * that all cards are ready for identification.
500 	 */
501 	for (retry = 0; retry < 100; retry++) {
502 		memset(&cmd, 0, sizeof(cmd));
503 		cmd.c_arg = !ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE) ?
504 		    ocr : (ocr & MMC_OCR_HCS);
505 		cmd.c_flags = SCF_CMD_BCR | SCF_RSP_R3 | SCF_RSP_SPI_R1;
506 
507 		if (ISSET(sc->sc_flags, SMF_SD_MODE)) {
508 			cmd.c_opcode = SD_APP_OP_COND;
509 			error = sdmmc_app_command(sc, NULL, &cmd);
510 		} else {
511 			cmd.c_opcode = MMC_SEND_OP_COND;
512 			error = sdmmc_mmc_command(sc, &cmd);
513 		}
514 		if (error)
515 			break;
516 
517 		if (ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE)) {
518 			if (!ISSET(MMC_SPI_R1(cmd.c_resp), R1_SPI_IDLE))
519 				break;
520 		} else {
521 			if (ISSET(MMC_R3(cmd.c_resp), MMC_OCR_MEM_READY) ||
522 			    ocr == 0)
523 				break;
524 		}
525 
526 		error = ETIMEDOUT;
527 		sdmmc_delay(10000);
528 	}
529 	if (error == 0 &&
530 	    ocrp != NULL &&
531 	    !ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE))
532 		*ocrp = MMC_R3(cmd.c_resp);
533 	DPRINTF(("%s: sdmmc_mem_send_op_cond: error=%d, ocr=%#x\n",
534 	    SDMMCDEVNAME(sc), error, MMC_R3(cmd.c_resp)));
535 	return error;
536 }
537 
538 int
539 sdmmc_mem_send_if_cond(struct sdmmc_softc *sc, uint32_t ocr, uint32_t *ocrp)
540 {
541 	struct sdmmc_command cmd;
542 	int error;
543 
544 	/* Don't lock */
545 
546 	memset(&cmd, 0, sizeof(cmd));
547 	cmd.c_arg = ocr;
548 	cmd.c_flags = SCF_CMD_BCR | SCF_RSP_R7 | SCF_RSP_SPI_R7;
549 	cmd.c_opcode = SD_SEND_IF_COND;
550 
551 	error = sdmmc_mmc_command(sc, &cmd);
552 	if (error == 0 && ocrp != NULL) {
553 		if (ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE)) {
554 			*ocrp = MMC_SPI_R7(cmd.c_resp);
555 		} else {
556 			*ocrp = MMC_R7(cmd.c_resp);
557 		}
558 		DPRINTF(("%s: sdmmc_mem_send_if_cond: error=%d, ocr=%#x\n",
559 		    SDMMCDEVNAME(sc), error, *ocrp));
560 	}
561 	return error;
562 }
563 
564 /*
565  * Set the read block length appropriately for this card, according to
566  * the card CSD register value.
567  */
568 int
569 sdmmc_mem_set_blocklen(struct sdmmc_softc *sc, struct sdmmc_function *sf,
570    int block_len)
571 {
572 	struct sdmmc_command cmd;
573 	int error;
574 
575 	/* Don't lock */
576 
577 	memset(&cmd, 0, sizeof(cmd));
578 	cmd.c_opcode = MMC_SET_BLOCKLEN;
579 	cmd.c_arg = block_len;
580 	cmd.c_flags = SCF_CMD_AC | SCF_RSP_R1 | SCF_RSP_SPI_R1;
581 
582 	error = sdmmc_mmc_command(sc, &cmd);
583 
584 	DPRINTF(("%s: sdmmc_mem_set_blocklen: read_bl_len=%d sector_size=%d\n",
585 	    SDMMCDEVNAME(sc), 1 << sf->csd.read_bl_len, block_len));
586 
587 	return error;
588 }
589 
590 /* make 512-bit BE quantity __bitfield()-compatible */
591 static void
592 sdmmc_be512_to_bitfield512(sdmmc_bitfield512_t *buf) {
593 	size_t i;
594 	uint32_t tmp0, tmp1;
595 	const size_t bitswords = __arraycount(buf->_bits);
596 	for (i = 0; i < bitswords/2; i++) {
597 		tmp0 = buf->_bits[i];
598 		tmp1 = buf->_bits[bitswords - 1 - i];
599 		buf->_bits[i] = be32toh(tmp1);
600 		buf->_bits[bitswords - 1 - i] = be32toh(tmp0);
601 	}
602 }
603 
604 static int
605 sdmmc_mem_sd_init(struct sdmmc_softc *sc, struct sdmmc_function *sf)
606 {
607 	static const struct {
608 		int v;
609 		int freq;
610 	} switch_group0_functions[] = {
611 		/* Default/SDR12 */
612 		{ MMC_OCR_1_7V_1_8V | MMC_OCR_1_8V_1_9V |
613 		  MMC_OCR_3_2V_3_3V | MMC_OCR_3_3V_3_4V,	 25000 },
614 
615 		/* High-Speed/SDR25 */
616 		{ MMC_OCR_1_7V_1_8V | MMC_OCR_1_8V_1_9V |
617 		  MMC_OCR_3_2V_3_3V | MMC_OCR_3_3V_3_4V,	 50000 },
618 
619 		/* SDR50 */
620 		{ MMC_OCR_1_7V_1_8V | MMC_OCR_1_8V_1_9V,	100000 },
621 
622 		/* SDR104 */
623 		{ MMC_OCR_1_7V_1_8V | MMC_OCR_1_8V_1_9V,	208000 },
624 
625 		/* DDR50 */
626 		{ MMC_OCR_1_7V_1_8V | MMC_OCR_1_8V_1_9V,	 50000 },
627 	};
628 	int host_ocr, support_func, best_func, bus_clock, error, g, i;
629 	sdmmc_bitfield512_t status; /* Switch Function Status */
630 
631 	/* change bus clock */
632 	bus_clock = min(sc->sc_busclk, sf->csd.tran_speed);
633 	error = sdmmc_chip_bus_clock(sc->sc_sct, sc->sc_sch, bus_clock);
634 	if (error) {
635 		aprint_error_dev(sc->sc_dev, "can't change bus clock\n");
636 		return error;
637 	}
638 
639 	error = sdmmc_mem_send_scr(sc, sf, sf->raw_scr);
640 	if (error) {
641 		aprint_error_dev(sc->sc_dev, "SD_SEND_SCR send failed.\n");
642 		return error;
643 	}
644 	error = sdmmc_mem_decode_scr(sc, sf);
645 	if (error)
646 		return error;
647 
648 	if (ISSET(sc->sc_caps, SMC_CAPS_4BIT_MODE) &&
649 	    ISSET(sf->scr.bus_width, SCR_SD_BUS_WIDTHS_4BIT)) {
650 		DPRINTF(("%s: change bus width\n", SDMMCDEVNAME(sc)));
651 		error = sdmmc_set_bus_width(sf, 4);
652 		if (error) {
653 			aprint_error_dev(sc->sc_dev,
654 			    "can't change bus width (%d bit)\n", 4);
655 			return error;
656 		}
657 		sf->width = 4;
658 	}
659 
660 	if (sf->scr.sd_spec >= SCR_SD_SPEC_VER_1_10 &&
661 	    ISSET(sf->csd.ccc, SD_CSD_CCC_SWITCH)) {
662 		DPRINTF(("%s: switch func mode 0\n", SDMMCDEVNAME(sc)));
663 		error = sdmmc_mem_sd_switch(sf, 0, 1, 0, &status);
664 		if (error) {
665 			aprint_error_dev(sc->sc_dev,
666 			    "switch func mode 0 failed\n");
667 			return error;
668 		}
669 
670 		host_ocr = sdmmc_chip_host_ocr(sc->sc_sct, sc->sc_sch);
671 		support_func = SFUNC_STATUS_GROUP(&status, 1);
672 		best_func = 0;
673 		for (i = 0, g = 1;
674 		    i < __arraycount(switch_group0_functions); i++, g <<= 1) {
675 			if (!(switch_group0_functions[i].v & host_ocr))
676 				continue;
677 			if (g & support_func)
678 				best_func = i;
679 		}
680 		if (ISSET(sc->sc_caps, SMC_CAPS_SD_HIGHSPEED) &&
681 		    best_func != 0) {
682 			DPRINTF(("%s: switch func mode 1(func=%d)\n",
683 			    SDMMCDEVNAME(sc), best_func));
684 			error =
685 			    sdmmc_mem_sd_switch(sf, 1, 1, best_func, &status);
686 			if (error) {
687 				aprint_error_dev(sc->sc_dev,
688 				    "switch func mode 1 failed:"
689 				    " group 1 function %d(0x%2x)\n",
690 				    best_func, support_func);
691 				return error;
692 			}
693 			sf->csd.tran_speed =
694 			    switch_group0_functions[best_func].freq;
695 
696 			/* Wait 400KHz x 8 clock (2.5us * 8 + slop) */
697 			delay(25);
698 		}
699 	}
700 
701 	/* update bus clock */
702 	if (sc->sc_busclk > sf->csd.tran_speed)
703 		sc->sc_busclk = sf->csd.tran_speed;
704 	if (sc->sc_busclk == bus_clock)
705 		return 0;
706 
707 	/* change bus clock */
708 	error = sdmmc_chip_bus_clock(sc->sc_sct, sc->sc_sch, sc->sc_busclk);
709 	if (error) {
710 		aprint_error_dev(sc->sc_dev, "can't change bus clock\n");
711 		return error;
712 	}
713 
714 	return 0;
715 }
716 
717 static int
718 sdmmc_mem_mmc_init(struct sdmmc_softc *sc, struct sdmmc_function *sf)
719 {
720 	int width, value, hs_timing, bus_clock, error;
721 	char ext_csd[512];
722 
723 	/* change bus clock */
724 	bus_clock = min(sc->sc_busclk, sf->csd.tran_speed);
725 	error = sdmmc_chip_bus_clock(sc->sc_sct, sc->sc_sch, bus_clock);
726 	if (error) {
727 		aprint_error_dev(sc->sc_dev, "can't change bus clock\n");
728 		return error;
729 	}
730 
731 	if (sf->csd.mmcver >= MMC_CSD_MMCVER_4_0) {
732 		error = sdmmc_mem_send_cxd_data(sc,
733 		    MMC_SEND_EXT_CSD, ext_csd, sizeof(ext_csd));
734 		if (error) {
735 			aprint_error_dev(sc->sc_dev,
736 			    "can't read EXT_CSD (error=%d)\n", error);
737 			return error;
738 		}
739 		if ((sf->csd.csdver == MMC_CSD_CSDVER_EXT_CSD) &&
740 		    (ext_csd[EXT_CSD_STRUCTURE] > EXT_CSD_STRUCTURE_VER_1_2)) {
741 			aprint_error_dev(sc->sc_dev,
742 			    "unrecognised future version (%d)\n",
743 				ext_csd[EXT_CSD_STRUCTURE]);
744 			return error;
745 		}
746 		hs_timing = 0;
747 		switch (ext_csd[EXT_CSD_CARD_TYPE]) {
748 		case EXT_CSD_CARD_TYPE_26M:
749 			sf->csd.tran_speed = 26000;	/* 26MHz */
750 			break;
751 
752 		case EXT_CSD_CARD_TYPE_52M:
753 		case EXT_CSD_CARD_TYPE_52M_V18:
754 		case EXT_CSD_CARD_TYPE_52M_V12:
755 		case EXT_CSD_CARD_TYPE_52M_V12_18:
756 			sf->csd.tran_speed = 52000;	/* 52MHz */
757 			hs_timing = 1;
758 			break;
759 
760 		default:
761 			aprint_error_dev(sc->sc_dev,
762 			    "unknown CARD_TYPE: 0x%x\n",
763 			    ext_csd[EXT_CSD_CARD_TYPE]);
764 			return error;
765 		}
766 
767 		if (!ISSET(sc->sc_caps, SMC_CAPS_MMC_HIGHSPEED)) {
768 			hs_timing = 0;
769 		}
770 		if (hs_timing) {
771 			error = sdmmc_mem_mmc_switch(sf, EXT_CSD_CMD_SET_NORMAL,
772 			    EXT_CSD_HS_TIMING, hs_timing);
773 			if (error) {
774 				aprint_error_dev(sc->sc_dev,
775 				    "can't change high speed\n");
776 				return error;
777 			}
778 		}
779 
780 		if (sc->sc_busclk > sf->csd.tran_speed)
781 			sc->sc_busclk = sf->csd.tran_speed;
782 		if (sc->sc_busclk != bus_clock) {
783 			error = sdmmc_chip_bus_clock(sc->sc_sct, sc->sc_sch,
784 			    sc->sc_busclk);
785 			if (error) {
786 				aprint_error_dev(sc->sc_dev,
787 				    "can't change bus clock\n");
788 				return error;
789 			}
790 		}
791 
792 		if (hs_timing) {
793 			error = sdmmc_mem_send_cxd_data(sc,
794 			    MMC_SEND_EXT_CSD, ext_csd, sizeof(ext_csd));
795 			if (error) {
796 				aprint_error_dev(sc->sc_dev,
797 				    "can't re-read EXT_CSD\n");
798 				return error;
799 			}
800 			if (ext_csd[EXT_CSD_HS_TIMING] != hs_timing) {
801 				aprint_error_dev(sc->sc_dev,
802 				    "HS_TIMING set failed\n");
803 				return EINVAL;
804 			}
805 		}
806 
807 		if (ISSET(sc->sc_caps, SMC_CAPS_8BIT_MODE)) {
808 			width = 8;
809 			value = EXT_CSD_BUS_WIDTH_8;
810 		} else if (ISSET(sc->sc_caps, SMC_CAPS_4BIT_MODE)) {
811 			width = 4;
812 			value = EXT_CSD_BUS_WIDTH_4;
813 		} else {
814 			width = 1;
815 			value = EXT_CSD_BUS_WIDTH_1;
816 		}
817 
818 		if (width != 1) {
819 			error = sdmmc_mem_mmc_switch(sf, EXT_CSD_CMD_SET_NORMAL,
820 			    EXT_CSD_BUS_WIDTH, value);
821 			if (error == 0)
822 				error = sdmmc_chip_bus_width(sc->sc_sct,
823 				    sc->sc_sch, width);
824 			else {
825 				DPRINTF(("%s: can't change bus width"
826 				    " (%d bit)\n", SDMMCDEVNAME(sc), width));
827 				return error;
828 			}
829 
830 			/* XXXX: need bus test? (using by CMD14 & CMD19) */
831 		}
832 		sf->width = width;
833 	} else {
834 		if (sc->sc_busclk > sf->csd.tran_speed)
835 			sc->sc_busclk = sf->csd.tran_speed;
836 		if (sc->sc_busclk != bus_clock) {
837 			error = sdmmc_chip_bus_clock(sc->sc_sct, sc->sc_sch,
838 			    sc->sc_busclk);
839 			if (error) {
840 				aprint_error_dev(sc->sc_dev,
841 				    "can't change bus clock\n");
842 				return error;
843 			}
844 		}
845 	}
846 
847 	return 0;
848 }
849 
850 static int
851 sdmmc_mem_send_cid(struct sdmmc_softc *sc, sdmmc_response *resp)
852 {
853 	struct sdmmc_command cmd;
854 	int error;
855 
856 	if (!ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE)) {
857 		memset(&cmd, 0, sizeof cmd);
858 		cmd.c_opcode = MMC_ALL_SEND_CID;
859 		cmd.c_flags = SCF_CMD_BCR | SCF_RSP_R2;
860 
861 		error = sdmmc_mmc_command(sc, &cmd);
862 	} else {
863 		error = sdmmc_mem_send_cxd_data(sc, MMC_SEND_CID, &cmd.c_resp,
864 		    sizeof(cmd.c_resp));
865 	}
866 
867 #ifdef SDMMC_DEBUG
868 	if (error == 0)
869 		sdmmc_dump_data("CID", cmd.c_resp, sizeof(cmd.c_resp));
870 #endif
871 	if (error == 0 && resp != NULL)
872 		memcpy(resp, &cmd.c_resp, sizeof(*resp));
873 	return error;
874 }
875 
876 static int
877 sdmmc_mem_send_csd(struct sdmmc_softc *sc, struct sdmmc_function *sf,
878     sdmmc_response *resp)
879 {
880 	struct sdmmc_command cmd;
881 	int error;
882 
883 	if (!ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE)) {
884 		memset(&cmd, 0, sizeof cmd);
885 		cmd.c_opcode = MMC_SEND_CSD;
886 		cmd.c_arg = MMC_ARG_RCA(sf->rca);
887 		cmd.c_flags = SCF_CMD_AC | SCF_RSP_R2;
888 
889 		error = sdmmc_mmc_command(sc, &cmd);
890 	} else {
891 		error = sdmmc_mem_send_cxd_data(sc, MMC_SEND_CSD, &cmd.c_resp,
892 		    sizeof(cmd.c_resp));
893 	}
894 
895 #ifdef SDMMC_DEBUG
896 	if (error == 0)
897 		sdmmc_dump_data("CSD", cmd.c_resp, sizeof(cmd.c_resp));
898 #endif
899 	if (error == 0 && resp != NULL)
900 		memcpy(resp, &cmd.c_resp, sizeof(*resp));
901 	return error;
902 }
903 
904 static int
905 sdmmc_mem_send_scr(struct sdmmc_softc *sc, struct sdmmc_function *sf,
906     uint32_t *scr)
907 {
908 	struct sdmmc_command cmd;
909 	bus_dma_segment_t ds[1];
910 	void *ptr = NULL;
911 	int datalen = 8;
912 	int rseg;
913 	int error = 0;
914 
915 	/* Don't lock */
916 
917 	if (ISSET(sc->sc_caps, SMC_CAPS_DMA)) {
918 		error = bus_dmamem_alloc(sc->sc_dmat, datalen, PAGE_SIZE, 0,
919 		    ds, 1, &rseg, BUS_DMA_NOWAIT);
920 		if (error)
921 			goto out;
922 		error = bus_dmamem_map(sc->sc_dmat, ds, 1, datalen, &ptr,
923 		    BUS_DMA_NOWAIT);
924 		if (error)
925 			goto dmamem_free;
926 		error = bus_dmamap_load(sc->sc_dmat, sc->sc_dmap, ptr, datalen,
927 		    NULL, BUS_DMA_NOWAIT|BUS_DMA_STREAMING|BUS_DMA_READ);
928 		if (error)
929 			goto dmamem_unmap;
930 
931 		bus_dmamap_sync(sc->sc_dmat, sc->sc_dmap, 0, datalen,
932 		    BUS_DMASYNC_PREREAD);
933 	} else {
934 		ptr = malloc(datalen, M_DEVBUF, M_NOWAIT | M_ZERO);
935 		if (ptr == NULL)
936 			goto out;
937 	}
938 
939 	memset(&cmd, 0, sizeof(cmd));
940 	cmd.c_data = ptr;
941 	cmd.c_datalen = datalen;
942 	cmd.c_blklen = datalen;
943 	cmd.c_arg = 0;
944 	cmd.c_flags = SCF_CMD_ADTC | SCF_CMD_READ | SCF_RSP_R1 | SCF_RSP_SPI_R1;
945 	cmd.c_opcode = SD_APP_SEND_SCR;
946 	if (ISSET(sc->sc_caps, SMC_CAPS_DMA))
947 		cmd.c_dmamap = sc->sc_dmap;
948 
949 	error = sdmmc_app_command(sc, sf, &cmd);
950 	if (error == 0) {
951 		if (ISSET(sc->sc_caps, SMC_CAPS_DMA)) {
952 			bus_dmamap_sync(sc->sc_dmat, sc->sc_dmap, 0, datalen,
953 			    BUS_DMASYNC_POSTREAD);
954 		}
955 		memcpy(scr, ptr, datalen);
956 	}
957 
958 out:
959 	if (ptr != NULL) {
960 		if (ISSET(sc->sc_caps, SMC_CAPS_DMA)) {
961 			bus_dmamap_unload(sc->sc_dmat, sc->sc_dmap);
962 dmamem_unmap:
963 			bus_dmamem_unmap(sc->sc_dmat, ptr, datalen);
964 dmamem_free:
965 			bus_dmamem_free(sc->sc_dmat, ds, rseg);
966 		} else {
967 			free(ptr, M_DEVBUF);
968 		}
969 	}
970 	DPRINTF(("%s: sdmem_mem_send_scr: error = %d\n", SDMMCDEVNAME(sc),
971 	    error));
972 
973 #ifdef SDMMC_DEBUG
974 	if (error == 0)
975 		sdmmc_dump_data("SCR", scr, datalen);
976 #endif
977 	return error;
978 }
979 
980 static int
981 sdmmc_mem_decode_scr(struct sdmmc_softc *sc, struct sdmmc_function *sf)
982 {
983 	sdmmc_response resp;
984 	int ver;
985 
986 	memset(resp, 0, sizeof(resp));
987 	/*
988 	 * Change the raw-scr received from the DMA stream to resp.
989 	 */
990 	resp[0] = be32toh(sf->raw_scr[1]) >> 8;		// LSW
991 	resp[1] = be32toh(sf->raw_scr[0]);		// MSW
992 	resp[0] |= (resp[1] & 0xff) << 24;
993 	resp[1] >>= 8;
994 
995 	ver = SCR_STRUCTURE(resp);
996 	sf->scr.sd_spec = SCR_SD_SPEC(resp);
997 	sf->scr.bus_width = SCR_SD_BUS_WIDTHS(resp);
998 
999 	DPRINTF(("%s: sdmmc_mem_decode_scr: %08x%08x spec=%d, bus width=%d\n",
1000 	    SDMMCDEVNAME(sc), resp[1], resp[0],
1001 	    sf->scr.sd_spec, sf->scr.bus_width));
1002 
1003 	if (ver != 0) {
1004 		DPRINTF(("%s: unknown structure version: %d\n",
1005 		    SDMMCDEVNAME(sc), ver));
1006 		return EINVAL;
1007 	}
1008 	return 0;
1009 }
1010 
1011 static int
1012 sdmmc_mem_send_cxd_data(struct sdmmc_softc *sc, int opcode, void *data,
1013     size_t datalen)
1014 {
1015 	struct sdmmc_command cmd;
1016 	bus_dma_segment_t ds[1];
1017 	void *ptr = NULL;
1018 	int rseg;
1019 	int error = 0;
1020 
1021 	if (ISSET(sc->sc_caps, SMC_CAPS_DMA)) {
1022 		error = bus_dmamem_alloc(sc->sc_dmat, datalen, PAGE_SIZE, 0, ds,
1023 		    1, &rseg, BUS_DMA_NOWAIT);
1024 		if (error)
1025 			goto out;
1026 		error = bus_dmamem_map(sc->sc_dmat, ds, 1, datalen, &ptr,
1027 		    BUS_DMA_NOWAIT);
1028 		if (error)
1029 			goto dmamem_free;
1030 		error = bus_dmamap_load(sc->sc_dmat, sc->sc_dmap, ptr, datalen,
1031 		    NULL, BUS_DMA_NOWAIT|BUS_DMA_STREAMING|BUS_DMA_READ);
1032 		if (error)
1033 			goto dmamem_unmap;
1034 
1035 		bus_dmamap_sync(sc->sc_dmat, sc->sc_dmap, 0, datalen,
1036 		    BUS_DMASYNC_PREREAD);
1037 	} else {
1038 		ptr = malloc(datalen, M_DEVBUF, M_NOWAIT | M_ZERO);
1039 		if (ptr == NULL)
1040 			goto out;
1041 	}
1042 
1043 	memset(&cmd, 0, sizeof(cmd));
1044 	cmd.c_data = ptr;
1045 	cmd.c_datalen = datalen;
1046 	cmd.c_blklen = datalen;
1047 	cmd.c_opcode = opcode;
1048 	cmd.c_arg = 0;
1049 	cmd.c_flags = SCF_CMD_ADTC | SCF_CMD_READ | SCF_RSP_SPI_R1;
1050 	if (opcode == MMC_SEND_EXT_CSD)
1051 		SET(cmd.c_flags, SCF_RSP_R1);
1052 	else
1053 		SET(cmd.c_flags, SCF_RSP_R2);
1054 	if (ISSET(sc->sc_caps, SMC_CAPS_DMA))
1055 		cmd.c_dmamap = sc->sc_dmap;
1056 
1057 	error = sdmmc_mmc_command(sc, &cmd);
1058 	if (error == 0) {
1059 		if (ISSET(sc->sc_caps, SMC_CAPS_DMA)) {
1060 			bus_dmamap_sync(sc->sc_dmat, sc->sc_dmap, 0, datalen,
1061 			    BUS_DMASYNC_POSTREAD);
1062 		}
1063 		memcpy(data, ptr, datalen);
1064 #ifdef SDMMC_DEBUG
1065 		sdmmc_dump_data("CXD", data, datalen);
1066 #endif
1067 	}
1068 
1069 out:
1070 	if (ptr != NULL) {
1071 		if (ISSET(sc->sc_caps, SMC_CAPS_DMA)) {
1072 			bus_dmamap_unload(sc->sc_dmat, sc->sc_dmap);
1073 dmamem_unmap:
1074 			bus_dmamem_unmap(sc->sc_dmat, ptr, datalen);
1075 dmamem_free:
1076 			bus_dmamem_free(sc->sc_dmat, ds, rseg);
1077 		} else {
1078 			free(ptr, M_DEVBUF);
1079 		}
1080 	}
1081 	return error;
1082 }
1083 
1084 static int
1085 sdmmc_set_bus_width(struct sdmmc_function *sf, int width)
1086 {
1087 	struct sdmmc_softc *sc = sf->sc;
1088 	struct sdmmc_command cmd;
1089 	int error;
1090 
1091 	if (ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE))
1092 		return ENODEV;
1093 
1094 	memset(&cmd, 0, sizeof(cmd));
1095 	cmd.c_opcode = SD_APP_SET_BUS_WIDTH;
1096 	cmd.c_flags = SCF_RSP_R1 | SCF_CMD_AC;
1097 
1098 	switch (width) {
1099 	case 1:
1100 		cmd.c_arg = SD_ARG_BUS_WIDTH_1;
1101 		break;
1102 
1103 	case 4:
1104 		cmd.c_arg = SD_ARG_BUS_WIDTH_4;
1105 		break;
1106 
1107 	default:
1108 		return EINVAL;
1109 	}
1110 
1111 	error = sdmmc_app_command(sc, sf, &cmd);
1112 	if (error == 0)
1113 		error = sdmmc_chip_bus_width(sc->sc_sct, sc->sc_sch, width);
1114 	return error;
1115 }
1116 
1117 static int
1118 sdmmc_mem_sd_switch(struct sdmmc_function *sf, int mode, int group,
1119     int function, sdmmc_bitfield512_t *status)
1120 {
1121 	struct sdmmc_softc *sc = sf->sc;
1122 	struct sdmmc_command cmd;
1123 	bus_dma_segment_t ds[1];
1124 	void *ptr = NULL;
1125 	int gsft, rseg, error = 0;
1126 	const int statlen = 64;
1127 
1128 	if (sf->scr.sd_spec >= SCR_SD_SPEC_VER_1_10 &&
1129 	    !ISSET(sf->csd.ccc, SD_CSD_CCC_SWITCH))
1130 		return EINVAL;
1131 
1132 	if (group <= 0 || group > 6 ||
1133 	    function < 0 || function > 15)
1134 		return EINVAL;
1135 
1136 	gsft = (group - 1) << 2;
1137 
1138 	if (ISSET(sc->sc_caps, SMC_CAPS_DMA)) {
1139 		error = bus_dmamem_alloc(sc->sc_dmat, statlen, PAGE_SIZE, 0, ds,
1140 		    1, &rseg, BUS_DMA_NOWAIT);
1141 		if (error)
1142 			goto out;
1143 		error = bus_dmamem_map(sc->sc_dmat, ds, 1, statlen, &ptr,
1144 		    BUS_DMA_NOWAIT);
1145 		if (error)
1146 			goto dmamem_free;
1147 		error = bus_dmamap_load(sc->sc_dmat, sc->sc_dmap, ptr, statlen,
1148 		    NULL, BUS_DMA_NOWAIT|BUS_DMA_STREAMING|BUS_DMA_READ);
1149 		if (error)
1150 			goto dmamem_unmap;
1151 
1152 		bus_dmamap_sync(sc->sc_dmat, sc->sc_dmap, 0, statlen,
1153 		    BUS_DMASYNC_PREREAD);
1154 	} else {
1155 		ptr = malloc(statlen, M_DEVBUF, M_NOWAIT | M_ZERO);
1156 		if (ptr == NULL)
1157 			goto out;
1158 	}
1159 
1160 	memset(&cmd, 0, sizeof(cmd));
1161 	cmd.c_data = ptr;
1162 	cmd.c_datalen = statlen;
1163 	cmd.c_blklen = statlen;
1164 	cmd.c_opcode = SD_SEND_SWITCH_FUNC;
1165 	cmd.c_arg =
1166 	    (!!mode << 31) | (function << gsft) | (0x00ffffff & ~(0xf << gsft));
1167 	cmd.c_flags = SCF_CMD_ADTC | SCF_CMD_READ | SCF_RSP_R1 | SCF_RSP_SPI_R1;
1168 	if (ISSET(sc->sc_caps, SMC_CAPS_DMA))
1169 		cmd.c_dmamap = sc->sc_dmap;
1170 
1171 	error = sdmmc_mmc_command(sc, &cmd);
1172 	if (error == 0) {
1173 		if (ISSET(sc->sc_caps, SMC_CAPS_DMA)) {
1174 			bus_dmamap_sync(sc->sc_dmat, sc->sc_dmap, 0, statlen,
1175 			    BUS_DMASYNC_POSTREAD);
1176 		}
1177 		memcpy(status, ptr, statlen);
1178 	}
1179 
1180 out:
1181 	if (ptr != NULL) {
1182 		if (ISSET(sc->sc_caps, SMC_CAPS_DMA)) {
1183 			bus_dmamap_unload(sc->sc_dmat, sc->sc_dmap);
1184 dmamem_unmap:
1185 			bus_dmamem_unmap(sc->sc_dmat, ptr, statlen);
1186 dmamem_free:
1187 			bus_dmamem_free(sc->sc_dmat, ds, rseg);
1188 		} else {
1189 			free(ptr, M_DEVBUF);
1190 		}
1191 	}
1192 
1193 	if (error == 0)
1194 		sdmmc_be512_to_bitfield512(status);
1195 
1196 	return error;
1197 }
1198 
1199 static int
1200 sdmmc_mem_mmc_switch(struct sdmmc_function *sf, uint8_t set, uint8_t index,
1201     uint8_t value)
1202 {
1203 	struct sdmmc_softc *sc = sf->sc;
1204 	struct sdmmc_command cmd;
1205 
1206 	memset(&cmd, 0, sizeof(cmd));
1207 	cmd.c_opcode = MMC_SWITCH;
1208 	cmd.c_arg = (MMC_SWITCH_MODE_WRITE_BYTE << 24) |
1209 	    (index << 16) | (value << 8) | set;
1210 	cmd.c_flags = SCF_RSP_SPI_R1B | SCF_RSP_R1B | SCF_CMD_AC;
1211 
1212 	return sdmmc_mmc_command(sc, &cmd);
1213 }
1214 
1215 /*
1216  * SPI mode function
1217  */
1218 static int
1219 sdmmc_mem_spi_read_ocr(struct sdmmc_softc *sc, uint32_t hcs, uint32_t *card_ocr)
1220 {
1221 	struct sdmmc_command cmd;
1222 	int error;
1223 
1224 	memset(&cmd, 0, sizeof(cmd));
1225 	cmd.c_opcode = MMC_READ_OCR;
1226 	cmd.c_arg = hcs ? MMC_OCR_HCS : 0;
1227 	cmd.c_flags = SCF_RSP_SPI_R3;
1228 
1229 	error = sdmmc_mmc_command(sc, &cmd);
1230 	if (error == 0 && card_ocr != NULL)
1231 		*card_ocr = cmd.c_resp[1];
1232 	DPRINTF(("%s: sdmmc_mem_spi_read_ocr: error=%d, ocr=%#x\n",
1233 	    SDMMCDEVNAME(sc), error, cmd.c_resp[1]));
1234 	return error;
1235 }
1236 
1237 /*
1238  * read/write function
1239  */
1240 /* read */
1241 static int
1242 sdmmc_mem_single_read_block(struct sdmmc_function *sf, uint32_t blkno,
1243     u_char *data, size_t datalen)
1244 {
1245 	struct sdmmc_softc *sc __diagused = sf->sc;
1246 	int error = 0;
1247 	int i;
1248 
1249 	KASSERT((datalen % SDMMC_SECTOR_SIZE) == 0);
1250 	KASSERT(!ISSET(sc->sc_caps, SMC_CAPS_DMA));
1251 
1252 	for (i = 0; i < datalen / SDMMC_SECTOR_SIZE; i++) {
1253 		error = sdmmc_mem_read_block_subr(sf, blkno + i,
1254 		    data + i * SDMMC_SECTOR_SIZE, SDMMC_SECTOR_SIZE);
1255 		if (error)
1256 			break;
1257 	}
1258 	return error;
1259 }
1260 
1261 static int
1262 sdmmc_mem_read_block_subr(struct sdmmc_function *sf, uint32_t blkno,
1263     u_char *data, size_t datalen)
1264 {
1265 	struct sdmmc_softc *sc = sf->sc;
1266 	struct sdmmc_command cmd;
1267 	int error, bbuf, seg, off, len, num;
1268 
1269 	if (!ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE)) {
1270 		error = sdmmc_select_card(sc, sf);
1271 		if (error)
1272 			goto out;
1273 	}
1274 
1275 	bbuf = 0;
1276 	num = 0;
1277 	seg = off = len = 0;
1278 retry:
1279 	memset(&cmd, 0, sizeof(cmd));
1280 	cmd.c_data = data;
1281 	cmd.c_datalen = datalen;
1282 	cmd.c_blklen = SDMMC_SECTOR_SIZE;
1283 	cmd.c_opcode = (cmd.c_datalen / cmd.c_blklen) > 1 ?
1284 	    MMC_READ_BLOCK_MULTIPLE : MMC_READ_BLOCK_SINGLE;
1285 	cmd.c_arg = blkno;
1286 	if (!ISSET(sf->flags, SFF_SDHC))
1287 		cmd.c_arg <<= SDMMC_SECTOR_SIZE_SB;
1288 	cmd.c_flags = SCF_CMD_ADTC | SCF_CMD_READ | SCF_RSP_R1 | SCF_RSP_SPI_R1;
1289 	if (ISSET(sc->sc_caps, SMC_CAPS_DMA)) {
1290 		cmd.c_dmamap = sc->sc_dmap;
1291 		if (!ISSET(sc->sc_caps, SMC_CAPS_MULTI_SEG_DMA)) {
1292 			len = sc->sc_dmap->dm_segs[seg].ds_len - off;
1293 			len &= ~(SDMMC_SECTOR_SIZE - 1);
1294 			cmd.c_datalen = len;
1295 			cmd.c_dmaseg = seg;
1296 			cmd.c_dmaoff = off;
1297 			bbuf = 0;
1298 			if (len == 0) {
1299 				/* Use bounce buffer */
1300 				bus_dmamap_sync(sc->sc_dmat, sf->bbuf_dmap,
1301 				    0, SDMMC_SECTOR_SIZE, BUS_DMASYNC_PREREAD);
1302 				cmd.c_datalen = SDMMC_SECTOR_SIZE;
1303 				cmd.c_dmamap = sf->bbuf_dmap;
1304 				cmd.c_dmaseg = 0;
1305 				cmd.c_dmaoff = 0;
1306 				bbuf = 1;
1307 				len = SDMMC_SECTOR_SIZE;
1308 			}
1309 			cmd.c_opcode = (cmd.c_datalen / cmd.c_blklen) > 1 ?
1310 			    MMC_READ_BLOCK_MULTIPLE : MMC_READ_BLOCK_SINGLE;
1311 		}
1312 	}
1313 
1314 	error = sdmmc_mmc_command(sc, &cmd);
1315 	if (error)
1316 		goto out;
1317 
1318 	if (!ISSET(sc->sc_caps, SMC_CAPS_AUTO_STOP)) {
1319 		if (cmd.c_opcode == MMC_READ_BLOCK_MULTIPLE) {
1320 			memset(&cmd, 0, sizeof cmd);
1321 			cmd.c_opcode = MMC_STOP_TRANSMISSION;
1322 			cmd.c_arg = MMC_ARG_RCA(sf->rca);
1323 			cmd.c_flags = SCF_CMD_AC | SCF_RSP_R1B | SCF_RSP_SPI_R1B;
1324 			error = sdmmc_mmc_command(sc, &cmd);
1325 			if (error)
1326 				goto out;
1327 		}
1328 	}
1329 
1330 	if (!ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE)) {
1331 		do {
1332 			memset(&cmd, 0, sizeof(cmd));
1333 			cmd.c_opcode = MMC_SEND_STATUS;
1334 			if (!ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE))
1335 				cmd.c_arg = MMC_ARG_RCA(sf->rca);
1336 			cmd.c_flags = SCF_CMD_AC | SCF_RSP_R1 | SCF_RSP_SPI_R2;
1337 			error = sdmmc_mmc_command(sc, &cmd);
1338 			if (error)
1339 				break;
1340 			/* XXX time out */
1341 		} while (!ISSET(MMC_R1(cmd.c_resp), MMC_R1_READY_FOR_DATA));
1342 	}
1343 
1344 	if (ISSET(sc->sc_caps, SMC_CAPS_DMA) &&
1345 	    !ISSET(sc->sc_caps, SMC_CAPS_MULTI_SEG_DMA)) {
1346 		bus_dma_segment_t *dm_segs = sc->sc_dmap->dm_segs;
1347 
1348 		if (bbuf) {
1349 			bus_dmamap_sync(sc->sc_dmat, sf->bbuf_dmap,
1350 			    0, SDMMC_SECTOR_SIZE, BUS_DMASYNC_POSTREAD);
1351 			bus_dmamap_sync(sc->sc_dmat, sc->sc_dmap, num,
1352 			    SDMMC_SECTOR_SIZE, BUS_DMASYNC_POSTREAD);
1353 			memcpy(data, sf->bbuf, SDMMC_SECTOR_SIZE);
1354 			bus_dmamap_sync(sc->sc_dmat, sc->sc_dmap, num,
1355 			    SDMMC_SECTOR_SIZE, BUS_DMASYNC_PREREAD);
1356 		}
1357 		num += len;
1358 		data += len;
1359 		datalen -= len;
1360 		blkno += (len / SDMMC_SECTOR_SIZE);
1361 
1362 		while (off + len >= dm_segs[seg].ds_len) {
1363 			len -= dm_segs[seg++].ds_len;
1364 			off = 0;
1365 		}
1366 		off += len;
1367 
1368 		if (seg < sc->sc_dmap->dm_nsegs)
1369 			goto retry;
1370 	}
1371 
1372 out:
1373 	return error;
1374 }
1375 
1376 int
1377 sdmmc_mem_read_block(struct sdmmc_function *sf, uint32_t blkno, u_char *data,
1378     size_t datalen)
1379 {
1380 	struct sdmmc_softc *sc = sf->sc;
1381 	int error;
1382 
1383 	SDMMC_LOCK(sc);
1384 
1385 	if (ISSET(sc->sc_caps, SMC_CAPS_SINGLE_ONLY)) {
1386 		error = sdmmc_mem_single_read_block(sf, blkno, data, datalen);
1387 		goto out;
1388 	}
1389 
1390 	if (!ISSET(sc->sc_caps, SMC_CAPS_DMA)) {
1391 		error = sdmmc_mem_read_block_subr(sf, blkno, data, datalen);
1392 		goto out;
1393 	}
1394 
1395 	/* DMA transfer */
1396 	error = bus_dmamap_load(sc->sc_dmat, sc->sc_dmap, data, datalen, NULL,
1397 	    BUS_DMA_NOWAIT|BUS_DMA_READ);
1398 	if (error)
1399 		goto out;
1400 
1401 #ifdef SDMMC_DEBUG
1402 	for (int i = 0; i < sc->sc_dmap->dm_nsegs; i++) {
1403 		printf("seg#%d: addr=%#lx, size=%#lx\n", i,
1404 		    (u_long)sc->sc_dmap->dm_segs[i].ds_addr,
1405 		    (u_long)sc->sc_dmap->dm_segs[i].ds_len);
1406 	}
1407 #endif
1408 
1409 	bus_dmamap_sync(sc->sc_dmat, sc->sc_dmap, 0, datalen,
1410 	    BUS_DMASYNC_PREREAD);
1411 
1412 	error = sdmmc_mem_read_block_subr(sf, blkno, data, datalen);
1413 	if (error)
1414 		goto unload;
1415 
1416 	bus_dmamap_sync(sc->sc_dmat, sc->sc_dmap, 0, datalen,
1417 	    BUS_DMASYNC_POSTREAD);
1418 unload:
1419 	bus_dmamap_unload(sc->sc_dmat, sc->sc_dmap);
1420 
1421 out:
1422 	SDMMC_UNLOCK(sc);
1423 
1424 	return error;
1425 }
1426 
1427 /* write */
1428 static int
1429 sdmmc_mem_single_write_block(struct sdmmc_function *sf, uint32_t blkno,
1430     u_char *data, size_t datalen)
1431 {
1432 	struct sdmmc_softc *sc __diagused = sf->sc;
1433 	int error = 0;
1434 	int i;
1435 
1436 	KASSERT((datalen % SDMMC_SECTOR_SIZE) == 0);
1437 	KASSERT(!ISSET(sc->sc_caps, SMC_CAPS_DMA));
1438 
1439 	for (i = 0; i < datalen / SDMMC_SECTOR_SIZE; i++) {
1440 		error = sdmmc_mem_write_block_subr(sf, blkno + i,
1441 		    data + i * SDMMC_SECTOR_SIZE, SDMMC_SECTOR_SIZE);
1442 		if (error)
1443 			break;
1444 	}
1445 	return error;
1446 }
1447 
1448 static int
1449 sdmmc_mem_write_block_subr(struct sdmmc_function *sf, uint32_t blkno,
1450     u_char *data, size_t datalen)
1451 {
1452 	struct sdmmc_softc *sc = sf->sc;
1453 	struct sdmmc_command cmd;
1454 	int error, bbuf, seg, off, len, num;
1455 
1456 	if (!ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE)) {
1457 		error = sdmmc_select_card(sc, sf);
1458 		if (error)
1459 			goto out;
1460 	}
1461 
1462 	bbuf = 0;
1463 	num = 0;
1464 	seg = off = len = 0;
1465 retry:
1466 	memset(&cmd, 0, sizeof(cmd));
1467 	cmd.c_data = data;
1468 	cmd.c_datalen = datalen;
1469 	cmd.c_blklen = SDMMC_SECTOR_SIZE;
1470 	cmd.c_opcode = (cmd.c_datalen / cmd.c_blklen) > 1 ?
1471 	    MMC_WRITE_BLOCK_MULTIPLE : MMC_WRITE_BLOCK_SINGLE;
1472 	cmd.c_arg = blkno;
1473 	if (!ISSET(sf->flags, SFF_SDHC))
1474 		cmd.c_arg <<= SDMMC_SECTOR_SIZE_SB;
1475 	cmd.c_flags = SCF_CMD_ADTC | SCF_RSP_R1;
1476 	if (ISSET(sc->sc_caps, SMC_CAPS_DMA)) {
1477 		cmd.c_dmamap = sc->sc_dmap;
1478 		if (!ISSET(sc->sc_caps, SMC_CAPS_MULTI_SEG_DMA)) {
1479 			len = sc->sc_dmap->dm_segs[seg].ds_len - off;
1480 			len &= ~(SDMMC_SECTOR_SIZE - 1);
1481 			cmd.c_datalen = len;
1482 			cmd.c_dmaseg = seg;
1483 			cmd.c_dmaoff = off;
1484 			bbuf = 0;
1485 			if (len == 0) {
1486 				/* Use bounce buffer */
1487 				bus_dmamap_sync(sc->sc_dmat, sc->sc_dmap, num,
1488 				    SDMMC_SECTOR_SIZE, BUS_DMASYNC_POSTWRITE);
1489 				memcpy(sf->bbuf, data, SDMMC_SECTOR_SIZE);
1490 				bus_dmamap_sync(sc->sc_dmat, sc->sc_dmap, num,
1491 				    SDMMC_SECTOR_SIZE, BUS_DMASYNC_PREWRITE);
1492 				bus_dmamap_sync(sc->sc_dmat, sf->bbuf_dmap, 0,
1493 				    SDMMC_SECTOR_SIZE, BUS_DMASYNC_PREWRITE);
1494 				cmd.c_datalen = SDMMC_SECTOR_SIZE;
1495 				cmd.c_dmamap = sf->bbuf_dmap;
1496 				cmd.c_dmaseg = 0;
1497 				cmd.c_dmaoff = 0;
1498 				bbuf = 1;
1499 				len = SDMMC_SECTOR_SIZE;
1500 			}
1501 			cmd.c_opcode = (cmd.c_datalen / cmd.c_blklen) > 1 ?
1502 			    MMC_WRITE_BLOCK_MULTIPLE : MMC_WRITE_BLOCK_SINGLE;
1503 		}
1504 	}
1505 
1506 	error = sdmmc_mmc_command(sc, &cmd);
1507 	if (error)
1508 		goto out;
1509 
1510 	if (!ISSET(sc->sc_caps, SMC_CAPS_AUTO_STOP)) {
1511 		if (cmd.c_opcode == MMC_WRITE_BLOCK_MULTIPLE) {
1512 			memset(&cmd, 0, sizeof(cmd));
1513 			cmd.c_opcode = MMC_STOP_TRANSMISSION;
1514 			cmd.c_flags = SCF_CMD_AC | SCF_RSP_R1B | SCF_RSP_SPI_R1B;
1515 			error = sdmmc_mmc_command(sc, &cmd);
1516 			if (error)
1517 				goto out;
1518 		}
1519 	}
1520 
1521 	if (!ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE)) {
1522 		do {
1523 			memset(&cmd, 0, sizeof(cmd));
1524 			cmd.c_opcode = MMC_SEND_STATUS;
1525 			if (!ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE))
1526 				cmd.c_arg = MMC_ARG_RCA(sf->rca);
1527 			cmd.c_flags = SCF_CMD_AC | SCF_RSP_R1 | SCF_RSP_SPI_R2;
1528 			error = sdmmc_mmc_command(sc, &cmd);
1529 			if (error)
1530 				break;
1531 			/* XXX time out */
1532 		} while (!ISSET(MMC_R1(cmd.c_resp), MMC_R1_READY_FOR_DATA));
1533 	}
1534 
1535 	if (ISSET(sc->sc_caps, SMC_CAPS_DMA) &&
1536 	    !ISSET(sc->sc_caps, SMC_CAPS_MULTI_SEG_DMA)) {
1537 		bus_dma_segment_t *dm_segs = sc->sc_dmap->dm_segs;
1538 
1539 		if (bbuf)
1540 			bus_dmamap_sync(sc->sc_dmat, sf->bbuf_dmap,
1541 			    0, SDMMC_SECTOR_SIZE, BUS_DMASYNC_POSTWRITE);
1542 		num += len;
1543 		data += len;
1544 		datalen -= len;
1545 		blkno += (len / SDMMC_SECTOR_SIZE);
1546 
1547 		while (off + len >= dm_segs[seg].ds_len) {
1548 			len -= dm_segs[seg++].ds_len;
1549 			off = 0;
1550 		}
1551 		off += len;
1552 
1553 		if (seg < sc->sc_dmap->dm_nsegs)
1554 			goto retry;
1555 	}
1556 
1557 out:
1558 	return error;
1559 }
1560 
1561 int
1562 sdmmc_mem_write_block(struct sdmmc_function *sf, uint32_t blkno, u_char *data,
1563     size_t datalen)
1564 {
1565 	struct sdmmc_softc *sc = sf->sc;
1566 	int error;
1567 
1568 	SDMMC_LOCK(sc);
1569 
1570 	if (sdmmc_chip_write_protect(sc->sc_sct, sc->sc_sch)) {
1571 		aprint_normal_dev(sc->sc_dev, "write-protected\n");
1572 		error = EIO;
1573 		goto out;
1574 	}
1575 
1576 	if (ISSET(sc->sc_caps, SMC_CAPS_SINGLE_ONLY)) {
1577 		error = sdmmc_mem_single_write_block(sf, blkno, data, datalen);
1578 		goto out;
1579 	}
1580 
1581 	if (!ISSET(sc->sc_caps, SMC_CAPS_DMA)) {
1582 		error = sdmmc_mem_write_block_subr(sf, blkno, data, datalen);
1583 		goto out;
1584 	}
1585 
1586 	/* DMA transfer */
1587 	error = bus_dmamap_load(sc->sc_dmat, sc->sc_dmap, data, datalen, NULL,
1588 	    BUS_DMA_NOWAIT|BUS_DMA_WRITE);
1589 	if (error)
1590 		goto out;
1591 
1592 #ifdef SDMMC_DEBUG
1593 	for (int i = 0; i < sc->sc_dmap->dm_nsegs; i++) {
1594 		printf("seg#%d: addr=%#lx, size=%#lx\n", i,
1595 		    (u_long)sc->sc_dmap->dm_segs[i].ds_addr,
1596 		    (u_long)sc->sc_dmap->dm_segs[i].ds_len);
1597 	}
1598 #endif
1599 
1600 	bus_dmamap_sync(sc->sc_dmat, sc->sc_dmap, 0, datalen,
1601 	    BUS_DMASYNC_PREWRITE);
1602 
1603 	error = sdmmc_mem_write_block_subr(sf, blkno, data, datalen);
1604 	if (error)
1605 		goto unload;
1606 
1607 	bus_dmamap_sync(sc->sc_dmat, sc->sc_dmap, 0, datalen,
1608 	    BUS_DMASYNC_POSTWRITE);
1609 unload:
1610 	bus_dmamap_unload(sc->sc_dmat, sc->sc_dmap);
1611 
1612 out:
1613 	SDMMC_UNLOCK(sc);
1614 
1615 	return error;
1616 }
1617