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