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