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