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