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