xref: /netbsd-src/sys/dev/sdmmc/sdhc.c (revision 2718af68c3efc72c9769069b5c7f9ed36f6b9def)
1 /*	$NetBSD: sdhc.c,v 1.115 2022/02/06 15:52:20 jmcneill Exp $	*/
2 /*	$OpenBSD: sdhc.c,v 1.25 2009/01/13 19:44:20 grange Exp $	*/
3 
4 /*
5  * Copyright (c) 2006 Uwe Stuehler <uwe@openbsd.org>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 /*
21  * SD Host Controller driver based on the SD Host Controller Standard
22  * Simplified Specification Version 1.00 (www.sdcard.com).
23  */
24 
25 #include <sys/cdefs.h>
26 __KERNEL_RCSID(0, "$NetBSD: sdhc.c,v 1.115 2022/02/06 15:52:20 jmcneill Exp $");
27 
28 #ifdef _KERNEL_OPT
29 #include "opt_sdmmc.h"
30 #endif
31 
32 #include <sys/param.h>
33 #include <sys/device.h>
34 #include <sys/kernel.h>
35 #include <sys/malloc.h>
36 #include <sys/systm.h>
37 #include <sys/mutex.h>
38 #include <sys/condvar.h>
39 #include <sys/atomic.h>
40 
41 #include <dev/sdmmc/sdhcreg.h>
42 #include <dev/sdmmc/sdhcvar.h>
43 #include <dev/sdmmc/sdmmcchip.h>
44 #include <dev/sdmmc/sdmmcreg.h>
45 #include <dev/sdmmc/sdmmcvar.h>
46 
47 #ifdef SDHC_DEBUG
48 int sdhcdebug = 1;
49 #define DPRINTF(n,s)	do { if ((n) <= sdhcdebug) printf s; } while (0)
50 void	sdhc_dump_regs(struct sdhc_host *);
51 #else
52 #define DPRINTF(n,s)	do {} while (0)
53 #endif
54 
55 #define SDHC_COMMAND_TIMEOUT	hz
56 #define SDHC_BUFFER_TIMEOUT	hz
57 #define SDHC_TRANSFER_TIMEOUT	hz
58 #define SDHC_DMA_TIMEOUT	(hz*3)
59 #define SDHC_TUNING_TIMEOUT	hz
60 
61 struct sdhc_host {
62 	struct sdhc_softc *sc;		/* host controller device */
63 
64 	bus_space_tag_t iot;		/* host register set tag */
65 	bus_space_handle_t ioh;		/* host register set handle */
66 	bus_size_t ios;			/* host register space size */
67 	bus_dma_tag_t dmat;		/* host DMA tag */
68 
69 	device_t sdmmc;			/* generic SD/MMC device */
70 
71 	u_int clkbase;			/* base clock frequency in KHz */
72 	int maxblklen;			/* maximum block length */
73 	uint32_t ocr;			/* OCR value from capabilities */
74 
75 	uint8_t regs[14];		/* host controller state */
76 
77 	uint16_t intr_status;		/* soft interrupt status */
78 	uint16_t intr_error_status;	/* soft error status */
79 	kmutex_t intr_lock;
80 	kmutex_t bus_clock_lock;
81 	kcondvar_t intr_cv;
82 
83 	callout_t tuning_timer;
84 	int tuning_timing;
85 	u_int tuning_timer_count;
86 	u_int tuning_timer_pending;
87 
88 	int specver;			/* spec. version */
89 
90 	uint32_t flags;			/* flags for this host */
91 #define SHF_USE_DMA		0x0001
92 #define SHF_USE_4BIT_MODE	0x0002
93 #define SHF_USE_8BIT_MODE	0x0004
94 #define SHF_MODE_DMAEN		0x0008 /* needs SDHC_DMA_ENABLE in mode */
95 #define SHF_USE_ADMA2_32	0x0010
96 #define SHF_USE_ADMA2_64	0x0020
97 #define SHF_USE_ADMA2_MASK	0x0030
98 
99 	bus_dmamap_t		adma_map;
100 	bus_dma_segment_t	adma_segs[1];
101 	void			*adma2;
102 
103 	uint8_t			vdd;	/* last vdd setting */
104 };
105 
106 #define HDEVNAME(hp)	(device_xname((hp)->sc->sc_dev))
107 
108 static uint8_t
109 hread1(struct sdhc_host *hp, bus_size_t reg)
110 {
111 
112 	if (!ISSET(hp->sc->sc_flags, SDHC_FLAG_32BIT_ACCESS))
113 		return bus_space_read_1(hp->iot, hp->ioh, reg);
114 	return bus_space_read_4(hp->iot, hp->ioh, reg & -4) >> (8 * (reg & 3));
115 }
116 
117 static uint16_t
118 hread2(struct sdhc_host *hp, bus_size_t reg)
119 {
120 
121 	if (!ISSET(hp->sc->sc_flags, SDHC_FLAG_32BIT_ACCESS))
122 		return bus_space_read_2(hp->iot, hp->ioh, reg);
123 	return bus_space_read_4(hp->iot, hp->ioh, reg & -4) >> (8 * (reg & 2));
124 }
125 
126 #define HREAD1(hp, reg)		hread1(hp, reg)
127 #define HREAD2(hp, reg)		hread2(hp, reg)
128 #define HREAD4(hp, reg)		\
129 	(bus_space_read_4((hp)->iot, (hp)->ioh, (reg)))
130 
131 
132 static void
133 hwrite1(struct sdhc_host *hp, bus_size_t o, uint8_t val)
134 {
135 
136 	if (!ISSET(hp->sc->sc_flags, SDHC_FLAG_32BIT_ACCESS)) {
137 		bus_space_write_1(hp->iot, hp->ioh, o, val);
138 	} else {
139 		const size_t shift = 8 * (o & 3);
140 		o &= -4;
141 		uint32_t tmp = bus_space_read_4(hp->iot, hp->ioh, o);
142 		tmp = (val << shift) | (tmp & ~(0xffU << shift));
143 		bus_space_write_4(hp->iot, hp->ioh, o, tmp);
144 	}
145 }
146 
147 static void
148 hwrite2(struct sdhc_host *hp, bus_size_t o, uint16_t val)
149 {
150 
151 	if (!ISSET(hp->sc->sc_flags, SDHC_FLAG_32BIT_ACCESS)) {
152 		bus_space_write_2(hp->iot, hp->ioh, o, val);
153 	} else {
154 		const size_t shift = 8 * (o & 2);
155 		o &= -4;
156 		uint32_t tmp = bus_space_read_4(hp->iot, hp->ioh, o);
157 		tmp = (val << shift) | (tmp & ~(0xffffU << shift));
158 		bus_space_write_4(hp->iot, hp->ioh, o, tmp);
159 	}
160 }
161 
162 static void
163 hwrite4(struct sdhc_host *hp, bus_size_t o, uint32_t val)
164 {
165 
166 	bus_space_write_4(hp->iot, hp->ioh, o, val);
167 }
168 
169 #define HWRITE1(hp, reg, val)		hwrite1(hp, reg, val)
170 #define HWRITE2(hp, reg, val)		hwrite2(hp, reg, val)
171 #define HWRITE4(hp, reg, val)		hwrite4(hp, reg, val)
172 
173 #define HCLR1(hp, reg, bits)						\
174 	do if ((bits) != 0) HWRITE1((hp), (reg), HREAD1((hp), (reg)) & ~(bits)); while (0)
175 #define HCLR2(hp, reg, bits)						\
176 	do if ((bits) != 0) HWRITE2((hp), (reg), HREAD2((hp), (reg)) & ~(bits)); while (0)
177 #define HCLR4(hp, reg, bits)						\
178 	do if ((bits) != 0) HWRITE4((hp), (reg), HREAD4((hp), (reg)) & ~(bits)); while (0)
179 #define HSET1(hp, reg, bits)						\
180 	do if ((bits) != 0) HWRITE1((hp), (reg), HREAD1((hp), (reg)) | (bits)); while (0)
181 #define HSET2(hp, reg, bits)						\
182 	do if ((bits) != 0) HWRITE2((hp), (reg), HREAD2((hp), (reg)) | (bits)); while (0)
183 #define HSET4(hp, reg, bits)						\
184 	do if ((bits) != 0) HWRITE4((hp), (reg), HREAD4((hp), (reg)) | (bits)); while (0)
185 
186 static int	sdhc_host_reset(sdmmc_chipset_handle_t);
187 static int	sdhc_host_reset1(sdmmc_chipset_handle_t);
188 static uint32_t	sdhc_host_ocr(sdmmc_chipset_handle_t);
189 static int	sdhc_host_maxblklen(sdmmc_chipset_handle_t);
190 static int	sdhc_card_detect(sdmmc_chipset_handle_t);
191 static int	sdhc_write_protect(sdmmc_chipset_handle_t);
192 static int	sdhc_bus_power(sdmmc_chipset_handle_t, uint32_t);
193 static int	sdhc_bus_clock_ddr(sdmmc_chipset_handle_t, int, bool);
194 static int	sdhc_bus_width(sdmmc_chipset_handle_t, int);
195 static int	sdhc_bus_rod(sdmmc_chipset_handle_t, int);
196 static void	sdhc_card_enable_intr(sdmmc_chipset_handle_t, int);
197 static void	sdhc_card_intr_ack(sdmmc_chipset_handle_t);
198 static void	sdhc_exec_command(sdmmc_chipset_handle_t,
199 		    struct sdmmc_command *);
200 static int	sdhc_signal_voltage(sdmmc_chipset_handle_t, int);
201 static int	sdhc_execute_tuning1(struct sdhc_host *, int);
202 static int	sdhc_execute_tuning(sdmmc_chipset_handle_t, int);
203 static void	sdhc_tuning_timer(void *);
204 static void	sdhc_hw_reset(sdmmc_chipset_handle_t);
205 static int	sdhc_start_command(struct sdhc_host *, struct sdmmc_command *);
206 static int	sdhc_wait_state(struct sdhc_host *, uint32_t, uint32_t);
207 static int	sdhc_soft_reset(struct sdhc_host *, int);
208 static int	sdhc_wait_intr(struct sdhc_host *, int, int, bool);
209 static void	sdhc_transfer_data(struct sdhc_host *, struct sdmmc_command *);
210 static int	sdhc_transfer_data_dma(struct sdhc_host *, struct sdmmc_command *);
211 static int	sdhc_transfer_data_pio(struct sdhc_host *, struct sdmmc_command *);
212 static void	sdhc_read_data_pio(struct sdhc_host *, uint8_t *, u_int);
213 static void	sdhc_write_data_pio(struct sdhc_host *, uint8_t *, u_int);
214 static void	esdhc_read_data_pio(struct sdhc_host *, uint8_t *, u_int);
215 static void	esdhc_write_data_pio(struct sdhc_host *, uint8_t *, u_int);
216 
217 static struct sdmmc_chip_functions sdhc_functions = {
218 	/* host controller reset */
219 	.host_reset = sdhc_host_reset,
220 
221 	/* host controller capabilities */
222 	.host_ocr = sdhc_host_ocr,
223 	.host_maxblklen = sdhc_host_maxblklen,
224 
225 	/* card detection */
226 	.card_detect = sdhc_card_detect,
227 
228 	/* write protect */
229 	.write_protect = sdhc_write_protect,
230 
231 	/* bus power, clock frequency, width and ROD(OpenDrain/PushPull) */
232 	.bus_power = sdhc_bus_power,
233 	.bus_clock = NULL,	/* see sdhc_bus_clock_ddr */
234 	.bus_width = sdhc_bus_width,
235 	.bus_rod = sdhc_bus_rod,
236 
237 	/* command execution */
238 	.exec_command = sdhc_exec_command,
239 
240 	/* card interrupt */
241 	.card_enable_intr = sdhc_card_enable_intr,
242 	.card_intr_ack = sdhc_card_intr_ack,
243 
244 	/* UHS functions */
245 	.signal_voltage = sdhc_signal_voltage,
246 	.bus_clock_ddr = sdhc_bus_clock_ddr,
247 	.execute_tuning = sdhc_execute_tuning,
248 	.hw_reset = sdhc_hw_reset,
249 };
250 
251 static int
252 sdhc_cfprint(void *aux, const char *pnp)
253 {
254 	const struct sdmmcbus_attach_args * const saa = aux;
255 	const struct sdhc_host * const hp = saa->saa_sch;
256 
257 	if (pnp) {
258 		aprint_normal("sdmmc at %s", pnp);
259 	}
260 	for (size_t host = 0; host < hp->sc->sc_nhosts; host++) {
261 		if (hp->sc->sc_host[host] == hp) {
262 			aprint_normal(" slot %zu", host);
263 		}
264 	}
265 
266 	return UNCONF;
267 }
268 
269 /*
270  * Called by attachment driver.  For each SD card slot there is one SD
271  * host controller standard register set. (1.3)
272  */
273 int
274 sdhc_host_found(struct sdhc_softc *sc, bus_space_tag_t iot,
275     bus_space_handle_t ioh, bus_size_t iosize)
276 {
277 	struct sdmmcbus_attach_args saa;
278 	struct sdhc_host *hp;
279 	uint32_t caps, caps2;
280 	uint16_t sdhcver;
281 	int error;
282 
283 	/* Allocate one more host structure. */
284 	hp = malloc(sizeof(struct sdhc_host), M_DEVBUF, M_WAITOK|M_ZERO);
285 	if (hp == NULL) {
286 		aprint_error_dev(sc->sc_dev,
287 		    "couldn't alloc memory (sdhc host)\n");
288 		goto err1;
289 	}
290 	sc->sc_host[sc->sc_nhosts++] = hp;
291 
292 	/* Fill in the new host structure. */
293 	hp->sc = sc;
294 	hp->iot = iot;
295 	hp->ioh = ioh;
296 	hp->ios = iosize;
297 	hp->dmat = sc->sc_dmat;
298 
299 	mutex_init(&hp->intr_lock, MUTEX_DEFAULT, IPL_SDMMC);
300 	mutex_init(&hp->bus_clock_lock, MUTEX_DEFAULT, IPL_NONE);
301 	cv_init(&hp->intr_cv, "sdhcintr");
302 	callout_init(&hp->tuning_timer, CALLOUT_MPSAFE);
303 	callout_setfunc(&hp->tuning_timer, sdhc_tuning_timer, hp);
304 
305 	if (ISSET(hp->sc->sc_flags, SDHC_FLAG_USDHC)) {
306 		sdhcver = SDHC_SPEC_VERS_300 << SDHC_SPEC_VERS_SHIFT;
307 	} else if (ISSET(hp->sc->sc_flags, SDHC_FLAG_ENHANCED)) {
308 		sdhcver = HREAD4(hp, SDHC_ESDHC_HOST_CTL_VERSION);
309 	} else if (iosize <= SDHC_HOST_CTL_VERSION) {
310 		sdhcver = SDHC_SPEC_NOVERS << SDHC_SPEC_VERS_SHIFT;
311 	} else {
312 		sdhcver = HREAD2(hp, SDHC_HOST_CTL_VERSION);
313 	}
314 	aprint_normal_dev(sc->sc_dev, "SDHC ");
315 	hp->specver = SDHC_SPEC_VERSION(sdhcver);
316 	switch (SDHC_SPEC_VERSION(sdhcver)) {
317 	case SDHC_SPEC_VERS_100:
318 		aprint_normal("1.0");
319 		break;
320 	case SDHC_SPEC_VERS_200:
321 		aprint_normal("2.0");
322 		break;
323 	case SDHC_SPEC_VERS_300:
324 		aprint_normal("3.0");
325 		break;
326 	case SDHC_SPEC_VERS_400:
327 		aprint_normal("4.0");
328 		break;
329 	case SDHC_SPEC_VERS_410:
330 		aprint_normal("4.1");
331 		break;
332 	case SDHC_SPEC_VERS_420:
333 		aprint_normal("4.2");
334 		break;
335 	case SDHC_SPEC_NOVERS:
336 		hp->specver = -1;
337 		aprint_normal("NO-VERS");
338 		break;
339 	default:
340 		aprint_normal("unknown version(0x%x)",
341 		    SDHC_SPEC_VERSION(sdhcver));
342 		break;
343 	}
344 	if (SDHC_SPEC_VERSION(sdhcver) != SDHC_SPEC_NOVERS)
345 		aprint_normal(", rev %u", SDHC_VENDOR_VERSION(sdhcver));
346 
347 	/*
348 	 * Reset the host controller and enable interrupts.
349 	 */
350 	(void)sdhc_host_reset(hp);
351 
352 	if (ISSET(hp->sc->sc_flags, SDHC_FLAG_USDHC)) {
353 		/* init uSDHC registers */
354 		HWRITE4(hp, SDHC_MMC_BOOT, 0);
355 		HWRITE4(hp, SDHC_HOST_CTL, SDHC_USDHC_BURST_LEN_EN |
356 		    SDHC_USDHC_HOST_CTL_RESV23 | SDHC_USDHC_EMODE_LE);
357 		HWRITE4(hp, SDHC_WATERMARK_LEVEL,
358 		    (0x10 << SDHC_WATERMARK_WR_BRST_SHIFT) |
359 		    (0x40 << SDHC_WATERMARK_WRITE_SHIFT) |
360 		    (0x10 << SDHC_WATERMARK_RD_BRST_SHIFT) |
361 		    (0x40 << SDHC_WATERMARK_READ_SHIFT));
362 		HSET4(hp, SDHC_VEND_SPEC,
363 		    SDHC_VEND_SPEC_MBO |
364 		    SDHC_VEND_SPEC_CARD_CLK_SOFT_EN |
365 		    SDHC_VEND_SPEC_IPG_PERCLK_SOFT_EN |
366 		    SDHC_VEND_SPEC_HCLK_SOFT_EN |
367 		    SDHC_VEND_SPEC_IPG_CLK_SOFT_EN |
368 		    SDHC_VEND_SPEC_AC12_WR_CHKBUSY_EN |
369 		    SDHC_VEND_SPEC_FRC_SDCLK_ON);
370 	}
371 
372 	/* Determine host capabilities. */
373 	if (ISSET(sc->sc_flags, SDHC_FLAG_HOSTCAPS)) {
374 		caps = sc->sc_caps;
375 		caps2 = sc->sc_caps2;
376 	} else if (ISSET(hp->sc->sc_flags, SDHC_FLAG_USDHC)) {
377 		/* uSDHC capability register is little bit different */
378 		caps = HREAD4(hp, SDHC_CAPABILITIES);
379 		caps |= SDHC_8BIT_SUPP;
380 		if (caps & SDHC_ADMA1_SUPP)
381 			caps |= SDHC_ADMA2_SUPP;
382 		sc->sc_caps = caps;
383 		/* uSDHC has no SDHC_CAPABILITIES2 register */
384 		caps2 = sc->sc_caps2 = SDHC_SDR50_SUPP | SDHC_DDR50_SUPP;
385 	} else {
386 		caps = sc->sc_caps = HREAD4(hp, SDHC_CAPABILITIES);
387 		if (hp->specver >= SDHC_SPEC_VERS_300) {
388 			caps2 = sc->sc_caps2 = HREAD4(hp, SDHC_CAPABILITIES2);
389 		} else {
390 			caps2 = sc->sc_caps2 = 0;
391 		}
392 	}
393 
394 	aprint_verbose(", caps <%08x/%08x>", caps, caps2);
395 
396 	const u_int retuning_mode = (caps2 >> SDHC_RETUNING_MODES_SHIFT) &
397 	    SDHC_RETUNING_MODES_MASK;
398 	if (retuning_mode == SDHC_RETUNING_MODE_1) {
399 		hp->tuning_timer_count = (caps2 >> SDHC_TIMER_COUNT_SHIFT) &
400 		    SDHC_TIMER_COUNT_MASK;
401 		if (hp->tuning_timer_count == 0xf)
402 			hp->tuning_timer_count = 0;
403 		if (hp->tuning_timer_count)
404 			hp->tuning_timer_count =
405 			    1 << (hp->tuning_timer_count - 1);
406 	}
407 
408 	/*
409 	 * Use DMA if the host system and the controller support it.
410 	 * Supports integrated or external DMA egine, with or without
411 	 * SDHC_DMA_ENABLE in the command.
412 	 */
413 	if (ISSET(sc->sc_flags, SDHC_FLAG_FORCE_DMA) ||
414 	    (ISSET(sc->sc_flags, SDHC_FLAG_USE_DMA &&
415 	     ISSET(caps, SDHC_DMA_SUPPORT)))) {
416 		SET(hp->flags, SHF_USE_DMA);
417 
418 		if (ISSET(caps, SDHC_ADMA2_SUPP)) {
419 			SET(hp->flags, SHF_MODE_DMAEN);
420 			/*
421 			 * 64-bit mode was present in the 2.00 spec, removed
422 			 * from 3.00, and re-added in 4.00 with a different
423 			 * descriptor layout. We only support 2.00 and 3.00
424 			 * descriptors for now.
425 			 */
426 			if (hp->specver == SDHC_SPEC_VERS_200 &&
427 			    ISSET(caps, SDHC_64BIT_SYS_BUS)) {
428 				SET(hp->flags, SHF_USE_ADMA2_64);
429 				aprint_normal(", 64-bit ADMA2");
430 			} else {
431 				SET(hp->flags, SHF_USE_ADMA2_32);
432 				aprint_normal(", 32-bit ADMA2");
433 			}
434 		} else {
435 			if (!ISSET(sc->sc_flags, SDHC_FLAG_EXTERNAL_DMA) ||
436 			    ISSET(sc->sc_flags, SDHC_FLAG_EXTDMA_DMAEN))
437 				SET(hp->flags, SHF_MODE_DMAEN);
438 			if (sc->sc_vendor_transfer_data_dma) {
439 				aprint_normal(", platform DMA");
440 			} else {
441 				aprint_normal(", SDMA");
442 			}
443 		}
444 	} else {
445 		aprint_normal(", PIO");
446 	}
447 
448 	/*
449 	 * Determine the base clock frequency. (2.2.24)
450 	 */
451 	if (hp->specver >= SDHC_SPEC_VERS_300) {
452 		hp->clkbase = SDHC_BASE_V3_FREQ_KHZ(caps);
453 	} else {
454 		hp->clkbase = SDHC_BASE_FREQ_KHZ(caps);
455 	}
456 	if (hp->clkbase == 0 ||
457 	    ISSET(sc->sc_flags, SDHC_FLAG_NO_CLKBASE)) {
458 		if (sc->sc_clkbase == 0) {
459 			/* The attachment driver must tell us. */
460 			aprint_error_dev(sc->sc_dev,
461 			    "unknown base clock frequency\n");
462 			goto err;
463 		}
464 		hp->clkbase = sc->sc_clkbase;
465 	}
466 	if (hp->clkbase < 10000 || hp->clkbase > 10000 * 256) {
467 		/* SDHC 1.0 supports only 10-63 MHz. */
468 		aprint_error_dev(sc->sc_dev,
469 		    "base clock frequency out of range: %u MHz\n",
470 		    hp->clkbase / 1000);
471 		goto err;
472 	}
473 	aprint_normal(", %u kHz", hp->clkbase);
474 
475 	/*
476 	 * XXX Set the data timeout counter value according to
477 	 * capabilities. (2.2.15)
478 	 */
479 	HWRITE1(hp, SDHC_TIMEOUT_CTL, SDHC_TIMEOUT_MAX);
480 #if 1
481 	if (ISSET(hp->sc->sc_flags, SDHC_FLAG_ENHANCED))
482 		HWRITE4(hp, SDHC_NINTR_STATUS, SDHC_CMD_TIMEOUT_ERROR << 16);
483 #endif
484 
485 	if (ISSET(caps, SDHC_EMBEDDED_SLOT))
486 		aprint_normal(", embedded slot");
487 
488 	/*
489 	 * Determine SD bus voltage levels supported by the controller.
490 	 */
491 	aprint_normal(",");
492 	if (ISSET(caps, SDHC_HIGH_SPEED_SUPP)) {
493 		SET(hp->ocr, MMC_OCR_HCS);
494 		aprint_normal(" HS");
495 	}
496 	if (!ISSET(hp->sc->sc_flags, SDHC_FLAG_NO_1_8_V)) {
497 		if (ISSET(caps2, SDHC_SDR50_SUPP)) {
498 			SET(hp->ocr, MMC_OCR_S18A);
499 			aprint_normal(" SDR50");
500 		}
501 		if (ISSET(caps2, SDHC_DDR50_SUPP)) {
502 			SET(hp->ocr, MMC_OCR_S18A);
503 			aprint_normal(" DDR50");
504 		}
505 		if (ISSET(caps2, SDHC_SDR104_SUPP)) {
506 			SET(hp->ocr, MMC_OCR_S18A);
507 			aprint_normal(" SDR104 HS200");
508 		}
509 		if (ISSET(caps, SDHC_VOLTAGE_SUPP_1_8V)) {
510 			SET(hp->ocr, MMC_OCR_1_65V_1_95V);
511 			aprint_normal(" 1.8V");
512 		}
513 	}
514 	if (ISSET(caps, SDHC_VOLTAGE_SUPP_3_0V)) {
515 		SET(hp->ocr, MMC_OCR_2_9V_3_0V | MMC_OCR_3_0V_3_1V);
516 		aprint_normal(" 3.0V");
517 	}
518 	if (ISSET(caps, SDHC_VOLTAGE_SUPP_3_3V)) {
519 		SET(hp->ocr, MMC_OCR_3_2V_3_3V | MMC_OCR_3_3V_3_4V);
520 		aprint_normal(" 3.3V");
521 	}
522 	if (hp->specver >= SDHC_SPEC_VERS_300) {
523 		aprint_normal(", re-tuning mode %d", retuning_mode + 1);
524 		if (hp->tuning_timer_count)
525 			aprint_normal(" (%us timer)", hp->tuning_timer_count);
526 	}
527 
528 	/*
529 	 * Determine the maximum block length supported by the host
530 	 * controller. (2.2.24)
531 	 */
532 	switch((caps >> SDHC_MAX_BLK_LEN_SHIFT) & SDHC_MAX_BLK_LEN_MASK) {
533 	case SDHC_MAX_BLK_LEN_512:
534 		hp->maxblklen = 512;
535 		break;
536 
537 	case SDHC_MAX_BLK_LEN_1024:
538 		hp->maxblklen = 1024;
539 		break;
540 
541 	case SDHC_MAX_BLK_LEN_2048:
542 		hp->maxblklen = 2048;
543 		break;
544 
545 	case SDHC_MAX_BLK_LEN_4096:
546 		hp->maxblklen = 4096;
547 		break;
548 
549 	default:
550 		aprint_error_dev(sc->sc_dev, "max block length unknown\n");
551 		goto err;
552 	}
553 	aprint_normal(", %u byte blocks", hp->maxblklen);
554 	aprint_normal("\n");
555 
556 	if (ISSET(hp->flags, SHF_USE_ADMA2_MASK)) {
557 		int rseg;
558 
559 		/* Allocate ADMA2 descriptor memory */
560 		error = bus_dmamem_alloc(sc->sc_dmat, PAGE_SIZE, PAGE_SIZE,
561 		    PAGE_SIZE, hp->adma_segs, 1, &rseg, BUS_DMA_WAITOK);
562 		if (error) {
563 			aprint_error_dev(sc->sc_dev,
564 			    "ADMA2 dmamem_alloc failed (%d)\n", error);
565 			goto adma_done;
566 		}
567 		error = bus_dmamem_map(sc->sc_dmat, hp->adma_segs, rseg,
568 		    PAGE_SIZE, (void **)&hp->adma2, BUS_DMA_WAITOK);
569 		if (error) {
570 			aprint_error_dev(sc->sc_dev,
571 			    "ADMA2 dmamem_map failed (%d)\n", error);
572 			goto adma_done;
573 		}
574 		error = bus_dmamap_create(sc->sc_dmat, PAGE_SIZE, 1, PAGE_SIZE,
575 		    0, BUS_DMA_WAITOK, &hp->adma_map);
576 		if (error) {
577 			aprint_error_dev(sc->sc_dev,
578 			    "ADMA2 dmamap_create failed (%d)\n", error);
579 			goto adma_done;
580 		}
581 		error = bus_dmamap_load(sc->sc_dmat, hp->adma_map,
582 		    hp->adma2, PAGE_SIZE, NULL,
583 		    BUS_DMA_WAITOK|BUS_DMA_WRITE);
584 		if (error) {
585 			aprint_error_dev(sc->sc_dev,
586 			    "ADMA2 dmamap_load failed (%d)\n", error);
587 			goto adma_done;
588 		}
589 
590 		memset(hp->adma2, 0, PAGE_SIZE);
591 
592 adma_done:
593 		if (error)
594 			CLR(hp->flags, SHF_USE_ADMA2_MASK);
595 	}
596 
597 	/*
598 	 * Attach the generic SD/MMC bus driver.  (The bus driver must
599 	 * not invoke any chipset functions before it is attached.)
600 	 */
601 	memset(&saa, 0, sizeof(saa));
602 	saa.saa_busname = "sdmmc";
603 	saa.saa_sct = &sdhc_functions;
604 	saa.saa_sch = hp;
605 	saa.saa_dmat = hp->dmat;
606 	saa.saa_clkmax = hp->clkbase;
607 	if (ISSET(sc->sc_flags, SDHC_FLAG_HAVE_CGM))
608 		saa.saa_clkmin = hp->clkbase / 256 / 2046;
609 	else if (ISSET(sc->sc_flags, SDHC_FLAG_HAVE_DVS))
610 		saa.saa_clkmin = hp->clkbase / 256 / 16;
611 	else if (hp->sc->sc_clkmsk != 0)
612 		saa.saa_clkmin = hp->clkbase / (hp->sc->sc_clkmsk >>
613 		    (ffs(hp->sc->sc_clkmsk) - 1));
614 	else if (hp->specver >= SDHC_SPEC_VERS_300)
615 		saa.saa_clkmin = hp->clkbase / 0x3ff;
616 	else
617 		saa.saa_clkmin = hp->clkbase / 256;
618 	if (!ISSET(sc->sc_flags, SDHC_FLAG_NO_AUTO_STOP))
619 		saa.saa_caps |= SMC_CAPS_AUTO_STOP;
620 	saa.saa_caps |= SMC_CAPS_4BIT_MODE;
621 	if (ISSET(sc->sc_flags, SDHC_FLAG_8BIT_MODE))
622 		saa.saa_caps |= SMC_CAPS_8BIT_MODE;
623 	if (ISSET(caps, SDHC_HIGH_SPEED_SUPP))
624 		saa.saa_caps |= SMC_CAPS_SD_HIGHSPEED |
625 				SMC_CAPS_MMC_HIGHSPEED;
626 	if (ISSET(caps2, SDHC_SDR104_SUPP))
627 		saa.saa_caps |= SMC_CAPS_UHS_SDR104 |
628 				SMC_CAPS_UHS_SDR50 |
629 				SMC_CAPS_MMC_HS200;
630 	if (ISSET(caps2, SDHC_SDR50_SUPP))
631 		saa.saa_caps |= SMC_CAPS_UHS_SDR50;
632 	if (ISSET(caps2, SDHC_DDR50_SUPP))
633 		saa.saa_caps |= SMC_CAPS_UHS_DDR50;
634 	if (ISSET(hp->flags, SHF_USE_DMA)) {
635 		saa.saa_caps |= SMC_CAPS_DMA;
636 		if (!ISSET(hp->sc->sc_flags, SDHC_FLAG_ENHANCED))
637 			saa.saa_caps |= SMC_CAPS_MULTI_SEG_DMA;
638 	}
639 	if (ISSET(sc->sc_flags, SDHC_FLAG_SINGLE_ONLY))
640 		saa.saa_caps |= SMC_CAPS_SINGLE_ONLY;
641 	if (ISSET(sc->sc_flags, SDHC_FLAG_POLL_CARD_DET))
642 		saa.saa_caps |= SMC_CAPS_POLL_CARD_DET;
643 
644 	if (ISSET(sc->sc_flags, SDHC_FLAG_BROKEN_ADMA2_ZEROLEN))
645 		saa.saa_max_seg = 65535;
646 
647 	hp->sdmmc = config_found(sc->sc_dev, &saa, sdhc_cfprint, CFARGS_NONE);
648 
649 	return 0;
650 
651 err:
652 	callout_destroy(&hp->tuning_timer);
653 	cv_destroy(&hp->intr_cv);
654 	mutex_destroy(&hp->bus_clock_lock);
655 	mutex_destroy(&hp->intr_lock);
656 	free(hp, M_DEVBUF);
657 	sc->sc_host[--sc->sc_nhosts] = NULL;
658 err1:
659 	return 1;
660 }
661 
662 int
663 sdhc_detach(struct sdhc_softc *sc, int flags)
664 {
665 	struct sdhc_host *hp;
666 	int rv = 0;
667 
668 	for (size_t n = 0; n < sc->sc_nhosts; n++) {
669 		hp = sc->sc_host[n];
670 		if (hp == NULL)
671 			continue;
672 		if (hp->sdmmc != NULL) {
673 			rv = config_detach(hp->sdmmc, flags);
674 			if (rv)
675 				break;
676 			hp->sdmmc = NULL;
677 		}
678 		/* disable interrupts */
679 		if ((flags & DETACH_FORCE) == 0) {
680 			mutex_enter(&hp->intr_lock);
681 			if (ISSET(hp->sc->sc_flags, SDHC_FLAG_32BIT_ACCESS)) {
682 				HWRITE4(hp, SDHC_NINTR_SIGNAL_EN, 0);
683 			} else {
684 				HWRITE2(hp, SDHC_NINTR_SIGNAL_EN, 0);
685 			}
686 			sdhc_soft_reset(hp, SDHC_RESET_ALL);
687 			mutex_exit(&hp->intr_lock);
688 		}
689 		callout_halt(&hp->tuning_timer, NULL);
690 		callout_destroy(&hp->tuning_timer);
691 		cv_destroy(&hp->intr_cv);
692 		mutex_destroy(&hp->intr_lock);
693 		if (hp->ios > 0) {
694 			bus_space_unmap(hp->iot, hp->ioh, hp->ios);
695 			hp->ios = 0;
696 		}
697 		if (ISSET(hp->flags, SHF_USE_ADMA2_MASK)) {
698 			bus_dmamap_unload(sc->sc_dmat, hp->adma_map);
699 			bus_dmamap_destroy(sc->sc_dmat, hp->adma_map);
700 			bus_dmamem_unmap(sc->sc_dmat, hp->adma2, PAGE_SIZE);
701 			bus_dmamem_free(sc->sc_dmat, hp->adma_segs, 1);
702 		}
703 		free(hp, M_DEVBUF);
704 		sc->sc_host[n] = NULL;
705 	}
706 
707 	return rv;
708 }
709 
710 bool
711 sdhc_suspend(device_t dev, const pmf_qual_t *qual)
712 {
713 	struct sdhc_softc *sc = device_private(dev);
714 	struct sdhc_host *hp;
715 	size_t i;
716 
717 	/* XXX poll for command completion or suspend command
718 	 * in progress */
719 
720 	/* Save the host controller state. */
721 	for (size_t n = 0; n < sc->sc_nhosts; n++) {
722 		hp = sc->sc_host[n];
723 		if (ISSET(sc->sc_flags, SDHC_FLAG_32BIT_ACCESS)) {
724 			for (i = 0; i < sizeof hp->regs; i += 4) {
725 				uint32_t v = HREAD4(hp, i);
726 				hp->regs[i + 0] = (v >> 0);
727 				hp->regs[i + 1] = (v >> 8);
728 				if (i + 3 < sizeof hp->regs) {
729 					hp->regs[i + 2] = (v >> 16);
730 					hp->regs[i + 3] = (v >> 24);
731 				}
732 			}
733 		} else {
734 			for (i = 0; i < sizeof hp->regs; i++) {
735 				hp->regs[i] = HREAD1(hp, i);
736 			}
737 		}
738 	}
739 	return true;
740 }
741 
742 bool
743 sdhc_resume(device_t dev, const pmf_qual_t *qual)
744 {
745 	struct sdhc_softc *sc = device_private(dev);
746 	struct sdhc_host *hp;
747 	size_t i;
748 
749 	/* Restore the host controller state. */
750 	for (size_t n = 0; n < sc->sc_nhosts; n++) {
751 		hp = sc->sc_host[n];
752 		(void)sdhc_host_reset(hp);
753 		if (ISSET(sc->sc_flags, SDHC_FLAG_32BIT_ACCESS)) {
754 			for (i = 0; i < sizeof hp->regs; i += 4) {
755 				if (i + 3 < sizeof hp->regs) {
756 					HWRITE4(hp, i,
757 					    (hp->regs[i + 0] << 0)
758 					    | (hp->regs[i + 1] << 8)
759 					    | (hp->regs[i + 2] << 16)
760 					    | (hp->regs[i + 3] << 24));
761 				} else {
762 					HWRITE4(hp, i,
763 					    (hp->regs[i + 0] << 0)
764 					    | (hp->regs[i + 1] << 8));
765 				}
766 			}
767 		} else {
768 			for (i = 0; i < sizeof hp->regs; i++) {
769 				HWRITE1(hp, i, hp->regs[i]);
770 			}
771 		}
772 	}
773 	return true;
774 }
775 
776 bool
777 sdhc_shutdown(device_t dev, int flags)
778 {
779 	struct sdhc_softc *sc = device_private(dev);
780 	struct sdhc_host *hp;
781 
782 	/* XXX chip locks up if we don't disable it before reboot. */
783 	for (size_t i = 0; i < sc->sc_nhosts; i++) {
784 		hp = sc->sc_host[i];
785 		(void)sdhc_host_reset(hp);
786 	}
787 	return true;
788 }
789 
790 /*
791  * Reset the host controller.  Called during initialization, when
792  * cards are removed, upon resume, and during error recovery.
793  */
794 static int
795 sdhc_host_reset1(sdmmc_chipset_handle_t sch)
796 {
797 	struct sdhc_host *hp = (struct sdhc_host *)sch;
798 	uint32_t sdhcimask;
799 	int error;
800 
801 	KASSERT(mutex_owned(&hp->intr_lock));
802 
803 	/* Disable all interrupts. */
804 	if (ISSET(hp->sc->sc_flags, SDHC_FLAG_32BIT_ACCESS)) {
805 		HWRITE4(hp, SDHC_NINTR_SIGNAL_EN, 0);
806 	} else {
807 		HWRITE2(hp, SDHC_NINTR_SIGNAL_EN, 0);
808 	}
809 
810 	/* Let sdhc_bus_power restore power */
811 	hp->vdd = 0;
812 
813 	/*
814 	 * Reset the entire host controller and wait up to 100ms for
815 	 * the controller to clear the reset bit.
816 	 */
817 	error = sdhc_soft_reset(hp, SDHC_RESET_ALL);
818 	if (error)
819 		goto out;
820 
821 	/* Set data timeout counter value to max for now. */
822 	HWRITE1(hp, SDHC_TIMEOUT_CTL, SDHC_TIMEOUT_MAX);
823 #if 1
824 	if (ISSET(hp->sc->sc_flags, SDHC_FLAG_ENHANCED))
825 		HWRITE4(hp, SDHC_NINTR_STATUS, SDHC_CMD_TIMEOUT_ERROR << 16);
826 #endif
827 
828 	/* Enable interrupts. */
829 	sdhcimask = SDHC_CARD_REMOVAL | SDHC_CARD_INSERTION |
830 	    SDHC_BUFFER_READ_READY | SDHC_BUFFER_WRITE_READY |
831 	    SDHC_DMA_INTERRUPT | SDHC_BLOCK_GAP_EVENT |
832 	    SDHC_TRANSFER_COMPLETE | SDHC_COMMAND_COMPLETE;
833 	if (ISSET(hp->sc->sc_flags, SDHC_FLAG_32BIT_ACCESS)) {
834 		sdhcimask |= SDHC_EINTR_STATUS_MASK << 16;
835 		HWRITE4(hp, SDHC_NINTR_STATUS_EN, sdhcimask);
836 		sdhcimask ^=
837 		    (SDHC_EINTR_STATUS_MASK ^ SDHC_EINTR_SIGNAL_MASK) << 16;
838 		sdhcimask ^= SDHC_BUFFER_READ_READY ^ SDHC_BUFFER_WRITE_READY;
839 		HWRITE4(hp, SDHC_NINTR_SIGNAL_EN, sdhcimask);
840 	} else {
841 		HWRITE2(hp, SDHC_NINTR_STATUS_EN, sdhcimask);
842 		HWRITE2(hp, SDHC_EINTR_STATUS_EN, SDHC_EINTR_STATUS_MASK);
843 		sdhcimask ^= SDHC_BUFFER_READ_READY ^ SDHC_BUFFER_WRITE_READY;
844 		HWRITE2(hp, SDHC_NINTR_SIGNAL_EN, sdhcimask);
845 		HWRITE2(hp, SDHC_EINTR_SIGNAL_EN, SDHC_EINTR_SIGNAL_MASK);
846 	}
847 
848 out:
849 	return error;
850 }
851 
852 static int
853 sdhc_host_reset(sdmmc_chipset_handle_t sch)
854 {
855 	struct sdhc_host *hp = (struct sdhc_host *)sch;
856 	int error;
857 
858 	mutex_enter(&hp->intr_lock);
859 	error = sdhc_host_reset1(sch);
860 	mutex_exit(&hp->intr_lock);
861 
862 	return error;
863 }
864 
865 static uint32_t
866 sdhc_host_ocr(sdmmc_chipset_handle_t sch)
867 {
868 	struct sdhc_host *hp = (struct sdhc_host *)sch;
869 
870 	return hp->ocr;
871 }
872 
873 static int
874 sdhc_host_maxblklen(sdmmc_chipset_handle_t sch)
875 {
876 	struct sdhc_host *hp = (struct sdhc_host *)sch;
877 
878 	return hp->maxblklen;
879 }
880 
881 /*
882  * Return non-zero if the card is currently inserted.
883  */
884 static int
885 sdhc_card_detect(sdmmc_chipset_handle_t sch)
886 {
887 	struct sdhc_host *hp = (struct sdhc_host *)sch;
888 	int r;
889 
890 	if (hp->sc->sc_vendor_card_detect)
891 		return (*hp->sc->sc_vendor_card_detect)(hp->sc);
892 
893 	r = ISSET(HREAD4(hp, SDHC_PRESENT_STATE), SDHC_CARD_INSERTED);
894 
895 	return r ? 1 : 0;
896 }
897 
898 /*
899  * Return non-zero if the card is currently write-protected.
900  */
901 static int
902 sdhc_write_protect(sdmmc_chipset_handle_t sch)
903 {
904 	struct sdhc_host *hp = (struct sdhc_host *)sch;
905 	int r;
906 
907 	if (hp->sc->sc_vendor_write_protect)
908 		return (*hp->sc->sc_vendor_write_protect)(hp->sc);
909 
910 	r = ISSET(HREAD4(hp, SDHC_PRESENT_STATE), SDHC_WRITE_PROTECT_SWITCH);
911 
912 	return r ? 0 : 1;
913 }
914 
915 /*
916  * Set or change SD bus voltage and enable or disable SD bus power.
917  * Return zero on success.
918  */
919 static int
920 sdhc_bus_power(sdmmc_chipset_handle_t sch, uint32_t ocr)
921 {
922 	struct sdhc_host *hp = (struct sdhc_host *)sch;
923 	uint8_t vdd;
924 	int error = 0;
925 	const uint32_t pcmask =
926 	    ~(SDHC_BUS_POWER | (SDHC_VOLTAGE_MASK << SDHC_VOLTAGE_SHIFT));
927 	uint32_t reg;
928 
929 	mutex_enter(&hp->intr_lock);
930 
931 	/*
932 	 * Disable bus power before voltage change.
933 	 */
934 	if (!ISSET(hp->sc->sc_flags, SDHC_FLAG_32BIT_ACCESS)
935 	    && !ISSET(hp->sc->sc_flags, SDHC_FLAG_NO_PWR0)) {
936 		hp->vdd = 0;
937 		HWRITE1(hp, SDHC_POWER_CTL, 0);
938 	}
939 
940 	/* If power is disabled, reset the host and return now. */
941 	if (ocr == 0) {
942 		(void)sdhc_host_reset1(hp);
943 		callout_halt(&hp->tuning_timer, &hp->intr_lock);
944 		goto out;
945 	}
946 
947 	/*
948 	 * Select the lowest voltage according to capabilities.
949 	 */
950 	ocr &= hp->ocr;
951 	if (ISSET(ocr, MMC_OCR_1_65V_1_95V)) {
952 		vdd = SDHC_VOLTAGE_1_8V;
953 	} else if (ISSET(ocr, MMC_OCR_2_9V_3_0V|MMC_OCR_3_0V_3_1V)) {
954 		vdd = SDHC_VOLTAGE_3_0V;
955 	} else if (ISSET(ocr, MMC_OCR_3_2V_3_3V|MMC_OCR_3_3V_3_4V)) {
956 		vdd = SDHC_VOLTAGE_3_3V;
957 	} else {
958 		/* Unsupported voltage level requested. */
959 		error = EINVAL;
960 		goto out;
961 	}
962 
963 	/*
964 	 * Did voltage change ?
965 	 */
966 	if (vdd == hp->vdd)
967 		goto out;
968 
969 	if (!ISSET(hp->sc->sc_flags, SDHC_FLAG_ENHANCED)) {
970 		/*
971 		 * Enable bus power.  Wait at least 1 ms (or 74 clocks) plus
972 		 * voltage ramp until power rises.
973 		 */
974 
975 		if (ISSET(hp->sc->sc_flags, SDHC_FLAG_SINGLE_POWER_WRITE)) {
976 			HWRITE1(hp, SDHC_POWER_CTL,
977 			    (vdd << SDHC_VOLTAGE_SHIFT) | SDHC_BUS_POWER);
978 		} else {
979 			reg = HREAD1(hp, SDHC_POWER_CTL) & pcmask;
980 			HWRITE1(hp, SDHC_POWER_CTL, reg);
981 			sdmmc_delay(1);
982 			reg |= (vdd << SDHC_VOLTAGE_SHIFT);
983 			HWRITE1(hp, SDHC_POWER_CTL, reg);
984 			sdmmc_delay(1);
985 			reg |= SDHC_BUS_POWER;
986 			HWRITE1(hp, SDHC_POWER_CTL, reg);
987 			sdmmc_delay(10000);
988 		}
989 
990 		/*
991 		 * The host system may not power the bus due to battery low,
992 		 * etc.  In that case, the host controller should clear the
993 		 * bus power bit.
994 		 */
995 		if (!ISSET(HREAD1(hp, SDHC_POWER_CTL), SDHC_BUS_POWER)) {
996 			error = ENXIO;
997 			goto out;
998 		}
999 	}
1000 
1001 	/* power successfully changed */
1002 	hp->vdd = vdd;
1003 
1004 out:
1005 	mutex_exit(&hp->intr_lock);
1006 
1007 	return error;
1008 }
1009 
1010 /*
1011  * Return the smallest possible base clock frequency divisor value
1012  * for the CLOCK_CTL register to produce `freq' (KHz).
1013  */
1014 static bool
1015 sdhc_clock_divisor(struct sdhc_host *hp, u_int freq, u_int *divp)
1016 {
1017 	u_int div;
1018 
1019 	if (ISSET(hp->sc->sc_flags, SDHC_FLAG_HAVE_CGM)) {
1020 		for (div = hp->clkbase / freq; div <= 0x3ff; div++) {
1021 			if ((hp->clkbase / div) <= freq) {
1022 				*divp = SDHC_SDCLK_CGM
1023 				    | ((div & 0x300) << SDHC_SDCLK_XDIV_SHIFT)
1024 				    | ((div & 0x0ff) << SDHC_SDCLK_DIV_SHIFT);
1025 				//freq = hp->clkbase / div;
1026 				return true;
1027 			}
1028 		}
1029 		/* No divisor found. */
1030 		return false;
1031 	}
1032 	if (ISSET(hp->sc->sc_flags, SDHC_FLAG_HAVE_DVS)) {
1033 		u_int dvs = (hp->clkbase + freq - 1) / freq;
1034 		u_int roundup = dvs & 1;
1035 		for (dvs >>= 1, div = 1; div <= 256; div <<= 1, dvs >>= 1) {
1036 			if (dvs + roundup <= 16) {
1037 				dvs += roundup - 1;
1038 				*divp = (div << SDHC_SDCLK_DIV_SHIFT)
1039 				    |   (dvs << SDHC_SDCLK_DVS_SHIFT);
1040 				DPRINTF(2,
1041 				    ("%s: divisor for freq %u is %u * %u\n",
1042 				    HDEVNAME(hp), freq, div * 2, dvs + 1));
1043 				//freq = hp->clkbase / (div * 2) * (dvs + 1);
1044 				return true;
1045 			}
1046 			/*
1047 			 * If we drop bits, we need to round up the divisor.
1048 			 */
1049 			roundup |= dvs & 1;
1050 		}
1051 		/* No divisor found. */
1052 		return false;
1053 	}
1054 	if (hp->sc->sc_clkmsk != 0) {
1055 		div = howmany(hp->clkbase, freq);
1056 		if (div > (hp->sc->sc_clkmsk >> (ffs(hp->sc->sc_clkmsk) - 1)))
1057 			return false;
1058 		*divp = div << (ffs(hp->sc->sc_clkmsk) - 1);
1059 		//freq = hp->clkbase / div;
1060 		return true;
1061 	}
1062 	if (hp->specver >= SDHC_SPEC_VERS_300) {
1063 		div = howmany(hp->clkbase, freq);
1064 		div = div > 1 ? howmany(div, 2) : 0;
1065 		if (div > 0x3ff)
1066 			return false;
1067 		*divp = (((div >> 8) & SDHC_SDCLK_XDIV_MASK)
1068 			 << SDHC_SDCLK_XDIV_SHIFT) |
1069 			(((div >> 0) & SDHC_SDCLK_DIV_MASK)
1070 			 << SDHC_SDCLK_DIV_SHIFT);
1071 		//freq = hp->clkbase / (div ? div * 2 : 1);
1072 		return true;
1073 	} else {
1074 		for (div = 1; div <= 256; div *= 2) {
1075 			if ((hp->clkbase / div) <= freq) {
1076 				*divp = (div / 2) << SDHC_SDCLK_DIV_SHIFT;
1077 				//freq = hp->clkbase / div;
1078 				return true;
1079 			}
1080 		}
1081 		/* No divisor found. */
1082 		return false;
1083 	}
1084 	/* No divisor found. */
1085 	return false;
1086 }
1087 
1088 /*
1089  * Set or change SDCLK frequency or disable the SD clock.
1090  * Return zero on success.
1091  */
1092 static int
1093 sdhc_bus_clock_ddr(sdmmc_chipset_handle_t sch, int freq, bool ddr)
1094 {
1095 	struct sdhc_host *hp = (struct sdhc_host *)sch;
1096 	u_int div;
1097 	u_int timo;
1098 	int16_t reg;
1099 	int error = 0;
1100 	bool present __diagused;
1101 
1102 #ifdef DIAGNOSTIC
1103 	present = ISSET(HREAD4(hp, SDHC_PRESENT_STATE), SDHC_CMD_INHIBIT_MASK);
1104 
1105 	/* Must not stop the clock if commands are in progress. */
1106 	if (present && sdhc_card_detect(hp)) {
1107 		aprint_normal_dev(hp->sc->sc_dev,
1108 		    "%s: command in progress\n", __func__);
1109 	}
1110 #endif
1111 
1112 	if (hp->sc->sc_vendor_bus_clock) {
1113 		mutex_enter(&hp->bus_clock_lock);
1114 		error = (*hp->sc->sc_vendor_bus_clock)(hp->sc, freq);
1115 		mutex_exit(&hp->bus_clock_lock);
1116 		if (error != 0)
1117 			return error;
1118 	}
1119 
1120 	mutex_enter(&hp->intr_lock);
1121 
1122 	/*
1123 	 * Stop SD clock before changing the frequency.
1124 	 */
1125 	if (ISSET(hp->sc->sc_flags, SDHC_FLAG_USDHC)) {
1126 		HCLR4(hp, SDHC_VEND_SPEC,
1127 		    SDHC_VEND_SPEC_CARD_CLK_SOFT_EN |
1128 		    SDHC_VEND_SPEC_FRC_SDCLK_ON);
1129 		if (freq == SDMMC_SDCLK_OFF) {
1130 			goto out;
1131 		}
1132 	} else if (ISSET(hp->sc->sc_flags, SDHC_FLAG_ENHANCED)) {
1133 		HCLR4(hp, SDHC_CLOCK_CTL, 0xfff8);
1134 		if (freq == SDMMC_SDCLK_OFF) {
1135 			HSET4(hp, SDHC_CLOCK_CTL, 0x80f0);
1136 			goto out;
1137 		}
1138 	} else {
1139 		HCLR2(hp, SDHC_CLOCK_CTL, SDHC_SDCLK_ENABLE);
1140 		if (freq == SDMMC_SDCLK_OFF)
1141 			goto out;
1142 	}
1143 
1144 	if (ISSET(hp->sc->sc_flags, SDHC_FLAG_USDHC)) {
1145 		if (ddr)
1146 			HSET4(hp, SDHC_MIX_CTRL, SDHC_USDHC_DDR_EN);
1147 		else
1148 			HCLR4(hp, SDHC_MIX_CTRL, SDHC_USDHC_DDR_EN);
1149 	} else if (hp->specver >= SDHC_SPEC_VERS_300) {
1150 		HCLR2(hp, SDHC_HOST_CTL2, SDHC_UHS_MODE_SELECT_MASK);
1151 		if (freq > 100000) {
1152 			HSET2(hp, SDHC_HOST_CTL2, SDHC_UHS_MODE_SELECT_SDR104);
1153 		} else if (freq > 50000) {
1154 			if (ddr) {
1155 				HSET2(hp, SDHC_HOST_CTL2,
1156 				    SDHC_UHS_MODE_SELECT_DDR50);
1157 			} else {
1158 				HSET2(hp, SDHC_HOST_CTL2,
1159 				    SDHC_UHS_MODE_SELECT_SDR50);
1160 			}
1161 		} else if (freq > 25000) {
1162 			if (ddr) {
1163 				HSET2(hp, SDHC_HOST_CTL2,
1164 				    SDHC_UHS_MODE_SELECT_DDR50);
1165 			} else {
1166 				HSET2(hp, SDHC_HOST_CTL2,
1167 				    SDHC_UHS_MODE_SELECT_SDR25);
1168 			}
1169 		} else if (freq > 400) {
1170 			HSET2(hp, SDHC_HOST_CTL2, SDHC_UHS_MODE_SELECT_SDR12);
1171 		}
1172 	}
1173 
1174 	/*
1175 	 * Slow down Ricoh 5U823 controller that isn't reliable
1176 	 * at 100MHz bus clock.
1177 	 */
1178 	if (ISSET(hp->sc->sc_flags, SDHC_FLAG_SLOW_SDR50)) {
1179 		if (freq == 100000)
1180 			--freq;
1181 	}
1182 
1183 	/*
1184 	 * Set the minimum base clock frequency divisor.
1185 	 */
1186 	if (!sdhc_clock_divisor(hp, freq, &div)) {
1187 		/* Invalid base clock frequency or `freq' value. */
1188 		aprint_error_dev(hp->sc->sc_dev,
1189 			"Invalid bus clock %d kHz\n", freq);
1190 		error = EINVAL;
1191 		goto out;
1192 	}
1193 	if (ISSET(hp->sc->sc_flags, SDHC_FLAG_USDHC)) {
1194 		if (ddr) {
1195 			/* in ddr mode, divisor >>= 1 */
1196 			div = ((div >> 1) & (SDHC_SDCLK_DIV_MASK <<
1197 			    SDHC_SDCLK_DIV_SHIFT)) |
1198 			    (div & (SDHC_SDCLK_DVS_MASK <<
1199 			    SDHC_SDCLK_DVS_SHIFT));
1200 		}
1201 		for (timo = 1000; timo > 0; timo--) {
1202 			if (ISSET(HREAD4(hp, SDHC_PRESENT_STATE), SDHC_SDSTB))
1203 				break;
1204 			sdmmc_delay(10);
1205 		}
1206 		HWRITE4(hp, SDHC_CLOCK_CTL,
1207 		    div | (SDHC_TIMEOUT_MAX << 16) | 0x0f);
1208 	} else if (ISSET(hp->sc->sc_flags, SDHC_FLAG_ENHANCED)) {
1209 		HWRITE4(hp, SDHC_CLOCK_CTL,
1210 		    div | (SDHC_TIMEOUT_MAX << 16));
1211 	} else {
1212 		reg = HREAD2(hp, SDHC_CLOCK_CTL);
1213 		reg &= (SDHC_INTCLK_STABLE | SDHC_INTCLK_ENABLE);
1214 		HWRITE2(hp, SDHC_CLOCK_CTL, reg | div);
1215 	}
1216 
1217 	/*
1218 	 * Start internal clock.  Wait 10ms for stabilization.
1219 	 */
1220 	if (ISSET(hp->sc->sc_flags, SDHC_FLAG_USDHC)) {
1221 		HSET4(hp, SDHC_VEND_SPEC,
1222 		    SDHC_VEND_SPEC_CARD_CLK_SOFT_EN |
1223 		    SDHC_VEND_SPEC_FRC_SDCLK_ON);
1224 	} else if (ISSET(hp->sc->sc_flags, SDHC_FLAG_ENHANCED)) {
1225 		sdmmc_delay(10000);
1226 		HSET4(hp, SDHC_CLOCK_CTL,
1227 		    8 | SDHC_INTCLK_ENABLE | SDHC_INTCLK_STABLE);
1228 	} else {
1229 		HSET2(hp, SDHC_CLOCK_CTL, SDHC_INTCLK_ENABLE);
1230 		for (timo = 1000; timo > 0; timo--) {
1231 			if (ISSET(HREAD2(hp, SDHC_CLOCK_CTL),
1232 			    SDHC_INTCLK_STABLE))
1233 				break;
1234 			sdmmc_delay(10);
1235 		}
1236 		if (timo == 0) {
1237 			error = ETIMEDOUT;
1238 			DPRINTF(1,("%s: timeout\n", __func__));
1239 			goto out;
1240 		}
1241 	}
1242 
1243 	if (ISSET(hp->sc->sc_flags, SDHC_FLAG_ENHANCED | SDHC_FLAG_USDHC)) {
1244 		HSET1(hp, SDHC_SOFTWARE_RESET, SDHC_INIT_ACTIVE);
1245 		/*
1246 		 * Sending 80 clocks at 400kHz takes 200us.
1247 		 * So delay for that time + slop and then
1248 		 * check a few times for completion.
1249 		 */
1250 		sdmmc_delay(210);
1251 		for (timo = 10; timo > 0; timo--) {
1252 			if (!ISSET(HREAD1(hp, SDHC_SOFTWARE_RESET),
1253 			    SDHC_INIT_ACTIVE))
1254 				break;
1255 			sdmmc_delay(10);
1256 		}
1257 		DPRINTF(2,("%s: %u init spins\n", __func__, 10 - timo));
1258 
1259 		/*
1260 		 * Enable SD clock.
1261 		 */
1262 		if (ISSET(hp->sc->sc_flags, SDHC_FLAG_USDHC)) {
1263 			HSET4(hp, SDHC_VEND_SPEC,
1264 			    SDHC_VEND_SPEC_CARD_CLK_SOFT_EN |
1265 			    SDHC_VEND_SPEC_FRC_SDCLK_ON);
1266 		} else {
1267 			HSET4(hp, SDHC_CLOCK_CTL, SDHC_SDCLK_ENABLE);
1268 		}
1269 	} else {
1270 		/*
1271 		 * Enable SD clock.
1272 		 */
1273 		HSET2(hp, SDHC_CLOCK_CTL, SDHC_SDCLK_ENABLE);
1274 
1275 		if (freq > 25000 &&
1276 		    !ISSET(hp->sc->sc_flags, SDHC_FLAG_NO_HS_BIT))
1277 			HSET1(hp, SDHC_HOST_CTL, SDHC_HIGH_SPEED);
1278 		else
1279 			HCLR1(hp, SDHC_HOST_CTL, SDHC_HIGH_SPEED);
1280 	}
1281 
1282 	mutex_exit(&hp->intr_lock);
1283 
1284 	if (hp->sc->sc_vendor_bus_clock_post) {
1285 		mutex_enter(&hp->bus_clock_lock);
1286 		error = (*hp->sc->sc_vendor_bus_clock_post)(hp->sc, freq);
1287 		mutex_exit(&hp->bus_clock_lock);
1288 	}
1289 	return error;
1290 
1291 out:
1292 	mutex_exit(&hp->intr_lock);
1293 
1294 	return error;
1295 }
1296 
1297 static int
1298 sdhc_bus_width(sdmmc_chipset_handle_t sch, int width)
1299 {
1300 	struct sdhc_host *hp = (struct sdhc_host *)sch;
1301 	int reg;
1302 
1303 	switch (width) {
1304 	case 1:
1305 	case 4:
1306 		break;
1307 
1308 	case 8:
1309 		if (ISSET(hp->sc->sc_flags, SDHC_FLAG_8BIT_MODE))
1310 			break;
1311 		/* FALLTHROUGH */
1312 	default:
1313 		DPRINTF(0,("%s: unsupported bus width (%d)\n",
1314 		    HDEVNAME(hp), width));
1315 		return 1;
1316 	}
1317 
1318 	if (hp->sc->sc_vendor_bus_width) {
1319 		const int error = hp->sc->sc_vendor_bus_width(hp->sc, width);
1320 		if (error != 0)
1321 			return error;
1322 	}
1323 
1324 	mutex_enter(&hp->intr_lock);
1325 
1326 	reg = HREAD1(hp, SDHC_HOST_CTL);
1327 	if (ISSET(hp->sc->sc_flags, SDHC_FLAG_ENHANCED | SDHC_FLAG_USDHC)) {
1328 		reg &= ~(SDHC_4BIT_MODE|SDHC_ESDHC_8BIT_MODE);
1329 		if (width == 4)
1330 			reg |= SDHC_4BIT_MODE;
1331 		else if (width == 8)
1332 			reg |= SDHC_ESDHC_8BIT_MODE;
1333 	} else {
1334 		reg &= ~SDHC_4BIT_MODE;
1335 		if (hp->specver >= SDHC_SPEC_VERS_300) {
1336 			reg &= ~SDHC_8BIT_MODE;
1337 		}
1338 		if (width == 4) {
1339 			reg |= SDHC_4BIT_MODE;
1340 		} else if (width == 8 && hp->specver >= SDHC_SPEC_VERS_300) {
1341 			reg |= SDHC_8BIT_MODE;
1342 		}
1343 	}
1344 	HWRITE1(hp, SDHC_HOST_CTL, reg);
1345 
1346 	mutex_exit(&hp->intr_lock);
1347 
1348 	return 0;
1349 }
1350 
1351 static int
1352 sdhc_bus_rod(sdmmc_chipset_handle_t sch, int on)
1353 {
1354 	struct sdhc_host *hp = (struct sdhc_host *)sch;
1355 
1356 	if (hp->sc->sc_vendor_rod)
1357 		return (*hp->sc->sc_vendor_rod)(hp->sc, on);
1358 
1359 	return 0;
1360 }
1361 
1362 static void
1363 sdhc_card_enable_intr(sdmmc_chipset_handle_t sch, int enable)
1364 {
1365 	struct sdhc_host *hp = (struct sdhc_host *)sch;
1366 
1367 	if (!ISSET(hp->sc->sc_flags, SDHC_FLAG_ENHANCED | SDHC_FLAG_USDHC)) {
1368 		mutex_enter(&hp->intr_lock);
1369 		if (enable) {
1370 			HSET2(hp, SDHC_NINTR_STATUS_EN, SDHC_CARD_INTERRUPT);
1371 			HSET2(hp, SDHC_NINTR_SIGNAL_EN, SDHC_CARD_INTERRUPT);
1372 		} else {
1373 			HCLR2(hp, SDHC_NINTR_SIGNAL_EN, SDHC_CARD_INTERRUPT);
1374 			HCLR2(hp, SDHC_NINTR_STATUS_EN, SDHC_CARD_INTERRUPT);
1375 		}
1376 		mutex_exit(&hp->intr_lock);
1377 	}
1378 }
1379 
1380 static void
1381 sdhc_card_intr_ack(sdmmc_chipset_handle_t sch)
1382 {
1383 	struct sdhc_host *hp = (struct sdhc_host *)sch;
1384 
1385 	if (!ISSET(hp->sc->sc_flags, SDHC_FLAG_ENHANCED | SDHC_FLAG_USDHC)) {
1386 		mutex_enter(&hp->intr_lock);
1387 		HSET2(hp, SDHC_NINTR_STATUS_EN, SDHC_CARD_INTERRUPT);
1388 		mutex_exit(&hp->intr_lock);
1389 	}
1390 }
1391 
1392 static int
1393 sdhc_signal_voltage(sdmmc_chipset_handle_t sch, int signal_voltage)
1394 {
1395 	struct sdhc_host *hp = (struct sdhc_host *)sch;
1396 	int error = 0;
1397 
1398 	if (hp->specver < SDHC_SPEC_VERS_300)
1399 		return EINVAL;
1400 
1401 	mutex_enter(&hp->intr_lock);
1402 	switch (signal_voltage) {
1403 	case SDMMC_SIGNAL_VOLTAGE_180:
1404 		if (hp->sc->sc_vendor_signal_voltage != NULL) {
1405 			error = hp->sc->sc_vendor_signal_voltage(hp->sc,
1406 			    signal_voltage);
1407 			if (error != 0)
1408 				break;
1409 		}
1410 		if (!ISSET(hp->sc->sc_flags, SDHC_FLAG_USDHC))
1411 			HSET2(hp, SDHC_HOST_CTL2, SDHC_1_8V_SIGNAL_EN);
1412 		break;
1413 	case SDMMC_SIGNAL_VOLTAGE_330:
1414 		if (!ISSET(hp->sc->sc_flags, SDHC_FLAG_USDHC))
1415 			HCLR2(hp, SDHC_HOST_CTL2, SDHC_1_8V_SIGNAL_EN);
1416 		if (hp->sc->sc_vendor_signal_voltage != NULL) {
1417 			error = hp->sc->sc_vendor_signal_voltage(hp->sc,
1418 			    signal_voltage);
1419 			if (error != 0)
1420 				break;
1421 		}
1422 		break;
1423 	default:
1424 		error = EINVAL;
1425 		break;
1426 	}
1427 	mutex_exit(&hp->intr_lock);
1428 
1429 	return error;
1430 }
1431 
1432 /*
1433  * Sampling clock tuning procedure (UHS)
1434  */
1435 static int
1436 sdhc_execute_tuning1(struct sdhc_host *hp, int timing)
1437 {
1438 	struct sdmmc_command cmd;
1439 	uint8_t hostctl;
1440 	int opcode, error, retry = 40;
1441 
1442 	KASSERT(mutex_owned(&hp->intr_lock));
1443 
1444 	hp->tuning_timing = timing;
1445 
1446 	switch (timing) {
1447 	case SDMMC_TIMING_MMC_HS200:
1448 		opcode = MMC_SEND_TUNING_BLOCK_HS200;
1449 		break;
1450 	case SDMMC_TIMING_UHS_SDR50:
1451 		if (!ISSET(hp->sc->sc_caps2, SDHC_TUNING_SDR50))
1452 			return 0;
1453 		/* FALLTHROUGH */
1454 	case SDMMC_TIMING_UHS_SDR104:
1455 		opcode = MMC_SEND_TUNING_BLOCK;
1456 		break;
1457 	default:
1458 		return EINVAL;
1459 	}
1460 
1461 	hostctl = HREAD1(hp, SDHC_HOST_CTL);
1462 
1463 	/* enable buffer read ready interrupt */
1464 	HSET2(hp, SDHC_NINTR_SIGNAL_EN, SDHC_BUFFER_READ_READY);
1465 	HSET2(hp, SDHC_NINTR_STATUS_EN, SDHC_BUFFER_READ_READY);
1466 
1467 	/* disable DMA */
1468 	HCLR1(hp, SDHC_HOST_CTL, SDHC_DMA_SELECT);
1469 
1470 	/* reset tuning circuit */
1471 	HCLR2(hp, SDHC_HOST_CTL2, SDHC_SAMPLING_CLOCK_SEL);
1472 
1473 	/* start of tuning */
1474 	HWRITE2(hp, SDHC_HOST_CTL2, SDHC_EXECUTE_TUNING);
1475 
1476 	do {
1477 		memset(&cmd, 0, sizeof(cmd));
1478 		cmd.c_opcode = opcode;
1479 		cmd.c_arg = 0;
1480 		cmd.c_flags = SCF_CMD_ADTC | SCF_CMD_READ | SCF_RSP_R1;
1481 		if (ISSET(hostctl, SDHC_8BIT_MODE)) {
1482 			cmd.c_blklen = cmd.c_datalen = 128;
1483 		} else {
1484 			cmd.c_blklen = cmd.c_datalen = 64;
1485 		}
1486 
1487 		error = sdhc_start_command(hp, &cmd);
1488 		if (error)
1489 			break;
1490 
1491 		if (!sdhc_wait_intr(hp, SDHC_BUFFER_READ_READY,
1492 		    SDHC_TUNING_TIMEOUT, false)) {
1493 			break;
1494 		}
1495 
1496 		delay(1000);
1497 	} while (HREAD2(hp, SDHC_HOST_CTL2) & SDHC_EXECUTE_TUNING && --retry);
1498 
1499 	/* disable buffer read ready interrupt */
1500 	HCLR2(hp, SDHC_NINTR_SIGNAL_EN, SDHC_BUFFER_READ_READY);
1501 	HCLR2(hp, SDHC_NINTR_STATUS_EN, SDHC_BUFFER_READ_READY);
1502 
1503 	if (HREAD2(hp, SDHC_HOST_CTL2) & SDHC_EXECUTE_TUNING) {
1504 		HCLR2(hp, SDHC_HOST_CTL2,
1505 		    SDHC_SAMPLING_CLOCK_SEL|SDHC_EXECUTE_TUNING);
1506 		sdhc_soft_reset(hp, SDHC_RESET_DAT|SDHC_RESET_CMD);
1507 		aprint_error_dev(hp->sc->sc_dev,
1508 		    "tuning did not complete, using fixed sampling clock\n");
1509 		return 0;		/* tuning did not complete */
1510 	}
1511 
1512 	if ((HREAD2(hp, SDHC_HOST_CTL2) & SDHC_SAMPLING_CLOCK_SEL) == 0) {
1513 		HCLR2(hp, SDHC_HOST_CTL2,
1514 		    SDHC_SAMPLING_CLOCK_SEL|SDHC_EXECUTE_TUNING);
1515 		sdhc_soft_reset(hp, SDHC_RESET_DAT|SDHC_RESET_CMD);
1516 		aprint_error_dev(hp->sc->sc_dev,
1517 		    "tuning failed, using fixed sampling clock\n");
1518 		return 0;		/* tuning failed */
1519 	}
1520 
1521 	if (hp->tuning_timer_count) {
1522 		callout_schedule(&hp->tuning_timer,
1523 		    hz * hp->tuning_timer_count);
1524 	}
1525 
1526 	return 0;		/* tuning completed */
1527 }
1528 
1529 static int
1530 sdhc_execute_tuning(sdmmc_chipset_handle_t sch, int timing)
1531 {
1532 	struct sdhc_host *hp = (struct sdhc_host *)sch;
1533 	int error;
1534 
1535 	mutex_enter(&hp->intr_lock);
1536 	error = sdhc_execute_tuning1(hp, timing);
1537 	mutex_exit(&hp->intr_lock);
1538 	return error;
1539 }
1540 
1541 static void
1542 sdhc_tuning_timer(void *arg)
1543 {
1544 	struct sdhc_host *hp = arg;
1545 
1546 	atomic_swap_uint(&hp->tuning_timer_pending, 1);
1547 }
1548 
1549 static void
1550 sdhc_hw_reset(sdmmc_chipset_handle_t sch)
1551 {
1552 	struct sdhc_host *hp = (struct sdhc_host *)sch;
1553 	struct sdhc_softc *sc = hp->sc;
1554 
1555 	if (sc->sc_vendor_hw_reset != NULL)
1556 		sc->sc_vendor_hw_reset(sc, hp);
1557 }
1558 
1559 static int
1560 sdhc_wait_state(struct sdhc_host *hp, uint32_t mask, uint32_t value)
1561 {
1562 	uint32_t state;
1563 	int timeout;
1564 
1565 	for (timeout = 100000; timeout > 0; timeout--) {
1566 		if (((state = HREAD4(hp, SDHC_PRESENT_STATE)) & mask) == value)
1567 			return 0;
1568 		sdmmc_delay(10);
1569 	}
1570 	aprint_error_dev(hp->sc->sc_dev, "timeout waiting for mask %#x value %#x (state=%#x)\n",
1571 	    mask, value, state);
1572 	return ETIMEDOUT;
1573 }
1574 
1575 static void
1576 sdhc_exec_command(sdmmc_chipset_handle_t sch, struct sdmmc_command *cmd)
1577 {
1578 	struct sdhc_host *hp = (struct sdhc_host *)sch;
1579 	int error;
1580 	bool probing;
1581 
1582 	mutex_enter(&hp->intr_lock);
1583 
1584 	if (atomic_cas_uint(&hp->tuning_timer_pending, 1, 0) == 1) {
1585 		(void)sdhc_execute_tuning1(hp, hp->tuning_timing);
1586 	}
1587 
1588 	if (cmd->c_data &&
1589 	    ISSET(hp->sc->sc_flags, SDHC_FLAG_ENHANCED | SDHC_FLAG_USDHC)) {
1590 		const uint16_t ready = SDHC_BUFFER_READ_READY | SDHC_BUFFER_WRITE_READY;
1591 		if (ISSET(hp->flags, SHF_USE_DMA)) {
1592 			HCLR2(hp, SDHC_NINTR_SIGNAL_EN, ready);
1593 			HCLR2(hp, SDHC_NINTR_STATUS_EN, ready);
1594 		} else {
1595 			HSET2(hp, SDHC_NINTR_SIGNAL_EN, ready);
1596 			HSET2(hp, SDHC_NINTR_STATUS_EN, ready);
1597 		}
1598 	}
1599 
1600 	if (ISSET(hp->sc->sc_flags, SDHC_FLAG_NO_TIMEOUT)) {
1601 		const uint16_t eintr = SDHC_CMD_TIMEOUT_ERROR;
1602 		if (cmd->c_data != NULL) {
1603 			HCLR2(hp, SDHC_EINTR_SIGNAL_EN, eintr);
1604 			HCLR2(hp, SDHC_EINTR_STATUS_EN, eintr);
1605 		} else {
1606 			HSET2(hp, SDHC_EINTR_SIGNAL_EN, eintr);
1607 			HSET2(hp, SDHC_EINTR_STATUS_EN, eintr);
1608 		}
1609 	}
1610 
1611 	if (ISSET(hp->sc->sc_flags, SDHC_FLAG_STOP_WITH_TC)) {
1612 		if (cmd->c_opcode == MMC_STOP_TRANSMISSION)
1613 			SET(cmd->c_flags, SCF_RSP_BSY);
1614 	}
1615 
1616 	/*
1617 	 * Start the MMC command, or mark `cmd' as failed and return.
1618 	 */
1619 	error = sdhc_start_command(hp, cmd);
1620 	if (error) {
1621 		cmd->c_error = error;
1622 		goto out;
1623 	}
1624 
1625 	/*
1626 	 * Wait until the command phase is done, or until the command
1627 	 * is marked done for any other reason.
1628 	 */
1629 	probing = (cmd->c_flags & SCF_TOUT_OK) != 0;
1630 	if (!sdhc_wait_intr(hp, SDHC_COMMAND_COMPLETE, SDHC_COMMAND_TIMEOUT*3, probing)) {
1631 		DPRINTF(1,("%s: timeout for command\n", __func__));
1632 		sdmmc_delay(50);
1633 		cmd->c_error = ETIMEDOUT;
1634 		goto out;
1635 	}
1636 
1637 	/*
1638 	 * The host controller removes bits [0:7] from the response
1639 	 * data (CRC) and we pass the data up unchanged to the bus
1640 	 * driver (without padding).
1641 	 */
1642 	if (cmd->c_error == 0 && ISSET(cmd->c_flags, SCF_RSP_PRESENT)) {
1643 		cmd->c_resp[0] = HREAD4(hp, SDHC_RESPONSE + 0);
1644 		if (ISSET(cmd->c_flags, SCF_RSP_136)) {
1645 			cmd->c_resp[1] = HREAD4(hp, SDHC_RESPONSE + 4);
1646 			cmd->c_resp[2] = HREAD4(hp, SDHC_RESPONSE + 8);
1647 			cmd->c_resp[3] = HREAD4(hp, SDHC_RESPONSE + 12);
1648 			if (ISSET(hp->sc->sc_flags, SDHC_FLAG_RSP136_CRC)) {
1649 				cmd->c_resp[0] = (cmd->c_resp[0] >> 8) |
1650 				    (cmd->c_resp[1] << 24);
1651 				cmd->c_resp[1] = (cmd->c_resp[1] >> 8) |
1652 				    (cmd->c_resp[2] << 24);
1653 				cmd->c_resp[2] = (cmd->c_resp[2] >> 8) |
1654 				    (cmd->c_resp[3] << 24);
1655 				cmd->c_resp[3] = (cmd->c_resp[3] >> 8);
1656 			}
1657 		}
1658 	}
1659 	DPRINTF(1,("%s: resp = %08x\n", HDEVNAME(hp), cmd->c_resp[0]));
1660 
1661 	/*
1662 	 * If the command has data to transfer in any direction,
1663 	 * execute the transfer now.
1664 	 */
1665 	if (cmd->c_error == 0 && cmd->c_data != NULL)
1666 		sdhc_transfer_data(hp, cmd);
1667 	else if (ISSET(cmd->c_flags, SCF_RSP_BSY)) {
1668 		if (!ISSET(hp->sc->sc_flags, SDHC_FLAG_NO_BUSY_INTR) &&
1669 		    !sdhc_wait_intr(hp, SDHC_TRANSFER_COMPLETE, hz * 10, false)) {
1670 			DPRINTF(1,("%s: sdhc_exec_command: RSP_BSY\n",
1671 			    HDEVNAME(hp)));
1672 			cmd->c_error = ETIMEDOUT;
1673 			goto out;
1674 		}
1675 	}
1676 
1677 out:
1678 	if (!ISSET(hp->sc->sc_flags, SDHC_FLAG_ENHANCED)
1679 	    && !ISSET(hp->sc->sc_flags, SDHC_FLAG_NO_LED_ON)) {
1680 		/* Turn off the LED. */
1681 		HCLR1(hp, SDHC_HOST_CTL, SDHC_LED_ON);
1682 	}
1683 	SET(cmd->c_flags, SCF_ITSDONE);
1684 
1685 	if (ISSET(hp->sc->sc_flags, SDHC_FLAG_NO_AUTO_STOP) &&
1686 	    cmd->c_opcode == MMC_STOP_TRANSMISSION)
1687 		(void)sdhc_soft_reset(hp, SDHC_RESET_CMD|SDHC_RESET_DAT);
1688 
1689 	mutex_exit(&hp->intr_lock);
1690 
1691 	DPRINTF(1,("%s: cmd %d %s (flags=%08x error=%d)\n", HDEVNAME(hp),
1692 	    cmd->c_opcode, (cmd->c_error == 0) ? "done" : "abort",
1693 	    cmd->c_flags, cmd->c_error));
1694 }
1695 
1696 static int
1697 sdhc_start_command(struct sdhc_host *hp, struct sdmmc_command *cmd)
1698 {
1699 	struct sdhc_softc * const sc = hp->sc;
1700 	uint16_t blksize = 0;
1701 	uint16_t blkcount = 0;
1702 	uint16_t mode;
1703 	uint16_t command;
1704 	uint32_t pmask;
1705 	int error;
1706 
1707 	KASSERT(mutex_owned(&hp->intr_lock));
1708 
1709 	DPRINTF(1,("%s: start cmd %d arg=%08x data=%p dlen=%d flags=%08x, status=%#x\n",
1710 	    HDEVNAME(hp), cmd->c_opcode, cmd->c_arg, cmd->c_data,
1711 	    cmd->c_datalen, cmd->c_flags, HREAD4(hp, SDHC_NINTR_STATUS)));
1712 
1713 	/*
1714 	 * The maximum block length for commands should be the minimum
1715 	 * of the host buffer size and the card buffer size. (1.7.2)
1716 	 */
1717 
1718 	/* Fragment the data into proper blocks. */
1719 	if (cmd->c_datalen > 0) {
1720 		blksize = MIN(cmd->c_datalen, cmd->c_blklen);
1721 		blkcount = cmd->c_datalen / blksize;
1722 		if (cmd->c_datalen % blksize > 0) {
1723 			/* XXX: Split this command. (1.7.4) */
1724 			aprint_error_dev(sc->sc_dev,
1725 			    "data not a multiple of %u bytes\n", blksize);
1726 			return EINVAL;
1727 		}
1728 	}
1729 
1730 	/* Check limit imposed by 9-bit block count. (1.7.2) */
1731 	if (blkcount > SDHC_BLOCK_COUNT_MAX) {
1732 		aprint_error_dev(sc->sc_dev, "too much data\n");
1733 		return EINVAL;
1734 	}
1735 
1736 	/* Prepare transfer mode register value. (2.2.5) */
1737 	mode = 0;
1738 	if (ISSET(cmd->c_flags, SCF_CMD_READ))
1739 		mode |= SDHC_READ_MODE;
1740 	if (blkcount > 0) {
1741 		mode |= SDHC_BLOCK_COUNT_ENABLE;
1742 		if (blkcount > 1) {
1743 			mode |= SDHC_MULTI_BLOCK_MODE;
1744 			if (!ISSET(sc->sc_flags, SDHC_FLAG_NO_AUTO_STOP)
1745 			    && !ISSET(cmd->c_flags, SCF_NO_STOP))
1746 				mode |= SDHC_AUTO_CMD12_ENABLE;
1747 		}
1748 	}
1749 	if (cmd->c_dmamap != NULL && cmd->c_datalen > 0 &&
1750 	    ISSET(hp->flags,  SHF_MODE_DMAEN)) {
1751 		mode |= SDHC_DMA_ENABLE;
1752 	}
1753 
1754 	/*
1755 	 * Prepare command register value. (2.2.6)
1756 	 */
1757 	command = (cmd->c_opcode & SDHC_COMMAND_INDEX_MASK) << SDHC_COMMAND_INDEX_SHIFT;
1758 
1759 	if (ISSET(cmd->c_flags, SCF_RSP_CRC))
1760 		command |= SDHC_CRC_CHECK_ENABLE;
1761 	if (ISSET(cmd->c_flags, SCF_RSP_IDX))
1762 		command |= SDHC_INDEX_CHECK_ENABLE;
1763 	if (cmd->c_datalen > 0)
1764 		command |= SDHC_DATA_PRESENT_SELECT;
1765 
1766 	if (!ISSET(cmd->c_flags, SCF_RSP_PRESENT))
1767 		command |= SDHC_NO_RESPONSE;
1768 	else if (ISSET(cmd->c_flags, SCF_RSP_136))
1769 		command |= SDHC_RESP_LEN_136;
1770 	else if (ISSET(cmd->c_flags, SCF_RSP_BSY))
1771 		command |= SDHC_RESP_LEN_48_CHK_BUSY;
1772 	else
1773 		command |= SDHC_RESP_LEN_48;
1774 
1775 	/* Wait until command and optionally data inhibit bits are clear. (1.5) */
1776 	pmask = SDHC_CMD_INHIBIT_CMD;
1777 	if (cmd->c_flags & (SCF_CMD_ADTC|SCF_RSP_BSY))
1778 		pmask |= SDHC_CMD_INHIBIT_DAT;
1779 	error = sdhc_wait_state(hp, pmask, 0);
1780 	if (error) {
1781 		(void) sdhc_soft_reset(hp, SDHC_RESET_DAT|SDHC_RESET_CMD);
1782 		device_printf(sc->sc_dev, "command or data phase inhibited\n");
1783 		return error;
1784 	}
1785 
1786 	DPRINTF(1,("%s: writing cmd: blksize=%d blkcnt=%d mode=%04x cmd=%04x\n",
1787 	    HDEVNAME(hp), blksize, blkcount, mode, command));
1788 
1789 	if (!ISSET(hp->sc->sc_flags, SDHC_FLAG_ENHANCED | SDHC_FLAG_USDHC)) {
1790 		blksize |= (MAX(0, PAGE_SHIFT - 12) & SDHC_DMA_BOUNDARY_MASK) <<
1791 		    SDHC_DMA_BOUNDARY_SHIFT;	/* PAGE_SIZE DMA boundary */
1792 	}
1793 
1794 	if (!ISSET(hp->sc->sc_flags, SDHC_FLAG_ENHANCED)) {
1795 		/* Alert the user not to remove the card. */
1796 		HSET1(hp, SDHC_HOST_CTL, SDHC_LED_ON);
1797 	}
1798 
1799 	/* Set DMA start address. */
1800 	if (ISSET(hp->flags, SHF_USE_ADMA2_MASK) && cmd->c_data != NULL) {
1801 		for (int seg = 0; seg < cmd->c_dmamap->dm_nsegs; seg++) {
1802 			bus_addr_t paddr =
1803 			    cmd->c_dmamap->dm_segs[seg].ds_addr;
1804 			uint16_t len =
1805 			    cmd->c_dmamap->dm_segs[seg].ds_len == 65536 ?
1806 			    0 : cmd->c_dmamap->dm_segs[seg].ds_len;
1807 			uint16_t attr =
1808 			    SDHC_ADMA2_VALID | SDHC_ADMA2_ACT_TRANS;
1809 			if (seg == cmd->c_dmamap->dm_nsegs - 1) {
1810 				attr |= SDHC_ADMA2_END;
1811 			}
1812 			if (ISSET(hp->flags, SHF_USE_ADMA2_32)) {
1813 				struct sdhc_adma2_descriptor32 *desc =
1814 				    hp->adma2;
1815 				desc[seg].attribute = htole16(attr);
1816 				desc[seg].length = htole16(len);
1817 				desc[seg].address = htole32(paddr);
1818 			} else {
1819 				struct sdhc_adma2_descriptor64 *desc =
1820 				    hp->adma2;
1821 				desc[seg].attribute = htole16(attr);
1822 				desc[seg].length = htole16(len);
1823 				desc[seg].address = htole32(paddr & 0xffffffff);
1824 				desc[seg].address_hi = htole32(
1825 				    (uint64_t)paddr >> 32);
1826 			}
1827 		}
1828 		if (ISSET(hp->flags, SHF_USE_ADMA2_32)) {
1829 			struct sdhc_adma2_descriptor32 *desc = hp->adma2;
1830 			desc[cmd->c_dmamap->dm_nsegs].attribute = htole16(0);
1831 		} else {
1832 			struct sdhc_adma2_descriptor64 *desc = hp->adma2;
1833 			desc[cmd->c_dmamap->dm_nsegs].attribute = htole16(0);
1834 		}
1835 		bus_dmamap_sync(sc->sc_dmat, hp->adma_map, 0, PAGE_SIZE,
1836 		    BUS_DMASYNC_PREWRITE);
1837 		if (ISSET(hp->sc->sc_flags, SDHC_FLAG_USDHC)) {
1838 			HCLR4(hp, SDHC_HOST_CTL, SDHC_USDHC_DMA_SELECT);
1839 			HSET4(hp, SDHC_HOST_CTL, SDHC_USDHC_DMA_SELECT_ADMA2);
1840 		} else {
1841 			HCLR1(hp, SDHC_HOST_CTL, SDHC_DMA_SELECT);
1842 			HSET1(hp, SDHC_HOST_CTL, SDHC_DMA_SELECT_ADMA2);
1843 		}
1844 
1845 		const bus_addr_t desc_addr = hp->adma_map->dm_segs[0].ds_addr;
1846 
1847 		HWRITE4(hp, SDHC_ADMA_SYSTEM_ADDR, desc_addr & 0xffffffff);
1848 		if (ISSET(hp->flags, SHF_USE_ADMA2_64)) {
1849 			HWRITE4(hp, SDHC_ADMA_SYSTEM_ADDR + 4,
1850 			    (uint64_t)desc_addr >> 32);
1851 		}
1852 	} else if (ISSET(mode, SDHC_DMA_ENABLE) &&
1853 	    !ISSET(sc->sc_flags, SDHC_FLAG_EXTERNAL_DMA)) {
1854 		if (ISSET(hp->sc->sc_flags, SDHC_FLAG_USDHC)) {
1855 			HCLR4(hp, SDHC_HOST_CTL, SDHC_USDHC_DMA_SELECT);
1856 		}
1857 		HWRITE4(hp, SDHC_DMA_ADDR, cmd->c_dmamap->dm_segs[0].ds_addr);
1858 	}
1859 
1860 	/*
1861 	 * Start a CPU data transfer.  Writing to the high order byte
1862 	 * of the SDHC_COMMAND register triggers the SD command. (1.5)
1863 	 */
1864 	if (ISSET(hp->sc->sc_flags, SDHC_FLAG_32BIT_ACCESS)) {
1865 		HWRITE4(hp, SDHC_BLOCK_SIZE, blksize | (blkcount << 16));
1866 		HWRITE4(hp, SDHC_ARGUMENT, cmd->c_arg);
1867 		if (ISSET(hp->sc->sc_flags, SDHC_FLAG_USDHC)) {
1868 			/* mode bits is in MIX_CTRL register on uSDHC */
1869 			HWRITE4(hp, SDHC_MIX_CTRL, mode |
1870 			    (HREAD4(hp, SDHC_MIX_CTRL) & ~SDHC_TRANSFER_MODE_MASK));
1871 			if (cmd->c_opcode == MMC_STOP_TRANSMISSION)
1872 				command |= SDHC_COMMAND_TYPE_ABORT;
1873 			HWRITE4(hp, SDHC_TRANSFER_MODE, command << 16);
1874 		} else {
1875 			HWRITE4(hp, SDHC_TRANSFER_MODE, mode | (command << 16));
1876 		}
1877 	} else {
1878 		HWRITE2(hp, SDHC_BLOCK_SIZE, blksize);
1879 		HWRITE2(hp, SDHC_BLOCK_COUNT, blkcount);
1880 		HWRITE4(hp, SDHC_ARGUMENT, cmd->c_arg);
1881 		HWRITE2(hp, SDHC_TRANSFER_MODE, mode);
1882 		HWRITE2(hp, SDHC_COMMAND, command);
1883 	}
1884 
1885 	return 0;
1886 }
1887 
1888 static void
1889 sdhc_transfer_data(struct sdhc_host *hp, struct sdmmc_command *cmd)
1890 {
1891 	struct sdhc_softc *sc = hp->sc;
1892 	int error;
1893 
1894 	KASSERT(mutex_owned(&hp->intr_lock));
1895 
1896 	DPRINTF(1,("%s: data transfer: resp=%08x datalen=%u\n", HDEVNAME(hp),
1897 	    MMC_R1(cmd->c_resp), cmd->c_datalen));
1898 
1899 #ifdef SDHC_DEBUG
1900 	/* XXX I forgot why I wanted to know when this happens :-( */
1901 	if ((cmd->c_opcode == 52 || cmd->c_opcode == 53) &&
1902 	    ISSET(MMC_R1(cmd->c_resp), 0xcb00)) {
1903 		aprint_error_dev(hp->sc->sc_dev,
1904 		    "CMD52/53 error response flags %#x\n",
1905 		    MMC_R1(cmd->c_resp) & 0xff00);
1906 	}
1907 #endif
1908 
1909 	if (cmd->c_dmamap != NULL) {
1910 		if (hp->sc->sc_vendor_transfer_data_dma != NULL) {
1911 			error = hp->sc->sc_vendor_transfer_data_dma(sc, cmd);
1912 			if (error == 0 && !sdhc_wait_intr(hp,
1913 			    SDHC_TRANSFER_COMPLETE, SDHC_DMA_TIMEOUT, false)) {
1914 				DPRINTF(1,("%s: timeout\n", __func__));
1915 				error = ETIMEDOUT;
1916 			}
1917 		} else {
1918 			error = sdhc_transfer_data_dma(hp, cmd);
1919 		}
1920 	} else
1921 		error = sdhc_transfer_data_pio(hp, cmd);
1922 	if (error)
1923 		cmd->c_error = error;
1924 	SET(cmd->c_flags, SCF_ITSDONE);
1925 
1926 	DPRINTF(1,("%s: data transfer done (error=%d)\n",
1927 	    HDEVNAME(hp), cmd->c_error));
1928 }
1929 
1930 static int
1931 sdhc_transfer_data_dma(struct sdhc_host *hp, struct sdmmc_command *cmd)
1932 {
1933 	bus_dma_segment_t *dm_segs = cmd->c_dmamap->dm_segs;
1934 	bus_addr_t posaddr;
1935 	bus_addr_t segaddr;
1936 	bus_size_t seglen;
1937 	u_int seg = 0;
1938 	int error = 0;
1939 	int status;
1940 
1941 	KASSERT(mutex_owned(&hp->intr_lock));
1942 	KASSERT(HREAD2(hp, SDHC_NINTR_STATUS_EN) & SDHC_DMA_INTERRUPT);
1943 	KASSERT(HREAD2(hp, SDHC_NINTR_SIGNAL_EN) & SDHC_DMA_INTERRUPT);
1944 	KASSERT(HREAD2(hp, SDHC_NINTR_STATUS_EN) & SDHC_TRANSFER_COMPLETE);
1945 	KASSERT(HREAD2(hp, SDHC_NINTR_SIGNAL_EN) & SDHC_TRANSFER_COMPLETE);
1946 
1947 	for (;;) {
1948 		status = sdhc_wait_intr(hp,
1949 		    SDHC_DMA_INTERRUPT|SDHC_TRANSFER_COMPLETE,
1950 		    SDHC_DMA_TIMEOUT, false);
1951 
1952 		if (status & SDHC_TRANSFER_COMPLETE) {
1953 			break;
1954 		}
1955 		if (!status) {
1956 			DPRINTF(1,("%s: timeout\n", __func__));
1957 			error = ETIMEDOUT;
1958 			break;
1959 		}
1960 
1961 		if (ISSET(hp->flags, SHF_USE_ADMA2_MASK)) {
1962 			continue;
1963 		}
1964 
1965 		if ((status & SDHC_DMA_INTERRUPT) == 0) {
1966 			continue;
1967 		}
1968 
1969 		/* DMA Interrupt (boundary crossing) */
1970 
1971 		segaddr = dm_segs[seg].ds_addr;
1972 		seglen = dm_segs[seg].ds_len;
1973 		posaddr = HREAD4(hp, SDHC_DMA_ADDR);
1974 
1975 		if ((seg == (cmd->c_dmamap->dm_nsegs-1)) && (posaddr == (segaddr + seglen))) {
1976 			continue;
1977 		}
1978 		if ((posaddr >= segaddr) && (posaddr < (segaddr + seglen)))
1979 			HWRITE4(hp, SDHC_DMA_ADDR, posaddr);
1980 		else if ((posaddr >= segaddr) && (posaddr == (segaddr + seglen)) && (seg + 1) < cmd->c_dmamap->dm_nsegs)
1981 			HWRITE4(hp, SDHC_DMA_ADDR, dm_segs[++seg].ds_addr);
1982 		KASSERT(seg < cmd->c_dmamap->dm_nsegs);
1983 	}
1984 
1985 	if (ISSET(hp->flags, SHF_USE_ADMA2_MASK)) {
1986 		bus_dmamap_sync(hp->sc->sc_dmat, hp->adma_map, 0,
1987 		    PAGE_SIZE, BUS_DMASYNC_POSTWRITE);
1988 	}
1989 
1990 	return error;
1991 }
1992 
1993 static int
1994 sdhc_transfer_data_pio(struct sdhc_host *hp, struct sdmmc_command *cmd)
1995 {
1996 	uint8_t *data = cmd->c_data;
1997 	void (*pio_func)(struct sdhc_host *, uint8_t *, u_int);
1998 	u_int len, datalen;
1999 	u_int imask;
2000 	u_int pmask;
2001 	int error = 0;
2002 
2003 	KASSERT(mutex_owned(&hp->intr_lock));
2004 
2005 	if (ISSET(cmd->c_flags, SCF_CMD_READ)) {
2006 		imask = SDHC_BUFFER_READ_READY;
2007 		pmask = SDHC_BUFFER_READ_ENABLE;
2008 		if (ISSET(hp->sc->sc_flags,
2009 		    SDHC_FLAG_ENHANCED | SDHC_FLAG_USDHC)) {
2010 			pio_func = esdhc_read_data_pio;
2011 		} else {
2012 			pio_func = sdhc_read_data_pio;
2013 		}
2014 	} else {
2015 		imask = SDHC_BUFFER_WRITE_READY;
2016 		pmask = SDHC_BUFFER_WRITE_ENABLE;
2017 		if (ISSET(hp->sc->sc_flags,
2018 		    SDHC_FLAG_ENHANCED | SDHC_FLAG_USDHC)) {
2019 			pio_func = esdhc_write_data_pio;
2020 		} else {
2021 			pio_func = sdhc_write_data_pio;
2022 		}
2023 	}
2024 	datalen = cmd->c_datalen;
2025 
2026 	KASSERT(mutex_owned(&hp->intr_lock));
2027 	KASSERT(HREAD2(hp, SDHC_NINTR_STATUS_EN) & imask);
2028 	KASSERT(HREAD2(hp, SDHC_NINTR_STATUS_EN) & SDHC_TRANSFER_COMPLETE);
2029 	KASSERT(HREAD2(hp, SDHC_NINTR_SIGNAL_EN) & SDHC_TRANSFER_COMPLETE);
2030 
2031 	while (datalen > 0) {
2032 		if (!ISSET(HREAD4(hp, SDHC_PRESENT_STATE), pmask)) {
2033 			if (ISSET(hp->sc->sc_flags, SDHC_FLAG_32BIT_ACCESS)) {
2034 				HSET4(hp, SDHC_NINTR_SIGNAL_EN, imask);
2035 			} else {
2036 				HSET2(hp, SDHC_NINTR_SIGNAL_EN, imask);
2037 			}
2038 			if (!sdhc_wait_intr(hp, imask, SDHC_BUFFER_TIMEOUT, false)) {
2039 				DPRINTF(1,("%s: timeout\n", __func__));
2040 				error = ETIMEDOUT;
2041 				break;
2042 			}
2043 
2044 			error = sdhc_wait_state(hp, pmask, pmask);
2045 			if (error)
2046 				break;
2047 		}
2048 
2049 		len = MIN(datalen, cmd->c_blklen);
2050 		(*pio_func)(hp, data, len);
2051 		DPRINTF(2,("%s: pio data transfer %u @ %p\n",
2052 		    HDEVNAME(hp), len, data));
2053 
2054 		data += len;
2055 		datalen -= len;
2056 	}
2057 
2058 	if (error == 0 && !sdhc_wait_intr(hp, SDHC_TRANSFER_COMPLETE,
2059 	    SDHC_TRANSFER_TIMEOUT, false)) {
2060 		DPRINTF(1,("%s: timeout for transfer\n", __func__));
2061 		error = ETIMEDOUT;
2062 	}
2063 
2064 	return error;
2065 }
2066 
2067 static void
2068 sdhc_read_data_pio(struct sdhc_host *hp, uint8_t *data, u_int datalen)
2069 {
2070 
2071 	if (((__uintptr_t)data & 3) == 0) {
2072 		while (datalen > 3) {
2073 			*(uint32_t *)data = le32toh(HREAD4(hp, SDHC_DATA));
2074 			data += 4;
2075 			datalen -= 4;
2076 		}
2077 		if (datalen > 1) {
2078 			*(uint16_t *)data = le16toh(HREAD2(hp, SDHC_DATA));
2079 			data += 2;
2080 			datalen -= 2;
2081 		}
2082 		if (datalen > 0) {
2083 			*data = HREAD1(hp, SDHC_DATA);
2084 			data += 1;
2085 			datalen -= 1;
2086 		}
2087 	} else if (((__uintptr_t)data & 1) == 0) {
2088 		while (datalen > 1) {
2089 			*(uint16_t *)data = le16toh(HREAD2(hp, SDHC_DATA));
2090 			data += 2;
2091 			datalen -= 2;
2092 		}
2093 		if (datalen > 0) {
2094 			*data = HREAD1(hp, SDHC_DATA);
2095 			data += 1;
2096 			datalen -= 1;
2097 		}
2098 	} else {
2099 		while (datalen > 0) {
2100 			*data = HREAD1(hp, SDHC_DATA);
2101 			data += 1;
2102 			datalen -= 1;
2103 		}
2104 	}
2105 }
2106 
2107 static void
2108 sdhc_write_data_pio(struct sdhc_host *hp, uint8_t *data, u_int datalen)
2109 {
2110 
2111 	if (((__uintptr_t)data & 3) == 0) {
2112 		while (datalen > 3) {
2113 			HWRITE4(hp, SDHC_DATA, htole32(*(uint32_t *)data));
2114 			data += 4;
2115 			datalen -= 4;
2116 		}
2117 		if (datalen > 1) {
2118 			HWRITE2(hp, SDHC_DATA, htole16(*(uint16_t *)data));
2119 			data += 2;
2120 			datalen -= 2;
2121 		}
2122 		if (datalen > 0) {
2123 			HWRITE1(hp, SDHC_DATA, *data);
2124 			data += 1;
2125 			datalen -= 1;
2126 		}
2127 	} else if (((__uintptr_t)data & 1) == 0) {
2128 		while (datalen > 1) {
2129 			HWRITE2(hp, SDHC_DATA, htole16(*(uint16_t *)data));
2130 			data += 2;
2131 			datalen -= 2;
2132 		}
2133 		if (datalen > 0) {
2134 			HWRITE1(hp, SDHC_DATA, *data);
2135 			data += 1;
2136 			datalen -= 1;
2137 		}
2138 	} else {
2139 		while (datalen > 0) {
2140 			HWRITE1(hp, SDHC_DATA, *data);
2141 			data += 1;
2142 			datalen -= 1;
2143 		}
2144 	}
2145 }
2146 
2147 static void
2148 esdhc_read_data_pio(struct sdhc_host *hp, uint8_t *data, u_int datalen)
2149 {
2150 	uint16_t status = HREAD2(hp, SDHC_NINTR_STATUS);
2151 	uint32_t v;
2152 
2153 	const size_t watermark = (HREAD4(hp, SDHC_WATERMARK_LEVEL) >> SDHC_WATERMARK_READ_SHIFT) & SDHC_WATERMARK_READ_MASK;
2154 	size_t count = 0;
2155 
2156 	while (datalen > 3 && !ISSET(status, SDHC_TRANSFER_COMPLETE)) {
2157 		if (count == 0) {
2158 			/*
2159 			 * If we've drained "watermark" words, we need to wait
2160 			 * a little bit so the read FIFO can refill.
2161 			 */
2162 			sdmmc_delay(10);
2163 			count = watermark;
2164 		}
2165 		v = HREAD4(hp, SDHC_DATA);
2166 		v = le32toh(v);
2167 		*(uint32_t *)data = v;
2168 		data += 4;
2169 		datalen -= 4;
2170 		status = HREAD2(hp, SDHC_NINTR_STATUS);
2171 		count--;
2172 	}
2173 	if (datalen > 0 && !ISSET(status, SDHC_TRANSFER_COMPLETE)) {
2174 		if (count == 0) {
2175 			sdmmc_delay(10);
2176 		}
2177 		v = HREAD4(hp, SDHC_DATA);
2178 		v = le32toh(v);
2179 		do {
2180 			*data++ = v;
2181 			v >>= 8;
2182 		} while (--datalen > 0);
2183 	}
2184 }
2185 
2186 static void
2187 esdhc_write_data_pio(struct sdhc_host *hp, uint8_t *data, u_int datalen)
2188 {
2189 	uint16_t status = HREAD2(hp, SDHC_NINTR_STATUS);
2190 	uint32_t v;
2191 
2192 	const size_t watermark = (HREAD4(hp, SDHC_WATERMARK_LEVEL) >> SDHC_WATERMARK_WRITE_SHIFT) & SDHC_WATERMARK_WRITE_MASK;
2193 	size_t count = watermark;
2194 
2195 	while (datalen > 3 && !ISSET(status, SDHC_TRANSFER_COMPLETE)) {
2196 		if (count == 0) {
2197 			sdmmc_delay(10);
2198 			count = watermark;
2199 		}
2200 		v = *(uint32_t *)data;
2201 		v = htole32(v);
2202 		HWRITE4(hp, SDHC_DATA, v);
2203 		data += 4;
2204 		datalen -= 4;
2205 		status = HREAD2(hp, SDHC_NINTR_STATUS);
2206 		count--;
2207 	}
2208 	if (datalen > 0 && !ISSET(status, SDHC_TRANSFER_COMPLETE)) {
2209 		if (count == 0) {
2210 			sdmmc_delay(10);
2211 		}
2212 		v = *(uint32_t *)data;
2213 		v = htole32(v);
2214 		HWRITE4(hp, SDHC_DATA, v);
2215 	}
2216 }
2217 
2218 /* Prepare for another command. */
2219 static int
2220 sdhc_soft_reset(struct sdhc_host *hp, int mask)
2221 {
2222 	int timo;
2223 
2224 	KASSERT(mutex_owned(&hp->intr_lock));
2225 
2226 	DPRINTF(1,("%s: software reset reg=%08x\n", HDEVNAME(hp), mask));
2227 
2228 	/* Request the reset.  */
2229 	HWRITE1(hp, SDHC_SOFTWARE_RESET, mask);
2230 
2231 	/*
2232 	 * If necessary, wait for the controller to set the bits to
2233 	 * acknowledge the reset.
2234 	 */
2235 	if (ISSET(hp->sc->sc_flags, SDHC_FLAG_WAIT_RESET) &&
2236 	    ISSET(mask, (SDHC_RESET_DAT | SDHC_RESET_CMD))) {
2237 		for (timo = 10000; timo > 0; timo--) {
2238 			if (ISSET(HREAD1(hp, SDHC_SOFTWARE_RESET), mask))
2239 				break;
2240 			/* Short delay because I worry we may miss it...  */
2241 			sdmmc_delay(1);
2242 		}
2243 		if (timo == 0) {
2244 			DPRINTF(1,("%s: timeout for reset on\n", __func__));
2245 			return ETIMEDOUT;
2246 		}
2247 	}
2248 
2249 	/*
2250 	 * Wait for the controller to clear the bits to indicate that
2251 	 * the reset has completed.
2252 	 */
2253 	for (timo = 10; timo > 0; timo--) {
2254 		if (!ISSET(HREAD1(hp, SDHC_SOFTWARE_RESET), mask))
2255 			break;
2256 		sdmmc_delay(10000);
2257 	}
2258 	if (timo == 0) {
2259 		DPRINTF(1,("%s: timeout reg=%08x\n", HDEVNAME(hp),
2260 		    HREAD1(hp, SDHC_SOFTWARE_RESET)));
2261 		return ETIMEDOUT;
2262 	}
2263 
2264 	if (ISSET(hp->sc->sc_flags, SDHC_FLAG_ENHANCED)) {
2265 		HSET4(hp, SDHC_DMA_CTL, SDHC_DMA_SNOOP);
2266 	}
2267 
2268 	return 0;
2269 }
2270 
2271 static int
2272 sdhc_wait_intr(struct sdhc_host *hp, int mask, int timo, bool probing)
2273 {
2274 	int status, error, nointr;
2275 
2276 	KASSERT(mutex_owned(&hp->intr_lock));
2277 
2278 	mask |= SDHC_ERROR_INTERRUPT;
2279 
2280 	nointr = 0;
2281 	status = hp->intr_status & mask;
2282 	while (status == 0) {
2283 		if (cv_timedwait(&hp->intr_cv, &hp->intr_lock, timo)
2284 		    == EWOULDBLOCK) {
2285 			nointr = 1;
2286 			break;
2287 		}
2288 		status = hp->intr_status & mask;
2289 	}
2290 	error = hp->intr_error_status;
2291 
2292 	DPRINTF(2,("%s: intr status %#x error %#x\n", HDEVNAME(hp), status,
2293 	    error));
2294 
2295 	hp->intr_status &= ~status;
2296 	hp->intr_error_status &= ~error;
2297 
2298 	if (ISSET(status, SDHC_ERROR_INTERRUPT)) {
2299 		if (ISSET(error, SDHC_DMA_ERROR))
2300 			device_printf(hp->sc->sc_dev,"dma error\n");
2301 		if (ISSET(error, SDHC_ADMA_ERROR))
2302 			device_printf(hp->sc->sc_dev,"adma error\n");
2303 		if (ISSET(error, SDHC_AUTO_CMD12_ERROR))
2304 			device_printf(hp->sc->sc_dev,"auto_cmd12 error\n");
2305 		if (ISSET(error, SDHC_CURRENT_LIMIT_ERROR))
2306 			device_printf(hp->sc->sc_dev,"current limit error\n");
2307 		if (ISSET(error, SDHC_DATA_END_BIT_ERROR))
2308 			device_printf(hp->sc->sc_dev,"data end bit error\n");
2309 		if (ISSET(error, SDHC_DATA_CRC_ERROR))
2310 			device_printf(hp->sc->sc_dev,"data crc error\n");
2311 		if (ISSET(error, SDHC_DATA_TIMEOUT_ERROR))
2312 			device_printf(hp->sc->sc_dev,"data timeout error\n");
2313 		if (ISSET(error, SDHC_CMD_INDEX_ERROR))
2314 			device_printf(hp->sc->sc_dev,"cmd index error\n");
2315 		if (ISSET(error, SDHC_CMD_END_BIT_ERROR))
2316 			device_printf(hp->sc->sc_dev,"cmd end bit error\n");
2317 		if (ISSET(error, SDHC_CMD_CRC_ERROR))
2318 			device_printf(hp->sc->sc_dev,"cmd crc error\n");
2319 		if (ISSET(error, SDHC_CMD_TIMEOUT_ERROR)) {
2320 			if (!probing)
2321 				device_printf(hp->sc->sc_dev,"cmd timeout error\n");
2322 #ifdef SDHC_DEBUG
2323 			else if (sdhcdebug > 0)
2324 				device_printf(hp->sc->sc_dev,"cmd timeout (expected)\n");
2325 #endif
2326 		}
2327 		if ((error & ~SDHC_EINTR_STATUS_MASK) != 0)
2328 			device_printf(hp->sc->sc_dev,"vendor error %#x\n",
2329 				(error & ~SDHC_EINTR_STATUS_MASK));
2330 		if (error == 0)
2331 			device_printf(hp->sc->sc_dev,"no error\n");
2332 
2333 		/* Command timeout has higher priority than command complete. */
2334 		if (ISSET(error, SDHC_CMD_TIMEOUT_ERROR))
2335 			CLR(status, SDHC_COMMAND_COMPLETE);
2336 
2337 		/* Transfer complete has higher priority than data timeout. */
2338 		if (ISSET(status, SDHC_TRANSFER_COMPLETE))
2339 			CLR(error, SDHC_DATA_TIMEOUT_ERROR);
2340 	}
2341 
2342 	if (nointr ||
2343 	    (ISSET(status, SDHC_ERROR_INTERRUPT) && error)) {
2344 		if (!ISSET(hp->sc->sc_flags, SDHC_FLAG_ENHANCED))
2345 			(void)sdhc_soft_reset(hp, SDHC_RESET_CMD|SDHC_RESET_DAT);
2346 		hp->intr_error_status = 0;
2347 		status = 0;
2348 	}
2349 
2350 	return status;
2351 }
2352 
2353 /*
2354  * Established by attachment driver at interrupt priority IPL_SDMMC.
2355  */
2356 int
2357 sdhc_intr(void *arg)
2358 {
2359 	struct sdhc_softc *sc = (struct sdhc_softc *)arg;
2360 	struct sdhc_host *hp;
2361 	int done = 0;
2362 	uint16_t status;
2363 	uint16_t error;
2364 
2365 	/* We got an interrupt, but we don't know from which slot. */
2366 	for (size_t host = 0; host < sc->sc_nhosts; host++) {
2367 		hp = sc->sc_host[host];
2368 		if (hp == NULL)
2369 			continue;
2370 
2371 		mutex_enter(&hp->intr_lock);
2372 
2373 		if (ISSET(sc->sc_flags, SDHC_FLAG_32BIT_ACCESS)) {
2374 			/* Find out which interrupts are pending. */
2375 			uint32_t xstatus = HREAD4(hp, SDHC_NINTR_STATUS);
2376 			status = xstatus;
2377 			error = xstatus >> 16;
2378 			if (ISSET(sc->sc_flags, SDHC_FLAG_USDHC) &&
2379 			    (xstatus & SDHC_TRANSFER_COMPLETE) &&
2380 			    !(xstatus & SDHC_DMA_INTERRUPT)) {
2381 				/* read again due to uSDHC errata */
2382 				status = xstatus = HREAD4(hp,
2383 				    SDHC_NINTR_STATUS);
2384 				error = xstatus >> 16;
2385 			}
2386 			if (ISSET(sc->sc_flags,
2387 			    SDHC_FLAG_ENHANCED | SDHC_FLAG_USDHC)) {
2388 				if ((error & SDHC_NINTR_STATUS_MASK) != 0)
2389 					SET(status, SDHC_ERROR_INTERRUPT);
2390 			}
2391 			if (error)
2392 				xstatus |= SDHC_ERROR_INTERRUPT;
2393 			else if (!ISSET(status, SDHC_NINTR_STATUS_MASK))
2394 				goto next_port; /* no interrupt for us */
2395 			/* Acknowledge the interrupts we are about to handle. */
2396 			HWRITE4(hp, SDHC_NINTR_STATUS, xstatus);
2397 		} else {
2398 			/* Find out which interrupts are pending. */
2399 			error = 0;
2400 			status = HREAD2(hp, SDHC_NINTR_STATUS);
2401 			if (!ISSET(status, SDHC_NINTR_STATUS_MASK))
2402 				goto next_port; /* no interrupt for us */
2403 			/* Acknowledge the interrupts we are about to handle. */
2404 			HWRITE2(hp, SDHC_NINTR_STATUS, status);
2405 			if (ISSET(status, SDHC_ERROR_INTERRUPT)) {
2406 				/* Acknowledge error interrupts. */
2407 				error = HREAD2(hp, SDHC_EINTR_STATUS);
2408 				HWRITE2(hp, SDHC_EINTR_STATUS, error);
2409 			}
2410 		}
2411 
2412 		DPRINTF(2,("%s: interrupt status=%x error=%x\n", HDEVNAME(hp),
2413 		    status, error));
2414 
2415 		/* Claim this interrupt. */
2416 		done = 1;
2417 
2418 		if (ISSET(status, SDHC_ERROR_INTERRUPT) &&
2419 		    ISSET(error, SDHC_ADMA_ERROR)) {
2420 			uint8_t adma_err = HREAD1(hp, SDHC_ADMA_ERROR_STATUS);
2421 			printf("%s: ADMA error, status %02x\n", HDEVNAME(hp),
2422 			    adma_err);
2423 		}
2424 
2425 		/*
2426 		 * Wake up the sdmmc event thread to scan for cards.
2427 		 */
2428 		if (ISSET(status, SDHC_CARD_REMOVAL|SDHC_CARD_INSERTION)) {
2429 			if (hp->sdmmc != NULL) {
2430 				sdmmc_needs_discover(hp->sdmmc);
2431 			}
2432 			if (ISSET(sc->sc_flags,
2433 			    SDHC_FLAG_ENHANCED | SDHC_FLAG_USDHC)) {
2434 				HCLR4(hp, SDHC_NINTR_STATUS_EN,
2435 				    status & (SDHC_CARD_REMOVAL|SDHC_CARD_INSERTION));
2436 				HCLR4(hp, SDHC_NINTR_SIGNAL_EN,
2437 				    status & (SDHC_CARD_REMOVAL|SDHC_CARD_INSERTION));
2438 			}
2439 		}
2440 
2441 		/*
2442 		 * Schedule re-tuning process (UHS).
2443 		 */
2444 		if (ISSET(status, SDHC_RETUNING_EVENT)) {
2445 			atomic_swap_uint(&hp->tuning_timer_pending, 1);
2446 		}
2447 
2448 		/*
2449 		 * Wake up the blocking process to service command
2450 		 * related interrupt(s).
2451 		 */
2452 		if (ISSET(status, SDHC_COMMAND_COMPLETE|SDHC_ERROR_INTERRUPT|
2453 		    SDHC_BUFFER_READ_READY|SDHC_BUFFER_WRITE_READY|
2454 		    SDHC_TRANSFER_COMPLETE|SDHC_DMA_INTERRUPT)) {
2455 			hp->intr_error_status |= error;
2456 			hp->intr_status |= status;
2457 			if (ISSET(sc->sc_flags,
2458 			    SDHC_FLAG_ENHANCED | SDHC_FLAG_USDHC)) {
2459 				HCLR4(hp, SDHC_NINTR_SIGNAL_EN,
2460 				    status & (SDHC_BUFFER_READ_READY|SDHC_BUFFER_WRITE_READY));
2461 			}
2462 			cv_broadcast(&hp->intr_cv);
2463 		}
2464 
2465 		/*
2466 		 * Service SD card interrupts.
2467 		 */
2468 		if (!ISSET(sc->sc_flags, SDHC_FLAG_ENHANCED | SDHC_FLAG_USDHC)
2469 		    && ISSET(status, SDHC_CARD_INTERRUPT)) {
2470 			DPRINTF(0,("%s: card interrupt\n", HDEVNAME(hp)));
2471 			HCLR2(hp, SDHC_NINTR_STATUS_EN, SDHC_CARD_INTERRUPT);
2472 			sdmmc_card_intr(hp->sdmmc);
2473 		}
2474 next_port:
2475 		mutex_exit(&hp->intr_lock);
2476 	}
2477 
2478 	return done;
2479 }
2480 
2481 kmutex_t *
2482 sdhc_host_lock(struct sdhc_host *hp)
2483 {
2484 	return &hp->intr_lock;
2485 }
2486 
2487 uint8_t
2488 sdhc_host_read_1(struct sdhc_host *hp, int reg)
2489 {
2490 	return HREAD1(hp, reg);
2491 }
2492 
2493 uint16_t
2494 sdhc_host_read_2(struct sdhc_host *hp, int reg)
2495 {
2496 	return HREAD2(hp, reg);
2497 }
2498 
2499 uint32_t
2500 sdhc_host_read_4(struct sdhc_host *hp, int reg)
2501 {
2502 	return HREAD4(hp, reg);
2503 }
2504 
2505 void
2506 sdhc_host_write_1(struct sdhc_host *hp, int reg, uint8_t val)
2507 {
2508 	HWRITE1(hp, reg, val);
2509 }
2510 
2511 void
2512 sdhc_host_write_2(struct sdhc_host *hp, int reg, uint16_t val)
2513 {
2514 	HWRITE2(hp, reg, val);
2515 }
2516 
2517 void
2518 sdhc_host_write_4(struct sdhc_host *hp, int reg, uint32_t val)
2519 {
2520 	HWRITE4(hp, reg, val);
2521 }
2522 
2523 #ifdef SDHC_DEBUG
2524 void
2525 sdhc_dump_regs(struct sdhc_host *hp)
2526 {
2527 
2528 	printf("0x%02x PRESENT_STATE:    %x\n", SDHC_PRESENT_STATE,
2529 	    HREAD4(hp, SDHC_PRESENT_STATE));
2530 	if (!ISSET(hp->sc->sc_flags, SDHC_FLAG_ENHANCED))
2531 		printf("0x%02x POWER_CTL:        %x\n", SDHC_POWER_CTL,
2532 		    HREAD1(hp, SDHC_POWER_CTL));
2533 	printf("0x%02x NINTR_STATUS:     %x\n", SDHC_NINTR_STATUS,
2534 	    HREAD2(hp, SDHC_NINTR_STATUS));
2535 	printf("0x%02x EINTR_STATUS:     %x\n", SDHC_EINTR_STATUS,
2536 	    HREAD2(hp, SDHC_EINTR_STATUS));
2537 	printf("0x%02x NINTR_STATUS_EN:  %x\n", SDHC_NINTR_STATUS_EN,
2538 	    HREAD2(hp, SDHC_NINTR_STATUS_EN));
2539 	printf("0x%02x EINTR_STATUS_EN:  %x\n", SDHC_EINTR_STATUS_EN,
2540 	    HREAD2(hp, SDHC_EINTR_STATUS_EN));
2541 	printf("0x%02x NINTR_SIGNAL_EN:  %x\n", SDHC_NINTR_SIGNAL_EN,
2542 	    HREAD2(hp, SDHC_NINTR_SIGNAL_EN));
2543 	printf("0x%02x EINTR_SIGNAL_EN:  %x\n", SDHC_EINTR_SIGNAL_EN,
2544 	    HREAD2(hp, SDHC_EINTR_SIGNAL_EN));
2545 	printf("0x%02x CAPABILITIES:     %x\n", SDHC_CAPABILITIES,
2546 	    HREAD4(hp, SDHC_CAPABILITIES));
2547 	printf("0x%02x MAX_CAPABILITIES: %x\n", SDHC_MAX_CAPABILITIES,
2548 	    HREAD4(hp, SDHC_MAX_CAPABILITIES));
2549 }
2550 #endif
2551