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