xref: /freebsd-13-stable/sys/dev/sdhci/sdhci.c (revision 3bc80996974a61a4223eae4c1ccd47b6ee32a48a)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2008 Alexander Motin <mav@FreeBSD.org>
5  * Copyright (c) 2017 Marius Strobl <marius@FreeBSD.org>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/bus.h>
33 #include <sys/callout.h>
34 #include <sys/conf.h>
35 #include <sys/kernel.h>
36 #include <sys/kobj.h>
37 #include <sys/libkern.h>
38 #include <sys/lock.h>
39 #include <sys/malloc.h>
40 #include <sys/module.h>
41 #include <sys/mutex.h>
42 #include <sys/resource.h>
43 #include <sys/rman.h>
44 #include <sys/sysctl.h>
45 #include <sys/taskqueue.h>
46 
47 #include <machine/bus.h>
48 #include <machine/resource.h>
49 #include <machine/stdarg.h>
50 
51 #include <dev/mmc/bridge.h>
52 #include <dev/mmc/mmcreg.h>
53 #include <dev/mmc/mmcbrvar.h>
54 
55 #include <dev/sdhci/sdhci.h>
56 
57 #include <cam/cam.h>
58 #include <cam/cam_ccb.h>
59 #include <cam/cam_debug.h>
60 #include <cam/cam_sim.h>
61 #include <cam/cam_xpt_sim.h>
62 
63 #include "mmcbr_if.h"
64 #include "sdhci_if.h"
65 
66 #include "opt_mmccam.h"
67 
68 SYSCTL_NODE(_hw, OID_AUTO, sdhci, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
69     "sdhci driver");
70 
71 static int sdhci_debug = 0;
72 SYSCTL_INT(_hw_sdhci, OID_AUTO, debug, CTLFLAG_RWTUN, &sdhci_debug, 0,
73     "Debug level");
74 u_int sdhci_quirk_clear = 0;
75 SYSCTL_INT(_hw_sdhci, OID_AUTO, quirk_clear, CTLFLAG_RWTUN, &sdhci_quirk_clear,
76     0, "Mask of quirks to clear");
77 u_int sdhci_quirk_set = 0;
78 SYSCTL_INT(_hw_sdhci, OID_AUTO, quirk_set, CTLFLAG_RWTUN, &sdhci_quirk_set, 0,
79     "Mask of quirks to set");
80 
81 #define	RD1(slot, off)	SDHCI_READ_1((slot)->bus, (slot), (off))
82 #define	RD2(slot, off)	SDHCI_READ_2((slot)->bus, (slot), (off))
83 #define	RD4(slot, off)	SDHCI_READ_4((slot)->bus, (slot), (off))
84 #define	RD_MULTI_4(slot, off, ptr, count)	\
85     SDHCI_READ_MULTI_4((slot)->bus, (slot), (off), (ptr), (count))
86 
87 #define	WR1(slot, off, val)	SDHCI_WRITE_1((slot)->bus, (slot), (off), (val))
88 #define	WR2(slot, off, val)	SDHCI_WRITE_2((slot)->bus, (slot), (off), (val))
89 #define	WR4(slot, off, val)	SDHCI_WRITE_4((slot)->bus, (slot), (off), (val))
90 #define	WR_MULTI_4(slot, off, ptr, count)	\
91     SDHCI_WRITE_MULTI_4((slot)->bus, (slot), (off), (ptr), (count))
92 
93 static void sdhci_acmd_irq(struct sdhci_slot *slot, uint16_t acmd_err);
94 static void sdhci_card_poll(void *arg);
95 static void sdhci_card_task(void *arg, int pending);
96 static void sdhci_cmd_irq(struct sdhci_slot *slot, uint32_t intmask);
97 static void sdhci_data_irq(struct sdhci_slot *slot, uint32_t intmask);
98 static int sdhci_exec_tuning(struct sdhci_slot *slot, bool reset);
99 static void sdhci_handle_card_present_locked(struct sdhci_slot *slot,
100     bool is_present);
101 static void sdhci_finish_command(struct sdhci_slot *slot);
102 static void sdhci_init(struct sdhci_slot *slot);
103 static void sdhci_read_block_pio(struct sdhci_slot *slot);
104 static void sdhci_req_done(struct sdhci_slot *slot);
105 static void sdhci_req_wakeup(struct mmc_request *req);
106 static void sdhci_reset(struct sdhci_slot *slot, uint8_t mask);
107 static void sdhci_retune(void *arg);
108 static void sdhci_set_clock(struct sdhci_slot *slot, uint32_t clock);
109 static void sdhci_set_power(struct sdhci_slot *slot, u_char power);
110 static void sdhci_set_transfer_mode(struct sdhci_slot *slot,
111    const struct mmc_data *data);
112 static void sdhci_start(struct sdhci_slot *slot);
113 static void sdhci_timeout(void *arg);
114 static void sdhci_start_command(struct sdhci_slot *slot,
115    struct mmc_command *cmd);
116 static void sdhci_start_data(struct sdhci_slot *slot,
117    const struct mmc_data *data);
118 static void sdhci_write_block_pio(struct sdhci_slot *slot);
119 static void sdhci_transfer_pio(struct sdhci_slot *slot);
120 
121 #ifdef MMCCAM
122 /* CAM-related */
123 static void sdhci_cam_action(struct cam_sim *sim, union ccb *ccb);
124 static int sdhci_cam_get_possible_host_clock(const struct sdhci_slot *slot,
125     int proposed_clock);
126 static void sdhci_cam_poll(struct cam_sim *sim);
127 static int sdhci_cam_request(struct sdhci_slot *slot, union ccb *ccb);
128 static int sdhci_cam_settran_settings(struct sdhci_slot *slot, union ccb *ccb);
129 static int sdhci_cam_update_ios(struct sdhci_slot *slot);
130 #endif
131 
132 /* helper routines */
133 static int sdhci_dma_alloc(struct sdhci_slot *slot);
134 static void sdhci_dma_free(struct sdhci_slot *slot);
135 static void sdhci_dumpregs(struct sdhci_slot *slot);
136 static void sdhci_getaddr(void *arg, bus_dma_segment_t *segs, int nsegs,
137     int error);
138 static int slot_printf(const struct sdhci_slot *slot, const char * fmt, ...)
139     __printflike(2, 3);
140 static uint32_t sdhci_tuning_intmask(const struct sdhci_slot *slot);
141 
142 #define	SDHCI_LOCK(_slot)		mtx_lock(&(_slot)->mtx)
143 #define	SDHCI_UNLOCK(_slot)		mtx_unlock(&(_slot)->mtx)
144 #define	SDHCI_LOCK_INIT(_slot) \
145 	mtx_init(&_slot->mtx, "SD slot mtx", "sdhci", MTX_DEF)
146 #define	SDHCI_LOCK_DESTROY(_slot)	mtx_destroy(&_slot->mtx);
147 #define	SDHCI_ASSERT_LOCKED(_slot)	mtx_assert(&_slot->mtx, MA_OWNED);
148 #define	SDHCI_ASSERT_UNLOCKED(_slot)	mtx_assert(&_slot->mtx, MA_NOTOWNED);
149 
150 #define	SDHCI_DEFAULT_MAX_FREQ	50
151 
152 #define	SDHCI_200_MAX_DIVIDER	256
153 #define	SDHCI_300_MAX_DIVIDER	2046
154 
155 #define	SDHCI_CARD_PRESENT_TICKS	(hz / 5)
156 #define	SDHCI_INSERT_DELAY_TICKS	(hz / 2)
157 
158 /*
159  * Broadcom BCM577xx Controller Constants
160  */
161 /* Maximum divider supported by the default clock source. */
162 #define	BCM577XX_DEFAULT_MAX_DIVIDER	256
163 /* Alternative clock's base frequency. */
164 #define	BCM577XX_ALT_CLOCK_BASE		63000000
165 
166 #define	BCM577XX_HOST_CONTROL		0x198
167 #define	BCM577XX_CTRL_CLKSEL_MASK	0xFFFFCFFF
168 #define	BCM577XX_CTRL_CLKSEL_SHIFT	12
169 #define	BCM577XX_CTRL_CLKSEL_DEFAULT	0x0
170 #define	BCM577XX_CTRL_CLKSEL_64MHZ	0x3
171 
172 static void
sdhci_getaddr(void * arg,bus_dma_segment_t * segs,int nsegs,int error)173 sdhci_getaddr(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
174 {
175 
176 	if (error != 0) {
177 		printf("getaddr: error %d\n", error);
178 		return;
179 	}
180 	*(bus_addr_t *)arg = segs[0].ds_addr;
181 }
182 
183 static int
slot_printf(const struct sdhci_slot * slot,const char * fmt,...)184 slot_printf(const struct sdhci_slot *slot, const char * fmt, ...)
185 {
186 	char buf[128];
187 	va_list ap;
188 	int retval;
189 
190 	/*
191 	 * Make sure we print a single line all together rather than in two
192 	 * halves to avoid console gibberish bingo.
193 	 */
194 	va_start(ap, fmt);
195 	retval = vsnprintf(buf, sizeof(buf), fmt, ap);
196 	va_end(ap);
197 
198 	retval += printf("%s-slot%d: %s",
199 	    device_get_nameunit(slot->bus), slot->num, buf);
200 	return (retval);
201 }
202 
203 static void
sdhci_dumpregs(struct sdhci_slot * slot)204 sdhci_dumpregs(struct sdhci_slot *slot)
205 {
206 
207 	slot_printf(slot,
208 	    "============== REGISTER DUMP ==============\n");
209 
210 	slot_printf(slot, "Sys addr: 0x%08x | Version:  0x%08x\n",
211 	    RD4(slot, SDHCI_DMA_ADDRESS), RD2(slot, SDHCI_HOST_VERSION));
212 	slot_printf(slot, "Blk size: 0x%08x | Blk cnt:  0x%08x\n",
213 	    RD2(slot, SDHCI_BLOCK_SIZE), RD2(slot, SDHCI_BLOCK_COUNT));
214 	slot_printf(slot, "Argument: 0x%08x | Trn mode: 0x%08x\n",
215 	    RD4(slot, SDHCI_ARGUMENT), RD2(slot, SDHCI_TRANSFER_MODE));
216 	slot_printf(slot, "Present:  0x%08x | Host ctl: 0x%08x\n",
217 	    RD4(slot, SDHCI_PRESENT_STATE), RD1(slot, SDHCI_HOST_CONTROL));
218 	slot_printf(slot, "Power:    0x%08x | Blk gap:  0x%08x\n",
219 	    RD1(slot, SDHCI_POWER_CONTROL), RD1(slot, SDHCI_BLOCK_GAP_CONTROL));
220 	slot_printf(slot, "Wake-up:  0x%08x | Clock:    0x%08x\n",
221 	    RD1(slot, SDHCI_WAKE_UP_CONTROL), RD2(slot, SDHCI_CLOCK_CONTROL));
222 	slot_printf(slot, "Timeout:  0x%08x | Int stat: 0x%08x\n",
223 	    RD1(slot, SDHCI_TIMEOUT_CONTROL), RD4(slot, SDHCI_INT_STATUS));
224 	slot_printf(slot, "Int enab: 0x%08x | Sig enab: 0x%08x\n",
225 	    RD4(slot, SDHCI_INT_ENABLE), RD4(slot, SDHCI_SIGNAL_ENABLE));
226 	slot_printf(slot, "AC12 err: 0x%08x | Host ctl2:0x%08x\n",
227 	    RD2(slot, SDHCI_ACMD12_ERR), RD2(slot, SDHCI_HOST_CONTROL2));
228 	slot_printf(slot, "Caps:     0x%08x | Caps2:    0x%08x\n",
229 	    RD4(slot, SDHCI_CAPABILITIES), RD4(slot, SDHCI_CAPABILITIES2));
230 	slot_printf(slot, "Max curr: 0x%08x | ADMA err: 0x%08x\n",
231 	    RD4(slot, SDHCI_MAX_CURRENT), RD1(slot, SDHCI_ADMA_ERR));
232 	slot_printf(slot, "ADMA addr:0x%08x | Slot int: 0x%08x\n",
233 	    RD4(slot, SDHCI_ADMA_ADDRESS_LO), RD2(slot, SDHCI_SLOT_INT_STATUS));
234 
235 	slot_printf(slot,
236 	    "===========================================\n");
237 }
238 
239 static void
sdhci_reset(struct sdhci_slot * slot,uint8_t mask)240 sdhci_reset(struct sdhci_slot *slot, uint8_t mask)
241 {
242 	int timeout;
243 	uint32_t clock;
244 
245 	if (slot->quirks & SDHCI_QUIRK_NO_CARD_NO_RESET) {
246 		if (!SDHCI_GET_CARD_PRESENT(slot->bus, slot))
247 			return;
248 	}
249 
250 	/* Some controllers need this kick or reset won't work. */
251 	if ((mask & SDHCI_RESET_ALL) == 0 &&
252 	    (slot->quirks & SDHCI_QUIRK_CLOCK_BEFORE_RESET)) {
253 		/* This is to force an update */
254 		clock = slot->clock;
255 		slot->clock = 0;
256 		sdhci_set_clock(slot, clock);
257 	}
258 
259 	if (mask & SDHCI_RESET_ALL) {
260 		slot->clock = 0;
261 		slot->power = 0;
262 	}
263 
264 	WR1(slot, SDHCI_SOFTWARE_RESET, mask);
265 
266 	if (slot->quirks & SDHCI_QUIRK_WAITFOR_RESET_ASSERTED) {
267 		/*
268 		 * Resets on TI OMAPs and AM335x are incompatible with SDHCI
269 		 * specification.  The reset bit has internal propagation delay,
270 		 * so a fast read after write returns 0 even if reset process is
271 		 * in progress.  The workaround is to poll for 1 before polling
272 		 * for 0.  In the worst case, if we miss seeing it asserted the
273 		 * time we spent waiting is enough to ensure the reset finishes.
274 		 */
275 		timeout = 10000;
276 		while ((RD1(slot, SDHCI_SOFTWARE_RESET) & mask) != mask) {
277 			if (timeout <= 0)
278 				break;
279 			timeout--;
280 			DELAY(1);
281 		}
282 	}
283 
284 	/* Wait max 100 ms */
285 	timeout = 10000;
286 	/* Controller clears the bits when it's done */
287 	while (RD1(slot, SDHCI_SOFTWARE_RESET) & mask) {
288 		if (timeout <= 0) {
289 			slot_printf(slot, "Reset 0x%x never completed.\n",
290 			    mask);
291 			sdhci_dumpregs(slot);
292 			return;
293 		}
294 		timeout--;
295 		DELAY(10);
296 	}
297 }
298 
299 static uint32_t
sdhci_tuning_intmask(const struct sdhci_slot * slot)300 sdhci_tuning_intmask(const struct sdhci_slot *slot)
301 {
302 	uint32_t intmask;
303 
304 	intmask = 0;
305 	if (slot->opt & SDHCI_TUNING_ENABLED) {
306 		intmask |= SDHCI_INT_TUNEERR;
307 		if (slot->retune_mode == SDHCI_RETUNE_MODE_2 ||
308 		    slot->retune_mode == SDHCI_RETUNE_MODE_3)
309 			intmask |= SDHCI_INT_RETUNE;
310 	}
311 	return (intmask);
312 }
313 
314 static void
sdhci_init(struct sdhci_slot * slot)315 sdhci_init(struct sdhci_slot *slot)
316 {
317 
318 	sdhci_reset(slot, SDHCI_RESET_ALL);
319 
320 	/* Enable interrupts. */
321 	slot->intmask = SDHCI_INT_BUS_POWER | SDHCI_INT_DATA_END_BIT |
322 	    SDHCI_INT_DATA_CRC | SDHCI_INT_DATA_TIMEOUT | SDHCI_INT_INDEX |
323 	    SDHCI_INT_END_BIT | SDHCI_INT_CRC | SDHCI_INT_TIMEOUT |
324 	    SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL |
325 	    SDHCI_INT_DMA_END | SDHCI_INT_DATA_END | SDHCI_INT_RESPONSE |
326 	    SDHCI_INT_ACMD12ERR;
327 
328 	if (!(slot->quirks & SDHCI_QUIRK_POLL_CARD_PRESENT) &&
329 	    !(slot->opt & SDHCI_NON_REMOVABLE)) {
330 		slot->intmask |= SDHCI_INT_CARD_REMOVE | SDHCI_INT_CARD_INSERT;
331 	}
332 
333 	WR4(slot, SDHCI_INT_ENABLE, slot->intmask);
334 	WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask);
335 }
336 
337 static void
sdhci_set_clock(struct sdhci_slot * slot,uint32_t clock)338 sdhci_set_clock(struct sdhci_slot *slot, uint32_t clock)
339 {
340 	uint32_t clk_base;
341 	uint32_t clk_sel;
342 	uint32_t res;
343 	uint16_t clk;
344 	uint16_t div;
345 	int timeout;
346 
347 	if (clock == slot->clock)
348 		return;
349 	slot->clock = clock;
350 
351 	/* Turn off the clock. */
352 	clk = RD2(slot, SDHCI_CLOCK_CONTROL);
353 	WR2(slot, SDHCI_CLOCK_CONTROL, clk & ~SDHCI_CLOCK_CARD_EN);
354 	/* If no clock requested - leave it so. */
355 	if (clock == 0)
356 		return;
357 
358 	/* Determine the clock base frequency */
359 	clk_base = slot->max_clk;
360 	if (slot->quirks & SDHCI_QUIRK_BCM577XX_400KHZ_CLKSRC) {
361 		clk_sel = RD2(slot, BCM577XX_HOST_CONTROL) &
362 		    BCM577XX_CTRL_CLKSEL_MASK;
363 
364 		/*
365 		 * Select clock source appropriate for the requested frequency.
366 		 */
367 		if ((clk_base / BCM577XX_DEFAULT_MAX_DIVIDER) > clock) {
368 			clk_base = BCM577XX_ALT_CLOCK_BASE;
369 			clk_sel |= (BCM577XX_CTRL_CLKSEL_64MHZ <<
370 			    BCM577XX_CTRL_CLKSEL_SHIFT);
371 		} else {
372 			clk_sel |= (BCM577XX_CTRL_CLKSEL_DEFAULT <<
373 			    BCM577XX_CTRL_CLKSEL_SHIFT);
374 		}
375 
376 		WR2(slot, BCM577XX_HOST_CONTROL, clk_sel);
377 	}
378 
379 	/* Recalculate timeout clock frequency based on the new sd clock. */
380 	if (slot->quirks & SDHCI_QUIRK_DATA_TIMEOUT_USES_SDCLK)
381 		slot->timeout_clk = slot->clock / 1000;
382 
383 	if (slot->version < SDHCI_SPEC_300) {
384 		/* Looking for highest freq <= clock. */
385 		res = clk_base;
386 		for (div = 1; div < SDHCI_200_MAX_DIVIDER; div <<= 1) {
387 			if (res <= clock)
388 				break;
389 			res >>= 1;
390 		}
391 		/* Divider 1:1 is 0x00, 2:1 is 0x01, 256:1 is 0x80 ... */
392 		div >>= 1;
393 	} else {
394 		/* Version 3.0 divisors are multiples of two up to 1023 * 2 */
395 		if (clock >= clk_base)
396 			div = 0;
397 		else {
398 			for (div = 2; div < SDHCI_300_MAX_DIVIDER; div += 2) {
399 				if ((clk_base / div) <= clock)
400 					break;
401 			}
402 		}
403 		div >>= 1;
404 	}
405 
406 	if (bootverbose || sdhci_debug)
407 		slot_printf(slot, "Divider %d for freq %d (base %d)\n",
408 			div, clock, clk_base);
409 
410 	/* Now we have got divider, set it. */
411 	clk = (div & SDHCI_DIVIDER_MASK) << SDHCI_DIVIDER_SHIFT;
412 	clk |= ((div >> SDHCI_DIVIDER_MASK_LEN) & SDHCI_DIVIDER_HI_MASK)
413 		<< SDHCI_DIVIDER_HI_SHIFT;
414 
415 	WR2(slot, SDHCI_CLOCK_CONTROL, clk);
416 	/* Enable clock. */
417 	clk |= SDHCI_CLOCK_INT_EN;
418 	WR2(slot, SDHCI_CLOCK_CONTROL, clk);
419 	/* Wait up to 10 ms until it stabilize. */
420 	timeout = 10;
421 	while (!((clk = RD2(slot, SDHCI_CLOCK_CONTROL))
422 		& SDHCI_CLOCK_INT_STABLE)) {
423 		if (timeout == 0) {
424 			slot_printf(slot,
425 			    "Internal clock never stabilised.\n");
426 			sdhci_dumpregs(slot);
427 			return;
428 		}
429 		timeout--;
430 		DELAY(1000);
431 	}
432 	/* Pass clock signal to the bus. */
433 	clk |= SDHCI_CLOCK_CARD_EN;
434 	WR2(slot, SDHCI_CLOCK_CONTROL, clk);
435 }
436 
437 static void
sdhci_set_power(struct sdhci_slot * slot,u_char power)438 sdhci_set_power(struct sdhci_slot *slot, u_char power)
439 {
440 	int i;
441 	uint8_t pwr;
442 
443 	if (slot->power == power)
444 		return;
445 
446 	slot->power = power;
447 
448 	/* Turn off the power. */
449 	pwr = 0;
450 	WR1(slot, SDHCI_POWER_CONTROL, pwr);
451 	/* If power down requested - leave it so. */
452 	if (power == 0)
453 		return;
454 	/* Set voltage. */
455 	switch (1 << power) {
456 	case MMC_OCR_LOW_VOLTAGE:
457 		pwr |= SDHCI_POWER_180;
458 		break;
459 	case MMC_OCR_290_300:
460 	case MMC_OCR_300_310:
461 		pwr |= SDHCI_POWER_300;
462 		break;
463 	case MMC_OCR_320_330:
464 	case MMC_OCR_330_340:
465 		pwr |= SDHCI_POWER_330;
466 		break;
467 	}
468 	WR1(slot, SDHCI_POWER_CONTROL, pwr);
469 	/*
470 	 * Turn on VDD1 power.  Note that at least some Intel controllers can
471 	 * fail to enable bus power on the first try after transiting from D3
472 	 * to D0, so we give them up to 2 ms.
473 	 */
474 	pwr |= SDHCI_POWER_ON;
475 	for (i = 0; i < 20; i++) {
476 		WR1(slot, SDHCI_POWER_CONTROL, pwr);
477 		if (RD1(slot, SDHCI_POWER_CONTROL) & SDHCI_POWER_ON)
478 			break;
479 		DELAY(100);
480 	}
481 	if (!(RD1(slot, SDHCI_POWER_CONTROL) & SDHCI_POWER_ON))
482 		slot_printf(slot, "Bus power failed to enable\n");
483 
484 	if (slot->quirks & SDHCI_QUIRK_INTEL_POWER_UP_RESET) {
485 		WR1(slot, SDHCI_POWER_CONTROL, pwr | 0x10);
486 		DELAY(10);
487 		WR1(slot, SDHCI_POWER_CONTROL, pwr);
488 		DELAY(300);
489 	}
490 }
491 
492 static void
sdhci_read_block_pio(struct sdhci_slot * slot)493 sdhci_read_block_pio(struct sdhci_slot *slot)
494 {
495 	uint32_t data;
496 	char *buffer;
497 	size_t left;
498 
499 	buffer = slot->curcmd->data->data;
500 	buffer += slot->offset;
501 	/* Transfer one block at a time. */
502 #ifdef MMCCAM
503 	if (slot->curcmd->data->flags & MMC_DATA_BLOCK_SIZE)
504 		left = min(slot->curcmd->data->block_size,
505 		    slot->curcmd->data->len - slot->offset);
506 	else
507 #endif
508 		left = min(512, slot->curcmd->data->len - slot->offset);
509 	slot->offset += left;
510 
511 	/* If we are too fast, broken controllers return zeroes. */
512 	if (slot->quirks & SDHCI_QUIRK_BROKEN_TIMINGS)
513 		DELAY(10);
514 	/* Handle unaligned and aligned buffer cases. */
515 	if ((intptr_t)buffer & 3) {
516 		while (left > 3) {
517 			data = RD4(slot, SDHCI_BUFFER);
518 			buffer[0] = data;
519 			buffer[1] = (data >> 8);
520 			buffer[2] = (data >> 16);
521 			buffer[3] = (data >> 24);
522 			buffer += 4;
523 			left -= 4;
524 		}
525 	} else {
526 		RD_MULTI_4(slot, SDHCI_BUFFER,
527 		    (uint32_t *)buffer, left >> 2);
528 		left &= 3;
529 	}
530 	/* Handle uneven size case. */
531 	if (left > 0) {
532 		data = RD4(slot, SDHCI_BUFFER);
533 		while (left > 0) {
534 			*(buffer++) = data;
535 			data >>= 8;
536 			left--;
537 		}
538 	}
539 }
540 
541 static void
sdhci_write_block_pio(struct sdhci_slot * slot)542 sdhci_write_block_pio(struct sdhci_slot *slot)
543 {
544 	uint32_t data = 0;
545 	char *buffer;
546 	size_t left;
547 
548 	buffer = slot->curcmd->data->data;
549 	buffer += slot->offset;
550 	/* Transfer one block at a time. */
551 #ifdef MMCCAM
552 	if (slot->curcmd->data->flags & MMC_DATA_BLOCK_SIZE) {
553 		left = min(slot->curcmd->data->block_size,
554 		    slot->curcmd->data->len - slot->offset);
555 	} else
556 #endif
557 		left = min(512, slot->curcmd->data->len - slot->offset);
558 	slot->offset += left;
559 
560 	/* Handle unaligned and aligned buffer cases. */
561 	if ((intptr_t)buffer & 3) {
562 		while (left > 3) {
563 			data = buffer[0] +
564 			    (buffer[1] << 8) +
565 			    (buffer[2] << 16) +
566 			    (buffer[3] << 24);
567 			left -= 4;
568 			buffer += 4;
569 			WR4(slot, SDHCI_BUFFER, data);
570 		}
571 	} else {
572 		WR_MULTI_4(slot, SDHCI_BUFFER,
573 		    (uint32_t *)buffer, left >> 2);
574 		left &= 3;
575 	}
576 	/* Handle uneven size case. */
577 	if (left > 0) {
578 		while (left > 0) {
579 			data <<= 8;
580 			data += *(buffer++);
581 			left--;
582 		}
583 		WR4(slot, SDHCI_BUFFER, data);
584 	}
585 }
586 
587 static void
sdhci_transfer_pio(struct sdhci_slot * slot)588 sdhci_transfer_pio(struct sdhci_slot *slot)
589 {
590 
591 	/* Read as many blocks as possible. */
592 	if (slot->curcmd->data->flags & MMC_DATA_READ) {
593 		while (RD4(slot, SDHCI_PRESENT_STATE) &
594 		    SDHCI_DATA_AVAILABLE) {
595 			sdhci_read_block_pio(slot);
596 			if (slot->offset >= slot->curcmd->data->len)
597 				break;
598 		}
599 	} else {
600 		while (RD4(slot, SDHCI_PRESENT_STATE) &
601 		    SDHCI_SPACE_AVAILABLE) {
602 			sdhci_write_block_pio(slot);
603 			if (slot->offset >= slot->curcmd->data->len)
604 				break;
605 		}
606 	}
607 }
608 
609 static void
sdhci_card_task(void * arg,int pending __unused)610 sdhci_card_task(void *arg, int pending __unused)
611 {
612 	struct sdhci_slot *slot = arg;
613 	device_t d;
614 
615 	SDHCI_LOCK(slot);
616 	if (SDHCI_GET_CARD_PRESENT(slot->bus, slot)) {
617 #ifdef MMCCAM
618 		if (slot->card_present == 0) {
619 #else
620 		if (slot->dev == NULL) {
621 #endif
622 			/* If card is present - attach mmc bus. */
623 			if (bootverbose || sdhci_debug)
624 				slot_printf(slot, "Card inserted\n");
625 #ifdef MMCCAM
626 			slot->card_present = 1;
627 			mmccam_start_discovery(slot->sim);
628 			SDHCI_UNLOCK(slot);
629 #else
630 			d = slot->dev = device_add_child(slot->bus, "mmc", -1);
631 			SDHCI_UNLOCK(slot);
632 			if (d) {
633 				device_set_ivars(d, slot);
634 				(void)device_probe_and_attach(d);
635 			}
636 #endif
637 		} else
638 			SDHCI_UNLOCK(slot);
639 	} else {
640 #ifdef MMCCAM
641 		if (slot->card_present == 1) {
642 #else
643 		if (slot->dev != NULL) {
644 #endif
645 			/* If no card present - detach mmc bus. */
646 			if (bootverbose || sdhci_debug)
647 				slot_printf(slot, "Card removed\n");
648 			d = slot->dev;
649 			slot->dev = NULL;
650 #ifdef MMCCAM
651 			slot->card_present = 0;
652 			mmccam_start_discovery(slot->sim);
653 			SDHCI_UNLOCK(slot);
654 #else
655 			slot->intmask &= ~sdhci_tuning_intmask(slot);
656 			WR4(slot, SDHCI_INT_ENABLE, slot->intmask);
657 			WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask);
658 			slot->opt &= ~SDHCI_TUNING_ENABLED;
659 			SDHCI_UNLOCK(slot);
660 			callout_drain(&slot->retune_callout);
661 			device_delete_child(slot->bus, d);
662 #endif
663 		} else
664 			SDHCI_UNLOCK(slot);
665 	}
666 }
667 
668 static void
669 sdhci_handle_card_present_locked(struct sdhci_slot *slot, bool is_present)
670 {
671 	bool was_present;
672 
673 	/*
674 	 * If there was no card and now there is one, schedule the task to
675 	 * create the child device after a short delay.  The delay is to
676 	 * debounce the card insert (sometimes the card detect pin stabilizes
677 	 * before the other pins have made good contact).
678 	 *
679 	 * If there was a card present and now it's gone, immediately schedule
680 	 * the task to delete the child device.  No debouncing -- gone is gone,
681 	 * because once power is removed, a full card re-init is needed, and
682 	 * that happens by deleting and recreating the child device.
683 	 */
684 #ifdef MMCCAM
685 	was_present = slot->card_present;
686 #else
687 	was_present = slot->dev != NULL;
688 #endif
689 	if (!was_present && is_present) {
690 		taskqueue_enqueue_timeout(taskqueue_swi_giant,
691 		    &slot->card_delayed_task, -SDHCI_INSERT_DELAY_TICKS);
692 	} else if (was_present && !is_present) {
693 		taskqueue_enqueue(taskqueue_swi_giant, &slot->card_task);
694 	}
695 }
696 
697 void
698 sdhci_handle_card_present(struct sdhci_slot *slot, bool is_present)
699 {
700 
701 	SDHCI_LOCK(slot);
702 	sdhci_handle_card_present_locked(slot, is_present);
703 	SDHCI_UNLOCK(slot);
704 }
705 
706 static void
707 sdhci_card_poll(void *arg)
708 {
709 	struct sdhci_slot *slot = arg;
710 
711 	sdhci_handle_card_present(slot,
712 	    SDHCI_GET_CARD_PRESENT(slot->bus, slot));
713 	callout_reset(&slot->card_poll_callout, SDHCI_CARD_PRESENT_TICKS,
714 	    sdhci_card_poll, slot);
715 }
716 
717 static int
718 sdhci_dma_alloc(struct sdhci_slot *slot)
719 {
720 	int err;
721 
722 	if (!(slot->quirks & SDHCI_QUIRK_BROKEN_SDMA_BOUNDARY)) {
723 		if (maxphys <= 1024 * 4)
724 			slot->sdma_boundary = SDHCI_BLKSZ_SDMA_BNDRY_4K;
725 		else if (maxphys <= 1024 * 8)
726 			slot->sdma_boundary = SDHCI_BLKSZ_SDMA_BNDRY_8K;
727 		else if (maxphys <= 1024 * 16)
728 			slot->sdma_boundary = SDHCI_BLKSZ_SDMA_BNDRY_16K;
729 		else if (maxphys <= 1024 * 32)
730 			slot->sdma_boundary = SDHCI_BLKSZ_SDMA_BNDRY_32K;
731 		else if (maxphys <= 1024 * 64)
732 			slot->sdma_boundary = SDHCI_BLKSZ_SDMA_BNDRY_64K;
733 		else if (maxphys <= 1024 * 128)
734 			slot->sdma_boundary = SDHCI_BLKSZ_SDMA_BNDRY_128K;
735 		else if (maxphys <= 1024 * 256)
736 			slot->sdma_boundary = SDHCI_BLKSZ_SDMA_BNDRY_256K;
737 		else
738 			slot->sdma_boundary = SDHCI_BLKSZ_SDMA_BNDRY_512K;
739 	}
740 	slot->sdma_bbufsz = SDHCI_SDMA_BNDRY_TO_BBUFSZ(slot->sdma_boundary);
741 
742 	/*
743 	 * Allocate the DMA tag for an SDMA bounce buffer.
744 	 * Note that the SDHCI specification doesn't state any alignment
745 	 * constraint for the SDMA system address.  However, controllers
746 	 * typically ignore the SDMA boundary bits in SDHCI_DMA_ADDRESS when
747 	 * forming the actual address of data, requiring the SDMA buffer to
748 	 * be aligned to the SDMA boundary.
749 	 */
750 	err = bus_dma_tag_create(bus_get_dma_tag(slot->bus), slot->sdma_bbufsz,
751 	    0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
752 	    slot->sdma_bbufsz, 1, slot->sdma_bbufsz, BUS_DMA_ALLOCNOW,
753 	    NULL, NULL, &slot->dmatag);
754 	if (err != 0) {
755 		slot_printf(slot, "Can't create DMA tag for SDMA\n");
756 		return (err);
757 	}
758 	/* Allocate DMA memory for the SDMA bounce buffer. */
759 	err = bus_dmamem_alloc(slot->dmatag, (void **)&slot->dmamem,
760 	    BUS_DMA_NOWAIT, &slot->dmamap);
761 	if (err != 0) {
762 		slot_printf(slot, "Can't alloc DMA memory for SDMA\n");
763 		bus_dma_tag_destroy(slot->dmatag);
764 		return (err);
765 	}
766 	/* Map the memory of the SDMA bounce buffer. */
767 	err = bus_dmamap_load(slot->dmatag, slot->dmamap,
768 	    (void *)slot->dmamem, slot->sdma_bbufsz, sdhci_getaddr,
769 	    &slot->paddr, 0);
770 	if (err != 0 || slot->paddr == 0) {
771 		slot_printf(slot, "Can't load DMA memory for SDMA\n");
772 		bus_dmamem_free(slot->dmatag, slot->dmamem, slot->dmamap);
773 		bus_dma_tag_destroy(slot->dmatag);
774 		if (err)
775 			return (err);
776 		else
777 			return (EFAULT);
778 	}
779 
780 	return (0);
781 }
782 
783 static void
784 sdhci_dma_free(struct sdhci_slot *slot)
785 {
786 
787 	bus_dmamap_unload(slot->dmatag, slot->dmamap);
788 	bus_dmamem_free(slot->dmatag, slot->dmamem, slot->dmamap);
789 	bus_dma_tag_destroy(slot->dmatag);
790 }
791 
792 int
793 sdhci_init_slot(device_t dev, struct sdhci_slot *slot, int num)
794 {
795 	kobjop_desc_t kobj_desc;
796 	kobj_method_t *kobj_method;
797 	uint32_t caps, caps2, freq, host_caps;
798 	int err;
799 
800 	SDHCI_LOCK_INIT(slot);
801 
802 	slot->num = num;
803 	slot->bus = dev;
804 
805 	slot->version = (RD2(slot, SDHCI_HOST_VERSION)
806 		>> SDHCI_SPEC_VER_SHIFT) & SDHCI_SPEC_VER_MASK;
807 	if (slot->quirks & SDHCI_QUIRK_MISSING_CAPS) {
808 		caps = slot->caps;
809 		caps2 = slot->caps2;
810 	} else {
811 		caps = RD4(slot, SDHCI_CAPABILITIES);
812 		if (slot->version >= SDHCI_SPEC_300)
813 			caps2 = RD4(slot, SDHCI_CAPABILITIES2);
814 		else
815 			caps2 = 0;
816 	}
817 	if (slot->version >= SDHCI_SPEC_300) {
818 		if ((caps & SDHCI_SLOTTYPE_MASK) != SDHCI_SLOTTYPE_REMOVABLE &&
819 		    (caps & SDHCI_SLOTTYPE_MASK) != SDHCI_SLOTTYPE_EMBEDDED) {
820 			slot_printf(slot,
821 			    "Driver doesn't support shared bus slots\n");
822 			SDHCI_LOCK_DESTROY(slot);
823 			return (ENXIO);
824 		} else if ((caps & SDHCI_SLOTTYPE_MASK) ==
825 		    SDHCI_SLOTTYPE_EMBEDDED) {
826 			slot->opt |= SDHCI_SLOT_EMBEDDED | SDHCI_NON_REMOVABLE;
827 		}
828 	}
829 	/* Calculate base clock frequency. */
830 	if (slot->version >= SDHCI_SPEC_300)
831 		freq = (caps & SDHCI_CLOCK_V3_BASE_MASK) >>
832 		    SDHCI_CLOCK_BASE_SHIFT;
833 	else
834 		freq = (caps & SDHCI_CLOCK_BASE_MASK) >>
835 		    SDHCI_CLOCK_BASE_SHIFT;
836 	if (freq != 0)
837 		slot->max_clk = freq * 1000000;
838 	/*
839 	 * If the frequency wasn't in the capabilities and the hardware driver
840 	 * hasn't already set max_clk we're probably not going to work right
841 	 * with an assumption, so complain about it.
842 	 */
843 	if (slot->max_clk == 0) {
844 		slot->max_clk = SDHCI_DEFAULT_MAX_FREQ * 1000000;
845 		slot_printf(slot, "Hardware doesn't specify base clock "
846 		    "frequency, using %dMHz as default.\n",
847 		    SDHCI_DEFAULT_MAX_FREQ);
848 	}
849 	/* Calculate/set timeout clock frequency. */
850 	if (slot->quirks & SDHCI_QUIRK_DATA_TIMEOUT_USES_SDCLK) {
851 		slot->timeout_clk = slot->max_clk / 1000;
852 	} else if (slot->quirks & SDHCI_QUIRK_DATA_TIMEOUT_1MHZ) {
853 		slot->timeout_clk = 1000;
854 	} else {
855 		slot->timeout_clk = (caps & SDHCI_TIMEOUT_CLK_MASK) >>
856 		    SDHCI_TIMEOUT_CLK_SHIFT;
857 		if (caps & SDHCI_TIMEOUT_CLK_UNIT)
858 			slot->timeout_clk *= 1000;
859 	}
860 	/*
861 	 * If the frequency wasn't in the capabilities and the hardware driver
862 	 * hasn't already set timeout_clk we'll probably work okay using the
863 	 * max timeout, but still mention it.
864 	 */
865 	if (slot->timeout_clk == 0) {
866 		slot_printf(slot, "Hardware doesn't specify timeout clock "
867 		    "frequency, setting BROKEN_TIMEOUT quirk.\n");
868 		slot->quirks |= SDHCI_QUIRK_BROKEN_TIMEOUT_VAL;
869 	}
870 
871 	slot->host.f_min = SDHCI_MIN_FREQ(slot->bus, slot);
872 	slot->host.f_max = slot->max_clk;
873 	slot->host.host_ocr = 0;
874 	if (caps & SDHCI_CAN_VDD_330)
875 	    slot->host.host_ocr |= MMC_OCR_320_330 | MMC_OCR_330_340;
876 	if (caps & SDHCI_CAN_VDD_300)
877 	    slot->host.host_ocr |= MMC_OCR_290_300 | MMC_OCR_300_310;
878 	/*
879 	 * 1.8V VDD is not supposed to be used for removable cards.  Hardware
880 	 * prior to v3.0 had no way to indicate embedded slots, but did
881 	 * sometimes support 1.8v for non-removable devices.
882 	 */
883 	if ((caps & SDHCI_CAN_VDD_180) && (slot->version < SDHCI_SPEC_300 ||
884 	    (slot->opt & SDHCI_SLOT_EMBEDDED)))
885 	    slot->host.host_ocr |= MMC_OCR_LOW_VOLTAGE;
886 	if (slot->host.host_ocr == 0) {
887 		slot_printf(slot, "Hardware doesn't report any "
888 		    "support voltages.\n");
889 	}
890 
891 	host_caps = slot->host.caps;
892 	host_caps |= MMC_CAP_4_BIT_DATA;
893 	if (caps & SDHCI_CAN_DO_8BITBUS)
894 		host_caps |= MMC_CAP_8_BIT_DATA;
895 	if (caps & SDHCI_CAN_DO_HISPD)
896 		host_caps |= MMC_CAP_HSPEED;
897 	if (slot->quirks & SDHCI_QUIRK_BOOT_NOACC)
898 		host_caps |= MMC_CAP_BOOT_NOACC;
899 	if (slot->quirks & SDHCI_QUIRK_WAIT_WHILE_BUSY)
900 		host_caps |= MMC_CAP_WAIT_WHILE_BUSY;
901 
902 	/* Determine supported UHS-I and eMMC modes. */
903 	if (caps2 & (SDHCI_CAN_SDR50 | SDHCI_CAN_SDR104 | SDHCI_CAN_DDR50))
904 		host_caps |= MMC_CAP_UHS_SDR12 | MMC_CAP_UHS_SDR25;
905 	if (caps2 & SDHCI_CAN_SDR104) {
906 		host_caps |= MMC_CAP_UHS_SDR104 | MMC_CAP_UHS_SDR50;
907 		if (!(slot->quirks & SDHCI_QUIRK_BROKEN_MMC_HS200))
908 			host_caps |= MMC_CAP_MMC_HS200;
909 	} else if (caps2 & SDHCI_CAN_SDR50)
910 		host_caps |= MMC_CAP_UHS_SDR50;
911 	if (caps2 & SDHCI_CAN_DDR50 &&
912 	    !(slot->quirks & SDHCI_QUIRK_BROKEN_UHS_DDR50))
913 		host_caps |= MMC_CAP_UHS_DDR50;
914 	if (slot->quirks & SDHCI_QUIRK_MMC_DDR52)
915 		host_caps |= MMC_CAP_MMC_DDR52;
916 	if (slot->quirks & SDHCI_QUIRK_CAPS_BIT63_FOR_MMC_HS400 &&
917 	    caps2 & SDHCI_CAN_MMC_HS400)
918 		host_caps |= MMC_CAP_MMC_HS400;
919 	if (slot->quirks & SDHCI_QUIRK_MMC_HS400_IF_CAN_SDR104 &&
920 	    caps2 & SDHCI_CAN_SDR104)
921 		host_caps |= MMC_CAP_MMC_HS400;
922 
923 	/*
924 	 * Disable UHS-I and eMMC modes if the set_uhs_timing method is the
925 	 * default NULL implementation.
926 	 */
927 	kobj_desc = &sdhci_set_uhs_timing_desc;
928 	kobj_method = kobj_lookup_method(((kobj_t)dev)->ops->cls, NULL,
929 	    kobj_desc);
930 	if (kobj_method == &kobj_desc->deflt)
931 		host_caps &= ~(MMC_CAP_UHS_SDR12 | MMC_CAP_UHS_SDR25 |
932 		    MMC_CAP_UHS_SDR50 | MMC_CAP_UHS_DDR50 | MMC_CAP_UHS_SDR104 |
933 		    MMC_CAP_MMC_DDR52 | MMC_CAP_MMC_HS200 | MMC_CAP_MMC_HS400);
934 
935 #define	SDHCI_CAP_MODES_TUNING(caps2)					\
936     (((caps2) & SDHCI_TUNE_SDR50 ? MMC_CAP_UHS_SDR50 : 0) |		\
937     MMC_CAP_UHS_DDR50 | MMC_CAP_UHS_SDR104 | MMC_CAP_MMC_HS200 |	\
938     MMC_CAP_MMC_HS400)
939 
940 	/*
941 	 * Disable UHS-I and eMMC modes that require (re-)tuning if either
942 	 * the tune or re-tune method is the default NULL implementation.
943 	 */
944 	kobj_desc = &mmcbr_tune_desc;
945 	kobj_method = kobj_lookup_method(((kobj_t)dev)->ops->cls, NULL,
946 	    kobj_desc);
947 	if (kobj_method == &kobj_desc->deflt)
948 		goto no_tuning;
949 	kobj_desc = &mmcbr_retune_desc;
950 	kobj_method = kobj_lookup_method(((kobj_t)dev)->ops->cls, NULL,
951 	    kobj_desc);
952 	if (kobj_method == &kobj_desc->deflt) {
953 no_tuning:
954 		host_caps &= ~(SDHCI_CAP_MODES_TUNING(caps2));
955 	}
956 
957 	/* Allocate tuning structures and determine tuning parameters. */
958 	if (host_caps & SDHCI_CAP_MODES_TUNING(caps2)) {
959 		slot->opt |= SDHCI_TUNING_SUPPORTED;
960 		slot->tune_req = malloc(sizeof(*slot->tune_req), M_DEVBUF,
961 		    M_WAITOK);
962 		slot->tune_cmd = malloc(sizeof(*slot->tune_cmd), M_DEVBUF,
963 		    M_WAITOK);
964 		slot->tune_data = malloc(sizeof(*slot->tune_data), M_DEVBUF,
965 		    M_WAITOK);
966 		if (caps2 & SDHCI_TUNE_SDR50)
967 			slot->opt |= SDHCI_SDR50_NEEDS_TUNING;
968 		slot->retune_mode = (caps2 & SDHCI_RETUNE_MODES_MASK) >>
969 		    SDHCI_RETUNE_MODES_SHIFT;
970 		if (slot->retune_mode == SDHCI_RETUNE_MODE_1) {
971 			slot->retune_count = (caps2 & SDHCI_RETUNE_CNT_MASK) >>
972 			    SDHCI_RETUNE_CNT_SHIFT;
973 			if (slot->retune_count > 0xb) {
974 				slot_printf(slot, "Unknown re-tuning count "
975 				    "%x, using 1 sec\n", slot->retune_count);
976 				slot->retune_count = 1;
977 			} else if (slot->retune_count != 0)
978 				slot->retune_count =
979 				    1 << (slot->retune_count - 1);
980 		}
981 	}
982 
983 #undef SDHCI_CAP_MODES_TUNING
984 
985 	/* Determine supported VCCQ signaling levels. */
986 	host_caps |= MMC_CAP_SIGNALING_330;
987 	if (host_caps & (MMC_CAP_UHS_SDR12 | MMC_CAP_UHS_SDR25 |
988 	    MMC_CAP_UHS_SDR50 | MMC_CAP_UHS_DDR50 | MMC_CAP_UHS_SDR104 |
989 	    MMC_CAP_MMC_DDR52_180 | MMC_CAP_MMC_HS200_180 |
990 	    MMC_CAP_MMC_HS400_180))
991 		host_caps |= MMC_CAP_SIGNALING_120 | MMC_CAP_SIGNALING_180;
992 
993 	/*
994 	 * Disable 1.2 V and 1.8 V signaling if the switch_vccq method is the
995 	 * default NULL implementation.  Disable 1.2 V support if it's the
996 	 * generic SDHCI implementation.
997 	 */
998 	kobj_desc = &mmcbr_switch_vccq_desc;
999 	kobj_method = kobj_lookup_method(((kobj_t)dev)->ops->cls, NULL,
1000 	    kobj_desc);
1001 	if (kobj_method == &kobj_desc->deflt)
1002 		host_caps &= ~(MMC_CAP_SIGNALING_120 | MMC_CAP_SIGNALING_180);
1003 	else if (kobj_method->func == (kobjop_t)sdhci_generic_switch_vccq)
1004 		host_caps &= ~MMC_CAP_SIGNALING_120;
1005 
1006 	/* Determine supported driver types (type B is always mandatory). */
1007 	if (caps2 & SDHCI_CAN_DRIVE_TYPE_A)
1008 		host_caps |= MMC_CAP_DRIVER_TYPE_A;
1009 	if (caps2 & SDHCI_CAN_DRIVE_TYPE_C)
1010 		host_caps |= MMC_CAP_DRIVER_TYPE_C;
1011 	if (caps2 & SDHCI_CAN_DRIVE_TYPE_D)
1012 		host_caps |= MMC_CAP_DRIVER_TYPE_D;
1013 	slot->host.caps = host_caps;
1014 
1015 	/* Decide if we have usable DMA. */
1016 	if (caps & SDHCI_CAN_DO_DMA)
1017 		slot->opt |= SDHCI_HAVE_DMA;
1018 
1019 	if (slot->quirks & SDHCI_QUIRK_BROKEN_DMA)
1020 		slot->opt &= ~SDHCI_HAVE_DMA;
1021 	if (slot->quirks & SDHCI_QUIRK_FORCE_DMA)
1022 		slot->opt |= SDHCI_HAVE_DMA;
1023 	if (slot->quirks & SDHCI_QUIRK_ALL_SLOTS_NON_REMOVABLE)
1024 		slot->opt |= SDHCI_NON_REMOVABLE;
1025 
1026 	/*
1027 	 * Use platform-provided transfer backend
1028 	 * with PIO as a fallback mechanism
1029 	 */
1030 	if (slot->opt & SDHCI_PLATFORM_TRANSFER)
1031 		slot->opt &= ~SDHCI_HAVE_DMA;
1032 
1033 	if (slot->opt & SDHCI_HAVE_DMA) {
1034 		err = sdhci_dma_alloc(slot);
1035 		if (err != 0) {
1036 			if (slot->opt & SDHCI_TUNING_SUPPORTED) {
1037 				free(slot->tune_req, M_DEVBUF);
1038 				free(slot->tune_cmd, M_DEVBUF);
1039 				free(slot->tune_data, M_DEVBUF);
1040 			}
1041 			SDHCI_LOCK_DESTROY(slot);
1042 			return (err);
1043 		}
1044 	}
1045 
1046 	if (bootverbose || sdhci_debug) {
1047 		slot_printf(slot,
1048 		    "%uMHz%s %s VDD:%s%s%s VCCQ: 3.3V%s%s DRV: B%s%s%s %s %s\n",
1049 		    slot->max_clk / 1000000,
1050 		    (caps & SDHCI_CAN_DO_HISPD) ? " HS" : "",
1051 		    (host_caps & MMC_CAP_8_BIT_DATA) ? "8bits" :
1052 			((host_caps & MMC_CAP_4_BIT_DATA) ? "4bits" : "1bit"),
1053 		    (caps & SDHCI_CAN_VDD_330) ? " 3.3V" : "",
1054 		    (caps & SDHCI_CAN_VDD_300) ? " 3.0V" : "",
1055 		    ((caps & SDHCI_CAN_VDD_180) &&
1056 		    (slot->opt & SDHCI_SLOT_EMBEDDED)) ? " 1.8V" : "",
1057 		    (host_caps & MMC_CAP_SIGNALING_180) ? " 1.8V" : "",
1058 		    (host_caps & MMC_CAP_SIGNALING_120) ? " 1.2V" : "",
1059 		    (host_caps & MMC_CAP_DRIVER_TYPE_A) ? "A" : "",
1060 		    (host_caps & MMC_CAP_DRIVER_TYPE_C) ? "C" : "",
1061 		    (host_caps & MMC_CAP_DRIVER_TYPE_D) ? "D" : "",
1062 		    (slot->opt & SDHCI_HAVE_DMA) ? "DMA" : "PIO",
1063 		    (slot->opt & SDHCI_SLOT_EMBEDDED) ? "embedded" :
1064 		    (slot->opt & SDHCI_NON_REMOVABLE) ? "non-removable" :
1065 		    "removable");
1066 		if (host_caps & (MMC_CAP_MMC_DDR52 | MMC_CAP_MMC_HS200 |
1067 		    MMC_CAP_MMC_HS400 | MMC_CAP_MMC_ENH_STROBE))
1068 			slot_printf(slot, "eMMC:%s%s%s%s\n",
1069 			    (host_caps & MMC_CAP_MMC_DDR52) ? " DDR52" : "",
1070 			    (host_caps & MMC_CAP_MMC_HS200) ? " HS200" : "",
1071 			    (host_caps & MMC_CAP_MMC_HS400) ? " HS400" : "",
1072 			    ((host_caps &
1073 			    (MMC_CAP_MMC_HS400 | MMC_CAP_MMC_ENH_STROBE)) ==
1074 			    (MMC_CAP_MMC_HS400 | MMC_CAP_MMC_ENH_STROBE)) ?
1075 			    " HS400ES" : "");
1076 		if (host_caps & (MMC_CAP_UHS_SDR12 | MMC_CAP_UHS_SDR25 |
1077 		    MMC_CAP_UHS_SDR50 | MMC_CAP_UHS_SDR104))
1078 			slot_printf(slot, "UHS-I:%s%s%s%s%s\n",
1079 			    (host_caps & MMC_CAP_UHS_SDR12) ? " SDR12" : "",
1080 			    (host_caps & MMC_CAP_UHS_SDR25) ? " SDR25" : "",
1081 			    (host_caps & MMC_CAP_UHS_SDR50) ? " SDR50" : "",
1082 			    (host_caps & MMC_CAP_UHS_SDR104) ? " SDR104" : "",
1083 			    (host_caps & MMC_CAP_UHS_DDR50) ? " DDR50" : "");
1084 		if (slot->opt & SDHCI_TUNING_SUPPORTED)
1085 			slot_printf(slot, "Re-tuning count %d secs, mode %d\n",
1086 			    slot->retune_count, slot->retune_mode + 1);
1087 		sdhci_dumpregs(slot);
1088 	}
1089 
1090 	slot->timeout = 10;
1091 	SYSCTL_ADD_INT(device_get_sysctl_ctx(slot->bus),
1092 	    SYSCTL_CHILDREN(device_get_sysctl_tree(slot->bus)), OID_AUTO,
1093 	    "timeout", CTLFLAG_RWTUN, &slot->timeout, 0,
1094 	    "Maximum timeout for SDHCI transfers (in secs)");
1095 	TASK_INIT(&slot->card_task, 0, sdhci_card_task, slot);
1096 	TIMEOUT_TASK_INIT(taskqueue_swi_giant, &slot->card_delayed_task, 0,
1097 		sdhci_card_task, slot);
1098 	callout_init(&slot->card_poll_callout, 1);
1099 	callout_init_mtx(&slot->timeout_callout, &slot->mtx, 0);
1100 	callout_init_mtx(&slot->retune_callout, &slot->mtx, 0);
1101 
1102 	if ((slot->quirks & SDHCI_QUIRK_POLL_CARD_PRESENT) &&
1103 	    !(slot->opt & SDHCI_NON_REMOVABLE)) {
1104 		callout_reset(&slot->card_poll_callout,
1105 		    SDHCI_CARD_PRESENT_TICKS, sdhci_card_poll, slot);
1106 	}
1107 
1108 	sdhci_init(slot);
1109 
1110 	return (0);
1111 }
1112 
1113 #ifndef MMCCAM
1114 void
1115 sdhci_start_slot(struct sdhci_slot *slot)
1116 {
1117 
1118 	sdhci_card_task(slot, 0);
1119 }
1120 #endif
1121 
1122 int
1123 sdhci_cleanup_slot(struct sdhci_slot *slot)
1124 {
1125 	device_t d;
1126 
1127 	callout_drain(&slot->timeout_callout);
1128 	callout_drain(&slot->card_poll_callout);
1129 	callout_drain(&slot->retune_callout);
1130 	taskqueue_drain(taskqueue_swi_giant, &slot->card_task);
1131 	taskqueue_drain_timeout(taskqueue_swi_giant, &slot->card_delayed_task);
1132 
1133 	SDHCI_LOCK(slot);
1134 	d = slot->dev;
1135 	slot->dev = NULL;
1136 	SDHCI_UNLOCK(slot);
1137 	if (d != NULL)
1138 		device_delete_child(slot->bus, d);
1139 
1140 	SDHCI_LOCK(slot);
1141 	sdhci_reset(slot, SDHCI_RESET_ALL);
1142 	SDHCI_UNLOCK(slot);
1143 	if (slot->opt & SDHCI_HAVE_DMA)
1144 		sdhci_dma_free(slot);
1145 	if (slot->opt & SDHCI_TUNING_SUPPORTED) {
1146 		free(slot->tune_req, M_DEVBUF);
1147 		free(slot->tune_cmd, M_DEVBUF);
1148 		free(slot->tune_data, M_DEVBUF);
1149 	}
1150 
1151 	SDHCI_LOCK_DESTROY(slot);
1152 
1153 	return (0);
1154 }
1155 
1156 int
1157 sdhci_generic_suspend(struct sdhci_slot *slot)
1158 {
1159 
1160 	/*
1161 	 * We expect the MMC layer to issue initial tuning after resume.
1162 	 * Otherwise, we'd need to indicate re-tuning including circuit reset
1163 	 * being required at least for re-tuning modes 1 and 2 ourselves.
1164 	 */
1165 	callout_drain(&slot->retune_callout);
1166 	SDHCI_LOCK(slot);
1167 	slot->opt &= ~SDHCI_TUNING_ENABLED;
1168 	sdhci_reset(slot, SDHCI_RESET_ALL);
1169 	SDHCI_UNLOCK(slot);
1170 
1171 	return (0);
1172 }
1173 
1174 int
1175 sdhci_generic_resume(struct sdhci_slot *slot)
1176 {
1177 
1178 	SDHCI_LOCK(slot);
1179 	sdhci_init(slot);
1180 	SDHCI_UNLOCK(slot);
1181 
1182 	return (0);
1183 }
1184 
1185 uint32_t
1186 sdhci_generic_min_freq(device_t brdev __unused, struct sdhci_slot *slot)
1187 {
1188 
1189 	if (slot->version >= SDHCI_SPEC_300)
1190 		return (slot->max_clk / SDHCI_300_MAX_DIVIDER);
1191 	else
1192 		return (slot->max_clk / SDHCI_200_MAX_DIVIDER);
1193 }
1194 
1195 bool
1196 sdhci_generic_get_card_present(device_t brdev __unused, struct sdhci_slot *slot)
1197 {
1198 
1199 	if (slot->opt & SDHCI_NON_REMOVABLE)
1200 		return true;
1201 
1202 	return (RD4(slot, SDHCI_PRESENT_STATE) & SDHCI_CARD_PRESENT);
1203 }
1204 
1205 void
1206 sdhci_generic_set_uhs_timing(device_t brdev __unused, struct sdhci_slot *slot)
1207 {
1208 	const struct mmc_ios *ios;
1209 	uint16_t hostctrl2;
1210 
1211 	if (slot->version < SDHCI_SPEC_300)
1212 		return;
1213 
1214 	SDHCI_ASSERT_LOCKED(slot);
1215 	ios = &slot->host.ios;
1216 	sdhci_set_clock(slot, 0);
1217 	hostctrl2 = RD2(slot, SDHCI_HOST_CONTROL2);
1218 	hostctrl2 &= ~SDHCI_CTRL2_UHS_MASK;
1219 	if (ios->clock > SD_SDR50_MAX) {
1220 		if (ios->timing == bus_timing_mmc_hs400 ||
1221 		    ios->timing == bus_timing_mmc_hs400es)
1222 			hostctrl2 |= SDHCI_CTRL2_MMC_HS400;
1223 		else
1224 			hostctrl2 |= SDHCI_CTRL2_UHS_SDR104;
1225 	}
1226 	else if (ios->clock > SD_SDR25_MAX)
1227 		hostctrl2 |= SDHCI_CTRL2_UHS_SDR50;
1228 	else if (ios->clock > SD_SDR12_MAX) {
1229 		if (ios->timing == bus_timing_uhs_ddr50 ||
1230 		    ios->timing == bus_timing_mmc_ddr52)
1231 			hostctrl2 |= SDHCI_CTRL2_UHS_DDR50;
1232 		else
1233 			hostctrl2 |= SDHCI_CTRL2_UHS_SDR25;
1234 	} else if (ios->clock > SD_MMC_CARD_ID_FREQUENCY)
1235 		hostctrl2 |= SDHCI_CTRL2_UHS_SDR12;
1236 	WR2(slot, SDHCI_HOST_CONTROL2, hostctrl2);
1237 	sdhci_set_clock(slot, ios->clock);
1238 }
1239 
1240 int
1241 sdhci_generic_update_ios(device_t brdev, device_t reqdev)
1242 {
1243 	struct sdhci_slot *slot = device_get_ivars(reqdev);
1244 	struct mmc_ios *ios = &slot->host.ios;
1245 
1246 	SDHCI_LOCK(slot);
1247 	/* Do full reset on bus power down to clear from any state. */
1248 	if (ios->power_mode == power_off) {
1249 		WR4(slot, SDHCI_SIGNAL_ENABLE, 0);
1250 		sdhci_init(slot);
1251 	}
1252 	/* Configure the bus. */
1253 	sdhci_set_clock(slot, ios->clock);
1254 	sdhci_set_power(slot, (ios->power_mode == power_off) ? 0 : ios->vdd);
1255 	if (ios->bus_width == bus_width_8) {
1256 		slot->hostctrl |= SDHCI_CTRL_8BITBUS;
1257 		slot->hostctrl &= ~SDHCI_CTRL_4BITBUS;
1258 	} else if (ios->bus_width == bus_width_4) {
1259 		slot->hostctrl &= ~SDHCI_CTRL_8BITBUS;
1260 		slot->hostctrl |= SDHCI_CTRL_4BITBUS;
1261 	} else if (ios->bus_width == bus_width_1) {
1262 		slot->hostctrl &= ~SDHCI_CTRL_8BITBUS;
1263 		slot->hostctrl &= ~SDHCI_CTRL_4BITBUS;
1264 	} else {
1265 		panic("Invalid bus width: %d", ios->bus_width);
1266 	}
1267 	if (ios->clock > SD_SDR12_MAX &&
1268 	    !(slot->quirks & SDHCI_QUIRK_DONT_SET_HISPD_BIT))
1269 		slot->hostctrl |= SDHCI_CTRL_HISPD;
1270 	else
1271 		slot->hostctrl &= ~SDHCI_CTRL_HISPD;
1272 	WR1(slot, SDHCI_HOST_CONTROL, slot->hostctrl);
1273 	SDHCI_SET_UHS_TIMING(brdev, slot);
1274 	/* Some controllers like reset after bus changes. */
1275 	if (slot->quirks & SDHCI_QUIRK_RESET_ON_IOS)
1276 		sdhci_reset(slot, SDHCI_RESET_CMD | SDHCI_RESET_DATA);
1277 
1278 	SDHCI_UNLOCK(slot);
1279 	return (0);
1280 }
1281 
1282 int
1283 sdhci_generic_switch_vccq(device_t brdev __unused, device_t reqdev)
1284 {
1285 	struct sdhci_slot *slot = device_get_ivars(reqdev);
1286 	enum mmc_vccq vccq;
1287 	int err;
1288 	uint16_t hostctrl2;
1289 
1290 	if (slot->version < SDHCI_SPEC_300)
1291 		return (0);
1292 
1293 	err = 0;
1294 	vccq = slot->host.ios.vccq;
1295 	SDHCI_LOCK(slot);
1296 	sdhci_set_clock(slot, 0);
1297 	hostctrl2 = RD2(slot, SDHCI_HOST_CONTROL2);
1298 	switch (vccq) {
1299 	case vccq_330:
1300 		if (!(hostctrl2 & SDHCI_CTRL2_S18_ENABLE))
1301 			goto done;
1302 		hostctrl2 &= ~SDHCI_CTRL2_S18_ENABLE;
1303 		WR2(slot, SDHCI_HOST_CONTROL2, hostctrl2);
1304 		DELAY(5000);
1305 		hostctrl2 = RD2(slot, SDHCI_HOST_CONTROL2);
1306 		if (!(hostctrl2 & SDHCI_CTRL2_S18_ENABLE))
1307 			goto done;
1308 		err = EAGAIN;
1309 		break;
1310 	case vccq_180:
1311 		if (!(slot->host.caps & MMC_CAP_SIGNALING_180)) {
1312 			err = EINVAL;
1313 			goto done;
1314 		}
1315 		if (hostctrl2 & SDHCI_CTRL2_S18_ENABLE)
1316 			goto done;
1317 		hostctrl2 |= SDHCI_CTRL2_S18_ENABLE;
1318 		WR2(slot, SDHCI_HOST_CONTROL2, hostctrl2);
1319 		DELAY(5000);
1320 		hostctrl2 = RD2(slot, SDHCI_HOST_CONTROL2);
1321 		if (hostctrl2 & SDHCI_CTRL2_S18_ENABLE)
1322 			goto done;
1323 		err = EAGAIN;
1324 		break;
1325 	default:
1326 		slot_printf(slot,
1327 		    "Attempt to set unsupported signaling voltage\n");
1328 		err = EINVAL;
1329 		break;
1330 	}
1331 done:
1332 	sdhci_set_clock(slot, slot->host.ios.clock);
1333 	SDHCI_UNLOCK(slot);
1334 	return (err);
1335 }
1336 
1337 int
1338 sdhci_generic_tune(device_t brdev __unused, device_t reqdev, bool hs400)
1339 {
1340 	struct sdhci_slot *slot = device_get_ivars(reqdev);
1341 	const struct mmc_ios *ios = &slot->host.ios;
1342 	struct mmc_command *tune_cmd;
1343 	struct mmc_data *tune_data;
1344 	uint32_t opcode;
1345 	int err;
1346 
1347 	if (!(slot->opt & SDHCI_TUNING_SUPPORTED))
1348 		return (0);
1349 
1350 	slot->retune_ticks = slot->retune_count * hz;
1351 	opcode = MMC_SEND_TUNING_BLOCK;
1352 	SDHCI_LOCK(slot);
1353 	switch (ios->timing) {
1354 	case bus_timing_mmc_hs400:
1355 		slot_printf(slot, "HS400 must be tuned in HS200 mode\n");
1356 		SDHCI_UNLOCK(slot);
1357 		return (EINVAL);
1358 	case bus_timing_mmc_hs200:
1359 		/*
1360 		 * In HS400 mode, controllers use the data strobe line to
1361 		 * latch data from the devices so periodic re-tuning isn't
1362 		 * expected to be required.
1363 		 */
1364 		if (hs400)
1365 			slot->retune_ticks = 0;
1366 		opcode = MMC_SEND_TUNING_BLOCK_HS200;
1367 		break;
1368 	case bus_timing_uhs_ddr50:
1369 	case bus_timing_uhs_sdr104:
1370 		break;
1371 	case bus_timing_uhs_sdr50:
1372 		if (slot->opt & SDHCI_SDR50_NEEDS_TUNING)
1373 			break;
1374 		SDHCI_UNLOCK(slot);
1375 		return (0);
1376 	default:
1377 		slot_printf(slot, "Tuning requested but not required.\n");
1378 		SDHCI_UNLOCK(slot);
1379 		return (EINVAL);
1380 	}
1381 
1382 	tune_cmd = slot->tune_cmd;
1383 	memset(tune_cmd, 0, sizeof(*tune_cmd));
1384 	tune_cmd->opcode = opcode;
1385 	tune_cmd->flags = MMC_RSP_R1 | MMC_CMD_ADTC;
1386 	tune_data = tune_cmd->data = slot->tune_data;
1387 	memset(tune_data, 0, sizeof(*tune_data));
1388 	tune_data->len = (opcode == MMC_SEND_TUNING_BLOCK_HS200 &&
1389 	    ios->bus_width == bus_width_8) ? MMC_TUNING_LEN_HS200 :
1390 	    MMC_TUNING_LEN;
1391 	tune_data->flags = MMC_DATA_READ;
1392 	tune_data->mrq = tune_cmd->mrq = slot->tune_req;
1393 
1394 	slot->opt &= ~SDHCI_TUNING_ENABLED;
1395 	err = sdhci_exec_tuning(slot, true);
1396 	if (err == 0) {
1397 		slot->opt |= SDHCI_TUNING_ENABLED;
1398 		slot->intmask |= sdhci_tuning_intmask(slot);
1399 		WR4(slot, SDHCI_INT_ENABLE, slot->intmask);
1400 		WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask);
1401 		if (slot->retune_ticks) {
1402 			callout_reset(&slot->retune_callout, slot->retune_ticks,
1403 			    sdhci_retune, slot);
1404 		}
1405 	}
1406 	SDHCI_UNLOCK(slot);
1407 	return (err);
1408 }
1409 
1410 int
1411 sdhci_generic_retune(device_t brdev __unused, device_t reqdev, bool reset)
1412 {
1413 	struct sdhci_slot *slot = device_get_ivars(reqdev);
1414 	int err;
1415 
1416 	if (!(slot->opt & SDHCI_TUNING_ENABLED))
1417 		return (0);
1418 
1419 	/* HS400 must be tuned in HS200 mode. */
1420 	if (slot->host.ios.timing == bus_timing_mmc_hs400)
1421 		return (EINVAL);
1422 
1423 	SDHCI_LOCK(slot);
1424 	err = sdhci_exec_tuning(slot, reset);
1425 	/*
1426 	 * There are two ways sdhci_exec_tuning() can fail:
1427 	 * EBUSY should not actually happen when requests are only issued
1428 	 *	 with the host properly acquired, and
1429 	 * EIO   re-tuning failed (but it did work initially).
1430 	 *
1431 	 * In both cases, we should retry at later point if periodic re-tuning
1432 	 * is enabled.  Note that due to slot->retune_req not being cleared in
1433 	 * these failure cases, the MMC layer should trigger another attempt at
1434 	 * re-tuning with the next request anyway, though.
1435 	 */
1436 	if (slot->retune_ticks) {
1437 		callout_reset(&slot->retune_callout, slot->retune_ticks,
1438 		    sdhci_retune, slot);
1439 	}
1440 	SDHCI_UNLOCK(slot);
1441 	return (err);
1442 }
1443 
1444 static int
1445 sdhci_exec_tuning(struct sdhci_slot *slot, bool reset)
1446 {
1447 	struct mmc_request *tune_req;
1448 	struct mmc_command *tune_cmd;
1449 	int i;
1450 	uint32_t intmask;
1451 	uint16_t hostctrl2;
1452 	u_char opt;
1453 
1454 	SDHCI_ASSERT_LOCKED(slot);
1455 	if (slot->req != NULL)
1456 		return (EBUSY);
1457 
1458 	/* Tuning doesn't work with DMA enabled. */
1459 	opt = slot->opt;
1460 	slot->opt = opt & ~SDHCI_HAVE_DMA;
1461 
1462 	/*
1463 	 * Ensure that as documented, SDHCI_INT_DATA_AVAIL is the only
1464 	 * kind of interrupt we receive in response to a tuning request.
1465 	 */
1466 	intmask = slot->intmask;
1467 	slot->intmask = SDHCI_INT_DATA_AVAIL;
1468 	WR4(slot, SDHCI_INT_ENABLE, SDHCI_INT_DATA_AVAIL);
1469 	WR4(slot, SDHCI_SIGNAL_ENABLE, SDHCI_INT_DATA_AVAIL);
1470 
1471 	hostctrl2 = RD2(slot, SDHCI_HOST_CONTROL2);
1472 	if (reset)
1473 		hostctrl2 &= ~SDHCI_CTRL2_SAMPLING_CLOCK;
1474 	else
1475 		hostctrl2 |= SDHCI_CTRL2_SAMPLING_CLOCK;
1476 	WR2(slot, SDHCI_HOST_CONTROL2, hostctrl2 | SDHCI_CTRL2_EXEC_TUNING);
1477 
1478 	tune_req = slot->tune_req;
1479 	tune_cmd = slot->tune_cmd;
1480 	for (i = 0; i < MMC_TUNING_MAX; i++) {
1481 		memset(tune_req, 0, sizeof(*tune_req));
1482 		tune_req->cmd = tune_cmd;
1483 		tune_req->done = sdhci_req_wakeup;
1484 		tune_req->done_data = slot;
1485 		slot->req = tune_req;
1486 		slot->flags = 0;
1487 		sdhci_start(slot);
1488 		while (!(tune_req->flags & MMC_REQ_DONE))
1489 			msleep(tune_req, &slot->mtx, 0, "sdhciet", 0);
1490 		if (!(tune_req->flags & MMC_TUNE_DONE))
1491 			break;
1492 		hostctrl2 = RD2(slot, SDHCI_HOST_CONTROL2);
1493 		if (!(hostctrl2 & SDHCI_CTRL2_EXEC_TUNING))
1494 			break;
1495 		if (tune_cmd->opcode == MMC_SEND_TUNING_BLOCK)
1496 			DELAY(1000);
1497 	}
1498 
1499 	/*
1500 	 * Restore DMA usage and interrupts.
1501 	 * Note that the interrupt aggregation code might have cleared
1502 	 * SDHCI_INT_DMA_END and/or SDHCI_INT_RESPONSE in slot->intmask
1503 	 * and SDHCI_SIGNAL_ENABLE respectively so ensure SDHCI_INT_ENABLE
1504 	 * doesn't lose these.
1505 	 */
1506 	slot->opt = opt;
1507 	slot->intmask = intmask;
1508 	WR4(slot, SDHCI_INT_ENABLE, intmask | SDHCI_INT_DMA_END |
1509 	    SDHCI_INT_RESPONSE);
1510 	WR4(slot, SDHCI_SIGNAL_ENABLE, intmask);
1511 
1512 	if ((hostctrl2 & (SDHCI_CTRL2_EXEC_TUNING |
1513 	    SDHCI_CTRL2_SAMPLING_CLOCK)) == SDHCI_CTRL2_SAMPLING_CLOCK) {
1514 		slot->retune_req = 0;
1515 		return (0);
1516 	}
1517 
1518 	slot_printf(slot, "Tuning failed, using fixed sampling clock\n");
1519 	WR2(slot, SDHCI_HOST_CONTROL2, hostctrl2 & ~(SDHCI_CTRL2_EXEC_TUNING |
1520 	    SDHCI_CTRL2_SAMPLING_CLOCK));
1521 	sdhci_reset(slot, SDHCI_RESET_CMD | SDHCI_RESET_DATA);
1522 	return (EIO);
1523 }
1524 
1525 static void
1526 sdhci_retune(void *arg)
1527 {
1528 	struct sdhci_slot *slot = arg;
1529 
1530 	slot->retune_req |= SDHCI_RETUNE_REQ_NEEDED;
1531 }
1532 
1533 #ifdef MMCCAM
1534 static void
1535 sdhci_req_done(struct sdhci_slot *slot)
1536 {
1537 	union ccb *ccb;
1538 
1539 	if (__predict_false(sdhci_debug > 1))
1540 		slot_printf(slot, "%s\n", __func__);
1541 	if (slot->ccb != NULL && slot->curcmd != NULL) {
1542 		callout_stop(&slot->timeout_callout);
1543 		ccb = slot->ccb;
1544 		slot->ccb = NULL;
1545 		slot->curcmd = NULL;
1546 
1547 		/* Tell CAM the request is finished */
1548 		struct ccb_mmcio *mmcio;
1549 		mmcio = &ccb->mmcio;
1550 
1551 		ccb->ccb_h.status =
1552 		    (mmcio->cmd.error == 0 ? CAM_REQ_CMP : CAM_REQ_CMP_ERR);
1553 		xpt_done(ccb);
1554 	}
1555 }
1556 #else
1557 static void
1558 sdhci_req_done(struct sdhci_slot *slot)
1559 {
1560 	struct mmc_request *req;
1561 
1562 	if (slot->req != NULL && slot->curcmd != NULL) {
1563 		callout_stop(&slot->timeout_callout);
1564 		req = slot->req;
1565 		slot->req = NULL;
1566 		slot->curcmd = NULL;
1567 		req->done(req);
1568 	}
1569 }
1570 #endif
1571 
1572 static void
1573 sdhci_req_wakeup(struct mmc_request *req)
1574 {
1575 	struct sdhci_slot *slot;
1576 
1577 	slot = req->done_data;
1578 	req->flags |= MMC_REQ_DONE;
1579 	wakeup(req);
1580 }
1581 
1582 static void
1583 sdhci_timeout(void *arg)
1584 {
1585 	struct sdhci_slot *slot = arg;
1586 
1587 	if (slot->curcmd != NULL) {
1588 		slot_printf(slot, "Controller timeout\n");
1589 		sdhci_dumpregs(slot);
1590 		sdhci_reset(slot, SDHCI_RESET_CMD | SDHCI_RESET_DATA);
1591 		slot->curcmd->error = MMC_ERR_TIMEOUT;
1592 		sdhci_req_done(slot);
1593 	} else {
1594 		slot_printf(slot, "Spurious timeout - no active command\n");
1595 	}
1596 }
1597 
1598 static void
1599 sdhci_set_transfer_mode(struct sdhci_slot *slot, const struct mmc_data *data)
1600 {
1601 	uint16_t mode;
1602 
1603 	if (data == NULL)
1604 		return;
1605 
1606 	mode = SDHCI_TRNS_BLK_CNT_EN;
1607 	if (data->len > 512 || data->block_count > 1) {
1608 		mode |= SDHCI_TRNS_MULTI;
1609 		if (data->block_count == 0 && __predict_true(
1610 #ifdef MMCCAM
1611 		    slot->ccb->mmcio.stop.opcode == MMC_STOP_TRANSMISSION &&
1612 #else
1613 		    slot->req->stop != NULL &&
1614 #endif
1615 		    !(slot->quirks & SDHCI_QUIRK_BROKEN_AUTO_STOP)))
1616 			mode |= SDHCI_TRNS_ACMD12;
1617 	}
1618 	if (data->flags & MMC_DATA_READ)
1619 		mode |= SDHCI_TRNS_READ;
1620 	if (slot->flags & SDHCI_USE_DMA)
1621 		mode |= SDHCI_TRNS_DMA;
1622 
1623 	WR2(slot, SDHCI_TRANSFER_MODE, mode);
1624 }
1625 
1626 static void
1627 sdhci_start_command(struct sdhci_slot *slot, struct mmc_command *cmd)
1628 {
1629 	int flags, timeout;
1630 	uint32_t mask;
1631 
1632 	slot->curcmd = cmd;
1633 	slot->cmd_done = 0;
1634 
1635 	cmd->error = MMC_ERR_NONE;
1636 
1637 	/* This flags combination is not supported by controller. */
1638 	if ((cmd->flags & MMC_RSP_136) && (cmd->flags & MMC_RSP_BUSY)) {
1639 		slot_printf(slot, "Unsupported response type!\n");
1640 		cmd->error = MMC_ERR_FAILED;
1641 		sdhci_req_done(slot);
1642 		return;
1643 	}
1644 
1645 	/*
1646 	 * Do not issue command if there is no card, clock or power.
1647 	 * Controller will not detect timeout without clock active.
1648 	 */
1649 	if (!SDHCI_GET_CARD_PRESENT(slot->bus, slot) ||
1650 	    slot->power == 0 ||
1651 	    slot->clock == 0) {
1652 		slot_printf(slot,
1653 			    "Cannot issue a command (power=%d clock=%d)",
1654 			    slot->power, slot->clock);
1655 		cmd->error = MMC_ERR_FAILED;
1656 		sdhci_req_done(slot);
1657 		return;
1658 	}
1659 	/* Always wait for free CMD bus. */
1660 	mask = SDHCI_CMD_INHIBIT;
1661 	/* Wait for free DAT if we have data or busy signal. */
1662 	if (cmd->data != NULL || (cmd->flags & MMC_RSP_BUSY))
1663 		mask |= SDHCI_DAT_INHIBIT;
1664 	/*
1665 	 * We shouldn't wait for DAT for stop commands or CMD19/CMD21.  Note
1666 	 * that these latter are also special in that SDHCI_CMD_DATA should
1667 	 * be set below but no actual data is ever read from the controller.
1668 	*/
1669 #ifdef MMCCAM
1670 	if (cmd == &slot->ccb->mmcio.stop ||
1671 #else
1672 	if (cmd == slot->req->stop ||
1673 #endif
1674 	    __predict_false(cmd->opcode == MMC_SEND_TUNING_BLOCK ||
1675 	    cmd->opcode == MMC_SEND_TUNING_BLOCK_HS200))
1676 		mask &= ~SDHCI_DAT_INHIBIT;
1677 	/*
1678 	 *  Wait for bus no more then 250 ms.  Typically there will be no wait
1679 	 *  here at all, but when writing a crash dump we may be bypassing the
1680 	 *  host platform's interrupt handler, and in some cases that handler
1681 	 *  may be working around hardware quirks such as not respecting r1b
1682 	 *  busy indications.  In those cases, this wait-loop serves the purpose
1683 	 *  of waiting for the prior command and data transfers to be done, and
1684 	 *  SD cards are allowed to take up to 250ms for write and erase ops.
1685 	 *  (It's usually more like 20-30ms in the real world.)
1686 	 */
1687 	timeout = 250;
1688 	while (mask & RD4(slot, SDHCI_PRESENT_STATE)) {
1689 		if (timeout == 0) {
1690 			slot_printf(slot, "Controller never released "
1691 			    "inhibit bit(s).\n");
1692 			sdhci_dumpregs(slot);
1693 			cmd->error = MMC_ERR_FAILED;
1694 			sdhci_req_done(slot);
1695 			return;
1696 		}
1697 		timeout--;
1698 		DELAY(1000);
1699 	}
1700 
1701 	/* Prepare command flags. */
1702 	if (!(cmd->flags & MMC_RSP_PRESENT))
1703 		flags = SDHCI_CMD_RESP_NONE;
1704 	else if (cmd->flags & MMC_RSP_136)
1705 		flags = SDHCI_CMD_RESP_LONG;
1706 	else if (cmd->flags & MMC_RSP_BUSY)
1707 		flags = SDHCI_CMD_RESP_SHORT_BUSY;
1708 	else
1709 		flags = SDHCI_CMD_RESP_SHORT;
1710 	if (cmd->flags & MMC_RSP_CRC)
1711 		flags |= SDHCI_CMD_CRC;
1712 	if (cmd->flags & MMC_RSP_OPCODE)
1713 		flags |= SDHCI_CMD_INDEX;
1714 	if (cmd->data != NULL)
1715 		flags |= SDHCI_CMD_DATA;
1716 	if (cmd->opcode == MMC_STOP_TRANSMISSION)
1717 		flags |= SDHCI_CMD_TYPE_ABORT;
1718 	/* Prepare data. */
1719 	sdhci_start_data(slot, cmd->data);
1720 	/*
1721 	 * Interrupt aggregation: To reduce total number of interrupts
1722 	 * group response interrupt with data interrupt when possible.
1723 	 * If there going to be data interrupt, mask response one.
1724 	 */
1725 	if (slot->data_done == 0) {
1726 		WR4(slot, SDHCI_SIGNAL_ENABLE,
1727 		    slot->intmask &= ~SDHCI_INT_RESPONSE);
1728 	}
1729 	/* Set command argument. */
1730 	WR4(slot, SDHCI_ARGUMENT, cmd->arg);
1731 	/* Set data transfer mode. */
1732 	sdhci_set_transfer_mode(slot, cmd->data);
1733 	if (__predict_false(sdhci_debug > 1))
1734 		slot_printf(slot, "Starting command opcode %#04x flags %#04x\n",
1735 		    cmd->opcode, flags);
1736 
1737 	/* Start command. */
1738 	WR2(slot, SDHCI_COMMAND_FLAGS, (cmd->opcode << 8) | (flags & 0xff));
1739 	/* Start timeout callout. */
1740 	callout_reset(&slot->timeout_callout, slot->timeout * hz,
1741 	    sdhci_timeout, slot);
1742 }
1743 
1744 static void
1745 sdhci_finish_command(struct sdhci_slot *slot)
1746 {
1747 	int i;
1748 	uint32_t val;
1749 	uint8_t extra;
1750 
1751 	if (__predict_false(sdhci_debug > 1))
1752 		slot_printf(slot, "%s: called, err %d flags %#04x\n",
1753 		    __func__, slot->curcmd->error, slot->curcmd->flags);
1754 	slot->cmd_done = 1;
1755 	/*
1756 	 * Interrupt aggregation: Restore command interrupt.
1757 	 * Main restore point for the case when command interrupt
1758 	 * happened first.
1759 	 */
1760 	if (__predict_true(slot->curcmd->opcode != MMC_SEND_TUNING_BLOCK &&
1761 	    slot->curcmd->opcode != MMC_SEND_TUNING_BLOCK_HS200))
1762 		WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask |=
1763 		    SDHCI_INT_RESPONSE);
1764 	/* In case of error - reset host and return. */
1765 	if (slot->curcmd->error) {
1766 		if (slot->curcmd->error == MMC_ERR_BADCRC)
1767 			slot->retune_req |= SDHCI_RETUNE_REQ_RESET;
1768 		sdhci_reset(slot, SDHCI_RESET_CMD);
1769 		sdhci_reset(slot, SDHCI_RESET_DATA);
1770 		sdhci_start(slot);
1771 		return;
1772 	}
1773 	/* If command has response - fetch it. */
1774 	if (slot->curcmd->flags & MMC_RSP_PRESENT) {
1775 		if (slot->curcmd->flags & MMC_RSP_136) {
1776 			/* CRC is stripped so we need one byte shift. */
1777 			extra = 0;
1778 			for (i = 0; i < 4; i++) {
1779 				val = RD4(slot, SDHCI_RESPONSE + i * 4);
1780 				if (slot->quirks &
1781 				    SDHCI_QUIRK_DONT_SHIFT_RESPONSE)
1782 					slot->curcmd->resp[3 - i] = val;
1783 				else {
1784 					slot->curcmd->resp[3 - i] =
1785 					    (val << 8) | extra;
1786 					extra = val >> 24;
1787 				}
1788 			}
1789 		} else
1790 			slot->curcmd->resp[0] = RD4(slot, SDHCI_RESPONSE);
1791 	}
1792 	if (__predict_false(sdhci_debug > 1))
1793 		slot_printf(slot, "Resp: %#04x %#04x %#04x %#04x\n",
1794 		    slot->curcmd->resp[0], slot->curcmd->resp[1],
1795 		    slot->curcmd->resp[2], slot->curcmd->resp[3]);
1796 
1797 	/* If data ready - finish. */
1798 	if (slot->data_done)
1799 		sdhci_start(slot);
1800 }
1801 
1802 static void
1803 sdhci_start_data(struct sdhci_slot *slot, const struct mmc_data *data)
1804 {
1805 	uint32_t blkcnt, blksz, current_timeout, sdma_bbufsz, target_timeout;
1806 	uint8_t div;
1807 
1808 	if (data == NULL && (slot->curcmd->flags & MMC_RSP_BUSY) == 0) {
1809 		slot->data_done = 1;
1810 		return;
1811 	}
1812 
1813 	slot->data_done = 0;
1814 
1815 	/* Calculate and set data timeout.*/
1816 	/* XXX: We should have this from mmc layer, now assume 1 sec. */
1817 	if (slot->quirks & SDHCI_QUIRK_BROKEN_TIMEOUT_VAL) {
1818 		div = 0xE;
1819 	} else {
1820 		target_timeout = 1000000;
1821 		div = 0;
1822 		current_timeout = (1 << 13) * 1000 / slot->timeout_clk;
1823 		while (current_timeout < target_timeout && div < 0xE) {
1824 			++div;
1825 			current_timeout <<= 1;
1826 		}
1827 		/* Compensate for an off-by-one error in the CaFe chip.*/
1828 		if (div < 0xE &&
1829 		    (slot->quirks & SDHCI_QUIRK_INCR_TIMEOUT_CONTROL)) {
1830 			++div;
1831 		}
1832 	}
1833 	WR1(slot, SDHCI_TIMEOUT_CONTROL, div);
1834 
1835 	if (data == NULL)
1836 		return;
1837 
1838 	/* Use DMA if possible. */
1839 	if ((slot->opt & SDHCI_HAVE_DMA))
1840 		slot->flags |= SDHCI_USE_DMA;
1841 	/* If data is small, broken DMA may return zeroes instead of data. */
1842 	if ((slot->quirks & SDHCI_QUIRK_BROKEN_TIMINGS) &&
1843 	    (data->len <= 512))
1844 		slot->flags &= ~SDHCI_USE_DMA;
1845 	/* Some controllers require even block sizes. */
1846 	if ((slot->quirks & SDHCI_QUIRK_32BIT_DMA_SIZE) &&
1847 	    ((data->len) & 0x3))
1848 		slot->flags &= ~SDHCI_USE_DMA;
1849 	/* Load DMA buffer. */
1850 	if (slot->flags & SDHCI_USE_DMA) {
1851 		sdma_bbufsz = slot->sdma_bbufsz;
1852 		if (data->flags & MMC_DATA_READ)
1853 			bus_dmamap_sync(slot->dmatag, slot->dmamap,
1854 			    BUS_DMASYNC_PREREAD);
1855 		else {
1856 			memcpy(slot->dmamem, data->data, ulmin(data->len,
1857 			    sdma_bbufsz));
1858 			bus_dmamap_sync(slot->dmatag, slot->dmamap,
1859 			    BUS_DMASYNC_PREWRITE);
1860 		}
1861 		WR4(slot, SDHCI_DMA_ADDRESS, slot->paddr);
1862 		/*
1863 		 * Interrupt aggregation: Mask border interrupt for the last
1864 		 * bounce buffer and unmask otherwise.
1865 		 */
1866 		if (data->len == sdma_bbufsz)
1867 			slot->intmask &= ~SDHCI_INT_DMA_END;
1868 		else
1869 			slot->intmask |= SDHCI_INT_DMA_END;
1870 		WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask);
1871 	}
1872 	/* Current data offset for both PIO and DMA. */
1873 	slot->offset = 0;
1874 #ifdef MMCCAM
1875 	if (data->flags & MMC_DATA_BLOCK_SIZE) {
1876 		/* Set block size and request border interrupts on the SDMA boundary. */
1877 		blksz = SDHCI_MAKE_BLKSZ(slot->sdma_boundary, data->block_size);
1878 		blkcnt = data->block_count;
1879 		if (__predict_false(sdhci_debug > 0))
1880 			slot_printf(slot, "SDIO Custom block params: blksz: "
1881 			    "%#10x, blk cnt: %#10x\n", blksz, blkcnt);
1882 	} else
1883 #endif
1884 	{
1885 		/* Set block size and request border interrupts on the SDMA boundary. */
1886 		blksz = SDHCI_MAKE_BLKSZ(slot->sdma_boundary, ulmin(data->len, 512));
1887 		blkcnt = howmany(data->len, 512);
1888 	}
1889 
1890 	WR2(slot, SDHCI_BLOCK_SIZE, blksz);
1891 	WR2(slot, SDHCI_BLOCK_COUNT, blkcnt);
1892 	if (__predict_false(sdhci_debug > 1))
1893 		slot_printf(slot, "Blk size: 0x%08x | Blk cnt:  0x%08x\n",
1894 		    blksz, blkcnt);
1895 }
1896 
1897 void
1898 sdhci_finish_data(struct sdhci_slot *slot)
1899 {
1900 	struct mmc_data *data = slot->curcmd->data;
1901 	size_t left;
1902 
1903 	/* Interrupt aggregation: Restore command interrupt.
1904 	 * Auxiliary restore point for the case when data interrupt
1905 	 * happened first. */
1906 	if (!slot->cmd_done) {
1907 		WR4(slot, SDHCI_SIGNAL_ENABLE,
1908 		    slot->intmask |= SDHCI_INT_RESPONSE);
1909 	}
1910 	/* Unload rest of data from DMA buffer. */
1911 	if (!slot->data_done && (slot->flags & SDHCI_USE_DMA) &&
1912 	    slot->curcmd->data != NULL) {
1913 		if (data->flags & MMC_DATA_READ) {
1914 			left = data->len - slot->offset;
1915 			bus_dmamap_sync(slot->dmatag, slot->dmamap,
1916 			    BUS_DMASYNC_POSTREAD);
1917 			memcpy((u_char*)data->data + slot->offset, slot->dmamem,
1918 			    ulmin(left, slot->sdma_bbufsz));
1919 		} else
1920 			bus_dmamap_sync(slot->dmatag, slot->dmamap,
1921 			    BUS_DMASYNC_POSTWRITE);
1922 	}
1923 	slot->data_done = 1;
1924 	/* If there was error - reset the host. */
1925 	if (slot->curcmd->error) {
1926 		if (slot->curcmd->error == MMC_ERR_BADCRC)
1927 			slot->retune_req |= SDHCI_RETUNE_REQ_RESET;
1928 		sdhci_reset(slot, SDHCI_RESET_CMD);
1929 		sdhci_reset(slot, SDHCI_RESET_DATA);
1930 		sdhci_start(slot);
1931 		return;
1932 	}
1933 	/* If we already have command response - finish. */
1934 	if (slot->cmd_done)
1935 		sdhci_start(slot);
1936 }
1937 
1938 #ifdef MMCCAM
1939 static void
1940 sdhci_start(struct sdhci_slot *slot)
1941 {
1942 	union ccb *ccb;
1943 	struct ccb_mmcio *mmcio;
1944 
1945 	ccb = slot->ccb;
1946 	if (ccb == NULL)
1947 		return;
1948 
1949 	mmcio = &ccb->mmcio;
1950 	if (!(slot->flags & CMD_STARTED)) {
1951 		slot->flags |= CMD_STARTED;
1952 		sdhci_start_command(slot, &mmcio->cmd);
1953 		return;
1954 	}
1955 
1956 	/*
1957 	 * Old stack doesn't use this!
1958 	 * Enabling this code causes significant performance degradation
1959 	 * and IRQ storms on BBB, Wandboard behaves fine.
1960 	 * Not using this code does no harm...
1961 	if (!(slot->flags & STOP_STARTED) && mmcio->stop.opcode != 0) {
1962 		slot->flags |= STOP_STARTED;
1963 		sdhci_start_command(slot, &mmcio->stop);
1964 		return;
1965 	}
1966 	*/
1967 	if (__predict_false(sdhci_debug > 1))
1968 		slot_printf(slot, "result: %d\n", mmcio->cmd.error);
1969 	if (mmcio->cmd.error == 0 &&
1970 	    (slot->quirks & SDHCI_QUIRK_RESET_AFTER_REQUEST)) {
1971 		sdhci_reset(slot, SDHCI_RESET_CMD);
1972 		sdhci_reset(slot, SDHCI_RESET_DATA);
1973 	}
1974 
1975 	sdhci_req_done(slot);
1976 }
1977 #else
1978 static void
1979 sdhci_start(struct sdhci_slot *slot)
1980 {
1981 	const struct mmc_request *req;
1982 
1983 	req = slot->req;
1984 	if (req == NULL)
1985 		return;
1986 
1987 	if (!(slot->flags & CMD_STARTED)) {
1988 		slot->flags |= CMD_STARTED;
1989 		sdhci_start_command(slot, req->cmd);
1990 		return;
1991 	}
1992 	if ((slot->quirks & SDHCI_QUIRK_BROKEN_AUTO_STOP) &&
1993 	    !(slot->flags & STOP_STARTED) && req->stop) {
1994 		slot->flags |= STOP_STARTED;
1995 		sdhci_start_command(slot, req->stop);
1996 		return;
1997 	}
1998 	if (__predict_false(sdhci_debug > 1))
1999 		slot_printf(slot, "result: %d\n", req->cmd->error);
2000 	if (!req->cmd->error &&
2001 	    ((slot->curcmd == req->stop &&
2002 	     (slot->quirks & SDHCI_QUIRK_BROKEN_AUTO_STOP)) ||
2003 	     (slot->quirks & SDHCI_QUIRK_RESET_AFTER_REQUEST))) {
2004 		sdhci_reset(slot, SDHCI_RESET_CMD);
2005 		sdhci_reset(slot, SDHCI_RESET_DATA);
2006 	}
2007 
2008 	sdhci_req_done(slot);
2009 }
2010 #endif
2011 
2012 int
2013 sdhci_generic_request(device_t brdev __unused, device_t reqdev,
2014     struct mmc_request *req)
2015 {
2016 	struct sdhci_slot *slot = device_get_ivars(reqdev);
2017 
2018 	SDHCI_LOCK(slot);
2019 	if (slot->req != NULL) {
2020 		SDHCI_UNLOCK(slot);
2021 		return (EBUSY);
2022 	}
2023 	if (__predict_false(sdhci_debug > 1)) {
2024 		slot_printf(slot,
2025 		    "CMD%u arg %#x flags %#x dlen %u dflags %#x\n",
2026 		    req->cmd->opcode, req->cmd->arg, req->cmd->flags,
2027 		    (req->cmd->data)?(u_int)req->cmd->data->len:0,
2028 		    (req->cmd->data)?req->cmd->data->flags:0);
2029 	}
2030 	slot->req = req;
2031 	slot->flags = 0;
2032 	sdhci_start(slot);
2033 	SDHCI_UNLOCK(slot);
2034 	if (dumping) {
2035 		while (slot->req != NULL) {
2036 			sdhci_generic_intr(slot);
2037 			DELAY(10);
2038 		}
2039 	}
2040 	return (0);
2041 }
2042 
2043 int
2044 sdhci_generic_get_ro(device_t brdev __unused, device_t reqdev)
2045 {
2046 	struct sdhci_slot *slot = device_get_ivars(reqdev);
2047 	uint32_t val;
2048 
2049 	SDHCI_LOCK(slot);
2050 	val = RD4(slot, SDHCI_PRESENT_STATE);
2051 	SDHCI_UNLOCK(slot);
2052 	return (!(val & SDHCI_WRITE_PROTECT));
2053 }
2054 
2055 int
2056 sdhci_generic_acquire_host(device_t brdev __unused, device_t reqdev)
2057 {
2058 	struct sdhci_slot *slot = device_get_ivars(reqdev);
2059 	int err = 0;
2060 
2061 	SDHCI_LOCK(slot);
2062 	while (slot->bus_busy)
2063 		msleep(slot, &slot->mtx, 0, "sdhciah", 0);
2064 	slot->bus_busy++;
2065 	/* Activate led. */
2066 	WR1(slot, SDHCI_HOST_CONTROL, slot->hostctrl |= SDHCI_CTRL_LED);
2067 	SDHCI_UNLOCK(slot);
2068 	return (err);
2069 }
2070 
2071 int
2072 sdhci_generic_release_host(device_t brdev __unused, device_t reqdev)
2073 {
2074 	struct sdhci_slot *slot = device_get_ivars(reqdev);
2075 
2076 	SDHCI_LOCK(slot);
2077 	/* Deactivate led. */
2078 	WR1(slot, SDHCI_HOST_CONTROL, slot->hostctrl &= ~SDHCI_CTRL_LED);
2079 	slot->bus_busy--;
2080 	SDHCI_UNLOCK(slot);
2081 	wakeup(slot);
2082 	return (0);
2083 }
2084 
2085 static void
2086 sdhci_cmd_irq(struct sdhci_slot *slot, uint32_t intmask)
2087 {
2088 
2089 	if (!slot->curcmd) {
2090 		slot_printf(slot, "Got command interrupt 0x%08x, but "
2091 		    "there is no active command.\n", intmask);
2092 		sdhci_dumpregs(slot);
2093 		return;
2094 	}
2095 	if (intmask & SDHCI_INT_TIMEOUT)
2096 		slot->curcmd->error = MMC_ERR_TIMEOUT;
2097 	else if (intmask & SDHCI_INT_CRC)
2098 		slot->curcmd->error = MMC_ERR_BADCRC;
2099 	else if (intmask & (SDHCI_INT_END_BIT | SDHCI_INT_INDEX))
2100 		slot->curcmd->error = MMC_ERR_FIFO;
2101 
2102 	sdhci_finish_command(slot);
2103 }
2104 
2105 static void
2106 sdhci_data_irq(struct sdhci_slot *slot, uint32_t intmask)
2107 {
2108 	struct mmc_data *data;
2109 	size_t left;
2110 	uint32_t sdma_bbufsz;
2111 
2112 	if (!slot->curcmd) {
2113 		slot_printf(slot, "Got data interrupt 0x%08x, but "
2114 		    "there is no active command.\n", intmask);
2115 		sdhci_dumpregs(slot);
2116 		return;
2117 	}
2118 	if (slot->curcmd->data == NULL &&
2119 	    (slot->curcmd->flags & MMC_RSP_BUSY) == 0) {
2120 		slot_printf(slot, "Got data interrupt 0x%08x, but "
2121 		    "there is no active data operation.\n",
2122 		    intmask);
2123 		sdhci_dumpregs(slot);
2124 		return;
2125 	}
2126 	if (intmask & SDHCI_INT_DATA_TIMEOUT)
2127 		slot->curcmd->error = MMC_ERR_TIMEOUT;
2128 	else if (intmask & (SDHCI_INT_DATA_CRC | SDHCI_INT_DATA_END_BIT))
2129 		slot->curcmd->error = MMC_ERR_BADCRC;
2130 	if (slot->curcmd->data == NULL &&
2131 	    (intmask & (SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL |
2132 	    SDHCI_INT_DMA_END))) {
2133 		slot_printf(slot, "Got data interrupt 0x%08x, but "
2134 		    "there is busy-only command.\n", intmask);
2135 		sdhci_dumpregs(slot);
2136 		slot->curcmd->error = MMC_ERR_INVALID;
2137 	}
2138 	if (slot->curcmd->error) {
2139 		/* No need to continue after any error. */
2140 		goto done;
2141 	}
2142 
2143 	/* Handle tuning completion interrupt. */
2144 	if (__predict_false((intmask & SDHCI_INT_DATA_AVAIL) &&
2145 	    (slot->curcmd->opcode == MMC_SEND_TUNING_BLOCK ||
2146 	    slot->curcmd->opcode == MMC_SEND_TUNING_BLOCK_HS200))) {
2147 		slot->req->flags |= MMC_TUNE_DONE;
2148 		sdhci_finish_command(slot);
2149 		sdhci_finish_data(slot);
2150 		return;
2151 	}
2152 	/* Handle PIO interrupt. */
2153 	if (intmask & (SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL)) {
2154 		if ((slot->opt & SDHCI_PLATFORM_TRANSFER) &&
2155 		    SDHCI_PLATFORM_WILL_HANDLE(slot->bus, slot)) {
2156 			SDHCI_PLATFORM_START_TRANSFER(slot->bus, slot,
2157 			    &intmask);
2158 			slot->flags |= PLATFORM_DATA_STARTED;
2159 		} else
2160 			sdhci_transfer_pio(slot);
2161 	}
2162 	/* Handle DMA border. */
2163 	if (intmask & SDHCI_INT_DMA_END) {
2164 		data = slot->curcmd->data;
2165 		sdma_bbufsz = slot->sdma_bbufsz;
2166 
2167 		/* Unload DMA buffer ... */
2168 		left = data->len - slot->offset;
2169 		if (data->flags & MMC_DATA_READ) {
2170 			bus_dmamap_sync(slot->dmatag, slot->dmamap,
2171 			    BUS_DMASYNC_POSTREAD);
2172 			memcpy((u_char*)data->data + slot->offset, slot->dmamem,
2173 			    ulmin(left, sdma_bbufsz));
2174 		} else {
2175 			bus_dmamap_sync(slot->dmatag, slot->dmamap,
2176 			    BUS_DMASYNC_POSTWRITE);
2177 		}
2178 		/* ... and reload it again. */
2179 		slot->offset += sdma_bbufsz;
2180 		left = data->len - slot->offset;
2181 		if (data->flags & MMC_DATA_READ) {
2182 			bus_dmamap_sync(slot->dmatag, slot->dmamap,
2183 			    BUS_DMASYNC_PREREAD);
2184 		} else {
2185 			memcpy(slot->dmamem, (u_char*)data->data + slot->offset,
2186 			    ulmin(left, sdma_bbufsz));
2187 			bus_dmamap_sync(slot->dmatag, slot->dmamap,
2188 			    BUS_DMASYNC_PREWRITE);
2189 		}
2190 		/*
2191 		 * Interrupt aggregation: Mask border interrupt for the last
2192 		 * bounce buffer.
2193 		 */
2194 		if (left == sdma_bbufsz) {
2195 			slot->intmask &= ~SDHCI_INT_DMA_END;
2196 			WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask);
2197 		}
2198 		/* Restart DMA. */
2199 		WR4(slot, SDHCI_DMA_ADDRESS, slot->paddr);
2200 	}
2201 	/* We have got all data. */
2202 	if (intmask & SDHCI_INT_DATA_END) {
2203 		if (slot->flags & PLATFORM_DATA_STARTED) {
2204 			slot->flags &= ~PLATFORM_DATA_STARTED;
2205 			SDHCI_PLATFORM_FINISH_TRANSFER(slot->bus, slot);
2206 		} else
2207 			sdhci_finish_data(slot);
2208 	}
2209 done:
2210 	if (slot->curcmd != NULL && slot->curcmd->error != 0) {
2211 		if (slot->flags & PLATFORM_DATA_STARTED) {
2212 			slot->flags &= ~PLATFORM_DATA_STARTED;
2213 			SDHCI_PLATFORM_FINISH_TRANSFER(slot->bus, slot);
2214 		} else
2215 			sdhci_finish_data(slot);
2216 	}
2217 }
2218 
2219 static void
2220 sdhci_acmd_irq(struct sdhci_slot *slot, uint16_t acmd_err)
2221 {
2222 
2223 	if (!slot->curcmd) {
2224 		slot_printf(slot, "Got AutoCMD12 error 0x%04x, but "
2225 		    "there is no active command.\n", acmd_err);
2226 		sdhci_dumpregs(slot);
2227 		return;
2228 	}
2229 	slot_printf(slot, "Got AutoCMD12 error 0x%04x\n", acmd_err);
2230 	sdhci_reset(slot, SDHCI_RESET_CMD);
2231 }
2232 
2233 void
2234 sdhci_generic_intr(struct sdhci_slot *slot)
2235 {
2236 	uint32_t intmask, present;
2237 	uint16_t val16;
2238 
2239 	SDHCI_LOCK(slot);
2240 	/* Read slot interrupt status. */
2241 	intmask = RD4(slot, SDHCI_INT_STATUS);
2242 	if (intmask == 0 || intmask == 0xffffffff) {
2243 		SDHCI_UNLOCK(slot);
2244 		return;
2245 	}
2246 	if (__predict_false(sdhci_debug > 2))
2247 		slot_printf(slot, "Interrupt %#x\n", intmask);
2248 
2249 	/* Handle tuning error interrupt. */
2250 	if (__predict_false(intmask & SDHCI_INT_TUNEERR)) {
2251 		WR4(slot, SDHCI_INT_STATUS, SDHCI_INT_TUNEERR);
2252 		slot_printf(slot, "Tuning error indicated\n");
2253 		slot->retune_req |= SDHCI_RETUNE_REQ_RESET;
2254 		if (slot->curcmd) {
2255 			slot->curcmd->error = MMC_ERR_BADCRC;
2256 			sdhci_finish_command(slot);
2257 		}
2258 	}
2259 	/* Handle re-tuning interrupt. */
2260 	if (__predict_false(intmask & SDHCI_INT_RETUNE))
2261 		slot->retune_req |= SDHCI_RETUNE_REQ_NEEDED;
2262 	/* Handle card presence interrupts. */
2263 	if (intmask & (SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE)) {
2264 		present = (intmask & SDHCI_INT_CARD_INSERT) != 0;
2265 		slot->intmask &=
2266 		    ~(SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE);
2267 		slot->intmask |= present ? SDHCI_INT_CARD_REMOVE :
2268 		    SDHCI_INT_CARD_INSERT;
2269 		WR4(slot, SDHCI_INT_ENABLE, slot->intmask);
2270 		WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask);
2271 		WR4(slot, SDHCI_INT_STATUS, intmask &
2272 		    (SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE));
2273 		sdhci_handle_card_present_locked(slot, present);
2274 	}
2275 	/* Handle command interrupts. */
2276 	if (intmask & SDHCI_INT_CMD_MASK) {
2277 		WR4(slot, SDHCI_INT_STATUS, intmask & SDHCI_INT_CMD_MASK);
2278 		sdhci_cmd_irq(slot, intmask & SDHCI_INT_CMD_MASK);
2279 	}
2280 	/* Handle data interrupts. */
2281 	if (intmask & SDHCI_INT_DATA_MASK) {
2282 		WR4(slot, SDHCI_INT_STATUS, intmask & SDHCI_INT_DATA_MASK);
2283 		/* Don't call data_irq in case of errored command. */
2284 		if ((intmask & SDHCI_INT_CMD_ERROR_MASK) == 0)
2285 			sdhci_data_irq(slot, intmask & SDHCI_INT_DATA_MASK);
2286 	}
2287 	/* Handle AutoCMD12 error interrupt. */
2288 	if (intmask & SDHCI_INT_ACMD12ERR) {
2289 		/* Clearing SDHCI_INT_ACMD12ERR may clear SDHCI_ACMD12_ERR. */
2290 		val16 = RD2(slot, SDHCI_ACMD12_ERR);
2291 		WR4(slot, SDHCI_INT_STATUS, SDHCI_INT_ACMD12ERR);
2292 		sdhci_acmd_irq(slot, val16);
2293 	}
2294 	/* Handle bus power interrupt. */
2295 	if (intmask & SDHCI_INT_BUS_POWER) {
2296 		WR4(slot, SDHCI_INT_STATUS, SDHCI_INT_BUS_POWER);
2297 		slot_printf(slot, "Card is consuming too much power!\n");
2298 	}
2299 	intmask &= ~(SDHCI_INT_ERROR | SDHCI_INT_TUNEERR | SDHCI_INT_RETUNE |
2300 	    SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE | SDHCI_INT_CMD_MASK |
2301 	    SDHCI_INT_DATA_MASK | SDHCI_INT_ACMD12ERR | SDHCI_INT_BUS_POWER);
2302 	/* The rest is unknown. */
2303 	if (intmask) {
2304 		WR4(slot, SDHCI_INT_STATUS, intmask);
2305 		slot_printf(slot, "Unexpected interrupt 0x%08x.\n",
2306 		    intmask);
2307 		sdhci_dumpregs(slot);
2308 	}
2309 
2310 	SDHCI_UNLOCK(slot);
2311 }
2312 
2313 int
2314 sdhci_generic_read_ivar(device_t bus, device_t child, int which,
2315     uintptr_t *result)
2316 {
2317 	const struct sdhci_slot *slot = device_get_ivars(child);
2318 
2319 	switch (which) {
2320 	default:
2321 		return (EINVAL);
2322 	case MMCBR_IVAR_BUS_MODE:
2323 		*result = slot->host.ios.bus_mode;
2324 		break;
2325 	case MMCBR_IVAR_BUS_WIDTH:
2326 		*result = slot->host.ios.bus_width;
2327 		break;
2328 	case MMCBR_IVAR_CHIP_SELECT:
2329 		*result = slot->host.ios.chip_select;
2330 		break;
2331 	case MMCBR_IVAR_CLOCK:
2332 		*result = slot->host.ios.clock;
2333 		break;
2334 	case MMCBR_IVAR_F_MIN:
2335 		*result = slot->host.f_min;
2336 		break;
2337 	case MMCBR_IVAR_F_MAX:
2338 		*result = slot->host.f_max;
2339 		break;
2340 	case MMCBR_IVAR_HOST_OCR:
2341 		*result = slot->host.host_ocr;
2342 		break;
2343 	case MMCBR_IVAR_MODE:
2344 		*result = slot->host.mode;
2345 		break;
2346 	case MMCBR_IVAR_OCR:
2347 		*result = slot->host.ocr;
2348 		break;
2349 	case MMCBR_IVAR_POWER_MODE:
2350 		*result = slot->host.ios.power_mode;
2351 		break;
2352 	case MMCBR_IVAR_VDD:
2353 		*result = slot->host.ios.vdd;
2354 		break;
2355 	case MMCBR_IVAR_RETUNE_REQ:
2356 		if (slot->opt & SDHCI_TUNING_ENABLED) {
2357 			if (slot->retune_req & SDHCI_RETUNE_REQ_RESET) {
2358 				*result = retune_req_reset;
2359 				break;
2360 			}
2361 			if (slot->retune_req & SDHCI_RETUNE_REQ_NEEDED) {
2362 				*result = retune_req_normal;
2363 				break;
2364 			}
2365 		}
2366 		*result = retune_req_none;
2367 		break;
2368 	case MMCBR_IVAR_VCCQ:
2369 		*result = slot->host.ios.vccq;
2370 		break;
2371 	case MMCBR_IVAR_CAPS:
2372 		*result = slot->host.caps;
2373 		break;
2374 	case MMCBR_IVAR_TIMING:
2375 		*result = slot->host.ios.timing;
2376 		break;
2377 	case MMCBR_IVAR_MAX_DATA:
2378 		/*
2379 		 * Re-tuning modes 1 and 2 restrict the maximum data length
2380 		 * per read/write command to 4 MiB.
2381 		 */
2382 		if (slot->opt & SDHCI_TUNING_ENABLED &&
2383 		    (slot->retune_mode == SDHCI_RETUNE_MODE_1 ||
2384 		    slot->retune_mode == SDHCI_RETUNE_MODE_2)) {
2385 			*result = 4 * 1024 * 1024 / MMC_SECTOR_SIZE;
2386 			break;
2387 		}
2388 		*result = 65535;
2389 		break;
2390 	case MMCBR_IVAR_MAX_BUSY_TIMEOUT:
2391 		/*
2392 		 * Currently, sdhci_start_data() hardcodes 1 s for all CMDs.
2393 		 */
2394 		*result = 1000000;
2395 		break;
2396 	}
2397 	return (0);
2398 }
2399 
2400 int
2401 sdhci_generic_write_ivar(device_t bus, device_t child, int which,
2402     uintptr_t value)
2403 {
2404 	struct sdhci_slot *slot = device_get_ivars(child);
2405 	uint32_t clock, max_clock;
2406 	int i;
2407 
2408 	if (sdhci_debug > 1)
2409 		slot_printf(slot, "%s: var=%d\n", __func__, which);
2410 	switch (which) {
2411 	default:
2412 		return (EINVAL);
2413 	case MMCBR_IVAR_BUS_MODE:
2414 		slot->host.ios.bus_mode = value;
2415 		break;
2416 	case MMCBR_IVAR_BUS_WIDTH:
2417 		slot->host.ios.bus_width = value;
2418 		break;
2419 	case MMCBR_IVAR_CHIP_SELECT:
2420 		slot->host.ios.chip_select = value;
2421 		break;
2422 	case MMCBR_IVAR_CLOCK:
2423 		if (value > 0) {
2424 			max_clock = slot->max_clk;
2425 			clock = max_clock;
2426 
2427 			if (slot->version < SDHCI_SPEC_300) {
2428 				for (i = 0; i < SDHCI_200_MAX_DIVIDER;
2429 				    i <<= 1) {
2430 					if (clock <= value)
2431 						break;
2432 					clock >>= 1;
2433 				}
2434 			} else {
2435 				for (i = 0; i < SDHCI_300_MAX_DIVIDER;
2436 				    i += 2) {
2437 					if (clock <= value)
2438 						break;
2439 					clock = max_clock / (i + 2);
2440 				}
2441 			}
2442 
2443 			slot->host.ios.clock = clock;
2444 		} else
2445 			slot->host.ios.clock = 0;
2446 		break;
2447 	case MMCBR_IVAR_MODE:
2448 		slot->host.mode = value;
2449 		break;
2450 	case MMCBR_IVAR_OCR:
2451 		slot->host.ocr = value;
2452 		break;
2453 	case MMCBR_IVAR_POWER_MODE:
2454 		slot->host.ios.power_mode = value;
2455 		break;
2456 	case MMCBR_IVAR_VDD:
2457 		slot->host.ios.vdd = value;
2458 		break;
2459 	case MMCBR_IVAR_VCCQ:
2460 		slot->host.ios.vccq = value;
2461 		break;
2462 	case MMCBR_IVAR_TIMING:
2463 		slot->host.ios.timing = value;
2464 		break;
2465 	case MMCBR_IVAR_CAPS:
2466 	case MMCBR_IVAR_HOST_OCR:
2467 	case MMCBR_IVAR_F_MIN:
2468 	case MMCBR_IVAR_F_MAX:
2469 	case MMCBR_IVAR_MAX_DATA:
2470 	case MMCBR_IVAR_RETUNE_REQ:
2471 		return (EINVAL);
2472 	}
2473 	return (0);
2474 }
2475 
2476 #ifdef MMCCAM
2477 void
2478 sdhci_start_slot(struct sdhci_slot *slot)
2479 {
2480 
2481 	if ((slot->devq = cam_simq_alloc(1)) == NULL)
2482 		goto fail;
2483 
2484 	mtx_init(&slot->sim_mtx, "sdhcisim", NULL, MTX_DEF);
2485 	slot->sim = cam_sim_alloc_dev(sdhci_cam_action, sdhci_cam_poll,
2486 	    "sdhci_slot", slot, slot->bus,
2487 	    &slot->sim_mtx, 1, 1, slot->devq);
2488 
2489 	if (slot->sim == NULL) {
2490 		cam_simq_free(slot->devq);
2491 		slot_printf(slot, "cannot allocate CAM SIM\n");
2492 		goto fail;
2493 	}
2494 
2495 	mtx_lock(&slot->sim_mtx);
2496 	if (xpt_bus_register(slot->sim, slot->bus, 0) != 0) {
2497 		slot_printf(slot, "cannot register SCSI pass-through bus\n");
2498 		cam_sim_free(slot->sim, FALSE);
2499 		cam_simq_free(slot->devq);
2500 		mtx_unlock(&slot->sim_mtx);
2501 		goto fail;
2502 	}
2503 	mtx_unlock(&slot->sim_mtx);
2504 
2505 	/* End CAM-specific init */
2506 	slot->card_present = 0;
2507 	sdhci_card_task(slot, 0);
2508 	return;
2509 
2510 fail:
2511 	if (slot->sim != NULL) {
2512 		mtx_lock(&slot->sim_mtx);
2513 		xpt_bus_deregister(cam_sim_path(slot->sim));
2514 		cam_sim_free(slot->sim, FALSE);
2515 		mtx_unlock(&slot->sim_mtx);
2516 	}
2517 
2518 	if (slot->devq != NULL)
2519 		cam_simq_free(slot->devq);
2520 }
2521 
2522 void
2523 sdhci_cam_action(struct cam_sim *sim, union ccb *ccb)
2524 {
2525 	struct sdhci_slot *slot;
2526 
2527 	slot = cam_sim_softc(sim);
2528 	if (slot == NULL) {
2529 		ccb->ccb_h.status = CAM_SEL_TIMEOUT;
2530 		xpt_done(ccb);
2531 		return;
2532 	}
2533 
2534 	mtx_assert(&slot->sim_mtx, MA_OWNED);
2535 
2536 	switch (ccb->ccb_h.func_code) {
2537 	case XPT_PATH_INQ:
2538 		mmc_path_inq(&ccb->cpi, "Deglitch Networks", sim, maxphys);
2539 		break;
2540 
2541 	case XPT_MMC_GET_TRAN_SETTINGS:
2542 	case XPT_GET_TRAN_SETTINGS:
2543 	{
2544 		struct ccb_trans_settings *cts = &ccb->cts;
2545 		uint32_t max_data;
2546 
2547 		if (sdhci_debug > 1)
2548 			slot_printf(slot, "Got XPT_GET_TRAN_SETTINGS\n");
2549 
2550 		cts->protocol = PROTO_MMCSD;
2551 		cts->protocol_version = 1;
2552 		cts->transport = XPORT_MMCSD;
2553 		cts->transport_version = 1;
2554 		cts->xport_specific.valid = 0;
2555 		cts->proto_specific.mmc.host_ocr = slot->host.host_ocr;
2556 		cts->proto_specific.mmc.host_f_min = slot->host.f_min;
2557 		cts->proto_specific.mmc.host_f_max = slot->host.f_max;
2558 		cts->proto_specific.mmc.host_caps = slot->host.caps;
2559 		/*
2560 		 * Re-tuning modes 1 and 2 restrict the maximum data length
2561 		 * per read/write command to 4 MiB.
2562 		 */
2563 		if (slot->opt & SDHCI_TUNING_ENABLED &&
2564 		    (slot->retune_mode == SDHCI_RETUNE_MODE_1 ||
2565 		    slot->retune_mode == SDHCI_RETUNE_MODE_2)) {
2566 			max_data = 4 * 1024 * 1024 / MMC_SECTOR_SIZE;
2567 		} else {
2568 			max_data = 65535;
2569 		}
2570 		cts->proto_specific.mmc.host_max_data = max_data;
2571 
2572 		memcpy(&cts->proto_specific.mmc.ios, &slot->host.ios, sizeof(struct mmc_ios));
2573 		ccb->ccb_h.status = CAM_REQ_CMP;
2574 		break;
2575 	}
2576 	case XPT_MMC_SET_TRAN_SETTINGS:
2577 	case XPT_SET_TRAN_SETTINGS:
2578 		if (sdhci_debug > 1)
2579 			slot_printf(slot, "Got XPT_SET_TRAN_SETTINGS\n");
2580 		sdhci_cam_settran_settings(slot, ccb);
2581 		ccb->ccb_h.status = CAM_REQ_CMP;
2582 		break;
2583 	case XPT_RESET_BUS:
2584 		if (sdhci_debug > 1)
2585 			slot_printf(slot, "Got XPT_RESET_BUS, ACK it...\n");
2586 		ccb->ccb_h.status = CAM_REQ_CMP;
2587 		break;
2588 	case XPT_MMC_IO:
2589 		/*
2590 		 * Here is the HW-dependent part of
2591 		 * sending the command to the underlying h/w
2592 		 * At some point in the future an interrupt comes.
2593 		 * Then the request will be marked as completed.
2594 		 */
2595 		if (__predict_false(sdhci_debug > 1))
2596 			slot_printf(slot, "Got XPT_MMC_IO\n");
2597 		ccb->ccb_h.status = CAM_REQ_INPROG;
2598 
2599 		sdhci_cam_request(cam_sim_softc(sim), ccb);
2600 		return;
2601 	default:
2602 		ccb->ccb_h.status = CAM_REQ_INVALID;
2603 		break;
2604 	}
2605 	xpt_done(ccb);
2606 	return;
2607 }
2608 
2609 void
2610 sdhci_cam_poll(struct cam_sim *sim)
2611 {
2612 	sdhci_generic_intr(cam_sim_softc(sim));
2613 }
2614 
2615 static int
2616 sdhci_cam_get_possible_host_clock(const struct sdhci_slot *slot,
2617     int proposed_clock)
2618 {
2619 	int max_clock, clock, i;
2620 
2621 	if (proposed_clock == 0)
2622 		return 0;
2623 	max_clock = slot->max_clk;
2624 	clock = max_clock;
2625 
2626 	if (slot->version < SDHCI_SPEC_300) {
2627 		for (i = 0; i < SDHCI_200_MAX_DIVIDER; i <<= 1) {
2628 			if (clock <= proposed_clock)
2629 				break;
2630 			clock >>= 1;
2631 		}
2632 	} else {
2633 		for (i = 0; i < SDHCI_300_MAX_DIVIDER; i += 2) {
2634 			if (clock <= proposed_clock)
2635 				break;
2636 			clock = max_clock / (i + 2);
2637 		}
2638 	}
2639 	return clock;
2640 }
2641 
2642 static int
2643 sdhci_cam_settran_settings(struct sdhci_slot *slot, union ccb *ccb)
2644 {
2645 	struct mmc_ios *ios;
2646 	const struct mmc_ios *new_ios;
2647 	const struct ccb_trans_settings_mmc *cts;
2648 
2649 	ios = &slot->host.ios;
2650 	cts = &ccb->cts.proto_specific.mmc;
2651 	new_ios = &cts->ios;
2652 
2653 	/* Update only requested fields */
2654 	if (cts->ios_valid & MMC_CLK) {
2655 		ios->clock = sdhci_cam_get_possible_host_clock(slot, new_ios->clock);
2656 		if (sdhci_debug > 1)
2657 			slot_printf(slot, "Clock => %d\n", ios->clock);
2658 	}
2659 	if (cts->ios_valid & MMC_VDD) {
2660 		ios->vdd = new_ios->vdd;
2661 		if (sdhci_debug > 1)
2662 			slot_printf(slot, "VDD => %d\n", ios->vdd);
2663 	}
2664 	if (cts->ios_valid & MMC_CS) {
2665 		ios->chip_select = new_ios->chip_select;
2666 		if (sdhci_debug > 1)
2667 			slot_printf(slot, "CS => %d\n", ios->chip_select);
2668 	}
2669 	if (cts->ios_valid & MMC_BW) {
2670 		ios->bus_width = new_ios->bus_width;
2671 		if (sdhci_debug > 1)
2672 			slot_printf(slot, "Bus width => %d\n", ios->bus_width);
2673 	}
2674 	if (cts->ios_valid & MMC_PM) {
2675 		ios->power_mode = new_ios->power_mode;
2676 		if (sdhci_debug > 1)
2677 			slot_printf(slot, "Power mode => %d\n", ios->power_mode);
2678 	}
2679 	if (cts->ios_valid & MMC_BT) {
2680 		ios->timing = new_ios->timing;
2681 		if (sdhci_debug > 1)
2682 			slot_printf(slot, "Timing => %d\n", ios->timing);
2683 	}
2684 	if (cts->ios_valid & MMC_BM) {
2685 		ios->bus_mode = new_ios->bus_mode;
2686 		if (sdhci_debug > 1)
2687 			slot_printf(slot, "Bus mode => %d\n", ios->bus_mode);
2688 	}
2689 	if (cts->ios_valid & MMC_VCCQ) {
2690 		ios->vccq = new_ios->vccq;
2691 		if (sdhci_debug > 1)
2692 			slot_printf(slot, "VCCQ => %d\n", ios->vccq);
2693 	}
2694 
2695 	/* XXX Provide a way to call a chip-specific IOS update, required for TI */
2696 	return (sdhci_cam_update_ios(slot));
2697 }
2698 
2699 static int
2700 sdhci_cam_update_ios(struct sdhci_slot *slot)
2701 {
2702 	struct mmc_ios *ios = &slot->host.ios;
2703 
2704 	if (sdhci_debug > 1)
2705 		slot_printf(slot, "%s: power_mode=%d, clk=%d, bus_width=%d, timing=%d\n",
2706 		    __func__, ios->power_mode, ios->clock, ios->bus_width, ios->timing);
2707 	SDHCI_LOCK(slot);
2708 	/* Do full reset on bus power down to clear from any state. */
2709 	if (ios->power_mode == power_off) {
2710 		WR4(slot, SDHCI_SIGNAL_ENABLE, 0);
2711 		sdhci_init(slot);
2712 	}
2713 	/* Configure the bus. */
2714 	sdhci_set_clock(slot, ios->clock);
2715 	sdhci_set_power(slot, (ios->power_mode == power_off) ? 0 : ios->vdd);
2716 	if (ios->bus_width == bus_width_8) {
2717 		slot->hostctrl |= SDHCI_CTRL_8BITBUS;
2718 		slot->hostctrl &= ~SDHCI_CTRL_4BITBUS;
2719 	} else if (ios->bus_width == bus_width_4) {
2720 		slot->hostctrl &= ~SDHCI_CTRL_8BITBUS;
2721 		slot->hostctrl |= SDHCI_CTRL_4BITBUS;
2722 	} else if (ios->bus_width == bus_width_1) {
2723 		slot->hostctrl &= ~SDHCI_CTRL_8BITBUS;
2724 		slot->hostctrl &= ~SDHCI_CTRL_4BITBUS;
2725 	} else {
2726 		panic("Invalid bus width: %d", ios->bus_width);
2727 	}
2728 	if (ios->timing == bus_timing_hs &&
2729 	    !(slot->quirks & SDHCI_QUIRK_DONT_SET_HISPD_BIT))
2730 		slot->hostctrl |= SDHCI_CTRL_HISPD;
2731 	else
2732 		slot->hostctrl &= ~SDHCI_CTRL_HISPD;
2733 	WR1(slot, SDHCI_HOST_CONTROL, slot->hostctrl);
2734 	/* Some controllers like reset after bus changes. */
2735 	if(slot->quirks & SDHCI_QUIRK_RESET_ON_IOS)
2736 		sdhci_reset(slot, SDHCI_RESET_CMD | SDHCI_RESET_DATA);
2737 
2738 	SDHCI_UNLOCK(slot);
2739 	return (0);
2740 }
2741 
2742 static int
2743 sdhci_cam_request(struct sdhci_slot *slot, union ccb *ccb)
2744 {
2745 	const struct ccb_mmcio *mmcio;
2746 
2747 	mmcio = &ccb->mmcio;
2748 
2749 	SDHCI_LOCK(slot);
2750 /*	if (slot->req != NULL) {
2751 		SDHCI_UNLOCK(slot);
2752 		return (EBUSY);
2753 	}
2754 */
2755 	if (__predict_false(sdhci_debug > 1)) {
2756 		slot_printf(slot, "CMD%u arg %#x flags %#x dlen %u dflags %#x "
2757 		    "blksz=%zu blkcnt=%zu\n",
2758 		    mmcio->cmd.opcode, mmcio->cmd.arg, mmcio->cmd.flags,
2759 		    mmcio->cmd.data != NULL ? (unsigned int) mmcio->cmd.data->len : 0,
2760 		    mmcio->cmd.data != NULL ? mmcio->cmd.data->flags : 0,
2761 		    mmcio->cmd.data != NULL ? mmcio->cmd.data->block_size : 0,
2762 		    mmcio->cmd.data != NULL ? mmcio->cmd.data->block_count : 0);
2763 	}
2764 	if (mmcio->cmd.data != NULL) {
2765 		if (mmcio->cmd.data->len == 0 || mmcio->cmd.data->flags == 0)
2766 			panic("data->len = %d, data->flags = %d -- something is b0rked",
2767 			    (int)mmcio->cmd.data->len, mmcio->cmd.data->flags);
2768 	}
2769 	slot->ccb = ccb;
2770 	slot->flags = 0;
2771 	sdhci_start(slot);
2772 	SDHCI_UNLOCK(slot);
2773 	return (0);
2774 }
2775 #endif /* MMCCAM */
2776 
2777 MODULE_VERSION(sdhci, SDHCI_VERSION);
2778