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