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