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