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