xref: /freebsd/sys/dev/sdhci/sdhci.c (revision c66ec88fed842fbaad62c30d510644ceb7bd2d71)
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);
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)
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, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
754 	    slot->sdma_bbufsz, 1, slot->sdma_bbufsz, BUS_DMA_ALLOCNOW,
755 	    NULL, NULL, &slot->dmatag);
756 	if (err != 0) {
757 		slot_printf(slot, "Can't create DMA tag for SDMA\n");
758 		return (err);
759 	}
760 	/* Allocate DMA memory for the SDMA bounce buffer. */
761 	err = bus_dmamem_alloc(slot->dmatag, (void **)&slot->dmamem,
762 	    BUS_DMA_NOWAIT, &slot->dmamap);
763 	if (err != 0) {
764 		slot_printf(slot, "Can't alloc DMA memory for SDMA\n");
765 		bus_dma_tag_destroy(slot->dmatag);
766 		return (err);
767 	}
768 	/* Map the memory of the SDMA bounce buffer. */
769 	err = bus_dmamap_load(slot->dmatag, slot->dmamap,
770 	    (void *)slot->dmamem, slot->sdma_bbufsz, sdhci_getaddr,
771 	    &slot->paddr, 0);
772 	if (err != 0 || slot->paddr == 0) {
773 		slot_printf(slot, "Can't load DMA memory for SDMA\n");
774 		bus_dmamem_free(slot->dmatag, slot->dmamem, slot->dmamap);
775 		bus_dma_tag_destroy(slot->dmatag);
776 		if (err)
777 			return (err);
778 		else
779 			return (EFAULT);
780 	}
781 
782 	return (0);
783 }
784 
785 static void
786 sdhci_dma_free(struct sdhci_slot *slot)
787 {
788 
789 	bus_dmamap_unload(slot->dmatag, slot->dmamap);
790 	bus_dmamem_free(slot->dmatag, slot->dmamem, slot->dmamap);
791 	bus_dma_tag_destroy(slot->dmatag);
792 }
793 
794 int
795 sdhci_init_slot(device_t dev, struct sdhci_slot *slot, int num)
796 {
797 	kobjop_desc_t kobj_desc;
798 	kobj_method_t *kobj_method;
799 	uint32_t caps, caps2, freq, host_caps;
800 	int err;
801 
802 	SDHCI_LOCK_INIT(slot);
803 
804 	slot->num = num;
805 	slot->bus = dev;
806 
807 	slot->version = (RD2(slot, SDHCI_HOST_VERSION)
808 		>> SDHCI_SPEC_VER_SHIFT) & SDHCI_SPEC_VER_MASK;
809 	if (slot->quirks & SDHCI_QUIRK_MISSING_CAPS) {
810 		caps = slot->caps;
811 		caps2 = slot->caps2;
812 	} else {
813 		caps = RD4(slot, SDHCI_CAPABILITIES);
814 		if (slot->version >= SDHCI_SPEC_300)
815 			caps2 = RD4(slot, SDHCI_CAPABILITIES2);
816 		else
817 			caps2 = 0;
818 	}
819 	if (slot->version >= SDHCI_SPEC_300) {
820 		if ((caps & SDHCI_SLOTTYPE_MASK) != SDHCI_SLOTTYPE_REMOVABLE &&
821 		    (caps & SDHCI_SLOTTYPE_MASK) != SDHCI_SLOTTYPE_EMBEDDED) {
822 			slot_printf(slot,
823 			    "Driver doesn't support shared bus slots\n");
824 			SDHCI_LOCK_DESTROY(slot);
825 			return (ENXIO);
826 		} else if ((caps & SDHCI_SLOTTYPE_MASK) ==
827 		    SDHCI_SLOTTYPE_EMBEDDED) {
828 			slot->opt |= SDHCI_SLOT_EMBEDDED | SDHCI_NON_REMOVABLE;
829 		}
830 	}
831 	/* Calculate base clock frequency. */
832 	if (slot->version >= SDHCI_SPEC_300)
833 		freq = (caps & SDHCI_CLOCK_V3_BASE_MASK) >>
834 		    SDHCI_CLOCK_BASE_SHIFT;
835 	else
836 		freq = (caps & SDHCI_CLOCK_BASE_MASK) >>
837 		    SDHCI_CLOCK_BASE_SHIFT;
838 	if (freq != 0)
839 		slot->max_clk = freq * 1000000;
840 	/*
841 	 * If the frequency wasn't in the capabilities and the hardware driver
842 	 * hasn't already set max_clk we're probably not going to work right
843 	 * with an assumption, so complain about it.
844 	 */
845 	if (slot->max_clk == 0) {
846 		slot->max_clk = SDHCI_DEFAULT_MAX_FREQ * 1000000;
847 		slot_printf(slot, "Hardware doesn't specify base clock "
848 		    "frequency, using %dMHz as default.\n",
849 		    SDHCI_DEFAULT_MAX_FREQ);
850 	}
851 	/* Calculate/set timeout clock frequency. */
852 	if (slot->quirks & SDHCI_QUIRK_DATA_TIMEOUT_USES_SDCLK) {
853 		slot->timeout_clk = slot->max_clk / 1000;
854 	} else if (slot->quirks & SDHCI_QUIRK_DATA_TIMEOUT_1MHZ) {
855 		slot->timeout_clk = 1000;
856 	} else {
857 		slot->timeout_clk = (caps & SDHCI_TIMEOUT_CLK_MASK) >>
858 		    SDHCI_TIMEOUT_CLK_SHIFT;
859 		if (caps & SDHCI_TIMEOUT_CLK_UNIT)
860 			slot->timeout_clk *= 1000;
861 	}
862 	/*
863 	 * If the frequency wasn't in the capabilities and the hardware driver
864 	 * hasn't already set timeout_clk we'll probably work okay using the
865 	 * max timeout, but still mention it.
866 	 */
867 	if (slot->timeout_clk == 0) {
868 		slot_printf(slot, "Hardware doesn't specify timeout clock "
869 		    "frequency, setting BROKEN_TIMEOUT quirk.\n");
870 		slot->quirks |= SDHCI_QUIRK_BROKEN_TIMEOUT_VAL;
871 	}
872 
873 	slot->host.f_min = SDHCI_MIN_FREQ(slot->bus, slot);
874 	slot->host.f_max = slot->max_clk;
875 	slot->host.host_ocr = 0;
876 	if (caps & SDHCI_CAN_VDD_330)
877 	    slot->host.host_ocr |= MMC_OCR_320_330 | MMC_OCR_330_340;
878 	if (caps & SDHCI_CAN_VDD_300)
879 	    slot->host.host_ocr |= MMC_OCR_290_300 | MMC_OCR_300_310;
880 	/*
881 	 * 1.8V VDD is not supposed to be used for removable cards.  Hardware
882 	 * prior to v3.0 had no way to indicate embedded slots, but did
883 	 * sometimes support 1.8v for non-removable devices.
884 	 */
885 	if ((caps & SDHCI_CAN_VDD_180) && (slot->version < SDHCI_SPEC_300 ||
886 	    (slot->opt & SDHCI_SLOT_EMBEDDED)))
887 	    slot->host.host_ocr |= MMC_OCR_LOW_VOLTAGE;
888 	if (slot->host.host_ocr == 0) {
889 		slot_printf(slot, "Hardware doesn't report any "
890 		    "support voltages.\n");
891 	}
892 
893 	host_caps = MMC_CAP_4_BIT_DATA;
894 	if (caps & SDHCI_CAN_DO_8BITBUS)
895 		host_caps |= MMC_CAP_8_BIT_DATA;
896 	if (caps & SDHCI_CAN_DO_HISPD)
897 		host_caps |= MMC_CAP_HSPEED;
898 	if (slot->quirks & SDHCI_QUIRK_BOOT_NOACC)
899 		host_caps |= MMC_CAP_BOOT_NOACC;
900 	if (slot->quirks & SDHCI_QUIRK_WAIT_WHILE_BUSY)
901 		host_caps |= MMC_CAP_WAIT_WHILE_BUSY;
902 
903 	/* Determine supported UHS-I and eMMC modes. */
904 	if (caps2 & (SDHCI_CAN_SDR50 | SDHCI_CAN_SDR104 | SDHCI_CAN_DDR50))
905 		host_caps |= MMC_CAP_UHS_SDR12 | MMC_CAP_UHS_SDR25;
906 	if (caps2 & SDHCI_CAN_SDR104) {
907 		host_caps |= MMC_CAP_UHS_SDR104 | MMC_CAP_UHS_SDR50;
908 		if (!(slot->quirks & SDHCI_QUIRK_BROKEN_MMC_HS200))
909 			host_caps |= MMC_CAP_MMC_HS200;
910 	} else if (caps2 & SDHCI_CAN_SDR50)
911 		host_caps |= MMC_CAP_UHS_SDR50;
912 	if (caps2 & SDHCI_CAN_DDR50 &&
913 	    !(slot->quirks & SDHCI_QUIRK_BROKEN_UHS_DDR50))
914 		host_caps |= MMC_CAP_UHS_DDR50;
915 	if (slot->quirks & SDHCI_QUIRK_MMC_DDR52)
916 		host_caps |= MMC_CAP_MMC_DDR52;
917 	if (slot->quirks & SDHCI_QUIRK_CAPS_BIT63_FOR_MMC_HS400 &&
918 	    caps2 & SDHCI_CAN_MMC_HS400)
919 		host_caps |= MMC_CAP_MMC_HS400;
920 	if (slot->quirks & SDHCI_QUIRK_MMC_HS400_IF_CAN_SDR104 &&
921 	    caps2 & SDHCI_CAN_SDR104)
922 		host_caps |= MMC_CAP_MMC_HS400;
923 
924 	/*
925 	 * Disable UHS-I and eMMC modes if the set_uhs_timing method is the
926 	 * default NULL implementation.
927 	 */
928 	kobj_desc = &sdhci_set_uhs_timing_desc;
929 	kobj_method = kobj_lookup_method(((kobj_t)dev)->ops->cls, NULL,
930 	    kobj_desc);
931 	if (kobj_method == &kobj_desc->deflt)
932 		host_caps &= ~(MMC_CAP_UHS_SDR12 | MMC_CAP_UHS_SDR25 |
933 		    MMC_CAP_UHS_SDR50 | MMC_CAP_UHS_DDR50 | MMC_CAP_UHS_SDR104 |
934 		    MMC_CAP_MMC_DDR52 | MMC_CAP_MMC_HS200 | MMC_CAP_MMC_HS400);
935 
936 #define	SDHCI_CAP_MODES_TUNING(caps2)					\
937     (((caps2) & SDHCI_TUNE_SDR50 ? MMC_CAP_UHS_SDR50 : 0) |		\
938     MMC_CAP_UHS_DDR50 | MMC_CAP_UHS_SDR104 | MMC_CAP_MMC_HS200 |	\
939     MMC_CAP_MMC_HS400)
940 
941 	/*
942 	 * Disable UHS-I and eMMC modes that require (re-)tuning if either
943 	 * the tune or re-tune method is the default NULL implementation.
944 	 */
945 	kobj_desc = &mmcbr_tune_desc;
946 	kobj_method = kobj_lookup_method(((kobj_t)dev)->ops->cls, NULL,
947 	    kobj_desc);
948 	if (kobj_method == &kobj_desc->deflt)
949 		goto no_tuning;
950 	kobj_desc = &mmcbr_retune_desc;
951 	kobj_method = kobj_lookup_method(((kobj_t)dev)->ops->cls, NULL,
952 	    kobj_desc);
953 	if (kobj_method == &kobj_desc->deflt) {
954 no_tuning:
955 		host_caps &= ~(SDHCI_CAP_MODES_TUNING(caps2));
956 	}
957 
958 	/* Allocate tuning structures and determine tuning parameters. */
959 	if (host_caps & SDHCI_CAP_MODES_TUNING(caps2)) {
960 		slot->opt |= SDHCI_TUNING_SUPPORTED;
961 		slot->tune_req = malloc(sizeof(*slot->tune_req), M_DEVBUF,
962 		    M_WAITOK);
963 		slot->tune_cmd = malloc(sizeof(*slot->tune_cmd), M_DEVBUF,
964 		    M_WAITOK);
965 		slot->tune_data = malloc(sizeof(*slot->tune_data), M_DEVBUF,
966 		    M_WAITOK);
967 		if (caps2 & SDHCI_TUNE_SDR50)
968 			slot->opt |= SDHCI_SDR50_NEEDS_TUNING;
969 		slot->retune_mode = (caps2 & SDHCI_RETUNE_MODES_MASK) >>
970 		    SDHCI_RETUNE_MODES_SHIFT;
971 		if (slot->retune_mode == SDHCI_RETUNE_MODE_1) {
972 			slot->retune_count = (caps2 & SDHCI_RETUNE_CNT_MASK) >>
973 			    SDHCI_RETUNE_CNT_SHIFT;
974 			if (slot->retune_count > 0xb) {
975 				slot_printf(slot, "Unknown re-tuning count "
976 				    "%x, using 1 sec\n", slot->retune_count);
977 				slot->retune_count = 1;
978 			} else if (slot->retune_count != 0)
979 				slot->retune_count =
980 				    1 << (slot->retune_count - 1);
981 		}
982 	}
983 
984 #undef SDHCI_CAP_MODES_TUNING
985 
986 	/* Determine supported VCCQ signaling levels. */
987 	host_caps |= MMC_CAP_SIGNALING_330;
988 	if (host_caps & (MMC_CAP_UHS_SDR12 | MMC_CAP_UHS_SDR25 |
989 	    MMC_CAP_UHS_SDR50 | MMC_CAP_UHS_DDR50 | MMC_CAP_UHS_SDR104 |
990 	    MMC_CAP_MMC_DDR52_180 | MMC_CAP_MMC_HS200_180 |
991 	    MMC_CAP_MMC_HS400_180))
992 		host_caps |= MMC_CAP_SIGNALING_120 | MMC_CAP_SIGNALING_180;
993 
994 	/*
995 	 * Disable 1.2 V and 1.8 V signaling if the switch_vccq method is the
996 	 * default NULL implementation.  Disable 1.2 V support if it's the
997 	 * generic SDHCI implementation.
998 	 */
999 	kobj_desc = &mmcbr_switch_vccq_desc;
1000 	kobj_method = kobj_lookup_method(((kobj_t)dev)->ops->cls, NULL,
1001 	    kobj_desc);
1002 	if (kobj_method == &kobj_desc->deflt)
1003 		host_caps &= ~(MMC_CAP_SIGNALING_120 | MMC_CAP_SIGNALING_180);
1004 	else if (kobj_method->func == (kobjop_t)sdhci_generic_switch_vccq)
1005 		host_caps &= ~MMC_CAP_SIGNALING_120;
1006 
1007 	/* Determine supported driver types (type B is always mandatory). */
1008 	if (caps2 & SDHCI_CAN_DRIVE_TYPE_A)
1009 		host_caps |= MMC_CAP_DRIVER_TYPE_A;
1010 	if (caps2 & SDHCI_CAN_DRIVE_TYPE_C)
1011 		host_caps |= MMC_CAP_DRIVER_TYPE_C;
1012 	if (caps2 & SDHCI_CAN_DRIVE_TYPE_D)
1013 		host_caps |= MMC_CAP_DRIVER_TYPE_D;
1014 	slot->host.caps = host_caps;
1015 
1016 	/* Decide if we have usable DMA. */
1017 	if (caps & SDHCI_CAN_DO_DMA)
1018 		slot->opt |= SDHCI_HAVE_DMA;
1019 
1020 	if (slot->quirks & SDHCI_QUIRK_BROKEN_DMA)
1021 		slot->opt &= ~SDHCI_HAVE_DMA;
1022 	if (slot->quirks & SDHCI_QUIRK_FORCE_DMA)
1023 		slot->opt |= SDHCI_HAVE_DMA;
1024 	if (slot->quirks & SDHCI_QUIRK_ALL_SLOTS_NON_REMOVABLE)
1025 		slot->opt |= SDHCI_NON_REMOVABLE;
1026 
1027 	/*
1028 	 * Use platform-provided transfer backend
1029 	 * with PIO as a fallback mechanism
1030 	 */
1031 	if (slot->opt & SDHCI_PLATFORM_TRANSFER)
1032 		slot->opt &= ~SDHCI_HAVE_DMA;
1033 
1034 	if (slot->opt & SDHCI_HAVE_DMA) {
1035 		err = sdhci_dma_alloc(slot);
1036 		if (err != 0) {
1037 			if (slot->opt & SDHCI_TUNING_SUPPORTED) {
1038 				free(slot->tune_req, M_DEVBUF);
1039 				free(slot->tune_cmd, M_DEVBUF);
1040 				free(slot->tune_data, M_DEVBUF);
1041 			}
1042 			SDHCI_LOCK_DESTROY(slot);
1043 			return (err);
1044 		}
1045 	}
1046 
1047 	if (bootverbose || sdhci_debug) {
1048 		slot_printf(slot,
1049 		    "%uMHz%s %s VDD:%s%s%s VCCQ: 3.3V%s%s DRV: B%s%s%s %s %s\n",
1050 		    slot->max_clk / 1000000,
1051 		    (caps & SDHCI_CAN_DO_HISPD) ? " HS" : "",
1052 		    (host_caps & MMC_CAP_8_BIT_DATA) ? "8bits" :
1053 			((host_caps & MMC_CAP_4_BIT_DATA) ? "4bits" : "1bit"),
1054 		    (caps & SDHCI_CAN_VDD_330) ? " 3.3V" : "",
1055 		    (caps & SDHCI_CAN_VDD_300) ? " 3.0V" : "",
1056 		    ((caps & SDHCI_CAN_VDD_180) &&
1057 		    (slot->opt & SDHCI_SLOT_EMBEDDED)) ? " 1.8V" : "",
1058 		    (host_caps & MMC_CAP_SIGNALING_180) ? " 1.8V" : "",
1059 		    (host_caps & MMC_CAP_SIGNALING_120) ? " 1.2V" : "",
1060 		    (host_caps & MMC_CAP_DRIVER_TYPE_A) ? "A" : "",
1061 		    (host_caps & MMC_CAP_DRIVER_TYPE_C) ? "C" : "",
1062 		    (host_caps & MMC_CAP_DRIVER_TYPE_D) ? "D" : "",
1063 		    (slot->opt & SDHCI_HAVE_DMA) ? "DMA" : "PIO",
1064 		    (slot->opt & SDHCI_SLOT_EMBEDDED) ? "embedded" :
1065 		    (slot->opt & SDHCI_NON_REMOVABLE) ? "non-removable" :
1066 		    "removable");
1067 		if (host_caps & (MMC_CAP_MMC_DDR52 | MMC_CAP_MMC_HS200 |
1068 		    MMC_CAP_MMC_HS400 | MMC_CAP_MMC_ENH_STROBE))
1069 			slot_printf(slot, "eMMC:%s%s%s%s\n",
1070 			    (host_caps & MMC_CAP_MMC_DDR52) ? " DDR52" : "",
1071 			    (host_caps & MMC_CAP_MMC_HS200) ? " HS200" : "",
1072 			    (host_caps & MMC_CAP_MMC_HS400) ? " HS400" : "",
1073 			    ((host_caps &
1074 			    (MMC_CAP_MMC_HS400 | MMC_CAP_MMC_ENH_STROBE)) ==
1075 			    (MMC_CAP_MMC_HS400 | MMC_CAP_MMC_ENH_STROBE)) ?
1076 			    " HS400ES" : "");
1077 		if (host_caps & (MMC_CAP_UHS_SDR12 | MMC_CAP_UHS_SDR25 |
1078 		    MMC_CAP_UHS_SDR50 | MMC_CAP_UHS_SDR104))
1079 			slot_printf(slot, "UHS-I:%s%s%s%s%s\n",
1080 			    (host_caps & MMC_CAP_UHS_SDR12) ? " SDR12" : "",
1081 			    (host_caps & MMC_CAP_UHS_SDR25) ? " SDR25" : "",
1082 			    (host_caps & MMC_CAP_UHS_SDR50) ? " SDR50" : "",
1083 			    (host_caps & MMC_CAP_UHS_SDR104) ? " SDR104" : "",
1084 			    (host_caps & MMC_CAP_UHS_DDR50) ? " DDR50" : "");
1085 		if (slot->opt & SDHCI_TUNING_SUPPORTED)
1086 			slot_printf(slot, "Re-tuning count %d secs, mode %d\n",
1087 			    slot->retune_count, slot->retune_mode + 1);
1088 		sdhci_dumpregs(slot);
1089 	}
1090 
1091 	slot->timeout = 10;
1092 	SYSCTL_ADD_INT(device_get_sysctl_ctx(slot->bus),
1093 	    SYSCTL_CHILDREN(device_get_sysctl_tree(slot->bus)), OID_AUTO,
1094 	    "timeout", CTLFLAG_RWTUN, &slot->timeout, 0,
1095 	    "Maximum timeout for SDHCI transfers (in secs)");
1096 	TASK_INIT(&slot->card_task, 0, sdhci_card_task, slot);
1097 	TIMEOUT_TASK_INIT(taskqueue_swi_giant, &slot->card_delayed_task, 0,
1098 		sdhci_card_task, slot);
1099 	callout_init(&slot->card_poll_callout, 1);
1100 	callout_init_mtx(&slot->timeout_callout, &slot->mtx, 0);
1101 	callout_init_mtx(&slot->retune_callout, &slot->mtx, 0);
1102 
1103 	if ((slot->quirks & SDHCI_QUIRK_POLL_CARD_PRESENT) &&
1104 	    !(slot->opt & SDHCI_NON_REMOVABLE)) {
1105 		callout_reset(&slot->card_poll_callout,
1106 		    SDHCI_CARD_PRESENT_TICKS, sdhci_card_poll, slot);
1107 	}
1108 
1109 	sdhci_init(slot);
1110 
1111 	return (0);
1112 }
1113 
1114 #ifndef MMCCAM
1115 void
1116 sdhci_start_slot(struct sdhci_slot *slot)
1117 {
1118 
1119 	sdhci_card_task(slot, 0);
1120 }
1121 #endif
1122 
1123 int
1124 sdhci_cleanup_slot(struct sdhci_slot *slot)
1125 {
1126 	device_t d;
1127 
1128 	callout_drain(&slot->timeout_callout);
1129 	callout_drain(&slot->card_poll_callout);
1130 	callout_drain(&slot->retune_callout);
1131 	taskqueue_drain(taskqueue_swi_giant, &slot->card_task);
1132 	taskqueue_drain_timeout(taskqueue_swi_giant, &slot->card_delayed_task);
1133 
1134 	SDHCI_LOCK(slot);
1135 	d = slot->dev;
1136 	slot->dev = NULL;
1137 	SDHCI_UNLOCK(slot);
1138 	if (d != NULL)
1139 		device_delete_child(slot->bus, d);
1140 
1141 	SDHCI_LOCK(slot);
1142 	sdhci_reset(slot, SDHCI_RESET_ALL);
1143 	SDHCI_UNLOCK(slot);
1144 	if (slot->opt & SDHCI_HAVE_DMA)
1145 		sdhci_dma_free(slot);
1146 	if (slot->opt & SDHCI_TUNING_SUPPORTED) {
1147 		free(slot->tune_req, M_DEVBUF);
1148 		free(slot->tune_cmd, M_DEVBUF);
1149 		free(slot->tune_data, M_DEVBUF);
1150 	}
1151 
1152 	SDHCI_LOCK_DESTROY(slot);
1153 
1154 	return (0);
1155 }
1156 
1157 int
1158 sdhci_generic_suspend(struct sdhci_slot *slot)
1159 {
1160 
1161 	/*
1162 	 * We expect the MMC layer to issue initial tuning after resume.
1163 	 * Otherwise, we'd need to indicate re-tuning including circuit reset
1164 	 * being required at least for re-tuning modes 1 and 2 ourselves.
1165 	 */
1166 	callout_drain(&slot->retune_callout);
1167 	SDHCI_LOCK(slot);
1168 	slot->opt &= ~SDHCI_TUNING_ENABLED;
1169 	sdhci_reset(slot, SDHCI_RESET_ALL);
1170 	SDHCI_UNLOCK(slot);
1171 
1172 	return (0);
1173 }
1174 
1175 int
1176 sdhci_generic_resume(struct sdhci_slot *slot)
1177 {
1178 
1179 	SDHCI_LOCK(slot);
1180 	sdhci_init(slot);
1181 	SDHCI_UNLOCK(slot);
1182 
1183 	return (0);
1184 }
1185 
1186 uint32_t
1187 sdhci_generic_min_freq(device_t brdev __unused, struct sdhci_slot *slot)
1188 {
1189 
1190 	if (slot->version >= SDHCI_SPEC_300)
1191 		return (slot->max_clk / SDHCI_300_MAX_DIVIDER);
1192 	else
1193 		return (slot->max_clk / SDHCI_200_MAX_DIVIDER);
1194 }
1195 
1196 bool
1197 sdhci_generic_get_card_present(device_t brdev __unused, struct sdhci_slot *slot)
1198 {
1199 
1200 	if (slot->opt & SDHCI_NON_REMOVABLE)
1201 		return true;
1202 
1203 	return (RD4(slot, SDHCI_PRESENT_STATE) & SDHCI_CARD_PRESENT);
1204 }
1205 
1206 void
1207 sdhci_generic_set_uhs_timing(device_t brdev __unused, struct sdhci_slot *slot)
1208 {
1209 	const struct mmc_ios *ios;
1210 	uint16_t hostctrl2;
1211 
1212 	if (slot->version < SDHCI_SPEC_300)
1213 		return;
1214 
1215 	SDHCI_ASSERT_LOCKED(slot);
1216 	ios = &slot->host.ios;
1217 	sdhci_set_clock(slot, 0);
1218 	hostctrl2 = RD2(slot, SDHCI_HOST_CONTROL2);
1219 	hostctrl2 &= ~SDHCI_CTRL2_UHS_MASK;
1220 	if (ios->clock > SD_SDR50_MAX) {
1221 		if (ios->timing == bus_timing_mmc_hs400 ||
1222 		    ios->timing == bus_timing_mmc_hs400es)
1223 			hostctrl2 |= SDHCI_CTRL2_MMC_HS400;
1224 		else
1225 			hostctrl2 |= SDHCI_CTRL2_UHS_SDR104;
1226 	}
1227 	else if (ios->clock > SD_SDR25_MAX)
1228 		hostctrl2 |= SDHCI_CTRL2_UHS_SDR50;
1229 	else if (ios->clock > SD_SDR12_MAX) {
1230 		if (ios->timing == bus_timing_uhs_ddr50 ||
1231 		    ios->timing == bus_timing_mmc_ddr52)
1232 			hostctrl2 |= SDHCI_CTRL2_UHS_DDR50;
1233 		else
1234 			hostctrl2 |= SDHCI_CTRL2_UHS_SDR25;
1235 	} else if (ios->clock > SD_MMC_CARD_ID_FREQUENCY)
1236 		hostctrl2 |= SDHCI_CTRL2_UHS_SDR12;
1237 	WR2(slot, SDHCI_HOST_CONTROL2, hostctrl2);
1238 	sdhci_set_clock(slot, ios->clock);
1239 }
1240 
1241 int
1242 sdhci_generic_update_ios(device_t brdev, device_t reqdev)
1243 {
1244 	struct sdhci_slot *slot = device_get_ivars(reqdev);
1245 	struct mmc_ios *ios = &slot->host.ios;
1246 
1247 	SDHCI_LOCK(slot);
1248 	/* Do full reset on bus power down to clear from any state. */
1249 	if (ios->power_mode == power_off) {
1250 		WR4(slot, SDHCI_SIGNAL_ENABLE, 0);
1251 		sdhci_init(slot);
1252 	}
1253 	/* Configure the bus. */
1254 	sdhci_set_clock(slot, ios->clock);
1255 	sdhci_set_power(slot, (ios->power_mode == power_off) ? 0 : ios->vdd);
1256 	if (ios->bus_width == bus_width_8) {
1257 		slot->hostctrl |= SDHCI_CTRL_8BITBUS;
1258 		slot->hostctrl &= ~SDHCI_CTRL_4BITBUS;
1259 	} else if (ios->bus_width == bus_width_4) {
1260 		slot->hostctrl &= ~SDHCI_CTRL_8BITBUS;
1261 		slot->hostctrl |= SDHCI_CTRL_4BITBUS;
1262 	} else if (ios->bus_width == bus_width_1) {
1263 		slot->hostctrl &= ~SDHCI_CTRL_8BITBUS;
1264 		slot->hostctrl &= ~SDHCI_CTRL_4BITBUS;
1265 	} else {
1266 		panic("Invalid bus width: %d", ios->bus_width);
1267 	}
1268 	if (ios->clock > SD_SDR12_MAX &&
1269 	    !(slot->quirks & SDHCI_QUIRK_DONT_SET_HISPD_BIT))
1270 		slot->hostctrl |= SDHCI_CTRL_HISPD;
1271 	else
1272 		slot->hostctrl &= ~SDHCI_CTRL_HISPD;
1273 	WR1(slot, SDHCI_HOST_CONTROL, slot->hostctrl);
1274 	SDHCI_SET_UHS_TIMING(brdev, slot);
1275 	/* Some controllers like reset after bus changes. */
1276 	if (slot->quirks & SDHCI_QUIRK_RESET_ON_IOS)
1277 		sdhci_reset(slot, SDHCI_RESET_CMD | SDHCI_RESET_DATA);
1278 
1279 	SDHCI_UNLOCK(slot);
1280 	return (0);
1281 }
1282 
1283 int
1284 sdhci_generic_switch_vccq(device_t brdev __unused, device_t reqdev)
1285 {
1286 	struct sdhci_slot *slot = device_get_ivars(reqdev);
1287 	enum mmc_vccq vccq;
1288 	int err;
1289 	uint16_t hostctrl2;
1290 
1291 	if (slot->version < SDHCI_SPEC_300)
1292 		return (0);
1293 
1294 	err = 0;
1295 	vccq = slot->host.ios.vccq;
1296 	SDHCI_LOCK(slot);
1297 	sdhci_set_clock(slot, 0);
1298 	hostctrl2 = RD2(slot, SDHCI_HOST_CONTROL2);
1299 	switch (vccq) {
1300 	case vccq_330:
1301 		if (!(hostctrl2 & SDHCI_CTRL2_S18_ENABLE))
1302 			goto done;
1303 		hostctrl2 &= ~SDHCI_CTRL2_S18_ENABLE;
1304 		WR2(slot, SDHCI_HOST_CONTROL2, hostctrl2);
1305 		DELAY(5000);
1306 		hostctrl2 = RD2(slot, SDHCI_HOST_CONTROL2);
1307 		if (!(hostctrl2 & SDHCI_CTRL2_S18_ENABLE))
1308 			goto done;
1309 		err = EAGAIN;
1310 		break;
1311 	case vccq_180:
1312 		if (!(slot->host.caps & MMC_CAP_SIGNALING_180)) {
1313 			err = EINVAL;
1314 			goto done;
1315 		}
1316 		if (hostctrl2 & SDHCI_CTRL2_S18_ENABLE)
1317 			goto done;
1318 		hostctrl2 |= SDHCI_CTRL2_S18_ENABLE;
1319 		WR2(slot, SDHCI_HOST_CONTROL2, hostctrl2);
1320 		DELAY(5000);
1321 		hostctrl2 = RD2(slot, SDHCI_HOST_CONTROL2);
1322 		if (hostctrl2 & SDHCI_CTRL2_S18_ENABLE)
1323 			goto done;
1324 		err = EAGAIN;
1325 		break;
1326 	default:
1327 		slot_printf(slot,
1328 		    "Attempt to set unsupported signaling voltage\n");
1329 		err = EINVAL;
1330 		break;
1331 	}
1332 done:
1333 	sdhci_set_clock(slot, slot->host.ios.clock);
1334 	SDHCI_UNLOCK(slot);
1335 	return (err);
1336 }
1337 
1338 int
1339 sdhci_generic_tune(device_t brdev __unused, device_t reqdev, bool hs400)
1340 {
1341 	struct sdhci_slot *slot = device_get_ivars(reqdev);
1342 	const struct mmc_ios *ios = &slot->host.ios;
1343 	struct mmc_command *tune_cmd;
1344 	struct mmc_data *tune_data;
1345 	uint32_t opcode;
1346 	int err;
1347 
1348 	if (!(slot->opt & SDHCI_TUNING_SUPPORTED))
1349 		return (0);
1350 
1351 	slot->retune_ticks = slot->retune_count * hz;
1352 	opcode = MMC_SEND_TUNING_BLOCK;
1353 	SDHCI_LOCK(slot);
1354 	switch (ios->timing) {
1355 	case bus_timing_mmc_hs400:
1356 		slot_printf(slot, "HS400 must be tuned in HS200 mode\n");
1357 		SDHCI_UNLOCK(slot);
1358 		return (EINVAL);
1359 	case bus_timing_mmc_hs200:
1360 		/*
1361 		 * In HS400 mode, controllers use the data strobe line to
1362 		 * latch data from the devices so periodic re-tuning isn't
1363 		 * expected to be required.
1364 		 */
1365 		if (hs400)
1366 			slot->retune_ticks = 0;
1367 		opcode = MMC_SEND_TUNING_BLOCK_HS200;
1368 		break;
1369 	case bus_timing_uhs_ddr50:
1370 	case bus_timing_uhs_sdr104:
1371 		break;
1372 	case bus_timing_uhs_sdr50:
1373 		if (slot->opt & SDHCI_SDR50_NEEDS_TUNING)
1374 			break;
1375 		/* FALLTHROUGH */
1376 	default:
1377 		SDHCI_UNLOCK(slot);
1378 		return (0);
1379 	}
1380 
1381 	tune_cmd = slot->tune_cmd;
1382 	memset(tune_cmd, 0, sizeof(*tune_cmd));
1383 	tune_cmd->opcode = opcode;
1384 	tune_cmd->flags = MMC_RSP_R1 | MMC_CMD_ADTC;
1385 	tune_data = tune_cmd->data = slot->tune_data;
1386 	memset(tune_data, 0, sizeof(*tune_data));
1387 	tune_data->len = (opcode == MMC_SEND_TUNING_BLOCK_HS200 &&
1388 	    ios->bus_width == bus_width_8) ? MMC_TUNING_LEN_HS200 :
1389 	    MMC_TUNING_LEN;
1390 	tune_data->flags = MMC_DATA_READ;
1391 	tune_data->mrq = tune_cmd->mrq = slot->tune_req;
1392 
1393 	slot->opt &= ~SDHCI_TUNING_ENABLED;
1394 	err = sdhci_exec_tuning(slot, true);
1395 	if (err == 0) {
1396 		slot->opt |= SDHCI_TUNING_ENABLED;
1397 		slot->intmask |= sdhci_tuning_intmask(slot);
1398 		WR4(slot, SDHCI_INT_ENABLE, slot->intmask);
1399 		WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask);
1400 		if (slot->retune_ticks) {
1401 			callout_reset(&slot->retune_callout, slot->retune_ticks,
1402 			    sdhci_retune, slot);
1403 		}
1404 	}
1405 	SDHCI_UNLOCK(slot);
1406 	return (err);
1407 }
1408 
1409 int
1410 sdhci_generic_retune(device_t brdev __unused, device_t reqdev, bool reset)
1411 {
1412 	struct sdhci_slot *slot = device_get_ivars(reqdev);
1413 	int err;
1414 
1415 	if (!(slot->opt & SDHCI_TUNING_ENABLED))
1416 		return (0);
1417 
1418 	/* HS400 must be tuned in HS200 mode. */
1419 	if (slot->host.ios.timing == bus_timing_mmc_hs400)
1420 		return (EINVAL);
1421 
1422 	SDHCI_LOCK(slot);
1423 	err = sdhci_exec_tuning(slot, reset);
1424 	/*
1425 	 * There are two ways sdhci_exec_tuning() can fail:
1426 	 * EBUSY should not actually happen when requests are only issued
1427 	 *	 with the host properly acquired, and
1428 	 * EIO   re-tuning failed (but it did work initially).
1429 	 *
1430 	 * In both cases, we should retry at later point if periodic re-tuning
1431 	 * is enabled.  Note that due to slot->retune_req not being cleared in
1432 	 * these failure cases, the MMC layer should trigger another attempt at
1433 	 * re-tuning with the next request anyway, though.
1434 	 */
1435 	if (slot->retune_ticks) {
1436 		callout_reset(&slot->retune_callout, slot->retune_ticks,
1437 		    sdhci_retune, slot);
1438 	}
1439 	SDHCI_UNLOCK(slot);
1440 	return (err);
1441 }
1442 
1443 static int
1444 sdhci_exec_tuning(struct sdhci_slot *slot, bool reset)
1445 {
1446 	struct mmc_request *tune_req;
1447 	struct mmc_command *tune_cmd;
1448 	int i;
1449 	uint32_t intmask;
1450 	uint16_t hostctrl2;
1451 	u_char opt;
1452 
1453 	SDHCI_ASSERT_LOCKED(slot);
1454 	if (slot->req != NULL)
1455 		return (EBUSY);
1456 
1457 	/* Tuning doesn't work with DMA enabled. */
1458 	opt = slot->opt;
1459 	slot->opt = opt & ~SDHCI_HAVE_DMA;
1460 
1461 	/*
1462 	 * Ensure that as documented, SDHCI_INT_DATA_AVAIL is the only
1463 	 * kind of interrupt we receive in response to a tuning request.
1464 	 */
1465 	intmask = slot->intmask;
1466 	slot->intmask = SDHCI_INT_DATA_AVAIL;
1467 	WR4(slot, SDHCI_INT_ENABLE, SDHCI_INT_DATA_AVAIL);
1468 	WR4(slot, SDHCI_SIGNAL_ENABLE, SDHCI_INT_DATA_AVAIL);
1469 
1470 	hostctrl2 = RD2(slot, SDHCI_HOST_CONTROL2);
1471 	if (reset)
1472 		hostctrl2 &= ~SDHCI_CTRL2_SAMPLING_CLOCK;
1473 	else
1474 		hostctrl2 |= SDHCI_CTRL2_SAMPLING_CLOCK;
1475 	WR2(slot, SDHCI_HOST_CONTROL2, hostctrl2 | SDHCI_CTRL2_EXEC_TUNING);
1476 
1477 	tune_req = slot->tune_req;
1478 	tune_cmd = slot->tune_cmd;
1479 	for (i = 0; i < MMC_TUNING_MAX; i++) {
1480 		memset(tune_req, 0, sizeof(*tune_req));
1481 		tune_req->cmd = tune_cmd;
1482 		tune_req->done = sdhci_req_wakeup;
1483 		tune_req->done_data = slot;
1484 		slot->req = tune_req;
1485 		slot->flags = 0;
1486 		sdhci_start(slot);
1487 		while (!(tune_req->flags & MMC_REQ_DONE))
1488 			msleep(tune_req, &slot->mtx, 0, "sdhciet", 0);
1489 		if (!(tune_req->flags & MMC_TUNE_DONE))
1490 			break;
1491 		hostctrl2 = RD2(slot, SDHCI_HOST_CONTROL2);
1492 		if (!(hostctrl2 & SDHCI_CTRL2_EXEC_TUNING))
1493 			break;
1494 		if (tune_cmd->opcode == MMC_SEND_TUNING_BLOCK)
1495 			DELAY(1000);
1496 	}
1497 
1498 	/*
1499 	 * Restore DMA usage and interrupts.
1500 	 * Note that the interrupt aggregation code might have cleared
1501 	 * SDHCI_INT_DMA_END and/or SDHCI_INT_RESPONSE in slot->intmask
1502 	 * and SDHCI_SIGNAL_ENABLE respectively so ensure SDHCI_INT_ENABLE
1503 	 * doesn't lose these.
1504 	 */
1505 	slot->opt = opt;
1506 	slot->intmask = intmask;
1507 	WR4(slot, SDHCI_INT_ENABLE, intmask | SDHCI_INT_DMA_END |
1508 	    SDHCI_INT_RESPONSE);
1509 	WR4(slot, SDHCI_SIGNAL_ENABLE, intmask);
1510 
1511 	if ((hostctrl2 & (SDHCI_CTRL2_EXEC_TUNING |
1512 	    SDHCI_CTRL2_SAMPLING_CLOCK)) == SDHCI_CTRL2_SAMPLING_CLOCK) {
1513 		slot->retune_req = 0;
1514 		return (0);
1515 	}
1516 
1517 	slot_printf(slot, "Tuning failed, using fixed sampling clock\n");
1518 	WR2(slot, SDHCI_HOST_CONTROL2, hostctrl2 & ~(SDHCI_CTRL2_EXEC_TUNING |
1519 	    SDHCI_CTRL2_SAMPLING_CLOCK));
1520 	sdhci_reset(slot, SDHCI_RESET_CMD | SDHCI_RESET_DATA);
1521 	return (EIO);
1522 }
1523 
1524 static void
1525 sdhci_retune(void *arg)
1526 {
1527 	struct sdhci_slot *slot = arg;
1528 
1529 	slot->retune_req |= SDHCI_RETUNE_REQ_NEEDED;
1530 }
1531 
1532 #ifdef MMCCAM
1533 static void
1534 sdhci_req_done(struct sdhci_slot *slot)
1535 {
1536 	union ccb *ccb;
1537 
1538 	if (__predict_false(sdhci_debug > 1))
1539 		slot_printf(slot, "%s\n", __func__);
1540 	if (slot->ccb != NULL && slot->curcmd != NULL) {
1541 		callout_stop(&slot->timeout_callout);
1542 		ccb = slot->ccb;
1543 		slot->ccb = NULL;
1544 		slot->curcmd = NULL;
1545 
1546 		/* Tell CAM the request is finished */
1547 		struct ccb_mmcio *mmcio;
1548 		mmcio = &ccb->mmcio;
1549 
1550 		ccb->ccb_h.status =
1551 		    (mmcio->cmd.error == 0 ? CAM_REQ_CMP : CAM_REQ_CMP_ERR);
1552 		xpt_done(ccb);
1553 	}
1554 }
1555 #else
1556 static void
1557 sdhci_req_done(struct sdhci_slot *slot)
1558 {
1559 	struct mmc_request *req;
1560 
1561 	if (slot->req != NULL && slot->curcmd != NULL) {
1562 		callout_stop(&slot->timeout_callout);
1563 		req = slot->req;
1564 		slot->req = NULL;
1565 		slot->curcmd = NULL;
1566 		req->done(req);
1567 	}
1568 }
1569 #endif
1570 
1571 static void
1572 sdhci_req_wakeup(struct mmc_request *req)
1573 {
1574 	struct sdhci_slot *slot;
1575 
1576 	slot = req->done_data;
1577 	req->flags |= MMC_REQ_DONE;
1578 	wakeup(req);
1579 }
1580 
1581 static void
1582 sdhci_timeout(void *arg)
1583 {
1584 	struct sdhci_slot *slot = arg;
1585 
1586 	if (slot->curcmd != NULL) {
1587 		slot_printf(slot, "Controller timeout\n");
1588 		sdhci_dumpregs(slot);
1589 		sdhci_reset(slot, SDHCI_RESET_CMD | SDHCI_RESET_DATA);
1590 		slot->curcmd->error = MMC_ERR_TIMEOUT;
1591 		sdhci_req_done(slot);
1592 	} else {
1593 		slot_printf(slot, "Spurious timeout - no active command\n");
1594 	}
1595 }
1596 
1597 static void
1598 sdhci_set_transfer_mode(struct sdhci_slot *slot, const struct mmc_data *data)
1599 {
1600 	uint16_t mode;
1601 
1602 	if (data == NULL)
1603 		return;
1604 
1605 	mode = SDHCI_TRNS_BLK_CNT_EN;
1606 	if (data->len > 512 || data->block_count > 1) {
1607 		mode |= SDHCI_TRNS_MULTI;
1608 		if (data->block_count == 0 && __predict_true(
1609 #ifdef MMCCAM
1610 		    slot->ccb->mmcio.stop.opcode == MMC_STOP_TRANSMISSION &&
1611 #else
1612 		    slot->req->stop != NULL &&
1613 #endif
1614 		    !(slot->quirks & SDHCI_QUIRK_BROKEN_AUTO_STOP)))
1615 			mode |= SDHCI_TRNS_ACMD12;
1616 	}
1617 	if (data->flags & MMC_DATA_READ)
1618 		mode |= SDHCI_TRNS_READ;
1619 	if (slot->flags & SDHCI_USE_DMA)
1620 		mode |= SDHCI_TRNS_DMA;
1621 
1622 	WR2(slot, SDHCI_TRANSFER_MODE, mode);
1623 }
1624 
1625 static void
1626 sdhci_start_command(struct sdhci_slot *slot, struct mmc_command *cmd)
1627 {
1628 	int flags, timeout;
1629 	uint32_t mask;
1630 
1631 	slot->curcmd = cmd;
1632 	slot->cmd_done = 0;
1633 
1634 	cmd->error = MMC_ERR_NONE;
1635 
1636 	/* This flags combination is not supported by controller. */
1637 	if ((cmd->flags & MMC_RSP_136) && (cmd->flags & MMC_RSP_BUSY)) {
1638 		slot_printf(slot, "Unsupported response type!\n");
1639 		cmd->error = MMC_ERR_FAILED;
1640 		sdhci_req_done(slot);
1641 		return;
1642 	}
1643 
1644 	/*
1645 	 * Do not issue command if there is no card, clock or power.
1646 	 * Controller will not detect timeout without clock active.
1647 	 */
1648 	if (!SDHCI_GET_CARD_PRESENT(slot->bus, slot) ||
1649 	    slot->power == 0 ||
1650 	    slot->clock == 0) {
1651 		slot_printf(slot,
1652 			    "Cannot issue a command (power=%d clock=%d)",
1653 			    slot->power, slot->clock);
1654 		cmd->error = MMC_ERR_FAILED;
1655 		sdhci_req_done(slot);
1656 		return;
1657 	}
1658 	/* Always wait for free CMD bus. */
1659 	mask = SDHCI_CMD_INHIBIT;
1660 	/* Wait for free DAT if we have data or busy signal. */
1661 	if (cmd->data != NULL || (cmd->flags & MMC_RSP_BUSY))
1662 		mask |= SDHCI_DAT_INHIBIT;
1663 	/*
1664 	 * We shouldn't wait for DAT for stop commands or CMD19/CMD21.  Note
1665 	 * that these latter are also special in that SDHCI_CMD_DATA should
1666 	 * be set below but no actual data is ever read from the controller.
1667 	*/
1668 #ifdef MMCCAM
1669 	if (cmd == &slot->ccb->mmcio.stop ||
1670 #else
1671 	if (cmd == slot->req->stop ||
1672 #endif
1673 	    __predict_false(cmd->opcode == MMC_SEND_TUNING_BLOCK ||
1674 	    cmd->opcode == MMC_SEND_TUNING_BLOCK_HS200))
1675 		mask &= ~SDHCI_DAT_INHIBIT;
1676 	/*
1677 	 *  Wait for bus no more then 250 ms.  Typically there will be no wait
1678 	 *  here at all, but when writing a crash dump we may be bypassing the
1679 	 *  host platform's interrupt handler, and in some cases that handler
1680 	 *  may be working around hardware quirks such as not respecting r1b
1681 	 *  busy indications.  In those cases, this wait-loop serves the purpose
1682 	 *  of waiting for the prior command and data transfers to be done, and
1683 	 *  SD cards are allowed to take up to 250ms for write and erase ops.
1684 	 *  (It's usually more like 20-30ms in the real world.)
1685 	 */
1686 	timeout = 250;
1687 	while (mask & RD4(slot, SDHCI_PRESENT_STATE)) {
1688 		if (timeout == 0) {
1689 			slot_printf(slot, "Controller never released "
1690 			    "inhibit bit(s).\n");
1691 			sdhci_dumpregs(slot);
1692 			cmd->error = MMC_ERR_FAILED;
1693 			sdhci_req_done(slot);
1694 			return;
1695 		}
1696 		timeout--;
1697 		DELAY(1000);
1698 	}
1699 
1700 	/* Prepare command flags. */
1701 	if (!(cmd->flags & MMC_RSP_PRESENT))
1702 		flags = SDHCI_CMD_RESP_NONE;
1703 	else if (cmd->flags & MMC_RSP_136)
1704 		flags = SDHCI_CMD_RESP_LONG;
1705 	else if (cmd->flags & MMC_RSP_BUSY)
1706 		flags = SDHCI_CMD_RESP_SHORT_BUSY;
1707 	else
1708 		flags = SDHCI_CMD_RESP_SHORT;
1709 	if (cmd->flags & MMC_RSP_CRC)
1710 		flags |= SDHCI_CMD_CRC;
1711 	if (cmd->flags & MMC_RSP_OPCODE)
1712 		flags |= SDHCI_CMD_INDEX;
1713 	if (cmd->data != NULL)
1714 		flags |= SDHCI_CMD_DATA;
1715 	if (cmd->opcode == MMC_STOP_TRANSMISSION)
1716 		flags |= SDHCI_CMD_TYPE_ABORT;
1717 	/* Prepare data. */
1718 	sdhci_start_data(slot, cmd->data);
1719 	/*
1720 	 * Interrupt aggregation: To reduce total number of interrupts
1721 	 * group response interrupt with data interrupt when possible.
1722 	 * If there going to be data interrupt, mask response one.
1723 	 */
1724 	if (slot->data_done == 0) {
1725 		WR4(slot, SDHCI_SIGNAL_ENABLE,
1726 		    slot->intmask &= ~SDHCI_INT_RESPONSE);
1727 	}
1728 	/* Set command argument. */
1729 	WR4(slot, SDHCI_ARGUMENT, cmd->arg);
1730 	/* Set data transfer mode. */
1731 	sdhci_set_transfer_mode(slot, cmd->data);
1732 	if (__predict_false(sdhci_debug > 1))
1733 		slot_printf(slot, "Starting command opcode %#04x flags %#04x\n",
1734 		    cmd->opcode, flags);
1735 
1736 	/* Start command. */
1737 	WR2(slot, SDHCI_COMMAND_FLAGS, (cmd->opcode << 8) | (flags & 0xff));
1738 	/* Start timeout callout. */
1739 	callout_reset(&slot->timeout_callout, slot->timeout * hz,
1740 	    sdhci_timeout, slot);
1741 }
1742 
1743 static void
1744 sdhci_finish_command(struct sdhci_slot *slot)
1745 {
1746 	int i;
1747 	uint32_t val;
1748 	uint8_t extra;
1749 
1750 	if (__predict_false(sdhci_debug > 1))
1751 		slot_printf(slot, "%s: called, err %d flags %#04x\n",
1752 		    __func__, slot->curcmd->error, slot->curcmd->flags);
1753 	slot->cmd_done = 1;
1754 	/*
1755 	 * Interrupt aggregation: Restore command interrupt.
1756 	 * Main restore point for the case when command interrupt
1757 	 * happened first.
1758 	 */
1759 	if (__predict_true(slot->curcmd->opcode != MMC_SEND_TUNING_BLOCK &&
1760 	    slot->curcmd->opcode != MMC_SEND_TUNING_BLOCK_HS200))
1761 		WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask |=
1762 		    SDHCI_INT_RESPONSE);
1763 	/* In case of error - reset host and return. */
1764 	if (slot->curcmd->error) {
1765 		if (slot->curcmd->error == MMC_ERR_BADCRC)
1766 			slot->retune_req |= SDHCI_RETUNE_REQ_RESET;
1767 		sdhci_reset(slot, SDHCI_RESET_CMD);
1768 		sdhci_reset(slot, SDHCI_RESET_DATA);
1769 		sdhci_start(slot);
1770 		return;
1771 	}
1772 	/* If command has response - fetch it. */
1773 	if (slot->curcmd->flags & MMC_RSP_PRESENT) {
1774 		if (slot->curcmd->flags & MMC_RSP_136) {
1775 			/* CRC is stripped so we need one byte shift. */
1776 			extra = 0;
1777 			for (i = 0; i < 4; i++) {
1778 				val = RD4(slot, SDHCI_RESPONSE + i * 4);
1779 				if (slot->quirks &
1780 				    SDHCI_QUIRK_DONT_SHIFT_RESPONSE)
1781 					slot->curcmd->resp[3 - i] = val;
1782 				else {
1783 					slot->curcmd->resp[3 - i] =
1784 					    (val << 8) | extra;
1785 					extra = val >> 24;
1786 				}
1787 			}
1788 		} else
1789 			slot->curcmd->resp[0] = RD4(slot, SDHCI_RESPONSE);
1790 	}
1791 	if (__predict_false(sdhci_debug > 1))
1792 		slot_printf(slot, "Resp: %#04x %#04x %#04x %#04x\n",
1793 		    slot->curcmd->resp[0], slot->curcmd->resp[1],
1794 		    slot->curcmd->resp[2], slot->curcmd->resp[3]);
1795 
1796 	/* If data ready - finish. */
1797 	if (slot->data_done)
1798 		sdhci_start(slot);
1799 }
1800 
1801 static void
1802 sdhci_start_data(struct sdhci_slot *slot, const struct mmc_data *data)
1803 {
1804 	uint32_t blkcnt, blksz, current_timeout, sdma_bbufsz, target_timeout;
1805 	uint8_t div;
1806 
1807 	if (data == NULL && (slot->curcmd->flags & MMC_RSP_BUSY) == 0) {
1808 		slot->data_done = 1;
1809 		return;
1810 	}
1811 
1812 	slot->data_done = 0;
1813 
1814 	/* Calculate and set data timeout.*/
1815 	/* XXX: We should have this from mmc layer, now assume 1 sec. */
1816 	if (slot->quirks & SDHCI_QUIRK_BROKEN_TIMEOUT_VAL) {
1817 		div = 0xE;
1818 	} else {
1819 		target_timeout = 1000000;
1820 		div = 0;
1821 		current_timeout = (1 << 13) * 1000 / slot->timeout_clk;
1822 		while (current_timeout < target_timeout && div < 0xE) {
1823 			++div;
1824 			current_timeout <<= 1;
1825 		}
1826 		/* Compensate for an off-by-one error in the CaFe chip.*/
1827 		if (div < 0xE &&
1828 		    (slot->quirks & SDHCI_QUIRK_INCR_TIMEOUT_CONTROL)) {
1829 			++div;
1830 		}
1831 	}
1832 	WR1(slot, SDHCI_TIMEOUT_CONTROL, div);
1833 
1834 	if (data == NULL)
1835 		return;
1836 
1837 	/* Use DMA if possible. */
1838 	if ((slot->opt & SDHCI_HAVE_DMA))
1839 		slot->flags |= SDHCI_USE_DMA;
1840 	/* If data is small, broken DMA may return zeroes instead of data. */
1841 	if ((slot->quirks & SDHCI_QUIRK_BROKEN_TIMINGS) &&
1842 	    (data->len <= 512))
1843 		slot->flags &= ~SDHCI_USE_DMA;
1844 	/* Some controllers require even block sizes. */
1845 	if ((slot->quirks & SDHCI_QUIRK_32BIT_DMA_SIZE) &&
1846 	    ((data->len) & 0x3))
1847 		slot->flags &= ~SDHCI_USE_DMA;
1848 	/* Load DMA buffer. */
1849 	if (slot->flags & SDHCI_USE_DMA) {
1850 		sdma_bbufsz = slot->sdma_bbufsz;
1851 		if (data->flags & MMC_DATA_READ)
1852 			bus_dmamap_sync(slot->dmatag, slot->dmamap,
1853 			    BUS_DMASYNC_PREREAD);
1854 		else {
1855 			memcpy(slot->dmamem, data->data, ulmin(data->len,
1856 			    sdma_bbufsz));
1857 			bus_dmamap_sync(slot->dmatag, slot->dmamap,
1858 			    BUS_DMASYNC_PREWRITE);
1859 		}
1860 		WR4(slot, SDHCI_DMA_ADDRESS, slot->paddr);
1861 		/*
1862 		 * Interrupt aggregation: Mask border interrupt for the last
1863 		 * bounce buffer and unmask otherwise.
1864 		 */
1865 		if (data->len == sdma_bbufsz)
1866 			slot->intmask &= ~SDHCI_INT_DMA_END;
1867 		else
1868 			slot->intmask |= SDHCI_INT_DMA_END;
1869 		WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask);
1870 	}
1871 	/* Current data offset for both PIO and DMA. */
1872 	slot->offset = 0;
1873 #ifdef MMCCAM
1874 	if (data->flags & MMC_DATA_BLOCK_SIZE) {
1875 		/* Set block size and request border interrupts on the SDMA boundary. */
1876 		blksz = SDHCI_MAKE_BLKSZ(slot->sdma_boundary, data->block_size);
1877 		blkcnt = data->block_count;
1878 		if (__predict_false(sdhci_debug > 0))
1879 			slot_printf(slot, "SDIO Custom block params: blksz: "
1880 			    "%#10x, blk cnt: %#10x\n", blksz, blkcnt);
1881 	} else
1882 #endif
1883 	{
1884 		/* Set block size and request border interrupts on the SDMA boundary. */
1885 		blksz = SDHCI_MAKE_BLKSZ(slot->sdma_boundary, ulmin(data->len, 512));
1886 		blkcnt = howmany(data->len, 512);
1887 	}
1888 
1889 	WR2(slot, SDHCI_BLOCK_SIZE, blksz);
1890 	WR2(slot, SDHCI_BLOCK_COUNT, blkcnt);
1891 	if (__predict_false(sdhci_debug > 1))
1892 		slot_printf(slot, "Blk size: 0x%08x | Blk cnt:  0x%08x\n",
1893 		    blksz, blkcnt);
1894 }
1895 
1896 void
1897 sdhci_finish_data(struct sdhci_slot *slot)
1898 {
1899 	struct mmc_data *data = slot->curcmd->data;
1900 	size_t left;
1901 
1902 	/* Interrupt aggregation: Restore command interrupt.
1903 	 * Auxiliary restore point for the case when data interrupt
1904 	 * happened first. */
1905 	if (!slot->cmd_done) {
1906 		WR4(slot, SDHCI_SIGNAL_ENABLE,
1907 		    slot->intmask |= SDHCI_INT_RESPONSE);
1908 	}
1909 	/* Unload rest of data from DMA buffer. */
1910 	if (!slot->data_done && (slot->flags & SDHCI_USE_DMA) &&
1911 	    slot->curcmd->data != NULL) {
1912 		if (data->flags & MMC_DATA_READ) {
1913 			left = data->len - slot->offset;
1914 			bus_dmamap_sync(slot->dmatag, slot->dmamap,
1915 			    BUS_DMASYNC_POSTREAD);
1916 			memcpy((u_char*)data->data + slot->offset, slot->dmamem,
1917 			    ulmin(left, slot->sdma_bbufsz));
1918 		} else
1919 			bus_dmamap_sync(slot->dmatag, slot->dmamap,
1920 			    BUS_DMASYNC_POSTWRITE);
1921 	}
1922 	slot->data_done = 1;
1923 	/* If there was error - reset the host. */
1924 	if (slot->curcmd->error) {
1925 		if (slot->curcmd->error == MMC_ERR_BADCRC)
1926 			slot->retune_req |= SDHCI_RETUNE_REQ_RESET;
1927 		sdhci_reset(slot, SDHCI_RESET_CMD);
1928 		sdhci_reset(slot, SDHCI_RESET_DATA);
1929 		sdhci_start(slot);
1930 		return;
1931 	}
1932 	/* If we already have command response - finish. */
1933 	if (slot->cmd_done)
1934 		sdhci_start(slot);
1935 }
1936 
1937 #ifdef MMCCAM
1938 static void
1939 sdhci_start(struct sdhci_slot *slot)
1940 {
1941 	union ccb *ccb;
1942 	struct ccb_mmcio *mmcio;
1943 
1944 	ccb = slot->ccb;
1945 	if (ccb == NULL)
1946 		return;
1947 
1948 	mmcio = &ccb->mmcio;
1949 	if (!(slot->flags & CMD_STARTED)) {
1950 		slot->flags |= CMD_STARTED;
1951 		sdhci_start_command(slot, &mmcio->cmd);
1952 		return;
1953 	}
1954 
1955 	/*
1956 	 * Old stack doesn't use this!
1957 	 * Enabling this code causes significant performance degradation
1958 	 * and IRQ storms on BBB, Wandboard behaves fine.
1959 	 * Not using this code does no harm...
1960 	if (!(slot->flags & STOP_STARTED) && mmcio->stop.opcode != 0) {
1961 		slot->flags |= STOP_STARTED;
1962 		sdhci_start_command(slot, &mmcio->stop);
1963 		return;
1964 	}
1965 	*/
1966 	if (__predict_false(sdhci_debug > 1))
1967 		slot_printf(slot, "result: %d\n", mmcio->cmd.error);
1968 	if (mmcio->cmd.error == 0 &&
1969 	    (slot->quirks & SDHCI_QUIRK_RESET_AFTER_REQUEST)) {
1970 		sdhci_reset(slot, SDHCI_RESET_CMD);
1971 		sdhci_reset(slot, SDHCI_RESET_DATA);
1972 	}
1973 
1974 	sdhci_req_done(slot);
1975 }
1976 #else
1977 static void
1978 sdhci_start(struct sdhci_slot *slot)
1979 {
1980 	const struct mmc_request *req;
1981 
1982 	req = slot->req;
1983 	if (req == NULL)
1984 		return;
1985 
1986 	if (!(slot->flags & CMD_STARTED)) {
1987 		slot->flags |= CMD_STARTED;
1988 		sdhci_start_command(slot, req->cmd);
1989 		return;
1990 	}
1991 	if ((slot->quirks & SDHCI_QUIRK_BROKEN_AUTO_STOP) &&
1992 	    !(slot->flags & STOP_STARTED) && req->stop) {
1993 		slot->flags |= STOP_STARTED;
1994 		sdhci_start_command(slot, req->stop);
1995 		return;
1996 	}
1997 	if (__predict_false(sdhci_debug > 1))
1998 		slot_printf(slot, "result: %d\n", req->cmd->error);
1999 	if (!req->cmd->error &&
2000 	    ((slot->curcmd == req->stop &&
2001 	     (slot->quirks & SDHCI_QUIRK_BROKEN_AUTO_STOP)) ||
2002 	     (slot->quirks & SDHCI_QUIRK_RESET_AFTER_REQUEST))) {
2003 		sdhci_reset(slot, SDHCI_RESET_CMD);
2004 		sdhci_reset(slot, SDHCI_RESET_DATA);
2005 	}
2006 
2007 	sdhci_req_done(slot);
2008 }
2009 #endif
2010 
2011 int
2012 sdhci_generic_request(device_t brdev __unused, device_t reqdev,
2013     struct mmc_request *req)
2014 {
2015 	struct sdhci_slot *slot = device_get_ivars(reqdev);
2016 
2017 	SDHCI_LOCK(slot);
2018 	if (slot->req != NULL) {
2019 		SDHCI_UNLOCK(slot);
2020 		return (EBUSY);
2021 	}
2022 	if (__predict_false(sdhci_debug > 1)) {
2023 		slot_printf(slot,
2024 		    "CMD%u arg %#x flags %#x dlen %u dflags %#x\n",
2025 		    req->cmd->opcode, req->cmd->arg, req->cmd->flags,
2026 		    (req->cmd->data)?(u_int)req->cmd->data->len:0,
2027 		    (req->cmd->data)?req->cmd->data->flags:0);
2028 	}
2029 	slot->req = req;
2030 	slot->flags = 0;
2031 	sdhci_start(slot);
2032 	SDHCI_UNLOCK(slot);
2033 	if (dumping) {
2034 		while (slot->req != NULL) {
2035 			sdhci_generic_intr(slot);
2036 			DELAY(10);
2037 		}
2038 	}
2039 	return (0);
2040 }
2041 
2042 int
2043 sdhci_generic_get_ro(device_t brdev __unused, device_t reqdev)
2044 {
2045 	struct sdhci_slot *slot = device_get_ivars(reqdev);
2046 	uint32_t val;
2047 
2048 	SDHCI_LOCK(slot);
2049 	val = RD4(slot, SDHCI_PRESENT_STATE);
2050 	SDHCI_UNLOCK(slot);
2051 	return (!(val & SDHCI_WRITE_PROTECT));
2052 }
2053 
2054 int
2055 sdhci_generic_acquire_host(device_t brdev __unused, device_t reqdev)
2056 {
2057 	struct sdhci_slot *slot = device_get_ivars(reqdev);
2058 	int err = 0;
2059 
2060 	SDHCI_LOCK(slot);
2061 	while (slot->bus_busy)
2062 		msleep(slot, &slot->mtx, 0, "sdhciah", 0);
2063 	slot->bus_busy++;
2064 	/* Activate led. */
2065 	WR1(slot, SDHCI_HOST_CONTROL, slot->hostctrl |= SDHCI_CTRL_LED);
2066 	SDHCI_UNLOCK(slot);
2067 	return (err);
2068 }
2069 
2070 int
2071 sdhci_generic_release_host(device_t brdev __unused, device_t reqdev)
2072 {
2073 	struct sdhci_slot *slot = device_get_ivars(reqdev);
2074 
2075 	SDHCI_LOCK(slot);
2076 	/* Deactivate led. */
2077 	WR1(slot, SDHCI_HOST_CONTROL, slot->hostctrl &= ~SDHCI_CTRL_LED);
2078 	slot->bus_busy--;
2079 	SDHCI_UNLOCK(slot);
2080 	wakeup(slot);
2081 	return (0);
2082 }
2083 
2084 static void
2085 sdhci_cmd_irq(struct sdhci_slot *slot, uint32_t intmask)
2086 {
2087 
2088 	if (!slot->curcmd) {
2089 		slot_printf(slot, "Got command interrupt 0x%08x, but "
2090 		    "there is no active command.\n", intmask);
2091 		sdhci_dumpregs(slot);
2092 		return;
2093 	}
2094 	if (intmask & SDHCI_INT_TIMEOUT)
2095 		slot->curcmd->error = MMC_ERR_TIMEOUT;
2096 	else if (intmask & SDHCI_INT_CRC)
2097 		slot->curcmd->error = MMC_ERR_BADCRC;
2098 	else if (intmask & (SDHCI_INT_END_BIT | SDHCI_INT_INDEX))
2099 		slot->curcmd->error = MMC_ERR_FIFO;
2100 
2101 	sdhci_finish_command(slot);
2102 }
2103 
2104 static void
2105 sdhci_data_irq(struct sdhci_slot *slot, uint32_t intmask)
2106 {
2107 	struct mmc_data *data;
2108 	size_t left;
2109 	uint32_t sdma_bbufsz;
2110 
2111 	if (!slot->curcmd) {
2112 		slot_printf(slot, "Got data interrupt 0x%08x, but "
2113 		    "there is no active command.\n", intmask);
2114 		sdhci_dumpregs(slot);
2115 		return;
2116 	}
2117 	if (slot->curcmd->data == NULL &&
2118 	    (slot->curcmd->flags & MMC_RSP_BUSY) == 0) {
2119 		slot_printf(slot, "Got data interrupt 0x%08x, but "
2120 		    "there is no active data operation.\n",
2121 		    intmask);
2122 		sdhci_dumpregs(slot);
2123 		return;
2124 	}
2125 	if (intmask & SDHCI_INT_DATA_TIMEOUT)
2126 		slot->curcmd->error = MMC_ERR_TIMEOUT;
2127 	else if (intmask & (SDHCI_INT_DATA_CRC | SDHCI_INT_DATA_END_BIT))
2128 		slot->curcmd->error = MMC_ERR_BADCRC;
2129 	if (slot->curcmd->data == NULL &&
2130 	    (intmask & (SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL |
2131 	    SDHCI_INT_DMA_END))) {
2132 		slot_printf(slot, "Got data interrupt 0x%08x, but "
2133 		    "there is busy-only command.\n", intmask);
2134 		sdhci_dumpregs(slot);
2135 		slot->curcmd->error = MMC_ERR_INVALID;
2136 	}
2137 	if (slot->curcmd->error) {
2138 		/* No need to continue after any error. */
2139 		goto done;
2140 	}
2141 
2142 	/* Handle tuning completion interrupt. */
2143 	if (__predict_false((intmask & SDHCI_INT_DATA_AVAIL) &&
2144 	    (slot->curcmd->opcode == MMC_SEND_TUNING_BLOCK ||
2145 	    slot->curcmd->opcode == MMC_SEND_TUNING_BLOCK_HS200))) {
2146 		slot->req->flags |= MMC_TUNE_DONE;
2147 		sdhci_finish_command(slot);
2148 		sdhci_finish_data(slot);
2149 		return;
2150 	}
2151 	/* Handle PIO interrupt. */
2152 	if (intmask & (SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL)) {
2153 		if ((slot->opt & SDHCI_PLATFORM_TRANSFER) &&
2154 		    SDHCI_PLATFORM_WILL_HANDLE(slot->bus, slot)) {
2155 			SDHCI_PLATFORM_START_TRANSFER(slot->bus, slot,
2156 			    &intmask);
2157 			slot->flags |= PLATFORM_DATA_STARTED;
2158 		} else
2159 			sdhci_transfer_pio(slot);
2160 	}
2161 	/* Handle DMA border. */
2162 	if (intmask & SDHCI_INT_DMA_END) {
2163 		data = slot->curcmd->data;
2164 		sdma_bbufsz = slot->sdma_bbufsz;
2165 
2166 		/* Unload DMA buffer ... */
2167 		left = data->len - slot->offset;
2168 		if (data->flags & MMC_DATA_READ) {
2169 			bus_dmamap_sync(slot->dmatag, slot->dmamap,
2170 			    BUS_DMASYNC_POSTREAD);
2171 			memcpy((u_char*)data->data + slot->offset, slot->dmamem,
2172 			    ulmin(left, sdma_bbufsz));
2173 		} else {
2174 			bus_dmamap_sync(slot->dmatag, slot->dmamap,
2175 			    BUS_DMASYNC_POSTWRITE);
2176 		}
2177 		/* ... and reload it again. */
2178 		slot->offset += sdma_bbufsz;
2179 		left = data->len - slot->offset;
2180 		if (data->flags & MMC_DATA_READ) {
2181 			bus_dmamap_sync(slot->dmatag, slot->dmamap,
2182 			    BUS_DMASYNC_PREREAD);
2183 		} else {
2184 			memcpy(slot->dmamem, (u_char*)data->data + slot->offset,
2185 			    ulmin(left, sdma_bbufsz));
2186 			bus_dmamap_sync(slot->dmatag, slot->dmamap,
2187 			    BUS_DMASYNC_PREWRITE);
2188 		}
2189 		/*
2190 		 * Interrupt aggregation: Mask border interrupt for the last
2191 		 * bounce buffer.
2192 		 */
2193 		if (left == sdma_bbufsz) {
2194 			slot->intmask &= ~SDHCI_INT_DMA_END;
2195 			WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask);
2196 		}
2197 		/* Restart DMA. */
2198 		WR4(slot, SDHCI_DMA_ADDRESS, slot->paddr);
2199 	}
2200 	/* We have got all data. */
2201 	if (intmask & SDHCI_INT_DATA_END) {
2202 		if (slot->flags & PLATFORM_DATA_STARTED) {
2203 			slot->flags &= ~PLATFORM_DATA_STARTED;
2204 			SDHCI_PLATFORM_FINISH_TRANSFER(slot->bus, slot);
2205 		} else
2206 			sdhci_finish_data(slot);
2207 	}
2208 done:
2209 	if (slot->curcmd != NULL && slot->curcmd->error != 0) {
2210 		if (slot->flags & PLATFORM_DATA_STARTED) {
2211 			slot->flags &= ~PLATFORM_DATA_STARTED;
2212 			SDHCI_PLATFORM_FINISH_TRANSFER(slot->bus, slot);
2213 		} else
2214 			sdhci_finish_data(slot);
2215 	}
2216 }
2217 
2218 static void
2219 sdhci_acmd_irq(struct sdhci_slot *slot, uint16_t acmd_err)
2220 {
2221 
2222 	if (!slot->curcmd) {
2223 		slot_printf(slot, "Got AutoCMD12 error 0x%04x, but "
2224 		    "there is no active command.\n", acmd_err);
2225 		sdhci_dumpregs(slot);
2226 		return;
2227 	}
2228 	slot_printf(slot, "Got AutoCMD12 error 0x%04x\n", acmd_err);
2229 	sdhci_reset(slot, SDHCI_RESET_CMD);
2230 }
2231 
2232 void
2233 sdhci_generic_intr(struct sdhci_slot *slot)
2234 {
2235 	uint32_t intmask, present;
2236 	uint16_t val16;
2237 
2238 	SDHCI_LOCK(slot);
2239 	/* Read slot interrupt status. */
2240 	intmask = RD4(slot, SDHCI_INT_STATUS);
2241 	if (intmask == 0 || intmask == 0xffffffff) {
2242 		SDHCI_UNLOCK(slot);
2243 		return;
2244 	}
2245 	if (__predict_false(sdhci_debug > 2))
2246 		slot_printf(slot, "Interrupt %#x\n", intmask);
2247 
2248 	/* Handle tuning error interrupt. */
2249 	if (__predict_false(intmask & SDHCI_INT_TUNEERR)) {
2250 		WR4(slot, SDHCI_INT_STATUS, SDHCI_INT_TUNEERR);
2251 		slot_printf(slot, "Tuning error indicated\n");
2252 		slot->retune_req |= SDHCI_RETUNE_REQ_RESET;
2253 		if (slot->curcmd) {
2254 			slot->curcmd->error = MMC_ERR_BADCRC;
2255 			sdhci_finish_command(slot);
2256 		}
2257 	}
2258 	/* Handle re-tuning interrupt. */
2259 	if (__predict_false(intmask & SDHCI_INT_RETUNE))
2260 		slot->retune_req |= SDHCI_RETUNE_REQ_NEEDED;
2261 	/* Handle card presence interrupts. */
2262 	if (intmask & (SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE)) {
2263 		present = (intmask & SDHCI_INT_CARD_INSERT) != 0;
2264 		slot->intmask &=
2265 		    ~(SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE);
2266 		slot->intmask |= present ? SDHCI_INT_CARD_REMOVE :
2267 		    SDHCI_INT_CARD_INSERT;
2268 		WR4(slot, SDHCI_INT_ENABLE, slot->intmask);
2269 		WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask);
2270 		WR4(slot, SDHCI_INT_STATUS, intmask &
2271 		    (SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE));
2272 		sdhci_handle_card_present_locked(slot, present);
2273 	}
2274 	/* Handle command interrupts. */
2275 	if (intmask & SDHCI_INT_CMD_MASK) {
2276 		WR4(slot, SDHCI_INT_STATUS, intmask & SDHCI_INT_CMD_MASK);
2277 		sdhci_cmd_irq(slot, intmask & SDHCI_INT_CMD_MASK);
2278 	}
2279 	/* Handle data interrupts. */
2280 	if (intmask & SDHCI_INT_DATA_MASK) {
2281 		WR4(slot, SDHCI_INT_STATUS, intmask & SDHCI_INT_DATA_MASK);
2282 		/* Don't call data_irq in case of errored command. */
2283 		if ((intmask & SDHCI_INT_CMD_ERROR_MASK) == 0)
2284 			sdhci_data_irq(slot, intmask & SDHCI_INT_DATA_MASK);
2285 	}
2286 	/* Handle AutoCMD12 error interrupt. */
2287 	if (intmask & SDHCI_INT_ACMD12ERR) {
2288 		/* Clearing SDHCI_INT_ACMD12ERR may clear SDHCI_ACMD12_ERR. */
2289 		val16 = RD2(slot, SDHCI_ACMD12_ERR);
2290 		WR4(slot, SDHCI_INT_STATUS, SDHCI_INT_ACMD12ERR);
2291 		sdhci_acmd_irq(slot, val16);
2292 	}
2293 	/* Handle bus power interrupt. */
2294 	if (intmask & SDHCI_INT_BUS_POWER) {
2295 		WR4(slot, SDHCI_INT_STATUS, SDHCI_INT_BUS_POWER);
2296 		slot_printf(slot, "Card is consuming too much power!\n");
2297 	}
2298 	intmask &= ~(SDHCI_INT_ERROR | SDHCI_INT_TUNEERR | SDHCI_INT_RETUNE |
2299 	    SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE | SDHCI_INT_CMD_MASK |
2300 	    SDHCI_INT_DATA_MASK | SDHCI_INT_ACMD12ERR | SDHCI_INT_BUS_POWER);
2301 	/* The rest is unknown. */
2302 	if (intmask) {
2303 		WR4(slot, SDHCI_INT_STATUS, intmask);
2304 		slot_printf(slot, "Unexpected interrupt 0x%08x.\n",
2305 		    intmask);
2306 		sdhci_dumpregs(slot);
2307 	}
2308 
2309 	SDHCI_UNLOCK(slot);
2310 }
2311 
2312 int
2313 sdhci_generic_read_ivar(device_t bus, device_t child, int which,
2314     uintptr_t *result)
2315 {
2316 	const struct sdhci_slot *slot = device_get_ivars(child);
2317 
2318 	switch (which) {
2319 	default:
2320 		return (EINVAL);
2321 	case MMCBR_IVAR_BUS_MODE:
2322 		*result = slot->host.ios.bus_mode;
2323 		break;
2324 	case MMCBR_IVAR_BUS_WIDTH:
2325 		*result = slot->host.ios.bus_width;
2326 		break;
2327 	case MMCBR_IVAR_CHIP_SELECT:
2328 		*result = slot->host.ios.chip_select;
2329 		break;
2330 	case MMCBR_IVAR_CLOCK:
2331 		*result = slot->host.ios.clock;
2332 		break;
2333 	case MMCBR_IVAR_F_MIN:
2334 		*result = slot->host.f_min;
2335 		break;
2336 	case MMCBR_IVAR_F_MAX:
2337 		*result = slot->host.f_max;
2338 		break;
2339 	case MMCBR_IVAR_HOST_OCR:
2340 		*result = slot->host.host_ocr;
2341 		break;
2342 	case MMCBR_IVAR_MODE:
2343 		*result = slot->host.mode;
2344 		break;
2345 	case MMCBR_IVAR_OCR:
2346 		*result = slot->host.ocr;
2347 		break;
2348 	case MMCBR_IVAR_POWER_MODE:
2349 		*result = slot->host.ios.power_mode;
2350 		break;
2351 	case MMCBR_IVAR_VDD:
2352 		*result = slot->host.ios.vdd;
2353 		break;
2354 	case MMCBR_IVAR_RETUNE_REQ:
2355 		if (slot->opt & SDHCI_TUNING_ENABLED) {
2356 			if (slot->retune_req & SDHCI_RETUNE_REQ_RESET) {
2357 				*result = retune_req_reset;
2358 				break;
2359 			}
2360 			if (slot->retune_req & SDHCI_RETUNE_REQ_NEEDED) {
2361 				*result = retune_req_normal;
2362 				break;
2363 			}
2364 		}
2365 		*result = retune_req_none;
2366 		break;
2367 	case MMCBR_IVAR_VCCQ:
2368 		*result = slot->host.ios.vccq;
2369 		break;
2370 	case MMCBR_IVAR_CAPS:
2371 		*result = slot->host.caps;
2372 		break;
2373 	case MMCBR_IVAR_TIMING:
2374 		*result = slot->host.ios.timing;
2375 		break;
2376 	case MMCBR_IVAR_MAX_DATA:
2377 		/*
2378 		 * Re-tuning modes 1 and 2 restrict the maximum data length
2379 		 * per read/write command to 4 MiB.
2380 		 */
2381 		if (slot->opt & SDHCI_TUNING_ENABLED &&
2382 		    (slot->retune_mode == SDHCI_RETUNE_MODE_1 ||
2383 		    slot->retune_mode == SDHCI_RETUNE_MODE_2)) {
2384 			*result = 4 * 1024 * 1024 / MMC_SECTOR_SIZE;
2385 			break;
2386 		}
2387 		*result = 65535;
2388 		break;
2389 	case MMCBR_IVAR_MAX_BUSY_TIMEOUT:
2390 		/*
2391 		 * Currently, sdhci_start_data() hardcodes 1 s for all CMDs.
2392 		 */
2393 		*result = 1000000;
2394 		break;
2395 	}
2396 	return (0);
2397 }
2398 
2399 int
2400 sdhci_generic_write_ivar(device_t bus, device_t child, int which,
2401     uintptr_t value)
2402 {
2403 	struct sdhci_slot *slot = device_get_ivars(child);
2404 	uint32_t clock, max_clock;
2405 	int i;
2406 
2407 	if (sdhci_debug > 1)
2408 		slot_printf(slot, "%s: var=%d\n", __func__, which);
2409 	switch (which) {
2410 	default:
2411 		return (EINVAL);
2412 	case MMCBR_IVAR_BUS_MODE:
2413 		slot->host.ios.bus_mode = value;
2414 		break;
2415 	case MMCBR_IVAR_BUS_WIDTH:
2416 		slot->host.ios.bus_width = value;
2417 		break;
2418 	case MMCBR_IVAR_CHIP_SELECT:
2419 		slot->host.ios.chip_select = value;
2420 		break;
2421 	case MMCBR_IVAR_CLOCK:
2422 		if (value > 0) {
2423 			max_clock = slot->max_clk;
2424 			clock = max_clock;
2425 
2426 			if (slot->version < SDHCI_SPEC_300) {
2427 				for (i = 0; i < SDHCI_200_MAX_DIVIDER;
2428 				    i <<= 1) {
2429 					if (clock <= value)
2430 						break;
2431 					clock >>= 1;
2432 				}
2433 			} else {
2434 				for (i = 0; i < SDHCI_300_MAX_DIVIDER;
2435 				    i += 2) {
2436 					if (clock <= value)
2437 						break;
2438 					clock = max_clock / (i + 2);
2439 				}
2440 			}
2441 
2442 			slot->host.ios.clock = clock;
2443 		} else
2444 			slot->host.ios.clock = 0;
2445 		break;
2446 	case MMCBR_IVAR_MODE:
2447 		slot->host.mode = value;
2448 		break;
2449 	case MMCBR_IVAR_OCR:
2450 		slot->host.ocr = value;
2451 		break;
2452 	case MMCBR_IVAR_POWER_MODE:
2453 		slot->host.ios.power_mode = value;
2454 		break;
2455 	case MMCBR_IVAR_VDD:
2456 		slot->host.ios.vdd = value;
2457 		break;
2458 	case MMCBR_IVAR_VCCQ:
2459 		slot->host.ios.vccq = value;
2460 		break;
2461 	case MMCBR_IVAR_TIMING:
2462 		slot->host.ios.timing = value;
2463 		break;
2464 	case MMCBR_IVAR_CAPS:
2465 	case MMCBR_IVAR_HOST_OCR:
2466 	case MMCBR_IVAR_F_MIN:
2467 	case MMCBR_IVAR_F_MAX:
2468 	case MMCBR_IVAR_MAX_DATA:
2469 	case MMCBR_IVAR_RETUNE_REQ:
2470 		return (EINVAL);
2471 	}
2472 	return (0);
2473 }
2474 
2475 #ifdef MMCCAM
2476 void
2477 sdhci_start_slot(struct sdhci_slot *slot)
2478 {
2479 
2480 	if ((slot->devq = cam_simq_alloc(1)) == NULL)
2481 		goto fail;
2482 
2483 	mtx_init(&slot->sim_mtx, "sdhcisim", NULL, MTX_DEF);
2484 	slot->sim = cam_sim_alloc_dev(sdhci_cam_action, sdhci_cam_poll,
2485 	    "sdhci_slot", slot, slot->bus,
2486 	    &slot->sim_mtx, 1, 1, slot->devq);
2487 
2488 	if (slot->sim == NULL) {
2489 		cam_simq_free(slot->devq);
2490 		slot_printf(slot, "cannot allocate CAM SIM\n");
2491 		goto fail;
2492 	}
2493 
2494 	mtx_lock(&slot->sim_mtx);
2495 	if (xpt_bus_register(slot->sim, slot->bus, 0) != 0) {
2496 		slot_printf(slot, "cannot register SCSI pass-through bus\n");
2497 		cam_sim_free(slot->sim, FALSE);
2498 		cam_simq_free(slot->devq);
2499 		mtx_unlock(&slot->sim_mtx);
2500 		goto fail;
2501 	}
2502 	mtx_unlock(&slot->sim_mtx);
2503 
2504 	/* End CAM-specific init */
2505 	slot->card_present = 0;
2506 	sdhci_card_task(slot, 0);
2507 	return;
2508 
2509 fail:
2510 	if (slot->sim != NULL) {
2511 		mtx_lock(&slot->sim_mtx);
2512 		xpt_bus_deregister(cam_sim_path(slot->sim));
2513 		cam_sim_free(slot->sim, FALSE);
2514 		mtx_unlock(&slot->sim_mtx);
2515 	}
2516 
2517 	if (slot->devq != NULL)
2518 		cam_simq_free(slot->devq);
2519 }
2520 
2521 void
2522 sdhci_cam_action(struct cam_sim *sim, union ccb *ccb)
2523 {
2524 	struct sdhci_slot *slot;
2525 
2526 	slot = cam_sim_softc(sim);
2527 	if (slot == NULL) {
2528 		ccb->ccb_h.status = CAM_SEL_TIMEOUT;
2529 		xpt_done(ccb);
2530 		return;
2531 	}
2532 
2533 	mtx_assert(&slot->sim_mtx, MA_OWNED);
2534 
2535 	switch (ccb->ccb_h.func_code) {
2536 	case XPT_PATH_INQ:
2537 		mmc_path_inq(&ccb->cpi, "Deglitch Networks", sim, maxphys);
2538 		break;
2539 
2540 	case XPT_GET_TRAN_SETTINGS:
2541 	{
2542 		struct ccb_trans_settings *cts = &ccb->cts;
2543 		uint32_t max_data;
2544 
2545 		if (sdhci_debug > 1)
2546 			slot_printf(slot, "Got XPT_GET_TRAN_SETTINGS\n");
2547 
2548 		cts->protocol = PROTO_MMCSD;
2549 		cts->protocol_version = 1;
2550 		cts->transport = XPORT_MMCSD;
2551 		cts->transport_version = 1;
2552 		cts->xport_specific.valid = 0;
2553 		cts->proto_specific.mmc.host_ocr = slot->host.host_ocr;
2554 		cts->proto_specific.mmc.host_f_min = slot->host.f_min;
2555 		cts->proto_specific.mmc.host_f_max = slot->host.f_max;
2556 		cts->proto_specific.mmc.host_caps = slot->host.caps;
2557 		/*
2558 		 * Re-tuning modes 1 and 2 restrict the maximum data length
2559 		 * per read/write command to 4 MiB.
2560 		 */
2561 		if (slot->opt & SDHCI_TUNING_ENABLED &&
2562 		    (slot->retune_mode == SDHCI_RETUNE_MODE_1 ||
2563 		    slot->retune_mode == SDHCI_RETUNE_MODE_2)) {
2564 			max_data = 4 * 1024 * 1024 / MMC_SECTOR_SIZE;
2565 		} else {
2566 			max_data = 65535;
2567 		}
2568 		cts->proto_specific.mmc.host_max_data = max_data;
2569 
2570 		memcpy(&cts->proto_specific.mmc.ios, &slot->host.ios, sizeof(struct mmc_ios));
2571 		ccb->ccb_h.status = CAM_REQ_CMP;
2572 		break;
2573 	}
2574 	case XPT_SET_TRAN_SETTINGS:
2575 		if (sdhci_debug > 1)
2576 			slot_printf(slot, "Got XPT_SET_TRAN_SETTINGS\n");
2577 		sdhci_cam_settran_settings(slot, ccb);
2578 		ccb->ccb_h.status = CAM_REQ_CMP;
2579 		break;
2580 	case XPT_RESET_BUS:
2581 		if (sdhci_debug > 1)
2582 			slot_printf(slot, "Got XPT_RESET_BUS, ACK it...\n");
2583 		ccb->ccb_h.status = CAM_REQ_CMP;
2584 		break;
2585 	case XPT_MMC_IO:
2586 		/*
2587 		 * Here is the HW-dependent part of
2588 		 * sending the command to the underlying h/w
2589 		 * At some point in the future an interrupt comes.
2590 		 * Then the request will be marked as completed.
2591 		 */
2592 		if (__predict_false(sdhci_debug > 1))
2593 			slot_printf(slot, "Got XPT_MMC_IO\n");
2594 		ccb->ccb_h.status = CAM_REQ_INPROG;
2595 
2596 		sdhci_cam_request(cam_sim_softc(sim), ccb);
2597 		return;
2598 	default:
2599 		ccb->ccb_h.status = CAM_REQ_INVALID;
2600 		break;
2601 	}
2602 	xpt_done(ccb);
2603 	return;
2604 }
2605 
2606 void
2607 sdhci_cam_poll(struct cam_sim *sim)
2608 {
2609 	return;
2610 }
2611 
2612 static int
2613 sdhci_cam_get_possible_host_clock(const struct sdhci_slot *slot,
2614     int proposed_clock)
2615 {
2616 	int max_clock, clock, i;
2617 
2618 	if (proposed_clock == 0)
2619 		return 0;
2620 	max_clock = slot->max_clk;
2621 	clock = max_clock;
2622 
2623 	if (slot->version < SDHCI_SPEC_300) {
2624 		for (i = 0; i < SDHCI_200_MAX_DIVIDER; i <<= 1) {
2625 			if (clock <= proposed_clock)
2626 				break;
2627 			clock >>= 1;
2628 		}
2629 	} else {
2630 		for (i = 0; i < SDHCI_300_MAX_DIVIDER; i += 2) {
2631 			if (clock <= proposed_clock)
2632 				break;
2633 			clock = max_clock / (i + 2);
2634 		}
2635 	}
2636 	return clock;
2637 }
2638 
2639 static int
2640 sdhci_cam_settran_settings(struct sdhci_slot *slot, union ccb *ccb)
2641 {
2642 	struct mmc_ios *ios;
2643 	const struct mmc_ios *new_ios;
2644 	const struct ccb_trans_settings_mmc *cts;
2645 
2646 	ios = &slot->host.ios;
2647 	cts = &ccb->cts.proto_specific.mmc;
2648 	new_ios = &cts->ios;
2649 
2650 	/* Update only requested fields */
2651 	if (cts->ios_valid & MMC_CLK) {
2652 		ios->clock = sdhci_cam_get_possible_host_clock(slot, new_ios->clock);
2653 		if (sdhci_debug > 1)
2654 			slot_printf(slot, "Clock => %d\n", ios->clock);
2655 	}
2656 	if (cts->ios_valid & MMC_VDD) {
2657 		ios->vdd = new_ios->vdd;
2658 		if (sdhci_debug > 1)
2659 			slot_printf(slot, "VDD => %d\n", ios->vdd);
2660 	}
2661 	if (cts->ios_valid & MMC_CS) {
2662 		ios->chip_select = new_ios->chip_select;
2663 		if (sdhci_debug > 1)
2664 			slot_printf(slot, "CS => %d\n", ios->chip_select);
2665 	}
2666 	if (cts->ios_valid & MMC_BW) {
2667 		ios->bus_width = new_ios->bus_width;
2668 		if (sdhci_debug > 1)
2669 			slot_printf(slot, "Bus width => %d\n", ios->bus_width);
2670 	}
2671 	if (cts->ios_valid & MMC_PM) {
2672 		ios->power_mode = new_ios->power_mode;
2673 		if (sdhci_debug > 1)
2674 			slot_printf(slot, "Power mode => %d\n", ios->power_mode);
2675 	}
2676 	if (cts->ios_valid & MMC_BT) {
2677 		ios->timing = new_ios->timing;
2678 		if (sdhci_debug > 1)
2679 			slot_printf(slot, "Timing => %d\n", ios->timing);
2680 	}
2681 	if (cts->ios_valid & MMC_BM) {
2682 		ios->bus_mode = new_ios->bus_mode;
2683 		if (sdhci_debug > 1)
2684 			slot_printf(slot, "Bus mode => %d\n", ios->bus_mode);
2685 	}
2686 	if (cts->ios_valid & MMC_VCCQ) {
2687 		ios->vccq = new_ios->vccq;
2688 		if (sdhci_debug > 1)
2689 			slot_printf(slot, "VCCQ => %d\n", ios->vccq);
2690 	}
2691 
2692 	/* XXX Provide a way to call a chip-specific IOS update, required for TI */
2693 	return (sdhci_cam_update_ios(slot));
2694 }
2695 
2696 static int
2697 sdhci_cam_update_ios(struct sdhci_slot *slot)
2698 {
2699 	struct mmc_ios *ios = &slot->host.ios;
2700 
2701 	if (sdhci_debug > 1)
2702 		slot_printf(slot, "%s: power_mode=%d, clk=%d, bus_width=%d, timing=%d\n",
2703 		    __func__, ios->power_mode, ios->clock, ios->bus_width, ios->timing);
2704 	SDHCI_LOCK(slot);
2705 	/* Do full reset on bus power down to clear from any state. */
2706 	if (ios->power_mode == power_off) {
2707 		WR4(slot, SDHCI_SIGNAL_ENABLE, 0);
2708 		sdhci_init(slot);
2709 	}
2710 	/* Configure the bus. */
2711 	sdhci_set_clock(slot, ios->clock);
2712 	sdhci_set_power(slot, (ios->power_mode == power_off) ? 0 : ios->vdd);
2713 	if (ios->bus_width == bus_width_8) {
2714 		slot->hostctrl |= SDHCI_CTRL_8BITBUS;
2715 		slot->hostctrl &= ~SDHCI_CTRL_4BITBUS;
2716 	} else if (ios->bus_width == bus_width_4) {
2717 		slot->hostctrl &= ~SDHCI_CTRL_8BITBUS;
2718 		slot->hostctrl |= SDHCI_CTRL_4BITBUS;
2719 	} else if (ios->bus_width == bus_width_1) {
2720 		slot->hostctrl &= ~SDHCI_CTRL_8BITBUS;
2721 		slot->hostctrl &= ~SDHCI_CTRL_4BITBUS;
2722 	} else {
2723 		panic("Invalid bus width: %d", ios->bus_width);
2724 	}
2725 	if (ios->timing == bus_timing_hs &&
2726 	    !(slot->quirks & SDHCI_QUIRK_DONT_SET_HISPD_BIT))
2727 		slot->hostctrl |= SDHCI_CTRL_HISPD;
2728 	else
2729 		slot->hostctrl &= ~SDHCI_CTRL_HISPD;
2730 	WR1(slot, SDHCI_HOST_CONTROL, slot->hostctrl);
2731 	/* Some controllers like reset after bus changes. */
2732 	if(slot->quirks & SDHCI_QUIRK_RESET_ON_IOS)
2733 		sdhci_reset(slot, SDHCI_RESET_CMD | SDHCI_RESET_DATA);
2734 
2735 	SDHCI_UNLOCK(slot);
2736 	return (0);
2737 }
2738 
2739 static int
2740 sdhci_cam_request(struct sdhci_slot *slot, union ccb *ccb)
2741 {
2742 	const struct ccb_mmcio *mmcio;
2743 
2744 	mmcio = &ccb->mmcio;
2745 
2746 	SDHCI_LOCK(slot);
2747 /*	if (slot->req != NULL) {
2748 		SDHCI_UNLOCK(slot);
2749 		return (EBUSY);
2750 	}
2751 */
2752 	if (__predict_false(sdhci_debug > 1)) {
2753 		slot_printf(slot, "CMD%u arg %#x flags %#x dlen %u dflags %#x "
2754 		    "blksz=%zu blkcnt=%zu\n",
2755 		    mmcio->cmd.opcode, mmcio->cmd.arg, mmcio->cmd.flags,
2756 		    mmcio->cmd.data != NULL ? (unsigned int) mmcio->cmd.data->len : 0,
2757 		    mmcio->cmd.data != NULL ? mmcio->cmd.data->flags : 0,
2758 		    mmcio->cmd.data != NULL ? mmcio->cmd.data->block_size : 0,
2759 		    mmcio->cmd.data != NULL ? mmcio->cmd.data->block_count : 0);
2760 	}
2761 	if (mmcio->cmd.data != NULL) {
2762 		if (mmcio->cmd.data->len == 0 || mmcio->cmd.data->flags == 0)
2763 			panic("data->len = %d, data->flags = %d -- something is b0rked",
2764 			    (int)mmcio->cmd.data->len, mmcio->cmd.data->flags);
2765 	}
2766 	slot->ccb = ccb;
2767 	slot->flags = 0;
2768 	sdhci_start(slot);
2769 	SDHCI_UNLOCK(slot);
2770 	if (dumping) {
2771 		while (slot->ccb != NULL) {
2772 			sdhci_generic_intr(slot);
2773 			DELAY(10);
2774 		}
2775 	}
2776 	return (0);
2777 }
2778 #endif /* MMCCAM */
2779 
2780 MODULE_VERSION(sdhci, SDHCI_VERSION);
2781