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