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