xref: /freebsd-14-stable/sys/dev/rtsx/rtsx.c (revision ee08e8455170b65b85e85aa44374494b95fc5f0c)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2006 Uwe Stuehler <uwe@openbsd.org>
5  * Copyright (c) 2012 Stefan Sperling <stsp@openbsd.org>
6  * Copyright (c) 2020 Henri Hennebert <hlh@restart.be>
7  * Copyright (c) 2020 Gary Jennejohn <gj@freebsd.org>
8  * Copyright (c) 2020 Jesper Schmitz Mouridsen <jsm@FreeBSD.org>
9  * All rights reserved.
10  *
11  * Patch from:
12  * - Lutz Bichler <Lutz.Bichler@gmail.com>
13  *
14  * Base on OpenBSD /sys/dev/pci/rtsx_pci.c & /dev/ic/rtsx.c
15  *      on Linux   /drivers/mmc/host/rtsx_pci_sdmmc.c,
16  *                 /include/linux/rtsx_pci.h &
17  *                 /drivers/misc/cardreader/rtsx_pcr.c
18  *      on NetBSD  /sys/dev/ic/rtsx.c
19  *
20  * Permission to use, copy, modify, and distribute this software for any
21  * purpose with or without fee is hereby granted, provided that the above
22  * copyright notice and this permission notice appear in all copies.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #include <sys/cdefs.h>
38 #include <sys/param.h>
39 #include <sys/module.h>
40 #include <sys/systm.h> /* For FreeBSD 11 */
41 #include <sys/types.h> /* For FreeBSD 11 */
42 #include <sys/errno.h>
43 #include <sys/kernel.h>
44 #include <sys/bus.h>
45 #include <sys/endian.h>
46 #include <machine/bus.h>
47 #include <sys/mutex.h>
48 #include <sys/malloc.h>
49 #include <sys/rman.h>
50 #include <sys/queue.h>
51 #include <sys/taskqueue.h>
52 #include <sys/sysctl.h>
53 #include <dev/pci/pcivar.h>
54 #include <dev/pci/pcireg.h>
55 #include <dev/mmc/bridge.h>
56 #include <dev/mmc/mmcreg.h>
57 #include <dev/mmc/mmcbrvar.h>
58 #include <machine/_inttypes.h>
59 
60 #include "opt_mmccam.h"
61 
62 #ifdef MMCCAM
63 #include <cam/cam.h>
64 #include <cam/cam_ccb.h>
65 #include <cam/cam_debug.h>
66 #include <cam/cam_sim.h>
67 #include <cam/cam_xpt_sim.h>
68 #include <cam/mmc/mmc_sim.h>
69 #include "mmc_sim_if.h"
70 #endif /* MMCCAM */
71 
72 #include "rtsxreg.h"
73 
74 /* The softc holds our per-instance data. */
75 struct rtsx_softc {
76 	struct mtx	rtsx_mtx;		/* device mutex */
77 	device_t	rtsx_dev;		/* device */
78 	uint16_t	rtsx_flags;		/* device flags */
79 	uint16_t	rtsx_device_id;		/* device ID */
80 	device_t	rtsx_mmc_dev;		/* device of mmc bus */
81 	uint32_t	rtsx_intr_enabled;	/* enabled interrupts */
82 	uint32_t 	rtsx_intr_status;	/* soft interrupt status */
83 	int		rtsx_irq_res_id;	/* bus IRQ resource id */
84 	struct resource *rtsx_irq_res;		/* bus IRQ resource */
85 	void		*rtsx_irq_cookie;	/* bus IRQ resource cookie */
86 	struct callout	rtsx_timeout_callout;	/* callout for timeout */
87 	int		rtsx_timeout_cmd;	/* interrupt timeout for setup commands */
88 	int		rtsx_timeout_io;	/* interrupt timeout for I/O commands */
89 	void		(*rtsx_intr_trans_ok)(struct rtsx_softc *sc);
90 						/* function to call if transfer succeed */
91 	void		(*rtsx_intr_trans_ko)(struct rtsx_softc *sc);
92 						/* function to call if transfer fail */
93 
94 	struct timeout_task
95 			rtsx_card_insert_task;	/* card insert delayed task */
96 	struct task	rtsx_card_remove_task;	/* card remove task */
97 
98 	int		rtsx_mem_res_id;	/* bus memory resource id */
99 	struct resource *rtsx_mem_res;		/* bus memory resource */
100 	bus_space_tag_t	   rtsx_mem_btag;	/* host register set tag */
101 	bus_space_handle_t rtsx_mem_bhandle;	/* host register set handle */
102 
103 	bus_dma_tag_t	rtsx_cmd_dma_tag;	/* DMA tag for command transfer */
104 	bus_dmamap_t	rtsx_cmd_dmamap;	/* DMA map for command transfer */
105 	void		*rtsx_cmd_dmamem;	/* DMA mem for command transfer */
106 	bus_addr_t	rtsx_cmd_buffer;	/* device visible address of the DMA segment */
107 	int		rtsx_cmd_index;		/* index in rtsx_cmd_buffer */
108 
109 	bus_dma_tag_t	rtsx_data_dma_tag;	/* DMA tag for data transfer */
110 	bus_dmamap_t	rtsx_data_dmamap;	/* DMA map for data transfer */
111 	void		*rtsx_data_dmamem;	/* DMA mem for data transfer */
112 	bus_addr_t	rtsx_data_buffer;	/* device visible address of the DMA segment */
113 
114 #ifdef MMCCAM
115 	union ccb		*rtsx_ccb;	/* CAM control block */
116 	struct mmc_sim		rtsx_mmc_sim;	/* CAM generic sim */
117 	struct mmc_request	rtsx_cam_req;	/* CAM MMC request */
118 #endif /* MMCCAM */
119 
120 	struct mmc_request *rtsx_req;		/* MMC request */
121 	struct mmc_host rtsx_host;		/* host parameters */
122 	int		rtsx_pcie_cap;		/* PCIe capability offset */
123 	int8_t		rtsx_bus_busy;		/* bus busy status */
124 	int8_t		rtsx_ios_bus_width;	/* current host.ios.bus_width */
125 	int32_t		rtsx_ios_clock;		/* current host.ios.clock */
126 	int8_t		rtsx_ios_power_mode;	/* current host.ios.power mode */
127 	int8_t		rtsx_ios_timing;	/* current host.ios.timing */
128 	int8_t		rtsx_ios_vccq;		/* current host.ios.vccq */
129 	uint8_t		rtsx_read_only;		/* card read only status */
130 	uint8_t		rtsx_inversion;		/* inversion of card detection and read only status */
131 	uint8_t		rtsx_force_timing;	/* force bus_timing_uhs_sdr50 */
132 	uint8_t		rtsx_debug_mask;	/* debugging mask */
133 #define 	RTSX_DEBUG_BASIC	0x01	/* debug basic flow */
134 #define 	RTSX_TRACE_SD_CMD	0x02	/* trace SD commands */
135 #define 	RTSX_DEBUG_TUNING	0x04	/* debug tuning */
136 #ifdef MMCCAM
137 	uint8_t		rtsx_cam_status;	/* CAM status - 1 if card in use */
138 #endif /* MMCCAM */
139 	uint64_t	rtsx_read_count;	/* count of read operations */
140 	uint64_t	rtsx_write_count;	/* count of write operations */
141 	bool		rtsx_discovery_mode;	/* are we in discovery mode? */
142 	bool		rtsx_tuning_mode;	/* are we tuning */
143 	bool		rtsx_double_clk;	/* double clock freqency */
144 	bool		rtsx_vpclk;		/* voltage at Pulse-width Modulation(PWM) clock? */
145 	uint8_t		rtsx_ssc_depth;		/* Spread spectrum clocking depth */
146 	uint8_t		rtsx_card_drive_sel;	/* value for RTSX_CARD_DRIVE_SEL */
147 	uint8_t		rtsx_sd30_drive_sel_3v3;/* value for RTSX_SD30_DRIVE_SEL */
148 };
149 
150 /* rtsx_flags values */
151 #define	RTSX_F_DEFAULT		0x0000
152 #define	RTSX_F_CARD_PRESENT	0x0001
153 #define	RTSX_F_SDIO_SUPPORT	0x0002
154 #define	RTSX_F_VERSION_A	0x0004
155 #define	RTSX_F_VERSION_B	0x0008
156 #define	RTSX_F_VERSION_C	0x0010
157 #define	RTSX_F_VERSION_D	0x0020
158 #define	RTSX_F_8411B_QFN48	0x0040
159 #define	RTSX_F_REVERSE_SOCKET	0x0080
160 
161 #define	RTSX_REALTEK		0x10ec
162 #define	RTSX_RTS5209		0x5209
163 #define	RTSX_RTS5227		0x5227
164 #define	RTSX_RTS5229		0x5229
165 #define	RTSX_RTS522A		0x522a
166 #define	RTSX_RTS525A		0x525a
167 #define	RTSX_RTS5249		0x5249
168 #define	RTSX_RTS5260		0x5260
169 #define	RTSX_RTL8402		0x5286
170 #define	RTSX_RTL8411		0x5289
171 #define	RTSX_RTL8411B		0x5287
172 
173 #define	RTSX_VERSION		"2.1g"
174 
175 static const struct rtsx_pciids {
176 	uint16_t	device_id;
177 	const char	*desc;
178 } rtsx_ids[] = {
179 	{ RTSX_RTS5209, RTSX_VERSION " Realtek RTS5209 PCIe SD Card Reader" },
180 	{ RTSX_RTS5227, RTSX_VERSION " Realtek RTS5227 PCIe SD Card Reader" },
181 	{ RTSX_RTS5229, RTSX_VERSION " Realtek RTS5229 PCIe SD Card Reader" },
182 	{ RTSX_RTS522A, RTSX_VERSION " Realtek RTS522A PCIe SD Card Reader" },
183 	{ RTSX_RTS525A, RTSX_VERSION " Realtek RTS525A PCIe SD Card Reader" },
184 	{ RTSX_RTS5249, RTSX_VERSION " Realtek RTS5249 PCIe SD Card Reader" },
185 	{ RTSX_RTS5260, RTSX_VERSION " Realtek RTS5260 PCIe SD Card Reader" },
186 	{ RTSX_RTL8402, RTSX_VERSION " Realtek RTL8402 PCIe SD Card Reader" },
187 	{ RTSX_RTL8411, RTSX_VERSION " Realtek RTL8411 PCIe SD Card Reader" },
188 	{ RTSX_RTL8411B, RTSX_VERSION " Realtek RTL8411B PCIe SD Card Reader" },
189 };
190 
191 /* See `kenv | grep smbios.system` */
192 static const struct rtsx_inversion_model {
193 	char	*maker;
194 	char	*family;
195 	char	*product;
196 } rtsx_inversion_models[] = {
197 	{ "LENOVO",		"ThinkPad T470p",	"20J7S0PM00"},
198 	{ "LENOVO",		"ThinkPad X13 Gen 1",	"20UF000QRT"},
199 	{ NULL,			NULL,			NULL}
200 };
201 
202 static int	rtsx_dma_alloc(struct rtsx_softc *sc);
203 static void	rtsx_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error);
204 static void	rtsx_dma_free(struct rtsx_softc *sc);
205 static void	rtsx_intr(void *arg);
206 static void	rtsx_handle_card_present(struct rtsx_softc *sc);
207 static void	rtsx_card_task(void *arg, int pending __unused);
208 static bool	rtsx_is_card_present(struct rtsx_softc *sc);
209 static int	rtsx_init(struct rtsx_softc *sc);
210 static int	rtsx_map_sd_drive(int index);
211 static int	rtsx_rts5227_fill_driving(struct rtsx_softc *sc);
212 static int	rtsx_rts5249_fill_driving(struct rtsx_softc *sc);
213 static int	rtsx_rts5260_fill_driving(struct rtsx_softc *sc);
214 static int	rtsx_read(struct rtsx_softc *, uint16_t, uint8_t *);
215 static int	rtsx_read_cfg(struct rtsx_softc *sc, uint8_t func, uint16_t addr, uint32_t *val);
216 static int	rtsx_write(struct rtsx_softc *sc, uint16_t addr, uint8_t mask, uint8_t val);
217 static int	rtsx_read_phy(struct rtsx_softc *sc, uint8_t addr, uint16_t *val);
218 static int	rtsx_write_phy(struct rtsx_softc *sc, uint8_t addr, uint16_t val);
219 static int	rtsx_bus_power_off(struct rtsx_softc *sc);
220 static int	rtsx_bus_power_on(struct rtsx_softc *sc);
221 static int	rtsx_set_bus_width(struct rtsx_softc *sc, enum mmc_bus_width width);
222 static int	rtsx_set_sd_timing(struct rtsx_softc *sc, enum mmc_bus_timing timing);
223 static int	rtsx_set_sd_clock(struct rtsx_softc *sc, uint32_t freq);
224 static int	rtsx_stop_sd_clock(struct rtsx_softc *sc);
225 static int	rtsx_switch_sd_clock(struct rtsx_softc *sc, uint8_t clk, uint8_t n, uint8_t div, uint8_t mcu);
226 #ifndef MMCCAM
227 static void	rtsx_sd_change_tx_phase(struct rtsx_softc *sc, uint8_t sample_point);
228 static void	rtsx_sd_change_rx_phase(struct rtsx_softc *sc, uint8_t sample_point);
229 static void	rtsx_sd_tuning_rx_phase(struct rtsx_softc *sc, uint32_t *phase_map);
230 static int	rtsx_sd_tuning_rx_cmd(struct rtsx_softc *sc, uint8_t sample_point);
231 static int	rtsx_sd_tuning_rx_cmd_wait(struct rtsx_softc *sc, struct mmc_command *cmd);
232 static void	rtsx_sd_tuning_rx_cmd_wakeup(struct rtsx_softc *sc);
233 static void	rtsx_sd_wait_data_idle(struct rtsx_softc *sc);
234 static uint8_t	rtsx_sd_search_final_rx_phase(struct rtsx_softc *sc, uint32_t phase_map);
235 static int	rtsx_sd_get_rx_phase_len(uint32_t phase_map, int start_bit);
236 #endif /* !MMCCAM */
237 #if 0	/* For led */
238 static int	rtsx_led_enable(struct rtsx_softc *sc);
239 static int	rtsx_led_disable(struct rtsx_softc *sc);
240 #endif	/* For led */
241 static uint8_t	rtsx_response_type(uint16_t mmc_rsp);
242 static void	rtsx_init_cmd(struct rtsx_softc *sc, struct mmc_command *cmd);
243 static void	rtsx_push_cmd(struct rtsx_softc *sc, uint8_t cmd, uint16_t reg,
244 			      uint8_t mask, uint8_t data);
245 static void	rtsx_set_cmd_data_len(struct rtsx_softc *sc, uint16_t block_cnt, uint16_t byte_cnt);
246 static void	rtsx_send_cmd(struct rtsx_softc *sc);
247 static void	rtsx_ret_resp(struct rtsx_softc *sc);
248 static void	rtsx_set_resp(struct rtsx_softc *sc, struct mmc_command *cmd);
249 static void	rtsx_stop_cmd(struct rtsx_softc *sc);
250 static void	rtsx_clear_error(struct rtsx_softc *sc);
251 static void	rtsx_req_done(struct rtsx_softc *sc);
252 static int	rtsx_send_req(struct rtsx_softc *sc, struct mmc_command *cmd);
253 static int	rtsx_xfer_short(struct rtsx_softc *sc, struct mmc_command *cmd);
254 static void	rtsx_ask_ppbuf_part1(struct rtsx_softc *sc);
255 static void	rtsx_get_ppbuf_part1(struct rtsx_softc *sc);
256 static void	rtsx_get_ppbuf_part2(struct rtsx_softc *sc);
257 static void	rtsx_put_ppbuf_part1(struct rtsx_softc *sc);
258 static void	rtsx_put_ppbuf_part2(struct rtsx_softc *sc);
259 static void	rtsx_write_ppbuf(struct rtsx_softc *sc);
260 static int	rtsx_xfer(struct rtsx_softc *sc, struct mmc_command *cmd);
261 static void	rtsx_xfer_begin(struct rtsx_softc *sc);
262 static void	rtsx_xfer_start(struct rtsx_softc *sc);
263 static void	rtsx_xfer_finish(struct rtsx_softc *sc);
264 static void	rtsx_timeout(void *arg);
265 
266 #ifdef MMCCAM
267 static int	rtsx_get_tran_settings(device_t dev, struct ccb_trans_settings_mmc *cts);
268 static int	rtsx_set_tran_settings(device_t dev, struct ccb_trans_settings_mmc *cts);
269 static int	rtsx_cam_request(device_t dev, union ccb *ccb);
270 #endif /* MMCCAM */
271 
272 static int	rtsx_read_ivar(device_t bus, device_t child, int which, uintptr_t *result);
273 static int	rtsx_write_ivar(device_t bus, device_t child, int which, uintptr_t value);
274 
275 static int	rtsx_mmcbr_update_ios(device_t bus, device_t child __unused);
276 static int	rtsx_mmcbr_switch_vccq(device_t bus, device_t child __unused);
277 static int	rtsx_mmcbr_request(device_t bus, device_t child __unused, struct mmc_request *req);
278 #ifndef MMCCAM
279 static int	rtsx_mmcbr_tune(device_t bus, device_t child __unused, bool hs400 __unused);
280 static int	rtsx_mmcbr_retune(device_t bus, device_t child __unused, bool reset __unused);
281 static int	rtsx_mmcbr_get_ro(device_t bus, device_t child __unused);
282 static int	rtsx_mmcbr_acquire_host(device_t bus, device_t child __unused);
283 static int	rtsx_mmcbr_release_host(device_t bus, device_t child __unused);
284 #endif /* !MMCCAM */
285 
286 static int	rtsx_probe(device_t dev);
287 static int	rtsx_attach(device_t dev);
288 static int	rtsx_detach(device_t dev);
289 static int	rtsx_shutdown(device_t dev);
290 static int	rtsx_suspend(device_t dev);
291 static int	rtsx_resume(device_t dev);
292 
293 #define	RTSX_LOCK_INIT(_sc)	mtx_init(&(_sc)->rtsx_mtx,	\
294 					 device_get_nameunit(sc->rtsx_dev), "rtsx", MTX_DEF)
295 #define	RTSX_LOCK(_sc)		mtx_lock(&(_sc)->rtsx_mtx)
296 #define	RTSX_UNLOCK(_sc)	mtx_unlock(&(_sc)->rtsx_mtx)
297 #define	RTSX_LOCK_DESTROY(_sc)	mtx_destroy(&(_sc)->rtsx_mtx)
298 
299 #define	RTSX_SDCLK_OFF			0
300 #define	RTSX_SDCLK_250KHZ	   250000
301 #define	RTSX_SDCLK_400KHZ	   400000
302 #define	RTSX_SDCLK_25MHZ	 25000000
303 #define	RTSX_SDCLK_50MHZ	 50000000
304 #define	RTSX_SDCLK_100MHZ	100000000
305 #define	RTSX_SDCLK_208MHZ	208000000
306 
307 #define	RTSX_MIN_DIV_N		80
308 #define	RTSX_MAX_DIV_N		208
309 
310 #define	RTSX_MAX_DATA_BLKLEN	512
311 
312 #define	RTSX_DMA_ALIGN		4
313 #define	RTSX_HOSTCMD_MAX	256
314 #define	RTSX_DMA_CMD_BIFSIZE	(sizeof(uint32_t) * RTSX_HOSTCMD_MAX)
315 #define	RTSX_DMA_DATA_BUFSIZE	MAXPHYS
316 
317 #define	ISSET(t, f) ((t) & (f))
318 
319 #define	READ4(sc, reg)						\
320 	(bus_space_read_4((sc)->rtsx_mem_btag, (sc)->rtsx_mem_bhandle, (reg)))
321 #define	WRITE4(sc, reg, val)					\
322 	(bus_space_write_4((sc)->rtsx_mem_btag, (sc)->rtsx_mem_bhandle, (reg), (val)))
323 
324 #define	RTSX_READ(sc, reg, val) 				\
325 	do { 							\
326 		int err = rtsx_read((sc), (reg), (val)); 	\
327 		if (err) 					\
328 			return (err);				\
329 	} while (0)
330 
331 #define	RTSX_WRITE(sc, reg, val) 				\
332 	do { 							\
333 		int err = rtsx_write((sc), (reg), 0xff, (val));	\
334 		if (err) 					\
335 			return (err);				\
336 	} while (0)
337 #define	RTSX_CLR(sc, reg, bits)					\
338 	do { 							\
339 		int err = rtsx_write((sc), (reg), (bits), 0); 	\
340 		if (err) 					\
341 			return (err);				\
342 	} while (0)
343 
344 #define	RTSX_SET(sc, reg, bits)					\
345 	do { 							\
346 		int err = rtsx_write((sc), (reg), (bits), 0xff);\
347 		if (err) 					\
348 			return (err);				\
349 	} while (0)
350 
351 #define	RTSX_BITOP(sc, reg, mask, bits)				\
352 	do {							\
353 		int err = rtsx_write((sc), (reg), (mask), (bits));	\
354 		if (err)					\
355 			return (err);				\
356 	} while (0)
357 
358 /*
359  * We use two DMA buffers: a command buffer and a data buffer.
360  *
361  * The command buffer contains a command queue for the host controller,
362  * which describes SD/MMC commands to run, and other parameters. The chip
363  * runs the command queue when a special bit in the RTSX_HCBAR register is
364  * set and signals completion with the RTSX_TRANS_OK_INT interrupt.
365  * Each command is encoded as a 4 byte sequence containing command number
366  * (read, write, or check a host controller register), a register address,
367  * and a data bit-mask and value.
368  * SD/MMC commands which do not transfer any data from/to the card only use
369  * the command buffer.
370  *
371  * The data buffer is used for transfer longer than 512. Data transfer is
372  * controlled via the RTSX_HDBAR register and completion is signalled by
373  * the RTSX_TRANS_OK_INT interrupt.
374  *
375  * The chip is unable to perform DMA above 4GB.
376  */
377 
378 /*
379  * Main commands in the usual seqence used:
380  *
381  * CMD0		Go idle state
382  * CMD8		Send interface condition
383  * CMD55	Application Command for next ACMD
384  * ACMD41	Send Operation Conditions Register (OCR: voltage profile of the card)
385  * CMD2		Send Card Identification (CID) Register
386  * CMD3		Send relative address
387  * CMD9		Send Card Specific Data (CSD)
388  * CMD13	Send status (32 bits -  bit 25: card password protected)
389  * CMD7		Select card (before Get card SCR)
390  * ACMD51	Send SCR (SD CARD Configuration Register - [51:48]: Bus widths supported)
391  * CMD6		SD switch function
392  * ACMD13	Send SD status (512 bits)
393  * ACMD42	Set/Clear card detect
394  * ACMD6	Set bus width
395  * CMD19	Send tuning block
396  * CMD12	Stop transmission
397  *
398  * CMD17	Read single block (<=512)
399  * CMD18	Read multiple blocks (>512)
400  * CMD24	Write single block (<=512)
401  * CMD25	Write multiple blocks (>512)
402  *
403  * CMD52	IO R/W direct
404  * CMD5		Send Operation Conditions
405  */
406 
407 static int
rtsx_dma_alloc(struct rtsx_softc * sc)408 rtsx_dma_alloc(struct rtsx_softc *sc)
409 {
410 	int	error = 0;
411 
412 	error = bus_dma_tag_create(bus_get_dma_tag(sc->rtsx_dev), /* inherit from parent */
413 	    RTSX_DMA_ALIGN, 0,		/* alignment, boundary */
414 	    BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
415 	    BUS_SPACE_MAXADDR,		/* highaddr */
416 	    NULL, NULL,			/* filter, filterarg */
417 	    RTSX_DMA_CMD_BIFSIZE, 1,	/* maxsize, nsegments */
418 	    RTSX_DMA_CMD_BIFSIZE,	/* maxsegsize */
419 	    0,				/* flags */
420 	    NULL, NULL,			/* lockfunc, lockarg */
421 	    &sc->rtsx_cmd_dma_tag);
422 	if (error) {
423 		device_printf(sc->rtsx_dev,
424 			      "Can't create cmd parent DMA tag\n");
425 		return (error);
426 	}
427 	error = bus_dmamem_alloc(sc->rtsx_cmd_dma_tag,		/* DMA tag */
428 	    &sc->rtsx_cmd_dmamem,				/* will hold the KVA pointer */
429 	    BUS_DMA_COHERENT | BUS_DMA_WAITOK | BUS_DMA_ZERO,	/* flags */
430 	    &sc->rtsx_cmd_dmamap); 				/* DMA map */
431 	if (error) {
432 		device_printf(sc->rtsx_dev,
433 			      "Can't create DMA map for command transfer\n");
434 		goto destroy_cmd_dma_tag;
435 
436 	}
437 	error = bus_dmamap_load(sc->rtsx_cmd_dma_tag,	/* DMA tag */
438 	    sc->rtsx_cmd_dmamap,	/* DMA map */
439 	    sc->rtsx_cmd_dmamem,	/* KVA pointer to be mapped */
440 	    RTSX_DMA_CMD_BIFSIZE,	/* size of buffer */
441 	    rtsx_dmamap_cb,		/* callback */
442 	    &sc->rtsx_cmd_buffer,	/* first arg of callback */
443 	    0);				/* flags */
444 	if (error || sc->rtsx_cmd_buffer == 0) {
445 		device_printf(sc->rtsx_dev,
446 			      "Can't load DMA memory for command transfer\n");
447 		error = (error) ? error : EFAULT;
448 		goto destroy_cmd_dmamem_alloc;
449 	}
450 
451 	error = bus_dma_tag_create(bus_get_dma_tag(sc->rtsx_dev),	/* inherit from parent */
452 	    RTSX_DMA_DATA_BUFSIZE, 0,	/* alignment, boundary */
453 	    BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
454 	    BUS_SPACE_MAXADDR,		/* highaddr */
455 	    NULL, NULL,			/* filter, filterarg */
456 	    RTSX_DMA_DATA_BUFSIZE, 1,	/* maxsize, nsegments */
457 	    RTSX_DMA_DATA_BUFSIZE,	/* maxsegsize */
458 	    0,				/* flags */
459 	    NULL, NULL,			/* lockfunc, lockarg */
460 	    &sc->rtsx_data_dma_tag);
461 	if (error) {
462 		device_printf(sc->rtsx_dev,
463 			      "Can't create data parent DMA tag\n");
464 		goto destroy_cmd_dmamap_load;
465 	}
466 	error = bus_dmamem_alloc(sc->rtsx_data_dma_tag,		/* DMA tag */
467 	    &sc->rtsx_data_dmamem,				/* will hold the KVA pointer */
468 	    BUS_DMA_WAITOK | BUS_DMA_ZERO,			/* flags */
469 	    &sc->rtsx_data_dmamap); 				/* DMA map */
470 	if (error) {
471 		device_printf(sc->rtsx_dev,
472 			      "Can't create DMA map for data transfer\n");
473 		goto destroy_data_dma_tag;
474 	}
475 	error = bus_dmamap_load(sc->rtsx_data_dma_tag,	/* DMA tag */
476 	    sc->rtsx_data_dmamap,	/* DMA map */
477 	    sc->rtsx_data_dmamem,	/* KVA pointer to be mapped */
478 	    RTSX_DMA_DATA_BUFSIZE,	/* size of buffer */
479 	    rtsx_dmamap_cb,		/* callback */
480 	    &sc->rtsx_data_buffer,	/* first arg of callback */
481 	    0);				/* flags */
482 	if (error || sc->rtsx_data_buffer == 0) {
483 		device_printf(sc->rtsx_dev,
484 			      "Can't load DMA memory for data transfer\n");
485 		error = (error) ? error : EFAULT;
486 		goto destroy_data_dmamem_alloc;
487 	}
488 	return (error);
489 
490  destroy_data_dmamem_alloc:
491 	bus_dmamem_free(sc->rtsx_data_dma_tag, sc->rtsx_data_dmamem, sc->rtsx_data_dmamap);
492  destroy_data_dma_tag:
493 	bus_dma_tag_destroy(sc->rtsx_data_dma_tag);
494  destroy_cmd_dmamap_load:
495 	bus_dmamap_unload(sc->rtsx_cmd_dma_tag, sc->rtsx_cmd_dmamap);
496  destroy_cmd_dmamem_alloc:
497 	bus_dmamem_free(sc->rtsx_cmd_dma_tag, sc->rtsx_cmd_dmamem, sc->rtsx_cmd_dmamap);
498  destroy_cmd_dma_tag:
499 	bus_dma_tag_destroy(sc->rtsx_cmd_dma_tag);
500 
501 	return (error);
502 }
503 
504 static void
rtsx_dmamap_cb(void * arg,bus_dma_segment_t * segs,int nsegs,int error)505 rtsx_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
506 {
507 	if (error) {
508 		printf("rtsx_dmamap_cb: error %d\n", error);
509 		return;
510 	}
511 	*(bus_addr_t *)arg = segs[0].ds_addr;
512 }
513 
514 static void
rtsx_dma_free(struct rtsx_softc * sc)515 rtsx_dma_free(struct rtsx_softc *sc)
516 {
517 	if (sc->rtsx_cmd_dma_tag != NULL) {
518 		if (sc->rtsx_cmd_dmamap != NULL)
519 			bus_dmamap_unload(sc->rtsx_cmd_dma_tag,
520 					  sc->rtsx_cmd_dmamap);
521 		if (sc->rtsx_cmd_dmamem != NULL)
522 			bus_dmamem_free(sc->rtsx_cmd_dma_tag,
523 					sc->rtsx_cmd_dmamem,
524 					sc->rtsx_cmd_dmamap);
525 		sc->rtsx_cmd_dmamap = NULL;
526 		sc->rtsx_cmd_dmamem = NULL;
527 		sc->rtsx_cmd_buffer = 0;
528 		bus_dma_tag_destroy(sc->rtsx_cmd_dma_tag);
529 		sc->rtsx_cmd_dma_tag = NULL;
530 	}
531 	if (sc->rtsx_data_dma_tag != NULL) {
532 		if (sc->rtsx_data_dmamap != NULL)
533 			bus_dmamap_unload(sc->rtsx_data_dma_tag,
534 					  sc->rtsx_data_dmamap);
535 		if (sc->rtsx_data_dmamem != NULL)
536 			bus_dmamem_free(sc->rtsx_data_dma_tag,
537 					sc->rtsx_data_dmamem,
538 					sc->rtsx_data_dmamap);
539 		sc->rtsx_data_dmamap = NULL;
540 		sc->rtsx_data_dmamem = NULL;
541 		sc->rtsx_data_buffer = 0;
542 		bus_dma_tag_destroy(sc->rtsx_data_dma_tag);
543 		sc->rtsx_data_dma_tag = NULL;
544 	}
545 }
546 
547 static void
rtsx_intr(void * arg)548 rtsx_intr(void *arg)
549 {
550 	struct rtsx_softc *sc = arg;
551 	uint32_t	enabled;
552 	uint32_t	status;
553 
554 	RTSX_LOCK(sc);
555 
556 	enabled = sc->rtsx_intr_enabled;
557 	status = READ4(sc, RTSX_BIPR);	/* read Bus Interrupt Pending Register */
558 	sc->rtsx_intr_status = status;
559 
560 	if (sc->rtsx_debug_mask & RTSX_TRACE_SD_CMD)
561 		device_printf(sc->rtsx_dev, "Interrupt handler - enabled: 0x%08x, status: 0x%08x\n", enabled, status);
562 
563 	/* Ack interrupts. */
564 	WRITE4(sc, RTSX_BIPR, status);
565 
566 	if (((enabled & status) == 0) || status == 0xffffffff) {
567 		device_printf(sc->rtsx_dev, "Spurious interrupt - enabled: 0x%08x, status: 0x%08x\n", enabled, status);
568 		RTSX_UNLOCK(sc);
569 		return;
570 	}
571 
572 	/* Detect write protect. */
573 	if (status & RTSX_SD_WRITE_PROTECT)
574 		sc->rtsx_read_only = 1;
575 	else
576 		sc->rtsx_read_only = 0;
577 
578 	/* Start task to handle SD card status change (from dwmmc.c). */
579 	if (status & RTSX_SD_INT) {
580 		device_printf(sc->rtsx_dev, "Interrupt card inserted/removed\n");
581 		rtsx_handle_card_present(sc);
582 	}
583 
584 	if (sc->rtsx_req == NULL) {
585 		RTSX_UNLOCK(sc);
586 		return;
587 	}
588 
589 	if (status & RTSX_TRANS_OK_INT) {
590 		sc->rtsx_req->cmd->error = MMC_ERR_NONE;
591 		if (sc->rtsx_intr_trans_ok != NULL)
592 			sc->rtsx_intr_trans_ok(sc);
593 	} else if (status & RTSX_TRANS_FAIL_INT) {
594 		uint8_t stat1;
595 		sc->rtsx_req->cmd->error = MMC_ERR_FAILED;
596 		if (rtsx_read(sc, RTSX_SD_STAT1, &stat1) == 0 &&
597 		    (stat1 & RTSX_SD_CRC_ERR)) {
598 			device_printf(sc->rtsx_dev, "CRC error\n");
599 			sc->rtsx_req->cmd->error = MMC_ERR_BADCRC;
600 		}
601 		if (!sc->rtsx_tuning_mode)
602 			device_printf(sc->rtsx_dev, "Transfer fail - status: 0x%08x\n", status);
603 		rtsx_stop_cmd(sc);
604 		if (sc->rtsx_intr_trans_ko != NULL)
605 			sc->rtsx_intr_trans_ko(sc);
606 	}
607 
608 	RTSX_UNLOCK(sc);
609 }
610 
611 /*
612  * Function called from the IRQ handler (from dwmmc.c).
613  */
614 static void
rtsx_handle_card_present(struct rtsx_softc * sc)615 rtsx_handle_card_present(struct rtsx_softc *sc)
616 {
617 	bool	was_present;
618 	bool	is_present;
619 
620 #ifdef MMCCAM
621 	was_present = sc->rtsx_cam_status;
622 #else  /* !MMCCAM */
623 	was_present = sc->rtsx_mmc_dev != NULL;
624 #endif /* MMCCAM */
625 	is_present = rtsx_is_card_present(sc);
626 	if (is_present)
627 		device_printf(sc->rtsx_dev, "Card present\n");
628 	else
629 		device_printf(sc->rtsx_dev, "Card absent\n");
630 
631 	if (!was_present && is_present) {
632 		/*
633 		 * The delay is to debounce the card insert
634 		 * (sometimes the card detect pin stabilizes
635 		 * before the other pins have made good contact).
636 		 */
637 		taskqueue_enqueue_timeout(taskqueue_bus,
638 					  &sc->rtsx_card_insert_task, -hz);
639 	} else if (was_present && !is_present) {
640 		taskqueue_enqueue(taskqueue_bus, &sc->rtsx_card_remove_task);
641 	}
642 }
643 
644 /*
645  * This function is called at startup.
646  */
647 static void
rtsx_card_task(void * arg,int pending __unused)648 rtsx_card_task(void *arg, int pending __unused)
649 {
650 	struct rtsx_softc *sc = arg;
651 
652 #ifndef MMCCAM
653 	bus_topo_lock();
654 #endif
655 	if (rtsx_is_card_present(sc)) {
656 		sc->rtsx_flags |= RTSX_F_CARD_PRESENT;
657 		/* Card is present, attach if necessary. */
658 #ifdef MMCCAM
659 		if (sc->rtsx_cam_status == 0) {
660 #else  /* !MMCCAM */
661 		if (sc->rtsx_mmc_dev == NULL) {
662 #endif /* MMCCAM */
663 			if (sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
664 				device_printf(sc->rtsx_dev, "Card inserted\n");
665 
666 			sc->rtsx_read_count = sc->rtsx_write_count = 0;
667 #ifdef MMCCAM
668 			sc->rtsx_cam_status = 1;
669 			mmc_cam_sim_discover(&sc->rtsx_mmc_sim);
670 #else  /* !MMCCAM */
671 			sc->rtsx_mmc_dev = device_add_child(sc->rtsx_dev, "mmc", -1);
672 			if (sc->rtsx_mmc_dev == NULL) {
673 				device_printf(sc->rtsx_dev, "Adding MMC bus failed\n");
674 			} else {
675 				device_set_ivars(sc->rtsx_mmc_dev, sc);
676 				device_probe_and_attach(sc->rtsx_mmc_dev);
677 			}
678 #endif /* MMCCAM */
679 		}
680 	} else {
681 		sc->rtsx_flags &= ~RTSX_F_CARD_PRESENT;
682 		/* Card isn't present, detach if necessary. */
683 #ifdef MMCCAM
684 		if (sc->rtsx_cam_status != 0) {
685 #else  /* !MMCCAM */
686 		if (sc->rtsx_mmc_dev != NULL) {
687 #endif /* MMCCAM */
688 			if (sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
689 				device_printf(sc->rtsx_dev, "Card removed\n");
690 
691 			if (sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
692 				device_printf(sc->rtsx_dev, "Read count: %" PRIu64 ", write count: %" PRIu64 "\n",
693 					      sc->rtsx_read_count, sc->rtsx_write_count);
694 #ifdef MMCCAM
695 			sc->rtsx_cam_status = 0;
696 			mmc_cam_sim_discover(&sc->rtsx_mmc_sim);
697 #else  /* !MMCCAM */
698 			if (device_delete_child(sc->rtsx_dev, sc->rtsx_mmc_dev))
699 				device_printf(sc->rtsx_dev, "Detaching MMC bus failed\n");
700 			sc->rtsx_mmc_dev = NULL;
701 #endif /* MMCCAM */
702 		}
703 	}
704 #ifndef MMCCAM
705 	bus_topo_unlock();
706 #endif
707 }
708 
709 static bool
710 rtsx_is_card_present(struct rtsx_softc *sc)
711 {
712 	uint32_t status;
713 
714 	status = READ4(sc, RTSX_BIPR);
715 	if (sc->rtsx_inversion == 0)
716 		return (status & RTSX_SD_EXIST);
717 	else
718 		return !(status & RTSX_SD_EXIST);
719 }
720 
721 static int
722 rtsx_init(struct rtsx_softc *sc)
723 {
724 	uint8_t	version;
725 	uint8_t	val;
726 	int	error;
727 
728 	sc->rtsx_host.host_ocr = RTSX_SUPPORTED_VOLTAGE;
729 	sc->rtsx_host.f_min = RTSX_SDCLK_250KHZ;
730 	sc->rtsx_host.f_max = RTSX_SDCLK_208MHZ;
731 	sc->rtsx_host.caps = MMC_CAP_4_BIT_DATA | MMC_CAP_HSPEED |
732 		MMC_CAP_UHS_SDR12 | MMC_CAP_UHS_SDR25;
733 
734 	sc->rtsx_host.caps |= MMC_CAP_UHS_SDR50 | MMC_CAP_UHS_SDR104;
735 	if (sc->rtsx_device_id == RTSX_RTS5209)
736 		sc->rtsx_host.caps |= MMC_CAP_8_BIT_DATA;
737 	pci_find_cap(sc->rtsx_dev, PCIY_EXPRESS, &(sc->rtsx_pcie_cap));
738 
739 	/*
740 	 * Check IC version.
741 	 */
742 	switch (sc->rtsx_device_id) {
743 	case RTSX_RTS5229:
744 		/* Read IC version from dummy register. */
745 		RTSX_READ(sc, RTSX_DUMMY_REG, &version);
746 		if ((version & 0x0F) == RTSX_IC_VERSION_C)
747 			sc->rtsx_flags |= RTSX_F_VERSION_C;
748 		break;
749 	case RTSX_RTS522A:
750 		/* Read IC version from dummy register. */
751 		RTSX_READ(sc, RTSX_DUMMY_REG, &version);
752 		if ((version & 0x0F) == RTSX_IC_VERSION_A)
753 			sc->rtsx_flags |= RTSX_F_VERSION_A;
754 		break;
755 	case RTSX_RTS525A:
756 		/* Read IC version from dummy register. */
757 		RTSX_READ(sc, RTSX_DUMMY_REG, &version);
758 		if ((version & 0x0F) == RTSX_IC_VERSION_A)
759 			sc->rtsx_flags |= RTSX_F_VERSION_A;
760 		break;
761 	case RTSX_RTL8411B:
762 		RTSX_READ(sc, RTSX_RTL8411B_PACKAGE, &version);
763 		if (version & RTSX_RTL8411B_QFN48)
764 			sc->rtsx_flags |= RTSX_F_8411B_QFN48;
765 		break;
766 	}
767 
768 	/*
769 	 * Fetch vendor settings.
770 	 */
771 	/*
772 	 * Normally OEMs will set vendor setting to the config space
773 	 * of Realtek card reader in BIOS stage. This statement reads
774 	 * the setting and configure the internal registers according
775 	 * to it, to improve card reader's compatibility condition.
776 	 */
777 	sc->rtsx_card_drive_sel = RTSX_CARD_DRIVE_DEFAULT;
778 	switch (sc->rtsx_device_id) {
779 		uint32_t reg;
780 		uint32_t reg1;
781 		uint8_t  reg3;
782 	case RTSX_RTS5209:
783 		sc->rtsx_card_drive_sel = RTSX_RTS5209_CARD_DRIVE_DEFAULT;
784 		sc->rtsx_sd30_drive_sel_3v3 = RTSX_DRIVER_TYPE_D;
785 		reg = pci_read_config(sc->rtsx_dev, RTSX_PCR_SETTING_REG2, 4);
786 		if (!(reg & 0x80)) {
787 			sc->rtsx_card_drive_sel = (reg >> 8) & 0x3F;
788 			sc->rtsx_sd30_drive_sel_3v3 = reg & 0x07;
789 		} else if (bootverbose || sc->rtsx_debug_mask & RTSX_DEBUG_BASIC) {
790 			device_printf(sc->rtsx_dev, "pci_read_config() error - reg: 0x%08x\n", reg);
791 		}
792 		if (bootverbose || sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
793 			device_printf(sc->rtsx_dev, "card_drive_sel: 0x%02x, sd30_drive_sel_3v3: 0x%02x\n",
794 				      sc->rtsx_card_drive_sel, sc->rtsx_sd30_drive_sel_3v3);
795 		break;
796 	case RTSX_RTS5227:
797 	case RTSX_RTS522A:
798 		sc->rtsx_sd30_drive_sel_3v3 = RTSX_CFG_DRIVER_TYPE_B;
799 		reg = pci_read_config(sc->rtsx_dev, RTSX_PCR_SETTING_REG1, 4);
800 		if (!(reg & 0x1000000)) {
801 			sc->rtsx_card_drive_sel &= 0x3F;
802 			sc->rtsx_card_drive_sel |= ((reg >> 25) & 0x01) << 6;
803 			reg = pci_read_config(sc->rtsx_dev, RTSX_PCR_SETTING_REG2, 4);
804 			sc->rtsx_sd30_drive_sel_3v3 = (reg >> 5) & 0x03;
805 			if (reg & 0x4000)
806 				sc->rtsx_flags |= RTSX_F_REVERSE_SOCKET;
807 		} else if (bootverbose || sc->rtsx_debug_mask & RTSX_DEBUG_BASIC) {
808 			device_printf(sc->rtsx_dev, "pci_read_config() error - reg: 0x%08x\n", reg);
809 		}
810 		if (bootverbose || sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
811 			device_printf(sc->rtsx_dev,
812 				      "card_drive_sel: 0x%02x, sd30_drive_sel_3v3: 0x%02x, reverse_socket is %s\n",
813 				      sc->rtsx_card_drive_sel, sc->rtsx_sd30_drive_sel_3v3,
814 				      (sc->rtsx_flags & RTSX_F_REVERSE_SOCKET) ? "true" : "false");
815 		break;
816 	case RTSX_RTS5229:
817 		sc->rtsx_sd30_drive_sel_3v3 = RTSX_DRIVER_TYPE_D;
818 		reg = pci_read_config(sc->rtsx_dev, RTSX_PCR_SETTING_REG1, 4);
819 		if (!(reg & 0x1000000)) {
820 			sc->rtsx_card_drive_sel &= 0x3F;
821 			sc->rtsx_card_drive_sel |= ((reg >> 25) & 0x01) << 6;
822 			reg = pci_read_config(sc->rtsx_dev, RTSX_PCR_SETTING_REG2, 4);
823 			sc->rtsx_sd30_drive_sel_3v3 = rtsx_map_sd_drive((reg >> 5) & 0x03);
824 		} else if (bootverbose || sc->rtsx_debug_mask & RTSX_DEBUG_BASIC) {
825 			device_printf(sc->rtsx_dev, "pci_read_config() error - reg: 0x%08x\n", reg);
826 		}
827 		if (bootverbose || sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
828 			device_printf(sc->rtsx_dev, "card_drive_sel: 0x%02x, sd30_drive_sel_3v3: 0x%02x\n",
829 				      sc->rtsx_card_drive_sel, sc->rtsx_sd30_drive_sel_3v3);
830 		break;
831 	case RTSX_RTS525A:
832 	case RTSX_RTS5249:
833 	case RTSX_RTS5260:
834 		sc->rtsx_sd30_drive_sel_3v3 = RTSX_CFG_DRIVER_TYPE_B;
835 		reg = pci_read_config(sc->rtsx_dev, RTSX_PCR_SETTING_REG1, 4);
836 		if ((reg & 0x1000000)) {
837 			sc->rtsx_card_drive_sel &= 0x3F;
838 			sc->rtsx_card_drive_sel |= ((reg >> 25) & 0x01) << 6;
839 			reg = pci_read_config(sc->rtsx_dev, RTSX_PCR_SETTING_REG2, 4);
840 			sc->rtsx_sd30_drive_sel_3v3 = (reg >> 5) & 0x03;
841 			if (reg & 0x4000)
842 				sc->rtsx_flags |= RTSX_F_REVERSE_SOCKET;
843 		} else if (bootverbose || sc->rtsx_debug_mask & RTSX_DEBUG_BASIC) {
844 			device_printf(sc->rtsx_dev, "pci_read_config() error - reg: 0x%08x\n", reg);
845 		}
846 		if (bootverbose || sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
847 			device_printf(sc->rtsx_dev,
848 				      "card_drive_sel = 0x%02x, sd30_drive_sel_3v3: 0x%02x, reverse_socket is %s\n",
849 				      sc->rtsx_card_drive_sel, sc->rtsx_sd30_drive_sel_3v3,
850 				      (sc->rtsx_flags & RTSX_F_REVERSE_SOCKET) ? "true" : "false");
851 		break;
852 	case RTSX_RTL8402:
853 	case RTSX_RTL8411:
854 		sc->rtsx_card_drive_sel = RTSX_RTL8411_CARD_DRIVE_DEFAULT;
855 		sc->rtsx_sd30_drive_sel_3v3 = RTSX_DRIVER_TYPE_D;
856 		reg1 = pci_read_config(sc->rtsx_dev, RTSX_PCR_SETTING_REG1, 4);
857 		if (reg1 & 0x1000000) {
858 			sc->rtsx_card_drive_sel &= 0x3F;
859 			sc->rtsx_card_drive_sel |= ((reg1 >> 25) & 0x01) << 6;
860 			reg3 = pci_read_config(sc->rtsx_dev, RTSX_PCR_SETTING_REG3, 1);
861 			sc->rtsx_sd30_drive_sel_3v3 = (reg3 >> 5) & 0x07;
862 		} else if (bootverbose || sc->rtsx_debug_mask & RTSX_DEBUG_BASIC) {
863 			device_printf(sc->rtsx_dev, "pci_read_config() error - reg1: 0x%08x\n", reg1);
864 		}
865 		if (bootverbose || sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
866 			device_printf(sc->rtsx_dev,
867 				      "card_drive_sel: 0x%02x, sd30_drive_sel_3v3: 0x%02x\n",
868 				      sc->rtsx_card_drive_sel, sc->rtsx_sd30_drive_sel_3v3);
869 		break;
870 	case RTSX_RTL8411B:
871 		sc->rtsx_card_drive_sel = RTSX_RTL8411_CARD_DRIVE_DEFAULT;
872 		sc->rtsx_sd30_drive_sel_3v3 = RTSX_DRIVER_TYPE_D;
873 		reg = pci_read_config(sc->rtsx_dev, RTSX_PCR_SETTING_REG1, 4);
874 		if (!(reg & 0x1000000)) {
875 			sc->rtsx_sd30_drive_sel_3v3 = rtsx_map_sd_drive(reg & 0x03);
876 		} else if (bootverbose || sc->rtsx_debug_mask & RTSX_DEBUG_BASIC) {
877 			device_printf(sc->rtsx_dev, "pci_read_config() error - reg: 0x%08x\n", reg);
878 		}
879 		if (bootverbose || sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
880 			device_printf(sc->rtsx_dev,
881 				      "card_drive_sel: 0x%02x, sd30_drive_sel_3v3: 0x%02x\n",
882 				      sc->rtsx_card_drive_sel, sc->rtsx_sd30_drive_sel_3v3);
883 		break;
884 	}
885 
886 	if (bootverbose || sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
887 		device_printf(sc->rtsx_dev, "rtsx_init() rtsx_flags: 0x%04x\n", sc->rtsx_flags);
888 
889 	/* Enable interrupts. */
890 	sc->rtsx_intr_enabled = RTSX_TRANS_OK_INT_EN | RTSX_TRANS_FAIL_INT_EN | RTSX_SD_INT_EN;
891 	WRITE4(sc, RTSX_BIER, sc->rtsx_intr_enabled);
892 
893 	/* Power on SSC clock. */
894 	RTSX_CLR(sc, RTSX_FPDCTL, RTSX_SSC_POWER_DOWN);
895 	/* Wait SSC power stable. */
896 	DELAY(200);
897 
898 	/* Disable ASPM */
899 	val = pci_read_config(sc->rtsx_dev, sc->rtsx_pcie_cap + PCIER_LINK_CTL, 1);
900 	pci_write_config(sc->rtsx_dev, sc->rtsx_pcie_cap + PCIER_LINK_CTL, val & 0xfc, 1);
901 
902 	/*
903 	 * Optimize phy.
904 	 */
905 	switch (sc->rtsx_device_id) {
906 	case RTSX_RTS5209:
907 		/* Some magic numbers from Linux driver. */
908 		if ((error = rtsx_write_phy(sc, 0x00, 0xB966)))
909 			return (error);
910 		break;
911 	case RTSX_RTS5227:
912 		RTSX_CLR(sc, RTSX_PM_CTRL3, RTSX_D3_DELINK_MODE_EN);
913 
914 		/* Optimize RX sensitivity. */
915 		if ((error = rtsx_write_phy(sc, 0x00, 0xBA42)))
916 			return (error);
917 		break;
918 	case RTSX_RTS5229:
919 		/* Optimize RX sensitivity. */
920 		if ((error = rtsx_write_phy(sc, 0x00, 0xBA42)))
921 			return (error);
922 		break;
923 	case RTSX_RTS522A:
924 		RTSX_CLR(sc, RTSX_RTS522A_PM_CTRL3, RTSX_D3_DELINK_MODE_EN);
925 		if (sc->rtsx_flags & RTSX_F_VERSION_A) {
926 			if ((error = rtsx_write_phy(sc, RTSX_PHY_RCR2, RTSX_PHY_RCR2_INIT_27S)))
927 				return (error);
928 		}
929 		if ((error = rtsx_write_phy(sc, RTSX_PHY_RCR1, RTSX_PHY_RCR1_INIT_27S)))
930 			return (error);
931 		if ((error = rtsx_write_phy(sc, RTSX_PHY_FLD0, RTSX_PHY_FLD0_INIT_27S)))
932 			return (error);
933 		if ((error = rtsx_write_phy(sc, RTSX_PHY_FLD3, RTSX_PHY_FLD3_INIT_27S)))
934 			return (error);
935 		if ((error = rtsx_write_phy(sc, RTSX_PHY_FLD4, RTSX_PHY_FLD4_INIT_27S)))
936 			return (error);
937 		break;
938 	case RTSX_RTS525A:
939 		if ((error = rtsx_write_phy(sc, RTSX__PHY_FLD0,
940 					    RTSX__PHY_FLD0_CLK_REQ_20C | RTSX__PHY_FLD0_RX_IDLE_EN |
941 					    RTSX__PHY_FLD0_BIT_ERR_RSTN | RTSX__PHY_FLD0_BER_COUNT |
942 					    RTSX__PHY_FLD0_BER_TIMER | RTSX__PHY_FLD0_CHECK_EN)))
943 			return (error);
944 		if ((error = rtsx_write_phy(sc, RTSX__PHY_ANA03,
945 					    RTSX__PHY_ANA03_TIMER_MAX | RTSX__PHY_ANA03_OOBS_DEB_EN |
946 					    RTSX__PHY_CMU_DEBUG_EN)))
947 			return (error);
948 		if (sc->rtsx_flags & RTSX_F_VERSION_A)
949 			if ((error = rtsx_write_phy(sc, RTSX__PHY_REV0,
950 						    RTSX__PHY_REV0_FILTER_OUT | RTSX__PHY_REV0_CDR_BYPASS_PFD |
951 						    RTSX__PHY_REV0_CDR_RX_IDLE_BYPASS)))
952 				return (error);
953 		break;
954 	case RTSX_RTS5249:
955 		RTSX_CLR(sc, RTSX_PM_CTRL3, RTSX_D3_DELINK_MODE_EN);
956 		if ((error = rtsx_write_phy(sc, RTSX_PHY_REV,
957 					    RTSX_PHY_REV_RESV | RTSX_PHY_REV_RXIDLE_LATCHED |
958 					    RTSX_PHY_REV_P1_EN | RTSX_PHY_REV_RXIDLE_EN |
959 					    RTSX_PHY_REV_CLKREQ_TX_EN | RTSX_PHY_REV_RX_PWST |
960 					    RTSX_PHY_REV_CLKREQ_DT_1_0 | RTSX_PHY_REV_STOP_CLKRD |
961 					    RTSX_PHY_REV_STOP_CLKWR)))
962 			return (error);
963 		DELAY(1000);
964 		if ((error = rtsx_write_phy(sc, RTSX_PHY_BPCR,
965 					    RTSX_PHY_BPCR_IBRXSEL | RTSX_PHY_BPCR_IBTXSEL |
966 					    RTSX_PHY_BPCR_IB_FILTER | RTSX_PHY_BPCR_CMIRROR_EN)))
967 			return (error);
968 		if ((error = rtsx_write_phy(sc, RTSX_PHY_PCR,
969 					    RTSX_PHY_PCR_FORCE_CODE | RTSX_PHY_PCR_OOBS_CALI_50 |
970 					    RTSX_PHY_PCR_OOBS_VCM_08 | RTSX_PHY_PCR_OOBS_SEN_90 |
971 					    RTSX_PHY_PCR_RSSI_EN | RTSX_PHY_PCR_RX10K)))
972 			return (error);
973 		if ((error = rtsx_write_phy(sc, RTSX_PHY_RCR2,
974 					    RTSX_PHY_RCR2_EMPHASE_EN | RTSX_PHY_RCR2_NADJR |
975 					    RTSX_PHY_RCR2_CDR_SR_2 | RTSX_PHY_RCR2_FREQSEL_12 |
976 					    RTSX_PHY_RCR2_CDR_SC_12P | RTSX_PHY_RCR2_CALIB_LATE)))
977 			return (error);
978 		if ((error = rtsx_write_phy(sc, RTSX_PHY_FLD4,
979 					    RTSX_PHY_FLD4_FLDEN_SEL | RTSX_PHY_FLD4_REQ_REF |
980 					    RTSX_PHY_FLD4_RXAMP_OFF | RTSX_PHY_FLD4_REQ_ADDA |
981 					    RTSX_PHY_FLD4_BER_COUNT | RTSX_PHY_FLD4_BER_TIMER |
982 					    RTSX_PHY_FLD4_BER_CHK_EN)))
983 			return (error);
984 		if ((error = rtsx_write_phy(sc, RTSX_PHY_RDR,
985 					    RTSX_PHY_RDR_RXDSEL_1_9 | RTSX_PHY_SSC_AUTO_PWD)))
986 			return (error);
987 		if ((error = rtsx_write_phy(sc, RTSX_PHY_RCR1,
988 					    RTSX_PHY_RCR1_ADP_TIME_4 | RTSX_PHY_RCR1_VCO_COARSE)))
989 			return (error);
990 		if ((error = rtsx_write_phy(sc, RTSX_PHY_FLD3,
991 					    RTSX_PHY_FLD3_TIMER_4 | RTSX_PHY_FLD3_TIMER_6 |
992 					    RTSX_PHY_FLD3_RXDELINK)))
993 			return (error);
994 		if ((error = rtsx_write_phy(sc, RTSX_PHY_TUNE,
995 					    RTSX_PHY_TUNE_TUNEREF_1_0 | RTSX_PHY_TUNE_VBGSEL_1252 |
996 					    RTSX_PHY_TUNE_SDBUS_33 | RTSX_PHY_TUNE_TUNED18 |
997 					    RTSX_PHY_TUNE_TUNED12 | RTSX_PHY_TUNE_TUNEA12)))
998 			return (error);
999 		break;
1000 	}
1001 
1002 	/* Set mcu_cnt to 7 to ensure data can be sampled properly. */
1003 	RTSX_BITOP(sc, RTSX_CLK_DIV, 0x07, 0x07);
1004 
1005 	/* Disable sleep mode. */
1006 	RTSX_CLR(sc, RTSX_HOST_SLEEP_STATE,
1007 		 RTSX_HOST_ENTER_S1 | RTSX_HOST_ENTER_S3);
1008 
1009 	/* Disable card clock. */
1010 	RTSX_CLR(sc, RTSX_CARD_CLK_EN, RTSX_CARD_CLK_EN_ALL);
1011 
1012 	/* Reset delink mode. */
1013 	RTSX_CLR(sc, RTSX_CHANGE_LINK_STATE,
1014 		 RTSX_FORCE_RST_CORE_EN | RTSX_NON_STICKY_RST_N_DBG);
1015 
1016 	/* Card driving select. */
1017 	RTSX_WRITE(sc, RTSX_CARD_DRIVE_SEL, sc->rtsx_card_drive_sel);
1018 
1019 	/* Enable SSC clock. */
1020 	RTSX_WRITE(sc, RTSX_SSC_CTL1, RTSX_SSC_8X_EN | RTSX_SSC_SEL_4M);
1021 	RTSX_WRITE(sc, RTSX_SSC_CTL2, 0x12);
1022 
1023 	/* Disable cd_pwr_save. */
1024 	RTSX_BITOP(sc, RTSX_CHANGE_LINK_STATE, 0x16, RTSX_MAC_PHY_RST_N_DBG);
1025 
1026 	/* Clear Link Ready Interrupt. */
1027 	RTSX_BITOP(sc, RTSX_IRQSTAT0, RTSX_LINK_READY_INT, RTSX_LINK_READY_INT);
1028 
1029 	/* Enlarge the estimation window of PERST# glitch
1030 	 * to reduce the chance of invalid card interrupt. */
1031 	RTSX_WRITE(sc, RTSX_PERST_GLITCH_WIDTH, 0x80);
1032 
1033 	/* Set RC oscillator to 400K. */
1034 	RTSX_CLR(sc, RTSX_RCCTL, RTSX_RCCTL_F_2M);
1035 
1036 	/* Enable interrupt write-clear (default is read-clear). */
1037 	RTSX_CLR(sc, RTSX_NFTS_TX_CTRL, RTSX_INT_READ_CLR);
1038 
1039 	switch (sc->rtsx_device_id) {
1040 	case RTSX_RTS525A:
1041 	case RTSX_RTS5260:
1042 		RTSX_BITOP(sc, RTSX_PM_CLK_FORCE_CTL, 1, 1);
1043 		break;
1044 	}
1045 
1046 	/* OC power down. */
1047 	RTSX_BITOP(sc, RTSX_FPDCTL, RTSX_SD_OC_POWER_DOWN, RTSX_SD_OC_POWER_DOWN);
1048 
1049 	/* Enable clk_request_n to enable clock power management */
1050 	pci_write_config(sc->rtsx_dev, sc->rtsx_pcie_cap + PCIER_LINK_CTL + 1, 1, 1);
1051 
1052 	/* Enter L1 when host tx idle */
1053 	pci_write_config(sc->rtsx_dev, 0x70F, 0x5B, 1);
1054 
1055 	/*
1056 	 * Specific extra init.
1057 	 */
1058 	switch (sc->rtsx_device_id) {
1059 		uint16_t cap;
1060 	case RTSX_RTS5209:
1061 		/* Turn off LED. */
1062 		RTSX_WRITE(sc, RTSX_CARD_GPIO, 0x03);
1063 		/* Reset ASPM state to default value. */
1064 		RTSX_CLR(sc, RTSX_ASPM_FORCE_CTL, RTSX_ASPM_FORCE_MASK);
1065 		/* Force CLKREQ# PIN to drive 0 to request clock. */
1066 		RTSX_BITOP(sc, RTSX_PETXCFG, 0x08, 0x08);
1067 		/* Configure GPIO as output. */
1068 		RTSX_WRITE(sc, RTSX_CARD_GPIO_DIR, 0x03);
1069 		/* Configure driving. */
1070 		RTSX_WRITE(sc, RTSX_SD30_CMD_DRIVE_SEL, sc->rtsx_sd30_drive_sel_3v3);
1071 		break;
1072 	case RTSX_RTS5227:
1073 		/* Configure GPIO as output. */
1074 		RTSX_BITOP(sc, RTSX_GPIO_CTL, RTSX_GPIO_LED_ON, RTSX_GPIO_LED_ON);
1075 		/* Reset ASPM state to default value. */
1076 		RTSX_BITOP(sc, RTSX_ASPM_FORCE_CTL, RTSX_ASPM_FORCE_MASK, RTSX_FORCE_ASPM_NO_ASPM);
1077 		/* Switch LDO3318 source from DV33 to 3V3. */
1078 		RTSX_CLR(sc, RTSX_LDO_PWR_SEL, RTSX_LDO_PWR_SEL_DV33);
1079 		RTSX_BITOP(sc, RTSX_LDO_PWR_SEL, RTSX_LDO_PWR_SEL_DV33, RTSX_LDO_PWR_SEL_3V3);
1080 		/* Set default OLT blink period. */
1081 		RTSX_BITOP(sc, RTSX_OLT_LED_CTL, 0x0F, RTSX_OLT_LED_PERIOD);
1082 		/* Configure LTR. */
1083 		cap = pci_read_config(sc->rtsx_dev, sc->rtsx_pcie_cap + PCIER_DEVICE_CTL2, 2);
1084 		if (cap & PCIEM_CTL2_LTR_ENABLE)
1085 			RTSX_WRITE(sc, RTSX_LTR_CTL, 0xa3);
1086 		/* Configure OBFF. */
1087 		RTSX_BITOP(sc, RTSX_OBFF_CFG, RTSX_OBFF_EN_MASK, RTSX_OBFF_ENABLE);
1088 		/* Configure driving. */
1089 		if ((error = rtsx_rts5227_fill_driving(sc)))
1090 			return (error);
1091 		/* Configure force_clock_req. */
1092 		if (sc->rtsx_flags & RTSX_F_REVERSE_SOCKET)
1093 			RTSX_BITOP(sc, RTSX_PETXCFG, 0xB8, 0xB8);
1094 		else
1095 			RTSX_BITOP(sc, RTSX_PETXCFG, 0xB8, 0x88);
1096 		RTSX_CLR(sc, RTSX_PM_CTRL3, RTSX_D3_DELINK_MODE_EN);
1097 		/*!!! Added for reboot after Windows. */
1098 		RTSX_BITOP(sc, RTSX_PM_CTRL3, RTSX_PM_WAKE_EN, RTSX_PM_WAKE_EN);
1099 		break;
1100 	case RTSX_RTS5229:
1101 		/* Configure GPIO as output. */
1102 		RTSX_BITOP(sc, RTSX_GPIO_CTL, RTSX_GPIO_LED_ON, RTSX_GPIO_LED_ON);
1103 		/* Reset ASPM state to default value. */
1104 		/*  With this reset: dd if=/dev/random of=/dev/mmcsd0 encounter a timeout. */
1105 //!!!		RTSX_BITOP(sc, RTSX_ASPM_FORCE_CTL, RTSX_ASPM_FORCE_MASK, RTSX_FORCE_ASPM_NO_ASPM);
1106 		/* Force CLKREQ# PIN to drive 0 to request clock. */
1107 		RTSX_BITOP(sc, RTSX_PETXCFG, 0x08, 0x08);
1108 		/* Switch LDO3318 source from DV33 to card_3v3. */
1109 		RTSX_CLR(sc, RTSX_LDO_PWR_SEL, RTSX_LDO_PWR_SEL_DV33);
1110 		RTSX_BITOP(sc, RTSX_LDO_PWR_SEL, RTSX_LDO_PWR_SEL_DV33, RTSX_LDO_PWR_SEL_3V3);
1111 		/* Set default OLT blink period. */
1112 		RTSX_BITOP(sc, RTSX_OLT_LED_CTL, 0x0F, RTSX_OLT_LED_PERIOD);
1113 		/* Configure driving. */
1114 		RTSX_WRITE(sc, RTSX_SD30_CMD_DRIVE_SEL, sc->rtsx_sd30_drive_sel_3v3);
1115 		break;
1116 	case RTSX_RTS522A:
1117 		/* Add specific init from RTS5227. */
1118 		/* Configure GPIO as output. */
1119 		RTSX_BITOP(sc, RTSX_GPIO_CTL, RTSX_GPIO_LED_ON, RTSX_GPIO_LED_ON);
1120 		/* Reset ASPM state to default value. */
1121 		RTSX_BITOP(sc, RTSX_ASPM_FORCE_CTL, RTSX_ASPM_FORCE_MASK, RTSX_FORCE_ASPM_NO_ASPM);
1122 		/* Switch LDO3318 source from DV33 to 3V3. */
1123 		RTSX_CLR(sc, RTSX_LDO_PWR_SEL, RTSX_LDO_PWR_SEL_DV33);
1124 		RTSX_BITOP(sc, RTSX_LDO_PWR_SEL, RTSX_LDO_PWR_SEL_DV33, RTSX_LDO_PWR_SEL_3V3);
1125 		/* Set default OLT blink period. */
1126 		RTSX_BITOP(sc, RTSX_OLT_LED_CTL, 0x0F, RTSX_OLT_LED_PERIOD);
1127 		/* Configure LTR. */
1128 		cap = pci_read_config(sc->rtsx_dev, sc->rtsx_pcie_cap + PCIER_DEVICE_CTL2, 2);
1129 		if (cap & PCIEM_CTL2_LTR_ENABLE)
1130 			RTSX_WRITE(sc, RTSX_LTR_CTL, 0xa3);
1131 		/* Configure OBFF. */
1132 		RTSX_BITOP(sc, RTSX_OBFF_CFG, RTSX_OBFF_EN_MASK, RTSX_OBFF_ENABLE);
1133 		/* Configure driving. */
1134 		if ((error = rtsx_rts5227_fill_driving(sc)))
1135 			return (error);
1136 		/* Configure force_clock_req. */
1137 		if (sc->rtsx_flags & RTSX_F_REVERSE_SOCKET)
1138 			RTSX_BITOP(sc, RTSX_PETXCFG, 0xB8, 0xB8);
1139 		else
1140 			RTSX_BITOP(sc, RTSX_PETXCFG, 0xB8, 0x88);
1141 		RTSX_CLR(sc, RTSX_RTS522A_PM_CTRL3,  0x10);
1142 
1143 		/* specific for RTS522A. */
1144 		RTSX_BITOP(sc, RTSX_FUNC_FORCE_CTL,
1145 			   RTSX_FUNC_FORCE_UPME_XMT_DBG, RTSX_FUNC_FORCE_UPME_XMT_DBG);
1146 		RTSX_BITOP(sc, RTSX_PCLK_CTL, 0x04, 0x04);
1147 		RTSX_BITOP(sc, RTSX_PM_EVENT_DEBUG,
1148 			   RTSX_PME_DEBUG_0, RTSX_PME_DEBUG_0);
1149 		RTSX_WRITE(sc, RTSX_PM_CLK_FORCE_CTL, 0x11);
1150 		break;
1151 	case RTSX_RTS525A:
1152 		/* Add specific init from RTS5249. */
1153 		/* Rest L1SUB Config. */
1154 		RTSX_CLR(sc, RTSX_L1SUB_CONFIG3, 0xff);
1155 		/* Configure GPIO as output. */
1156 		RTSX_BITOP(sc, RTSX_GPIO_CTL, RTSX_GPIO_LED_ON, RTSX_GPIO_LED_ON);
1157 		/* Reset ASPM state to default value. */
1158 		RTSX_BITOP(sc, RTSX_ASPM_FORCE_CTL, RTSX_ASPM_FORCE_MASK, RTSX_FORCE_ASPM_NO_ASPM);
1159 		/* Switch LDO3318 source from DV33 to 3V3. */
1160 		RTSX_CLR(sc, RTSX_LDO_PWR_SEL, RTSX_LDO_PWR_SEL_DV33);
1161 		RTSX_BITOP(sc, RTSX_LDO_PWR_SEL, RTSX_LDO_PWR_SEL_DV33, RTSX_LDO_PWR_SEL_3V3);
1162 		/* Set default OLT blink period. */
1163 		RTSX_BITOP(sc, RTSX_OLT_LED_CTL, 0x0F, RTSX_OLT_LED_PERIOD);
1164 		/* Configure driving. */
1165 		if ((error = rtsx_rts5249_fill_driving(sc)))
1166 			return (error);
1167 		/* Configure force_clock_req. */
1168 		if (sc->rtsx_flags & RTSX_F_REVERSE_SOCKET)
1169 			RTSX_BITOP(sc, RTSX_PETXCFG, 0xB0, 0xB0);
1170 		else
1171 			RTSX_BITOP(sc, RTSX_PETXCFG, 0xB0, 0x80);
1172 
1173 		/* Specifc for RTS525A. */
1174 		RTSX_BITOP(sc, RTSX_PCLK_CTL, RTSX_PCLK_MODE_SEL, RTSX_PCLK_MODE_SEL);
1175 		if (sc->rtsx_flags & RTSX_F_VERSION_A) {
1176 			RTSX_WRITE(sc, RTSX_L1SUB_CONFIG2, RTSX_L1SUB_AUTO_CFG);
1177 			RTSX_BITOP(sc, RTSX_RREF_CFG,
1178 				   RTSX_RREF_VBGSEL_MASK, RTSX_RREF_VBGSEL_1V25);
1179 			RTSX_BITOP(sc, RTSX_LDO_VIO_CFG,
1180 				   RTSX_LDO_VIO_TUNE_MASK, RTSX_LDO_VIO_1V7);
1181 			RTSX_BITOP(sc, RTSX_LDO_DV12S_CFG,
1182 				   RTSX_LDO_D12_TUNE_MASK, RTSX_LDO_D12_TUNE_DF);
1183 			RTSX_BITOP(sc, RTSX_LDO_AV12S_CFG,
1184 				   RTSX_LDO_AV12S_TUNE_MASK, RTSX_LDO_AV12S_TUNE_DF);
1185 			RTSX_BITOP(sc, RTSX_LDO_VCC_CFG0,
1186 				   RTSX_LDO_VCC_LMTVTH_MASK, RTSX_LDO_VCC_LMTVTH_2A);
1187 			RTSX_BITOP(sc, RTSX_OOBS_CONFIG,
1188 				   RTSX_OOBS_AUTOK_DIS | RTSX_OOBS_VAL_MASK, 0x89);
1189 		}
1190 		break;
1191 	case RTSX_RTS5249:
1192 		/* Rest L1SUB Config. */
1193 		RTSX_CLR(sc, RTSX_L1SUB_CONFIG3, 0xff);
1194 		/* Configure GPIO as output. */
1195 		RTSX_BITOP(sc, RTSX_GPIO_CTL, RTSX_GPIO_LED_ON, RTSX_GPIO_LED_ON);
1196 		/* Reset ASPM state to default value. */
1197 		RTSX_BITOP(sc, RTSX_ASPM_FORCE_CTL, RTSX_ASPM_FORCE_MASK, RTSX_FORCE_ASPM_NO_ASPM);
1198 		/* Switch LDO3318 source from DV33 to 3V3. */
1199 		RTSX_CLR(sc, RTSX_LDO_PWR_SEL, RTSX_LDO_PWR_SEL_DV33);
1200 		RTSX_BITOP(sc, RTSX_LDO_PWR_SEL, RTSX_LDO_PWR_SEL_DV33, RTSX_LDO_PWR_SEL_3V3);
1201 		/* Set default OLT blink period. */
1202 		RTSX_BITOP(sc, RTSX_OLT_LED_CTL, 0x0F, RTSX_OLT_LED_PERIOD);
1203 		/* Configure driving. */
1204 		if ((error = rtsx_rts5249_fill_driving(sc)))
1205 			return (error);
1206 		/* Configure force_clock_req. */
1207 		if (sc->rtsx_flags & RTSX_F_REVERSE_SOCKET)
1208 			RTSX_BITOP(sc, RTSX_PETXCFG, 0xB0, 0xB0);
1209 		else
1210 			RTSX_BITOP(sc, RTSX_PETXCFG, 0xB0, 0x80);
1211 		break;
1212 	case RTSX_RTS5260:
1213 		/* Set mcu_cnt to 7 to ensure data can be sampled properly. */
1214 		RTSX_BITOP(sc, RTSX_CLK_DIV, 0x07, 0x07);
1215 		RTSX_WRITE(sc, RTSX_SSC_DIV_N_0, 0x5D);
1216 		/* Force no MDIO */
1217 		RTSX_WRITE(sc, RTSX_RTS5260_AUTOLOAD_CFG4, RTSX_RTS5260_MIMO_DISABLE);
1218 		/* Modify SDVCC Tune Default Parameters! */
1219 		RTSX_BITOP(sc, RTSX_LDO_VCC_CFG0, RTSX_RTS5260_DVCC_TUNE_MASK, RTSX_RTS5260_DVCC_33);
1220 
1221 		RTSX_BITOP(sc, RTSX_PCLK_CTL, RTSX_PCLK_MODE_SEL, RTSX_PCLK_MODE_SEL);
1222 
1223 		RTSX_BITOP(sc, RTSX_L1SUB_CONFIG1, RTSX_AUX_CLK_ACTIVE_SEL_MASK, RTSX_MAC_CKSW_DONE);
1224 		/* Rest L1SUB Config */
1225 		RTSX_CLR(sc, RTSX_L1SUB_CONFIG3, 0xFF);
1226 		RTSX_BITOP(sc, RTSX_PM_CLK_FORCE_CTL, RTSX_CLK_PM_EN, RTSX_CLK_PM_EN);
1227 		RTSX_WRITE(sc, RTSX_PWD_SUSPEND_EN, 0xFF);
1228 		RTSX_BITOP(sc, RTSX_PWR_GATE_CTRL, RTSX_PWR_GATE_EN, RTSX_PWR_GATE_EN);
1229 		RTSX_BITOP(sc, RTSX_REG_VREF, RTSX_PWD_SUSPND_EN, RTSX_PWD_SUSPND_EN);
1230 		RTSX_BITOP(sc, RTSX_RBCTL, RTSX_U_AUTO_DMA_EN_MASK, RTSX_U_AUTO_DMA_DISABLE);
1231 		if (sc->rtsx_flags & RTSX_F_REVERSE_SOCKET)
1232 			RTSX_BITOP(sc, RTSX_PETXCFG, 0xB0, 0xB0);
1233 		else
1234 			RTSX_BITOP(sc, RTSX_PETXCFG, 0xB0, 0x80);
1235 		RTSX_BITOP(sc, RTSX_OBFF_CFG, RTSX_OBFF_EN_MASK, RTSX_OBFF_DISABLE);
1236 
1237 		RTSX_CLR(sc, RTSX_RTS5260_DVCC_CTRL, RTSX_RTS5260_DVCC_OCP_EN | RTSX_RTS5260_DVCC_OCP_CL_EN);
1238 
1239 		/* CLKREQ# PIN will be forced to drive low. */
1240 		RTSX_BITOP(sc, RTSX_PETXCFG, RTSX_FORCE_CLKREQ_DELINK_MASK, RTSX_FORCE_CLKREQ_LOW);
1241 
1242 		RTSX_CLR(sc, RTSX_RTS522A_PM_CTRL3,  0x10);
1243 		break;
1244 	case RTSX_RTL8402:
1245 	case RTSX_RTL8411:
1246 		RTSX_WRITE(sc, RTSX_SD30_CMD_DRIVE_SEL, sc->rtsx_sd30_drive_sel_3v3);
1247 		RTSX_BITOP(sc, RTSX_CARD_PAD_CTL, RTSX_CD_DISABLE_MASK | RTSX_CD_AUTO_DISABLE,
1248 			   RTSX_CD_ENABLE);
1249 		break;
1250 	case RTSX_RTL8411B:
1251 		if (sc->rtsx_flags & RTSX_F_8411B_QFN48)
1252 			RTSX_WRITE(sc, RTSX_CARD_PULL_CTL3, 0xf5);
1253 		RTSX_WRITE(sc, RTSX_SD30_CMD_DRIVE_SEL, sc->rtsx_sd30_drive_sel_3v3);
1254 		/* Enable SD interrupt. */
1255 		RTSX_BITOP(sc, RTSX_CARD_PAD_CTL, RTSX_CD_DISABLE_MASK | RTSX_CD_AUTO_DISABLE,
1256 			   RTSX_CD_ENABLE);
1257 		/* Clear hw_pfm_en to disable hardware PFM mode. */
1258 		RTSX_BITOP(sc, RTSX_FUNC_FORCE_CTL, 0x06, 0x00);
1259 		break;
1260 	}
1261 
1262 	/*!!! Added for reboot after Windows. */
1263 	rtsx_bus_power_off(sc);
1264 	rtsx_set_sd_timing(sc, bus_timing_normal);
1265 	rtsx_set_sd_clock(sc, 0);
1266 	/*!!! Added for reboot after Windows. */
1267 
1268 	return (0);
1269 }
1270 
1271 static int
1272 rtsx_map_sd_drive(int index)
1273 {
1274 	uint8_t	sd_drive[4] =
1275 		{
1276 		 0x01,	/* Type D */
1277 		 0x02,	/* Type C */
1278 		 0x05,	/* Type A */
1279 		 0x03	/* Type B */
1280 		};
1281 	return (sd_drive[index]);
1282 }
1283 
1284 /* For voltage 3v3. */
1285 static int
1286 rtsx_rts5227_fill_driving(struct rtsx_softc *sc)
1287 {
1288 	u_char	driving_3v3[4][3] = {
1289 				     {0x13, 0x13, 0x13},
1290 				     {0x96, 0x96, 0x96},
1291 				     {0x7F, 0x7F, 0x7F},
1292 				     {0x96, 0x96, 0x96},
1293 	};
1294 	RTSX_WRITE(sc, RTSX_SD30_CLK_DRIVE_SEL, driving_3v3[sc->rtsx_sd30_drive_sel_3v3][0]);
1295 	RTSX_WRITE(sc, RTSX_SD30_CMD_DRIVE_SEL, driving_3v3[sc->rtsx_sd30_drive_sel_3v3][1]);
1296 	RTSX_WRITE(sc, RTSX_SD30_DAT_DRIVE_SEL, driving_3v3[sc->rtsx_sd30_drive_sel_3v3][2]);
1297 
1298 	return (0);
1299 }
1300 
1301 /* For voltage 3v3. */
1302 static int
1303 rtsx_rts5249_fill_driving(struct rtsx_softc *sc)
1304 {
1305 	u_char	driving_3v3[4][3] = {
1306 				     {0x11, 0x11, 0x18},
1307 				     {0x55, 0x55, 0x5C},
1308 				     {0xFF, 0xFF, 0xFF},
1309 				     {0x96, 0x96, 0x96},
1310 	};
1311 	RTSX_WRITE(sc, RTSX_SD30_CLK_DRIVE_SEL, driving_3v3[sc->rtsx_sd30_drive_sel_3v3][0]);
1312 	RTSX_WRITE(sc, RTSX_SD30_CMD_DRIVE_SEL, driving_3v3[sc->rtsx_sd30_drive_sel_3v3][1]);
1313 	RTSX_WRITE(sc, RTSX_SD30_DAT_DRIVE_SEL, driving_3v3[sc->rtsx_sd30_drive_sel_3v3][2]);
1314 
1315 	return (0);
1316 }
1317 
1318 static int
1319 rtsx_rts5260_fill_driving(struct rtsx_softc *sc)
1320 {
1321 	u_char	driving_3v3[4][3] = {
1322 				     {0x11, 0x11, 0x11},
1323 				     {0x22, 0x22, 0x22},
1324 				     {0x55, 0x55, 0x55},
1325 				     {0x33, 0x33, 0x33},
1326 	};
1327 	RTSX_WRITE(sc, RTSX_SD30_CLK_DRIVE_SEL, driving_3v3[sc->rtsx_sd30_drive_sel_3v3][0]);
1328 	RTSX_WRITE(sc, RTSX_SD30_CMD_DRIVE_SEL, driving_3v3[sc->rtsx_sd30_drive_sel_3v3][1]);
1329 	RTSX_WRITE(sc, RTSX_SD30_DAT_DRIVE_SEL, driving_3v3[sc->rtsx_sd30_drive_sel_3v3][2]);
1330 
1331 	return (0);
1332 }
1333 
1334 static int
1335 rtsx_read(struct rtsx_softc *sc, uint16_t addr, uint8_t *val)
1336 {
1337 	int	 tries = 1024;
1338 	uint32_t arg;
1339 	uint32_t reg;
1340 
1341 	arg = RTSX_HAIMR_BUSY | (uint32_t)((addr & 0x3FFF) << 16);
1342 	WRITE4(sc, RTSX_HAIMR, arg);
1343 
1344 	while (tries--) {
1345 		reg = READ4(sc, RTSX_HAIMR);
1346 		if (!(reg & RTSX_HAIMR_BUSY))
1347 			break;
1348 	}
1349 	*val = (reg & 0xff);
1350 
1351 	if (tries > 0) {
1352 		return (0);
1353 	} else {
1354 		device_printf(sc->rtsx_dev, "rtsx_read(0x%x) timeout\n", arg);
1355 		return (ETIMEDOUT);
1356 	}
1357 }
1358 
1359 static int
1360 rtsx_read_cfg(struct rtsx_softc *sc, uint8_t func, uint16_t addr, uint32_t *val)
1361 {
1362 	int	tries = 1024;
1363 	uint8_t	data0, data1, data2, data3, rwctl;
1364 
1365 	RTSX_WRITE(sc, RTSX_CFGADDR0, addr);
1366 	RTSX_WRITE(sc, RTSX_CFGADDR1, addr >> 8);
1367 	RTSX_WRITE(sc, RTSX_CFGRWCTL, RTSX_CFG_BUSY | (func & 0x03 << 4));
1368 
1369 	while (tries--) {
1370 		RTSX_READ(sc, RTSX_CFGRWCTL, &rwctl);
1371 		if (!(rwctl & RTSX_CFG_BUSY))
1372 			break;
1373 	}
1374 
1375 	if (tries == 0)
1376 		return (ETIMEDOUT);
1377 
1378 	RTSX_READ(sc, RTSX_CFGDATA0, &data0);
1379 	RTSX_READ(sc, RTSX_CFGDATA1, &data1);
1380 	RTSX_READ(sc, RTSX_CFGDATA2, &data2);
1381 	RTSX_READ(sc, RTSX_CFGDATA3, &data3);
1382 
1383 	*val = (data3 << 24) | (data2 << 16) | (data1 << 8) | data0;
1384 
1385 	return (0);
1386 }
1387 
1388 static int
1389 rtsx_write(struct rtsx_softc *sc, uint16_t addr, uint8_t mask, uint8_t val)
1390 {
1391 	int 	 tries = 1024;
1392 	uint32_t arg;
1393 	uint32_t reg;
1394 
1395 	arg = RTSX_HAIMR_BUSY | RTSX_HAIMR_WRITE |
1396 		(uint32_t)(((addr & 0x3FFF) << 16) |
1397 			   (mask << 8) | val);
1398 	WRITE4(sc, RTSX_HAIMR, arg);
1399 
1400 	while (tries--) {
1401 		reg = READ4(sc, RTSX_HAIMR);
1402 		if (!(reg & RTSX_HAIMR_BUSY)) {
1403 			if (val != (reg & 0xff)) {
1404 				device_printf(sc->rtsx_dev, "rtsx_write(0x%x) error reg=0x%x\n", arg, reg);
1405 				return (EIO);
1406 			}
1407 			return (0);
1408 		}
1409 	}
1410 	device_printf(sc->rtsx_dev, "rtsx_write(0x%x) timeout\n", arg);
1411 
1412 	return (ETIMEDOUT);
1413 }
1414 
1415 static int
1416 rtsx_read_phy(struct rtsx_softc *sc, uint8_t addr, uint16_t *val)
1417 {
1418 	int	tries = 100000;
1419 	uint8_t	data0, data1, rwctl;
1420 
1421 	RTSX_WRITE(sc, RTSX_PHY_ADDR, addr);
1422 	RTSX_WRITE(sc, RTSX_PHY_RWCTL, RTSX_PHY_BUSY | RTSX_PHY_READ);
1423 
1424 	while (tries--) {
1425 		RTSX_READ(sc, RTSX_PHY_RWCTL, &rwctl);
1426 		if (!(rwctl & RTSX_PHY_BUSY))
1427 			break;
1428 	}
1429 	if (tries == 0)
1430 		return (ETIMEDOUT);
1431 
1432 	RTSX_READ(sc, RTSX_PHY_DATA0, &data0);
1433 	RTSX_READ(sc, RTSX_PHY_DATA1, &data1);
1434 	*val = data1 << 8 | data0;
1435 
1436 	return (0);
1437 }
1438 
1439 static int
1440 rtsx_write_phy(struct rtsx_softc *sc, uint8_t addr, uint16_t val)
1441 {
1442 	int	tries = 100000;
1443 	uint8_t	rwctl;
1444 
1445 	RTSX_WRITE(sc, RTSX_PHY_DATA0, val);
1446 	RTSX_WRITE(sc, RTSX_PHY_DATA1, val >> 8);
1447 	RTSX_WRITE(sc, RTSX_PHY_ADDR, addr);
1448 	RTSX_WRITE(sc, RTSX_PHY_RWCTL, RTSX_PHY_BUSY | RTSX_PHY_WRITE);
1449 
1450 	while (tries--) {
1451 		RTSX_READ(sc, RTSX_PHY_RWCTL, &rwctl);
1452 		if (!(rwctl & RTSX_PHY_BUSY))
1453 			break;
1454 	}
1455 
1456 	return ((tries == 0) ? ETIMEDOUT : 0);
1457 }
1458 
1459 /*
1460  * Notice that the meaning of RTSX_PWR_GATE_CTRL changes between RTS5209 and
1461  * RTS5229. In RTS5209 it is a mask of disabled power gates, while in RTS5229
1462  * it is a mask of *enabled* gates.
1463  */
1464 static int
1465 rtsx_bus_power_off(struct rtsx_softc *sc)
1466 {
1467 	if (sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
1468 		device_printf(sc->rtsx_dev, "rtsx_bus_power_off()\n");
1469 
1470 	/* Disable SD clock. */
1471 	RTSX_CLR(sc, RTSX_CARD_CLK_EN, RTSX_SD_CLK_EN);
1472 
1473 	/* Disable SD output. */
1474 	RTSX_CLR(sc, RTSX_CARD_OE, RTSX_SD_OUTPUT_EN);
1475 
1476 	/* Turn off power. */
1477 	switch (sc->rtsx_device_id) {
1478 	case RTSX_RTS5209:
1479 		RTSX_BITOP(sc, RTSX_CARD_PWR_CTL, RTSX_SD_PWR_MASK | RTSX_PMOS_STRG_MASK,
1480 			   RTSX_SD_PWR_OFF | RTSX_PMOS_STRG_400mA);
1481 		RTSX_SET(sc, RTSX_PWR_GATE_CTRL, RTSX_LDO3318_OFF);
1482 		break;
1483 	case RTSX_RTS5227:
1484 	case RTSX_RTS5229:
1485 	case RTSX_RTS522A:
1486 		RTSX_BITOP(sc, RTSX_CARD_PWR_CTL, RTSX_SD_PWR_MASK | RTSX_PMOS_STRG_MASK,
1487 			   RTSX_SD_PWR_OFF | RTSX_PMOS_STRG_400mA);
1488 		RTSX_CLR(sc, RTSX_PWR_GATE_CTRL, RTSX_LDO3318_PWR_MASK);
1489 		break;
1490 	case RTSX_RTS5260:
1491 		rtsx_stop_cmd(sc);
1492 		/* Switch vccq to 330 */
1493 		RTSX_BITOP(sc, RTSX_LDO_CONFIG2, RTSX_DV331812_VDD1, RTSX_DV331812_VDD1);
1494 		RTSX_BITOP(sc, RTSX_LDO_DV18_CFG, RTSX_DV331812_MASK, RTSX_DV331812_33);
1495 		RTSX_CLR(sc, RTSX_SD_PAD_CTL, RTSX_SD_IO_USING_1V8);
1496 		rtsx_rts5260_fill_driving(sc);
1497 
1498 		RTSX_BITOP(sc, RTSX_LDO_VCC_CFG1, RTSX_LDO_POW_SDVDD1_MASK, RTSX_LDO_POW_SDVDD1_OFF);
1499 		RTSX_BITOP(sc, RTSX_LDO_CONFIG2, RTSX_DV331812_POWERON, RTSX_DV331812_POWEROFF);
1500 		break;
1501 	case RTSX_RTL8402:
1502 	case RTSX_RTL8411:
1503 	case RTSX_RTL8411B:
1504 		RTSX_BITOP(sc, RTSX_CARD_PWR_CTL, RTSX_BPP_POWER_MASK,
1505 			   RTSX_BPP_POWER_OFF);
1506 		RTSX_BITOP(sc, RTSX_LDO_CTL, RTSX_BPP_LDO_POWB,
1507 			   RTSX_BPP_LDO_SUSPEND);
1508 		break;
1509 	default:
1510 		RTSX_CLR(sc, RTSX_PWR_GATE_CTRL, RTSX_LDO3318_PWR_MASK);
1511 		RTSX_SET(sc, RTSX_CARD_PWR_CTL, RTSX_SD_PWR_OFF);
1512 		RTSX_CLR(sc, RTSX_CARD_PWR_CTL, RTSX_PMOS_STRG_800mA);
1513 		break;
1514 	}
1515 
1516 	/* Disable pull control. */
1517 	switch (sc->rtsx_device_id) {
1518 	case RTSX_RTS5209:
1519 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL1, RTSX_PULL_CTL_DISABLE12);
1520 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL2, RTSX_PULL_CTL_DISABLE12);
1521 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL3, RTSX_PULL_CTL_DISABLE3);
1522 		break;
1523 	case RTSX_RTS5227:
1524 	case RTSX_RTS522A:
1525 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL2, RTSX_PULL_CTL_DISABLE12);
1526 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL3, RTSX_PULL_CTL_DISABLE3);
1527 		break;
1528 	case RTSX_RTS5229:
1529 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL2, RTSX_PULL_CTL_DISABLE12);
1530 		if (sc->rtsx_flags & RTSX_F_VERSION_C)
1531 			RTSX_WRITE(sc, RTSX_CARD_PULL_CTL3, RTSX_PULL_CTL_DISABLE3_TYPE_C);
1532 		else
1533 			RTSX_WRITE(sc, RTSX_CARD_PULL_CTL3, RTSX_PULL_CTL_DISABLE3);
1534 		break;
1535 	case RTSX_RTS525A:
1536 	case RTSX_RTS5249:
1537 	case RTSX_RTS5260:
1538 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL1, 0x66);
1539 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL2, RTSX_PULL_CTL_DISABLE12);
1540 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL3, RTSX_PULL_CTL_DISABLE3);
1541 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL4, 0x55);
1542 		break;
1543 	case RTSX_RTL8402:
1544 	case RTSX_RTL8411:
1545 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL1, 0x65);
1546 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL2, 0x55);
1547 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL3, 0x95);
1548 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL4, 0x09);
1549 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL5, 0x05);
1550 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL6, 0x04);
1551 		break;
1552 	case RTSX_RTL8411B:
1553 		if (sc->rtsx_flags & RTSX_F_8411B_QFN48) {
1554 			RTSX_WRITE(sc, RTSX_CARD_PULL_CTL2, 0x55);
1555 			RTSX_WRITE(sc, RTSX_CARD_PULL_CTL3, 0xf5);
1556 			RTSX_WRITE(sc, RTSX_CARD_PULL_CTL6, 0x15);
1557 		} else {
1558 			RTSX_WRITE(sc, RTSX_CARD_PULL_CTL1, 0x65);
1559 			RTSX_WRITE(sc, RTSX_CARD_PULL_CTL2, 0x55);
1560 			RTSX_WRITE(sc, RTSX_CARD_PULL_CTL3, 0xd5);
1561 			RTSX_WRITE(sc, RTSX_CARD_PULL_CTL4, 0x59);
1562 			RTSX_WRITE(sc, RTSX_CARD_PULL_CTL5, 0x55);
1563 			RTSX_WRITE(sc, RTSX_CARD_PULL_CTL6, 0x15);
1564 		}
1565 		break;
1566 	}
1567 
1568 	return (0);
1569 }
1570 
1571 static int
1572 rtsx_bus_power_on(struct rtsx_softc *sc)
1573 {
1574 	if (sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
1575 		device_printf(sc->rtsx_dev, "rtsx_bus_power_on()\n");
1576 
1577 	/* Select SD card. */
1578 	RTSX_BITOP(sc, RTSX_CARD_SELECT, 0x07, RTSX_SD_MOD_SEL);
1579 	RTSX_BITOP(sc, RTSX_CARD_SHARE_MODE, RTSX_CARD_SHARE_MASK, RTSX_CARD_SHARE_48_SD);
1580 
1581 	/* Enable SD clock. */
1582 	RTSX_BITOP(sc, RTSX_CARD_CLK_EN, RTSX_SD_CLK_EN,  RTSX_SD_CLK_EN);
1583 
1584 	/* Enable pull control. */
1585 	switch (sc->rtsx_device_id) {
1586 	case RTSX_RTS5209:
1587 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL1, RTSX_PULL_CTL_ENABLE12);
1588 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL2, RTSX_PULL_CTL_ENABLE12);
1589 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL3, RTSX_PULL_CTL_ENABLE3);
1590 		break;
1591 	case RTSX_RTS5227:
1592 	case RTSX_RTS522A:
1593 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL2, RTSX_PULL_CTL_ENABLE12);
1594 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL3, RTSX_PULL_CTL_ENABLE3);
1595 		break;
1596 	case RTSX_RTS5229:
1597 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL2, RTSX_PULL_CTL_ENABLE12);
1598 		if (sc->rtsx_flags & RTSX_F_VERSION_C)
1599 			RTSX_WRITE(sc, RTSX_CARD_PULL_CTL3, RTSX_PULL_CTL_ENABLE3_TYPE_C);
1600 		else
1601 			RTSX_WRITE(sc, RTSX_CARD_PULL_CTL3, RTSX_PULL_CTL_ENABLE3);
1602 		break;
1603 	case RTSX_RTS525A:
1604 	case RTSX_RTS5249:
1605 	case RTSX_RTS5260:
1606 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL1, 0x66);
1607 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL2, RTSX_PULL_CTL_ENABLE12);
1608 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL3, RTSX_PULL_CTL_ENABLE3);
1609 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL4, 0xaa);
1610 		break;
1611 	case RTSX_RTL8402:
1612 	case RTSX_RTL8411:
1613 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL1, 0xaa);
1614 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL2, 0xaa);
1615 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL3, 0xa9);
1616 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL4, 0x09);
1617 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL5, 0x09);
1618 		RTSX_WRITE(sc, RTSX_CARD_PULL_CTL6, 0x04);
1619 		break;
1620 	case RTSX_RTL8411B:
1621 		if (sc->rtsx_flags & RTSX_F_8411B_QFN48) {
1622 			RTSX_WRITE(sc, RTSX_CARD_PULL_CTL2, 0xaa);
1623 			RTSX_WRITE(sc, RTSX_CARD_PULL_CTL3, 0xf9);
1624 			RTSX_WRITE(sc, RTSX_CARD_PULL_CTL6, 0x19);
1625 		} else {
1626 			RTSX_WRITE(sc, RTSX_CARD_PULL_CTL1, 0xaa);
1627 			RTSX_WRITE(sc, RTSX_CARD_PULL_CTL2, 0xaa);
1628 			RTSX_WRITE(sc, RTSX_CARD_PULL_CTL3, 0xd9);
1629 			RTSX_WRITE(sc, RTSX_CARD_PULL_CTL4, 0x59);
1630 			RTSX_WRITE(sc, RTSX_CARD_PULL_CTL5, 0x55);
1631 			RTSX_WRITE(sc, RTSX_CARD_PULL_CTL6, 0x15);
1632 		}
1633 		break;
1634 	}
1635 
1636 	/*
1637 	 * To avoid a current peak, enable card power in two phases
1638 	 * with a delay in between.
1639 	 */
1640 	switch (sc->rtsx_device_id) {
1641 	case RTSX_RTS5209:
1642 		/* Partial power. */
1643 		RTSX_BITOP(sc, RTSX_CARD_PWR_CTL, RTSX_SD_PWR_MASK, RTSX_SD_PARTIAL_PWR_ON);
1644 		RTSX_BITOP(sc, RTSX_PWR_GATE_CTRL, RTSX_LDO3318_PWR_MASK, RTSX_LDO3318_VCC2);
1645 
1646 		DELAY(200);
1647 
1648 		/* Full power. */
1649 		RTSX_BITOP(sc, RTSX_CARD_PWR_CTL, RTSX_SD_PWR_MASK, RTSX_SD_PWR_ON);
1650 		RTSX_BITOP(sc, RTSX_PWR_GATE_CTRL, RTSX_LDO3318_PWR_MASK, RTSX_LDO3318_ON);
1651 		break;
1652 	case RTSX_RTS5227:
1653 	case RTSX_RTS522A:
1654 		/* Partial power. */
1655 		RTSX_BITOP(sc, RTSX_CARD_PWR_CTL, RTSX_SD_PWR_MASK, RTSX_SD_PARTIAL_PWR_ON);
1656 		RTSX_BITOP(sc, RTSX_PWR_GATE_CTRL, RTSX_LDO3318_PWR_MASK, RTSX_LDO3318_VCC1);
1657 
1658 		DELAY(20000);
1659 
1660 		/* Full power. */
1661 		RTSX_BITOP(sc, RTSX_CARD_PWR_CTL, RTSX_SD_PWR_MASK, RTSX_SD_PWR_ON);
1662 		RTSX_BITOP(sc, RTSX_PWR_GATE_CTRL, RTSX_LDO3318_PWR_MASK,
1663 			   RTSX_LDO3318_VCC1 | RTSX_LDO3318_VCC2);
1664 		RTSX_BITOP(sc, RTSX_CARD_OE, RTSX_SD_OUTPUT_EN, RTSX_SD_OUTPUT_EN);
1665 		RTSX_BITOP(sc, RTSX_CARD_OE, RTSX_MS_OUTPUT_EN, RTSX_MS_OUTPUT_EN);
1666 		break;
1667 	case RTSX_RTS5229:
1668 		/* Partial power. */
1669 		RTSX_BITOP(sc, RTSX_CARD_PWR_CTL, RTSX_SD_PWR_MASK, RTSX_SD_PARTIAL_PWR_ON);
1670 		RTSX_BITOP(sc, RTSX_PWR_GATE_CTRL, RTSX_LDO3318_PWR_MASK, RTSX_LDO3318_VCC1);
1671 
1672 		DELAY(200);
1673 
1674 		/* Full power. */
1675 		RTSX_BITOP(sc, RTSX_CARD_PWR_CTL, RTSX_SD_PWR_MASK, RTSX_SD_PWR_ON);
1676 		RTSX_BITOP(sc, RTSX_PWR_GATE_CTRL, RTSX_LDO3318_PWR_MASK,
1677 			   RTSX_LDO3318_VCC1 | RTSX_LDO3318_VCC2);
1678 		break;
1679 	case RTSX_RTS525A:
1680 		RTSX_BITOP(sc, RTSX_LDO_VCC_CFG1, RTSX_LDO_VCC_TUNE_MASK, RTSX_LDO_VCC_3V3);
1681 	case RTSX_RTS5249:
1682 		/* Partial power. */
1683 		RTSX_BITOP(sc, RTSX_CARD_PWR_CTL, RTSX_SD_PWR_MASK, RTSX_SD_PARTIAL_PWR_ON);
1684 		RTSX_BITOP(sc, RTSX_PWR_GATE_CTRL, RTSX_LDO3318_PWR_MASK, RTSX_LDO3318_VCC1);
1685 
1686 		DELAY(5000);
1687 
1688 		/* Full power. */
1689 		RTSX_BITOP(sc, RTSX_CARD_PWR_CTL, RTSX_SD_PWR_MASK, RTSX_SD_PWR_ON);
1690 		RTSX_BITOP(sc, RTSX_PWR_GATE_CTRL, RTSX_LDO3318_PWR_MASK,
1691 			   RTSX_LDO3318_VCC1 | RTSX_LDO3318_VCC2);
1692 		break;
1693 	case RTSX_RTS5260:
1694 		RTSX_BITOP(sc, RTSX_LDO_CONFIG2, RTSX_DV331812_VDD1, RTSX_DV331812_VDD1);
1695 		RTSX_BITOP(sc, RTSX_LDO_VCC_CFG0, RTSX_RTS5260_DVCC_TUNE_MASK, RTSX_RTS5260_DVCC_33);
1696 		RTSX_BITOP(sc, RTSX_LDO_VCC_CFG1, RTSX_LDO_POW_SDVDD1_MASK, RTSX_LDO_POW_SDVDD1_ON);
1697 		RTSX_BITOP(sc, RTSX_LDO_CONFIG2, RTSX_DV331812_POWERON, RTSX_DV331812_POWERON);
1698 
1699 		DELAY(20000);
1700 
1701 		RTSX_BITOP(sc, RTSX_SD_CFG1, RTSX_SD_MODE_MASK | RTSX_SD_ASYNC_FIFO_NOT_RST,
1702 			   RTSX_SD30_MODE | RTSX_SD_ASYNC_FIFO_NOT_RST);
1703 		RTSX_BITOP(sc, RTSX_CLK_CTL, RTSX_CHANGE_CLK, RTSX_CLK_LOW_FREQ);
1704 		RTSX_WRITE(sc, RTSX_CARD_CLK_SOURCE,
1705 			   RTSX_CRC_VAR_CLK0 | RTSX_SD30_FIX_CLK | RTSX_SAMPLE_VAR_CLK1);
1706 		RTSX_CLR(sc, RTSX_CLK_CTL, RTSX_CLK_LOW_FREQ);
1707 
1708 		/* Initialize SD_CFG1 register */
1709 		RTSX_WRITE(sc, RTSX_SD_CFG1, RTSX_CLK_DIVIDE_128 | RTSX_SD20_MODE);
1710 		RTSX_WRITE(sc, RTSX_SD_SAMPLE_POINT_CTL, RTSX_SD20_RX_POS_EDGE);
1711 		RTSX_CLR(sc, RTSX_SD_PUSH_POINT_CTL, 0xff);
1712 		RTSX_BITOP(sc, RTSX_CARD_STOP, RTSX_SD_STOP | RTSX_SD_CLR_ERR,
1713 			   RTSX_SD_STOP | RTSX_SD_CLR_ERR);
1714 		/* Reset SD_CFG3 register */
1715 		RTSX_CLR(sc, RTSX_SD_CFG3, RTSX_SD30_CLK_END_EN);
1716 		RTSX_CLR(sc, RTSX_REG_SD_STOP_SDCLK_CFG,
1717 			 RTSX_SD30_CLK_STOP_CFG_EN | RTSX_SD30_CLK_STOP_CFG0 | RTSX_SD30_CLK_STOP_CFG1);
1718 		RTSX_CLR(sc, RTSX_REG_PRE_RW_MODE, RTSX_EN_INFINITE_MODE);
1719 		break;
1720 	case RTSX_RTL8402:
1721 	case RTSX_RTL8411:
1722 	case RTSX_RTL8411B:
1723 		RTSX_BITOP(sc, RTSX_CARD_PWR_CTL, RTSX_BPP_POWER_MASK,
1724 			   RTSX_BPP_POWER_5_PERCENT_ON);
1725 		RTSX_BITOP(sc, RTSX_LDO_CTL, RTSX_BPP_LDO_POWB,
1726 			   RTSX_BPP_LDO_SUSPEND);
1727 		DELAY(150);
1728 		RTSX_BITOP(sc, RTSX_CARD_PWR_CTL, RTSX_BPP_POWER_MASK,
1729 			   RTSX_BPP_POWER_10_PERCENT_ON);
1730 		DELAY(150);
1731 		RTSX_BITOP(sc, RTSX_CARD_PWR_CTL, RTSX_BPP_POWER_MASK,
1732 			   RTSX_BPP_POWER_15_PERCENT_ON);
1733 		DELAY(150);
1734 		RTSX_BITOP(sc, RTSX_CARD_PWR_CTL, RTSX_BPP_POWER_MASK,
1735 			   RTSX_BPP_POWER_ON);
1736 		RTSX_BITOP(sc, RTSX_LDO_CTL, RTSX_BPP_LDO_POWB,
1737 			   RTSX_BPP_LDO_ON);
1738 		break;
1739 	}
1740 
1741 	/* Enable SD card output. */
1742 	RTSX_WRITE(sc, RTSX_CARD_OE, RTSX_SD_OUTPUT_EN);
1743 
1744 	DELAY(200);
1745 
1746 	return (0);
1747 }
1748 
1749 /*
1750  * Set but width.
1751  */
1752 static int
1753 rtsx_set_bus_width(struct rtsx_softc *sc, enum mmc_bus_width width)
1754 {
1755 	uint32_t bus_width;
1756 
1757 	switch (width) {
1758 	case bus_width_1:
1759 		bus_width = RTSX_BUS_WIDTH_1;
1760 		break;
1761 	case bus_width_4:
1762 		bus_width = RTSX_BUS_WIDTH_4;
1763 		break;
1764 	case bus_width_8:
1765 		bus_width = RTSX_BUS_WIDTH_8;
1766 		break;
1767 	default:
1768 		return (MMC_ERR_INVALID);
1769 	}
1770 	RTSX_BITOP(sc, RTSX_SD_CFG1, RTSX_BUS_WIDTH_MASK, bus_width);
1771 
1772 	if (sc->rtsx_debug_mask & RTSX_DEBUG_BASIC) {
1773 		char *busw[] = {
1774 				"1 bit",
1775 				"4 bits",
1776 				"8 bits"
1777 		};
1778 		device_printf(sc->rtsx_dev, "Setting bus width to %s\n", busw[bus_width]);
1779 	}
1780 	return (0);
1781 }
1782 
1783 static int
1784 rtsx_set_sd_timing(struct rtsx_softc *sc, enum mmc_bus_timing timing)
1785 {
1786 	if (timing == bus_timing_hs && sc->rtsx_force_timing) {
1787 		timing = bus_timing_uhs_sdr50;
1788 		sc->rtsx_ios_timing = timing;
1789 	}
1790 
1791 	if (sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
1792 		device_printf(sc->rtsx_dev, "rtsx_set_sd_timing(%u)\n", timing);
1793 
1794 	switch (timing) {
1795 	case bus_timing_uhs_sdr50:
1796 	case bus_timing_uhs_sdr104:
1797 		sc->rtsx_double_clk = false;
1798 		sc->rtsx_vpclk = true;
1799 		RTSX_BITOP(sc, RTSX_SD_CFG1, 0x0c | RTSX_SD_ASYNC_FIFO_NOT_RST,
1800 			   RTSX_SD30_MODE | RTSX_SD_ASYNC_FIFO_NOT_RST);
1801 		RTSX_BITOP(sc, RTSX_CLK_CTL, RTSX_CLK_LOW_FREQ, RTSX_CLK_LOW_FREQ);
1802 		RTSX_WRITE(sc, RTSX_CARD_CLK_SOURCE,
1803 			   RTSX_CRC_VAR_CLK0 | RTSX_SD30_FIX_CLK | RTSX_SAMPLE_VAR_CLK1);
1804 		RTSX_CLR(sc, RTSX_CLK_CTL, RTSX_CLK_LOW_FREQ);
1805 		break;
1806 	case bus_timing_hs:
1807 		RTSX_BITOP(sc, RTSX_SD_CFG1, RTSX_SD_MODE_MASK, RTSX_SD20_MODE);
1808 		RTSX_BITOP(sc, RTSX_CLK_CTL, RTSX_CLK_LOW_FREQ, RTSX_CLK_LOW_FREQ);
1809 		RTSX_WRITE(sc, RTSX_CARD_CLK_SOURCE,
1810 			   RTSX_CRC_FIX_CLK | RTSX_SD30_VAR_CLK0 | RTSX_SAMPLE_VAR_CLK1);
1811 		RTSX_CLR(sc, RTSX_CLK_CTL, RTSX_CLK_LOW_FREQ);
1812 
1813 		RTSX_BITOP(sc, RTSX_SD_PUSH_POINT_CTL,
1814 			   RTSX_SD20_TX_SEL_MASK, RTSX_SD20_TX_14_AHEAD);
1815 		RTSX_BITOP(sc, RTSX_SD_SAMPLE_POINT_CTL,
1816 			   RTSX_SD20_RX_SEL_MASK, RTSX_SD20_RX_14_DELAY);
1817 		break;
1818 	default:
1819 		RTSX_BITOP(sc, RTSX_SD_CFG1, RTSX_SD_MODE_MASK, RTSX_SD20_MODE);
1820 		RTSX_BITOP(sc, RTSX_CLK_CTL, RTSX_CLK_LOW_FREQ, RTSX_CLK_LOW_FREQ);
1821 		RTSX_WRITE(sc, RTSX_CARD_CLK_SOURCE,
1822 			   RTSX_CRC_FIX_CLK | RTSX_SD30_VAR_CLK0 | RTSX_SAMPLE_VAR_CLK1);
1823 		RTSX_CLR(sc, RTSX_CLK_CTL, RTSX_CLK_LOW_FREQ);
1824 
1825 		RTSX_WRITE(sc, RTSX_SD_PUSH_POINT_CTL, RTSX_SD20_TX_NEG_EDGE);
1826 		RTSX_BITOP(sc, RTSX_SD_SAMPLE_POINT_CTL,
1827 			   RTSX_SD20_RX_SEL_MASK, RTSX_SD20_RX_POS_EDGE);
1828 		break;
1829 	}
1830 
1831 	return (0);
1832 }
1833 
1834 /*
1835  * Set or change SDCLK frequency or disable the SD clock.
1836  * Return zero on success.
1837  */
1838 static int
1839 rtsx_set_sd_clock(struct rtsx_softc *sc, uint32_t freq)
1840 {
1841 	uint8_t	clk;
1842 	uint8_t	clk_divider, n, div, mcu;
1843 	int	error = 0;
1844 
1845 	if (sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
1846 		device_printf(sc->rtsx_dev, "rtsx_set_sd_clock(%u)\n", freq);
1847 
1848 	if (freq == RTSX_SDCLK_OFF) {
1849 		error = rtsx_stop_sd_clock(sc);
1850 		return error;
1851 	}
1852 
1853 	sc->rtsx_ssc_depth = RTSX_SSC_DEPTH_500K;
1854 	sc->rtsx_discovery_mode = (freq <= 1000000) ? true : false;
1855 
1856 	if (sc->rtsx_discovery_mode) {
1857 		/* We use 250k(around) here, in discovery stage. */
1858 		clk_divider = RTSX_CLK_DIVIDE_128;
1859 		freq = 30000000;
1860 	} else {
1861 		clk_divider = RTSX_CLK_DIVIDE_0;
1862 	}
1863 	RTSX_BITOP(sc, RTSX_SD_CFG1, RTSX_CLK_DIVIDE_MASK, clk_divider);
1864 
1865 	freq /= 1000000;
1866 	if (sc->rtsx_discovery_mode || !sc->rtsx_double_clk)
1867 		clk = freq;
1868 	else
1869 		clk = freq * 2;
1870 
1871 	switch (sc->rtsx_device_id) {
1872 	case RTSX_RTL8402:
1873 	case RTSX_RTL8411:
1874 	case RTSX_RTL8411B:
1875 		n = clk * 4 / 5 - 2;
1876 		break;
1877 	default:
1878 		n = clk - 2;
1879 		break;
1880 	}
1881 	if ((clk <= 2) || (n > RTSX_MAX_DIV_N))
1882 		return (MMC_ERR_INVALID);
1883 
1884 	mcu = 125 / clk + 3;
1885 	if (mcu > 15)
1886 		mcu = 15;
1887 
1888 	/* Make sure that the SSC clock div_n is not less than RTSX_MIN_DIV_N. */
1889 	div = RTSX_CLK_DIV_1;
1890 	while ((n < RTSX_MIN_DIV_N) && (div < RTSX_CLK_DIV_8)) {
1891 		switch (sc->rtsx_device_id) {
1892 		case RTSX_RTL8402:
1893 		case RTSX_RTL8411:
1894 		case RTSX_RTL8411B:
1895 			n = (((n + 2) * 5 / 4) * 2) * 4 / 5 - 2;
1896 			break;
1897 		default:
1898 			n = (n + 2) * 2 - 2;
1899 			break;
1900 		}
1901 		div++;
1902 	}
1903 
1904 	if (sc->rtsx_double_clk && sc->rtsx_ssc_depth > 1)
1905 		sc->rtsx_ssc_depth -= 1;
1906 
1907 	if (div > RTSX_CLK_DIV_1) {
1908 		if (sc->rtsx_ssc_depth > (div - 1))
1909 			sc->rtsx_ssc_depth -= (div - 1);
1910 		else
1911 			sc->rtsx_ssc_depth = RTSX_SSC_DEPTH_4M;
1912 	}
1913 
1914 	/* Enable SD clock. */
1915 	error = rtsx_switch_sd_clock(sc, clk, n, div, mcu);
1916 
1917 	return (error);
1918 }
1919 
1920 static int
1921 rtsx_stop_sd_clock(struct rtsx_softc *sc)
1922 {
1923 	RTSX_CLR(sc, RTSX_CARD_CLK_EN, RTSX_CARD_CLK_EN_ALL);
1924 	RTSX_SET(sc, RTSX_SD_BUS_STAT, RTSX_SD_CLK_FORCE_STOP);
1925 
1926 	return (0);
1927 }
1928 
1929 static int
1930 rtsx_switch_sd_clock(struct rtsx_softc *sc, uint8_t clk, uint8_t n, uint8_t div, uint8_t mcu)
1931 {
1932 	if (sc->rtsx_debug_mask & RTSX_DEBUG_BASIC) {
1933 		device_printf(sc->rtsx_dev, "rtsx_switch_sd_clock() - discovery-mode is %s, ssc_depth: %d\n",
1934 			      (sc->rtsx_discovery_mode) ? "true" : "false", sc->rtsx_ssc_depth);
1935 		device_printf(sc->rtsx_dev, "rtsx_switch_sd_clock() - clk: %d, n: %d, div: %d, mcu: %d\n",
1936 			      clk, n, div, mcu);
1937 	}
1938 
1939 	RTSX_BITOP(sc, RTSX_CLK_CTL, RTSX_CLK_LOW_FREQ, RTSX_CLK_LOW_FREQ);
1940 	RTSX_WRITE(sc, RTSX_CLK_DIV, (div << 4) | mcu);
1941 	RTSX_CLR(sc, RTSX_SSC_CTL1, RTSX_RSTB);
1942 	RTSX_BITOP(sc, RTSX_SSC_CTL2, RTSX_SSC_DEPTH_MASK, sc->rtsx_ssc_depth);
1943 	RTSX_WRITE(sc, RTSX_SSC_DIV_N_0, n);
1944 	RTSX_BITOP(sc, RTSX_SSC_CTL1, RTSX_RSTB, RTSX_RSTB);
1945 	if (sc->rtsx_vpclk) {
1946 		RTSX_CLR(sc, RTSX_SD_VPCLK0_CTL, RTSX_PHASE_NOT_RESET);
1947 		RTSX_BITOP(sc, RTSX_SD_VPCLK0_CTL, RTSX_PHASE_NOT_RESET, RTSX_PHASE_NOT_RESET);
1948 	}
1949 
1950 	/* Wait SSC clock stable. */
1951 	DELAY(200);
1952 
1953 	RTSX_CLR(sc, RTSX_CLK_CTL, RTSX_CLK_LOW_FREQ);
1954 
1955 	return (0);
1956 }
1957 
1958 #ifndef MMCCAM
1959 static void
1960 rtsx_sd_change_tx_phase(struct rtsx_softc *sc, uint8_t sample_point)
1961 {
1962 	if (sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
1963 		device_printf(sc->rtsx_dev, "rtsx_sd_change_tx_phase() - sample_point: %d\n", sample_point);
1964 
1965 	rtsx_write(sc, RTSX_CLK_CTL, RTSX_CHANGE_CLK, RTSX_CHANGE_CLK);
1966 	rtsx_write(sc, RTSX_SD_VPCLK0_CTL, RTSX_PHASE_SELECT_MASK, sample_point);
1967 	rtsx_write(sc, RTSX_SD_VPCLK0_CTL, RTSX_PHASE_NOT_RESET, 0);
1968 	rtsx_write(sc, RTSX_SD_VPCLK0_CTL, RTSX_PHASE_NOT_RESET, RTSX_PHASE_NOT_RESET);
1969 	rtsx_write(sc, RTSX_CLK_CTL, RTSX_CHANGE_CLK, 0);
1970 	rtsx_write(sc, RTSX_SD_CFG1, RTSX_SD_ASYNC_FIFO_NOT_RST, 0);
1971 }
1972 
1973 static void
1974 rtsx_sd_change_rx_phase(struct rtsx_softc *sc, uint8_t sample_point)
1975 {
1976 	if (sc->rtsx_debug_mask & RTSX_DEBUG_TUNING)
1977 		device_printf(sc->rtsx_dev, "rtsx_sd_change_rx_phase() - sample_point: %d\n", sample_point);
1978 
1979 	rtsx_write(sc, RTSX_CLK_CTL, RTSX_CHANGE_CLK, RTSX_CHANGE_CLK);
1980 	rtsx_write(sc, RTSX_SD_VPCLK1_CTL, RTSX_PHASE_SELECT_MASK, sample_point);
1981 	rtsx_write(sc, RTSX_SD_VPCLK1_CTL, RTSX_PHASE_NOT_RESET, 0);
1982 	rtsx_write(sc, RTSX_SD_VPCLK1_CTL, RTSX_PHASE_NOT_RESET, RTSX_PHASE_NOT_RESET);
1983 	rtsx_write(sc, RTSX_CLK_CTL, RTSX_CHANGE_CLK, 0);
1984 	rtsx_write(sc, RTSX_SD_CFG1, RTSX_SD_ASYNC_FIFO_NOT_RST, 0);
1985 }
1986 
1987 static void
1988 rtsx_sd_tuning_rx_phase(struct rtsx_softc *sc, uint32_t *phase_map)
1989 {
1990 	uint32_t raw_phase_map = 0;
1991 	int	 i;
1992 	int	 error;
1993 
1994 	for (i = 0; i < RTSX_RX_PHASE_MAX; i++) {
1995 		error = rtsx_sd_tuning_rx_cmd(sc, (uint8_t)i);
1996 		if (error == 0)
1997 			raw_phase_map |= 1 << i;
1998 	}
1999 	if (phase_map != NULL)
2000 		*phase_map = raw_phase_map;
2001 }
2002 
2003 static int
2004 rtsx_sd_tuning_rx_cmd(struct rtsx_softc *sc, uint8_t sample_point)
2005 {
2006 	struct mmc_request req = {};
2007 	struct mmc_command cmd = {};
2008 	int	error = 0;
2009 
2010 	cmd.opcode = MMC_SEND_TUNING_BLOCK;
2011 	cmd.arg = 0;
2012 	req.cmd = &cmd;
2013 
2014 	RTSX_LOCK(sc);
2015 
2016 	sc->rtsx_req = &req;
2017 
2018 	rtsx_sd_change_rx_phase(sc, sample_point);
2019 
2020 	rtsx_write(sc, RTSX_SD_CFG3, RTSX_SD_RSP_80CLK_TIMEOUT_EN,
2021 		   RTSX_SD_RSP_80CLK_TIMEOUT_EN);
2022 
2023 	rtsx_init_cmd(sc, &cmd);
2024 	rtsx_set_cmd_data_len(sc, 1, 0x40);
2025 	rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_SD_CFG2, 0xff,
2026 		      RTSX_SD_CALCULATE_CRC7 | RTSX_SD_CHECK_CRC16 |
2027 		      RTSX_SD_NO_WAIT_BUSY_END | RTSX_SD_CHECK_CRC7 | RTSX_SD_RSP_LEN_6);
2028 	rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_SD_TRANSFER,
2029 		      0xff, RTSX_TM_AUTO_TUNING | RTSX_SD_TRANSFER_START);
2030 	rtsx_push_cmd(sc, RTSX_CHECK_REG_CMD, RTSX_SD_TRANSFER,
2031 		      RTSX_SD_TRANSFER_END, RTSX_SD_TRANSFER_END);
2032 
2033 	/* Set interrupt post processing */
2034 	sc->rtsx_intr_trans_ok = rtsx_sd_tuning_rx_cmd_wakeup;
2035 	sc->rtsx_intr_trans_ko = rtsx_sd_tuning_rx_cmd_wakeup;
2036 
2037 	/* Run the command queue. */
2038 	rtsx_send_cmd(sc);
2039 
2040 	error = rtsx_sd_tuning_rx_cmd_wait(sc, &cmd);
2041 
2042 	if (error) {
2043 		if (sc->rtsx_debug_mask & RTSX_DEBUG_TUNING)
2044 			device_printf(sc->rtsx_dev, "rtsx_sd_tuning_rx_cmd() - error: %d\n", error);
2045 		rtsx_sd_wait_data_idle(sc);
2046 		rtsx_clear_error(sc);
2047 	}
2048 	rtsx_write(sc, RTSX_SD_CFG3, RTSX_SD_RSP_80CLK_TIMEOUT_EN, 0);
2049 
2050 	sc->rtsx_req = NULL;
2051 
2052 	RTSX_UNLOCK(sc);
2053 
2054 	return (error);
2055 }
2056 
2057 static int
2058 rtsx_sd_tuning_rx_cmd_wait(struct rtsx_softc *sc, struct mmc_command *cmd)
2059 {
2060 	int	status;
2061 	int	mask = RTSX_TRANS_OK_INT | RTSX_TRANS_FAIL_INT;
2062 
2063 	status = sc->rtsx_intr_status & mask;
2064 	while (status == 0) {
2065 		if (msleep(&sc->rtsx_intr_status, &sc->rtsx_mtx, 0, "rtsxintr", sc->rtsx_timeout_cmd) == EWOULDBLOCK) {
2066 			cmd->error = MMC_ERR_TIMEOUT;
2067 			return (MMC_ERR_TIMEOUT);
2068 		}
2069 		status = sc->rtsx_intr_status & mask;
2070 	}
2071 	return (cmd->error);
2072 }
2073 
2074 static void
2075 rtsx_sd_tuning_rx_cmd_wakeup(struct rtsx_softc *sc)
2076 {
2077 	wakeup(&sc->rtsx_intr_status);
2078 }
2079 
2080 static void
2081 rtsx_sd_wait_data_idle(struct rtsx_softc *sc)
2082 {
2083 	int	i;
2084 	uint8_t	val;
2085 
2086 	for (i = 0; i < 100; i++) {
2087 		rtsx_read(sc, RTSX_SD_DATA_STATE, &val);
2088 		if (val & RTSX_SD_DATA_IDLE)
2089 			return;
2090 		DELAY(100);
2091 	}
2092 }
2093 
2094 static uint8_t
2095 rtsx_sd_search_final_rx_phase(struct rtsx_softc *sc, uint32_t phase_map)
2096 {
2097 	int	start = 0, len = 0;
2098 	int	start_final = 0, len_final = 0;
2099 	uint8_t	final_phase = 0xff;
2100 
2101 	while (start < RTSX_RX_PHASE_MAX) {
2102 		len = rtsx_sd_get_rx_phase_len(phase_map, start);
2103 		if (len_final < len) {
2104 			start_final = start;
2105 			len_final = len;
2106 		}
2107 		start += len ? len : 1;
2108 	}
2109 
2110 	final_phase = (start_final + len_final / 2) % RTSX_RX_PHASE_MAX;
2111 
2112 	if (sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
2113 		device_printf(sc->rtsx_dev,
2114 			      "rtsx_sd_search_final_rx_phase() - phase_map: %x, start_final: %d, len_final: %d, final_phase: %d\n",
2115 			      phase_map, start_final, len_final, final_phase);
2116 
2117 	return final_phase;
2118 }
2119 
2120 static int
2121 rtsx_sd_get_rx_phase_len(uint32_t phase_map, int start_bit)
2122 {
2123 	int	i;
2124 
2125 	for (i = 0; i < RTSX_RX_PHASE_MAX; i++) {
2126 		if ((phase_map & (1 << (start_bit + i) % RTSX_RX_PHASE_MAX)) == 0)
2127 			return i;
2128 	}
2129 	return RTSX_RX_PHASE_MAX;
2130 }
2131 #endif /* !MMCCAM */
2132 
2133 #if 0	/* For led */
2134 static int
2135 rtsx_led_enable(struct rtsx_softc *sc)
2136 {
2137 	switch (sc->rtsx_device_id) {
2138 	case RTSX_RTS5209:
2139 		RTSX_CLR(sc, RTSX_CARD_GPIO, RTSX_CARD_GPIO_LED_OFF);
2140 		RTSX_WRITE(sc, RTSX_CARD_AUTO_BLINK,
2141 			   RTSX_LED_BLINK_EN | RTSX_LED_BLINK_SPEED);
2142 		break;
2143 	case RTSX_RTL8411B:
2144 		RTSX_CLR(sc, RTSX_GPIO_CTL, 0x01);
2145 		RTSX_WRITE(sc, RTSX_CARD_AUTO_BLINK,
2146 			   RTSX_LED_BLINK_EN | RTSX_LED_BLINK_SPEED);
2147 		break;
2148 	default:
2149 		RTSX_SET(sc, RTSX_GPIO_CTL, RTSX_GPIO_LED_ON);
2150 		RTSX_SET(sc, RTSX_OLT_LED_CTL, RTSX_OLT_LED_AUTOBLINK);
2151 		break;
2152 	}
2153 
2154 	return (0);
2155 }
2156 
2157 static int
2158 rtsx_led_disable(struct rtsx_softc *sc)
2159 {
2160 	switch (sc->rtsx_device_id) {
2161 	case RTSX_RTS5209:
2162 		RTSX_CLR(sc, RTSX_CARD_AUTO_BLINK, RTSX_LED_BLINK_EN);
2163 		RTSX_WRITE(sc, RTSX_CARD_GPIO, RTSX_CARD_GPIO_LED_OFF);
2164 		break;
2165 	case RTSX_RTL8411B:
2166 		RTSX_CLR(sc, RTSX_CARD_AUTO_BLINK, RTSX_LED_BLINK_EN);
2167 		RTSX_SET(sc, RTSX_GPIO_CTL, 0x01);
2168 		break;
2169 	default:
2170 		RTSX_CLR(sc, RTSX_OLT_LED_CTL, RTSX_OLT_LED_AUTOBLINK);
2171 		RTSX_CLR(sc, RTSX_GPIO_CTL, RTSX_GPIO_LED_ON);
2172 		break;
2173 	}
2174 
2175 	return (0);
2176 }
2177 #endif	/* For led */
2178 
2179 static uint8_t
2180 rtsx_response_type(uint16_t mmc_rsp)
2181 {
2182 	int	i;
2183 	struct rsp_type {
2184 		uint16_t mmc_rsp;
2185 		uint8_t  rtsx_rsp;
2186 	} rsp_types[] = {
2187 		{ MMC_RSP_NONE,	RTSX_SD_RSP_TYPE_R0 },
2188 		{ MMC_RSP_R1,	RTSX_SD_RSP_TYPE_R1 },
2189 		{ MMC_RSP_R1B,	RTSX_SD_RSP_TYPE_R1B },
2190 		{ MMC_RSP_R2,	RTSX_SD_RSP_TYPE_R2 },
2191 		{ MMC_RSP_R3,	RTSX_SD_RSP_TYPE_R3 },
2192 		{ MMC_RSP_R4,	RTSX_SD_RSP_TYPE_R4 },
2193 		{ MMC_RSP_R5,	RTSX_SD_RSP_TYPE_R5 },
2194 		{ MMC_RSP_R6,	RTSX_SD_RSP_TYPE_R6 },
2195 		{ MMC_RSP_R7,	RTSX_SD_RSP_TYPE_R7 }
2196 	};
2197 
2198 	for (i = 0; i < nitems(rsp_types); i++) {
2199 		if (mmc_rsp == rsp_types[i].mmc_rsp)
2200 			return (rsp_types[i].rtsx_rsp);
2201 	}
2202 
2203 	return (0);
2204 }
2205 
2206 /*
2207  * Init command buffer with SD command index and argument.
2208  */
2209 static void
2210 rtsx_init_cmd(struct rtsx_softc *sc, struct mmc_command *cmd)
2211 {
2212 	sc->rtsx_cmd_index = 0;
2213 	rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_SD_CMD0,
2214 		      0xff, RTSX_SD_CMD_START  | cmd->opcode);
2215 	rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_SD_CMD1,
2216 		     0xff, cmd->arg >> 24);
2217 	rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_SD_CMD2,
2218 		      0xff, cmd->arg >> 16);
2219 	rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_SD_CMD3,
2220 		     0xff, cmd->arg >> 8);
2221 	rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_SD_CMD4,
2222 		     0xff, cmd->arg);
2223 }
2224 
2225 /*
2226  * Append a properly encoded host command to the host command buffer.
2227  */
2228 static void
2229 rtsx_push_cmd(struct rtsx_softc *sc, uint8_t cmd, uint16_t reg,
2230 	      uint8_t mask, uint8_t data)
2231 {
2232 	KASSERT(sc->rtsx_cmd_index < RTSX_HOSTCMD_MAX,
2233 		("rtsx: Too many host commands (%d)\n", sc->rtsx_cmd_index));
2234 
2235 	uint32_t *cmd_buffer = (uint32_t *)(sc->rtsx_cmd_dmamem);
2236 	cmd_buffer[sc->rtsx_cmd_index++] =
2237 		htole32((uint32_t)(cmd & 0x3) << 30) |
2238 		((uint32_t)(reg & 0x3fff) << 16) |
2239 		((uint32_t)(mask) << 8) |
2240 		((uint32_t)data);
2241 }
2242 
2243 /*
2244  * Queue commands to configure data transfer size.
2245  */
2246 static void
2247 rtsx_set_cmd_data_len(struct rtsx_softc *sc, uint16_t block_cnt, uint16_t byte_cnt)
2248 {
2249 	rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_SD_BLOCK_CNT_L,
2250 		      0xff, block_cnt & 0xff);
2251 	rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_SD_BLOCK_CNT_H,
2252 		      0xff, block_cnt >> 8);
2253 	rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_SD_BYTE_CNT_L,
2254 		      0xff, byte_cnt & 0xff);
2255 	rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_SD_BYTE_CNT_H,
2256 		      0xff, byte_cnt >> 8);
2257 }
2258 
2259 /*
2260  * Run the command queue.
2261  */
2262 static void
2263 rtsx_send_cmd(struct rtsx_softc *sc)
2264 {
2265 	if (sc->rtsx_debug_mask & RTSX_TRACE_SD_CMD)
2266 		device_printf(sc->rtsx_dev, "rtsx_send_cmd()\n");
2267 
2268 	sc->rtsx_intr_status = 0;
2269 
2270 	/* Sync command DMA buffer. */
2271 	bus_dmamap_sync(sc->rtsx_cmd_dma_tag, sc->rtsx_cmd_dmamap, BUS_DMASYNC_PREREAD);
2272 	bus_dmamap_sync(sc->rtsx_cmd_dma_tag, sc->rtsx_cmd_dmamap, BUS_DMASYNC_PREWRITE);
2273 
2274 	/* Tell the chip where the command buffer is and run the commands. */
2275 	WRITE4(sc, RTSX_HCBAR, (uint32_t)sc->rtsx_cmd_buffer);
2276 	WRITE4(sc, RTSX_HCBCTLR,
2277 	       ((sc->rtsx_cmd_index * 4) & 0x00ffffff) | RTSX_START_CMD | RTSX_HW_AUTO_RSP);
2278 }
2279 
2280 /*
2281  * Stop previous command.
2282  */
2283 static void
2284 rtsx_stop_cmd(struct rtsx_softc *sc)
2285 {
2286 	/* Stop command transfer. */
2287 	WRITE4(sc, RTSX_HCBCTLR, RTSX_STOP_CMD);
2288 
2289 	/* Stop DMA transfer. */
2290 	WRITE4(sc, RTSX_HDBCTLR, RTSX_STOP_DMA);
2291 
2292 	switch (sc->rtsx_device_id) {
2293 	case RTSX_RTS5260:
2294 		rtsx_write(sc, RTSX_RTS5260_DMA_RST_CTL_0,
2295 			   RTSX_RTS5260_DMA_RST | RTSX_RTS5260_ADMA3_RST,
2296 			   RTSX_RTS5260_DMA_RST | RTSX_RTS5260_ADMA3_RST);
2297 		rtsx_write(sc, RTSX_RBCTL, RTSX_RB_FLUSH, RTSX_RB_FLUSH);
2298 		break;
2299 	default:
2300 		rtsx_write(sc, RTSX_DMACTL, RTSX_DMA_RST, RTSX_DMA_RST);
2301 
2302 		rtsx_write(sc, RTSX_RBCTL, RTSX_RB_FLUSH, RTSX_RB_FLUSH);
2303 		break;
2304 	}
2305 }
2306 
2307 /*
2308  * Clear error.
2309  */
2310 static void
2311 rtsx_clear_error(struct rtsx_softc *sc)
2312 {
2313 	/* Clear error. */
2314 	rtsx_write(sc, RTSX_CARD_STOP, RTSX_SD_STOP | RTSX_SD_CLR_ERR,
2315 		   RTSX_SD_STOP | RTSX_SD_CLR_ERR);
2316 }
2317 
2318 /*
2319  * Signal end of request to mmc/mmcsd.
2320  */
2321 static void
2322 rtsx_req_done(struct rtsx_softc *sc)
2323 {
2324 #ifdef MMCCAM
2325 	union ccb *ccb;
2326 #endif /* MMCCAM */
2327 	struct mmc_request *req;
2328 
2329 	req = sc->rtsx_req;
2330 	if (req->cmd->error == MMC_ERR_NONE) {
2331 		if (req->cmd->opcode == MMC_READ_SINGLE_BLOCK ||
2332 		    req->cmd->opcode == MMC_READ_MULTIPLE_BLOCK)
2333 			sc->rtsx_read_count++;
2334 		else if (req->cmd->opcode == MMC_WRITE_BLOCK ||
2335 			 req->cmd->opcode == MMC_WRITE_MULTIPLE_BLOCK)
2336 			sc->rtsx_write_count++;
2337 	} else {
2338 		rtsx_clear_error(sc);
2339 	}
2340 	callout_stop(&sc->rtsx_timeout_callout);
2341 	sc->rtsx_req = NULL;
2342 #ifdef MMCCAM
2343 	ccb = sc->rtsx_ccb;
2344 	sc->rtsx_ccb = NULL;
2345 	ccb->ccb_h.status = (req->cmd->error == 0 ? CAM_REQ_CMP : CAM_REQ_CMP_ERR);
2346 	xpt_done(ccb);
2347 #else  /* !MMCCAM */
2348 	req->done(req);
2349 #endif /* MMCCAM */
2350 }
2351 
2352 /*
2353  * Send request.
2354  */
2355 static int
2356 rtsx_send_req(struct rtsx_softc *sc, struct mmc_command *cmd)
2357 {
2358 	uint8_t	 rsp_type;
2359 	uint16_t reg;
2360 
2361 	if (sc->rtsx_debug_mask & RTSX_TRACE_SD_CMD)
2362 		device_printf(sc->rtsx_dev, "rtsx_send_req() - CMD%d\n", cmd->opcode);
2363 
2364 	/* Convert response type. */
2365 	rsp_type = rtsx_response_type(cmd->flags & MMC_RSP_MASK);
2366 	if (rsp_type == 0) {
2367 		device_printf(sc->rtsx_dev, "Unknown rsp_type: 0x%lx\n", (cmd->flags & MMC_RSP_MASK));
2368 		cmd->error = MMC_ERR_INVALID;
2369 		return (MMC_ERR_INVALID);
2370 	}
2371 
2372 	rtsx_init_cmd(sc, cmd);
2373 
2374 	/* Queue command to set response type. */
2375 	rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_SD_CFG2, 0xff, rsp_type);
2376 
2377 	/* Use the ping-pong buffer (cmd buffer) for commands which do not transfer data. */
2378 	rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_CARD_DATA_SOURCE,
2379 		      0x01, RTSX_PINGPONG_BUFFER);
2380 
2381 	/* Queue commands to perform SD transfer. */
2382 	rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_SD_TRANSFER,
2383 		      0xff, RTSX_TM_CMD_RSP | RTSX_SD_TRANSFER_START);
2384 	rtsx_push_cmd(sc, RTSX_CHECK_REG_CMD, RTSX_SD_TRANSFER,
2385 		      RTSX_SD_TRANSFER_END|RTSX_SD_STAT_IDLE,
2386 		      RTSX_SD_TRANSFER_END|RTSX_SD_STAT_IDLE);
2387 
2388 	/* If needed queue commands to read back card status response. */
2389 	if (rsp_type == RTSX_SD_RSP_TYPE_R2) {
2390 		/* Read data from ping-pong buffer. */
2391 		for (reg = RTSX_PPBUF_BASE2; reg < RTSX_PPBUF_BASE2 + 16; reg++)
2392 			rtsx_push_cmd(sc, RTSX_READ_REG_CMD, reg, 0, 0);
2393 	} else if (rsp_type != RTSX_SD_RSP_TYPE_R0) {
2394 		/* Read data from SD_CMDx registers. */
2395 		for (reg = RTSX_SD_CMD0; reg <= RTSX_SD_CMD4; reg++)
2396 			rtsx_push_cmd(sc, RTSX_READ_REG_CMD, reg, 0, 0);
2397 	}
2398 	rtsx_push_cmd(sc, RTSX_READ_REG_CMD, RTSX_SD_STAT1, 0, 0);
2399 
2400 	/* Set transfer OK function. */
2401 	if (sc->rtsx_intr_trans_ok == NULL)
2402 		sc->rtsx_intr_trans_ok = rtsx_ret_resp;
2403 
2404 	/* Run the command queue. */
2405 	rtsx_send_cmd(sc);
2406 
2407 	return (0);
2408 }
2409 
2410 /*
2411  * Return response of previous command (case cmd->data == NULL) and complete resquest.
2412  * This Function is called by the interrupt handler via sc->rtsx_intr_trans_ok.
2413  */
2414 static void
2415 rtsx_ret_resp(struct rtsx_softc *sc)
2416 {
2417 	struct mmc_command *cmd;
2418 
2419 	cmd = sc->rtsx_req->cmd;
2420 	rtsx_set_resp(sc, cmd);
2421 	rtsx_req_done(sc);
2422 }
2423 
2424 /*
2425  * Set response of previous command.
2426  */
2427 static void
2428 rtsx_set_resp(struct rtsx_softc *sc, struct mmc_command *cmd)
2429 {
2430 	uint8_t	 rsp_type;
2431 
2432 	rsp_type = rtsx_response_type(cmd->flags & MMC_RSP_MASK);
2433 
2434 	/* Sync command DMA buffer. */
2435 	bus_dmamap_sync(sc->rtsx_cmd_dma_tag, sc->rtsx_cmd_dmamap, BUS_DMASYNC_POSTREAD);
2436 	bus_dmamap_sync(sc->rtsx_cmd_dma_tag, sc->rtsx_cmd_dmamap, BUS_DMASYNC_POSTWRITE);
2437 
2438 	/* Copy card response into mmc response buffer. */
2439 	if (ISSET(cmd->flags, MMC_RSP_PRESENT)) {
2440 		uint32_t *cmd_buffer = (uint32_t *)(sc->rtsx_cmd_dmamem);
2441 
2442 		if (sc->rtsx_debug_mask & RTSX_TRACE_SD_CMD) {
2443 			device_printf(sc->rtsx_dev, "cmd_buffer: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n",
2444 				      cmd_buffer[0], cmd_buffer[1], cmd_buffer[2], cmd_buffer[3], cmd_buffer[4]);
2445 		}
2446 
2447 		if (rsp_type == RTSX_SD_RSP_TYPE_R2) {
2448 			/* First byte is CHECK_REG_CMD return value, skip it. */
2449 			unsigned char *ptr = (unsigned char *)cmd_buffer + 1;
2450 			int i;
2451 
2452 			/*
2453 			 * The controller offloads the last byte {CRC-7, end bit 1}
2454 			 * of response type R2. Assign dummy CRC, 0, and end bit to this
2455 			 * byte (ptr[16], goes into the LSB of resp[3] later).
2456 			 */
2457 			ptr[16] = 0x01;
2458 			/* The second byte is the status of response, skip it. */
2459 			for (i = 0; i < 4; i++)
2460 				cmd->resp[i] = be32dec(ptr + 1 + i * 4);
2461 		} else {
2462 			/*
2463 			 * First byte is CHECK_REG_CMD return value, second
2464 			 * one is the command op code -- we skip those.
2465 			 */
2466 			cmd->resp[0] =
2467 				((be32toh(cmd_buffer[0]) & 0x0000ffff) << 16) |
2468 				((be32toh(cmd_buffer[1]) & 0xffff0000) >> 16);
2469 		}
2470 
2471 		if (sc->rtsx_debug_mask & RTSX_TRACE_SD_CMD)
2472 			device_printf(sc->rtsx_dev, "cmd->resp: 0x%08x 0x%08x 0x%08x 0x%08x\n",
2473 				      cmd->resp[0], cmd->resp[1], cmd->resp[2], cmd->resp[3]);
2474 	}
2475 }
2476 
2477 /*
2478  * Use the ping-pong buffer (cmd buffer) for transfer <= 512 bytes.
2479  */
2480 static int
2481 rtsx_xfer_short(struct rtsx_softc *sc, struct mmc_command *cmd)
2482 {
2483 	int	read;
2484 
2485 	if (cmd->data == NULL || cmd->data->len == 0) {
2486 		cmd->error = MMC_ERR_INVALID;
2487 		return (MMC_ERR_INVALID);
2488 	}
2489 	cmd->data->xfer_len = (cmd->data->len > RTSX_MAX_DATA_BLKLEN) ?
2490 		RTSX_MAX_DATA_BLKLEN : cmd->data->len;
2491 
2492 	read = ISSET(cmd->data->flags, MMC_DATA_READ);
2493 
2494 	if (sc->rtsx_debug_mask & RTSX_TRACE_SD_CMD)
2495 		device_printf(sc->rtsx_dev, "rtsx_xfer_short() - %s xfer: %ld bytes with block size %ld\n",
2496 			      read ? "Read" : "Write",
2497 			      (unsigned long)cmd->data->len, (unsigned long)cmd->data->xfer_len);
2498 
2499 	if (cmd->data->len > 512) {
2500 		device_printf(sc->rtsx_dev, "rtsx_xfer_short() - length too large: %ld > 512\n",
2501 			      (unsigned long)cmd->data->len);
2502 		cmd->error = MMC_ERR_INVALID;
2503 		return (MMC_ERR_INVALID);
2504 	}
2505 
2506 	if (read) {
2507 		if (sc->rtsx_discovery_mode)
2508 			rtsx_write(sc, RTSX_SD_CFG1, RTSX_CLK_DIVIDE_MASK, RTSX_CLK_DIVIDE_0);
2509 
2510 		rtsx_init_cmd(sc, cmd);
2511 
2512 		/* Queue commands to configure data transfer size. */
2513 		rtsx_set_cmd_data_len(sc, cmd->data->len / cmd->data->xfer_len, cmd->data->xfer_len);
2514 
2515 		/* From Linux: rtsx_pci_sdmmc.c sd_read_data(). */
2516 		rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_SD_CFG2, 0xff,
2517 			      RTSX_SD_CALCULATE_CRC7 | RTSX_SD_CHECK_CRC16 |
2518 			      RTSX_SD_NO_WAIT_BUSY_END | RTSX_SD_CHECK_CRC7 | RTSX_SD_RSP_LEN_6);
2519 
2520 		/* Use the ping-pong buffer (cmd buffer). */
2521 		rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_CARD_DATA_SOURCE,
2522 			      0x01, RTSX_PINGPONG_BUFFER);
2523 
2524 		/* Queue commands to perform SD transfer. */
2525 		rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_SD_TRANSFER,
2526 			      0xff, RTSX_TM_NORMAL_READ | RTSX_SD_TRANSFER_START);
2527 		rtsx_push_cmd(sc, RTSX_CHECK_REG_CMD, RTSX_SD_TRANSFER,
2528 			      RTSX_SD_TRANSFER_END, RTSX_SD_TRANSFER_END);
2529 
2530 		/* Set transfer OK function. */
2531 		sc->rtsx_intr_trans_ok = rtsx_ask_ppbuf_part1;
2532 
2533 		/* Run the command queue. */
2534 		rtsx_send_cmd(sc);
2535 	} else {
2536 		/* Set transfer OK function. */
2537 		sc->rtsx_intr_trans_ok = rtsx_put_ppbuf_part1;
2538 
2539 		/* Run the command queue. */
2540 		rtsx_send_req(sc, cmd);
2541 	}
2542 
2543 	return (0);
2544 }
2545 
2546 /*
2547  * Use the ping-pong buffer (cmd buffer) for the transfer - first part <= 256 bytes.
2548  * This Function is called by the interrupt handler via sc->rtsx_intr_trans_ok.
2549  */
2550 static void
2551 rtsx_ask_ppbuf_part1(struct rtsx_softc *sc)
2552 {
2553 	struct mmc_command *cmd;
2554 	uint16_t reg = RTSX_PPBUF_BASE2;
2555 	int	 len;
2556 	int	 i;
2557 
2558 	cmd = sc->rtsx_req->cmd;
2559 	len = (cmd->data->len > RTSX_HOSTCMD_MAX) ? RTSX_HOSTCMD_MAX : cmd->data->len;
2560 
2561 	sc->rtsx_cmd_index = 0;
2562 	for (i = 0; i < len; i++) {
2563 		rtsx_push_cmd(sc, RTSX_READ_REG_CMD, reg++, 0, 0);
2564 	}
2565 
2566 	/* Set transfer OK function. */
2567 	sc->rtsx_intr_trans_ok = rtsx_get_ppbuf_part1;
2568 
2569 	/* Run the command queue. */
2570 	rtsx_send_cmd(sc);
2571 }
2572 
2573 /*
2574  * Get the data from the ping-pong buffer (cmd buffer) - first part <= 256 bytes.
2575  * This Function is called by the interrupt handler via sc->rtsx_intr_trans_ok.
2576  */
2577 static void
2578 rtsx_get_ppbuf_part1(struct rtsx_softc *sc)
2579 {
2580 	struct mmc_command *cmd;
2581 	uint8_t	 *ptr;
2582 	int	 len;
2583 
2584 	cmd = sc->rtsx_req->cmd;
2585 	ptr = cmd->data->data;
2586 	len = (cmd->data->len > RTSX_HOSTCMD_MAX) ? RTSX_HOSTCMD_MAX : cmd->data->len;
2587 
2588 	/* Sync command DMA buffer. */
2589 	bus_dmamap_sync(sc->rtsx_cmd_dma_tag, sc->rtsx_cmd_dmamap, BUS_DMASYNC_POSTREAD);
2590 	bus_dmamap_sync(sc->rtsx_cmd_dma_tag, sc->rtsx_cmd_dmamap, BUS_DMASYNC_POSTWRITE);
2591 
2592 	memcpy(ptr, sc->rtsx_cmd_dmamem, len);
2593 
2594 	len = (cmd->data->len > RTSX_HOSTCMD_MAX) ? cmd->data->len - RTSX_HOSTCMD_MAX : 0;
2595 
2596 	/* Use the ping-pong buffer (cmd buffer) for the transfer - second part > 256 bytes. */
2597 	if (len > 0) {
2598 		uint16_t reg = RTSX_PPBUF_BASE2 + RTSX_HOSTCMD_MAX;
2599 		int	 i;
2600 
2601 		sc->rtsx_cmd_index = 0;
2602 		for (i = 0; i < len; i++) {
2603 			rtsx_push_cmd(sc, RTSX_READ_REG_CMD, reg++, 0, 0);
2604 		}
2605 
2606 		/* Set transfer OK function. */
2607 		sc->rtsx_intr_trans_ok = rtsx_get_ppbuf_part2;
2608 
2609 		/* Run the command queue. */
2610 		rtsx_send_cmd(sc);
2611 	} else {
2612 		if (sc->rtsx_debug_mask & RTSX_TRACE_SD_CMD && cmd->opcode == ACMD_SEND_SCR) {
2613 			uint8_t *ptr = cmd->data->data;
2614 			device_printf(sc->rtsx_dev, "SCR: 0x%02x%02x%02x%02x%02x%02x%02x%02x\n",
2615 				      ptr[0], ptr[1], ptr[2], ptr[3],
2616 				      ptr[4], ptr[5], ptr[6], ptr[7]);
2617 		}
2618 
2619 		if (sc->rtsx_discovery_mode)
2620 			rtsx_write(sc, RTSX_SD_CFG1, RTSX_CLK_DIVIDE_MASK, RTSX_CLK_DIVIDE_128);
2621 
2622 		rtsx_req_done(sc);
2623 	}
2624 }
2625 
2626 /*
2627  * Get the data from the ping-pong buffer (cmd buffer) - second part > 256 bytes.
2628  * This Function is called by the interrupt handler via sc->rtsx_intr_trans_ok.
2629  */
2630 static void
2631 rtsx_get_ppbuf_part2(struct rtsx_softc *sc)
2632 {
2633 	struct mmc_command *cmd;
2634 	uint8_t	*ptr;
2635 	int	len;
2636 
2637 	cmd = sc->rtsx_req->cmd;
2638 	ptr = cmd->data->data;
2639 	ptr += RTSX_HOSTCMD_MAX;
2640 	len = cmd->data->len - RTSX_HOSTCMD_MAX;
2641 
2642 	/* Sync command DMA buffer. */
2643 	bus_dmamap_sync(sc->rtsx_cmd_dma_tag, sc->rtsx_cmd_dmamap, BUS_DMASYNC_POSTREAD);
2644 	bus_dmamap_sync(sc->rtsx_cmd_dma_tag, sc->rtsx_cmd_dmamap, BUS_DMASYNC_POSTWRITE);
2645 
2646 	memcpy(ptr, sc->rtsx_cmd_dmamem, len);
2647 
2648 	if (sc->rtsx_discovery_mode)
2649 		rtsx_write(sc, RTSX_SD_CFG1, RTSX_CLK_DIVIDE_MASK, RTSX_CLK_DIVIDE_128);
2650 
2651 	rtsx_req_done(sc);
2652 }
2653 
2654 /*
2655  * Use the ping-pong buffer (cmd buffer) for transfer - first part <= 256 bytes.
2656  * This Function is called by the interrupt handler via sc->rtsx_intr_trans_ok.
2657  */
2658 static void
2659 rtsx_put_ppbuf_part1(struct rtsx_softc *sc)
2660 {
2661 	struct mmc_command *cmd;
2662 	uint16_t reg = RTSX_PPBUF_BASE2;
2663 	uint8_t	 *ptr;
2664 	int	 len;
2665 	int	 i;
2666 
2667 	cmd = sc->rtsx_req->cmd;
2668 	ptr = cmd->data->data;
2669 	len = (cmd->data->len > RTSX_HOSTCMD_MAX) ? RTSX_HOSTCMD_MAX : cmd->data->len;
2670 
2671 	rtsx_set_resp(sc, cmd);
2672 
2673 	sc->rtsx_cmd_index = 0;
2674 	for (i = 0; i < len; i++) {
2675 		rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, reg++, 0xff, *ptr);
2676 		ptr++;
2677 	}
2678 
2679 	/* Set transfer OK function. */
2680 	if (cmd->data->len > RTSX_HOSTCMD_MAX)
2681 		sc->rtsx_intr_trans_ok = rtsx_put_ppbuf_part2;
2682 	else
2683 		sc->rtsx_intr_trans_ok = rtsx_write_ppbuf;
2684 
2685 	/* Run the command queue. */
2686 	rtsx_send_cmd(sc);
2687 }
2688 
2689 /*
2690  * Use the ping-pong buffer (cmd buffer) for transfer - second part > 256 bytes.
2691  * This Function is called by the interrupt handler via sc->rtsx_intr_trans_ok.
2692  */
2693 static void
2694 rtsx_put_ppbuf_part2(struct rtsx_softc *sc)
2695 {
2696 	struct mmc_command *cmd;
2697 	uint16_t reg = RTSX_PPBUF_BASE2 + RTSX_HOSTCMD_MAX;
2698 	uint8_t	 *ptr;
2699 	int	 len;
2700 	int	 i;
2701 
2702 	cmd = sc->rtsx_req->cmd;
2703 	ptr = cmd->data->data;
2704 	ptr += RTSX_HOSTCMD_MAX;
2705 	len = cmd->data->len - RTSX_HOSTCMD_MAX;
2706 
2707 	sc->rtsx_cmd_index = 0;
2708 	for (i = 0; i < len; i++) {
2709 		rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, reg++, 0xff, *ptr);
2710 		ptr++;
2711 	}
2712 
2713 	/* Set transfer OK function. */
2714 	sc->rtsx_intr_trans_ok = rtsx_write_ppbuf;
2715 
2716 	/* Run the command queue. */
2717 	rtsx_send_cmd(sc);
2718 }
2719 
2720 /*
2721  * Write the data previously given via the ping-pong buffer on the card.
2722  * This Function is called by the interrupt handler via sc->rtsx_intr_trans_ok.
2723  */
2724 static void
2725 rtsx_write_ppbuf(struct rtsx_softc *sc)
2726 {
2727 	struct mmc_command *cmd;
2728 
2729 	cmd = sc->rtsx_req->cmd;
2730 
2731 	sc->rtsx_cmd_index = 0;
2732 
2733 	/* Queue commands to configure data transfer size. */
2734 	rtsx_set_cmd_data_len(sc, cmd->data->len / cmd->data->xfer_len, cmd->data->xfer_len);
2735 
2736 	/* From Linux: rtsx_pci_sdmmc.c sd_write_data(). */
2737 	rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_SD_CFG2, 0xff,
2738 		      RTSX_SD_CALCULATE_CRC7 | RTSX_SD_CHECK_CRC16 |
2739 		      RTSX_SD_NO_WAIT_BUSY_END | RTSX_SD_CHECK_CRC7 | RTSX_SD_RSP_LEN_0);
2740 
2741 	rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_SD_TRANSFER, 0xff,
2742 		      RTSX_TM_AUTO_WRITE3 | RTSX_SD_TRANSFER_START);
2743 	rtsx_push_cmd(sc, RTSX_CHECK_REG_CMD, RTSX_SD_TRANSFER,
2744 		      RTSX_SD_TRANSFER_END, RTSX_SD_TRANSFER_END);
2745 
2746 	/* Set transfer OK function. */
2747 	sc->rtsx_intr_trans_ok = rtsx_req_done;
2748 
2749 	/* Run the command queue. */
2750 	rtsx_send_cmd(sc);
2751 }
2752 
2753 /*
2754  * Use the data buffer for transfer > 512 bytes.
2755  */
2756 static int
2757 rtsx_xfer(struct rtsx_softc *sc, struct mmc_command *cmd)
2758 {
2759 	int	read = ISSET(cmd->data->flags, MMC_DATA_READ);
2760 
2761 	cmd->data->xfer_len = (cmd->data->len > RTSX_MAX_DATA_BLKLEN) ?
2762 		RTSX_MAX_DATA_BLKLEN : cmd->data->len;
2763 
2764 	if (sc->rtsx_debug_mask & RTSX_TRACE_SD_CMD)
2765 		device_printf(sc->rtsx_dev, "rtsx_xfer() - %s xfer: %ld bytes with block size %ld\n",
2766 			      read ? "Read" : "Write",
2767 			      (unsigned long)cmd->data->len, (unsigned long)cmd->data->xfer_len);
2768 
2769 	if (cmd->data->len > RTSX_DMA_DATA_BUFSIZE) {
2770 		device_printf(sc->rtsx_dev, "rtsx_xfer() length too large: %ld > %d\n",
2771 			      (unsigned long)cmd->data->len, RTSX_DMA_DATA_BUFSIZE);
2772 		cmd->error = MMC_ERR_INVALID;
2773 		return (MMC_ERR_INVALID);
2774 	}
2775 
2776 	if (!read) {
2777 		/* Set transfer OK function. */
2778 		sc->rtsx_intr_trans_ok = rtsx_xfer_begin;
2779 
2780 		/* Run the command queue. */
2781 		rtsx_send_req(sc, cmd);
2782 	} else {
2783 		rtsx_xfer_start(sc);
2784 	}
2785 
2786 	return (0);
2787 }
2788 
2789 /*
2790  * Get request response and start dma data transfer (write command).
2791  * This Function is called by the interrupt handler via sc->rtsx_intr_trans_ok.
2792  */
2793 static void
2794 rtsx_xfer_begin(struct rtsx_softc *sc)
2795 {
2796 	struct mmc_command *cmd;
2797 
2798 	cmd = sc->rtsx_req->cmd;
2799 
2800 	if (sc->rtsx_debug_mask & RTSX_TRACE_SD_CMD)
2801 		device_printf(sc->rtsx_dev, "rtsx_xfer_begin() - CMD%d\n", cmd->opcode);
2802 
2803 	rtsx_set_resp(sc, cmd);
2804 	rtsx_xfer_start(sc);
2805 }
2806 
2807 /*
2808  * Start dma data transfer.
2809  */
2810 static void
2811 rtsx_xfer_start(struct rtsx_softc *sc)
2812 {
2813 	struct mmc_command *cmd;
2814 	int	read;
2815 	uint8_t	cfg2;
2816 	int	dma_dir;
2817 	int	tmode;
2818 
2819 	cmd = sc->rtsx_req->cmd;
2820 	read = ISSET(cmd->data->flags, MMC_DATA_READ);
2821 
2822 	/* Configure DMA transfer mode parameters. */
2823 	if (cmd->opcode == MMC_READ_MULTIPLE_BLOCK)
2824 		cfg2 = RTSX_SD_CHECK_CRC16 | RTSX_SD_NO_WAIT_BUSY_END | RTSX_SD_RSP_LEN_6;
2825 	else
2826 		cfg2 = RTSX_SD_CHECK_CRC16 | RTSX_SD_NO_WAIT_BUSY_END | RTSX_SD_RSP_LEN_0;
2827 	if (read) {
2828 		dma_dir = RTSX_DMA_DIR_FROM_CARD;
2829 		/*
2830 		 * Use transfer mode AUTO_READ1, which assume we not
2831 		 * already send the read command and don't need to send
2832 		 * CMD 12 manually after read.
2833 		 */
2834 		tmode = RTSX_TM_AUTO_READ1;
2835 		cfg2 |= RTSX_SD_CALCULATE_CRC7 | RTSX_SD_CHECK_CRC7;
2836 
2837 		rtsx_init_cmd(sc, cmd);
2838 	} else {
2839 		dma_dir = RTSX_DMA_DIR_TO_CARD;
2840 		/*
2841 		 * Use transfer mode AUTO_WRITE3, wich assumes we've already
2842 		 * sent the write command and gotten the response, and will
2843 		 * send CMD 12 manually after writing.
2844 		 */
2845 		tmode = RTSX_TM_AUTO_WRITE3;
2846 		cfg2 |= RTSX_SD_NO_CALCULATE_CRC7 | RTSX_SD_NO_CHECK_CRC7;
2847 
2848 		sc->rtsx_cmd_index = 0;
2849 	}
2850 
2851 	/* Queue commands to configure data transfer size. */
2852 	rtsx_set_cmd_data_len(sc, cmd->data->len / cmd->data->xfer_len, cmd->data->xfer_len);
2853 
2854 	/* Configure DMA controller. */
2855 	rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_IRQSTAT0,
2856 		     RTSX_DMA_DONE_INT, RTSX_DMA_DONE_INT);
2857 	rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_DMATC3,
2858 		     0xff, cmd->data->len >> 24);
2859 	rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_DMATC2,
2860 		     0xff, cmd->data->len >> 16);
2861 	rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_DMATC1,
2862 		     0xff, cmd->data->len >> 8);
2863 	rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_DMATC0,
2864 		     0xff, cmd->data->len);
2865 	rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_DMACTL,
2866 		     RTSX_DMA_EN | RTSX_DMA_DIR | RTSX_DMA_PACK_SIZE_MASK,
2867 		     RTSX_DMA_EN | dma_dir | RTSX_DMA_512);
2868 
2869 	/* Use the DMA ring buffer for commands which transfer data. */
2870 	rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_CARD_DATA_SOURCE,
2871 		      0x01, RTSX_RING_BUFFER);
2872 
2873 	/* Queue command to set response type. */
2874 	rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_SD_CFG2, 0xff, cfg2);
2875 
2876 	/* Queue commands to perform SD transfer. */
2877 	rtsx_push_cmd(sc, RTSX_WRITE_REG_CMD, RTSX_SD_TRANSFER,
2878 		      0xff, tmode | RTSX_SD_TRANSFER_START);
2879 	rtsx_push_cmd(sc, RTSX_CHECK_REG_CMD, RTSX_SD_TRANSFER,
2880 		      RTSX_SD_TRANSFER_END, RTSX_SD_TRANSFER_END);
2881 
2882 	/* Run the command queue. */
2883 	rtsx_send_cmd(sc);
2884 
2885 	if (!read)
2886 		memcpy(sc->rtsx_data_dmamem, cmd->data->data, cmd->data->len);
2887 
2888 	/* Sync data DMA buffer. */
2889 	bus_dmamap_sync(sc->rtsx_data_dma_tag, sc->rtsx_data_dmamap, BUS_DMASYNC_PREREAD);
2890 	bus_dmamap_sync(sc->rtsx_data_dma_tag, sc->rtsx_data_dmamap, BUS_DMASYNC_PREWRITE);
2891 
2892 	/* Set transfer OK function. */
2893 	sc->rtsx_intr_trans_ok = rtsx_xfer_finish;
2894 
2895 	/* Tell the chip where the data buffer is and run the transfer. */
2896 	WRITE4(sc, RTSX_HDBAR, sc->rtsx_data_buffer);
2897 	WRITE4(sc, RTSX_HDBCTLR, RTSX_TRIG_DMA | (read ? RTSX_DMA_READ : 0) |
2898 	       (cmd->data->len & 0x00ffffff));
2899 }
2900 
2901 /*
2902  * Finish dma data transfer.
2903  * This Function is called by the interrupt handler via sc->rtsx_intr_trans_ok.
2904  */
2905 static void
2906 rtsx_xfer_finish(struct rtsx_softc *sc)
2907 {
2908 	struct mmc_command *cmd;
2909 	int	read;
2910 
2911 	cmd = sc->rtsx_req->cmd;
2912 
2913 	if (sc->rtsx_debug_mask & RTSX_TRACE_SD_CMD)
2914 		device_printf(sc->rtsx_dev, "rtsx_xfer_finish() - CMD%d\n", cmd->opcode);
2915 
2916 	read = ISSET(cmd->data->flags, MMC_DATA_READ);
2917 
2918 	/* Sync data DMA buffer. */
2919 	bus_dmamap_sync(sc->rtsx_data_dma_tag, sc->rtsx_data_dmamap, BUS_DMASYNC_POSTREAD);
2920 	bus_dmamap_sync(sc->rtsx_data_dma_tag, sc->rtsx_data_dmamap, BUS_DMASYNC_POSTWRITE);
2921 
2922 	if (read) {
2923 		memcpy(cmd->data->data, sc->rtsx_data_dmamem, cmd->data->len);
2924 		rtsx_req_done(sc);
2925 	} else {
2926 		/* Send CMD12 after AUTO_WRITE3 (see mmcsd_rw() in mmcsd.c) */
2927 		/* and complete request. */
2928 		sc->rtsx_intr_trans_ok = NULL;
2929 		rtsx_send_req(sc, sc->rtsx_req->stop);
2930 	}
2931 }
2932 
2933 /*
2934  * Manage request timeout.
2935  */
2936 static void
2937 rtsx_timeout(void *arg)
2938 {
2939 	struct rtsx_softc *sc;
2940 
2941 	sc = (struct rtsx_softc *)arg;
2942 	if (sc->rtsx_req != NULL) {
2943 		device_printf(sc->rtsx_dev, "Controller timeout for CMD%u\n",
2944 			      sc->rtsx_req->cmd->opcode);
2945 		sc->rtsx_req->cmd->error = MMC_ERR_TIMEOUT;
2946 		rtsx_stop_cmd(sc);
2947 		rtsx_req_done(sc);
2948 	} else {
2949 		device_printf(sc->rtsx_dev, "Controller timeout!\n");
2950 	}
2951 }
2952 
2953 #ifdef MMCCAM
2954 static int
2955 rtsx_get_tran_settings(device_t dev, struct ccb_trans_settings_mmc *cts)
2956 {
2957 	struct rtsx_softc *sc;
2958 
2959 	sc = device_get_softc(dev);
2960 
2961 	cts->host_ocr = sc->rtsx_host.host_ocr;
2962 	cts->host_f_min = sc->rtsx_host.f_min;
2963 	cts->host_f_max = sc->rtsx_host.f_max;
2964 	cts->host_caps = sc->rtsx_host.caps;
2965 	cts->host_max_data = RTSX_DMA_DATA_BUFSIZE / MMC_SECTOR_SIZE;
2966 	memcpy(&cts->ios, &sc->rtsx_host.ios, sizeof(struct mmc_ios));
2967 
2968 	return (0);
2969 }
2970 
2971 /*
2972  *  Apply settings and return status accordingly.
2973 */
2974 static int
2975 rtsx_set_tran_settings(device_t dev, struct ccb_trans_settings_mmc *cts)
2976 {
2977 	struct rtsx_softc *sc;
2978 	struct mmc_ios *ios;
2979 	struct mmc_ios *new_ios;
2980 
2981 	sc = device_get_softc(dev);
2982 
2983 	ios = &sc->rtsx_host.ios;
2984 	new_ios = &cts->ios;
2985 
2986 	/* Update only requested fields */
2987 	if (cts->ios_valid & MMC_CLK) {
2988 		ios->clock = new_ios->clock;
2989 		sc->rtsx_ios_clock = -1;	/* To be updated by rtsx_mmcbr_update_ios(). */
2990 		if (sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
2991 			device_printf(sc->rtsx_dev, "rtsx_set_tran_settings() - clock: %u\n", ios->clock);
2992 	}
2993 	if (cts->ios_valid & MMC_VDD) {
2994 		ios->vdd = new_ios->vdd;
2995 		if (sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
2996 			device_printf(sc->rtsx_dev, "rtsx_set_tran_settings() - vdd: %d\n", ios->vdd);
2997 	}
2998 	if (cts->ios_valid & MMC_CS) {
2999 		ios->chip_select = new_ios->chip_select;
3000 		if (sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
3001 			device_printf(sc->rtsx_dev, "rtsx_set_tran_settings() - chip_select: %d\n", ios->chip_select);
3002 	}
3003 	if (cts->ios_valid & MMC_BW) {
3004 		ios->bus_width = new_ios->bus_width;
3005 		sc->rtsx_ios_bus_width = -1;	/* To be updated by rtsx_mmcbr_update_ios(). */
3006 		if (sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
3007 			device_printf(sc->rtsx_dev, "rtsx_set_tran_settings() - bus width: %d\n", ios->bus_width);
3008 	}
3009 	if (cts->ios_valid & MMC_PM) {
3010 		ios->power_mode = new_ios->power_mode;
3011 		sc->rtsx_ios_power_mode = -1;	/* To be updated by rtsx_mmcbr_update_ios(). */
3012 		if (sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
3013 			device_printf(sc->rtsx_dev, "rtsx_set_tran_settings() - power mode: %d\n", ios->power_mode);
3014 	}
3015 	if (cts->ios_valid & MMC_BT) {
3016 		ios->timing = new_ios->timing;
3017 		sc->rtsx_ios_timing = -1;	/* To be updated by rtsx_mmcbr_update_ios(). */
3018 		if (sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
3019 			device_printf(sc->rtsx_dev, "rtsx_set_tran_settings() - timing: %d\n", ios->timing);
3020 	}
3021 	if (cts->ios_valid & MMC_BM) {
3022 		ios->bus_mode = new_ios->bus_mode;
3023 		if (sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
3024 			device_printf(sc->rtsx_dev, "rtsx_set_tran_settings() - bus mode: %d\n", ios->bus_mode);
3025 	}
3026 #if  __FreeBSD_version >= 1300000
3027 	if (cts->ios_valid & MMC_VCCQ) {
3028 		ios->vccq = new_ios->vccq;
3029 		sc->rtsx_ios_vccq = -1;		/* To be updated by rtsx_mmcbr_update_ios(). */
3030 		if (sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
3031 			device_printf(sc->rtsx_dev, "rtsx_set_tran_settings() - vccq: %d\n", ios->vccq);
3032 	}
3033 #endif /* __FreeBSD_version >= 1300000 */
3034 	if (rtsx_mmcbr_update_ios(sc->rtsx_dev, NULL) == 0)
3035 		return (CAM_REQ_CMP);
3036 	else
3037 		return (CAM_REQ_CMP_ERR);
3038 }
3039 
3040 /*
3041  * Build a request and run it.
3042  */
3043 static int
3044 rtsx_cam_request(device_t dev, union ccb *ccb)
3045 {
3046 	struct rtsx_softc *sc;
3047 
3048 	sc = device_get_softc(dev);
3049 
3050 	RTSX_LOCK(sc);
3051 	if (sc->rtsx_ccb != NULL) {
3052 		RTSX_UNLOCK(sc);
3053 		return (CAM_BUSY);
3054 	}
3055 	sc->rtsx_ccb = ccb;
3056 	sc->rtsx_cam_req.cmd = &ccb->mmcio.cmd;
3057 	sc->rtsx_cam_req.stop = &ccb->mmcio.stop;
3058 	RTSX_UNLOCK(sc);
3059 
3060 	rtsx_mmcbr_request(sc->rtsx_dev, NULL, &sc->rtsx_cam_req);
3061 	return (0);
3062 }
3063 #endif /* MMCCAM */
3064 
3065 static int
3066 rtsx_read_ivar(device_t bus, device_t child, int which, uintptr_t *result)
3067 {
3068 	struct rtsx_softc *sc;
3069 
3070 	sc = device_get_softc(bus);
3071 	switch (which) {
3072 	case MMCBR_IVAR_BUS_MODE:		/* ivar  0 - 1 = opendrain, 2 = pushpull */
3073 		*result = sc->rtsx_host.ios.bus_mode;
3074 		break;
3075 	case MMCBR_IVAR_BUS_WIDTH:		/* ivar  1 - 0 = 1b   2 = 4b, 3 = 8b */
3076 		*result = sc->rtsx_host.ios.bus_width;
3077 		break;
3078 	case MMCBR_IVAR_CHIP_SELECT:		/* ivar  2 - O = dontcare, 1 = cs_high, 2 = cs_low */
3079 		*result = sc->rtsx_host.ios.chip_select;
3080 		break;
3081 	case MMCBR_IVAR_CLOCK:			/* ivar  3 - clock in Hz */
3082 		*result = sc->rtsx_host.ios.clock;
3083 		break;
3084 	case MMCBR_IVAR_F_MIN:			/* ivar  4 */
3085 		*result = sc->rtsx_host.f_min;
3086 		break;
3087 	case MMCBR_IVAR_F_MAX:			/* ivar  5 */
3088 		*result = sc->rtsx_host.f_max;
3089 		break;
3090 	case MMCBR_IVAR_HOST_OCR: 		/* ivar  6 - host operation conditions register */
3091 		*result = sc->rtsx_host.host_ocr;
3092 		break;
3093 	case MMCBR_IVAR_MODE:			/* ivar  7 - 0 = mode_mmc, 1 = mode_sd */
3094 		*result = sc->rtsx_host.mode;
3095 		break;
3096 	case MMCBR_IVAR_OCR:			/* ivar  8 - operation conditions register */
3097 		*result = sc->rtsx_host.ocr;
3098 		break;
3099 	case MMCBR_IVAR_POWER_MODE:		/* ivar  9 - 0 = off, 1 = up, 2 = on */
3100 		*result = sc->rtsx_host.ios.power_mode;
3101 		break;
3102 	case MMCBR_IVAR_VDD:			/* ivar 11 - voltage power pin */
3103 		*result = sc->rtsx_host.ios.vdd;
3104 		break;
3105 	case MMCBR_IVAR_VCCQ:			/* ivar 12 - signaling: 0 = 1.20V, 1 = 1.80V, 2 = 3.30V */
3106 		*result = sc->rtsx_host.ios.vccq;
3107 		break;
3108 	case MMCBR_IVAR_CAPS:			/* ivar 13 */
3109 		*result = sc->rtsx_host.caps;
3110 		break;
3111 	case MMCBR_IVAR_TIMING:			/* ivar 14 - 0 = normal, 1 = timing_hs, ... */
3112 		*result = sc->rtsx_host.ios.timing;
3113 		break;
3114 	case MMCBR_IVAR_MAX_DATA:		/* ivar 15 */
3115 		*result = RTSX_DMA_DATA_BUFSIZE / MMC_SECTOR_SIZE;
3116 		break;
3117 	case MMCBR_IVAR_RETUNE_REQ:		/* ivar 10 */
3118 	case MMCBR_IVAR_MAX_BUSY_TIMEOUT:	/* ivar 16 */
3119 	default:
3120 		return (EINVAL);
3121 	}
3122 
3123 	if (sc->rtsx_debug_mask & RTSX_TRACE_SD_CMD)
3124 		device_printf(bus, "Read ivar #%d, value %#x / #%d\n",
3125 			      which, *(int *)result, *(int *)result);
3126 
3127 	return (0);
3128 }
3129 
3130 static int
3131 rtsx_write_ivar(device_t bus, device_t child, int which, uintptr_t value)
3132 {
3133 	struct rtsx_softc *sc;
3134 
3135 	sc = device_get_softc(bus);
3136 	if (sc->rtsx_debug_mask & RTSX_TRACE_SD_CMD)
3137 		device_printf(bus, "Write ivar #%d, value %#x / #%d\n",
3138 			      which, (int)value, (int)value);
3139 
3140 	switch (which) {
3141 	case MMCBR_IVAR_BUS_MODE:		/* ivar  0 - 1 = opendrain, 2 = pushpull */
3142 		sc->rtsx_host.ios.bus_mode = value;
3143 		break;
3144 	case MMCBR_IVAR_BUS_WIDTH:		/* ivar  1 - 0 = 1b   2 = 4b, 3 = 8b */
3145 		sc->rtsx_host.ios.bus_width = value;
3146 		sc->rtsx_ios_bus_width = -1;	/* To be updated on next rtsx_mmcbr_update_ios(). */
3147 		break;
3148 	case MMCBR_IVAR_CHIP_SELECT:		/* ivar  2 - O = dontcare, 1 = cs_high, 2 = cs_low */
3149 		sc->rtsx_host.ios.chip_select = value;
3150 		break;
3151 	case MMCBR_IVAR_CLOCK:			/* ivar  3 - clock in Hz */
3152 		sc->rtsx_host.ios.clock = value;
3153 		sc->rtsx_ios_clock = -1;	/* To be updated on next rtsx_mmcbr_update_ios(). */
3154 		break;
3155 	case MMCBR_IVAR_MODE:			/* ivar  7 - 0 = mode_mmc, 1 = mode_sd */
3156 		sc->rtsx_host.mode = value;
3157 		break;
3158 	case MMCBR_IVAR_OCR:			/* ivar  8 - operation conditions register */
3159 		sc->rtsx_host.ocr = value;
3160 		break;
3161 	case MMCBR_IVAR_POWER_MODE:		/* ivar  9 - 0 = off, 1 = up, 2 = on */
3162 		sc->rtsx_host.ios.power_mode = value;
3163 		sc->rtsx_ios_power_mode = -1;	/* To be updated on next rtsx_mmcbr_update_ios(). */
3164 		break;
3165 	case MMCBR_IVAR_VDD:			/* ivar 11 - voltage power pin */
3166 		sc->rtsx_host.ios.vdd = value;
3167 		break;
3168 	case MMCBR_IVAR_VCCQ:			/* ivar 12 - signaling: 0 = 1.20V, 1 = 1.80V, 2 = 3.30V */
3169 		sc->rtsx_host.ios.vccq = value;
3170 		sc->rtsx_ios_vccq = value;	/* rtsx_mmcbr_switch_vccq() will be called by mmc.c (MMCCAM undef). */
3171 		break;
3172 	case MMCBR_IVAR_TIMING:			/* ivar 14 - 0 = normal, 1 = timing_hs, ... */
3173 		sc->rtsx_host.ios.timing = value;
3174 		sc->rtsx_ios_timing = -1;	/* To be updated on next rtsx_mmcbr_update_ios(). */
3175 		break;
3176 	/* These are read-only. */
3177 	case MMCBR_IVAR_F_MIN:			/* ivar  4 */
3178 	case MMCBR_IVAR_F_MAX:			/* ivar  5 */
3179 	case MMCBR_IVAR_HOST_OCR: 		/* ivar  6 - host operation conditions register */
3180 	case MMCBR_IVAR_RETUNE_REQ:		/* ivar 10 */
3181 	case MMCBR_IVAR_CAPS:			/* ivar 13 */
3182 	case MMCBR_IVAR_MAX_DATA:		/* ivar 15 */
3183 	case MMCBR_IVAR_MAX_BUSY_TIMEOUT:	/* ivar 16 */
3184 	default:
3185 		return (EINVAL);
3186 	}
3187 
3188 	return (0);
3189 }
3190 
3191 static int
3192 rtsx_mmcbr_update_ios(device_t bus, device_t child__unused)
3193 {
3194 	struct rtsx_softc *sc;
3195 	struct mmc_ios	  *ios;
3196 	int	error;
3197 
3198 	sc = device_get_softc(bus);
3199 	ios = &sc->rtsx_host.ios;
3200 
3201 	if (sc->rtsx_debug_mask & RTSX_TRACE_SD_CMD)
3202 		device_printf(bus, "rtsx_mmcbr_update_ios()\n");
3203 
3204 	/* if MMCBR_IVAR_BUS_WIDTH updated. */
3205 	if (sc->rtsx_ios_bus_width < 0) {
3206 		sc->rtsx_ios_bus_width = ios->bus_width;
3207 		if ((error = rtsx_set_bus_width(sc, ios->bus_width)))
3208 			return (error);
3209 	}
3210 
3211 	/* if MMCBR_IVAR_POWER_MODE updated. */
3212 	if (sc->rtsx_ios_power_mode < 0) {
3213 		sc->rtsx_ios_power_mode = ios->power_mode;
3214 		switch (ios->power_mode) {
3215 		case power_off:
3216 			if ((error = rtsx_bus_power_off(sc)))
3217 				return (error);
3218 			break;
3219 		case power_up:
3220 			if ((error = rtsx_bus_power_on(sc)))
3221 				return (error);
3222 			break;
3223 		case power_on:
3224 			if ((error = rtsx_bus_power_on(sc)))
3225 				return (error);
3226 			break;
3227 		}
3228 	}
3229 
3230 	sc->rtsx_double_clk = true;
3231 	sc->rtsx_vpclk = false;
3232 
3233 	/* if MMCBR_IVAR_TIMING updated. */
3234 	if (sc->rtsx_ios_timing < 0) {
3235 		sc->rtsx_ios_timing = ios->timing;
3236 		if ((error = rtsx_set_sd_timing(sc, ios->timing)))
3237 			return (error);
3238 	}
3239 
3240 	/* if MMCBR_IVAR_CLOCK updated, must be after rtsx_set_sd_timing() */
3241 	if (sc->rtsx_ios_clock < 0) {
3242 		sc->rtsx_ios_clock = ios->clock;
3243 		if ((error = rtsx_set_sd_clock(sc, ios->clock)))
3244 			return (error);
3245 	}
3246 
3247 	/* if MMCCAM and vccq updated */
3248 	if (sc->rtsx_ios_vccq < 0) {
3249 		sc->rtsx_ios_vccq = ios->vccq;
3250 		if ((error = rtsx_mmcbr_switch_vccq(sc->rtsx_dev, NULL)))
3251 			return (error);
3252 	}
3253 
3254 	return (0);
3255 }
3256 
3257 /*
3258  * Set output stage logic power voltage.
3259  */
3260 static int
3261 rtsx_mmcbr_switch_vccq(device_t bus, device_t child __unused)
3262 {
3263 	struct rtsx_softc *sc;
3264 	int	vccq = 0;
3265 	int	error;
3266 
3267 	sc = device_get_softc(bus);
3268 
3269 	switch (sc->rtsx_host.ios.vccq) {
3270 	case vccq_120:
3271 		vccq = 120;
3272 		break;
3273 	case vccq_180:
3274 		vccq = 180;
3275 		break;
3276 	case vccq_330:
3277 		vccq = 330;
3278 		break;
3279 	};
3280 	/* It seems it is always vccq_330. */
3281 	if (vccq == 330) {
3282 		switch (sc->rtsx_device_id) {
3283 			uint16_t val;
3284 		case RTSX_RTS5227:
3285 			if ((error = rtsx_write_phy(sc, 0x08, 0x4FE4)))
3286 				return (error);
3287 			if ((error = rtsx_rts5227_fill_driving(sc)))
3288 				return (error);
3289 			break;
3290 		case RTSX_RTS5209:
3291 		case RTSX_RTS5229:
3292 			RTSX_BITOP(sc, RTSX_SD30_CMD_DRIVE_SEL, RTSX_SD30_DRIVE_SEL_MASK, sc->rtsx_sd30_drive_sel_3v3);
3293 			if ((error = rtsx_write_phy(sc, 0x08, 0x4FE4)))
3294 				return (error);
3295 			break;
3296 		case RTSX_RTS522A:
3297 			if ((error = rtsx_write_phy(sc, 0x08, 0x57E4)))
3298 				return (error);
3299 			if ((error = rtsx_rts5227_fill_driving(sc)))
3300 				return (error);
3301 			break;
3302 		case RTSX_RTS525A:
3303 			RTSX_BITOP(sc, RTSX_LDO_CONFIG2, RTSX_LDO_D3318_MASK, RTSX_LDO_D3318_33V);
3304 			RTSX_BITOP(sc, RTSX_SD_PAD_CTL, RTSX_SD_IO_USING_1V8, 0);
3305 			if ((error = rtsx_rts5249_fill_driving(sc)))
3306 				return (error);
3307 			break;
3308 		case RTSX_RTS5249:
3309 			if ((error = rtsx_read_phy(sc, RTSX_PHY_TUNE, &val)))
3310 				return (error);
3311 			if ((error = rtsx_write_phy(sc, RTSX_PHY_TUNE,
3312 						    (val & RTSX_PHY_TUNE_VOLTAGE_MASK) | RTSX_PHY_TUNE_VOLTAGE_3V3)))
3313 				return (error);
3314 			if ((error = rtsx_rts5249_fill_driving(sc)))
3315 				return (error);
3316 			break;
3317 		case RTSX_RTS5260:
3318 			RTSX_BITOP(sc, RTSX_LDO_CONFIG2, RTSX_DV331812_VDD1, RTSX_DV331812_VDD1);
3319 			RTSX_BITOP(sc, RTSX_LDO_DV18_CFG, RTSX_DV331812_MASK, RTSX_DV331812_33);
3320 			RTSX_CLR(sc, RTSX_SD_PAD_CTL, RTSX_SD_IO_USING_1V8);
3321 			if ((error = rtsx_rts5260_fill_driving(sc)))
3322 				return (error);
3323 			break;
3324 		case RTSX_RTL8402:
3325 			RTSX_BITOP(sc, RTSX_SD30_CMD_DRIVE_SEL, RTSX_SD30_DRIVE_SEL_MASK, sc->rtsx_sd30_drive_sel_3v3);
3326 			RTSX_BITOP(sc, RTSX_LDO_CTL,
3327 				   (RTSX_BPP_ASIC_MASK << RTSX_BPP_SHIFT_8402) | RTSX_BPP_PAD_MASK,
3328 				   (RTSX_BPP_ASIC_3V3 << RTSX_BPP_SHIFT_8402) | RTSX_BPP_PAD_3V3);
3329 			break;
3330 		case RTSX_RTL8411:
3331 		case RTSX_RTL8411B:
3332 			RTSX_BITOP(sc, RTSX_SD30_CMD_DRIVE_SEL, RTSX_SD30_DRIVE_SEL_MASK, sc->rtsx_sd30_drive_sel_3v3);
3333 			RTSX_BITOP(sc, RTSX_LDO_CTL,
3334 				   (RTSX_BPP_ASIC_MASK << RTSX_BPP_SHIFT_8411) | RTSX_BPP_PAD_MASK,
3335 				   (RTSX_BPP_ASIC_3V3 << RTSX_BPP_SHIFT_8411) | RTSX_BPP_PAD_3V3);
3336 			break;
3337 		}
3338 		DELAY(300);
3339 	}
3340 
3341 	if (sc->rtsx_debug_mask & (RTSX_DEBUG_BASIC | RTSX_TRACE_SD_CMD))
3342 		device_printf(sc->rtsx_dev, "rtsx_mmcbr_switch_vccq(%d)\n", vccq);
3343 
3344 	return (0);
3345 }
3346 
3347 #ifndef MMCCAM
3348 /*
3349  * Tune card if bus_timing_uhs_sdr50.
3350  */
3351 static int
3352 rtsx_mmcbr_tune(device_t bus, device_t child __unused, bool hs400)
3353 {
3354 	struct rtsx_softc *sc;
3355 	uint32_t raw_phase_map[RTSX_RX_TUNING_CNT] = {0};
3356 	uint32_t phase_map;
3357 	uint8_t	 final_phase;
3358 	int	 i;
3359 
3360 	sc = device_get_softc(bus);
3361 
3362 	if (sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
3363 		device_printf(sc->rtsx_dev, "rtsx_mmcbr_tune() - hs400 is %s\n",
3364 			      (hs400) ? "true" : "false");
3365 
3366 	if (sc->rtsx_ios_timing != bus_timing_uhs_sdr50)
3367 		return (0);
3368 
3369 	sc->rtsx_tuning_mode = true;
3370 
3371 	switch (sc->rtsx_device_id) {
3372 	case RTSX_RTS5209:
3373 	case RTSX_RTS5227:
3374 		rtsx_sd_change_tx_phase(sc, 27);
3375 		break;
3376 	case RTSX_RTS522A:
3377 		rtsx_sd_change_tx_phase(sc, 20);
3378 		break;
3379 	case RTSX_RTS5229:
3380 		rtsx_sd_change_tx_phase(sc, 27);
3381 		break;
3382 	case RTSX_RTS525A:
3383 	case RTSX_RTS5249:
3384 		rtsx_sd_change_tx_phase(sc, 29);
3385 		break;
3386 	case RTSX_RTL8402:
3387 	case RTSX_RTL8411:
3388 	case RTSX_RTL8411B:
3389 		rtsx_sd_change_tx_phase(sc, 7);
3390 		break;
3391 	}
3392 
3393 	/* trying rx tuning for bus_timing_uhs_sdr50. */
3394 	for (i = 0; i < RTSX_RX_TUNING_CNT; i++) {
3395 		rtsx_sd_tuning_rx_phase(sc, &(raw_phase_map[i]));
3396 		if (raw_phase_map[i] == 0)
3397 			break;
3398 	}
3399 
3400 	phase_map = 0xffffffff;
3401 	for (i = 0; i < RTSX_RX_TUNING_CNT; i++) {
3402 		if (sc->rtsx_debug_mask & (RTSX_DEBUG_BASIC | RTSX_DEBUG_TUNING))
3403 			device_printf(sc->rtsx_dev, "rtsx_mmcbr_tune() - RX raw_phase_map[%d]: 0x%08x\n",
3404 				      i, raw_phase_map[i]);
3405 		phase_map &= raw_phase_map[i];
3406 	}
3407 	if (sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
3408 		device_printf(sc->rtsx_dev, "rtsx_mmcbr_tune() - RX phase_map: 0x%08x\n", phase_map);
3409 
3410 	if (phase_map) {
3411 		final_phase = rtsx_sd_search_final_rx_phase(sc, phase_map);
3412 		if (final_phase != 0xff) {
3413 			rtsx_sd_change_rx_phase(sc, final_phase);
3414 		}
3415 	}
3416 
3417 	sc->rtsx_tuning_mode = false;
3418 
3419 	return (0);
3420 }
3421 
3422 static int
3423 rtsx_mmcbr_retune(device_t bus, device_t child __unused, bool reset __unused)
3424 {
3425 	struct rtsx_softc *sc;
3426 
3427 	sc = device_get_softc(bus);
3428 
3429 	if (sc->rtsx_debug_mask & RTSX_TRACE_SD_CMD)
3430 		device_printf(sc->rtsx_dev, "rtsx_mmcbr_retune()\n");
3431 
3432 	return (0);
3433 }
3434 #endif /* !MMCCAM */
3435 
3436 static int
3437 rtsx_mmcbr_request(device_t bus, device_t child __unused, struct mmc_request *req)
3438 {
3439 	struct rtsx_softc  *sc;
3440 	struct mmc_command *cmd;
3441 	int	timeout;
3442 	int	error;
3443 
3444 	sc = device_get_softc(bus);
3445 
3446 	RTSX_LOCK(sc);
3447 	if (sc->rtsx_req != NULL) {
3448 		RTSX_UNLOCK(sc);
3449 		return (EBUSY);
3450 	}
3451 	sc->rtsx_req = req;
3452 	cmd = req->cmd;
3453 	cmd->error = error = MMC_ERR_NONE;
3454 	sc->rtsx_intr_status = 0;
3455 	sc->rtsx_intr_trans_ok = NULL;
3456 	sc->rtsx_intr_trans_ko = rtsx_req_done;
3457 
3458 	if (sc->rtsx_debug_mask & RTSX_TRACE_SD_CMD)
3459 		device_printf(sc->rtsx_dev, "rtsx_mmcbr_request(CMD%u arg %#x, flags %#x, dlen %u, dflags %#x)\n",
3460 			      cmd->opcode, cmd->arg, cmd->flags,
3461 			      cmd->data != NULL ? (unsigned int)cmd->data->len : 0,
3462 			      cmd->data != NULL ? cmd->data->flags : 0);
3463 
3464 	/* Check if card present. */
3465 	if (!ISSET(sc->rtsx_flags, RTSX_F_CARD_PRESENT)) {
3466 		cmd->error = error = MMC_ERR_FAILED;
3467 		goto end;
3468 	}
3469 
3470 	/* Refuse SDIO probe if the chip doesn't support SDIO. */
3471 	if (cmd->opcode == IO_SEND_OP_COND &&
3472 	    !ISSET(sc->rtsx_flags, RTSX_F_SDIO_SUPPORT)) {
3473 		cmd->error = error = MMC_ERR_INVALID;
3474 		goto end;
3475 	}
3476 
3477 	/* Return MMC_ERR_TIMEOUT for SD_IO_RW_DIRECT and IO_SEND_OP_COND. */
3478 	if (cmd->opcode == SD_IO_RW_DIRECT || cmd->opcode == IO_SEND_OP_COND) {
3479 		cmd->error = error = MMC_ERR_TIMEOUT;
3480 		goto end;
3481 	}
3482 
3483 	/* Select SD card. */
3484 	RTSX_BITOP(sc, RTSX_CARD_SELECT, 0x07, RTSX_SD_MOD_SEL);
3485 	RTSX_BITOP(sc, RTSX_CARD_SHARE_MODE, RTSX_CARD_SHARE_MASK, RTSX_CARD_SHARE_48_SD);
3486 
3487 	if (cmd->data == NULL) {
3488 		DELAY(200);
3489 		timeout = sc->rtsx_timeout_cmd;
3490 		error = rtsx_send_req(sc, cmd);
3491 	} else if (cmd->data->len <= 512) {
3492 		timeout = sc->rtsx_timeout_io;
3493 		error = rtsx_xfer_short(sc, cmd);
3494 	} else {
3495 		timeout = sc->rtsx_timeout_io;
3496 		error = rtsx_xfer(sc, cmd);
3497 	}
3498  end:
3499 	if (error == MMC_ERR_NONE) {
3500 		callout_reset(&sc->rtsx_timeout_callout, timeout * hz, rtsx_timeout, sc);
3501 	} else {
3502 		rtsx_req_done(sc);
3503 	}
3504 	RTSX_UNLOCK(sc);
3505 
3506 	return (error);
3507 }
3508 
3509 #ifndef MMCCAM
3510 static int
3511 rtsx_mmcbr_get_ro(device_t bus, device_t child __unused)
3512 {
3513 	struct rtsx_softc *sc;
3514 
3515 	sc = device_get_softc(bus);
3516 
3517 	if (sc->rtsx_inversion == 0)
3518 		return (sc->rtsx_read_only);
3519 	else
3520 		return !(sc->rtsx_read_only);
3521 }
3522 
3523 static int
3524 rtsx_mmcbr_acquire_host(device_t bus, device_t child __unused)
3525 {
3526 	struct rtsx_softc *sc;
3527 
3528 	sc = device_get_softc(bus);
3529 	if (sc->rtsx_debug_mask & RTSX_TRACE_SD_CMD)
3530 		device_printf(bus, "rtsx_mmcbr_acquire_host()\n");
3531 
3532 	RTSX_LOCK(sc);
3533 	while (sc->rtsx_bus_busy)
3534 		msleep(&sc->rtsx_bus_busy, &sc->rtsx_mtx, 0, "rtsxah", 0);
3535 	sc->rtsx_bus_busy++;
3536 	RTSX_UNLOCK(sc);
3537 
3538 	return (0);
3539 }
3540 
3541 static int
3542 rtsx_mmcbr_release_host(device_t bus, device_t child __unused)
3543 {
3544 	struct rtsx_softc *sc;
3545 
3546 	sc = device_get_softc(bus);
3547 	if (sc->rtsx_debug_mask & RTSX_TRACE_SD_CMD)
3548 		device_printf(bus, "rtsx_mmcbr_release_host()\n");
3549 
3550 	RTSX_LOCK(sc);
3551 	sc->rtsx_bus_busy--;
3552 	wakeup(&sc->rtsx_bus_busy);
3553 	RTSX_UNLOCK(sc);
3554 
3555 	return (0);
3556 }
3557 #endif /* !MMCCAM */
3558 
3559 /*
3560  *
3561  * PCI Support Functions
3562  *
3563  */
3564 
3565 /*
3566  * Compare the device ID (chip) of this device against the IDs that this driver
3567  * supports. If there is a match, set the description and return success.
3568  */
3569 static int
3570 rtsx_probe(device_t dev)
3571 {
3572 	uint16_t vendor_id;
3573 	uint16_t device_id;
3574 	int	 i;
3575 
3576 	vendor_id = pci_get_vendor(dev);
3577 	device_id = pci_get_device(dev);
3578 
3579 	if (vendor_id != RTSX_REALTEK)
3580 		return (ENXIO);
3581 	for (i = 0; i < nitems(rtsx_ids); i++) {
3582 		if (rtsx_ids[i].device_id == device_id) {
3583 			device_set_desc(dev, rtsx_ids[i].desc);
3584 			return (BUS_PROBE_DEFAULT);
3585 		}
3586 	}
3587 	return (ENXIO);
3588 }
3589 
3590 /*
3591  * Attach function is only called if the probe is successful.
3592  */
3593 static int
3594 rtsx_attach(device_t dev)
3595 {
3596 	struct rtsx_softc 	*sc = device_get_softc(dev);
3597 	uint16_t 		vendor_id;
3598 	uint16_t 		device_id;
3599 	struct sysctl_ctx_list	*ctx;
3600 	struct sysctl_oid_list	*tree;
3601 	int			msi_count = 1;
3602 	uint32_t		sdio_cfg;
3603 	int			error;
3604 	char			*maker;
3605 	char			*family;
3606 	char			*product;
3607 	int			i;
3608 
3609 	vendor_id = pci_get_vendor(dev);
3610 	device_id = pci_get_device(dev);
3611 	if (bootverbose)
3612 		device_printf(dev, "Attach - Vendor ID: 0x%x - Device ID: 0x%x\n",
3613 			      vendor_id, device_id);
3614 
3615 	sc->rtsx_dev = dev;
3616 	sc->rtsx_device_id = device_id;
3617 	sc->rtsx_req = NULL;
3618 	sc->rtsx_timeout_cmd = 1;
3619 	sc->rtsx_timeout_io = 10;
3620 	sc->rtsx_read_only = 0;
3621 	sc->rtsx_inversion = 0;
3622 	sc->rtsx_force_timing = 0;
3623 	sc->rtsx_debug_mask = 0;
3624 	sc->rtsx_read_count = 0;
3625 	sc->rtsx_write_count = 0;
3626 
3627 	maker = kern_getenv("smbios.system.maker");
3628 	family = kern_getenv("smbios.system.family");
3629 	product = kern_getenv("smbios.system.product");
3630 	for (i = 0; rtsx_inversion_models[i].maker != NULL; i++) {
3631 		if (strcmp(rtsx_inversion_models[i].maker, maker) == 0 &&
3632 		    strcmp(rtsx_inversion_models[i].family, family) == 0 &&
3633 		    strcmp(rtsx_inversion_models[i].product, product) == 0) {
3634 			device_printf(dev, "Inversion activated for %s/%s/%s, see BUG in rtsx(4)\n", maker, family, product);
3635 			device_printf(dev, "If a card is detected without an SD card present,"
3636 				      " add dev.rtsx.0.inversion=0 in loader.conf(5)\n");
3637 			sc->rtsx_inversion = 1;
3638 		}
3639 	}
3640 
3641 	RTSX_LOCK_INIT(sc);
3642 
3643 	ctx = device_get_sysctl_ctx(dev);
3644 	tree = SYSCTL_CHILDREN(device_get_sysctl_tree(dev));
3645 	SYSCTL_ADD_INT(ctx, tree, OID_AUTO, "timeout_io", CTLFLAG_RW,
3646 		       &sc->rtsx_timeout_io, 0, "Request timeout for I/O commands in seconds");
3647 	SYSCTL_ADD_INT(ctx, tree, OID_AUTO, "timeout_cmd", CTLFLAG_RW,
3648 		       &sc->rtsx_timeout_cmd, 0, "Request timeout for setup commands in seconds");
3649 	SYSCTL_ADD_U8(ctx, tree, OID_AUTO, "read_only", CTLFLAG_RD,
3650 		      &sc->rtsx_read_only, 0, "Card is write protected");
3651 	SYSCTL_ADD_U8(ctx, tree, OID_AUTO, "inversion", CTLFLAG_RWTUN,
3652 		      &sc->rtsx_inversion, 0, "Inversion of card detection and read only status");
3653 	SYSCTL_ADD_U8(ctx, tree, OID_AUTO, "force_timing", CTLFLAG_RW,
3654 		      &sc->rtsx_force_timing, 0, "Force bus_timing_uhs_sdr50");
3655 	SYSCTL_ADD_U8(ctx, tree, OID_AUTO, "debug_mask", CTLFLAG_RWTUN,
3656 		      &sc->rtsx_debug_mask, 0, "debugging mask, see rtsx(4)");
3657 	SYSCTL_ADD_U64(ctx, tree, OID_AUTO, "read_count", CTLFLAG_RD | CTLFLAG_STATS,
3658 		       &sc->rtsx_read_count, 0, "Count of read operations");
3659 	SYSCTL_ADD_U64(ctx, tree, OID_AUTO, "write_count", CTLFLAG_RD | CTLFLAG_STATS,
3660 		       &sc->rtsx_write_count, 0, "Count of write operations");
3661 
3662 	if (bootverbose || sc->rtsx_debug_mask & RTSX_DEBUG_BASIC)
3663 		device_printf(dev, "We are running with inversion: %d\n", sc->rtsx_inversion);
3664 
3665 	/* Allocate IRQ. */
3666 	sc->rtsx_irq_res_id = 0;
3667 	if (pci_alloc_msi(dev, &msi_count) == 0)
3668 		sc->rtsx_irq_res_id = 1;
3669 	sc->rtsx_irq_res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &sc->rtsx_irq_res_id,
3670 						  RF_ACTIVE | (sc->rtsx_irq_res_id != 0 ? 0 : RF_SHAREABLE));
3671 	if (sc->rtsx_irq_res == NULL) {
3672 		device_printf(dev, "Can't allocate IRQ resources for %d\n", sc->rtsx_irq_res_id);
3673 		pci_release_msi(dev);
3674 		return (ENXIO);
3675 	}
3676 
3677 	callout_init_mtx(&sc->rtsx_timeout_callout, &sc->rtsx_mtx, 0);
3678 
3679 	/* Allocate memory resource. */
3680 	if (sc->rtsx_device_id == RTSX_RTS525A)
3681 		sc->rtsx_mem_res_id = PCIR_BAR(1);
3682 	else
3683 		sc->rtsx_mem_res_id = PCIR_BAR(0);
3684 	sc->rtsx_mem_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &sc->rtsx_mem_res_id, RF_ACTIVE);
3685 	if (sc->rtsx_mem_res == NULL) {
3686 		device_printf(dev, "Can't allocate memory resource for %d\n", sc->rtsx_mem_res_id);
3687 		goto destroy_rtsx_irq_res;
3688 	}
3689 
3690 	if (bootverbose)
3691 		device_printf(dev, "rtsx_irq_res_id: %d, rtsx_mem_res_id: %d\n",
3692 			      sc->rtsx_irq_res_id, sc->rtsx_mem_res_id);
3693 
3694 	sc->rtsx_mem_btag = rman_get_bustag(sc->rtsx_mem_res);
3695 	sc->rtsx_mem_bhandle = rman_get_bushandle(sc->rtsx_mem_res);
3696 
3697 	TIMEOUT_TASK_INIT(taskqueue_bus, &sc->rtsx_card_insert_task, 0,
3698 			  rtsx_card_task, sc);
3699 	TASK_INIT(&sc->rtsx_card_remove_task, 0, rtsx_card_task, sc);
3700 
3701 	/* Allocate two DMA buffers: a command buffer and a data buffer. */
3702 	error = rtsx_dma_alloc(sc);
3703 	if (error)
3704 		goto destroy_rtsx_irq_res;
3705 
3706 	/* Activate the interrupt. */
3707 	error = bus_setup_intr(dev, sc->rtsx_irq_res, INTR_TYPE_MISC | INTR_MPSAFE,
3708 			       NULL, rtsx_intr, sc, &sc->rtsx_irq_cookie);
3709 	if (error) {
3710 		device_printf(dev, "Can't set up irq [0x%x]!\n", error);
3711 		goto destroy_rtsx_mem_res;
3712 	}
3713 	pci_enable_busmaster(dev);
3714 
3715 	if (rtsx_read_cfg(sc, 0, RTSX_SDIOCFG_REG, &sdio_cfg) == 0) {
3716 		if ((sdio_cfg & RTSX_SDIOCFG_SDIO_ONLY) ||
3717 		    (sdio_cfg & RTSX_SDIOCFG_HAVE_SDIO))
3718 			sc->rtsx_flags |= RTSX_F_SDIO_SUPPORT;
3719 	}
3720 
3721 #ifdef MMCCAM
3722 	sc->rtsx_ccb = NULL;
3723 	sc->rtsx_cam_status = 0;
3724 
3725 	SYSCTL_ADD_U8(ctx, tree, OID_AUTO, "cam_status", CTLFLAG_RD,
3726 		      &sc->rtsx_cam_status, 0, "driver cam card present");
3727 
3728 	if (mmc_cam_sim_alloc(dev, "rtsx_mmc", &sc->rtsx_mmc_sim) != 0) {
3729 		device_printf(dev, "Can't allocate CAM SIM\n");
3730 		goto destroy_rtsx_irq;
3731 	}
3732 #endif /* MMCCAM */
3733 
3734 	/* Initialize device. */
3735 	error = rtsx_init(sc);
3736 	if (error) {
3737 		device_printf(dev, "Error %d during rtsx_init()\n", error);
3738 		goto destroy_rtsx_irq;
3739 	}
3740 
3741 	/*
3742 	 * Schedule a card detection as we won't get an interrupt
3743 	 * if the card is inserted when we attach. We wait a quarter
3744 	 * of a second to allow for a "spontaneous" interrupt which may
3745 	 * change the card presence state. This delay avoid a panic
3746 	 * on some configuration (e.g. Lenovo T540p).
3747 	 */
3748 	DELAY(250000);
3749 	if (rtsx_is_card_present(sc))
3750 		device_printf(sc->rtsx_dev, "A card is detected\n");
3751 	else
3752 		device_printf(sc->rtsx_dev, "No card is detected\n");
3753 	rtsx_card_task(sc, 0);
3754 
3755 	if (bootverbose)
3756 		device_printf(dev, "Device attached\n");
3757 
3758 	return (0);
3759 
3760  destroy_rtsx_irq:
3761 	bus_teardown_intr(dev, sc->rtsx_irq_res, sc->rtsx_irq_cookie);
3762  destroy_rtsx_mem_res:
3763 	bus_release_resource(dev, SYS_RES_MEMORY, sc->rtsx_mem_res_id,
3764 			     sc->rtsx_mem_res);
3765 	rtsx_dma_free(sc);
3766  destroy_rtsx_irq_res:
3767 	callout_drain(&sc->rtsx_timeout_callout);
3768 	bus_release_resource(dev, SYS_RES_IRQ, sc->rtsx_irq_res_id,
3769 			     sc->rtsx_irq_res);
3770 	pci_release_msi(dev);
3771 	RTSX_LOCK_DESTROY(sc);
3772 
3773 	return (ENXIO);
3774 }
3775 
3776 static int
3777 rtsx_detach(device_t dev)
3778 {
3779 	struct rtsx_softc *sc = device_get_softc(dev);
3780 	int	error;
3781 
3782 	if (bootverbose)
3783 		device_printf(dev, "Detach - Vendor ID: 0x%x - Device ID: 0x%x\n",
3784 			      pci_get_vendor(dev), sc->rtsx_device_id);
3785 
3786 	/* Disable interrupts. */
3787 	sc->rtsx_intr_enabled = 0;
3788 	WRITE4(sc, RTSX_BIER, sc->rtsx_intr_enabled);
3789 
3790 	/* Stop device. */
3791 	error = device_delete_children(sc->rtsx_dev);
3792 	sc->rtsx_mmc_dev = NULL;
3793 	if (error)
3794 		return (error);
3795 
3796 	taskqueue_drain_timeout(taskqueue_bus, &sc->rtsx_card_insert_task);
3797 	taskqueue_drain(taskqueue_bus, &sc->rtsx_card_remove_task);
3798 
3799 	/* Teardown the state in our softc created in our attach routine. */
3800 	rtsx_dma_free(sc);
3801 	if (sc->rtsx_mem_res != NULL)
3802 		bus_release_resource(dev, SYS_RES_MEMORY, sc->rtsx_mem_res_id,
3803 				     sc->rtsx_mem_res);
3804 	if (sc->rtsx_irq_cookie != NULL)
3805 		bus_teardown_intr(dev, sc->rtsx_irq_res, sc->rtsx_irq_cookie);
3806 	if (sc->rtsx_irq_res != NULL) {
3807 		callout_drain(&sc->rtsx_timeout_callout);
3808 		bus_release_resource(dev, SYS_RES_IRQ, sc->rtsx_irq_res_id,
3809 				     sc->rtsx_irq_res);
3810 		pci_release_msi(dev);
3811 	}
3812 	RTSX_LOCK_DESTROY(sc);
3813 #ifdef MMCCAM
3814 	mmc_cam_sim_free(&sc->rtsx_mmc_sim);
3815 #endif /* MMCCAM */
3816 
3817 	return (0);
3818 }
3819 
3820 static int
3821 rtsx_shutdown(device_t dev)
3822 {
3823 	if (bootverbose)
3824 		device_printf(dev, "Shutdown\n");
3825 
3826 	return (0);
3827 }
3828 
3829 /*
3830  * Device suspend routine.
3831  */
3832 static int
3833 rtsx_suspend(device_t dev)
3834 {
3835 	struct rtsx_softc *sc = device_get_softc(dev);
3836 
3837 	device_printf(dev, "Suspend\n");
3838 
3839 #ifdef MMCCAM
3840 	if (sc->rtsx_ccb != NULL) {
3841 		device_printf(dev, "Request in progress: CMD%u, rtsr_intr_status: 0x%08x\n",
3842 			      sc->rtsx_ccb->mmcio.cmd.opcode, sc->rtsx_intr_status);
3843 	}
3844 #else  /* !MMCCAM */
3845 	if (sc->rtsx_req != NULL) {
3846 		device_printf(dev, "Request in progress: CMD%u, rtsr_intr_status: 0x%08x\n",
3847 			      sc->rtsx_req->cmd->opcode, sc->rtsx_intr_status);
3848 	}
3849 #endif /* MMCCAM */
3850 
3851 	bus_generic_suspend(dev);
3852 
3853 	return (0);
3854 }
3855 
3856 /*
3857  * Device resume routine.
3858  */
3859 static int
3860 rtsx_resume(device_t dev)
3861 {
3862 	device_printf(dev, "Resume\n");
3863 
3864 	rtsx_init(device_get_softc(dev));
3865 
3866 	bus_generic_resume(dev);
3867 
3868 	return (0);
3869 }
3870 
3871 static device_method_t rtsx_methods[] = {
3872 	/* Device interface */
3873 	DEVMETHOD(device_probe,		rtsx_probe),
3874 	DEVMETHOD(device_attach,	rtsx_attach),
3875 	DEVMETHOD(device_detach,	rtsx_detach),
3876 	DEVMETHOD(device_shutdown,	rtsx_shutdown),
3877 	DEVMETHOD(device_suspend,	rtsx_suspend),
3878 	DEVMETHOD(device_resume,	rtsx_resume),
3879 
3880 	/* Bus interface */
3881 	DEVMETHOD(bus_read_ivar,	rtsx_read_ivar),
3882 	DEVMETHOD(bus_write_ivar,	rtsx_write_ivar),
3883 
3884 #ifndef MMCCAM
3885 	/* MMC bridge interface */
3886 	DEVMETHOD(mmcbr_update_ios,	rtsx_mmcbr_update_ios),
3887 	DEVMETHOD(mmcbr_switch_vccq,	rtsx_mmcbr_switch_vccq),
3888 	DEVMETHOD(mmcbr_tune,		rtsx_mmcbr_tune),
3889 	DEVMETHOD(mmcbr_retune,		rtsx_mmcbr_retune),
3890 	DEVMETHOD(mmcbr_request,	rtsx_mmcbr_request),
3891 	DEVMETHOD(mmcbr_get_ro,		rtsx_mmcbr_get_ro),
3892 	DEVMETHOD(mmcbr_acquire_host,	rtsx_mmcbr_acquire_host),
3893 	DEVMETHOD(mmcbr_release_host,	rtsx_mmcbr_release_host),
3894 #endif /* !MMCCAM */
3895 
3896 #ifdef MMCCAM
3897 	/* MMCCAM interface */
3898 	DEVMETHOD(mmc_sim_get_tran_settings,	rtsx_get_tran_settings),
3899 	DEVMETHOD(mmc_sim_set_tran_settings,	rtsx_set_tran_settings),
3900 	DEVMETHOD(mmc_sim_cam_request,		rtsx_cam_request),
3901 #endif /* MMCCAM */
3902 
3903 	DEVMETHOD_END
3904 };
3905 
3906 DEFINE_CLASS_0(rtsx, rtsx_driver, rtsx_methods, sizeof(struct rtsx_softc));
3907 DRIVER_MODULE(rtsx, pci, rtsx_driver, NULL, NULL);
3908 
3909 /* For Plug and Play */
3910 MODULE_PNP_INFO("U16:device;D:#;T:vendor=0x10ec", pci, rtsx,
3911 		rtsx_ids, nitems(rtsx_ids));
3912 
3913 #ifndef MMCCAM
3914 MMC_DECLARE_BRIDGE(rtsx);
3915 #endif /* !MMCCAM */
3916