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