xref: /linux/drivers/mmc/host/atmel-mci.c (revision 45bd2d77fbedec862204bb5c0fcaba2b7fa5fb56)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Atmel MultiMedia Card Interface driver
4  *
5  * Copyright (C) 2004-2008 Atmel Corporation
6  */
7 #include <linux/blkdev.h>
8 #include <linux/clk.h>
9 #include <linux/debugfs.h>
10 #include <linux/device.h>
11 #include <linux/dmaengine.h>
12 #include <linux/dma-mapping.h>
13 #include <linux/err.h>
14 #include <linux/init.h>
15 #include <linux/interrupt.h>
16 #include <linux/io.h>
17 #include <linux/ioport.h>
18 #include <linux/module.h>
19 #include <linux/of.h>
20 #include <linux/irq.h>
21 #include <linux/gpio/consumer.h>
22 #include <linux/platform_device.h>
23 #include <linux/scatterlist.h>
24 #include <linux/seq_file.h>
25 #include <linux/slab.h>
26 #include <linux/stat.h>
27 #include <linux/types.h>
28 
29 #include <linux/mmc/host.h>
30 #include <linux/mmc/sdio.h>
31 
32 #include <linux/atmel_pdc.h>
33 #include <linux/pm.h>
34 #include <linux/pm_runtime.h>
35 #include <linux/pinctrl/consumer.h>
36 #include <linux/workqueue.h>
37 
38 #include <asm/cacheflush.h>
39 #include <asm/io.h>
40 #include <linux/unaligned.h>
41 #include <linux/string_choices.h>
42 
43 #define ATMCI_MAX_NR_SLOTS	2
44 
45 /*
46  * Superset of MCI IP registers integrated in Atmel AT91 Processor
47  * Registers and bitfields marked with [2] are only available in MCI2
48  */
49 
50 /* MCI Register Definitions */
51 #define	ATMCI_CR			0x0000	/* Control */
52 #define		ATMCI_CR_MCIEN			BIT(0)		/* MCI Enable */
53 #define		ATMCI_CR_MCIDIS			BIT(1)		/* MCI Disable */
54 #define		ATMCI_CR_PWSEN			BIT(2)		/* Power Save Enable */
55 #define		ATMCI_CR_PWSDIS			BIT(3)		/* Power Save Disable */
56 #define		ATMCI_CR_SWRST			BIT(7)		/* Software Reset */
57 #define	ATMCI_MR			0x0004	/* Mode */
58 #define		ATMCI_MR_CLKDIV(x)		((x) <<  0)	/* Clock Divider */
59 #define		ATMCI_MR_PWSDIV(x)		((x) <<  8)	/* Power Saving Divider */
60 #define		ATMCI_MR_RDPROOF		BIT(11)		/* Read Proof */
61 #define		ATMCI_MR_WRPROOF		BIT(12)		/* Write Proof */
62 #define		ATMCI_MR_PDCFBYTE		BIT(13)		/* Force Byte Transfer */
63 #define		ATMCI_MR_PDCPADV		BIT(14)		/* Padding Value */
64 #define		ATMCI_MR_PDCMODE		BIT(15)		/* PDC-oriented Mode */
65 #define		ATMCI_MR_CLKODD(x)		((x) << 16)	/* LSB of Clock Divider */
66 #define	ATMCI_DTOR			0x0008	/* Data Timeout */
67 #define		ATMCI_DTOCYC(x)			((x) <<  0)	/* Data Timeout Cycles */
68 #define		ATMCI_DTOMUL(x)			((x) <<  4)	/* Data Timeout Multiplier */
69 #define	ATMCI_SDCR			0x000c	/* SD Card / SDIO */
70 #define		ATMCI_SDCSEL_SLOT_A		(0 <<  0)	/* Select SD slot A */
71 #define		ATMCI_SDCSEL_SLOT_B		(1 <<  0)	/* Select SD slot A */
72 #define		ATMCI_SDCSEL_MASK		(3 <<  0)
73 #define		ATMCI_SDCBUS_1BIT		(0 <<  6)	/* 1-bit data bus */
74 #define		ATMCI_SDCBUS_4BIT		(2 <<  6)	/* 4-bit data bus */
75 #define		ATMCI_SDCBUS_8BIT		(3 <<  6)	/* 8-bit data bus[2] */
76 #define		ATMCI_SDCBUS_MASK		(3 <<  6)
77 #define	ATMCI_ARGR			0x0010	/* Command Argument */
78 #define	ATMCI_CMDR			0x0014	/* Command */
79 #define		ATMCI_CMDR_CMDNB(x)		((x) <<  0)	/* Command Opcode */
80 #define		ATMCI_CMDR_RSPTYP_NONE		(0 <<  6)	/* No response */
81 #define		ATMCI_CMDR_RSPTYP_48BIT		(1 <<  6)	/* 48-bit response */
82 #define		ATMCI_CMDR_RSPTYP_136BIT	(2 <<  6)	/* 136-bit response */
83 #define		ATMCI_CMDR_SPCMD_INIT		(1 <<  8)	/* Initialization command */
84 #define		ATMCI_CMDR_SPCMD_SYNC		(2 <<  8)	/* Synchronized command */
85 #define		ATMCI_CMDR_SPCMD_INT		(4 <<  8)	/* Interrupt command */
86 #define		ATMCI_CMDR_SPCMD_INTRESP	(5 <<  8)	/* Interrupt response */
87 #define		ATMCI_CMDR_OPDCMD		(1 << 11)	/* Open Drain */
88 #define		ATMCI_CMDR_MAXLAT_5CYC		(0 << 12)	/* Max latency 5 cycles */
89 #define		ATMCI_CMDR_MAXLAT_64CYC		(1 << 12)	/* Max latency 64 cycles */
90 #define		ATMCI_CMDR_START_XFER		(1 << 16)	/* Start data transfer */
91 #define		ATMCI_CMDR_STOP_XFER		(2 << 16)	/* Stop data transfer */
92 #define		ATMCI_CMDR_TRDIR_WRITE		(0 << 18)	/* Write data */
93 #define		ATMCI_CMDR_TRDIR_READ		(1 << 18)	/* Read data */
94 #define		ATMCI_CMDR_BLOCK		(0 << 19)	/* Single-block transfer */
95 #define		ATMCI_CMDR_MULTI_BLOCK		(1 << 19)	/* Multi-block transfer */
96 #define		ATMCI_CMDR_STREAM		(2 << 19)	/* MMC Stream transfer */
97 #define		ATMCI_CMDR_SDIO_BYTE		(4 << 19)	/* SDIO Byte transfer */
98 #define		ATMCI_CMDR_SDIO_BLOCK		(5 << 19)	/* SDIO Block transfer */
99 #define		ATMCI_CMDR_SDIO_SUSPEND		(1 << 24)	/* SDIO Suspend Command */
100 #define		ATMCI_CMDR_SDIO_RESUME		(2 << 24)	/* SDIO Resume Command */
101 #define	ATMCI_BLKR			0x0018	/* Block */
102 #define		ATMCI_BCNT(x)			((x) <<  0)	/* Data Block Count */
103 #define		ATMCI_BLKLEN(x)			((x) << 16)	/* Data Block Length */
104 #define	ATMCI_CSTOR			0x001c	/* Completion Signal Timeout[2] */
105 #define		ATMCI_CSTOCYC(x)		((x) <<  0)	/* CST cycles */
106 #define		ATMCI_CSTOMUL(x)		((x) <<  4)	/* CST multiplier */
107 #define	ATMCI_RSPR			0x0020	/* Response 0 */
108 #define	ATMCI_RSPR1			0x0024	/* Response 1 */
109 #define	ATMCI_RSPR2			0x0028	/* Response 2 */
110 #define	ATMCI_RSPR3			0x002c	/* Response 3 */
111 #define	ATMCI_RDR			0x0030	/* Receive Data */
112 #define	ATMCI_TDR			0x0034	/* Transmit Data */
113 #define	ATMCI_SR			0x0040	/* Status */
114 #define	ATMCI_IER			0x0044	/* Interrupt Enable */
115 #define	ATMCI_IDR			0x0048	/* Interrupt Disable */
116 #define	ATMCI_IMR			0x004c	/* Interrupt Mask */
117 #define		ATMCI_CMDRDY			BIT(0)		/* Command Ready */
118 #define		ATMCI_RXRDY			BIT(1)		/* Receiver Ready */
119 #define		ATMCI_TXRDY			BIT(2)		/* Transmitter Ready */
120 #define		ATMCI_BLKE			BIT(3)		/* Data Block Ended */
121 #define		ATMCI_DTIP			BIT(4)		/* Data Transfer In Progress */
122 #define		ATMCI_NOTBUSY			BIT(5)		/* Data Not Busy */
123 #define		ATMCI_ENDRX			BIT(6)		/* End of RX Buffer */
124 #define		ATMCI_ENDTX			BIT(7)		/* End of TX Buffer */
125 #define		ATMCI_SDIOIRQA			BIT(8)		/* SDIO IRQ in slot A */
126 #define		ATMCI_SDIOIRQB			BIT(9)		/* SDIO IRQ in slot B */
127 #define		ATMCI_SDIOWAIT			BIT(12)		/* SDIO Read Wait Operation Status */
128 #define		ATMCI_CSRCV			BIT(13)		/* CE-ATA Completion Signal Received */
129 #define		ATMCI_RXBUFF			BIT(14)		/* RX Buffer Full */
130 #define		ATMCI_TXBUFE			BIT(15)		/* TX Buffer Empty */
131 #define		ATMCI_RINDE			BIT(16)		/* Response Index Error */
132 #define		ATMCI_RDIRE			BIT(17)		/* Response Direction Error */
133 #define		ATMCI_RCRCE			BIT(18)		/* Response CRC Error */
134 #define		ATMCI_RENDE			BIT(19)		/* Response End Bit Error */
135 #define		ATMCI_RTOE			BIT(20)		/* Response Time-Out Error */
136 #define		ATMCI_DCRCE			BIT(21)		/* Data CRC Error */
137 #define		ATMCI_DTOE			BIT(22)		/* Data Time-Out Error */
138 #define		ATMCI_CSTOE			BIT(23)		/* Completion Signal Time-out Error */
139 #define		ATMCI_BLKOVRE			BIT(24)		/* DMA Block Overrun Error */
140 #define		ATMCI_DMADONE			BIT(25)		/* DMA Transfer Done */
141 #define		ATMCI_FIFOEMPTY			BIT(26)		/* FIFO Empty Flag */
142 #define		ATMCI_XFRDONE			BIT(27)		/* Transfer Done Flag */
143 #define		ATMCI_ACKRCV			BIT(28)		/* Boot Operation Acknowledge Received */
144 #define		ATMCI_ACKRCVE			BIT(29)		/* Boot Operation Acknowledge Error */
145 #define		ATMCI_OVRE			BIT(30)		/* RX Overrun Error */
146 #define		ATMCI_UNRE			BIT(31)		/* TX Underrun Error */
147 #define	ATMCI_DMA			0x0050	/* DMA Configuration[2] */
148 #define		ATMCI_DMA_OFFSET(x)		((x) <<  0)	/* DMA Write Buffer Offset */
149 #define		ATMCI_DMA_CHKSIZE(x)		((x) <<  4)	/* DMA Channel Read and Write Chunk Size */
150 #define		ATMCI_DMAEN			BIT(8)	/* DMA Hardware Handshaking Enable */
151 #define	ATMCI_CFG			0x0054	/* Configuration[2] */
152 #define		ATMCI_CFG_FIFOMODE_1DATA	BIT(0)		/* MCI Internal FIFO control mode */
153 #define		ATMCI_CFG_FERRCTRL_COR		BIT(4)		/* Flow Error flag reset control mode */
154 #define		ATMCI_CFG_HSMODE		BIT(8)		/* High Speed Mode */
155 #define		ATMCI_CFG_LSYNC			BIT(12)		/* Synchronize on the last block */
156 #define	ATMCI_WPMR			0x00e4	/* Write Protection Mode[2] */
157 #define		ATMCI_WP_EN			BIT(0)		/* WP Enable */
158 #define		ATMCI_WP_KEY			(0x4d4349 << 8)	/* WP Key */
159 #define	ATMCI_WPSR			0x00e8	/* Write Protection Status[2] */
160 #define		ATMCI_GET_WP_VS(x)		((x) & 0x0f)
161 #define		ATMCI_GET_WP_VSRC(x)		(((x) >> 8) & 0xffff)
162 #define	ATMCI_VERSION			0x00FC  /* Version */
163 #define	ATMCI_FIFO_APERTURE		0x0200	/* FIFO Aperture[2] */
164 
165 /* This is not including the FIFO Aperture on MCI2 */
166 #define	ATMCI_REGS_SIZE		0x100
167 
168 /* Register access macros */
169 #define	atmci_readl(port, reg)				\
170 	__raw_readl((port)->regs + reg)
171 #define	atmci_writel(port, reg, value)			\
172 	__raw_writel((value), (port)->regs + reg)
173 
174 #define ATMCI_CMD_TIMEOUT_MS	2000
175 #define AUTOSUSPEND_DELAY	50
176 
177 #define ATMCI_DATA_ERROR_FLAGS	(ATMCI_DCRCE | ATMCI_DTOE | ATMCI_OVRE | ATMCI_UNRE)
178 #define ATMCI_DMA_THRESHOLD	16
179 
180 enum {
181 	EVENT_CMD_RDY = 0,
182 	EVENT_XFER_COMPLETE,
183 	EVENT_NOTBUSY,
184 	EVENT_DATA_ERROR,
185 };
186 
187 enum atmel_mci_state {
188 	STATE_IDLE = 0,
189 	STATE_SENDING_CMD,
190 	STATE_DATA_XFER,
191 	STATE_WAITING_NOTBUSY,
192 	STATE_SENDING_STOP,
193 	STATE_END_REQUEST,
194 };
195 
196 enum atmci_xfer_dir {
197 	XFER_RECEIVE = 0,
198 	XFER_TRANSMIT,
199 };
200 
201 enum atmci_pdc_buf {
202 	PDC_FIRST_BUF = 0,
203 	PDC_SECOND_BUF,
204 };
205 
206 /**
207  * struct mci_slot_pdata - board-specific per-slot configuration
208  * @bus_width: Number of data lines wired up the slot
209  * @detect_pin: GPIO pin wired to the card detect switch
210  * @wp_pin: GPIO pin wired to the write protect sensor
211  * @non_removable: The slot is not removable, only detect once
212  *
213  * If a given slot is not present on the board, @bus_width should be
214  * set to 0. The other fields are ignored in this case.
215  *
216  * Any pins that aren't available should be set to a negative value.
217  *
218  * Note that support for multiple slots is experimental -- some cards
219  * might get upset if we don't get the clock management exactly right.
220  * But in most cases, it should work just fine.
221  */
222 struct mci_slot_pdata {
223 	unsigned int		bus_width;
224 	struct gpio_desc        *detect_pin;
225 	struct gpio_desc	*wp_pin;
226 	bool			non_removable;
227 };
228 
229 struct atmel_mci_caps {
230 	bool    has_dma_conf_reg;
231 	bool    has_pdc;
232 	bool    has_cfg_reg;
233 	bool    has_cstor_reg;
234 	bool    has_highspeed;
235 	bool    has_rwproof;
236 	bool	has_odd_clk_div;
237 	bool	has_bad_data_ordering;
238 	bool	need_reset_after_xfer;
239 	bool	need_blksz_mul_4;
240 	bool	need_notbusy_for_read_ops;
241 };
242 
243 struct atmel_mci_dma {
244 	struct dma_chan			*chan;
245 	struct dma_async_tx_descriptor	*data_desc;
246 };
247 
248 /**
249  * struct atmel_mci - MMC controller state shared between all slots
250  * @lock: Spinlock protecting the queue and associated data.
251  * @regs: Pointer to MMIO registers.
252  * @sg: Scatterlist entry currently being processed by PIO or PDC code.
253  * @sg_len: Size of the scatterlist
254  * @pio_offset: Offset into the current scatterlist entry.
255  * @buffer: Buffer used if we don't have the r/w proof capability. We
256  *      don't have the time to switch pdc buffers so we have to use only
257  *      one buffer for the full transaction.
258  * @buf_size: size of the buffer.
259  * @buf_phys_addr: buffer address needed for pdc.
260  * @cur_slot: The slot which is currently using the controller.
261  * @mrq: The request currently being processed on @cur_slot,
262  *	or NULL if the controller is idle.
263  * @cmd: The command currently being sent to the card, or NULL.
264  * @data: The data currently being transferred, or NULL if no data
265  *	transfer is in progress.
266  * @data_size: just data->blocks * data->blksz.
267  * @dma: DMA client state.
268  * @data_chan: DMA channel being used for the current data transfer.
269  * @dma_conf: Configuration for the DMA slave
270  * @cmd_status: Snapshot of SR taken upon completion of the current
271  *	command. Only valid when EVENT_CMD_COMPLETE is pending.
272  * @data_status: Snapshot of SR taken upon completion of the current
273  *	data transfer. Only valid when EVENT_DATA_COMPLETE or
274  *	EVENT_DATA_ERROR is pending.
275  * @stop_cmdr: Value to be loaded into CMDR when the stop command is
276  *	to be sent.
277  * @bh_work: Work running the request state machine.
278  * @pending_events: Bitmask of events flagged by the interrupt handler
279  *	to be processed by the work.
280  * @completed_events: Bitmask of events which the state machine has
281  *	processed.
282  * @state: Work state.
283  * @queue: List of slots waiting for access to the controller.
284  * @need_clock_update: Update the clock rate before the next request.
285  * @need_reset: Reset controller before next request.
286  * @timer: Timer to balance the data timeout error flag which cannot rise.
287  * @mode_reg: Value of the MR register.
288  * @cfg_reg: Value of the CFG register.
289  * @bus_hz: The rate of @mck in Hz. This forms the basis for MMC bus
290  *	rate and timeout calculations.
291  * @mapbase: Physical address of the MMIO registers.
292  * @mck: The peripheral bus clock hooked up to the MMC controller.
293  * @dev: Device associated with the MMC controller.
294  * @pdata: Per-slot configuration data.
295  * @slot: Slots sharing this MMC controller.
296  * @caps: MCI capabilities depending on MCI version.
297  * @prepare_data: function to setup MCI before data transfer which
298  * depends on MCI capabilities.
299  * @submit_data: function to start data transfer which depends on MCI
300  * capabilities.
301  * @stop_transfer: function to stop data transfer which depends on MCI
302  * capabilities.
303  *
304  * Locking
305  * =======
306  *
307  * @lock is a softirq-safe spinlock protecting @queue as well as
308  * @cur_slot, @mrq and @state. These must always be updated
309  * at the same time while holding @lock.
310  *
311  * @lock also protects mode_reg and need_clock_update since these are
312  * used to synchronize mode register updates with the queue
313  * processing.
314  *
315  * The @mrq field of struct atmel_mci_slot is also protected by @lock,
316  * and must always be written at the same time as the slot is added to
317  * @queue.
318  *
319  * @pending_events and @completed_events are accessed using atomic bit
320  * operations, so they don't need any locking.
321  *
322  * None of the fields touched by the interrupt handler need any
323  * locking. However, ordering is important: Before EVENT_DATA_ERROR or
324  * EVENT_DATA_COMPLETE is set in @pending_events, all data-related
325  * interrupts must be disabled and @data_status updated with a
326  * snapshot of SR. Similarly, before EVENT_CMD_COMPLETE is set, the
327  * CMDRDY interrupt must be disabled and @cmd_status updated with a
328  * snapshot of SR, and before EVENT_XFER_COMPLETE can be set, the
329  * bytes_xfered field of @data must be written. This is ensured by
330  * using barriers.
331  */
332 struct atmel_mci {
333 	spinlock_t		lock;
334 	void __iomem		*regs;
335 
336 	struct scatterlist	*sg;
337 	unsigned int		sg_len;
338 	unsigned int		pio_offset;
339 	unsigned int		*buffer;
340 	unsigned int		buf_size;
341 	dma_addr_t		buf_phys_addr;
342 
343 	struct atmel_mci_slot	*cur_slot;
344 	struct mmc_request	*mrq;
345 	struct mmc_command	*cmd;
346 	struct mmc_data		*data;
347 	unsigned int		data_size;
348 
349 	struct atmel_mci_dma	dma;
350 	struct dma_chan		*data_chan;
351 	struct dma_slave_config	dma_conf;
352 
353 	u32			cmd_status;
354 	u32			data_status;
355 	u32			stop_cmdr;
356 
357 	struct work_struct	bh_work;
358 	unsigned long		pending_events;
359 	unsigned long		completed_events;
360 	enum atmel_mci_state	state;
361 	struct list_head	queue;
362 
363 	bool			need_clock_update;
364 	bool			need_reset;
365 	struct timer_list	timer;
366 	u32			mode_reg;
367 	u32			cfg_reg;
368 	unsigned long		bus_hz;
369 	unsigned long		mapbase;
370 	struct clk		*mck;
371 	struct device		*dev;
372 
373 	struct mci_slot_pdata	pdata[ATMCI_MAX_NR_SLOTS];
374 	struct atmel_mci_slot	*slot[ATMCI_MAX_NR_SLOTS];
375 
376 	struct atmel_mci_caps   caps;
377 
378 	u32 (*prepare_data)(struct atmel_mci *host, struct mmc_data *data);
379 	void (*submit_data)(struct atmel_mci *host, struct mmc_data *data);
380 	void (*stop_transfer)(struct atmel_mci *host);
381 };
382 
383 /**
384  * struct atmel_mci_slot - MMC slot state
385  * @mmc: The mmc_host representing this slot.
386  * @host: The MMC controller this slot is using.
387  * @sdc_reg: Value of SDCR to be written before using this slot.
388  * @sdio_irq: SDIO irq mask for this slot.
389  * @mrq: mmc_request currently being processed or waiting to be
390  *	processed, or NULL when the slot is idle.
391  * @queue_node: List node for placing this node in the @queue list of
392  *	&struct atmel_mci.
393  * @clock: Clock rate configured by set_ios(). Protected by host->lock.
394  * @flags: Random state bits associated with the slot.
395  * @detect_pin: GPIO pin used for card detection, or negative if not
396  *	available.
397  * @wp_pin: GPIO pin used for card write protect sending, or negative
398  *	if not available.
399  * @detect_timer: Timer used for debouncing @detect_pin interrupts.
400  */
401 struct atmel_mci_slot {
402 	struct mmc_host		*mmc;
403 	struct atmel_mci	*host;
404 
405 	u32			sdc_reg;
406 	u32			sdio_irq;
407 
408 	struct mmc_request	*mrq;
409 	struct list_head	queue_node;
410 
411 	unsigned int		clock;
412 	unsigned long		flags;
413 #define ATMCI_CARD_PRESENT	0
414 #define ATMCI_CARD_NEED_INIT	1
415 #define ATMCI_SHUTDOWN		2
416 
417 	struct gpio_desc        *detect_pin;
418 	struct gpio_desc	*wp_pin;
419 
420 	struct timer_list	detect_timer;
421 };
422 
423 #define atmci_test_and_clear_pending(host, event)		\
424 	test_and_clear_bit(event, &host->pending_events)
425 #define atmci_set_completed(host, event)			\
426 	set_bit(event, &host->completed_events)
427 #define atmci_set_pending(host, event)				\
428 	set_bit(event, &host->pending_events)
429 
430 /*
431  * The debugfs stuff below is mostly optimized away when
432  * CONFIG_DEBUG_FS is not set.
433  */
434 static int atmci_req_show(struct seq_file *s, void *v)
435 {
436 	struct atmel_mci_slot	*slot = s->private;
437 	struct mmc_request	*mrq;
438 	struct mmc_command	*cmd;
439 	struct mmc_command	*stop;
440 	struct mmc_data		*data;
441 
442 	/* Make sure we get a consistent snapshot */
443 	spin_lock_bh(&slot->host->lock);
444 	mrq = slot->mrq;
445 
446 	if (mrq) {
447 		cmd = mrq->cmd;
448 		data = mrq->data;
449 		stop = mrq->stop;
450 
451 		if (cmd)
452 			seq_printf(s,
453 				"CMD%u(0x%x) flg %x rsp %x %x %x %x err %d\n",
454 				cmd->opcode, cmd->arg, cmd->flags,
455 				cmd->resp[0], cmd->resp[1], cmd->resp[2],
456 				cmd->resp[3], cmd->error);
457 		if (data)
458 			seq_printf(s, "DATA %u / %u * %u flg %x err %d\n",
459 				data->bytes_xfered, data->blocks,
460 				data->blksz, data->flags, data->error);
461 		if (stop)
462 			seq_printf(s,
463 				"CMD%u(0x%x) flg %x rsp %x %x %x %x err %d\n",
464 				stop->opcode, stop->arg, stop->flags,
465 				stop->resp[0], stop->resp[1], stop->resp[2],
466 				stop->resp[3], stop->error);
467 	}
468 
469 	spin_unlock_bh(&slot->host->lock);
470 
471 	return 0;
472 }
473 
474 DEFINE_SHOW_ATTRIBUTE(atmci_req);
475 
476 static void atmci_show_status_reg(struct seq_file *s,
477 		const char *regname, u32 value)
478 {
479 	static const char	*sr_bit[] = {
480 		[0]	= "CMDRDY",
481 		[1]	= "RXRDY",
482 		[2]	= "TXRDY",
483 		[3]	= "BLKE",
484 		[4]	= "DTIP",
485 		[5]	= "NOTBUSY",
486 		[6]	= "ENDRX",
487 		[7]	= "ENDTX",
488 		[8]	= "SDIOIRQA",
489 		[9]	= "SDIOIRQB",
490 		[12]	= "SDIOWAIT",
491 		[14]	= "RXBUFF",
492 		[15]	= "TXBUFE",
493 		[16]	= "RINDE",
494 		[17]	= "RDIRE",
495 		[18]	= "RCRCE",
496 		[19]	= "RENDE",
497 		[20]	= "RTOE",
498 		[21]	= "DCRCE",
499 		[22]	= "DTOE",
500 		[23]	= "CSTOE",
501 		[24]	= "BLKOVRE",
502 		[25]	= "DMADONE",
503 		[26]	= "FIFOEMPTY",
504 		[27]	= "XFRDONE",
505 		[30]	= "OVRE",
506 		[31]	= "UNRE",
507 	};
508 	unsigned int		i;
509 
510 	seq_printf(s, "%s:\t0x%08x", regname, value);
511 	for (i = 0; i < ARRAY_SIZE(sr_bit); i++) {
512 		if (value & (1 << i)) {
513 			if (sr_bit[i])
514 				seq_printf(s, " %s", sr_bit[i]);
515 			else
516 				seq_puts(s, " UNKNOWN");
517 		}
518 	}
519 	seq_putc(s, '\n');
520 }
521 
522 static int atmci_regs_show(struct seq_file *s, void *v)
523 {
524 	struct atmel_mci	*host = s->private;
525 	struct device		*dev = host->dev;
526 	u32			*buf;
527 	int			ret = 0;
528 
529 
530 	buf = kmalloc(ATMCI_REGS_SIZE, GFP_KERNEL);
531 	if (!buf)
532 		return -ENOMEM;
533 
534 	pm_runtime_get_sync(dev);
535 
536 	/*
537 	 * Grab a more or less consistent snapshot. Note that we're
538 	 * not disabling interrupts, so IMR and SR may not be
539 	 * consistent.
540 	 */
541 	spin_lock_bh(&host->lock);
542 	memcpy_fromio(buf, host->regs, ATMCI_REGS_SIZE);
543 	spin_unlock_bh(&host->lock);
544 
545 	pm_runtime_put_autosuspend(dev);
546 
547 	seq_printf(s, "MR:\t0x%08x%s%s ",
548 			buf[ATMCI_MR / 4],
549 			buf[ATMCI_MR / 4] & ATMCI_MR_RDPROOF ? " RDPROOF" : "",
550 			buf[ATMCI_MR / 4] & ATMCI_MR_WRPROOF ? " WRPROOF" : "");
551 	if (host->caps.has_odd_clk_div)
552 		seq_printf(s, "{CLKDIV,CLKODD}=%u\n",
553 				((buf[ATMCI_MR / 4] & 0xff) << 1)
554 				| ((buf[ATMCI_MR / 4] >> 16) & 1));
555 	else
556 		seq_printf(s, "CLKDIV=%u\n",
557 				(buf[ATMCI_MR / 4] & 0xff));
558 	seq_printf(s, "DTOR:\t0x%08x\n", buf[ATMCI_DTOR / 4]);
559 	seq_printf(s, "SDCR:\t0x%08x\n", buf[ATMCI_SDCR / 4]);
560 	seq_printf(s, "ARGR:\t0x%08x\n", buf[ATMCI_ARGR / 4]);
561 	seq_printf(s, "BLKR:\t0x%08x BCNT=%u BLKLEN=%u\n",
562 			buf[ATMCI_BLKR / 4],
563 			buf[ATMCI_BLKR / 4] & 0xffff,
564 			(buf[ATMCI_BLKR / 4] >> 16) & 0xffff);
565 	if (host->caps.has_cstor_reg)
566 		seq_printf(s, "CSTOR:\t0x%08x\n", buf[ATMCI_CSTOR / 4]);
567 
568 	/* Don't read RSPR and RDR; it will consume the data there */
569 
570 	atmci_show_status_reg(s, "SR", buf[ATMCI_SR / 4]);
571 	atmci_show_status_reg(s, "IMR", buf[ATMCI_IMR / 4]);
572 
573 	if (host->caps.has_dma_conf_reg) {
574 		u32 val;
575 
576 		val = buf[ATMCI_DMA / 4];
577 		seq_printf(s, "DMA:\t0x%08x OFFSET=%u CHKSIZE=%u%s\n",
578 				val, val & 3,
579 				((val >> 4) & 3) ?
580 					1 << (((val >> 4) & 3) + 1) : 1,
581 				val & ATMCI_DMAEN ? " DMAEN" : "");
582 	}
583 	if (host->caps.has_cfg_reg) {
584 		u32 val;
585 
586 		val = buf[ATMCI_CFG / 4];
587 		seq_printf(s, "CFG:\t0x%08x%s%s%s%s\n",
588 				val,
589 				val & ATMCI_CFG_FIFOMODE_1DATA ? " FIFOMODE_ONE_DATA" : "",
590 				val & ATMCI_CFG_FERRCTRL_COR ? " FERRCTRL_CLEAR_ON_READ" : "",
591 				val & ATMCI_CFG_HSMODE ? " HSMODE" : "",
592 				val & ATMCI_CFG_LSYNC ? " LSYNC" : "");
593 	}
594 
595 	kfree(buf);
596 
597 	return ret;
598 }
599 
600 DEFINE_SHOW_ATTRIBUTE(atmci_regs);
601 
602 static void atmci_init_debugfs(struct atmel_mci_slot *slot)
603 {
604 	struct mmc_host		*mmc = slot->mmc;
605 	struct atmel_mci	*host = slot->host;
606 	struct dentry		*root;
607 
608 	root = mmc->debugfs_root;
609 	if (!root)
610 		return;
611 
612 	debugfs_create_file("regs", 0400, root, host, &atmci_regs_fops);
613 	debugfs_create_file("req", 0400, root, slot, &atmci_req_fops);
614 	debugfs_create_u32("state", 0400, root, &host->state);
615 	debugfs_create_xul("pending_events", 0400, root,
616 			   &host->pending_events);
617 	debugfs_create_xul("completed_events", 0400, root,
618 			   &host->completed_events);
619 }
620 
621 static const struct of_device_id atmci_dt_ids[] = {
622 	{ .compatible = "atmel,hsmci" },
623 	{ /* sentinel */ }
624 };
625 
626 MODULE_DEVICE_TABLE(of, atmci_dt_ids);
627 
628 static int atmci_of_init(struct atmel_mci *host)
629 {
630 	struct device *dev = host->dev;
631 	struct device_node *np = dev->of_node;
632 	u32 slot_id;
633 	int err;
634 
635 	if (!np)
636 		return dev_err_probe(dev, -EINVAL, "device node not found\n");
637 
638 	for_each_child_of_node_scoped(np, cnp) {
639 		if (of_property_read_u32(cnp, "reg", &slot_id)) {
640 			dev_warn(dev, "reg property is missing for %pOF\n", cnp);
641 			continue;
642 		}
643 
644 		if (slot_id >= ATMCI_MAX_NR_SLOTS) {
645 			dev_warn(dev, "can't have more than %d slots\n",
646 			         ATMCI_MAX_NR_SLOTS);
647 			break;
648 		}
649 
650 		if (of_property_read_u32(cnp, "bus-width",
651 					 &host->pdata[slot_id].bus_width))
652 			host->pdata[slot_id].bus_width = 1;
653 
654 		host->pdata[slot_id].detect_pin =
655 			devm_fwnode_gpiod_get(dev, of_fwnode_handle(cnp),
656 					      "cd", GPIOD_IN, "cd-gpios");
657 		err = PTR_ERR_OR_ZERO(host->pdata[slot_id].detect_pin);
658 		if (err) {
659 			if (err != -ENOENT)
660 				return err;
661 			host->pdata[slot_id].detect_pin = NULL;
662 		}
663 
664 		host->pdata[slot_id].non_removable =
665 			of_property_read_bool(cnp, "non-removable");
666 
667 		host->pdata[slot_id].wp_pin =
668 			devm_fwnode_gpiod_get(dev, of_fwnode_handle(cnp),
669 					      "wp", GPIOD_IN, "wp-gpios");
670 		err = PTR_ERR_OR_ZERO(host->pdata[slot_id].wp_pin);
671 		if (err) {
672 			if (err != -ENOENT)
673 				return err;
674 			host->pdata[slot_id].wp_pin = NULL;
675 		}
676 	}
677 
678 	return 0;
679 }
680 
681 static inline unsigned int atmci_get_version(struct atmel_mci *host)
682 {
683 	return atmci_readl(host, ATMCI_VERSION) & 0x00000fff;
684 }
685 
686 /*
687  * Fix sconfig's burst size according to atmel MCI. We need to convert them as:
688  * 1 -> 0, 4 -> 1, 8 -> 2, 16 -> 3.
689  * With version 0x600, we need to convert them as: 1 -> 0, 2 -> 1, 4 -> 2,
690  * 8 -> 3, 16 -> 4.
691  *
692  * This can be done by finding most significant bit set.
693  */
694 static inline unsigned int atmci_convert_chksize(struct atmel_mci *host,
695 						 unsigned int maxburst)
696 {
697 	unsigned int version = atmci_get_version(host);
698 	unsigned int offset = 2;
699 
700 	if (version >= 0x600)
701 		offset = 1;
702 
703 	if (maxburst > 1)
704 		return fls(maxburst) - offset;
705 	else
706 		return 0;
707 }
708 
709 static void atmci_timeout_timer(struct timer_list *t)
710 {
711 	struct atmel_mci *host = timer_container_of(host, t, timer);
712 	struct device *dev = host->dev;
713 
714 	dev_dbg(dev, "software timeout\n");
715 
716 	if (host->mrq->cmd->data) {
717 		host->mrq->cmd->data->error = -ETIMEDOUT;
718 		host->data = NULL;
719 		/*
720 		 * With some SDIO modules, sometimes DMA transfer hangs. If
721 		 * stop_transfer() is not called then the DMA request is not
722 		 * removed, following ones are queued and never computed.
723 		 */
724 		if (host->state == STATE_DATA_XFER)
725 			host->stop_transfer(host);
726 	} else {
727 		host->mrq->cmd->error = -ETIMEDOUT;
728 		host->cmd = NULL;
729 	}
730 	host->need_reset = 1;
731 	host->state = STATE_END_REQUEST;
732 	smp_wmb();
733 	queue_work(system_bh_wq, &host->bh_work);
734 }
735 
736 static inline unsigned int atmci_ns_to_clocks(struct atmel_mci *host,
737 					unsigned int ns)
738 {
739 	/*
740 	 * It is easier here to use us instead of ns for the timeout,
741 	 * it prevents from overflows during calculation.
742 	 */
743 	unsigned int us = DIV_ROUND_UP(ns, 1000);
744 
745 	/* Maximum clock frequency is host->bus_hz/2 */
746 	return us * (DIV_ROUND_UP(host->bus_hz, 2000000));
747 }
748 
749 static void atmci_set_timeout(struct atmel_mci *host,
750 		struct atmel_mci_slot *slot, struct mmc_data *data)
751 {
752 	static unsigned	dtomul_to_shift[] = {
753 		0, 4, 7, 8, 10, 12, 16, 20
754 	};
755 	unsigned	timeout;
756 	unsigned	dtocyc;
757 	unsigned	dtomul;
758 
759 	timeout = atmci_ns_to_clocks(host, data->timeout_ns)
760 		+ data->timeout_clks;
761 
762 	for (dtomul = 0; dtomul < 8; dtomul++) {
763 		unsigned shift = dtomul_to_shift[dtomul];
764 		dtocyc = (timeout + (1 << shift) - 1) >> shift;
765 		if (dtocyc < 15)
766 			break;
767 	}
768 
769 	if (dtomul >= 8) {
770 		dtomul = 7;
771 		dtocyc = 15;
772 	}
773 
774 	dev_vdbg(&slot->mmc->class_dev, "setting timeout to %u cycles\n",
775 			dtocyc << dtomul_to_shift[dtomul]);
776 	atmci_writel(host, ATMCI_DTOR, (ATMCI_DTOMUL(dtomul) | ATMCI_DTOCYC(dtocyc)));
777 }
778 
779 /*
780  * Return mask with command flags to be enabled for this command.
781  */
782 static u32 atmci_prepare_command(struct mmc_host *mmc,
783 				 struct mmc_command *cmd)
784 {
785 	struct mmc_data	*data;
786 	u32		cmdr;
787 
788 	cmd->error = -EINPROGRESS;
789 
790 	cmdr = ATMCI_CMDR_CMDNB(cmd->opcode);
791 
792 	if (cmd->flags & MMC_RSP_PRESENT) {
793 		if (cmd->flags & MMC_RSP_136)
794 			cmdr |= ATMCI_CMDR_RSPTYP_136BIT;
795 		else
796 			cmdr |= ATMCI_CMDR_RSPTYP_48BIT;
797 	}
798 
799 	/*
800 	 * This should really be MAXLAT_5 for CMD2 and ACMD41, but
801 	 * it's too difficult to determine whether this is an ACMD or
802 	 * not. Better make it 64.
803 	 */
804 	cmdr |= ATMCI_CMDR_MAXLAT_64CYC;
805 
806 	if (mmc->ios.bus_mode == MMC_BUSMODE_OPENDRAIN)
807 		cmdr |= ATMCI_CMDR_OPDCMD;
808 
809 	data = cmd->data;
810 	if (data) {
811 		cmdr |= ATMCI_CMDR_START_XFER;
812 
813 		if (cmd->opcode == SD_IO_RW_EXTENDED) {
814 			cmdr |= ATMCI_CMDR_SDIO_BLOCK;
815 		} else {
816 			if (data->blocks > 1)
817 				cmdr |= ATMCI_CMDR_MULTI_BLOCK;
818 			else
819 				cmdr |= ATMCI_CMDR_BLOCK;
820 		}
821 
822 		if (data->flags & MMC_DATA_READ)
823 			cmdr |= ATMCI_CMDR_TRDIR_READ;
824 	}
825 
826 	return cmdr;
827 }
828 
829 static void atmci_send_command(struct atmel_mci *host,
830 		struct mmc_command *cmd, u32 cmd_flags)
831 {
832 	struct device *dev = host->dev;
833 	unsigned int timeout_ms = cmd->busy_timeout ? cmd->busy_timeout :
834 		ATMCI_CMD_TIMEOUT_MS;
835 
836 	WARN_ON(host->cmd);
837 	host->cmd = cmd;
838 
839 	dev_vdbg(dev, "start command: ARGR=0x%08x CMDR=0x%08x\n", cmd->arg, cmd_flags);
840 
841 	atmci_writel(host, ATMCI_ARGR, cmd->arg);
842 	atmci_writel(host, ATMCI_CMDR, cmd_flags);
843 
844 	mod_timer(&host->timer, jiffies + msecs_to_jiffies(timeout_ms));
845 }
846 
847 static void atmci_send_stop_cmd(struct atmel_mci *host, struct mmc_data *data)
848 {
849 	struct device *dev = host->dev;
850 
851 	dev_dbg(dev, "send stop command\n");
852 	atmci_send_command(host, data->stop, host->stop_cmdr);
853 	atmci_writel(host, ATMCI_IER, ATMCI_CMDRDY);
854 }
855 
856 /*
857  * Configure given PDC buffer taking care of alignment issues.
858  * Update host->data_size and host->sg.
859  */
860 static void atmci_pdc_set_single_buf(struct atmel_mci *host,
861 	enum atmci_xfer_dir dir, enum atmci_pdc_buf buf_nb)
862 {
863 	u32 pointer_reg, counter_reg;
864 	unsigned int buf_size;
865 
866 	if (dir == XFER_RECEIVE) {
867 		pointer_reg = ATMEL_PDC_RPR;
868 		counter_reg = ATMEL_PDC_RCR;
869 	} else {
870 		pointer_reg = ATMEL_PDC_TPR;
871 		counter_reg = ATMEL_PDC_TCR;
872 	}
873 
874 	if (buf_nb == PDC_SECOND_BUF) {
875 		pointer_reg += ATMEL_PDC_SCND_BUF_OFF;
876 		counter_reg += ATMEL_PDC_SCND_BUF_OFF;
877 	}
878 
879 	if (!host->caps.has_rwproof) {
880 		buf_size = host->buf_size;
881 		atmci_writel(host, pointer_reg, host->buf_phys_addr);
882 	} else {
883 		buf_size = sg_dma_len(host->sg);
884 		atmci_writel(host, pointer_reg, sg_dma_address(host->sg));
885 	}
886 
887 	if (host->data_size <= buf_size) {
888 		if (host->data_size & 0x3) {
889 			/* If size is different from modulo 4, transfer bytes */
890 			atmci_writel(host, counter_reg, host->data_size);
891 			atmci_writel(host, ATMCI_MR, host->mode_reg | ATMCI_MR_PDCFBYTE);
892 		} else {
893 			/* Else transfer 32-bits words */
894 			atmci_writel(host, counter_reg, host->data_size / 4);
895 		}
896 		host->data_size = 0;
897 	} else {
898 		/* We assume the size of a page is 32-bits aligned */
899 		atmci_writel(host, counter_reg, sg_dma_len(host->sg) / 4);
900 		host->data_size -= sg_dma_len(host->sg);
901 		if (host->data_size)
902 			host->sg = sg_next(host->sg);
903 	}
904 }
905 
906 /*
907  * Configure PDC buffer according to the data size ie configuring one or two
908  * buffers. Don't use this function if you want to configure only the second
909  * buffer. In this case, use atmci_pdc_set_single_buf.
910  */
911 static void atmci_pdc_set_both_buf(struct atmel_mci *host, int dir)
912 {
913 	atmci_pdc_set_single_buf(host, dir, PDC_FIRST_BUF);
914 	if (host->data_size)
915 		atmci_pdc_set_single_buf(host, dir, PDC_SECOND_BUF);
916 }
917 
918 /*
919  * Unmap sg lists, called when transfer is finished.
920  */
921 static void atmci_pdc_cleanup(struct atmel_mci *host)
922 {
923 	struct mmc_data         *data = host->data;
924 	struct device		*dev = host->dev;
925 
926 	if (data)
927 		dma_unmap_sg(dev, data->sg, data->sg_len, mmc_get_dma_dir(data));
928 }
929 
930 /*
931  * Disable PDC transfers. Update pending flags to EVENT_XFER_COMPLETE after
932  * having received ATMCI_TXBUFE or ATMCI_RXBUFF interrupt. Enable ATMCI_NOTBUSY
933  * interrupt needed for both transfer directions.
934  */
935 static void atmci_pdc_complete(struct atmel_mci *host)
936 {
937 	struct device *dev = host->dev;
938 	int transfer_size = host->data->blocks * host->data->blksz;
939 	int i;
940 
941 	atmci_writel(host, ATMEL_PDC_PTCR, ATMEL_PDC_RXTDIS | ATMEL_PDC_TXTDIS);
942 
943 	if ((!host->caps.has_rwproof)
944 	    && (host->data->flags & MMC_DATA_READ)) {
945 		if (host->caps.has_bad_data_ordering)
946 			for (i = 0; i < transfer_size; i++)
947 				host->buffer[i] = swab32(host->buffer[i]);
948 		sg_copy_from_buffer(host->data->sg, host->data->sg_len,
949 		                    host->buffer, transfer_size);
950 	}
951 
952 	atmci_pdc_cleanup(host);
953 
954 	dev_dbg(dev, "(%s) set pending xfer complete\n", __func__);
955 	atmci_set_pending(host, EVENT_XFER_COMPLETE);
956 	queue_work(system_bh_wq, &host->bh_work);
957 }
958 
959 static void atmci_dma_cleanup(struct atmel_mci *host)
960 {
961 	struct mmc_data                 *data = host->data;
962 
963 	if (data)
964 		dma_unmap_sg(host->dma.chan->device->dev,
965 				data->sg, data->sg_len,
966 				mmc_get_dma_dir(data));
967 }
968 
969 /*
970  * This function is called by the DMA driver from bh context.
971  */
972 static void atmci_dma_complete(void *arg)
973 {
974 	struct atmel_mci	*host = arg;
975 	struct mmc_data		*data = host->data;
976 	struct device		*dev = host->dev;
977 
978 	dev_vdbg(dev, "DMA complete\n");
979 
980 	if (host->caps.has_dma_conf_reg)
981 		/* Disable DMA hardware handshaking on MCI */
982 		atmci_writel(host, ATMCI_DMA, atmci_readl(host, ATMCI_DMA) & ~ATMCI_DMAEN);
983 
984 	atmci_dma_cleanup(host);
985 
986 	/*
987 	 * If the card was removed, data will be NULL. No point trying
988 	 * to send the stop command or waiting for NBUSY in this case.
989 	 */
990 	if (data) {
991 		dev_dbg(dev, "(%s) set pending xfer complete\n", __func__);
992 		atmci_set_pending(host, EVENT_XFER_COMPLETE);
993 		queue_work(system_bh_wq, &host->bh_work);
994 
995 		/*
996 		 * Regardless of what the documentation says, we have
997 		 * to wait for NOTBUSY even after block read
998 		 * operations.
999 		 *
1000 		 * When the DMA transfer is complete, the controller
1001 		 * may still be reading the CRC from the card, i.e.
1002 		 * the data transfer is still in progress and we
1003 		 * haven't seen all the potential error bits yet.
1004 		 *
1005 		 * The interrupt handler will schedule a different
1006 		 * bh work to finish things up when the data transfer
1007 		 * is completely done.
1008 		 *
1009 		 * We may not complete the mmc request here anyway
1010 		 * because the mmc layer may call back and cause us to
1011 		 * violate the "don't submit new operations from the
1012 		 * completion callback" rule of the dma engine
1013 		 * framework.
1014 		 */
1015 		atmci_writel(host, ATMCI_IER, ATMCI_NOTBUSY);
1016 	}
1017 }
1018 
1019 /*
1020  * Returns a mask of interrupt flags to be enabled after the whole
1021  * request has been prepared.
1022  */
1023 static u32 atmci_prepare_data(struct atmel_mci *host, struct mmc_data *data)
1024 {
1025 	u32 iflags;
1026 
1027 	data->error = -EINPROGRESS;
1028 
1029 	host->sg = data->sg;
1030 	host->sg_len = data->sg_len;
1031 	host->data = data;
1032 	host->data_chan = NULL;
1033 
1034 	iflags = ATMCI_DATA_ERROR_FLAGS;
1035 
1036 	/*
1037 	 * Errata: MMC data write operation with less than 12
1038 	 * bytes is impossible.
1039 	 *
1040 	 * Errata: MCI Transmit Data Register (TDR) FIFO
1041 	 * corruption when length is not multiple of 4.
1042 	 */
1043 	if (data->blocks * data->blksz < 12
1044 			|| (data->blocks * data->blksz) & 3)
1045 		host->need_reset = true;
1046 
1047 	host->pio_offset = 0;
1048 	if (data->flags & MMC_DATA_READ)
1049 		iflags |= ATMCI_RXRDY;
1050 	else
1051 		iflags |= ATMCI_TXRDY;
1052 
1053 	return iflags;
1054 }
1055 
1056 /*
1057  * Set interrupt flags and set block length into the MCI mode register even
1058  * if this value is also accessible in the MCI block register. It seems to be
1059  * necessary before the High Speed MCI version. It also map sg and configure
1060  * PDC registers.
1061  */
1062 static u32
1063 atmci_prepare_data_pdc(struct atmel_mci *host, struct mmc_data *data)
1064 {
1065 	struct device *dev = host->dev;
1066 	u32 iflags, tmp;
1067 	int i;
1068 
1069 	data->error = -EINPROGRESS;
1070 
1071 	host->data = data;
1072 	host->sg = data->sg;
1073 	iflags = ATMCI_DATA_ERROR_FLAGS;
1074 
1075 	/* Enable pdc mode */
1076 	atmci_writel(host, ATMCI_MR, host->mode_reg | ATMCI_MR_PDCMODE);
1077 
1078 	if (data->flags & MMC_DATA_READ)
1079 		iflags |= ATMCI_ENDRX | ATMCI_RXBUFF;
1080 	else
1081 		iflags |= ATMCI_ENDTX | ATMCI_TXBUFE | ATMCI_BLKE;
1082 
1083 	/* Set BLKLEN */
1084 	tmp = atmci_readl(host, ATMCI_MR);
1085 	tmp &= 0x0000ffff;
1086 	tmp |= ATMCI_BLKLEN(data->blksz);
1087 	atmci_writel(host, ATMCI_MR, tmp);
1088 
1089 	/* Configure PDC */
1090 	host->data_size = data->blocks * data->blksz;
1091 	dma_map_sg(dev, data->sg, data->sg_len, mmc_get_dma_dir(data));
1092 
1093 	if ((!host->caps.has_rwproof)
1094 	    && (host->data->flags & MMC_DATA_WRITE)) {
1095 		sg_copy_to_buffer(host->data->sg, host->data->sg_len,
1096 		                  host->buffer, host->data_size);
1097 		if (host->caps.has_bad_data_ordering)
1098 			for (i = 0; i < host->data_size; i++)
1099 				host->buffer[i] = swab32(host->buffer[i]);
1100 	}
1101 
1102 	if (host->data_size)
1103 		atmci_pdc_set_both_buf(host, data->flags & MMC_DATA_READ ?
1104 				       XFER_RECEIVE : XFER_TRANSMIT);
1105 	return iflags;
1106 }
1107 
1108 static u32
1109 atmci_prepare_data_dma(struct atmel_mci *host, struct mmc_data *data)
1110 {
1111 	struct dma_chan			*chan;
1112 	struct dma_async_tx_descriptor	*desc;
1113 	struct scatterlist		*sg;
1114 	unsigned int			i;
1115 	enum dma_transfer_direction	slave_dirn;
1116 	unsigned int			sglen;
1117 	u32				maxburst;
1118 	u32 iflags;
1119 
1120 	data->error = -EINPROGRESS;
1121 
1122 	WARN_ON(host->data);
1123 	host->sg = NULL;
1124 	host->data = data;
1125 
1126 	iflags = ATMCI_DATA_ERROR_FLAGS;
1127 
1128 	/*
1129 	 * We don't do DMA on "complex" transfers, i.e. with
1130 	 * non-word-aligned buffers or lengths. Also, we don't bother
1131 	 * with all the DMA setup overhead for short transfers.
1132 	 */
1133 	if (data->blocks * data->blksz < ATMCI_DMA_THRESHOLD)
1134 		return atmci_prepare_data(host, data);
1135 	if (data->blksz & 3)
1136 		return atmci_prepare_data(host, data);
1137 
1138 	for_each_sg(data->sg, sg, data->sg_len, i) {
1139 		if (sg->offset & 3 || sg->length & 3)
1140 			return atmci_prepare_data(host, data);
1141 	}
1142 
1143 	/* If we don't have a channel, we can't do DMA */
1144 	if (!host->dma.chan)
1145 		return -ENODEV;
1146 
1147 	chan = host->dma.chan;
1148 	host->data_chan = chan;
1149 
1150 	if (data->flags & MMC_DATA_READ) {
1151 		host->dma_conf.direction = slave_dirn = DMA_DEV_TO_MEM;
1152 		maxburst = atmci_convert_chksize(host,
1153 						 host->dma_conf.src_maxburst);
1154 	} else {
1155 		host->dma_conf.direction = slave_dirn = DMA_MEM_TO_DEV;
1156 		maxburst = atmci_convert_chksize(host,
1157 						 host->dma_conf.dst_maxburst);
1158 	}
1159 
1160 	if (host->caps.has_dma_conf_reg)
1161 		atmci_writel(host, ATMCI_DMA, ATMCI_DMA_CHKSIZE(maxburst) |
1162 			ATMCI_DMAEN);
1163 
1164 	sglen = dma_map_sg(chan->device->dev, data->sg,
1165 			data->sg_len, mmc_get_dma_dir(data));
1166 
1167 	dmaengine_slave_config(chan, &host->dma_conf);
1168 	desc = dmaengine_prep_slave_sg(chan,
1169 			data->sg, sglen, slave_dirn,
1170 			DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
1171 	if (!desc)
1172 		goto unmap_exit;
1173 
1174 	host->dma.data_desc = desc;
1175 	desc->callback = atmci_dma_complete;
1176 	desc->callback_param = host;
1177 
1178 	return iflags;
1179 unmap_exit:
1180 	dma_unmap_sg(chan->device->dev, data->sg, data->sg_len,
1181 		     mmc_get_dma_dir(data));
1182 	return -ENOMEM;
1183 }
1184 
1185 static void
1186 atmci_submit_data(struct atmel_mci *host, struct mmc_data *data)
1187 {
1188 	return;
1189 }
1190 
1191 /*
1192  * Start PDC according to transfer direction.
1193  */
1194 static void
1195 atmci_submit_data_pdc(struct atmel_mci *host, struct mmc_data *data)
1196 {
1197 	if (data->flags & MMC_DATA_READ)
1198 		atmci_writel(host, ATMEL_PDC_PTCR, ATMEL_PDC_RXTEN);
1199 	else
1200 		atmci_writel(host, ATMEL_PDC_PTCR, ATMEL_PDC_TXTEN);
1201 }
1202 
1203 static void
1204 atmci_submit_data_dma(struct atmel_mci *host, struct mmc_data *data)
1205 {
1206 	struct dma_chan			*chan = host->data_chan;
1207 	struct dma_async_tx_descriptor	*desc = host->dma.data_desc;
1208 
1209 	if (chan) {
1210 		dmaengine_submit(desc);
1211 		dma_async_issue_pending(chan);
1212 	}
1213 }
1214 
1215 static void atmci_stop_transfer(struct atmel_mci *host)
1216 {
1217 	struct device *dev = host->dev;
1218 
1219 	dev_dbg(dev, "(%s) set pending xfer complete\n", __func__);
1220 	atmci_set_pending(host, EVENT_XFER_COMPLETE);
1221 	atmci_writel(host, ATMCI_IER, ATMCI_NOTBUSY);
1222 }
1223 
1224 /*
1225  * Stop data transfer because error(s) occurred.
1226  */
1227 static void atmci_stop_transfer_pdc(struct atmel_mci *host)
1228 {
1229 	atmci_writel(host, ATMEL_PDC_PTCR, ATMEL_PDC_RXTDIS | ATMEL_PDC_TXTDIS);
1230 }
1231 
1232 static void atmci_stop_transfer_dma(struct atmel_mci *host)
1233 {
1234 	struct dma_chan *chan = host->data_chan;
1235 	struct device *dev = host->dev;
1236 
1237 	if (chan) {
1238 		dmaengine_terminate_all(chan);
1239 		atmci_dma_cleanup(host);
1240 	} else {
1241 		/* Data transfer was stopped by the interrupt handler */
1242 		dev_dbg(dev, "(%s) set pending xfer complete\n", __func__);
1243 		atmci_set_pending(host, EVENT_XFER_COMPLETE);
1244 		atmci_writel(host, ATMCI_IER, ATMCI_NOTBUSY);
1245 	}
1246 }
1247 
1248 /*
1249  * Start a request: prepare data if needed, prepare the command and activate
1250  * interrupts.
1251  */
1252 static void atmci_start_request(struct atmel_mci *host,
1253 		struct atmel_mci_slot *slot)
1254 {
1255 	struct device		*dev = host->dev;
1256 	struct mmc_request	*mrq;
1257 	struct mmc_command	*cmd;
1258 	struct mmc_data		*data;
1259 	u32			iflags;
1260 	u32			cmdflags;
1261 
1262 	mrq = slot->mrq;
1263 	host->cur_slot = slot;
1264 	host->mrq = mrq;
1265 
1266 	host->pending_events = 0;
1267 	host->completed_events = 0;
1268 	host->cmd_status = 0;
1269 	host->data_status = 0;
1270 
1271 	dev_dbg(dev, "start request: cmd %u\n", mrq->cmd->opcode);
1272 
1273 	if (host->need_reset || host->caps.need_reset_after_xfer) {
1274 		iflags = atmci_readl(host, ATMCI_IMR);
1275 		iflags &= (ATMCI_SDIOIRQA | ATMCI_SDIOIRQB);
1276 		atmci_writel(host, ATMCI_CR, ATMCI_CR_SWRST);
1277 		atmci_writel(host, ATMCI_CR, ATMCI_CR_MCIEN);
1278 		atmci_writel(host, ATMCI_MR, host->mode_reg);
1279 		if (host->caps.has_cfg_reg)
1280 			atmci_writel(host, ATMCI_CFG, host->cfg_reg);
1281 		atmci_writel(host, ATMCI_IER, iflags);
1282 		host->need_reset = false;
1283 	}
1284 	atmci_writel(host, ATMCI_SDCR, slot->sdc_reg);
1285 
1286 	iflags = atmci_readl(host, ATMCI_IMR);
1287 	if (iflags & ~(ATMCI_SDIOIRQA | ATMCI_SDIOIRQB))
1288 		dev_dbg(&slot->mmc->class_dev, "WARNING: IMR=0x%08x\n",
1289 				iflags);
1290 
1291 	if (unlikely(test_and_clear_bit(ATMCI_CARD_NEED_INIT, &slot->flags))) {
1292 		/* Send init sequence (74 clock cycles) */
1293 		atmci_writel(host, ATMCI_CMDR, ATMCI_CMDR_SPCMD_INIT);
1294 		while (!(atmci_readl(host, ATMCI_SR) & ATMCI_CMDRDY))
1295 			cpu_relax();
1296 	}
1297 	iflags = 0;
1298 	data = mrq->data;
1299 	if (data) {
1300 		atmci_set_timeout(host, slot, data);
1301 
1302 		/* Must set block count/size before sending command */
1303 		atmci_writel(host, ATMCI_BLKR, ATMCI_BCNT(data->blocks)
1304 				| ATMCI_BLKLEN(data->blksz));
1305 		dev_vdbg(&slot->mmc->class_dev, "BLKR=0x%08x\n",
1306 			ATMCI_BCNT(data->blocks) | ATMCI_BLKLEN(data->blksz));
1307 
1308 		iflags |= host->prepare_data(host, data);
1309 	}
1310 
1311 	iflags |= ATMCI_CMDRDY;
1312 	cmd = mrq->cmd;
1313 	cmdflags = atmci_prepare_command(slot->mmc, cmd);
1314 
1315 	/*
1316 	 * DMA transfer should be started before sending the command to avoid
1317 	 * unexpected errors especially for read operations in SDIO mode.
1318 	 * Unfortunately, in PDC mode, command has to be sent before starting
1319 	 * the transfer.
1320 	 */
1321 	if (host->submit_data != &atmci_submit_data_dma)
1322 		atmci_send_command(host, cmd, cmdflags);
1323 
1324 	if (data)
1325 		host->submit_data(host, data);
1326 
1327 	if (host->submit_data == &atmci_submit_data_dma)
1328 		atmci_send_command(host, cmd, cmdflags);
1329 
1330 	if (mrq->stop) {
1331 		host->stop_cmdr = atmci_prepare_command(slot->mmc, mrq->stop);
1332 		host->stop_cmdr |= ATMCI_CMDR_STOP_XFER;
1333 		if (!(data->flags & MMC_DATA_WRITE))
1334 			host->stop_cmdr |= ATMCI_CMDR_TRDIR_READ;
1335 		host->stop_cmdr |= ATMCI_CMDR_MULTI_BLOCK;
1336 	}
1337 
1338 	/*
1339 	 * We could have enabled interrupts earlier, but I suspect
1340 	 * that would open up a nice can of interesting race
1341 	 * conditions (e.g. command and data complete, but stop not
1342 	 * prepared yet.)
1343 	 */
1344 	atmci_writel(host, ATMCI_IER, iflags);
1345 }
1346 
1347 static void atmci_queue_request(struct atmel_mci *host,
1348 		struct atmel_mci_slot *slot, struct mmc_request *mrq)
1349 {
1350 	struct device *dev = host->dev;
1351 
1352 	dev_vdbg(&slot->mmc->class_dev, "queue request: state=%d\n",
1353 			host->state);
1354 
1355 	spin_lock_bh(&host->lock);
1356 	slot->mrq = mrq;
1357 	if (host->state == STATE_IDLE) {
1358 		host->state = STATE_SENDING_CMD;
1359 		atmci_start_request(host, slot);
1360 	} else {
1361 		dev_dbg(dev, "queue request\n");
1362 		list_add_tail(&slot->queue_node, &host->queue);
1363 	}
1364 	spin_unlock_bh(&host->lock);
1365 }
1366 
1367 static void atmci_request(struct mmc_host *mmc, struct mmc_request *mrq)
1368 {
1369 	struct atmel_mci_slot	*slot = mmc_priv(mmc);
1370 	struct atmel_mci	*host = slot->host;
1371 	struct device		*dev = host->dev;
1372 	struct mmc_data		*data;
1373 
1374 	WARN_ON(slot->mrq);
1375 	dev_dbg(dev, "MRQ: cmd %u\n", mrq->cmd->opcode);
1376 
1377 	/*
1378 	 * We may "know" the card is gone even though there's still an
1379 	 * electrical connection. If so, we really need to communicate
1380 	 * this to the MMC core since there won't be any more
1381 	 * interrupts as the card is completely removed. Otherwise,
1382 	 * the MMC core might believe the card is still there even
1383 	 * though the card was just removed very slowly.
1384 	 */
1385 	if (!test_bit(ATMCI_CARD_PRESENT, &slot->flags)) {
1386 		mrq->cmd->error = -ENOMEDIUM;
1387 		mmc_request_done(mmc, mrq);
1388 		return;
1389 	}
1390 
1391 	/* We don't support multiple blocks of weird lengths. */
1392 	data = mrq->data;
1393 	if (data && data->blocks > 1 && data->blksz & 3) {
1394 		mrq->cmd->error = -EINVAL;
1395 		mmc_request_done(mmc, mrq);
1396 	}
1397 
1398 	atmci_queue_request(host, slot, mrq);
1399 }
1400 
1401 static void atmci_set_ios(struct mmc_host *mmc, struct mmc_ios *ios)
1402 {
1403 	struct atmel_mci_slot	*slot = mmc_priv(mmc);
1404 	struct atmel_mci	*host = slot->host;
1405 	unsigned int		i;
1406 
1407 	slot->sdc_reg &= ~ATMCI_SDCBUS_MASK;
1408 	switch (ios->bus_width) {
1409 	case MMC_BUS_WIDTH_1:
1410 		slot->sdc_reg |= ATMCI_SDCBUS_1BIT;
1411 		break;
1412 	case MMC_BUS_WIDTH_4:
1413 		slot->sdc_reg |= ATMCI_SDCBUS_4BIT;
1414 		break;
1415 	case MMC_BUS_WIDTH_8:
1416 		slot->sdc_reg |= ATMCI_SDCBUS_8BIT;
1417 		break;
1418 	}
1419 
1420 	if (ios->clock) {
1421 		unsigned int clock_min = ~0U;
1422 		int clkdiv;
1423 
1424 		spin_lock_bh(&host->lock);
1425 		if (!host->mode_reg) {
1426 			atmci_writel(host, ATMCI_CR, ATMCI_CR_SWRST);
1427 			atmci_writel(host, ATMCI_CR, ATMCI_CR_MCIEN);
1428 			if (host->caps.has_cfg_reg)
1429 				atmci_writel(host, ATMCI_CFG, host->cfg_reg);
1430 		}
1431 
1432 		/*
1433 		 * Use mirror of ios->clock to prevent race with mmc
1434 		 * core ios update when finding the minimum.
1435 		 */
1436 		slot->clock = ios->clock;
1437 		for (i = 0; i < ATMCI_MAX_NR_SLOTS; i++) {
1438 			if (host->slot[i] && host->slot[i]->clock
1439 					&& host->slot[i]->clock < clock_min)
1440 				clock_min = host->slot[i]->clock;
1441 		}
1442 
1443 		/* Calculate clock divider */
1444 		if (host->caps.has_odd_clk_div) {
1445 			clkdiv = DIV_ROUND_UP(host->bus_hz, clock_min) - 2;
1446 			if (clkdiv < 0) {
1447 				dev_warn(&mmc->class_dev,
1448 					 "clock %u too fast; using %lu\n",
1449 					 clock_min, host->bus_hz / 2);
1450 				clkdiv = 0;
1451 			} else if (clkdiv > 511) {
1452 				dev_warn(&mmc->class_dev,
1453 				         "clock %u too slow; using %lu\n",
1454 				         clock_min, host->bus_hz / (511 + 2));
1455 				clkdiv = 511;
1456 			}
1457 			host->mode_reg = ATMCI_MR_CLKDIV(clkdiv >> 1)
1458 			                 | ATMCI_MR_CLKODD(clkdiv & 1);
1459 		} else {
1460 			clkdiv = DIV_ROUND_UP(host->bus_hz, 2 * clock_min) - 1;
1461 			if (clkdiv > 255) {
1462 				dev_warn(&mmc->class_dev,
1463 				         "clock %u too slow; using %lu\n",
1464 				         clock_min, host->bus_hz / (2 * 256));
1465 				clkdiv = 255;
1466 			}
1467 			host->mode_reg = ATMCI_MR_CLKDIV(clkdiv);
1468 		}
1469 
1470 		/*
1471 		 * WRPROOF and RDPROOF prevent overruns/underruns by
1472 		 * stopping the clock when the FIFO is full/empty.
1473 		 * This state is not expected to last for long.
1474 		 */
1475 		if (host->caps.has_rwproof)
1476 			host->mode_reg |= (ATMCI_MR_WRPROOF | ATMCI_MR_RDPROOF);
1477 
1478 		if (host->caps.has_cfg_reg) {
1479 			/* setup High Speed mode in relation with card capacity */
1480 			if (ios->timing == MMC_TIMING_SD_HS)
1481 				host->cfg_reg |= ATMCI_CFG_HSMODE;
1482 			else
1483 				host->cfg_reg &= ~ATMCI_CFG_HSMODE;
1484 		}
1485 
1486 		if (list_empty(&host->queue)) {
1487 			atmci_writel(host, ATMCI_MR, host->mode_reg);
1488 			if (host->caps.has_cfg_reg)
1489 				atmci_writel(host, ATMCI_CFG, host->cfg_reg);
1490 		} else {
1491 			host->need_clock_update = true;
1492 		}
1493 
1494 		spin_unlock_bh(&host->lock);
1495 	} else {
1496 		bool any_slot_active = false;
1497 
1498 		spin_lock_bh(&host->lock);
1499 		slot->clock = 0;
1500 		for (i = 0; i < ATMCI_MAX_NR_SLOTS; i++) {
1501 			if (host->slot[i] && host->slot[i]->clock) {
1502 				any_slot_active = true;
1503 				break;
1504 			}
1505 		}
1506 		if (!any_slot_active) {
1507 			atmci_writel(host, ATMCI_CR, ATMCI_CR_MCIDIS);
1508 			if (host->mode_reg) {
1509 				atmci_readl(host, ATMCI_MR);
1510 			}
1511 			host->mode_reg = 0;
1512 		}
1513 		spin_unlock_bh(&host->lock);
1514 	}
1515 
1516 	switch (ios->power_mode) {
1517 	case MMC_POWER_OFF:
1518 		if (!IS_ERR(mmc->supply.vmmc))
1519 			mmc_regulator_set_ocr(mmc, mmc->supply.vmmc, 0);
1520 		break;
1521 	case MMC_POWER_UP:
1522 		set_bit(ATMCI_CARD_NEED_INIT, &slot->flags);
1523 		if (!IS_ERR(mmc->supply.vmmc))
1524 			mmc_regulator_set_ocr(mmc, mmc->supply.vmmc, ios->vdd);
1525 		break;
1526 	default:
1527 		break;
1528 	}
1529 }
1530 
1531 static int atmci_get_ro(struct mmc_host *mmc)
1532 {
1533 	int			read_only = -ENOSYS;
1534 	struct atmel_mci_slot	*slot = mmc_priv(mmc);
1535 
1536 	if (slot->wp_pin) {
1537 		read_only = gpiod_get_value(slot->wp_pin);
1538 		dev_dbg(&mmc->class_dev, "card is %s\n",
1539 				read_only ? "read-only" : "read-write");
1540 	}
1541 
1542 	return read_only;
1543 }
1544 
1545 static int atmci_get_cd(struct mmc_host *mmc)
1546 {
1547 	int			present = -ENOSYS;
1548 	struct atmel_mci_slot	*slot = mmc_priv(mmc);
1549 
1550 	if (slot->detect_pin) {
1551 		present = gpiod_get_value_cansleep(slot->detect_pin);
1552 		dev_dbg(&mmc->class_dev, "card is %spresent\n",
1553 				present ? "" : "not ");
1554 	}
1555 
1556 	return present;
1557 }
1558 
1559 static void atmci_enable_sdio_irq(struct mmc_host *mmc, int enable)
1560 {
1561 	struct atmel_mci_slot	*slot = mmc_priv(mmc);
1562 	struct atmel_mci	*host = slot->host;
1563 
1564 	if (enable)
1565 		atmci_writel(host, ATMCI_IER, slot->sdio_irq);
1566 	else
1567 		atmci_writel(host, ATMCI_IDR, slot->sdio_irq);
1568 }
1569 
1570 static const struct mmc_host_ops atmci_ops = {
1571 	.request	= atmci_request,
1572 	.set_ios	= atmci_set_ios,
1573 	.get_ro		= atmci_get_ro,
1574 	.get_cd		= atmci_get_cd,
1575 	.enable_sdio_irq = atmci_enable_sdio_irq,
1576 };
1577 
1578 /* Called with host->lock held */
1579 static void atmci_request_end(struct atmel_mci *host, struct mmc_request *mrq)
1580 	__releases(&host->lock)
1581 	__acquires(&host->lock)
1582 {
1583 	struct atmel_mci_slot	*slot = NULL;
1584 	struct mmc_host		*prev_mmc = host->cur_slot->mmc;
1585 	struct device		*dev = host->dev;
1586 
1587 	WARN_ON(host->cmd || host->data);
1588 
1589 	timer_delete(&host->timer);
1590 
1591 	/*
1592 	 * Update the MMC clock rate if necessary. This may be
1593 	 * necessary if set_ios() is called when a different slot is
1594 	 * busy transferring data.
1595 	 */
1596 	if (host->need_clock_update) {
1597 		atmci_writel(host, ATMCI_MR, host->mode_reg);
1598 		if (host->caps.has_cfg_reg)
1599 			atmci_writel(host, ATMCI_CFG, host->cfg_reg);
1600 	}
1601 
1602 	host->cur_slot->mrq = NULL;
1603 	host->mrq = NULL;
1604 	if (!list_empty(&host->queue)) {
1605 		slot = list_entry(host->queue.next,
1606 				struct atmel_mci_slot, queue_node);
1607 		list_del(&slot->queue_node);
1608 		dev_vdbg(dev, "list not empty: %s is next\n", mmc_hostname(slot->mmc));
1609 		host->state = STATE_SENDING_CMD;
1610 		atmci_start_request(host, slot);
1611 	} else {
1612 		dev_vdbg(dev, "list empty\n");
1613 		host->state = STATE_IDLE;
1614 	}
1615 
1616 	spin_unlock(&host->lock);
1617 	mmc_request_done(prev_mmc, mrq);
1618 	spin_lock(&host->lock);
1619 }
1620 
1621 static void atmci_command_complete(struct atmel_mci *host,
1622 			struct mmc_command *cmd)
1623 {
1624 	u32		status = host->cmd_status;
1625 
1626 	/* Read the response from the card (up to 16 bytes) */
1627 	cmd->resp[0] = atmci_readl(host, ATMCI_RSPR);
1628 	cmd->resp[1] = atmci_readl(host, ATMCI_RSPR);
1629 	cmd->resp[2] = atmci_readl(host, ATMCI_RSPR);
1630 	cmd->resp[3] = atmci_readl(host, ATMCI_RSPR);
1631 
1632 	if (status & ATMCI_RTOE)
1633 		cmd->error = -ETIMEDOUT;
1634 	else if ((cmd->flags & MMC_RSP_CRC) && (status & ATMCI_RCRCE))
1635 		cmd->error = -EILSEQ;
1636 	else if (status & (ATMCI_RINDE | ATMCI_RDIRE | ATMCI_RENDE))
1637 		cmd->error = -EIO;
1638 	else if (host->mrq->data && (host->mrq->data->blksz & 3)) {
1639 		if (host->caps.need_blksz_mul_4) {
1640 			cmd->error = -EINVAL;
1641 			host->need_reset = 1;
1642 		}
1643 	} else
1644 		cmd->error = 0;
1645 }
1646 
1647 static void atmci_detect_change(struct timer_list *t)
1648 {
1649 	struct atmel_mci_slot	*slot = timer_container_of(slot, t,
1650 								detect_timer);
1651 	bool			present;
1652 	bool			present_old;
1653 
1654 	/*
1655 	 * atmci_cleanup_slot() sets the ATMCI_SHUTDOWN flag before
1656 	 * freeing the interrupt. We must not re-enable the interrupt
1657 	 * if it has been freed, and if we're shutting down, it
1658 	 * doesn't really matter whether the card is present or not.
1659 	 */
1660 	smp_rmb();
1661 	if (test_bit(ATMCI_SHUTDOWN, &slot->flags))
1662 		return;
1663 
1664 	enable_irq(gpiod_to_irq(slot->detect_pin));
1665 	present = gpiod_get_value_cansleep(slot->detect_pin);
1666 	present_old = test_bit(ATMCI_CARD_PRESENT, &slot->flags);
1667 
1668 	dev_vdbg(&slot->mmc->class_dev, "detect change: %d (was %d)\n",
1669 			present, present_old);
1670 
1671 	if (present != present_old) {
1672 		struct atmel_mci	*host = slot->host;
1673 		struct mmc_request	*mrq;
1674 
1675 		dev_dbg(&slot->mmc->class_dev, "card %s\n",
1676 			present ? "inserted" : "removed");
1677 
1678 		spin_lock(&host->lock);
1679 
1680 		if (!present)
1681 			clear_bit(ATMCI_CARD_PRESENT, &slot->flags);
1682 		else
1683 			set_bit(ATMCI_CARD_PRESENT, &slot->flags);
1684 
1685 		/* Clean up queue if present */
1686 		mrq = slot->mrq;
1687 		if (mrq) {
1688 			if (mrq == host->mrq) {
1689 				/*
1690 				 * Reset controller to terminate any ongoing
1691 				 * commands or data transfers.
1692 				 */
1693 				atmci_writel(host, ATMCI_CR, ATMCI_CR_SWRST);
1694 				atmci_writel(host, ATMCI_CR, ATMCI_CR_MCIEN);
1695 				atmci_writel(host, ATMCI_MR, host->mode_reg);
1696 				if (host->caps.has_cfg_reg)
1697 					atmci_writel(host, ATMCI_CFG, host->cfg_reg);
1698 
1699 				host->data = NULL;
1700 				host->cmd = NULL;
1701 
1702 				switch (host->state) {
1703 				case STATE_IDLE:
1704 					break;
1705 				case STATE_SENDING_CMD:
1706 					mrq->cmd->error = -ENOMEDIUM;
1707 					if (mrq->data)
1708 						host->stop_transfer(host);
1709 					break;
1710 				case STATE_DATA_XFER:
1711 					mrq->data->error = -ENOMEDIUM;
1712 					host->stop_transfer(host);
1713 					break;
1714 				case STATE_WAITING_NOTBUSY:
1715 					mrq->data->error = -ENOMEDIUM;
1716 					break;
1717 				case STATE_SENDING_STOP:
1718 					mrq->stop->error = -ENOMEDIUM;
1719 					break;
1720 				case STATE_END_REQUEST:
1721 					break;
1722 				}
1723 
1724 				atmci_request_end(host, mrq);
1725 			} else {
1726 				list_del(&slot->queue_node);
1727 				mrq->cmd->error = -ENOMEDIUM;
1728 				if (mrq->data)
1729 					mrq->data->error = -ENOMEDIUM;
1730 				if (mrq->stop)
1731 					mrq->stop->error = -ENOMEDIUM;
1732 
1733 				spin_unlock(&host->lock);
1734 				mmc_request_done(slot->mmc, mrq);
1735 				spin_lock(&host->lock);
1736 			}
1737 		}
1738 		spin_unlock(&host->lock);
1739 
1740 		mmc_detect_change(slot->mmc, 0);
1741 	}
1742 }
1743 
1744 static void atmci_work_func(struct work_struct *t)
1745 {
1746 	struct atmel_mci        *host = from_work(host, t, bh_work);
1747 	struct mmc_request	*mrq = host->mrq;
1748 	struct mmc_data		*data = host->data;
1749 	struct device		*dev = host->dev;
1750 	enum atmel_mci_state	state = host->state;
1751 	enum atmel_mci_state	prev_state;
1752 	u32			status;
1753 
1754 	spin_lock(&host->lock);
1755 
1756 	state = host->state;
1757 
1758 	dev_vdbg(dev, "bh_work: state %u pending/completed/mask %lx/%lx/%x\n",
1759 		state, host->pending_events, host->completed_events,
1760 		atmci_readl(host, ATMCI_IMR));
1761 
1762 	do {
1763 		prev_state = state;
1764 		dev_dbg(dev, "FSM: state=%d\n", state);
1765 
1766 		switch (state) {
1767 		case STATE_IDLE:
1768 			break;
1769 
1770 		case STATE_SENDING_CMD:
1771 			/*
1772 			 * Command has been sent, we are waiting for command
1773 			 * ready. Then we have three next states possible:
1774 			 * END_REQUEST by default, WAITING_NOTBUSY if it's a
1775 			 * command needing it or DATA_XFER if there is data.
1776 			 */
1777 			dev_dbg(dev, "FSM: cmd ready?\n");
1778 			if (!atmci_test_and_clear_pending(host,
1779 						EVENT_CMD_RDY))
1780 				break;
1781 
1782 			dev_dbg(dev, "set completed cmd ready\n");
1783 			host->cmd = NULL;
1784 			atmci_set_completed(host, EVENT_CMD_RDY);
1785 			atmci_command_complete(host, mrq->cmd);
1786 			if (mrq->data) {
1787 				dev_dbg(dev, "command with data transfer\n");
1788 				/*
1789 				 * If there is a command error don't start
1790 				 * data transfer.
1791 				 */
1792 				if (mrq->cmd->error) {
1793 					host->stop_transfer(host);
1794 					host->data = NULL;
1795 					atmci_writel(host, ATMCI_IDR,
1796 					             ATMCI_TXRDY | ATMCI_RXRDY
1797 					             | ATMCI_DATA_ERROR_FLAGS);
1798 					state = STATE_END_REQUEST;
1799 				} else
1800 					state = STATE_DATA_XFER;
1801 			} else if ((!mrq->data) && (mrq->cmd->flags & MMC_RSP_BUSY)) {
1802 				dev_dbg(dev, "command response need waiting notbusy\n");
1803 				atmci_writel(host, ATMCI_IER, ATMCI_NOTBUSY);
1804 				state = STATE_WAITING_NOTBUSY;
1805 			} else
1806 				state = STATE_END_REQUEST;
1807 
1808 			break;
1809 
1810 		case STATE_DATA_XFER:
1811 			if (atmci_test_and_clear_pending(host,
1812 						EVENT_DATA_ERROR)) {
1813 				dev_dbg(dev, "set completed data error\n");
1814 				atmci_set_completed(host, EVENT_DATA_ERROR);
1815 				state = STATE_END_REQUEST;
1816 				break;
1817 			}
1818 
1819 			/*
1820 			 * A data transfer is in progress. The event expected
1821 			 * to move to the next state depends of data transfer
1822 			 * type (PDC or DMA). Once transfer done we can move
1823 			 * to the next step which is WAITING_NOTBUSY in write
1824 			 * case and directly SENDING_STOP in read case.
1825 			 */
1826 			dev_dbg(dev, "FSM: xfer complete?\n");
1827 			if (!atmci_test_and_clear_pending(host,
1828 						EVENT_XFER_COMPLETE))
1829 				break;
1830 
1831 			dev_dbg(dev, "(%s) set completed xfer complete\n", __func__);
1832 			atmci_set_completed(host, EVENT_XFER_COMPLETE);
1833 
1834 			if (host->caps.need_notbusy_for_read_ops ||
1835 			   (host->data->flags & MMC_DATA_WRITE)) {
1836 				atmci_writel(host, ATMCI_IER, ATMCI_NOTBUSY);
1837 				state = STATE_WAITING_NOTBUSY;
1838 			} else if (host->mrq->stop) {
1839 				atmci_send_stop_cmd(host, data);
1840 				state = STATE_SENDING_STOP;
1841 			} else {
1842 				host->data = NULL;
1843 				data->bytes_xfered = data->blocks * data->blksz;
1844 				data->error = 0;
1845 				state = STATE_END_REQUEST;
1846 			}
1847 			break;
1848 
1849 		case STATE_WAITING_NOTBUSY:
1850 			/*
1851 			 * We can be in the state for two reasons: a command
1852 			 * requiring waiting not busy signal (stop command
1853 			 * included) or a write operation. In the latest case,
1854 			 * we need to send a stop command.
1855 			 */
1856 			dev_dbg(dev, "FSM: not busy?\n");
1857 			if (!atmci_test_and_clear_pending(host,
1858 						EVENT_NOTBUSY))
1859 				break;
1860 
1861 			dev_dbg(dev, "set completed not busy\n");
1862 			atmci_set_completed(host, EVENT_NOTBUSY);
1863 
1864 			if (host->data) {
1865 				/*
1866 				 * For some commands such as CMD53, even if
1867 				 * there is data transfer, there is no stop
1868 				 * command to send.
1869 				 */
1870 				if (host->mrq->stop) {
1871 					atmci_send_stop_cmd(host, data);
1872 					state = STATE_SENDING_STOP;
1873 				} else {
1874 					host->data = NULL;
1875 					data->bytes_xfered = data->blocks
1876 					                     * data->blksz;
1877 					data->error = 0;
1878 					state = STATE_END_REQUEST;
1879 				}
1880 			} else
1881 				state = STATE_END_REQUEST;
1882 			break;
1883 
1884 		case STATE_SENDING_STOP:
1885 			/*
1886 			 * In this state, it is important to set host->data to
1887 			 * NULL (which is tested in the waiting notbusy state)
1888 			 * in order to go to the end request state instead of
1889 			 * sending stop again.
1890 			 */
1891 			dev_dbg(dev, "FSM: cmd ready?\n");
1892 			if (!atmci_test_and_clear_pending(host,
1893 						EVENT_CMD_RDY))
1894 				break;
1895 
1896 			dev_dbg(dev, "FSM: cmd ready\n");
1897 			host->cmd = NULL;
1898 			data->bytes_xfered = data->blocks * data->blksz;
1899 			data->error = 0;
1900 			atmci_command_complete(host, mrq->stop);
1901 			if (mrq->stop->error) {
1902 				host->stop_transfer(host);
1903 				atmci_writel(host, ATMCI_IDR,
1904 				             ATMCI_TXRDY | ATMCI_RXRDY
1905 				             | ATMCI_DATA_ERROR_FLAGS);
1906 				state = STATE_END_REQUEST;
1907 			} else {
1908 				atmci_writel(host, ATMCI_IER, ATMCI_NOTBUSY);
1909 				state = STATE_WAITING_NOTBUSY;
1910 			}
1911 			host->data = NULL;
1912 			break;
1913 
1914 		case STATE_END_REQUEST:
1915 			atmci_writel(host, ATMCI_IDR, ATMCI_TXRDY | ATMCI_RXRDY
1916 			                   | ATMCI_DATA_ERROR_FLAGS);
1917 			status = host->data_status;
1918 			if (unlikely(status)) {
1919 				host->stop_transfer(host);
1920 				host->data = NULL;
1921 				if (data) {
1922 					if (status & ATMCI_DTOE) {
1923 						data->error = -ETIMEDOUT;
1924 					} else if (status & ATMCI_DCRCE) {
1925 						data->error = -EILSEQ;
1926 					} else {
1927 						data->error = -EIO;
1928 					}
1929 				}
1930 			}
1931 
1932 			atmci_request_end(host, host->mrq);
1933 			goto unlock; /* atmci_request_end() sets host->state */
1934 			break;
1935 		}
1936 	} while (state != prev_state);
1937 
1938 	host->state = state;
1939 
1940 unlock:
1941 	spin_unlock(&host->lock);
1942 }
1943 
1944 static void atmci_read_data_pio(struct atmel_mci *host)
1945 {
1946 	struct scatterlist	*sg = host->sg;
1947 	unsigned int		offset = host->pio_offset;
1948 	struct mmc_data		*data = host->data;
1949 	u32			value;
1950 	u32			status;
1951 	unsigned int		nbytes = 0;
1952 
1953 	do {
1954 		value = atmci_readl(host, ATMCI_RDR);
1955 		if (likely(offset + 4 <= sg->length)) {
1956 			sg_pcopy_from_buffer(sg, 1, &value, sizeof(u32), offset);
1957 
1958 			offset += 4;
1959 			nbytes += 4;
1960 
1961 			if (offset == sg->length) {
1962 				flush_dcache_page(sg_page(sg));
1963 				host->sg = sg = sg_next(sg);
1964 				host->sg_len--;
1965 				if (!sg || !host->sg_len)
1966 					goto done;
1967 
1968 				offset = 0;
1969 			}
1970 		} else {
1971 			unsigned int remaining = sg->length - offset;
1972 
1973 			sg_pcopy_from_buffer(sg, 1, &value, remaining, offset);
1974 			nbytes += remaining;
1975 
1976 			flush_dcache_page(sg_page(sg));
1977 			host->sg = sg = sg_next(sg);
1978 			host->sg_len--;
1979 			if (!sg || !host->sg_len)
1980 				goto done;
1981 
1982 			offset = 4 - remaining;
1983 			sg_pcopy_from_buffer(sg, 1, (u8 *)&value + remaining,
1984 					offset, 0);
1985 			nbytes += offset;
1986 		}
1987 
1988 		status = atmci_readl(host, ATMCI_SR);
1989 		if (status & ATMCI_DATA_ERROR_FLAGS) {
1990 			atmci_writel(host, ATMCI_IDR, (ATMCI_NOTBUSY | ATMCI_RXRDY
1991 						| ATMCI_DATA_ERROR_FLAGS));
1992 			host->data_status = status;
1993 			data->bytes_xfered += nbytes;
1994 			return;
1995 		}
1996 	} while (status & ATMCI_RXRDY);
1997 
1998 	host->pio_offset = offset;
1999 	data->bytes_xfered += nbytes;
2000 
2001 	return;
2002 
2003 done:
2004 	atmci_writel(host, ATMCI_IDR, ATMCI_RXRDY);
2005 	atmci_writel(host, ATMCI_IER, ATMCI_NOTBUSY);
2006 	data->bytes_xfered += nbytes;
2007 	smp_wmb();
2008 	atmci_set_pending(host, EVENT_XFER_COMPLETE);
2009 }
2010 
2011 static void atmci_write_data_pio(struct atmel_mci *host)
2012 {
2013 	struct scatterlist	*sg = host->sg;
2014 	unsigned int		offset = host->pio_offset;
2015 	struct mmc_data		*data = host->data;
2016 	u32			value;
2017 	u32			status;
2018 	unsigned int		nbytes = 0;
2019 
2020 	do {
2021 		if (likely(offset + 4 <= sg->length)) {
2022 			sg_pcopy_to_buffer(sg, 1, &value, sizeof(u32), offset);
2023 			atmci_writel(host, ATMCI_TDR, value);
2024 
2025 			offset += 4;
2026 			nbytes += 4;
2027 			if (offset == sg->length) {
2028 				host->sg = sg = sg_next(sg);
2029 				host->sg_len--;
2030 				if (!sg || !host->sg_len)
2031 					goto done;
2032 
2033 				offset = 0;
2034 			}
2035 		} else {
2036 			unsigned int remaining = sg->length - offset;
2037 
2038 			value = 0;
2039 			sg_pcopy_to_buffer(sg, 1, &value, remaining, offset);
2040 			nbytes += remaining;
2041 
2042 			host->sg = sg = sg_next(sg);
2043 			host->sg_len--;
2044 			if (!sg || !host->sg_len) {
2045 				atmci_writel(host, ATMCI_TDR, value);
2046 				goto done;
2047 			}
2048 
2049 			offset = 4 - remaining;
2050 			sg_pcopy_to_buffer(sg, 1, (u8 *)&value + remaining,
2051 					offset, 0);
2052 			atmci_writel(host, ATMCI_TDR, value);
2053 			nbytes += offset;
2054 		}
2055 
2056 		status = atmci_readl(host, ATMCI_SR);
2057 		if (status & ATMCI_DATA_ERROR_FLAGS) {
2058 			atmci_writel(host, ATMCI_IDR, (ATMCI_NOTBUSY | ATMCI_TXRDY
2059 						| ATMCI_DATA_ERROR_FLAGS));
2060 			host->data_status = status;
2061 			data->bytes_xfered += nbytes;
2062 			return;
2063 		}
2064 	} while (status & ATMCI_TXRDY);
2065 
2066 	host->pio_offset = offset;
2067 	data->bytes_xfered += nbytes;
2068 
2069 	return;
2070 
2071 done:
2072 	atmci_writel(host, ATMCI_IDR, ATMCI_TXRDY);
2073 	atmci_writel(host, ATMCI_IER, ATMCI_NOTBUSY);
2074 	data->bytes_xfered += nbytes;
2075 	smp_wmb();
2076 	atmci_set_pending(host, EVENT_XFER_COMPLETE);
2077 }
2078 
2079 static void atmci_sdio_interrupt(struct atmel_mci *host, u32 status)
2080 {
2081 	int	i;
2082 
2083 	for (i = 0; i < ATMCI_MAX_NR_SLOTS; i++) {
2084 		struct atmel_mci_slot *slot = host->slot[i];
2085 		if (slot && (status & slot->sdio_irq)) {
2086 			mmc_signal_sdio_irq(slot->mmc);
2087 		}
2088 	}
2089 }
2090 
2091 
2092 static irqreturn_t atmci_interrupt(int irq, void *dev_id)
2093 {
2094 	struct atmel_mci	*host = dev_id;
2095 	struct device		*dev = host->dev;
2096 	u32			status, mask, pending;
2097 	unsigned int		pass_count = 0;
2098 
2099 	do {
2100 		status = atmci_readl(host, ATMCI_SR);
2101 		mask = atmci_readl(host, ATMCI_IMR);
2102 		pending = status & mask;
2103 		if (!pending)
2104 			break;
2105 
2106 		if (pending & ATMCI_DATA_ERROR_FLAGS) {
2107 			dev_dbg(dev, "IRQ: data error\n");
2108 			atmci_writel(host, ATMCI_IDR, ATMCI_DATA_ERROR_FLAGS
2109 					| ATMCI_RXRDY | ATMCI_TXRDY
2110 					| ATMCI_ENDRX | ATMCI_ENDTX
2111 					| ATMCI_RXBUFF | ATMCI_TXBUFE);
2112 
2113 			host->data_status = status;
2114 			dev_dbg(dev, "set pending data error\n");
2115 			smp_wmb();
2116 			atmci_set_pending(host, EVENT_DATA_ERROR);
2117 			queue_work(system_bh_wq, &host->bh_work);
2118 		}
2119 
2120 		if (pending & ATMCI_TXBUFE) {
2121 			dev_dbg(dev, "IRQ: tx buffer empty\n");
2122 			atmci_writel(host, ATMCI_IDR, ATMCI_TXBUFE);
2123 			atmci_writel(host, ATMCI_IDR, ATMCI_ENDTX);
2124 			/*
2125 			 * We can receive this interruption before having configured
2126 			 * the second pdc buffer, so we need to reconfigure first and
2127 			 * second buffers again
2128 			 */
2129 			if (host->data_size) {
2130 				atmci_pdc_set_both_buf(host, XFER_TRANSMIT);
2131 				atmci_writel(host, ATMCI_IER, ATMCI_ENDTX);
2132 				atmci_writel(host, ATMCI_IER, ATMCI_TXBUFE);
2133 			} else {
2134 				atmci_pdc_complete(host);
2135 			}
2136 		} else if (pending & ATMCI_ENDTX) {
2137 			dev_dbg(dev, "IRQ: end of tx buffer\n");
2138 			atmci_writel(host, ATMCI_IDR, ATMCI_ENDTX);
2139 
2140 			if (host->data_size) {
2141 				atmci_pdc_set_single_buf(host,
2142 						XFER_TRANSMIT, PDC_SECOND_BUF);
2143 				atmci_writel(host, ATMCI_IER, ATMCI_ENDTX);
2144 			}
2145 		}
2146 
2147 		if (pending & ATMCI_RXBUFF) {
2148 			dev_dbg(dev, "IRQ: rx buffer full\n");
2149 			atmci_writel(host, ATMCI_IDR, ATMCI_RXBUFF);
2150 			atmci_writel(host, ATMCI_IDR, ATMCI_ENDRX);
2151 			/*
2152 			 * We can receive this interruption before having configured
2153 			 * the second pdc buffer, so we need to reconfigure first and
2154 			 * second buffers again
2155 			 */
2156 			if (host->data_size) {
2157 				atmci_pdc_set_both_buf(host, XFER_RECEIVE);
2158 				atmci_writel(host, ATMCI_IER, ATMCI_ENDRX);
2159 				atmci_writel(host, ATMCI_IER, ATMCI_RXBUFF);
2160 			} else {
2161 				atmci_pdc_complete(host);
2162 			}
2163 		} else if (pending & ATMCI_ENDRX) {
2164 			dev_dbg(dev, "IRQ: end of rx buffer\n");
2165 			atmci_writel(host, ATMCI_IDR, ATMCI_ENDRX);
2166 
2167 			if (host->data_size) {
2168 				atmci_pdc_set_single_buf(host,
2169 						XFER_RECEIVE, PDC_SECOND_BUF);
2170 				atmci_writel(host, ATMCI_IER, ATMCI_ENDRX);
2171 			}
2172 		}
2173 
2174 		/*
2175 		 * First mci IPs, so mainly the ones having pdc, have some
2176 		 * issues with the notbusy signal. You can't get it after
2177 		 * data transmission if you have not sent a stop command.
2178 		 * The appropriate workaround is to use the BLKE signal.
2179 		 */
2180 		if (pending & ATMCI_BLKE) {
2181 			dev_dbg(dev, "IRQ: blke\n");
2182 			atmci_writel(host, ATMCI_IDR, ATMCI_BLKE);
2183 			smp_wmb();
2184 			dev_dbg(dev, "set pending notbusy\n");
2185 			atmci_set_pending(host, EVENT_NOTBUSY);
2186 			queue_work(system_bh_wq, &host->bh_work);
2187 		}
2188 
2189 		if (pending & ATMCI_NOTBUSY) {
2190 			dev_dbg(dev, "IRQ: not_busy\n");
2191 			atmci_writel(host, ATMCI_IDR, ATMCI_NOTBUSY);
2192 			smp_wmb();
2193 			dev_dbg(dev, "set pending notbusy\n");
2194 			atmci_set_pending(host, EVENT_NOTBUSY);
2195 			queue_work(system_bh_wq, &host->bh_work);
2196 		}
2197 
2198 		if (pending & ATMCI_RXRDY)
2199 			atmci_read_data_pio(host);
2200 		if (pending & ATMCI_TXRDY)
2201 			atmci_write_data_pio(host);
2202 
2203 		if (pending & ATMCI_CMDRDY) {
2204 			dev_dbg(dev, "IRQ: cmd ready\n");
2205 			atmci_writel(host, ATMCI_IDR, ATMCI_CMDRDY);
2206 			host->cmd_status = status;
2207 			smp_wmb();
2208 			dev_dbg(dev, "set pending cmd rdy\n");
2209 			atmci_set_pending(host, EVENT_CMD_RDY);
2210 			queue_work(system_bh_wq, &host->bh_work);
2211 		}
2212 
2213 		if (pending & (ATMCI_SDIOIRQA | ATMCI_SDIOIRQB))
2214 			atmci_sdio_interrupt(host, status);
2215 
2216 	} while (pass_count++ < 5);
2217 
2218 	return pass_count ? IRQ_HANDLED : IRQ_NONE;
2219 }
2220 
2221 static irqreturn_t atmci_detect_interrupt(int irq, void *dev_id)
2222 {
2223 	struct atmel_mci_slot	*slot = dev_id;
2224 
2225 	/*
2226 	 * Disable interrupts until the pin has stabilized and check
2227 	 * the state then. Use mod_timer() since we may be in the
2228 	 * middle of the timer routine when this interrupt triggers.
2229 	 */
2230 	disable_irq_nosync(irq);
2231 	mod_timer(&slot->detect_timer, jiffies + msecs_to_jiffies(20));
2232 
2233 	return IRQ_HANDLED;
2234 }
2235 
2236 static int atmci_init_slot(struct atmel_mci *host,
2237 		struct mci_slot_pdata *slot_data, unsigned int id,
2238 		u32 sdc_reg, u32 sdio_irq)
2239 {
2240 	struct device			*dev = host->dev;
2241 	struct mmc_host			*mmc;
2242 	struct atmel_mci_slot		*slot;
2243 	int ret;
2244 
2245 	mmc = devm_mmc_alloc_host(dev, sizeof(*slot));
2246 	if (!mmc)
2247 		return -ENOMEM;
2248 
2249 	slot = mmc_priv(mmc);
2250 	slot->mmc = mmc;
2251 	slot->host = host;
2252 	slot->detect_pin = slot_data->detect_pin;
2253 	slot->wp_pin = slot_data->wp_pin;
2254 	slot->sdc_reg = sdc_reg;
2255 	slot->sdio_irq = sdio_irq;
2256 
2257 	dev_dbg(&mmc->class_dev,
2258 	        "slot[%u]: bus_width=%u, detect_pin=%d, "
2259 		"detect_is_active_high=%s, wp_pin=%d\n",
2260 		id, slot_data->bus_width, desc_to_gpio(slot_data->detect_pin),
2261 		str_true_false(!gpiod_is_active_low(slot_data->detect_pin)),
2262 		desc_to_gpio(slot_data->wp_pin));
2263 
2264 	mmc->ops = &atmci_ops;
2265 	mmc->f_min = DIV_ROUND_UP(host->bus_hz, 512);
2266 	mmc->f_max = host->bus_hz / 2;
2267 	mmc->ocr_avail	= MMC_VDD_32_33 | MMC_VDD_33_34;
2268 	if (sdio_irq)
2269 		mmc->caps |= MMC_CAP_SDIO_IRQ;
2270 	if (host->caps.has_highspeed)
2271 		mmc->caps |= MMC_CAP_SD_HIGHSPEED;
2272 	/*
2273 	 * Without the read/write proof capability, it is strongly suggested to
2274 	 * use only one bit for data to prevent fifo underruns and overruns
2275 	 * which will corrupt data.
2276 	 */
2277 	if ((slot_data->bus_width >= 4) && host->caps.has_rwproof) {
2278 		mmc->caps |= MMC_CAP_4_BIT_DATA;
2279 		if (slot_data->bus_width >= 8)
2280 			mmc->caps |= MMC_CAP_8_BIT_DATA;
2281 	}
2282 
2283 	if (atmci_get_version(host) < 0x200) {
2284 		mmc->max_segs = 256;
2285 		mmc->max_blk_size = 4095;
2286 		mmc->max_blk_count = 256;
2287 		mmc->max_req_size = mmc->max_blk_size * mmc->max_blk_count;
2288 		mmc->max_seg_size = mmc->max_blk_size * mmc->max_segs;
2289 	} else {
2290 		mmc->max_segs = 64;
2291 		mmc->max_req_size = 32768 * 512;
2292 		mmc->max_blk_size = 32768;
2293 		mmc->max_blk_count = 512;
2294 	}
2295 
2296 	/* Assume card is present initially */
2297 	set_bit(ATMCI_CARD_PRESENT, &slot->flags);
2298 	if (slot->detect_pin) {
2299 		if (!gpiod_get_value_cansleep(slot->detect_pin))
2300 			clear_bit(ATMCI_CARD_PRESENT, &slot->flags);
2301 	} else {
2302 		dev_dbg(&mmc->class_dev, "no detect pin available\n");
2303 	}
2304 
2305 	if (!slot->detect_pin) {
2306 		if (slot_data->non_removable)
2307 			mmc->caps |= MMC_CAP_NONREMOVABLE;
2308 		else
2309 			mmc->caps |= MMC_CAP_NEEDS_POLL;
2310 	}
2311 
2312 	if (!slot->wp_pin)
2313 		dev_dbg(&mmc->class_dev, "no WP pin available\n");
2314 
2315 	host->slot[id] = slot;
2316 	mmc_regulator_get_supply(mmc);
2317 	ret = mmc_add_host(mmc);
2318 	if (ret)
2319 		return ret;
2320 
2321 	if (slot->detect_pin) {
2322 		timer_setup(&slot->detect_timer, atmci_detect_change, 0);
2323 
2324 		ret = request_irq(gpiod_to_irq(slot->detect_pin),
2325 				  atmci_detect_interrupt,
2326 				  IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING,
2327 				  "mmc-detect", slot);
2328 		if (ret) {
2329 			dev_dbg(&mmc->class_dev,
2330 				"could not request IRQ %d for detect pin\n",
2331 				gpiod_to_irq(slot->detect_pin));
2332 			slot->detect_pin = NULL;
2333 		}
2334 	}
2335 
2336 	atmci_init_debugfs(slot);
2337 
2338 	return 0;
2339 }
2340 
2341 static void atmci_cleanup_slot(struct atmel_mci_slot *slot,
2342 		unsigned int id)
2343 {
2344 	/* Debugfs stuff is cleaned up by mmc core */
2345 
2346 	set_bit(ATMCI_SHUTDOWN, &slot->flags);
2347 	smp_wmb();
2348 
2349 	mmc_remove_host(slot->mmc);
2350 
2351 	if (slot->detect_pin) {
2352 		free_irq(gpiod_to_irq(slot->detect_pin), slot);
2353 		timer_delete_sync(&slot->detect_timer);
2354 	}
2355 
2356 	slot->host->slot[id] = NULL;
2357 }
2358 
2359 static int atmci_configure_dma(struct atmel_mci *host)
2360 {
2361 	struct device *dev = host->dev;
2362 
2363 	host->dma.chan = dma_request_chan(dev, "rxtx");
2364 	if (IS_ERR(host->dma.chan))
2365 		return PTR_ERR(host->dma.chan);
2366 
2367 	dev_info(dev, "using %s for DMA transfers\n", dma_chan_name(host->dma.chan));
2368 
2369 	host->dma_conf.src_addr = host->mapbase + ATMCI_RDR;
2370 	host->dma_conf.src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
2371 	host->dma_conf.src_maxburst = 1;
2372 	host->dma_conf.dst_addr = host->mapbase + ATMCI_TDR;
2373 	host->dma_conf.dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
2374 	host->dma_conf.dst_maxburst = 1;
2375 	host->dma_conf.device_fc = false;
2376 
2377 	return 0;
2378 }
2379 
2380 /*
2381  * HSMCI (High Speed MCI) module is not fully compatible with MCI module.
2382  * HSMCI provides DMA support and a new config register but no more supports
2383  * PDC.
2384  */
2385 static void atmci_get_cap(struct atmel_mci *host)
2386 {
2387 	struct device *dev = host->dev;
2388 	unsigned int version;
2389 
2390 	version = atmci_get_version(host);
2391 	dev_info(dev, "version: 0x%x\n", version);
2392 
2393 	host->caps.has_dma_conf_reg = false;
2394 	host->caps.has_pdc = true;
2395 	host->caps.has_cfg_reg = false;
2396 	host->caps.has_cstor_reg = false;
2397 	host->caps.has_highspeed = false;
2398 	host->caps.has_rwproof = false;
2399 	host->caps.has_odd_clk_div = false;
2400 	host->caps.has_bad_data_ordering = true;
2401 	host->caps.need_reset_after_xfer = true;
2402 	host->caps.need_blksz_mul_4 = true;
2403 	host->caps.need_notbusy_for_read_ops = false;
2404 
2405 	/* keep only major version number */
2406 	switch (version & 0xf00) {
2407 	case 0x600:
2408 	case 0x500:
2409 		host->caps.has_odd_clk_div = true;
2410 		fallthrough;
2411 	case 0x400:
2412 	case 0x300:
2413 		host->caps.has_dma_conf_reg = true;
2414 		host->caps.has_pdc = false;
2415 		host->caps.has_cfg_reg = true;
2416 		host->caps.has_cstor_reg = true;
2417 		host->caps.has_highspeed = true;
2418 		fallthrough;
2419 	case 0x200:
2420 		host->caps.has_rwproof = true;
2421 		host->caps.need_blksz_mul_4 = false;
2422 		host->caps.need_notbusy_for_read_ops = true;
2423 		fallthrough;
2424 	case 0x100:
2425 		host->caps.has_bad_data_ordering = false;
2426 		host->caps.need_reset_after_xfer = false;
2427 		fallthrough;
2428 	case 0x0:
2429 		break;
2430 	default:
2431 		host->caps.has_pdc = false;
2432 		dev_warn(dev, "Unmanaged mci version, set minimum capabilities\n");
2433 		break;
2434 	}
2435 }
2436 
2437 static int atmci_probe(struct platform_device *pdev)
2438 {
2439 	struct device			*dev = &pdev->dev;
2440 	struct atmel_mci		*host;
2441 	struct resource			*regs;
2442 	unsigned int			nr_slots;
2443 	int				irq;
2444 	int				ret, i;
2445 
2446 	regs = platform_get_resource(pdev, IORESOURCE_MEM, 0);
2447 	if (!regs)
2448 		return -ENXIO;
2449 
2450 	irq = platform_get_irq(pdev, 0);
2451 	if (irq < 0)
2452 		return irq;
2453 
2454 	host = devm_kzalloc(dev, sizeof(*host), GFP_KERNEL);
2455 	if (!host)
2456 		return -ENOMEM;
2457 
2458 	host->dev = dev;
2459 	spin_lock_init(&host->lock);
2460 	INIT_LIST_HEAD(&host->queue);
2461 
2462 	ret = atmci_of_init(host);
2463 	if (ret)
2464 		return dev_err_probe(dev, ret, "Slot information not available\n");
2465 
2466 	host->mck = devm_clk_get(dev, "mci_clk");
2467 	if (IS_ERR(host->mck))
2468 		return PTR_ERR(host->mck);
2469 
2470 	host->regs = devm_ioremap(dev, regs->start, resource_size(regs));
2471 	if (!host->regs)
2472 		return -ENOMEM;
2473 
2474 	ret = clk_prepare_enable(host->mck);
2475 	if (ret)
2476 		return ret;
2477 
2478 	atmci_writel(host, ATMCI_CR, ATMCI_CR_SWRST);
2479 	host->bus_hz = clk_get_rate(host->mck);
2480 
2481 	host->mapbase = regs->start;
2482 
2483 	INIT_WORK(&host->bh_work, atmci_work_func);
2484 
2485 	ret = request_irq(irq, atmci_interrupt, 0, dev_name(dev), host);
2486 	if (ret) {
2487 		clk_disable_unprepare(host->mck);
2488 		return ret;
2489 	}
2490 
2491 	/* Get MCI capabilities and set operations according to it */
2492 	atmci_get_cap(host);
2493 	ret = atmci_configure_dma(host);
2494 	if (ret == -EPROBE_DEFER) {
2495 		clk_disable_unprepare(host->mck);
2496 		goto err_dma_probe_defer;
2497 	}
2498 	if (ret == 0) {
2499 		host->prepare_data = &atmci_prepare_data_dma;
2500 		host->submit_data = &atmci_submit_data_dma;
2501 		host->stop_transfer = &atmci_stop_transfer_dma;
2502 	} else if (host->caps.has_pdc) {
2503 		dev_info(dev, "using PDC\n");
2504 		host->prepare_data = &atmci_prepare_data_pdc;
2505 		host->submit_data = &atmci_submit_data_pdc;
2506 		host->stop_transfer = &atmci_stop_transfer_pdc;
2507 	} else {
2508 		dev_info(dev, "using PIO\n");
2509 		host->prepare_data = &atmci_prepare_data;
2510 		host->submit_data = &atmci_submit_data;
2511 		host->stop_transfer = &atmci_stop_transfer;
2512 	}
2513 
2514 	platform_set_drvdata(pdev, host);
2515 
2516 	timer_setup(&host->timer, atmci_timeout_timer, 0);
2517 
2518 	pm_runtime_get_noresume(dev);
2519 	pm_runtime_set_active(dev);
2520 	pm_runtime_set_autosuspend_delay(dev, AUTOSUSPEND_DELAY);
2521 	pm_runtime_use_autosuspend(dev);
2522 	pm_runtime_enable(dev);
2523 
2524 	/* We need at least one slot to succeed */
2525 	nr_slots = 0;
2526 	ret = -ENODEV;
2527 	if (host->pdata[0].bus_width) {
2528 		ret = atmci_init_slot(host, &host->pdata[0],
2529 				0, ATMCI_SDCSEL_SLOT_A, ATMCI_SDIOIRQA);
2530 		if (!ret) {
2531 			nr_slots++;
2532 			host->buf_size = host->slot[0]->mmc->max_req_size;
2533 		}
2534 	}
2535 	if (host->pdata[1].bus_width) {
2536 		ret = atmci_init_slot(host, &host->pdata[1],
2537 				1, ATMCI_SDCSEL_SLOT_B, ATMCI_SDIOIRQB);
2538 		if (!ret) {
2539 			nr_slots++;
2540 			if (host->slot[1]->mmc->max_req_size > host->buf_size)
2541 				host->buf_size =
2542 					host->slot[1]->mmc->max_req_size;
2543 		}
2544 	}
2545 
2546 	if (!nr_slots) {
2547 		dev_err_probe(dev, ret, "init failed: no slot defined\n");
2548 		goto err_init_slot;
2549 	}
2550 
2551 	if (!host->caps.has_rwproof) {
2552 		host->buffer = dma_alloc_coherent(dev, host->buf_size,
2553 		                                  &host->buf_phys_addr,
2554 						  GFP_KERNEL);
2555 		if (!host->buffer) {
2556 			ret = dev_err_probe(dev, -ENOMEM, "buffer allocation failed\n");
2557 			goto err_dma_alloc;
2558 		}
2559 	}
2560 
2561 	dev_info(dev, "Atmel MCI controller at 0x%08lx irq %d, %u slots\n",
2562 		 host->mapbase, irq, nr_slots);
2563 
2564 	pm_runtime_put_autosuspend(dev);
2565 
2566 	return 0;
2567 
2568 err_dma_alloc:
2569 	for (i = 0; i < ATMCI_MAX_NR_SLOTS; i++) {
2570 		if (host->slot[i])
2571 			atmci_cleanup_slot(host->slot[i], i);
2572 	}
2573 err_init_slot:
2574 	clk_disable_unprepare(host->mck);
2575 
2576 	pm_runtime_disable(dev);
2577 	pm_runtime_put_noidle(dev);
2578 
2579 	timer_delete_sync(&host->timer);
2580 	if (!IS_ERR(host->dma.chan))
2581 		dma_release_channel(host->dma.chan);
2582 err_dma_probe_defer:
2583 	free_irq(irq, host);
2584 	return ret;
2585 }
2586 
2587 static void atmci_remove(struct platform_device *pdev)
2588 {
2589 	struct atmel_mci	*host = platform_get_drvdata(pdev);
2590 	struct device		*dev = &pdev->dev;
2591 	unsigned int		i;
2592 
2593 	pm_runtime_get_sync(dev);
2594 
2595 	if (host->buffer)
2596 		dma_free_coherent(dev, host->buf_size, host->buffer, host->buf_phys_addr);
2597 
2598 	for (i = 0; i < ATMCI_MAX_NR_SLOTS; i++) {
2599 		if (host->slot[i])
2600 			atmci_cleanup_slot(host->slot[i], i);
2601 	}
2602 
2603 	atmci_writel(host, ATMCI_IDR, ~0UL);
2604 	atmci_writel(host, ATMCI_CR, ATMCI_CR_MCIDIS);
2605 	atmci_readl(host, ATMCI_SR);
2606 
2607 	timer_delete_sync(&host->timer);
2608 	if (!IS_ERR(host->dma.chan))
2609 		dma_release_channel(host->dma.chan);
2610 
2611 	free_irq(platform_get_irq(pdev, 0), host);
2612 
2613 	clk_disable_unprepare(host->mck);
2614 
2615 	pm_runtime_disable(dev);
2616 	pm_runtime_put_noidle(dev);
2617 }
2618 
2619 static int atmci_runtime_suspend(struct device *dev)
2620 {
2621 	struct atmel_mci *host = dev_get_drvdata(dev);
2622 
2623 	clk_disable_unprepare(host->mck);
2624 
2625 	pinctrl_pm_select_sleep_state(dev);
2626 
2627 	return 0;
2628 }
2629 
2630 static int atmci_runtime_resume(struct device *dev)
2631 {
2632 	struct atmel_mci *host = dev_get_drvdata(dev);
2633 
2634 	pinctrl_select_default_state(dev);
2635 
2636 	return clk_prepare_enable(host->mck);
2637 }
2638 
2639 static const struct dev_pm_ops atmci_dev_pm_ops = {
2640 	SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend, pm_runtime_force_resume)
2641 	RUNTIME_PM_OPS(atmci_runtime_suspend, atmci_runtime_resume, NULL)
2642 };
2643 
2644 static struct platform_driver atmci_driver = {
2645 	.probe		= atmci_probe,
2646 	.remove		= atmci_remove,
2647 	.driver		= {
2648 		.name		= "atmel_mci",
2649 		.probe_type	= PROBE_PREFER_ASYNCHRONOUS,
2650 		.of_match_table	= atmci_dt_ids,
2651 		.pm		= pm_ptr(&atmci_dev_pm_ops),
2652 	},
2653 };
2654 module_platform_driver(atmci_driver);
2655 
2656 MODULE_DESCRIPTION("Atmel Multimedia Card Interface driver");
2657 MODULE_AUTHOR("Haavard Skinnemoen (Atmel)");
2658 MODULE_LICENSE("GPL v2");
2659