Home | History | Annotate | Line # | Download | only in sdmmc
sdmmc.c revision 1.19
      1 /*	$NetBSD: sdmmc.c,v 1.19 2012/12/22 20:21:09 jakllsch Exp $	*/
      2 /*	$OpenBSD: sdmmc.c,v 1.18 2009/01/09 10:58:38 jsg Exp $	*/
      3 
      4 /*
      5  * Copyright (c) 2006 Uwe Stuehler <uwe (at) 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 NONAKA Kimihiro <nonaka (at) 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 /*
     46  * Host controller independent SD/MMC bus driver based on information
     47  * from SanDisk SD Card Product Manual Revision 2.2 (SanDisk), SDIO
     48  * Simple Specification Version 1.0 (SDIO) and the Linux "mmc" driver.
     49  */
     50 
     51 #include <sys/cdefs.h>
     52 __KERNEL_RCSID(0, "$NetBSD: sdmmc.c,v 1.19 2012/12/22 20:21:09 jakllsch Exp $");
     53 
     54 #ifdef _KERNEL_OPT
     55 #include "opt_sdmmc.h"
     56 #endif
     57 
     58 #include <sys/param.h>
     59 #include <sys/device.h>
     60 #include <sys/kernel.h>
     61 #include <sys/kthread.h>
     62 #include <sys/malloc.h>
     63 #include <sys/proc.h>
     64 #include <sys/systm.h>
     65 #include <sys/callout.h>
     66 
     67 #include <machine/vmparam.h>
     68 
     69 #include <dev/sdmmc/sdmmc_ioreg.h>
     70 #include <dev/sdmmc/sdmmcchip.h>
     71 #include <dev/sdmmc/sdmmcreg.h>
     72 #include <dev/sdmmc/sdmmcvar.h>
     73 
     74 #ifdef SDMMC_DEBUG
     75 int sdmmcdebug = 1;
     76 static void sdmmc_dump_command(struct sdmmc_softc *, struct sdmmc_command *);
     77 #define DPRINTF(n,s)	do { if ((n) <= sdmmcdebug) printf s; } while (0)
     78 #else
     79 #define	DPRINTF(n,s)	do {} while (0)
     80 #endif
     81 
     82 #define	DEVNAME(sc)	SDMMCDEVNAME(sc)
     83 
     84 static int sdmmc_match(device_t, cfdata_t, void *);
     85 static void sdmmc_attach(device_t, device_t, void *);
     86 static int sdmmc_detach(device_t, int);
     87 
     88 CFATTACH_DECL_NEW(sdmmc, sizeof(struct sdmmc_softc),
     89     sdmmc_match, sdmmc_attach, sdmmc_detach, NULL);
     90 
     91 static void sdmmc_doattach(device_t);
     92 static void sdmmc_task_thread(void *);
     93 static void sdmmc_discover_task(void *);
     94 static void sdmmc_polling_card(void *);
     95 static void sdmmc_card_attach(struct sdmmc_softc *);
     96 static void sdmmc_card_detach(struct sdmmc_softc *, int);
     97 static int sdmmc_print(void *, const char *);
     98 static int sdmmc_enable(struct sdmmc_softc *);
     99 static void sdmmc_disable(struct sdmmc_softc *);
    100 static int sdmmc_scan(struct sdmmc_softc *);
    101 static int sdmmc_init(struct sdmmc_softc *);
    102 
    103 static int
    104 sdmmc_match(device_t parent, cfdata_t cf, void *aux)
    105 {
    106 	struct sdmmcbus_attach_args *saa = (struct sdmmcbus_attach_args *)aux;
    107 
    108 	if (strcmp(saa->saa_busname, cf->cf_name) == 0)
    109 		return 1;
    110 	return 0;
    111 }
    112 
    113 static void
    114 sdmmc_attach(device_t parent, device_t self, void *aux)
    115 {
    116 	struct sdmmc_softc *sc = device_private(self);
    117 	struct sdmmcbus_attach_args *saa = (struct sdmmcbus_attach_args *)aux;
    118 	int error;
    119 
    120 	aprint_normal("\n");
    121 	aprint_naive("\n");
    122 
    123 	sc->sc_dev = self;
    124 	sc->sc_sct = saa->saa_sct;
    125 	sc->sc_spi_sct = saa->saa_spi_sct;
    126 	sc->sc_sch = saa->saa_sch;
    127 	sc->sc_dmat = saa->saa_dmat;
    128 	sc->sc_clkmin = saa->saa_clkmin;
    129 	sc->sc_clkmax = saa->saa_clkmax;
    130 	sc->sc_busclk = sc->sc_clkmax;
    131 	sc->sc_buswidth = 1;
    132 	sc->sc_caps = saa->saa_caps;
    133 
    134 	if (ISSET(sc->sc_caps, SMC_CAPS_DMA)) {
    135 		error = bus_dmamap_create(sc->sc_dmat, MAXPHYS, SDMMC_MAXNSEGS,
    136 		    MAXPHYS, 0, BUS_DMA_NOWAIT|BUS_DMA_ALLOCNOW, &sc->sc_dmap);
    137 		if (error) {
    138 			aprint_error_dev(sc->sc_dev,
    139 			    "couldn't create dma map. (error=%d)\n", error);
    140 			return;
    141 		}
    142 	}
    143 
    144 	if (ISSET(sc->sc_caps, SMC_CAPS_POLL_CARD_DET)) {
    145 		callout_init(&sc->sc_card_detect_ch, 0);
    146 		callout_reset(&sc->sc_card_detect_ch, hz,
    147 		    sdmmc_polling_card, sc);
    148 	}
    149 
    150 	SIMPLEQ_INIT(&sc->sf_head);
    151 	TAILQ_INIT(&sc->sc_tskq);
    152 	TAILQ_INIT(&sc->sc_intrq);
    153 
    154 	sdmmc_init_task(&sc->sc_discover_task, sdmmc_discover_task, sc);
    155 	sdmmc_init_task(&sc->sc_intr_task, sdmmc_intr_task, sc);
    156 
    157 	mutex_init(&sc->sc_mtx, MUTEX_DEFAULT, IPL_SDMMC);
    158 	mutex_init(&sc->sc_tskq_mtx, MUTEX_DEFAULT, IPL_SDMMC);
    159 	mutex_init(&sc->sc_discover_task_mtx, MUTEX_DEFAULT, IPL_SDMMC);
    160 	mutex_init(&sc->sc_intr_task_mtx, MUTEX_DEFAULT, IPL_SDMMC);
    161 	cv_init(&sc->sc_tskq_cv, "mmctaskq");
    162 
    163 	if (!pmf_device_register(self, NULL, NULL)) {
    164 		aprint_error_dev(self, "couldn't establish power handler\n");
    165 	}
    166 
    167 	SET(sc->sc_flags, SMF_INITED);
    168 
    169 	/*
    170 	 * Create the event thread that will attach and detach cards
    171 	 * and perform other lengthy operations.
    172 	 */
    173 	config_pending_incr();
    174 	config_interrupts(self, sdmmc_doattach);
    175 }
    176 
    177 static int
    178 sdmmc_detach(device_t self, int flags)
    179 {
    180 	struct sdmmc_softc *sc = device_private(self);
    181 	int error;
    182 
    183 	mutex_enter(&sc->sc_tskq_mtx);
    184 	sc->sc_dying = 1;
    185 	cv_signal(&sc->sc_tskq_cv);
    186 	while (sc->sc_tskq_lwp != NULL)
    187 		cv_wait(&sc->sc_tskq_cv, &sc->sc_tskq_mtx);
    188 	mutex_exit(&sc->sc_tskq_mtx);
    189 
    190 	pmf_device_deregister(self);
    191 
    192 	error = config_detach_children(self, flags);
    193 	if (error)
    194 		return error;
    195 
    196 	if (ISSET(sc->sc_caps, SMC_CAPS_DMA)) {
    197 		bus_dmamap_unload(sc->sc_dmat, sc->sc_dmap);
    198 		bus_dmamap_destroy(sc->sc_dmat, sc->sc_dmap);
    199 	}
    200 
    201 	return 0;
    202 }
    203 
    204 static void
    205 sdmmc_doattach(device_t dev)
    206 {
    207 	struct sdmmc_softc *sc = device_private(dev);
    208 
    209 	if (kthread_create(PRI_NONE, KTHREAD_MPSAFE, NULL,
    210 	    sdmmc_task_thread, sc, &sc->sc_tskq_lwp, "%s", device_xname(dev))) {
    211 		aprint_error_dev(dev, "couldn't create task thread\n");
    212 	}
    213 }
    214 
    215 void
    216 sdmmc_add_task(struct sdmmc_softc *sc, struct sdmmc_task *task)
    217 {
    218 
    219 	mutex_enter(&sc->sc_tskq_mtx);
    220 	task->onqueue = 1;
    221 	task->sc = sc;
    222 	TAILQ_INSERT_TAIL(&sc->sc_tskq, task, next);
    223 	cv_broadcast(&sc->sc_tskq_cv);
    224 	mutex_exit(&sc->sc_tskq_mtx);
    225 }
    226 
    227 static inline void
    228 sdmmc_del_task1(struct sdmmc_softc *sc, struct sdmmc_task *task)
    229 {
    230 
    231 	TAILQ_REMOVE(&sc->sc_tskq, task, next);
    232 	task->sc = NULL;
    233 	task->onqueue = 0;
    234 }
    235 
    236 void
    237 sdmmc_del_task(struct sdmmc_task *task)
    238 {
    239 	struct sdmmc_softc *sc = (struct sdmmc_softc *)task->sc;
    240 
    241 	if (sc != NULL) {
    242 		mutex_enter(&sc->sc_tskq_mtx);
    243 		sdmmc_del_task1(sc, task);
    244 		mutex_exit(&sc->sc_tskq_mtx);
    245 	}
    246 }
    247 
    248 static void
    249 sdmmc_task_thread(void *arg)
    250 {
    251 	struct sdmmc_softc *sc = (struct sdmmc_softc *)arg;
    252 	struct sdmmc_task *task;
    253 
    254 	sdmmc_discover_task(sc);
    255 	config_pending_decr();
    256 
    257 	mutex_enter(&sc->sc_tskq_mtx);
    258 	for (;;) {
    259 		task = TAILQ_FIRST(&sc->sc_tskq);
    260 		if (task != NULL) {
    261 			sdmmc_del_task1(sc, task);
    262 			mutex_exit(&sc->sc_tskq_mtx);
    263 			(*task->func)(task->arg);
    264 			mutex_enter(&sc->sc_tskq_mtx);
    265 		} else {
    266 			/* Check for the exit condition. */
    267 			if (sc->sc_dying)
    268 				break;
    269 			cv_wait(&sc->sc_tskq_cv, &sc->sc_tskq_mtx);
    270 		}
    271 	}
    272 	/* time to die. */
    273 	sc->sc_dying = 0;
    274 	if (ISSET(sc->sc_flags, SMF_CARD_PRESENT))
    275 		sdmmc_card_detach(sc, DETACH_FORCE);
    276 	sc->sc_tskq_lwp = NULL;
    277 	cv_broadcast(&sc->sc_tskq_cv);
    278 	mutex_exit(&sc->sc_tskq_mtx);
    279 	kthread_exit(0);
    280 }
    281 
    282 void
    283 sdmmc_needs_discover(device_t dev)
    284 {
    285 	struct sdmmc_softc *sc = device_private(dev);
    286 
    287 	if (!ISSET(sc->sc_flags, SMF_INITED))
    288 		return;
    289 
    290 	mutex_enter(&sc->sc_discover_task_mtx);
    291 	if (!sdmmc_task_pending(&sc->sc_discover_task))
    292 		sdmmc_add_task(sc, &sc->sc_discover_task);
    293 	mutex_exit(&sc->sc_discover_task_mtx);
    294 }
    295 
    296 static void
    297 sdmmc_discover_task(void *arg)
    298 {
    299 	struct sdmmc_softc *sc = (struct sdmmc_softc *)arg;
    300 
    301 	if (sdmmc_chip_card_detect(sc->sc_sct, sc->sc_sch)) {
    302 		if (!ISSET(sc->sc_flags, SMF_CARD_PRESENT)) {
    303 			SET(sc->sc_flags, SMF_CARD_PRESENT);
    304 			sdmmc_card_attach(sc);
    305 			if (!ISSET(sc->sc_flags, SMF_CARD_ATTACHED))
    306 				CLR(sc->sc_flags, SMF_CARD_PRESENT);
    307 		}
    308 	} else {
    309 		if (ISSET(sc->sc_flags, SMF_CARD_PRESENT)) {
    310 			CLR(sc->sc_flags, SMF_CARD_PRESENT);
    311 			sdmmc_card_detach(sc, DETACH_FORCE);
    312 		}
    313 	}
    314 }
    315 
    316 static void
    317 sdmmc_polling_card(void *arg)
    318 {
    319 	struct sdmmc_softc *sc = (struct sdmmc_softc *)arg;
    320 	int card_detect;
    321 	int s;
    322 
    323 	s = splsdmmc();
    324 	card_detect = sdmmc_chip_card_detect(sc->sc_sct, sc->sc_sch);
    325 	if (card_detect) {
    326 		if (!ISSET(sc->sc_flags, SMF_CARD_PRESENT)) {
    327 			sdmmc_needs_discover(sc->sc_dev);
    328 		}
    329 	} else {
    330 		if (ISSET(sc->sc_flags, SMF_CARD_PRESENT)) {
    331 			sdmmc_needs_discover(sc->sc_dev);
    332 		}
    333 	}
    334 	splx(s);
    335 
    336 	callout_schedule(&sc->sc_card_detect_ch, hz);
    337 }
    338 
    339 /*
    340  * Called from process context when a card is present.
    341  */
    342 static void
    343 sdmmc_card_attach(struct sdmmc_softc *sc)
    344 {
    345 	struct sdmmc_function *sf;
    346 	struct sdmmc_attach_args saa;
    347 	int error;
    348 
    349 	DPRINTF(1,("%s: attach card\n", DEVNAME(sc)));
    350 
    351 	CLR(sc->sc_flags, SMF_CARD_ATTACHED);
    352 
    353 	/*
    354 	 * Power up the card (or card stack).
    355 	 */
    356 	error = sdmmc_enable(sc);
    357 	if (error) {
    358 		if (!ISSET(sc->sc_caps, SMC_CAPS_POLL_CARD_DET)) {
    359 			aprint_error_dev(sc->sc_dev, "couldn't enable card: %d\n", error);
    360 		}
    361 		goto err;
    362 	}
    363 
    364 	/*
    365 	 * Scan for I/O functions and memory cards on the bus,
    366 	 * allocating a sdmmc_function structure for each.
    367 	 */
    368 	error = sdmmc_scan(sc);
    369 	if (error) {
    370 		aprint_error_dev(sc->sc_dev, "no functions\n");
    371 		goto err;
    372 	}
    373 
    374 	/*
    375 	 * Initialize the I/O functions and memory cards.
    376 	 */
    377 	error = sdmmc_init(sc);
    378 	if (error) {
    379 		aprint_error_dev(sc->sc_dev, "init failed\n");
    380 		goto err;
    381 	}
    382 
    383 	SIMPLEQ_FOREACH(sf, &sc->sf_head, sf_list) {
    384 		if (ISSET(sc->sc_flags, SMF_IO_MODE) && sf->number < 1)
    385 			continue;
    386 
    387 		memset(&saa, 0, sizeof saa);
    388 		saa.manufacturer = sf->cis.manufacturer;
    389 		saa.product = sf->cis.product;
    390 		saa.interface = sf->interface;
    391 		saa.sf = sf;
    392 
    393 		sf->child =
    394 		    config_found_ia(sc->sc_dev, "sdmmc", &saa, sdmmc_print);
    395 	}
    396 
    397 	SET(sc->sc_flags, SMF_CARD_ATTACHED);
    398 	return;
    399 
    400 err:
    401 	sdmmc_card_detach(sc, DETACH_FORCE);
    402 }
    403 
    404 /*
    405  * Called from process context with DETACH_* flags from <sys/device.h>
    406  * when cards are gone.
    407  */
    408 static void
    409 sdmmc_card_detach(struct sdmmc_softc *sc, int flags)
    410 {
    411 	struct sdmmc_function *sf, *sfnext;
    412 
    413 	DPRINTF(1,("%s: detach card\n", DEVNAME(sc)));
    414 
    415 	if (ISSET(sc->sc_flags, SMF_CARD_ATTACHED)) {
    416 		SIMPLEQ_FOREACH(sf, &sc->sf_head, sf_list) {
    417 			if (sf->child != NULL) {
    418 				config_detach(sf->child, DETACH_FORCE);
    419 				sf->child = NULL;
    420 			}
    421 		}
    422 
    423 		KASSERT(TAILQ_EMPTY(&sc->sc_intrq));
    424 
    425 		CLR(sc->sc_flags, SMF_CARD_ATTACHED);
    426 	}
    427 
    428 	/* Power down. */
    429 	sdmmc_disable(sc);
    430 
    431 	/* Free all sdmmc_function structures. */
    432 	for (sf = SIMPLEQ_FIRST(&sc->sf_head); sf != NULL; sf = sfnext) {
    433 		sfnext = SIMPLEQ_NEXT(sf, sf_list);
    434 		sdmmc_function_free(sf);
    435 	}
    436 	SIMPLEQ_INIT(&sc->sf_head);
    437 	sc->sc_function_count = 0;
    438 	sc->sc_fn0 = NULL;
    439 }
    440 
    441 static int
    442 sdmmc_print(void *aux, const char *pnp)
    443 {
    444 	struct sdmmc_attach_args *sa = aux;
    445 	struct sdmmc_function *sf = sa->sf;
    446 	struct sdmmc_cis *cis = &sf->sc->sc_fn0->cis;
    447 	int i, x;
    448 
    449 	if (pnp) {
    450 		if (sf->number == 0)
    451 			return QUIET;
    452 
    453 		for (i = 0; i < 4 && cis->cis1_info[i]; i++)
    454 			printf("%s%s", i ? ", " : "\"", cis->cis1_info[i]);
    455 		if (i != 0)
    456 			printf("\"");
    457 
    458 		if ((cis->manufacturer != SDMMC_VENDOR_INVALID &&
    459 		    cis->product != SDMMC_PRODUCT_INVALID) ||
    460 		    sa->interface != SD_IO_SFIC_NO_STANDARD) {
    461 			x = !!(cis->manufacturer != SDMMC_VENDOR_INVALID);
    462 			x += !!(cis->product != SDMMC_PRODUCT_INVALID);
    463 			x += !!(sa->interface != SD_IO_SFIC_NO_STANDARD);
    464 			printf("%s(", i ? " " : "");
    465 			if (cis->manufacturer != SDMMC_VENDOR_INVALID)
    466 				printf("manufacturer 0x%x%s",
    467 				    cis->manufacturer, (--x == 0) ?  "" : ", ");
    468 			if (cis->product != SDMMC_PRODUCT_INVALID)
    469 				printf("product 0x%x%s",
    470 				    cis->product, (--x == 0) ?  "" : ", ");
    471 			if (sa->interface != SD_IO_SFIC_NO_STANDARD)
    472 				printf("standard function interface code 0x%x",
    473 				    sf->interface);
    474 			printf(")");
    475 		}
    476 		printf("%sat %s", i ? " " : "", pnp);
    477 	}
    478 	if (sf->number > 0)
    479 		printf(" function %d", sf->number);
    480 
    481 	if (!pnp) {
    482 		for (i = 0; i < 3 && cis->cis1_info[i]; i++)
    483 			printf("%s%s", i ? ", " : " \"", cis->cis1_info[i]);
    484 		if (i != 0)
    485 			printf("\"");
    486 	}
    487 	return UNCONF;
    488 }
    489 
    490 static int
    491 sdmmc_enable(struct sdmmc_softc *sc)
    492 {
    493 	int error;
    494 
    495 	/*
    496 	 * Calculate the equivalent of the card OCR from the host
    497 	 * capabilities and select the maximum supported bus voltage.
    498 	 */
    499 	error = sdmmc_chip_bus_power(sc->sc_sct, sc->sc_sch,
    500 	    sdmmc_chip_host_ocr(sc->sc_sct, sc->sc_sch));
    501 	if (error) {
    502 		aprint_error_dev(sc->sc_dev, "couldn't supply bus power\n");
    503 		goto out;
    504 	}
    505 
    506 	/*
    507 	 * Select the minimum clock frequency.
    508 	 */
    509 	error = sdmmc_chip_bus_clock(sc->sc_sct, sc->sc_sch, SDMMC_SDCLK_400K);
    510 	if (error) {
    511 		aprint_error_dev(sc->sc_dev, "couldn't supply clock\n");
    512 		goto out;
    513 	}
    514 
    515 	/* XXX wait for card to power up */
    516 	sdmmc_delay(100000);
    517 
    518 	if (!ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE)) {
    519 		/* Initialize SD I/O card function(s). */
    520 		error = sdmmc_io_enable(sc);
    521 		if (error) {
    522 			DPRINTF(1, ("%s: sdmmc_io_enable failed %d\n", DEVNAME(sc), error));
    523 			goto out;
    524 		}
    525 	}
    526 
    527 	/* Initialize SD/MMC memory card(s). */
    528 	if (ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE) ||
    529 	    ISSET(sc->sc_flags, SMF_MEM_MODE)) {
    530 		error = sdmmc_mem_enable(sc);
    531 		if (error) {
    532 			DPRINTF(1, ("%s: sdmmc_mem_enable failed %d\n", DEVNAME(sc), error));
    533 			goto out;
    534 		}
    535 	}
    536 
    537 out:
    538 	if (error)
    539 		sdmmc_disable(sc);
    540 	return error;
    541 }
    542 
    543 static void
    544 sdmmc_disable(struct sdmmc_softc *sc)
    545 {
    546 	/* XXX complete commands if card is still present. */
    547 
    548 	if (!ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE)) {
    549 		/* Make sure no card is still selected. */
    550 		(void)sdmmc_select_card(sc, NULL);
    551 	}
    552 
    553 	/* Turn off bus power and clock. */
    554 	(void)sdmmc_chip_bus_width(sc->sc_sct, sc->sc_sch, 1);
    555 	(void)sdmmc_chip_bus_clock(sc->sc_sct, sc->sc_sch, SDMMC_SDCLK_OFF);
    556 	(void)sdmmc_chip_bus_power(sc->sc_sct, sc->sc_sch, 0);
    557 	sc->sc_busclk = sc->sc_clkmax;
    558 }
    559 
    560 /*
    561  * Set the lowest bus voltage supported by the card and the host.
    562  */
    563 int
    564 sdmmc_set_bus_power(struct sdmmc_softc *sc, uint32_t host_ocr,
    565     uint32_t card_ocr)
    566 {
    567 	uint32_t bit;
    568 
    569 	/* Mask off unsupported voltage levels and select the lowest. */
    570 	DPRINTF(1,("%s: host_ocr=%x ", DEVNAME(sc), host_ocr));
    571 	host_ocr &= card_ocr;
    572 	for (bit = 4; bit < 23; bit++) {
    573 		if (ISSET(host_ocr, (1 << bit))) {
    574 			host_ocr &= (3 << bit);
    575 			break;
    576 		}
    577 	}
    578 	DPRINTF(1,("card_ocr=%x new_ocr=%x\n", card_ocr, host_ocr));
    579 
    580 	if (host_ocr == 0 ||
    581 	    sdmmc_chip_bus_power(sc->sc_sct, sc->sc_sch, host_ocr) != 0)
    582 		return 1;
    583 	return 0;
    584 }
    585 
    586 struct sdmmc_function *
    587 sdmmc_function_alloc(struct sdmmc_softc *sc)
    588 {
    589 	struct sdmmc_function *sf;
    590 
    591 	sf = malloc(sizeof *sf, M_DEVBUF, M_WAITOK|M_ZERO);
    592 	if (sf == NULL) {
    593 		aprint_error_dev(sc->sc_dev,
    594 		    "couldn't alloc memory (sdmmc function)\n");
    595 		return NULL;
    596 	}
    597 
    598 	sf->sc = sc;
    599 	sf->number = -1;
    600 	sf->cis.manufacturer = SDMMC_VENDOR_INVALID;
    601 	sf->cis.product = SDMMC_PRODUCT_INVALID;
    602 	sf->cis.function = SDMMC_FUNCTION_INVALID;
    603 	sf->width = 1;
    604 
    605 	if (ISSET(sc->sc_flags, SMF_MEM_MODE) &&
    606 	    ISSET(sc->sc_caps, SMC_CAPS_DMA) &&
    607 	    !ISSET(sc->sc_caps, SMC_CAPS_MULTI_SEG_DMA)) {
    608 		bus_dma_segment_t ds;
    609 		int rseg, error;
    610 
    611 		error = bus_dmamap_create(sc->sc_dmat, SDMMC_SECTOR_SIZE, 1,
    612 		    SDMMC_SECTOR_SIZE, 0, BUS_DMA_WAITOK, &sf->bbuf_dmap);
    613 		if (error)
    614 			goto fail1;
    615 		error = bus_dmamem_alloc(sc->sc_dmat, SDMMC_SECTOR_SIZE,
    616 		    PAGE_SIZE, 0, &ds, 1, &rseg, BUS_DMA_WAITOK);
    617 		if (error)
    618 			goto fail2;
    619 		error = bus_dmamem_map(sc->sc_dmat, &ds, 1, SDMMC_SECTOR_SIZE,
    620 		    &sf->bbuf, BUS_DMA_WAITOK);
    621 		if (error)
    622 			goto fail3;
    623 		error = bus_dmamap_load(sc->sc_dmat, sf->bbuf_dmap,
    624 		    sf->bbuf, SDMMC_SECTOR_SIZE, NULL,
    625 		    BUS_DMA_WAITOK|BUS_DMA_READ|BUS_DMA_WRITE);
    626 		if (!error)
    627 			goto out;
    628 
    629 		bus_dmamem_unmap(sc->sc_dmat, sf->bbuf, SDMMC_SECTOR_SIZE);
    630 fail3:
    631 		bus_dmamem_free(sc->sc_dmat, &ds, 1);
    632 fail2:
    633 		bus_dmamap_destroy(sc->sc_dmat, sf->bbuf_dmap);
    634 fail1:
    635 		free(sf, M_DEVBUF);
    636 		sf = NULL;
    637 	}
    638 out:
    639 
    640 	return sf;
    641 }
    642 
    643 void
    644 sdmmc_function_free(struct sdmmc_function *sf)
    645 {
    646 	struct sdmmc_softc *sc = sf->sc;
    647 
    648 	if (ISSET(sc->sc_flags, SMF_MEM_MODE) &&
    649 	    ISSET(sc->sc_caps, SMC_CAPS_DMA) &&
    650 	    !ISSET(sc->sc_caps, SMC_CAPS_MULTI_SEG_DMA)) {
    651 		bus_dmamap_unload(sc->sc_dmat, sf->bbuf_dmap);
    652 		bus_dmamem_unmap(sc->sc_dmat, sf->bbuf, SDMMC_SECTOR_SIZE);
    653 		bus_dmamem_free(sc->sc_dmat,
    654 		    sf->bbuf_dmap->dm_segs, sf->bbuf_dmap->dm_nsegs);
    655 		bus_dmamap_destroy(sc->sc_dmat, sf->bbuf_dmap);
    656 	}
    657 
    658 	free(sf, M_DEVBUF);
    659 }
    660 
    661 /*
    662  * Scan for I/O functions and memory cards on the bus, allocating a
    663  * sdmmc_function structure for each.
    664  */
    665 static int
    666 sdmmc_scan(struct sdmmc_softc *sc)
    667 {
    668 
    669 	if (!ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE)) {
    670 		/* Scan for I/O functions. */
    671 		if (ISSET(sc->sc_flags, SMF_IO_MODE))
    672 			sdmmc_io_scan(sc);
    673 	}
    674 
    675 	/* Scan for memory cards on the bus. */
    676 	if (ISSET(sc->sc_flags, SMF_MEM_MODE))
    677 		sdmmc_mem_scan(sc);
    678 
    679 	/* There should be at least one function now. */
    680 	if (SIMPLEQ_EMPTY(&sc->sf_head)) {
    681 		aprint_error_dev(sc->sc_dev, "couldn't identify card\n");
    682 		return 1;
    683 	}
    684 	return 0;
    685 }
    686 
    687 /*
    688  * Initialize all the distinguished functions of the card, be it I/O
    689  * or memory functions.
    690  */
    691 static int
    692 sdmmc_init(struct sdmmc_softc *sc)
    693 {
    694 	struct sdmmc_function *sf;
    695 
    696 	/* Initialize all identified card functions. */
    697 	SIMPLEQ_FOREACH(sf, &sc->sf_head, sf_list) {
    698 		if (!ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE)) {
    699 			if (ISSET(sc->sc_flags, SMF_IO_MODE) &&
    700 			    sdmmc_io_init(sc, sf) != 0) {
    701 				aprint_error_dev(sc->sc_dev,
    702 				    "i/o init failed\n");
    703 			}
    704 		}
    705 
    706 		if (ISSET(sc->sc_flags, SMF_MEM_MODE) &&
    707 		    sdmmc_mem_init(sc, sf) != 0) {
    708 			aprint_error_dev(sc->sc_dev, "mem init failed\n");
    709 		}
    710 	}
    711 
    712 	/* Any good functions left after initialization? */
    713 	SIMPLEQ_FOREACH(sf, &sc->sf_head, sf_list) {
    714 		if (!ISSET(sf->flags, SFF_ERROR))
    715 			return 0;
    716 	}
    717 
    718 	/* No, we should probably power down the card. */
    719 	return 1;
    720 }
    721 
    722 void
    723 sdmmc_delay(u_int usecs)
    724 {
    725 
    726 	delay(usecs);
    727 }
    728 
    729 int
    730 sdmmc_app_command(struct sdmmc_softc *sc, struct sdmmc_function *sf, struct sdmmc_command *cmd)
    731 {
    732 	struct sdmmc_command acmd;
    733 	int error;
    734 
    735 	DPRINTF(1,("sdmmc_app_command: start\n"));
    736 
    737 	/* Don't lock */
    738 
    739 	memset(&acmd, 0, sizeof(acmd));
    740 	acmd.c_opcode = MMC_APP_CMD;
    741 	if (sf != NULL) {
    742 		acmd.c_arg = sf->rca << 16;
    743 		acmd.c_flags = SCF_CMD_AC | SCF_RSP_R1 | SCF_RSP_SPI_R1;
    744 	} else {
    745 		acmd.c_arg = 0;
    746 		acmd.c_flags = SCF_CMD_BCR | SCF_RSP_R1 | SCF_RSP_SPI_R1;
    747 	}
    748 
    749 	error = sdmmc_mmc_command(sc, &acmd);
    750 	if (error == 0) {
    751 		if (!ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE) &&
    752 		    !ISSET(MMC_R1(acmd.c_resp), MMC_R1_APP_CMD)) {
    753 			/* Card does not support application commands. */
    754 			error = ENODEV;
    755 		} else {
    756 			error = sdmmc_mmc_command(sc, cmd);
    757 		}
    758 	}
    759 	DPRINTF(1,("sdmmc_app_command: done (error=%d)\n", error));
    760 	return error;
    761 }
    762 
    763 /*
    764  * Execute MMC command and data transfers.  All interactions with the
    765  * host controller to complete the command happen in the context of
    766  * the current process.
    767  */
    768 int
    769 sdmmc_mmc_command(struct sdmmc_softc *sc, struct sdmmc_command *cmd)
    770 {
    771 	int error;
    772 
    773 	DPRINTF(1,("sdmmc_mmc_command: cmd=%d, arg=%#x, flags=%#x\n",
    774 	    cmd->c_opcode, cmd->c_arg, cmd->c_flags));
    775 
    776 	/* Don't lock */
    777 
    778 #if defined(DIAGNOSTIC) || defined(SDMMC_DEBUG)
    779 	if (cmd->c_data && !ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE)) {
    780 		if (sc->sc_card == NULL)
    781 			panic("%s: deselected card\n", DEVNAME(sc));
    782 	}
    783 #endif
    784 
    785 	sdmmc_chip_exec_command(sc->sc_sct, sc->sc_sch, cmd);
    786 
    787 #ifdef SDMMC_DEBUG
    788 	sdmmc_dump_command(sc, cmd);
    789 #endif
    790 
    791 	error = cmd->c_error;
    792 
    793 	DPRINTF(1,("sdmmc_mmc_command: error=%d\n", error));
    794 
    795 	return error;
    796 }
    797 
    798 /*
    799  * Send the "GO IDLE STATE" command.
    800  */
    801 void
    802 sdmmc_go_idle_state(struct sdmmc_softc *sc)
    803 {
    804 	struct sdmmc_command cmd;
    805 
    806 	DPRINTF(1,("sdmmc_go_idle_state\n"));
    807 
    808 	/* Don't lock */
    809 
    810 	memset(&cmd, 0, sizeof(cmd));
    811 	cmd.c_opcode = MMC_GO_IDLE_STATE;
    812 	cmd.c_flags = SCF_CMD_BC | SCF_RSP_R0 | SCF_RSP_SPI_R1;
    813 
    814 	(void)sdmmc_mmc_command(sc, &cmd);
    815 }
    816 
    817 /*
    818  * Retrieve (SD) or set (MMC) the relative card address (RCA).
    819  */
    820 int
    821 sdmmc_set_relative_addr(struct sdmmc_softc *sc, struct sdmmc_function *sf)
    822 {
    823 	struct sdmmc_command cmd;
    824 	int error;
    825 
    826 	/* Don't lock */
    827 
    828 	if (ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE))
    829 		return EIO;
    830 
    831 	memset(&cmd, 0, sizeof(cmd));
    832 	if (ISSET(sc->sc_flags, SMF_SD_MODE)) {
    833 		cmd.c_opcode = SD_SEND_RELATIVE_ADDR;
    834 		cmd.c_flags = SCF_CMD_BCR | SCF_RSP_R6;
    835 	} else {
    836 		cmd.c_opcode = MMC_SET_RELATIVE_ADDR;
    837 		cmd.c_arg = MMC_ARG_RCA(sf->rca);
    838 		cmd.c_flags = SCF_CMD_AC | SCF_RSP_R1;
    839 	}
    840 	error = sdmmc_mmc_command(sc, &cmd);
    841 	if (error)
    842 		return error;
    843 
    844 	if (ISSET(sc->sc_flags, SMF_SD_MODE))
    845 		sf->rca = SD_R6_RCA(cmd.c_resp);
    846 
    847 	return 0;
    848 }
    849 
    850 int
    851 sdmmc_select_card(struct sdmmc_softc *sc, struct sdmmc_function *sf)
    852 {
    853 	struct sdmmc_command cmd;
    854 	int error;
    855 
    856 	/* Don't lock */
    857 
    858 	if (ISSET(sc->sc_caps, SMC_CAPS_SPI_MODE))
    859 		return EIO;
    860 
    861 	if (sc->sc_card == sf
    862 	 || (sf && sc->sc_card && sc->sc_card->rca == sf->rca)) {
    863 		sc->sc_card = sf;
    864 		return 0;
    865 	}
    866 
    867 	memset(&cmd, 0, sizeof(cmd));
    868 	cmd.c_opcode = MMC_SELECT_CARD;
    869 	cmd.c_arg = (sf == NULL) ? 0 : MMC_ARG_RCA(sf->rca);
    870 	cmd.c_flags = SCF_CMD_AC | ((sf == NULL) ? SCF_RSP_R0 : SCF_RSP_R1);
    871 	error = sdmmc_mmc_command(sc, &cmd);
    872 	if (error == 0 || sf == NULL)
    873 		sc->sc_card = sf;
    874 
    875 	return error;
    876 }
    877 
    878 #ifdef SDMMC_DEBUG
    879 static void
    880 sdmmc_dump_command(struct sdmmc_softc *sc, struct sdmmc_command *cmd)
    881 {
    882 	int i;
    883 
    884 	DPRINTF(1,("%s: cmd %u arg=%#x data=%p dlen=%d flags=%#x (error %d)\n",
    885 	    DEVNAME(sc), cmd->c_opcode, cmd->c_arg, cmd->c_data,
    886 	    cmd->c_datalen, cmd->c_flags, cmd->c_error));
    887 
    888 	if (cmd->c_error || sdmmcdebug < 1)
    889 		return;
    890 
    891 	aprint_normal_dev(sc->sc_dev, "resp=");
    892 	if (ISSET(cmd->c_flags, SCF_RSP_136))
    893 		for (i = 0; i < sizeof cmd->c_resp; i++)
    894 			aprint_normal("%02x ", ((uint8_t *)cmd->c_resp)[i]);
    895 	else if (ISSET(cmd->c_flags, SCF_RSP_PRESENT))
    896 		for (i = 0; i < 4; i++)
    897 			aprint_normal("%02x ", ((uint8_t *)cmd->c_resp)[i]);
    898 	else
    899 		aprint_normal("none");
    900 	aprint_normal("\n");
    901 }
    902 
    903 void
    904 sdmmc_dump_data(const char *title, void *ptr, size_t size)
    905 {
    906 	char buf[16];
    907 	uint8_t *p = ptr;
    908 	int i, j;
    909 
    910 	printf("sdmmc_dump_data: %s\n", title ? title : "");
    911 	printf("--------+--------------------------------------------------+------------------+\n");
    912 	printf("offset  | +0 +1 +2 +3 +4 +5 +6 +7  +8 +9 +a +b +c +d +e +f | data             |\n");
    913 	printf("--------+--------------------------------------------------+------------------+\n");
    914 	for (i = 0; i < (int)size; i++) {
    915 		if ((i % 16) == 0) {
    916 			printf("%08x| ", i);
    917 		} else if ((i % 16) == 8) {
    918 			printf(" ");
    919 		}
    920 
    921 		printf("%02x ", p[i]);
    922 		buf[i % 16] = p[i];
    923 
    924 		if ((i % 16) == 15) {
    925 			printf("| ");
    926 			for (j = 0; j < 16; j++) {
    927 				if (buf[j] >= 0x20 && buf[j] <= 0x7e) {
    928 					printf("%c", buf[j]);
    929 				} else {
    930 					printf(".");
    931 				}
    932 			}
    933 			printf(" |\n");
    934 		}
    935 	}
    936 	if ((i % 16) != 0) {
    937 		j = (i % 16);
    938 		for (; j < 16; j++) {
    939 			printf("   ");
    940 			if ((j % 16) == 8) {
    941 				printf(" ");
    942 			}
    943 		}
    944 
    945 		printf("| ");
    946 		for (j = 0; j < (i % 16); j++) {
    947 			if (buf[j] >= 0x20 && buf[j] <= 0x7e) {
    948 				printf("%c", buf[j]);
    949 			} else {
    950 				printf(".");
    951 			}
    952 		}
    953 		for (; j < 16; j++) {
    954 			printf(" ");
    955 		}
    956 		printf(" |\n");
    957 	}
    958 	printf("--------+--------------------------------------------------+------------------+\n");
    959 }
    960 #endif
    961