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