xref: /freebsd/sys/dev/sdhci/sdhci.c (revision ec273ebf3b6aed5fba8c56b6ece5ad8693a48ea7)
1 /*-
2  * Copyright (c) 2008 Alexander Motin <mav@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25 
26 #include <sys/cdefs.h>
27 __FBSDID("$FreeBSD$");
28 
29 #include <sys/param.h>
30 #include <sys/systm.h>
31 #include <sys/bus.h>
32 #include <sys/callout.h>
33 #include <sys/conf.h>
34 #include <sys/kernel.h>
35 #include <sys/lock.h>
36 #include <sys/module.h>
37 #include <sys/mutex.h>
38 #include <sys/resource.h>
39 #include <sys/rman.h>
40 #include <sys/sysctl.h>
41 #include <sys/taskqueue.h>
42 
43 #include <machine/bus.h>
44 #include <machine/resource.h>
45 #include <machine/stdarg.h>
46 
47 #include <dev/mmc/bridge.h>
48 #include <dev/mmc/mmcreg.h>
49 #include <dev/mmc/mmcbrvar.h>
50 
51 #include "mmcbr_if.h"
52 #include "sdhci.h"
53 #include "sdhci_if.h"
54 
55 SYSCTL_NODE(_hw, OID_AUTO, sdhci, CTLFLAG_RD, 0, "sdhci driver");
56 
57 static int sdhci_debug;
58 SYSCTL_INT(_hw_sdhci, OID_AUTO, debug, CTLFLAG_RWTUN, &sdhci_debug, 0, "Debug level");
59 
60 #define RD1(slot, off)	SDHCI_READ_1((slot)->bus, (slot), (off))
61 #define RD2(slot, off)	SDHCI_READ_2((slot)->bus, (slot), (off))
62 #define RD4(slot, off)	SDHCI_READ_4((slot)->bus, (slot), (off))
63 #define RD_MULTI_4(slot, off, ptr, count)	\
64     SDHCI_READ_MULTI_4((slot)->bus, (slot), (off), (ptr), (count))
65 
66 #define WR1(slot, off, val)	SDHCI_WRITE_1((slot)->bus, (slot), (off), (val))
67 #define WR2(slot, off, val)	SDHCI_WRITE_2((slot)->bus, (slot), (off), (val))
68 #define WR4(slot, off, val)	SDHCI_WRITE_4((slot)->bus, (slot), (off), (val))
69 #define WR_MULTI_4(slot, off, ptr, count)	\
70     SDHCI_WRITE_MULTI_4((slot)->bus, (slot), (off), (ptr), (count))
71 
72 static void sdhci_set_clock(struct sdhci_slot *slot, uint32_t clock);
73 static void sdhci_start(struct sdhci_slot *slot);
74 static void sdhci_start_data(struct sdhci_slot *slot, struct mmc_data *data);
75 
76 static void sdhci_card_task(void *, int);
77 
78 /* helper routines */
79 #define SDHCI_LOCK(_slot)		mtx_lock(&(_slot)->mtx)
80 #define	SDHCI_UNLOCK(_slot)		mtx_unlock(&(_slot)->mtx)
81 #define SDHCI_LOCK_INIT(_slot) \
82 	mtx_init(&_slot->mtx, "SD slot mtx", "sdhci", MTX_DEF)
83 #define SDHCI_LOCK_DESTROY(_slot)	mtx_destroy(&_slot->mtx);
84 #define SDHCI_ASSERT_LOCKED(_slot)	mtx_assert(&_slot->mtx, MA_OWNED);
85 #define SDHCI_ASSERT_UNLOCKED(_slot)	mtx_assert(&_slot->mtx, MA_NOTOWNED);
86 
87 #define	SDHCI_DEFAULT_MAX_FREQ	50
88 
89 #define	SDHCI_200_MAX_DIVIDER	256
90 #define	SDHCI_300_MAX_DIVIDER	2046
91 
92 static void
93 sdhci_getaddr(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
94 {
95 	if (error != 0) {
96 		printf("getaddr: error %d\n", error);
97 		return;
98 	}
99 	*(bus_addr_t *)arg = segs[0].ds_addr;
100 }
101 
102 static int
103 slot_printf(struct sdhci_slot *slot, const char * fmt, ...)
104 {
105 	va_list ap;
106 	int retval;
107 
108     	retval = printf("%s-slot%d: ",
109 	    device_get_nameunit(slot->bus), slot->num);
110 
111 	va_start(ap, fmt);
112 	retval += vprintf(fmt, ap);
113 	va_end(ap);
114 	return (retval);
115 }
116 
117 static void
118 sdhci_dumpregs(struct sdhci_slot *slot)
119 {
120 	slot_printf(slot,
121 	    "============== REGISTER DUMP ==============\n");
122 
123 	slot_printf(slot, "Sys addr: 0x%08x | Version:  0x%08x\n",
124 	    RD4(slot, SDHCI_DMA_ADDRESS), RD2(slot, SDHCI_HOST_VERSION));
125 	slot_printf(slot, "Blk size: 0x%08x | Blk cnt:  0x%08x\n",
126 	    RD2(slot, SDHCI_BLOCK_SIZE), RD2(slot, SDHCI_BLOCK_COUNT));
127 	slot_printf(slot, "Argument: 0x%08x | Trn mode: 0x%08x\n",
128 	    RD4(slot, SDHCI_ARGUMENT), RD2(slot, SDHCI_TRANSFER_MODE));
129 	slot_printf(slot, "Present:  0x%08x | Host ctl: 0x%08x\n",
130 	    RD4(slot, SDHCI_PRESENT_STATE), RD1(slot, SDHCI_HOST_CONTROL));
131 	slot_printf(slot, "Power:    0x%08x | Blk gap:  0x%08x\n",
132 	    RD1(slot, SDHCI_POWER_CONTROL), RD1(slot, SDHCI_BLOCK_GAP_CONTROL));
133 	slot_printf(slot, "Wake-up:  0x%08x | Clock:    0x%08x\n",
134 	    RD1(slot, SDHCI_WAKE_UP_CONTROL), RD2(slot, SDHCI_CLOCK_CONTROL));
135 	slot_printf(slot, "Timeout:  0x%08x | Int stat: 0x%08x\n",
136 	    RD1(slot, SDHCI_TIMEOUT_CONTROL), RD4(slot, SDHCI_INT_STATUS));
137 	slot_printf(slot, "Int enab: 0x%08x | Sig enab: 0x%08x\n",
138 	    RD4(slot, SDHCI_INT_ENABLE), RD4(slot, SDHCI_SIGNAL_ENABLE));
139 	slot_printf(slot, "AC12 err: 0x%08x | Slot int: 0x%08x\n",
140 	    RD2(slot, SDHCI_ACMD12_ERR), RD2(slot, SDHCI_SLOT_INT_STATUS));
141 	slot_printf(slot, "Caps:     0x%08x | Max curr: 0x%08x\n",
142 	    RD4(slot, SDHCI_CAPABILITIES), RD4(slot, SDHCI_MAX_CURRENT));
143 
144 	slot_printf(slot,
145 	    "===========================================\n");
146 }
147 
148 static void
149 sdhci_reset(struct sdhci_slot *slot, uint8_t mask)
150 {
151 	int timeout;
152 
153 	if (slot->quirks & SDHCI_QUIRK_NO_CARD_NO_RESET) {
154 		if (!(RD4(slot, SDHCI_PRESENT_STATE) &
155 			SDHCI_CARD_PRESENT))
156 			return;
157 	}
158 
159 	/* Some controllers need this kick or reset won't work. */
160 	if ((mask & SDHCI_RESET_ALL) == 0 &&
161 	    (slot->quirks & SDHCI_QUIRK_CLOCK_BEFORE_RESET)) {
162 		uint32_t clock;
163 
164 		/* This is to force an update */
165 		clock = slot->clock;
166 		slot->clock = 0;
167 		sdhci_set_clock(slot, clock);
168 	}
169 
170 	if (mask & SDHCI_RESET_ALL) {
171 		slot->clock = 0;
172 		slot->power = 0;
173 	}
174 
175 	WR1(slot, SDHCI_SOFTWARE_RESET, mask);
176 
177 	if (slot->quirks & SDHCI_QUIRK_WAITFOR_RESET_ASSERTED) {
178 		/*
179 		 * Resets on TI OMAPs and AM335x are incompatible with SDHCI
180 		 * specification.  The reset bit has internal propagation delay,
181 		 * so a fast read after write returns 0 even if reset process is
182 		 * in progress. The workaround is to poll for 1 before polling
183 		 * for 0.  In the worst case, if we miss seeing it asserted the
184 		 * time we spent waiting is enough to ensure the reset finishes.
185 		 */
186 		timeout = 10000;
187 		while ((RD1(slot, SDHCI_SOFTWARE_RESET) & mask) != mask) {
188 			if (timeout <= 0)
189 				break;
190 			timeout--;
191 			DELAY(1);
192 		}
193 	}
194 
195 	/* Wait max 100 ms */
196 	timeout = 10000;
197 	/* Controller clears the bits when it's done */
198 	while (RD1(slot, SDHCI_SOFTWARE_RESET) & mask) {
199 		if (timeout <= 0) {
200 			slot_printf(slot, "Reset 0x%x never completed.\n",
201 			    mask);
202 			sdhci_dumpregs(slot);
203 			return;
204 		}
205 		timeout--;
206 		DELAY(10);
207 	}
208 }
209 
210 static void
211 sdhci_init(struct sdhci_slot *slot)
212 {
213 
214 	sdhci_reset(slot, SDHCI_RESET_ALL);
215 
216 	/* Enable interrupts. */
217 	slot->intmask = SDHCI_INT_BUS_POWER | SDHCI_INT_DATA_END_BIT |
218 	    SDHCI_INT_DATA_CRC | SDHCI_INT_DATA_TIMEOUT | SDHCI_INT_INDEX |
219 	    SDHCI_INT_END_BIT | SDHCI_INT_CRC | SDHCI_INT_TIMEOUT |
220 	    SDHCI_INT_CARD_REMOVE | SDHCI_INT_CARD_INSERT |
221 	    SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL |
222 	    SDHCI_INT_DMA_END | SDHCI_INT_DATA_END | SDHCI_INT_RESPONSE |
223 	    SDHCI_INT_ACMD12ERR;
224 	WR4(slot, SDHCI_INT_ENABLE, slot->intmask);
225 	WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask);
226 }
227 
228 static void
229 sdhci_set_clock(struct sdhci_slot *slot, uint32_t clock)
230 {
231 	uint32_t res;
232 	uint16_t clk;
233 	uint16_t div;
234 	int timeout;
235 
236 	if (clock == slot->clock)
237 		return;
238 	slot->clock = clock;
239 
240 	/* Turn off the clock. */
241 	clk = RD2(slot, SDHCI_CLOCK_CONTROL);
242 	WR2(slot, SDHCI_CLOCK_CONTROL, clk & ~SDHCI_CLOCK_CARD_EN);
243 	/* If no clock requested - left it so. */
244 	if (clock == 0)
245 		return;
246 
247 	/* Recalculate timeout clock frequency based on the new sd clock. */
248 	if (slot->quirks & SDHCI_QUIRK_DATA_TIMEOUT_USES_SDCLK)
249 		slot->timeout_clk = slot->clock / 1000;
250 
251 	if (slot->version < SDHCI_SPEC_300) {
252 		/* Looking for highest freq <= clock. */
253 		res = slot->max_clk;
254 		for (div = 1; div < SDHCI_200_MAX_DIVIDER; div <<= 1) {
255 			if (res <= clock)
256 				break;
257 			res >>= 1;
258 		}
259 		/* Divider 1:1 is 0x00, 2:1 is 0x01, 256:1 is 0x80 ... */
260 		div >>= 1;
261 	}
262 	else {
263 		/* Version 3.0 divisors are multiples of two up to 1023*2 */
264 		if (clock >= slot->max_clk)
265 			div = 0;
266 		else {
267 			for (div = 2; div < SDHCI_300_MAX_DIVIDER; div += 2) {
268 				if ((slot->max_clk / div) <= clock)
269 					break;
270 			}
271 		}
272 		div >>= 1;
273 	}
274 
275 	if (bootverbose || sdhci_debug)
276 		slot_printf(slot, "Divider %d for freq %d (max %d)\n",
277 			div, clock, slot->max_clk);
278 
279 	/* Now we have got divider, set it. */
280 	clk = (div & SDHCI_DIVIDER_MASK) << SDHCI_DIVIDER_SHIFT;
281 	clk |= ((div >> SDHCI_DIVIDER_MASK_LEN) & SDHCI_DIVIDER_HI_MASK)
282 		<< SDHCI_DIVIDER_HI_SHIFT;
283 
284 	WR2(slot, SDHCI_CLOCK_CONTROL, clk);
285 	/* Enable clock. */
286 	clk |= SDHCI_CLOCK_INT_EN;
287 	WR2(slot, SDHCI_CLOCK_CONTROL, clk);
288 	/* Wait up to 10 ms until it stabilize. */
289 	timeout = 10;
290 	while (!((clk = RD2(slot, SDHCI_CLOCK_CONTROL))
291 		& SDHCI_CLOCK_INT_STABLE)) {
292 		if (timeout == 0) {
293 			slot_printf(slot,
294 			    "Internal clock never stabilised.\n");
295 			sdhci_dumpregs(slot);
296 			return;
297 		}
298 		timeout--;
299 		DELAY(1000);
300 	}
301 	/* Pass clock signal to the bus. */
302 	clk |= SDHCI_CLOCK_CARD_EN;
303 	WR2(slot, SDHCI_CLOCK_CONTROL, clk);
304 }
305 
306 static void
307 sdhci_set_power(struct sdhci_slot *slot, u_char power)
308 {
309 	uint8_t pwr;
310 
311 	if (slot->power == power)
312 		return;
313 
314 	slot->power = power;
315 
316 	/* Turn off the power. */
317 	pwr = 0;
318 	WR1(slot, SDHCI_POWER_CONTROL, pwr);
319 	/* If power down requested - left it so. */
320 	if (power == 0)
321 		return;
322 	/* Set voltage. */
323 	switch (1 << power) {
324 	case MMC_OCR_LOW_VOLTAGE:
325 		pwr |= SDHCI_POWER_180;
326 		break;
327 	case MMC_OCR_290_300:
328 	case MMC_OCR_300_310:
329 		pwr |= SDHCI_POWER_300;
330 		break;
331 	case MMC_OCR_320_330:
332 	case MMC_OCR_330_340:
333 		pwr |= SDHCI_POWER_330;
334 		break;
335 	}
336 	WR1(slot, SDHCI_POWER_CONTROL, pwr);
337 	/* Turn on the power. */
338 	pwr |= SDHCI_POWER_ON;
339 	WR1(slot, SDHCI_POWER_CONTROL, pwr);
340 }
341 
342 static void
343 sdhci_read_block_pio(struct sdhci_slot *slot)
344 {
345 	uint32_t data;
346 	char *buffer;
347 	size_t left;
348 
349 	buffer = slot->curcmd->data->data;
350 	buffer += slot->offset;
351 	/* Transfer one block at a time. */
352 	left = min(512, slot->curcmd->data->len - slot->offset);
353 	slot->offset += left;
354 
355 	/* If we are too fast, broken controllers return zeroes. */
356 	if (slot->quirks & SDHCI_QUIRK_BROKEN_TIMINGS)
357 		DELAY(10);
358 	/* Handle unaligned and aligned buffer cases. */
359 	if ((intptr_t)buffer & 3) {
360 		while (left > 3) {
361 			data = RD4(slot, SDHCI_BUFFER);
362 			buffer[0] = data;
363 			buffer[1] = (data >> 8);
364 			buffer[2] = (data >> 16);
365 			buffer[3] = (data >> 24);
366 			buffer += 4;
367 			left -= 4;
368 		}
369 	} else {
370 		RD_MULTI_4(slot, SDHCI_BUFFER,
371 		    (uint32_t *)buffer, left >> 2);
372 		left &= 3;
373 	}
374 	/* Handle uneven size case. */
375 	if (left > 0) {
376 		data = RD4(slot, SDHCI_BUFFER);
377 		while (left > 0) {
378 			*(buffer++) = data;
379 			data >>= 8;
380 			left--;
381 		}
382 	}
383 }
384 
385 static void
386 sdhci_write_block_pio(struct sdhci_slot *slot)
387 {
388 	uint32_t data = 0;
389 	char *buffer;
390 	size_t left;
391 
392 	buffer = slot->curcmd->data->data;
393 	buffer += slot->offset;
394 	/* Transfer one block at a time. */
395 	left = min(512, slot->curcmd->data->len - slot->offset);
396 	slot->offset += left;
397 
398 	/* Handle unaligned and aligned buffer cases. */
399 	if ((intptr_t)buffer & 3) {
400 		while (left > 3) {
401 			data = buffer[0] +
402 			    (buffer[1] << 8) +
403 			    (buffer[2] << 16) +
404 			    (buffer[3] << 24);
405 			left -= 4;
406 			buffer += 4;
407 			WR4(slot, SDHCI_BUFFER, data);
408 		}
409 	} else {
410 		WR_MULTI_4(slot, SDHCI_BUFFER,
411 		    (uint32_t *)buffer, left >> 2);
412 		left &= 3;
413 	}
414 	/* Handle uneven size case. */
415 	if (left > 0) {
416 		while (left > 0) {
417 			data <<= 8;
418 			data += *(buffer++);
419 			left--;
420 		}
421 		WR4(slot, SDHCI_BUFFER, data);
422 	}
423 }
424 
425 static void
426 sdhci_transfer_pio(struct sdhci_slot *slot)
427 {
428 
429 	/* Read as many blocks as possible. */
430 	if (slot->curcmd->data->flags & MMC_DATA_READ) {
431 		while (RD4(slot, SDHCI_PRESENT_STATE) &
432 		    SDHCI_DATA_AVAILABLE) {
433 			sdhci_read_block_pio(slot);
434 			if (slot->offset >= slot->curcmd->data->len)
435 				break;
436 		}
437 	} else {
438 		while (RD4(slot, SDHCI_PRESENT_STATE) &
439 		    SDHCI_SPACE_AVAILABLE) {
440 			sdhci_write_block_pio(slot);
441 			if (slot->offset >= slot->curcmd->data->len)
442 				break;
443 		}
444 	}
445 }
446 
447 static void
448 sdhci_card_delay(void *arg)
449 {
450 	struct sdhci_slot *slot = arg;
451 
452 	taskqueue_enqueue(taskqueue_swi_giant, &slot->card_task);
453 }
454 
455 static void
456 sdhci_card_task(void *arg, int pending)
457 {
458 	struct sdhci_slot *slot = arg;
459 
460 	SDHCI_LOCK(slot);
461 	if (RD4(slot, SDHCI_PRESENT_STATE) & SDHCI_CARD_PRESENT) {
462 		if (slot->dev == NULL) {
463 			/* If card is present - attach mmc bus. */
464 			slot->dev = device_add_child(slot->bus, "mmc", -1);
465 			device_set_ivars(slot->dev, slot);
466 			SDHCI_UNLOCK(slot);
467 			device_probe_and_attach(slot->dev);
468 		} else
469 			SDHCI_UNLOCK(slot);
470 	} else {
471 		if (slot->dev != NULL) {
472 			/* If no card present - detach mmc bus. */
473 			device_t d = slot->dev;
474 			slot->dev = NULL;
475 			SDHCI_UNLOCK(slot);
476 			device_delete_child(slot->bus, d);
477 		} else
478 			SDHCI_UNLOCK(slot);
479 	}
480 }
481 
482 int
483 sdhci_init_slot(device_t dev, struct sdhci_slot *slot, int num)
484 {
485 	uint32_t caps, freq;
486 	int err;
487 
488 	SDHCI_LOCK_INIT(slot);
489 	slot->num = num;
490 	slot->bus = dev;
491 
492 	/* Allocate DMA tag. */
493 	err = bus_dma_tag_create(bus_get_dma_tag(dev),
494 	    DMA_BLOCK_SIZE, 0, BUS_SPACE_MAXADDR_32BIT,
495 	    BUS_SPACE_MAXADDR, NULL, NULL,
496 	    DMA_BLOCK_SIZE, 1, DMA_BLOCK_SIZE,
497 	    BUS_DMA_ALLOCNOW, NULL, NULL,
498 	    &slot->dmatag);
499 	if (err != 0) {
500 		device_printf(dev, "Can't create DMA tag\n");
501 		SDHCI_LOCK_DESTROY(slot);
502 		return (err);
503 	}
504 	/* Allocate DMA memory. */
505 	err = bus_dmamem_alloc(slot->dmatag, (void **)&slot->dmamem,
506 	    BUS_DMA_NOWAIT, &slot->dmamap);
507 	if (err != 0) {
508 		device_printf(dev, "Can't alloc DMA memory\n");
509 		SDHCI_LOCK_DESTROY(slot);
510 		return (err);
511 	}
512 	/* Map the memory. */
513 	err = bus_dmamap_load(slot->dmatag, slot->dmamap,
514 	    (void *)slot->dmamem, DMA_BLOCK_SIZE,
515 	    sdhci_getaddr, &slot->paddr, 0);
516 	if (err != 0 || slot->paddr == 0) {
517 		device_printf(dev, "Can't load DMA memory\n");
518 		SDHCI_LOCK_DESTROY(slot);
519 		if(err)
520 			return (err);
521 		else
522 			return (EFAULT);
523 	}
524 
525 	/* Initialize slot. */
526 	sdhci_init(slot);
527 	slot->version = (RD2(slot, SDHCI_HOST_VERSION)
528 		>> SDHCI_SPEC_VER_SHIFT) & SDHCI_SPEC_VER_MASK;
529 	if (slot->quirks & SDHCI_QUIRK_MISSING_CAPS)
530 		caps = slot->caps;
531 	else
532 		caps = RD4(slot, SDHCI_CAPABILITIES);
533 	/* Calculate base clock frequency. */
534 	if (slot->version >= SDHCI_SPEC_300)
535 		freq = (caps & SDHCI_CLOCK_V3_BASE_MASK) >>
536 		    SDHCI_CLOCK_BASE_SHIFT;
537 	else
538 		freq = (caps & SDHCI_CLOCK_BASE_MASK) >>
539 		    SDHCI_CLOCK_BASE_SHIFT;
540 	if (freq != 0)
541 		slot->max_clk = freq * 1000000;
542 	/*
543 	 * If the frequency wasn't in the capabilities and the hardware driver
544 	 * hasn't already set max_clk we're probably not going to work right
545 	 * with an assumption, so complain about it.
546 	 */
547 	if (slot->max_clk == 0) {
548 		slot->max_clk = SDHCI_DEFAULT_MAX_FREQ * 1000000;
549 		device_printf(dev, "Hardware doesn't specify base clock "
550 		    "frequency, using %dMHz as default.\n", SDHCI_DEFAULT_MAX_FREQ);
551 	}
552 	/* Calculate timeout clock frequency. */
553 	if (slot->quirks & SDHCI_QUIRK_DATA_TIMEOUT_USES_SDCLK) {
554 		slot->timeout_clk = slot->max_clk / 1000;
555 	} else {
556 		slot->timeout_clk =
557 			(caps & SDHCI_TIMEOUT_CLK_MASK) >> SDHCI_TIMEOUT_CLK_SHIFT;
558 		if (caps & SDHCI_TIMEOUT_CLK_UNIT)
559 			slot->timeout_clk *= 1000;
560 	}
561 	/*
562 	 * If the frequency wasn't in the capabilities and the hardware driver
563 	 * hasn't already set timeout_clk we'll probably work okay using the
564 	 * max timeout, but still mention it.
565 	 */
566 	if (slot->timeout_clk == 0) {
567 		device_printf(dev, "Hardware doesn't specify timeout clock "
568 		    "frequency, setting BROKEN_TIMEOUT quirk.\n");
569 		slot->quirks |= SDHCI_QUIRK_BROKEN_TIMEOUT_VAL;
570 	}
571 
572 	slot->host.f_min = SDHCI_MIN_FREQ(slot->bus, slot);
573 	slot->host.f_max = slot->max_clk;
574 	slot->host.host_ocr = 0;
575 	if (caps & SDHCI_CAN_VDD_330)
576 	    slot->host.host_ocr |= MMC_OCR_320_330 | MMC_OCR_330_340;
577 	if (caps & SDHCI_CAN_VDD_300)
578 	    slot->host.host_ocr |= MMC_OCR_290_300 | MMC_OCR_300_310;
579 	if (caps & SDHCI_CAN_VDD_180)
580 	    slot->host.host_ocr |= MMC_OCR_LOW_VOLTAGE;
581 	if (slot->host.host_ocr == 0) {
582 		device_printf(dev, "Hardware doesn't report any "
583 		    "support voltages.\n");
584 	}
585 	slot->host.caps = MMC_CAP_4_BIT_DATA;
586 	if (caps & SDHCI_CAN_DO_HISPD)
587 		slot->host.caps |= MMC_CAP_HSPEED;
588 	/* Decide if we have usable DMA. */
589 	if (caps & SDHCI_CAN_DO_DMA)
590 		slot->opt |= SDHCI_HAVE_DMA;
591 
592 	if (slot->quirks & SDHCI_QUIRK_BROKEN_DMA)
593 		slot->opt &= ~SDHCI_HAVE_DMA;
594 	if (slot->quirks & SDHCI_QUIRK_FORCE_DMA)
595 		slot->opt |= SDHCI_HAVE_DMA;
596 
597 	/*
598 	 * Use platform-provided transfer backend
599 	 * with PIO as a fallback mechanism
600 	 */
601 	if (slot->opt & SDHCI_PLATFORM_TRANSFER)
602 		slot->opt &= ~SDHCI_HAVE_DMA;
603 
604 	if (bootverbose || sdhci_debug) {
605 		slot_printf(slot, "%uMHz%s 4bits%s%s%s %s\n",
606 		    slot->max_clk / 1000000,
607 		    (caps & SDHCI_CAN_DO_HISPD) ? " HS" : "",
608 		    (caps & SDHCI_CAN_VDD_330) ? " 3.3V" : "",
609 		    (caps & SDHCI_CAN_VDD_300) ? " 3.0V" : "",
610 		    (caps & SDHCI_CAN_VDD_180) ? " 1.8V" : "",
611 		    (slot->opt & SDHCI_HAVE_DMA) ? "DMA" : "PIO");
612 		sdhci_dumpregs(slot);
613 	}
614 
615 	TASK_INIT(&slot->card_task, 0, sdhci_card_task, slot);
616 	callout_init(&slot->card_callout, 1);
617 	callout_init_mtx(&slot->timeout_callout, &slot->mtx, 0);
618 	return (0);
619 }
620 
621 void
622 sdhci_start_slot(struct sdhci_slot *slot)
623 {
624 	sdhci_card_task(slot, 0);
625 }
626 
627 int
628 sdhci_cleanup_slot(struct sdhci_slot *slot)
629 {
630 	device_t d;
631 
632 	callout_drain(&slot->timeout_callout);
633 	callout_drain(&slot->card_callout);
634 	taskqueue_drain(taskqueue_swi_giant, &slot->card_task);
635 
636 	SDHCI_LOCK(slot);
637 	d = slot->dev;
638 	slot->dev = NULL;
639 	SDHCI_UNLOCK(slot);
640 	if (d != NULL)
641 		device_delete_child(slot->bus, d);
642 
643 	SDHCI_LOCK(slot);
644 	sdhci_reset(slot, SDHCI_RESET_ALL);
645 	SDHCI_UNLOCK(slot);
646 	bus_dmamap_unload(slot->dmatag, slot->dmamap);
647 	bus_dmamem_free(slot->dmatag, slot->dmamem, slot->dmamap);
648 	bus_dma_tag_destroy(slot->dmatag);
649 
650 	SDHCI_LOCK_DESTROY(slot);
651 
652 	return (0);
653 }
654 
655 int
656 sdhci_generic_suspend(struct sdhci_slot *slot)
657 {
658 	sdhci_reset(slot, SDHCI_RESET_ALL);
659 
660 	return (0);
661 }
662 
663 int
664 sdhci_generic_resume(struct sdhci_slot *slot)
665 {
666 	sdhci_init(slot);
667 
668 	return (0);
669 }
670 
671 uint32_t
672 sdhci_generic_min_freq(device_t brdev, struct sdhci_slot *slot)
673 {
674 	if (slot->version >= SDHCI_SPEC_300)
675 		return (slot->max_clk / SDHCI_300_MAX_DIVIDER);
676 	else
677 		return (slot->max_clk / SDHCI_200_MAX_DIVIDER);
678 }
679 
680 int
681 sdhci_generic_update_ios(device_t brdev, device_t reqdev)
682 {
683 	struct sdhci_slot *slot = device_get_ivars(reqdev);
684 	struct mmc_ios *ios = &slot->host.ios;
685 
686 	SDHCI_LOCK(slot);
687 	/* Do full reset on bus power down to clear from any state. */
688 	if (ios->power_mode == power_off) {
689 		WR4(slot, SDHCI_SIGNAL_ENABLE, 0);
690 		sdhci_init(slot);
691 	}
692 	/* Configure the bus. */
693 	sdhci_set_clock(slot, ios->clock);
694 	sdhci_set_power(slot, (ios->power_mode == power_off)?0:ios->vdd);
695 	if (ios->bus_width == bus_width_4)
696 		slot->hostctrl |= SDHCI_CTRL_4BITBUS;
697 	else
698 		slot->hostctrl &= ~SDHCI_CTRL_4BITBUS;
699 	if (ios->timing == bus_timing_hs &&
700 	    !(slot->quirks & SDHCI_QUIRK_DONT_SET_HISPD_BIT))
701 		slot->hostctrl |= SDHCI_CTRL_HISPD;
702 	else
703 		slot->hostctrl &= ~SDHCI_CTRL_HISPD;
704 	WR1(slot, SDHCI_HOST_CONTROL, slot->hostctrl);
705 	/* Some controllers like reset after bus changes. */
706 	if(slot->quirks & SDHCI_QUIRK_RESET_ON_IOS)
707 		sdhci_reset(slot, SDHCI_RESET_CMD | SDHCI_RESET_DATA);
708 
709 	SDHCI_UNLOCK(slot);
710 	return (0);
711 }
712 
713 static void
714 sdhci_req_done(struct sdhci_slot *slot)
715 {
716 	struct mmc_request *req;
717 
718 	if (slot->req != NULL && slot->curcmd != NULL) {
719 		callout_stop(&slot->timeout_callout);
720 		req = slot->req;
721 		slot->req = NULL;
722 		slot->curcmd = NULL;
723 		req->done(req);
724 	}
725 }
726 
727 static void
728 sdhci_timeout(void *arg)
729 {
730 	struct sdhci_slot *slot = arg;
731 
732 	if (slot->curcmd != NULL) {
733 		slot_printf(slot, " Controller timeout\n");
734 		sdhci_dumpregs(slot);
735 		sdhci_reset(slot, SDHCI_RESET_CMD|SDHCI_RESET_DATA);
736 		slot->curcmd->error = MMC_ERR_TIMEOUT;
737 		sdhci_req_done(slot);
738 	} else {
739 		slot_printf(slot, " Spurious timeout - no active command\n");
740 	}
741 }
742 
743 static void
744 sdhci_set_transfer_mode(struct sdhci_slot *slot,
745 	struct mmc_data *data)
746 {
747 	uint16_t mode;
748 
749 	if (data == NULL)
750 		return;
751 
752 	mode = SDHCI_TRNS_BLK_CNT_EN;
753 	if (data->len > 512)
754 		mode |= SDHCI_TRNS_MULTI;
755 	if (data->flags & MMC_DATA_READ)
756 		mode |= SDHCI_TRNS_READ;
757 	if (slot->req->stop)
758 		mode |= SDHCI_TRNS_ACMD12;
759 	if (slot->flags & SDHCI_USE_DMA)
760 		mode |= SDHCI_TRNS_DMA;
761 
762 	WR2(slot, SDHCI_TRANSFER_MODE, mode);
763 }
764 
765 static void
766 sdhci_start_command(struct sdhci_slot *slot, struct mmc_command *cmd)
767 {
768 	int flags, timeout;
769 	uint32_t mask, state;
770 
771 	slot->curcmd = cmd;
772 	slot->cmd_done = 0;
773 
774 	cmd->error = MMC_ERR_NONE;
775 
776 	/* This flags combination is not supported by controller. */
777 	if ((cmd->flags & MMC_RSP_136) && (cmd->flags & MMC_RSP_BUSY)) {
778 		slot_printf(slot, "Unsupported response type!\n");
779 		cmd->error = MMC_ERR_FAILED;
780 		sdhci_req_done(slot);
781 		return;
782 	}
783 
784 	/* Read controller present state. */
785 	state = RD4(slot, SDHCI_PRESENT_STATE);
786 	/* Do not issue command if there is no card, clock or power.
787 	 * Controller will not detect timeout without clock active. */
788 	if ((state & SDHCI_CARD_PRESENT) == 0 ||
789 	    slot->power == 0 ||
790 	    slot->clock == 0) {
791 		cmd->error = MMC_ERR_FAILED;
792 		sdhci_req_done(slot);
793 		return;
794 	}
795 	/* Always wait for free CMD bus. */
796 	mask = SDHCI_CMD_INHIBIT;
797 	/* Wait for free DAT if we have data or busy signal. */
798 	if (cmd->data || (cmd->flags & MMC_RSP_BUSY))
799 		mask |= SDHCI_DAT_INHIBIT;
800 	/* We shouldn't wait for DAT for stop commands. */
801 	if (cmd == slot->req->stop)
802 		mask &= ~SDHCI_DAT_INHIBIT;
803 	/*
804 	 *  Wait for bus no more then 250 ms.  Typically there will be no wait
805 	 *  here at all, but when writing a crash dump we may be bypassing the
806 	 *  host platform's interrupt handler, and in some cases that handler
807 	 *  may be working around hardware quirks such as not respecting r1b
808 	 *  busy indications.  In those cases, this wait-loop serves the purpose
809 	 *  of waiting for the prior command and data transfers to be done, and
810 	 *  SD cards are allowed to take up to 250ms for write and erase ops.
811 	 *  (It's usually more like 20-30ms in the real world.)
812 	 */
813 	timeout = 250;
814 	while (state & mask) {
815 		if (timeout == 0) {
816 			slot_printf(slot, "Controller never released "
817 			    "inhibit bit(s).\n");
818 			sdhci_dumpregs(slot);
819 			cmd->error = MMC_ERR_FAILED;
820 			sdhci_req_done(slot);
821 			return;
822 		}
823 		timeout--;
824 		DELAY(1000);
825 		state = RD4(slot, SDHCI_PRESENT_STATE);
826 	}
827 
828 	/* Prepare command flags. */
829 	if (!(cmd->flags & MMC_RSP_PRESENT))
830 		flags = SDHCI_CMD_RESP_NONE;
831 	else if (cmd->flags & MMC_RSP_136)
832 		flags = SDHCI_CMD_RESP_LONG;
833 	else if (cmd->flags & MMC_RSP_BUSY)
834 		flags = SDHCI_CMD_RESP_SHORT_BUSY;
835 	else
836 		flags = SDHCI_CMD_RESP_SHORT;
837 	if (cmd->flags & MMC_RSP_CRC)
838 		flags |= SDHCI_CMD_CRC;
839 	if (cmd->flags & MMC_RSP_OPCODE)
840 		flags |= SDHCI_CMD_INDEX;
841 	if (cmd->data)
842 		flags |= SDHCI_CMD_DATA;
843 	if (cmd->opcode == MMC_STOP_TRANSMISSION)
844 		flags |= SDHCI_CMD_TYPE_ABORT;
845 	/* Prepare data. */
846 	sdhci_start_data(slot, cmd->data);
847 	/*
848 	 * Interrupt aggregation: To reduce total number of interrupts
849 	 * group response interrupt with data interrupt when possible.
850 	 * If there going to be data interrupt, mask response one.
851 	 */
852 	if (slot->data_done == 0) {
853 		WR4(slot, SDHCI_SIGNAL_ENABLE,
854 		    slot->intmask &= ~SDHCI_INT_RESPONSE);
855 	}
856 	/* Set command argument. */
857 	WR4(slot, SDHCI_ARGUMENT, cmd->arg);
858 	/* Set data transfer mode. */
859 	sdhci_set_transfer_mode(slot, cmd->data);
860 	/* Start command. */
861 	WR2(slot, SDHCI_COMMAND_FLAGS, (cmd->opcode << 8) | (flags & 0xff));
862 	/* Start timeout callout. */
863 	callout_reset(&slot->timeout_callout, 2*hz, sdhci_timeout, slot);
864 }
865 
866 static void
867 sdhci_finish_command(struct sdhci_slot *slot)
868 {
869 	int i;
870 
871 	slot->cmd_done = 1;
872 	/* Interrupt aggregation: Restore command interrupt.
873 	 * Main restore point for the case when command interrupt
874 	 * happened first. */
875 	WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask |= SDHCI_INT_RESPONSE);
876 	/* In case of error - reset host and return. */
877 	if (slot->curcmd->error) {
878 		sdhci_reset(slot, SDHCI_RESET_CMD);
879 		sdhci_reset(slot, SDHCI_RESET_DATA);
880 		sdhci_start(slot);
881 		return;
882 	}
883 	/* If command has response - fetch it. */
884 	if (slot->curcmd->flags & MMC_RSP_PRESENT) {
885 		if (slot->curcmd->flags & MMC_RSP_136) {
886 			/* CRC is stripped so we need one byte shift. */
887 			uint8_t extra = 0;
888 			for (i = 0; i < 4; i++) {
889 				uint32_t val = RD4(slot, SDHCI_RESPONSE + i * 4);
890 				if (slot->quirks & SDHCI_QUIRK_DONT_SHIFT_RESPONSE)
891 					slot->curcmd->resp[3 - i] = val;
892 				else {
893 					slot->curcmd->resp[3 - i] =
894 					    (val << 8) | extra;
895 					extra = val >> 24;
896 				}
897 			}
898 		} else
899 			slot->curcmd->resp[0] = RD4(slot, SDHCI_RESPONSE);
900 	}
901 	/* If data ready - finish. */
902 	if (slot->data_done)
903 		sdhci_start(slot);
904 }
905 
906 static void
907 sdhci_start_data(struct sdhci_slot *slot, struct mmc_data *data)
908 {
909 	uint32_t target_timeout, current_timeout;
910 	uint8_t div;
911 
912 	if (data == NULL && (slot->curcmd->flags & MMC_RSP_BUSY) == 0) {
913 		slot->data_done = 1;
914 		return;
915 	}
916 
917 	slot->data_done = 0;
918 
919 	/* Calculate and set data timeout.*/
920 	/* XXX: We should have this from mmc layer, now assume 1 sec. */
921 	if (slot->quirks & SDHCI_QUIRK_BROKEN_TIMEOUT_VAL) {
922 		div = 0xE;
923 	} else {
924 		target_timeout = 1000000;
925 		div = 0;
926 		current_timeout = (1 << 13) * 1000 / slot->timeout_clk;
927 		while (current_timeout < target_timeout && div < 0xE) {
928 			++div;
929 			current_timeout <<= 1;
930 		}
931 		/* Compensate for an off-by-one error in the CaFe chip.*/
932 		if (div < 0xE &&
933 		    (slot->quirks & SDHCI_QUIRK_INCR_TIMEOUT_CONTROL)) {
934 			++div;
935 		}
936 	}
937 	WR1(slot, SDHCI_TIMEOUT_CONTROL, div);
938 
939 	if (data == NULL)
940 		return;
941 
942 	/* Use DMA if possible. */
943 	if ((slot->opt & SDHCI_HAVE_DMA))
944 		slot->flags |= SDHCI_USE_DMA;
945 	/* If data is small, broken DMA may return zeroes instead of data, */
946 	if ((slot->quirks & SDHCI_QUIRK_BROKEN_TIMINGS) &&
947 	    (data->len <= 512))
948 		slot->flags &= ~SDHCI_USE_DMA;
949 	/* Some controllers require even block sizes. */
950 	if ((slot->quirks & SDHCI_QUIRK_32BIT_DMA_SIZE) &&
951 	    ((data->len) & 0x3))
952 		slot->flags &= ~SDHCI_USE_DMA;
953 	/* Load DMA buffer. */
954 	if (slot->flags & SDHCI_USE_DMA) {
955 		if (data->flags & MMC_DATA_READ)
956 			bus_dmamap_sync(slot->dmatag, slot->dmamap,
957 			    BUS_DMASYNC_PREREAD);
958 		else {
959 			memcpy(slot->dmamem, data->data,
960 			    (data->len < DMA_BLOCK_SIZE) ?
961 			    data->len : DMA_BLOCK_SIZE);
962 			bus_dmamap_sync(slot->dmatag, slot->dmamap,
963 			    BUS_DMASYNC_PREWRITE);
964 		}
965 		WR4(slot, SDHCI_DMA_ADDRESS, slot->paddr);
966 		/* Interrupt aggregation: Mask border interrupt
967 		 * for the last page and unmask else. */
968 		if (data->len == DMA_BLOCK_SIZE)
969 			slot->intmask &= ~SDHCI_INT_DMA_END;
970 		else
971 			slot->intmask |= SDHCI_INT_DMA_END;
972 		WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask);
973 	}
974 	/* Current data offset for both PIO and DMA. */
975 	slot->offset = 0;
976 	/* Set block size and request IRQ on 4K border. */
977 	WR2(slot, SDHCI_BLOCK_SIZE,
978 	    SDHCI_MAKE_BLKSZ(DMA_BOUNDARY, (data->len < 512)?data->len:512));
979 	/* Set block count. */
980 	WR2(slot, SDHCI_BLOCK_COUNT, (data->len + 511) / 512);
981 }
982 
983 void
984 sdhci_finish_data(struct sdhci_slot *slot)
985 {
986 	struct mmc_data *data = slot->curcmd->data;
987 
988 	/* Interrupt aggregation: Restore command interrupt.
989 	 * Auxiliary restore point for the case when data interrupt
990 	 * happened first. */
991 	if (!slot->cmd_done) {
992 		WR4(slot, SDHCI_SIGNAL_ENABLE,
993 		    slot->intmask |= SDHCI_INT_RESPONSE);
994 	}
995 	/* Unload rest of data from DMA buffer. */
996 	if (!slot->data_done && (slot->flags & SDHCI_USE_DMA)) {
997 		if (data->flags & MMC_DATA_READ) {
998 			size_t left = data->len - slot->offset;
999 			bus_dmamap_sync(slot->dmatag, slot->dmamap,
1000 			    BUS_DMASYNC_POSTREAD);
1001 			memcpy((u_char*)data->data + slot->offset, slot->dmamem,
1002 			    (left < DMA_BLOCK_SIZE)?left:DMA_BLOCK_SIZE);
1003 		} else
1004 			bus_dmamap_sync(slot->dmatag, slot->dmamap,
1005 			    BUS_DMASYNC_POSTWRITE);
1006 	}
1007 	slot->data_done = 1;
1008 	/* If there was error - reset the host. */
1009 	if (slot->curcmd->error) {
1010 		sdhci_reset(slot, SDHCI_RESET_CMD);
1011 		sdhci_reset(slot, SDHCI_RESET_DATA);
1012 		sdhci_start(slot);
1013 		return;
1014 	}
1015 	/* If we already have command response - finish. */
1016 	if (slot->cmd_done)
1017 		sdhci_start(slot);
1018 }
1019 
1020 static void
1021 sdhci_start(struct sdhci_slot *slot)
1022 {
1023 	struct mmc_request *req;
1024 
1025 	req = slot->req;
1026 	if (req == NULL)
1027 		return;
1028 
1029 	if (!(slot->flags & CMD_STARTED)) {
1030 		slot->flags |= CMD_STARTED;
1031 		sdhci_start_command(slot, req->cmd);
1032 		return;
1033 	}
1034 /* 	We don't need this until using Auto-CMD12 feature
1035 	if (!(slot->flags & STOP_STARTED) && req->stop) {
1036 		slot->flags |= STOP_STARTED;
1037 		sdhci_start_command(slot, req->stop);
1038 		return;
1039 	}
1040 */
1041 	if (sdhci_debug > 1)
1042 		slot_printf(slot, "result: %d\n", req->cmd->error);
1043 	if (!req->cmd->error &&
1044 	    (slot->quirks & SDHCI_QUIRK_RESET_AFTER_REQUEST)) {
1045 		sdhci_reset(slot, SDHCI_RESET_CMD);
1046 		sdhci_reset(slot, SDHCI_RESET_DATA);
1047 	}
1048 
1049 	sdhci_req_done(slot);
1050 }
1051 
1052 int
1053 sdhci_generic_request(device_t brdev, device_t reqdev, struct mmc_request *req)
1054 {
1055 	struct sdhci_slot *slot = device_get_ivars(reqdev);
1056 
1057 	SDHCI_LOCK(slot);
1058 	if (slot->req != NULL) {
1059 		SDHCI_UNLOCK(slot);
1060 		return (EBUSY);
1061 	}
1062 	if (sdhci_debug > 1) {
1063 		slot_printf(slot, "CMD%u arg %#x flags %#x dlen %u dflags %#x\n",
1064     		    req->cmd->opcode, req->cmd->arg, req->cmd->flags,
1065     		    (req->cmd->data)?(u_int)req->cmd->data->len:0,
1066 		    (req->cmd->data)?req->cmd->data->flags:0);
1067 	}
1068 	slot->req = req;
1069 	slot->flags = 0;
1070 	sdhci_start(slot);
1071 	SDHCI_UNLOCK(slot);
1072 	if (dumping) {
1073 		while (slot->req != NULL) {
1074 			sdhci_generic_intr(slot);
1075 			DELAY(10);
1076 		}
1077 	}
1078 	return (0);
1079 }
1080 
1081 int
1082 sdhci_generic_get_ro(device_t brdev, device_t reqdev)
1083 {
1084 	struct sdhci_slot *slot = device_get_ivars(reqdev);
1085 	uint32_t val;
1086 
1087 	SDHCI_LOCK(slot);
1088 	val = RD4(slot, SDHCI_PRESENT_STATE);
1089 	SDHCI_UNLOCK(slot);
1090 	return (!(val & SDHCI_WRITE_PROTECT));
1091 }
1092 
1093 int
1094 sdhci_generic_acquire_host(device_t brdev, device_t reqdev)
1095 {
1096 	struct sdhci_slot *slot = device_get_ivars(reqdev);
1097 	int err = 0;
1098 
1099 	SDHCI_LOCK(slot);
1100 	while (slot->bus_busy)
1101 		msleep(slot, &slot->mtx, 0, "sdhciah", 0);
1102 	slot->bus_busy++;
1103 	/* Activate led. */
1104 	WR1(slot, SDHCI_HOST_CONTROL, slot->hostctrl |= SDHCI_CTRL_LED);
1105 	SDHCI_UNLOCK(slot);
1106 	return (err);
1107 }
1108 
1109 int
1110 sdhci_generic_release_host(device_t brdev, device_t reqdev)
1111 {
1112 	struct sdhci_slot *slot = device_get_ivars(reqdev);
1113 
1114 	SDHCI_LOCK(slot);
1115 	/* Deactivate led. */
1116 	WR1(slot, SDHCI_HOST_CONTROL, slot->hostctrl &= ~SDHCI_CTRL_LED);
1117 	slot->bus_busy--;
1118 	SDHCI_UNLOCK(slot);
1119 	wakeup(slot);
1120 	return (0);
1121 }
1122 
1123 static void
1124 sdhci_cmd_irq(struct sdhci_slot *slot, uint32_t intmask)
1125 {
1126 
1127 	if (!slot->curcmd) {
1128 		slot_printf(slot, "Got command interrupt 0x%08x, but "
1129 		    "there is no active command.\n", intmask);
1130 		sdhci_dumpregs(slot);
1131 		return;
1132 	}
1133 	if (intmask & SDHCI_INT_TIMEOUT)
1134 		slot->curcmd->error = MMC_ERR_TIMEOUT;
1135 	else if (intmask & SDHCI_INT_CRC)
1136 		slot->curcmd->error = MMC_ERR_BADCRC;
1137 	else if (intmask & (SDHCI_INT_END_BIT | SDHCI_INT_INDEX))
1138 		slot->curcmd->error = MMC_ERR_FIFO;
1139 
1140 	sdhci_finish_command(slot);
1141 }
1142 
1143 static void
1144 sdhci_data_irq(struct sdhci_slot *slot, uint32_t intmask)
1145 {
1146 
1147 	if (!slot->curcmd) {
1148 		slot_printf(slot, "Got data interrupt 0x%08x, but "
1149 		    "there is no active command.\n", intmask);
1150 		sdhci_dumpregs(slot);
1151 		return;
1152 	}
1153 	if (slot->curcmd->data == NULL &&
1154 	    (slot->curcmd->flags & MMC_RSP_BUSY) == 0) {
1155 		slot_printf(slot, "Got data interrupt 0x%08x, but "
1156 		    "there is no active data operation.\n",
1157 		    intmask);
1158 		sdhci_dumpregs(slot);
1159 		return;
1160 	}
1161 	if (intmask & SDHCI_INT_DATA_TIMEOUT)
1162 		slot->curcmd->error = MMC_ERR_TIMEOUT;
1163 	else if (intmask & (SDHCI_INT_DATA_CRC | SDHCI_INT_DATA_END_BIT))
1164 		slot->curcmd->error = MMC_ERR_BADCRC;
1165 	if (slot->curcmd->data == NULL &&
1166 	    (intmask & (SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL |
1167 	    SDHCI_INT_DMA_END))) {
1168 		slot_printf(slot, "Got data interrupt 0x%08x, but "
1169 		    "there is busy-only command.\n", intmask);
1170 		sdhci_dumpregs(slot);
1171 		slot->curcmd->error = MMC_ERR_INVALID;
1172 	}
1173 	if (slot->curcmd->error) {
1174 		/* No need to continue after any error. */
1175 		goto done;
1176 	}
1177 
1178 	/* Handle PIO interrupt. */
1179 	if (intmask & (SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL)) {
1180 		if ((slot->opt & SDHCI_PLATFORM_TRANSFER) &&
1181 		    SDHCI_PLATFORM_WILL_HANDLE(slot->bus, slot)) {
1182 			SDHCI_PLATFORM_START_TRANSFER(slot->bus, slot, &intmask);
1183 			slot->flags |= PLATFORM_DATA_STARTED;
1184 		} else
1185 			sdhci_transfer_pio(slot);
1186 	}
1187 	/* Handle DMA border. */
1188 	if (intmask & SDHCI_INT_DMA_END) {
1189 		struct mmc_data *data = slot->curcmd->data;
1190 		size_t left;
1191 
1192 		/* Unload DMA buffer... */
1193 		left = data->len - slot->offset;
1194 		if (data->flags & MMC_DATA_READ) {
1195 			bus_dmamap_sync(slot->dmatag, slot->dmamap,
1196 			    BUS_DMASYNC_POSTREAD);
1197 			memcpy((u_char*)data->data + slot->offset, slot->dmamem,
1198 			    (left < DMA_BLOCK_SIZE)?left:DMA_BLOCK_SIZE);
1199 		} else {
1200 			bus_dmamap_sync(slot->dmatag, slot->dmamap,
1201 			    BUS_DMASYNC_POSTWRITE);
1202 		}
1203 		/* ... and reload it again. */
1204 		slot->offset += DMA_BLOCK_SIZE;
1205 		left = data->len - slot->offset;
1206 		if (data->flags & MMC_DATA_READ) {
1207 			bus_dmamap_sync(slot->dmatag, slot->dmamap,
1208 			    BUS_DMASYNC_PREREAD);
1209 		} else {
1210 			memcpy(slot->dmamem, (u_char*)data->data + slot->offset,
1211 			    (left < DMA_BLOCK_SIZE)?left:DMA_BLOCK_SIZE);
1212 			bus_dmamap_sync(slot->dmatag, slot->dmamap,
1213 			    BUS_DMASYNC_PREWRITE);
1214 		}
1215 		/* Interrupt aggregation: Mask border interrupt
1216 		 * for the last page. */
1217 		if (left == DMA_BLOCK_SIZE) {
1218 			slot->intmask &= ~SDHCI_INT_DMA_END;
1219 			WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask);
1220 		}
1221 		/* Restart DMA. */
1222 		WR4(slot, SDHCI_DMA_ADDRESS, slot->paddr);
1223 	}
1224 	/* We have got all data. */
1225 	if (intmask & SDHCI_INT_DATA_END) {
1226 		if (slot->flags & PLATFORM_DATA_STARTED) {
1227 			slot->flags &= ~PLATFORM_DATA_STARTED;
1228 			SDHCI_PLATFORM_FINISH_TRANSFER(slot->bus, slot);
1229 		} else
1230 			sdhci_finish_data(slot);
1231 	}
1232 done:
1233 	if (slot->curcmd != NULL && slot->curcmd->error != 0) {
1234 		if (slot->flags & PLATFORM_DATA_STARTED) {
1235 			slot->flags &= ~PLATFORM_DATA_STARTED;
1236 			SDHCI_PLATFORM_FINISH_TRANSFER(slot->bus, slot);
1237 		} else
1238 			sdhci_finish_data(slot);
1239 		return;
1240 	}
1241 }
1242 
1243 static void
1244 sdhci_acmd_irq(struct sdhci_slot *slot)
1245 {
1246 	uint16_t err;
1247 
1248 	err = RD4(slot, SDHCI_ACMD12_ERR);
1249 	if (!slot->curcmd) {
1250 		slot_printf(slot, "Got AutoCMD12 error 0x%04x, but "
1251 		    "there is no active command.\n", err);
1252 		sdhci_dumpregs(slot);
1253 		return;
1254 	}
1255 	slot_printf(slot, "Got AutoCMD12 error 0x%04x\n", err);
1256 	sdhci_reset(slot, SDHCI_RESET_CMD);
1257 }
1258 
1259 void
1260 sdhci_generic_intr(struct sdhci_slot *slot)
1261 {
1262 	uint32_t intmask;
1263 
1264 	SDHCI_LOCK(slot);
1265 	/* Read slot interrupt status. */
1266 	intmask = RD4(slot, SDHCI_INT_STATUS);
1267 	if (intmask == 0 || intmask == 0xffffffff) {
1268 		SDHCI_UNLOCK(slot);
1269 		return;
1270 	}
1271 	if (sdhci_debug > 2)
1272 		slot_printf(slot, "Interrupt %#x\n", intmask);
1273 
1274 	/* Handle card presence interrupts. */
1275 	if (intmask & (SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE)) {
1276 		WR4(slot, SDHCI_INT_STATUS, intmask &
1277 		    (SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE));
1278 
1279 		if (intmask & SDHCI_INT_CARD_REMOVE) {
1280 			if (bootverbose || sdhci_debug)
1281 				slot_printf(slot, "Card removed\n");
1282 			callout_stop(&slot->card_callout);
1283 			taskqueue_enqueue(taskqueue_swi_giant,
1284 			    &slot->card_task);
1285 		}
1286 		if (intmask & SDHCI_INT_CARD_INSERT) {
1287 			if (bootverbose || sdhci_debug)
1288 				slot_printf(slot, "Card inserted\n");
1289 			callout_reset(&slot->card_callout, hz / 2,
1290 			    sdhci_card_delay, slot);
1291 		}
1292 		intmask &= ~(SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE);
1293 	}
1294 	/* Handle command interrupts. */
1295 	if (intmask & SDHCI_INT_CMD_MASK) {
1296 		WR4(slot, SDHCI_INT_STATUS, intmask & SDHCI_INT_CMD_MASK);
1297 		sdhci_cmd_irq(slot, intmask & SDHCI_INT_CMD_MASK);
1298 	}
1299 	/* Handle data interrupts. */
1300 	if (intmask & SDHCI_INT_DATA_MASK) {
1301 		WR4(slot, SDHCI_INT_STATUS, intmask & SDHCI_INT_DATA_MASK);
1302 		/* Dont call data_irq in case of errored command */
1303 		if ((intmask & SDHCI_INT_CMD_ERROR_MASK) == 0)
1304 			sdhci_data_irq(slot, intmask & SDHCI_INT_DATA_MASK);
1305 	}
1306 	/* Handle AutoCMD12 error interrupt. */
1307 	if (intmask & SDHCI_INT_ACMD12ERR) {
1308 		WR4(slot, SDHCI_INT_STATUS, SDHCI_INT_ACMD12ERR);
1309 		sdhci_acmd_irq(slot);
1310 	}
1311 	intmask &= ~(SDHCI_INT_CMD_MASK | SDHCI_INT_DATA_MASK);
1312 	intmask &= ~SDHCI_INT_ACMD12ERR;
1313 	intmask &= ~SDHCI_INT_ERROR;
1314 	/* Handle bus power interrupt. */
1315 	if (intmask & SDHCI_INT_BUS_POWER) {
1316 		WR4(slot, SDHCI_INT_STATUS, SDHCI_INT_BUS_POWER);
1317 		slot_printf(slot,
1318 		    "Card is consuming too much power!\n");
1319 		intmask &= ~SDHCI_INT_BUS_POWER;
1320 	}
1321 	/* The rest is unknown. */
1322 	if (intmask) {
1323 		WR4(slot, SDHCI_INT_STATUS, intmask);
1324 		slot_printf(slot, "Unexpected interrupt 0x%08x.\n",
1325 		    intmask);
1326 		sdhci_dumpregs(slot);
1327 	}
1328 
1329 	SDHCI_UNLOCK(slot);
1330 }
1331 
1332 int
1333 sdhci_generic_read_ivar(device_t bus, device_t child, int which, uintptr_t *result)
1334 {
1335 	struct sdhci_slot *slot = device_get_ivars(child);
1336 
1337 	switch (which) {
1338 	default:
1339 		return (EINVAL);
1340 	case MMCBR_IVAR_BUS_MODE:
1341 		*result = slot->host.ios.bus_mode;
1342 		break;
1343 	case MMCBR_IVAR_BUS_WIDTH:
1344 		*result = slot->host.ios.bus_width;
1345 		break;
1346 	case MMCBR_IVAR_CHIP_SELECT:
1347 		*result = slot->host.ios.chip_select;
1348 		break;
1349 	case MMCBR_IVAR_CLOCK:
1350 		*result = slot->host.ios.clock;
1351 		break;
1352 	case MMCBR_IVAR_F_MIN:
1353 		*result = slot->host.f_min;
1354 		break;
1355 	case MMCBR_IVAR_F_MAX:
1356 		*result = slot->host.f_max;
1357 		break;
1358 	case MMCBR_IVAR_HOST_OCR:
1359 		*result = slot->host.host_ocr;
1360 		break;
1361 	case MMCBR_IVAR_MODE:
1362 		*result = slot->host.mode;
1363 		break;
1364 	case MMCBR_IVAR_OCR:
1365 		*result = slot->host.ocr;
1366 		break;
1367 	case MMCBR_IVAR_POWER_MODE:
1368 		*result = slot->host.ios.power_mode;
1369 		break;
1370 	case MMCBR_IVAR_VDD:
1371 		*result = slot->host.ios.vdd;
1372 		break;
1373 	case MMCBR_IVAR_CAPS:
1374 		*result = slot->host.caps;
1375 		break;
1376 	case MMCBR_IVAR_TIMING:
1377 		*result = slot->host.ios.timing;
1378 		break;
1379 	case MMCBR_IVAR_MAX_DATA:
1380 		*result = 65535;
1381 		break;
1382 	}
1383 	return (0);
1384 }
1385 
1386 int
1387 sdhci_generic_write_ivar(device_t bus, device_t child, int which, uintptr_t value)
1388 {
1389 	struct sdhci_slot *slot = device_get_ivars(child);
1390 
1391 	switch (which) {
1392 	default:
1393 		return (EINVAL);
1394 	case MMCBR_IVAR_BUS_MODE:
1395 		slot->host.ios.bus_mode = value;
1396 		break;
1397 	case MMCBR_IVAR_BUS_WIDTH:
1398 		slot->host.ios.bus_width = value;
1399 		break;
1400 	case MMCBR_IVAR_CHIP_SELECT:
1401 		slot->host.ios.chip_select = value;
1402 		break;
1403 	case MMCBR_IVAR_CLOCK:
1404 		if (value > 0) {
1405 			uint32_t max_clock;
1406 			uint32_t clock;
1407 			int i;
1408 
1409 			max_clock = slot->max_clk;
1410 			clock = max_clock;
1411 
1412 			if (slot->version < SDHCI_SPEC_300) {
1413 				for (i = 0; i < SDHCI_200_MAX_DIVIDER;
1414 				    i <<= 1) {
1415 					if (clock <= value)
1416 						break;
1417 					clock >>= 1;
1418 				}
1419 			}
1420 			else {
1421 				for (i = 0; i < SDHCI_300_MAX_DIVIDER;
1422 				    i += 2) {
1423 					if (clock <= value)
1424 						break;
1425 					clock = max_clock / (i + 2);
1426 				}
1427 			}
1428 
1429 			slot->host.ios.clock = clock;
1430 		} else
1431 			slot->host.ios.clock = 0;
1432 		break;
1433 	case MMCBR_IVAR_MODE:
1434 		slot->host.mode = value;
1435 		break;
1436 	case MMCBR_IVAR_OCR:
1437 		slot->host.ocr = value;
1438 		break;
1439 	case MMCBR_IVAR_POWER_MODE:
1440 		slot->host.ios.power_mode = value;
1441 		break;
1442 	case MMCBR_IVAR_VDD:
1443 		slot->host.ios.vdd = value;
1444 		break;
1445 	case MMCBR_IVAR_TIMING:
1446 		slot->host.ios.timing = value;
1447 		break;
1448 	case MMCBR_IVAR_CAPS:
1449 	case MMCBR_IVAR_HOST_OCR:
1450 	case MMCBR_IVAR_F_MIN:
1451 	case MMCBR_IVAR_F_MAX:
1452 	case MMCBR_IVAR_MAX_DATA:
1453 		return (EINVAL);
1454 	}
1455 	return (0);
1456 }
1457 
1458 MODULE_VERSION(sdhci, 1);
1459