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