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