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