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