mmc: dw_mmc: Add data CRC error injection
[platform/kernel/linux-starfive.git] / drivers / mmc / host / dw_mmc.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Synopsys DesignWare Multimedia Card Interface driver
4  *  (Based on NXP driver for lpc 31xx)
5  *
6  * Copyright (C) 2009 NXP Semiconductors
7  * Copyright (C) 2009, 2010 Imagination Technologies Ltd.
8  */
9
10 #include <linux/blkdev.h>
11 #include <linux/clk.h>
12 #include <linux/debugfs.h>
13 #include <linux/device.h>
14 #include <linux/dma-mapping.h>
15 #include <linux/err.h>
16 #include <linux/init.h>
17 #include <linux/interrupt.h>
18 #include <linux/iopoll.h>
19 #include <linux/ioport.h>
20 #include <linux/ktime.h>
21 #include <linux/module.h>
22 #include <linux/platform_device.h>
23 #include <linux/pm_runtime.h>
24 #include <linux/prandom.h>
25 #include <linux/seq_file.h>
26 #include <linux/slab.h>
27 #include <linux/stat.h>
28 #include <linux/delay.h>
29 #include <linux/irq.h>
30 #include <linux/mmc/card.h>
31 #include <linux/mmc/host.h>
32 #include <linux/mmc/mmc.h>
33 #include <linux/mmc/sd.h>
34 #include <linux/mmc/sdio.h>
35 #include <linux/bitops.h>
36 #include <linux/regulator/consumer.h>
37 #include <linux/of.h>
38 #include <linux/of_gpio.h>
39 #include <linux/mmc/slot-gpio.h>
40
41 #include "dw_mmc.h"
42
43 /* Common flag combinations */
44 #define DW_MCI_DATA_ERROR_FLAGS (SDMMC_INT_DRTO | SDMMC_INT_DCRC | \
45                                  SDMMC_INT_HTO | SDMMC_INT_SBE  | \
46                                  SDMMC_INT_EBE | SDMMC_INT_HLE)
47 #define DW_MCI_CMD_ERROR_FLAGS  (SDMMC_INT_RTO | SDMMC_INT_RCRC | \
48                                  SDMMC_INT_RESP_ERR | SDMMC_INT_HLE)
49 #define DW_MCI_ERROR_FLAGS      (DW_MCI_DATA_ERROR_FLAGS | \
50                                  DW_MCI_CMD_ERROR_FLAGS)
51 #define DW_MCI_SEND_STATUS      1
52 #define DW_MCI_RECV_STATUS      2
53 #define DW_MCI_DMA_THRESHOLD    16
54
55 #define DW_MCI_FREQ_MAX 200000000       /* unit: HZ */
56 #define DW_MCI_FREQ_MIN 100000          /* unit: HZ */
57
58 #define IDMAC_INT_CLR           (SDMMC_IDMAC_INT_AI | SDMMC_IDMAC_INT_NI | \
59                                  SDMMC_IDMAC_INT_CES | SDMMC_IDMAC_INT_DU | \
60                                  SDMMC_IDMAC_INT_FBE | SDMMC_IDMAC_INT_RI | \
61                                  SDMMC_IDMAC_INT_TI)
62
63 #define DESC_RING_BUF_SZ        PAGE_SIZE
64
65 struct idmac_desc_64addr {
66         u32             des0;   /* Control Descriptor */
67 #define IDMAC_OWN_CLR64(x) \
68         !((x) & cpu_to_le32(IDMAC_DES0_OWN))
69
70         u32             des1;   /* Reserved */
71
72         u32             des2;   /*Buffer sizes */
73 #define IDMAC_64ADDR_SET_BUFFER1_SIZE(d, s) \
74         ((d)->des2 = ((d)->des2 & cpu_to_le32(0x03ffe000)) | \
75          ((cpu_to_le32(s)) & cpu_to_le32(0x1fff)))
76
77         u32             des3;   /* Reserved */
78
79         u32             des4;   /* Lower 32-bits of Buffer Address Pointer 1*/
80         u32             des5;   /* Upper 32-bits of Buffer Address Pointer 1*/
81
82         u32             des6;   /* Lower 32-bits of Next Descriptor Address */
83         u32             des7;   /* Upper 32-bits of Next Descriptor Address */
84 };
85
86 struct idmac_desc {
87         __le32          des0;   /* Control Descriptor */
88 #define IDMAC_DES0_DIC  BIT(1)
89 #define IDMAC_DES0_LD   BIT(2)
90 #define IDMAC_DES0_FD   BIT(3)
91 #define IDMAC_DES0_CH   BIT(4)
92 #define IDMAC_DES0_ER   BIT(5)
93 #define IDMAC_DES0_CES  BIT(30)
94 #define IDMAC_DES0_OWN  BIT(31)
95
96         __le32          des1;   /* Buffer sizes */
97 #define IDMAC_SET_BUFFER1_SIZE(d, s) \
98         ((d)->des1 = ((d)->des1 & cpu_to_le32(0x03ffe000)) | (cpu_to_le32((s) & 0x1fff)))
99
100         __le32          des2;   /* buffer 1 physical address */
101
102         __le32          des3;   /* buffer 2 physical address */
103 };
104
105 /* Each descriptor can transfer up to 4KB of data in chained mode */
106 #define DW_MCI_DESC_DATA_LENGTH 0x1000
107
108 #if defined(CONFIG_DEBUG_FS)
109 static int dw_mci_req_show(struct seq_file *s, void *v)
110 {
111         struct dw_mci_slot *slot = s->private;
112         struct mmc_request *mrq;
113         struct mmc_command *cmd;
114         struct mmc_command *stop;
115         struct mmc_data *data;
116
117         /* Make sure we get a consistent snapshot */
118         spin_lock_bh(&slot->host->lock);
119         mrq = slot->mrq;
120
121         if (mrq) {
122                 cmd = mrq->cmd;
123                 data = mrq->data;
124                 stop = mrq->stop;
125
126                 if (cmd)
127                         seq_printf(s,
128                                    "CMD%u(0x%x) flg %x rsp %x %x %x %x err %d\n",
129                                    cmd->opcode, cmd->arg, cmd->flags,
130                                    cmd->resp[0], cmd->resp[1], cmd->resp[2],
131                                    cmd->resp[2], cmd->error);
132                 if (data)
133                         seq_printf(s, "DATA %u / %u * %u flg %x err %d\n",
134                                    data->bytes_xfered, data->blocks,
135                                    data->blksz, data->flags, data->error);
136                 if (stop)
137                         seq_printf(s,
138                                    "CMD%u(0x%x) flg %x rsp %x %x %x %x err %d\n",
139                                    stop->opcode, stop->arg, stop->flags,
140                                    stop->resp[0], stop->resp[1], stop->resp[2],
141                                    stop->resp[2], stop->error);
142         }
143
144         spin_unlock_bh(&slot->host->lock);
145
146         return 0;
147 }
148 DEFINE_SHOW_ATTRIBUTE(dw_mci_req);
149
150 static int dw_mci_regs_show(struct seq_file *s, void *v)
151 {
152         struct dw_mci *host = s->private;
153
154         pm_runtime_get_sync(host->dev);
155
156         seq_printf(s, "STATUS:\t0x%08x\n", mci_readl(host, STATUS));
157         seq_printf(s, "RINTSTS:\t0x%08x\n", mci_readl(host, RINTSTS));
158         seq_printf(s, "CMD:\t0x%08x\n", mci_readl(host, CMD));
159         seq_printf(s, "CTRL:\t0x%08x\n", mci_readl(host, CTRL));
160         seq_printf(s, "INTMASK:\t0x%08x\n", mci_readl(host, INTMASK));
161         seq_printf(s, "CLKENA:\t0x%08x\n", mci_readl(host, CLKENA));
162
163         pm_runtime_put_autosuspend(host->dev);
164
165         return 0;
166 }
167 DEFINE_SHOW_ATTRIBUTE(dw_mci_regs);
168
169 static void dw_mci_init_debugfs(struct dw_mci_slot *slot)
170 {
171         struct mmc_host *mmc = slot->mmc;
172         struct dw_mci *host = slot->host;
173         struct dentry *root;
174
175         root = mmc->debugfs_root;
176         if (!root)
177                 return;
178
179         debugfs_create_file("regs", S_IRUSR, root, host, &dw_mci_regs_fops);
180         debugfs_create_file("req", S_IRUSR, root, slot, &dw_mci_req_fops);
181         debugfs_create_u32("state", S_IRUSR, root, &host->state);
182         debugfs_create_xul("pending_events", S_IRUSR, root,
183                            &host->pending_events);
184         debugfs_create_xul("completed_events", S_IRUSR, root,
185                            &host->completed_events);
186 #ifdef CONFIG_FAULT_INJECTION
187         fault_create_debugfs_attr("fail_data_crc", root, &host->fail_data_crc);
188 #endif
189 }
190 #endif /* defined(CONFIG_DEBUG_FS) */
191
192 static bool dw_mci_ctrl_reset(struct dw_mci *host, u32 reset)
193 {
194         u32 ctrl;
195
196         ctrl = mci_readl(host, CTRL);
197         ctrl |= reset;
198         mci_writel(host, CTRL, ctrl);
199
200         /* wait till resets clear */
201         if (readl_poll_timeout_atomic(host->regs + SDMMC_CTRL, ctrl,
202                                       !(ctrl & reset),
203                                       1, 500 * USEC_PER_MSEC)) {
204                 dev_err(host->dev,
205                         "Timeout resetting block (ctrl reset %#x)\n",
206                         ctrl & reset);
207                 return false;
208         }
209
210         return true;
211 }
212
213 static void dw_mci_wait_while_busy(struct dw_mci *host, u32 cmd_flags)
214 {
215         u32 status;
216
217         /*
218          * Databook says that before issuing a new data transfer command
219          * we need to check to see if the card is busy.  Data transfer commands
220          * all have SDMMC_CMD_PRV_DAT_WAIT set, so we'll key off that.
221          *
222          * ...also allow sending for SDMMC_CMD_VOLT_SWITCH where busy is
223          * expected.
224          */
225         if ((cmd_flags & SDMMC_CMD_PRV_DAT_WAIT) &&
226             !(cmd_flags & SDMMC_CMD_VOLT_SWITCH)) {
227                 if (readl_poll_timeout_atomic(host->regs + SDMMC_STATUS,
228                                               status,
229                                               !(status & SDMMC_STATUS_BUSY),
230                                               10, 500 * USEC_PER_MSEC))
231                         dev_err(host->dev, "Busy; trying anyway\n");
232         }
233 }
234
235 static void mci_send_cmd(struct dw_mci_slot *slot, u32 cmd, u32 arg)
236 {
237         struct dw_mci *host = slot->host;
238         unsigned int cmd_status = 0;
239
240         mci_writel(host, CMDARG, arg);
241         wmb(); /* drain writebuffer */
242         dw_mci_wait_while_busy(host, cmd);
243         mci_writel(host, CMD, SDMMC_CMD_START | cmd);
244
245         if (readl_poll_timeout_atomic(host->regs + SDMMC_CMD, cmd_status,
246                                       !(cmd_status & SDMMC_CMD_START),
247                                       1, 500 * USEC_PER_MSEC))
248                 dev_err(&slot->mmc->class_dev,
249                         "Timeout sending command (cmd %#x arg %#x status %#x)\n",
250                         cmd, arg, cmd_status);
251 }
252
253 static u32 dw_mci_prepare_command(struct mmc_host *mmc, struct mmc_command *cmd)
254 {
255         struct dw_mci_slot *slot = mmc_priv(mmc);
256         struct dw_mci *host = slot->host;
257         u32 cmdr;
258
259         cmd->error = -EINPROGRESS;
260         cmdr = cmd->opcode;
261
262         if (cmd->opcode == MMC_STOP_TRANSMISSION ||
263             cmd->opcode == MMC_GO_IDLE_STATE ||
264             cmd->opcode == MMC_GO_INACTIVE_STATE ||
265             (cmd->opcode == SD_IO_RW_DIRECT &&
266              ((cmd->arg >> 9) & 0x1FFFF) == SDIO_CCCR_ABORT))
267                 cmdr |= SDMMC_CMD_STOP;
268         else if (cmd->opcode != MMC_SEND_STATUS && cmd->data)
269                 cmdr |= SDMMC_CMD_PRV_DAT_WAIT;
270
271         if (cmd->opcode == SD_SWITCH_VOLTAGE) {
272                 u32 clk_en_a;
273
274                 /* Special bit makes CMD11 not die */
275                 cmdr |= SDMMC_CMD_VOLT_SWITCH;
276
277                 /* Change state to continue to handle CMD11 weirdness */
278                 WARN_ON(slot->host->state != STATE_SENDING_CMD);
279                 slot->host->state = STATE_SENDING_CMD11;
280
281                 /*
282                  * We need to disable low power mode (automatic clock stop)
283                  * while doing voltage switch so we don't confuse the card,
284                  * since stopping the clock is a specific part of the UHS
285                  * voltage change dance.
286                  *
287                  * Note that low power mode (SDMMC_CLKEN_LOW_PWR) will be
288                  * unconditionally turned back on in dw_mci_setup_bus() if it's
289                  * ever called with a non-zero clock.  That shouldn't happen
290                  * until the voltage change is all done.
291                  */
292                 clk_en_a = mci_readl(host, CLKENA);
293                 clk_en_a &= ~(SDMMC_CLKEN_LOW_PWR << slot->id);
294                 mci_writel(host, CLKENA, clk_en_a);
295                 mci_send_cmd(slot, SDMMC_CMD_UPD_CLK |
296                              SDMMC_CMD_PRV_DAT_WAIT, 0);
297         }
298
299         if (cmd->flags & MMC_RSP_PRESENT) {
300                 /* We expect a response, so set this bit */
301                 cmdr |= SDMMC_CMD_RESP_EXP;
302                 if (cmd->flags & MMC_RSP_136)
303                         cmdr |= SDMMC_CMD_RESP_LONG;
304         }
305
306         if (cmd->flags & MMC_RSP_CRC)
307                 cmdr |= SDMMC_CMD_RESP_CRC;
308
309         if (cmd->data) {
310                 cmdr |= SDMMC_CMD_DAT_EXP;
311                 if (cmd->data->flags & MMC_DATA_WRITE)
312                         cmdr |= SDMMC_CMD_DAT_WR;
313         }
314
315         if (!test_bit(DW_MMC_CARD_NO_USE_HOLD, &slot->flags))
316                 cmdr |= SDMMC_CMD_USE_HOLD_REG;
317
318         return cmdr;
319 }
320
321 static u32 dw_mci_prep_stop_abort(struct dw_mci *host, struct mmc_command *cmd)
322 {
323         struct mmc_command *stop;
324         u32 cmdr;
325
326         if (!cmd->data)
327                 return 0;
328
329         stop = &host->stop_abort;
330         cmdr = cmd->opcode;
331         memset(stop, 0, sizeof(struct mmc_command));
332
333         if (cmdr == MMC_READ_SINGLE_BLOCK ||
334             cmdr == MMC_READ_MULTIPLE_BLOCK ||
335             cmdr == MMC_WRITE_BLOCK ||
336             cmdr == MMC_WRITE_MULTIPLE_BLOCK ||
337             cmdr == MMC_SEND_TUNING_BLOCK ||
338             cmdr == MMC_SEND_TUNING_BLOCK_HS200) {
339                 stop->opcode = MMC_STOP_TRANSMISSION;
340                 stop->arg = 0;
341                 stop->flags = MMC_RSP_R1B | MMC_CMD_AC;
342         } else if (cmdr == SD_IO_RW_EXTENDED) {
343                 stop->opcode = SD_IO_RW_DIRECT;
344                 stop->arg |= (1 << 31) | (0 << 28) | (SDIO_CCCR_ABORT << 9) |
345                              ((cmd->arg >> 28) & 0x7);
346                 stop->flags = MMC_RSP_SPI_R5 | MMC_RSP_R5 | MMC_CMD_AC;
347         } else {
348                 return 0;
349         }
350
351         cmdr = stop->opcode | SDMMC_CMD_STOP |
352                 SDMMC_CMD_RESP_CRC | SDMMC_CMD_RESP_EXP;
353
354         if (!test_bit(DW_MMC_CARD_NO_USE_HOLD, &host->slot->flags))
355                 cmdr |= SDMMC_CMD_USE_HOLD_REG;
356
357         return cmdr;
358 }
359
360 static inline void dw_mci_set_cto(struct dw_mci *host)
361 {
362         unsigned int cto_clks;
363         unsigned int cto_div;
364         unsigned int cto_ms;
365         unsigned long irqflags;
366
367         cto_clks = mci_readl(host, TMOUT) & 0xff;
368         cto_div = (mci_readl(host, CLKDIV) & 0xff) * 2;
369         if (cto_div == 0)
370                 cto_div = 1;
371
372         cto_ms = DIV_ROUND_UP_ULL((u64)MSEC_PER_SEC * cto_clks * cto_div,
373                                   host->bus_hz);
374
375         /* add a bit spare time */
376         cto_ms += 10;
377
378         /*
379          * The durations we're working with are fairly short so we have to be
380          * extra careful about synchronization here.  Specifically in hardware a
381          * command timeout is _at most_ 5.1 ms, so that means we expect an
382          * interrupt (either command done or timeout) to come rather quickly
383          * after the mci_writel.  ...but just in case we have a long interrupt
384          * latency let's add a bit of paranoia.
385          *
386          * In general we'll assume that at least an interrupt will be asserted
387          * in hardware by the time the cto_timer runs.  ...and if it hasn't
388          * been asserted in hardware by that time then we'll assume it'll never
389          * come.
390          */
391         spin_lock_irqsave(&host->irq_lock, irqflags);
392         if (!test_bit(EVENT_CMD_COMPLETE, &host->pending_events))
393                 mod_timer(&host->cto_timer,
394                         jiffies + msecs_to_jiffies(cto_ms) + 1);
395         spin_unlock_irqrestore(&host->irq_lock, irqflags);
396 }
397
398 static void dw_mci_start_command(struct dw_mci *host,
399                                  struct mmc_command *cmd, u32 cmd_flags)
400 {
401         host->cmd = cmd;
402         dev_vdbg(host->dev,
403                  "start command: ARGR=0x%08x CMDR=0x%08x\n",
404                  cmd->arg, cmd_flags);
405
406         mci_writel(host, CMDARG, cmd->arg);
407         wmb(); /* drain writebuffer */
408         dw_mci_wait_while_busy(host, cmd_flags);
409
410         mci_writel(host, CMD, cmd_flags | SDMMC_CMD_START);
411
412         /* response expected command only */
413         if (cmd_flags & SDMMC_CMD_RESP_EXP)
414                 dw_mci_set_cto(host);
415 }
416
417 static inline void send_stop_abort(struct dw_mci *host, struct mmc_data *data)
418 {
419         struct mmc_command *stop = &host->stop_abort;
420
421         dw_mci_start_command(host, stop, host->stop_cmdr);
422 }
423
424 /* DMA interface functions */
425 static void dw_mci_stop_dma(struct dw_mci *host)
426 {
427         if (host->using_dma) {
428                 host->dma_ops->stop(host);
429                 host->dma_ops->cleanup(host);
430         }
431
432         /* Data transfer was stopped by the interrupt handler */
433         set_bit(EVENT_XFER_COMPLETE, &host->pending_events);
434 }
435
436 static void dw_mci_dma_cleanup(struct dw_mci *host)
437 {
438         struct mmc_data *data = host->data;
439
440         if (data && data->host_cookie == COOKIE_MAPPED) {
441                 dma_unmap_sg(host->dev,
442                              data->sg,
443                              data->sg_len,
444                              mmc_get_dma_dir(data));
445                 data->host_cookie = COOKIE_UNMAPPED;
446         }
447 }
448
449 static void dw_mci_idmac_reset(struct dw_mci *host)
450 {
451         u32 bmod = mci_readl(host, BMOD);
452         /* Software reset of DMA */
453         bmod |= SDMMC_IDMAC_SWRESET;
454         mci_writel(host, BMOD, bmod);
455 }
456
457 static void dw_mci_idmac_stop_dma(struct dw_mci *host)
458 {
459         u32 temp;
460
461         /* Disable and reset the IDMAC interface */
462         temp = mci_readl(host, CTRL);
463         temp &= ~SDMMC_CTRL_USE_IDMAC;
464         temp |= SDMMC_CTRL_DMA_RESET;
465         mci_writel(host, CTRL, temp);
466
467         /* Stop the IDMAC running */
468         temp = mci_readl(host, BMOD);
469         temp &= ~(SDMMC_IDMAC_ENABLE | SDMMC_IDMAC_FB);
470         temp |= SDMMC_IDMAC_SWRESET;
471         mci_writel(host, BMOD, temp);
472 }
473
474 static void dw_mci_dmac_complete_dma(void *arg)
475 {
476         struct dw_mci *host = arg;
477         struct mmc_data *data = host->data;
478
479         dev_vdbg(host->dev, "DMA complete\n");
480
481         if ((host->use_dma == TRANS_MODE_EDMAC) &&
482             data && (data->flags & MMC_DATA_READ))
483                 /* Invalidate cache after read */
484                 dma_sync_sg_for_cpu(mmc_dev(host->slot->mmc),
485                                     data->sg,
486                                     data->sg_len,
487                                     DMA_FROM_DEVICE);
488
489         host->dma_ops->cleanup(host);
490
491         /*
492          * If the card was removed, data will be NULL. No point in trying to
493          * send the stop command or waiting for NBUSY in this case.
494          */
495         if (data) {
496                 set_bit(EVENT_XFER_COMPLETE, &host->pending_events);
497                 tasklet_schedule(&host->tasklet);
498         }
499 }
500
501 static int dw_mci_idmac_init(struct dw_mci *host)
502 {
503         int i;
504
505         if (host->dma_64bit_address == 1) {
506                 struct idmac_desc_64addr *p;
507                 /* Number of descriptors in the ring buffer */
508                 host->ring_size =
509                         DESC_RING_BUF_SZ / sizeof(struct idmac_desc_64addr);
510
511                 /* Forward link the descriptor list */
512                 for (i = 0, p = host->sg_cpu; i < host->ring_size - 1;
513                                                                 i++, p++) {
514                         p->des6 = (host->sg_dma +
515                                         (sizeof(struct idmac_desc_64addr) *
516                                                         (i + 1))) & 0xffffffff;
517
518                         p->des7 = (u64)(host->sg_dma +
519                                         (sizeof(struct idmac_desc_64addr) *
520                                                         (i + 1))) >> 32;
521                         /* Initialize reserved and buffer size fields to "0" */
522                         p->des0 = 0;
523                         p->des1 = 0;
524                         p->des2 = 0;
525                         p->des3 = 0;
526                 }
527
528                 /* Set the last descriptor as the end-of-ring descriptor */
529                 p->des6 = host->sg_dma & 0xffffffff;
530                 p->des7 = (u64)host->sg_dma >> 32;
531                 p->des0 = IDMAC_DES0_ER;
532
533         } else {
534                 struct idmac_desc *p;
535                 /* Number of descriptors in the ring buffer */
536                 host->ring_size =
537                         DESC_RING_BUF_SZ / sizeof(struct idmac_desc);
538
539                 /* Forward link the descriptor list */
540                 for (i = 0, p = host->sg_cpu;
541                      i < host->ring_size - 1;
542                      i++, p++) {
543                         p->des3 = cpu_to_le32(host->sg_dma +
544                                         (sizeof(struct idmac_desc) * (i + 1)));
545                         p->des0 = 0;
546                         p->des1 = 0;
547                 }
548
549                 /* Set the last descriptor as the end-of-ring descriptor */
550                 p->des3 = cpu_to_le32(host->sg_dma);
551                 p->des0 = cpu_to_le32(IDMAC_DES0_ER);
552         }
553
554         dw_mci_idmac_reset(host);
555
556         if (host->dma_64bit_address == 1) {
557                 /* Mask out interrupts - get Tx & Rx complete only */
558                 mci_writel(host, IDSTS64, IDMAC_INT_CLR);
559                 mci_writel(host, IDINTEN64, SDMMC_IDMAC_INT_NI |
560                                 SDMMC_IDMAC_INT_RI | SDMMC_IDMAC_INT_TI);
561
562                 /* Set the descriptor base address */
563                 mci_writel(host, DBADDRL, host->sg_dma & 0xffffffff);
564                 mci_writel(host, DBADDRU, (u64)host->sg_dma >> 32);
565
566         } else {
567                 /* Mask out interrupts - get Tx & Rx complete only */
568                 mci_writel(host, IDSTS, IDMAC_INT_CLR);
569                 mci_writel(host, IDINTEN, SDMMC_IDMAC_INT_NI |
570                                 SDMMC_IDMAC_INT_RI | SDMMC_IDMAC_INT_TI);
571
572                 /* Set the descriptor base address */
573                 mci_writel(host, DBADDR, host->sg_dma);
574         }
575
576         return 0;
577 }
578
579 static inline int dw_mci_prepare_desc64(struct dw_mci *host,
580                                          struct mmc_data *data,
581                                          unsigned int sg_len)
582 {
583         unsigned int desc_len;
584         struct idmac_desc_64addr *desc_first, *desc_last, *desc;
585         u32 val;
586         int i;
587
588         desc_first = desc_last = desc = host->sg_cpu;
589
590         for (i = 0; i < sg_len; i++) {
591                 unsigned int length = sg_dma_len(&data->sg[i]);
592
593                 u64 mem_addr = sg_dma_address(&data->sg[i]);
594
595                 for ( ; length ; desc++) {
596                         desc_len = (length <= DW_MCI_DESC_DATA_LENGTH) ?
597                                    length : DW_MCI_DESC_DATA_LENGTH;
598
599                         length -= desc_len;
600
601                         /*
602                          * Wait for the former clear OWN bit operation
603                          * of IDMAC to make sure that this descriptor
604                          * isn't still owned by IDMAC as IDMAC's write
605                          * ops and CPU's read ops are asynchronous.
606                          */
607                         if (readl_poll_timeout_atomic(&desc->des0, val,
608                                                 !(val & IDMAC_DES0_OWN),
609                                                 10, 100 * USEC_PER_MSEC))
610                                 goto err_own_bit;
611
612                         /*
613                          * Set the OWN bit and disable interrupts
614                          * for this descriptor
615                          */
616                         desc->des0 = IDMAC_DES0_OWN | IDMAC_DES0_DIC |
617                                                 IDMAC_DES0_CH;
618
619                         /* Buffer length */
620                         IDMAC_64ADDR_SET_BUFFER1_SIZE(desc, desc_len);
621
622                         /* Physical address to DMA to/from */
623                         desc->des4 = mem_addr & 0xffffffff;
624                         desc->des5 = mem_addr >> 32;
625
626                         /* Update physical address for the next desc */
627                         mem_addr += desc_len;
628
629                         /* Save pointer to the last descriptor */
630                         desc_last = desc;
631                 }
632         }
633
634         /* Set first descriptor */
635         desc_first->des0 |= IDMAC_DES0_FD;
636
637         /* Set last descriptor */
638         desc_last->des0 &= ~(IDMAC_DES0_CH | IDMAC_DES0_DIC);
639         desc_last->des0 |= IDMAC_DES0_LD;
640
641         return 0;
642 err_own_bit:
643         /* restore the descriptor chain as it's polluted */
644         dev_dbg(host->dev, "descriptor is still owned by IDMAC.\n");
645         memset(host->sg_cpu, 0, DESC_RING_BUF_SZ);
646         dw_mci_idmac_init(host);
647         return -EINVAL;
648 }
649
650
651 static inline int dw_mci_prepare_desc32(struct dw_mci *host,
652                                          struct mmc_data *data,
653                                          unsigned int sg_len)
654 {
655         unsigned int desc_len;
656         struct idmac_desc *desc_first, *desc_last, *desc;
657         u32 val;
658         int i;
659
660         desc_first = desc_last = desc = host->sg_cpu;
661
662         for (i = 0; i < sg_len; i++) {
663                 unsigned int length = sg_dma_len(&data->sg[i]);
664
665                 u32 mem_addr = sg_dma_address(&data->sg[i]);
666
667                 for ( ; length ; desc++) {
668                         desc_len = (length <= DW_MCI_DESC_DATA_LENGTH) ?
669                                    length : DW_MCI_DESC_DATA_LENGTH;
670
671                         length -= desc_len;
672
673                         /*
674                          * Wait for the former clear OWN bit operation
675                          * of IDMAC to make sure that this descriptor
676                          * isn't still owned by IDMAC as IDMAC's write
677                          * ops and CPU's read ops are asynchronous.
678                          */
679                         if (readl_poll_timeout_atomic(&desc->des0, val,
680                                                       IDMAC_OWN_CLR64(val),
681                                                       10,
682                                                       100 * USEC_PER_MSEC))
683                                 goto err_own_bit;
684
685                         /*
686                          * Set the OWN bit and disable interrupts
687                          * for this descriptor
688                          */
689                         desc->des0 = cpu_to_le32(IDMAC_DES0_OWN |
690                                                  IDMAC_DES0_DIC |
691                                                  IDMAC_DES0_CH);
692
693                         /* Buffer length */
694                         IDMAC_SET_BUFFER1_SIZE(desc, desc_len);
695
696                         /* Physical address to DMA to/from */
697                         desc->des2 = cpu_to_le32(mem_addr);
698
699                         /* Update physical address for the next desc */
700                         mem_addr += desc_len;
701
702                         /* Save pointer to the last descriptor */
703                         desc_last = desc;
704                 }
705         }
706
707         /* Set first descriptor */
708         desc_first->des0 |= cpu_to_le32(IDMAC_DES0_FD);
709
710         /* Set last descriptor */
711         desc_last->des0 &= cpu_to_le32(~(IDMAC_DES0_CH |
712                                        IDMAC_DES0_DIC));
713         desc_last->des0 |= cpu_to_le32(IDMAC_DES0_LD);
714
715         return 0;
716 err_own_bit:
717         /* restore the descriptor chain as it's polluted */
718         dev_dbg(host->dev, "descriptor is still owned by IDMAC.\n");
719         memset(host->sg_cpu, 0, DESC_RING_BUF_SZ);
720         dw_mci_idmac_init(host);
721         return -EINVAL;
722 }
723
724 static int dw_mci_idmac_start_dma(struct dw_mci *host, unsigned int sg_len)
725 {
726         u32 temp;
727         int ret;
728
729         if (host->dma_64bit_address == 1)
730                 ret = dw_mci_prepare_desc64(host, host->data, sg_len);
731         else
732                 ret = dw_mci_prepare_desc32(host, host->data, sg_len);
733
734         if (ret)
735                 goto out;
736
737         /* drain writebuffer */
738         wmb();
739
740         /* Make sure to reset DMA in case we did PIO before this */
741         dw_mci_ctrl_reset(host, SDMMC_CTRL_DMA_RESET);
742         dw_mci_idmac_reset(host);
743
744         /* Select IDMAC interface */
745         temp = mci_readl(host, CTRL);
746         temp |= SDMMC_CTRL_USE_IDMAC;
747         mci_writel(host, CTRL, temp);
748
749         /* drain writebuffer */
750         wmb();
751
752         /* Enable the IDMAC */
753         temp = mci_readl(host, BMOD);
754         temp |= SDMMC_IDMAC_ENABLE | SDMMC_IDMAC_FB;
755         mci_writel(host, BMOD, temp);
756
757         /* Start it running */
758         mci_writel(host, PLDMND, 1);
759
760 out:
761         return ret;
762 }
763
764 static const struct dw_mci_dma_ops dw_mci_idmac_ops = {
765         .init = dw_mci_idmac_init,
766         .start = dw_mci_idmac_start_dma,
767         .stop = dw_mci_idmac_stop_dma,
768         .complete = dw_mci_dmac_complete_dma,
769         .cleanup = dw_mci_dma_cleanup,
770 };
771
772 static void dw_mci_edmac_stop_dma(struct dw_mci *host)
773 {
774         dmaengine_terminate_async(host->dms->ch);
775 }
776
777 static int dw_mci_edmac_start_dma(struct dw_mci *host,
778                                             unsigned int sg_len)
779 {
780         struct dma_slave_config cfg;
781         struct dma_async_tx_descriptor *desc = NULL;
782         struct scatterlist *sgl = host->data->sg;
783         static const u32 mszs[] = {1, 4, 8, 16, 32, 64, 128, 256};
784         u32 sg_elems = host->data->sg_len;
785         u32 fifoth_val;
786         u32 fifo_offset = host->fifo_reg - host->regs;
787         int ret = 0;
788
789         /* Set external dma config: burst size, burst width */
790         cfg.dst_addr = host->phy_regs + fifo_offset;
791         cfg.src_addr = cfg.dst_addr;
792         cfg.dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
793         cfg.src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
794
795         /* Match burst msize with external dma config */
796         fifoth_val = mci_readl(host, FIFOTH);
797         cfg.dst_maxburst = mszs[(fifoth_val >> 28) & 0x7];
798         cfg.src_maxburst = cfg.dst_maxburst;
799
800         if (host->data->flags & MMC_DATA_WRITE)
801                 cfg.direction = DMA_MEM_TO_DEV;
802         else
803                 cfg.direction = DMA_DEV_TO_MEM;
804
805         ret = dmaengine_slave_config(host->dms->ch, &cfg);
806         if (ret) {
807                 dev_err(host->dev, "Failed to config edmac.\n");
808                 return -EBUSY;
809         }
810
811         desc = dmaengine_prep_slave_sg(host->dms->ch, sgl,
812                                        sg_len, cfg.direction,
813                                        DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
814         if (!desc) {
815                 dev_err(host->dev, "Can't prepare slave sg.\n");
816                 return -EBUSY;
817         }
818
819         /* Set dw_mci_dmac_complete_dma as callback */
820         desc->callback = dw_mci_dmac_complete_dma;
821         desc->callback_param = (void *)host;
822         dmaengine_submit(desc);
823
824         /* Flush cache before write */
825         if (host->data->flags & MMC_DATA_WRITE)
826                 dma_sync_sg_for_device(mmc_dev(host->slot->mmc), sgl,
827                                        sg_elems, DMA_TO_DEVICE);
828
829         dma_async_issue_pending(host->dms->ch);
830
831         return 0;
832 }
833
834 static int dw_mci_edmac_init(struct dw_mci *host)
835 {
836         /* Request external dma channel */
837         host->dms = kzalloc(sizeof(struct dw_mci_dma_slave), GFP_KERNEL);
838         if (!host->dms)
839                 return -ENOMEM;
840
841         host->dms->ch = dma_request_chan(host->dev, "rx-tx");
842         if (IS_ERR(host->dms->ch)) {
843                 int ret = PTR_ERR(host->dms->ch);
844
845                 dev_err(host->dev, "Failed to get external DMA channel.\n");
846                 kfree(host->dms);
847                 host->dms = NULL;
848                 return ret;
849         }
850
851         return 0;
852 }
853
854 static void dw_mci_edmac_exit(struct dw_mci *host)
855 {
856         if (host->dms) {
857                 if (host->dms->ch) {
858                         dma_release_channel(host->dms->ch);
859                         host->dms->ch = NULL;
860                 }
861                 kfree(host->dms);
862                 host->dms = NULL;
863         }
864 }
865
866 static const struct dw_mci_dma_ops dw_mci_edmac_ops = {
867         .init = dw_mci_edmac_init,
868         .exit = dw_mci_edmac_exit,
869         .start = dw_mci_edmac_start_dma,
870         .stop = dw_mci_edmac_stop_dma,
871         .complete = dw_mci_dmac_complete_dma,
872         .cleanup = dw_mci_dma_cleanup,
873 };
874
875 static int dw_mci_pre_dma_transfer(struct dw_mci *host,
876                                    struct mmc_data *data,
877                                    int cookie)
878 {
879         struct scatterlist *sg;
880         unsigned int i, sg_len;
881
882         if (data->host_cookie == COOKIE_PRE_MAPPED)
883                 return data->sg_len;
884
885         /*
886          * We don't do DMA on "complex" transfers, i.e. with
887          * non-word-aligned buffers or lengths. Also, we don't bother
888          * with all the DMA setup overhead for short transfers.
889          */
890         if (data->blocks * data->blksz < DW_MCI_DMA_THRESHOLD)
891                 return -EINVAL;
892
893         if (data->blksz & 3)
894                 return -EINVAL;
895
896         for_each_sg(data->sg, sg, data->sg_len, i) {
897                 if (sg->offset & 3 || sg->length & 3)
898                         return -EINVAL;
899         }
900
901         sg_len = dma_map_sg(host->dev,
902                             data->sg,
903                             data->sg_len,
904                             mmc_get_dma_dir(data));
905         if (sg_len == 0)
906                 return -EINVAL;
907
908         data->host_cookie = cookie;
909
910         return sg_len;
911 }
912
913 static void dw_mci_pre_req(struct mmc_host *mmc,
914                            struct mmc_request *mrq)
915 {
916         struct dw_mci_slot *slot = mmc_priv(mmc);
917         struct mmc_data *data = mrq->data;
918
919         if (!slot->host->use_dma || !data)
920                 return;
921
922         /* This data might be unmapped at this time */
923         data->host_cookie = COOKIE_UNMAPPED;
924
925         if (dw_mci_pre_dma_transfer(slot->host, mrq->data,
926                                 COOKIE_PRE_MAPPED) < 0)
927                 data->host_cookie = COOKIE_UNMAPPED;
928 }
929
930 static void dw_mci_post_req(struct mmc_host *mmc,
931                             struct mmc_request *mrq,
932                             int err)
933 {
934         struct dw_mci_slot *slot = mmc_priv(mmc);
935         struct mmc_data *data = mrq->data;
936
937         if (!slot->host->use_dma || !data)
938                 return;
939
940         if (data->host_cookie != COOKIE_UNMAPPED)
941                 dma_unmap_sg(slot->host->dev,
942                              data->sg,
943                              data->sg_len,
944                              mmc_get_dma_dir(data));
945         data->host_cookie = COOKIE_UNMAPPED;
946 }
947
948 static int dw_mci_get_cd(struct mmc_host *mmc)
949 {
950         int present;
951         struct dw_mci_slot *slot = mmc_priv(mmc);
952         struct dw_mci *host = slot->host;
953         int gpio_cd = mmc_gpio_get_cd(mmc);
954
955         /* Use platform get_cd function, else try onboard card detect */
956         if (((mmc->caps & MMC_CAP_NEEDS_POLL)
957                                 || !mmc_card_is_removable(mmc))) {
958                 present = 1;
959
960                 if (!test_bit(DW_MMC_CARD_PRESENT, &slot->flags)) {
961                         if (mmc->caps & MMC_CAP_NEEDS_POLL) {
962                                 dev_info(&mmc->class_dev,
963                                         "card is polling.\n");
964                         } else {
965                                 dev_info(&mmc->class_dev,
966                                         "card is non-removable.\n");
967                         }
968                         set_bit(DW_MMC_CARD_PRESENT, &slot->flags);
969                 }
970
971                 return present;
972         } else if (gpio_cd >= 0)
973                 present = gpio_cd;
974         else
975                 present = (mci_readl(slot->host, CDETECT) & (1 << slot->id))
976                         == 0 ? 1 : 0;
977
978         spin_lock_bh(&host->lock);
979         if (present && !test_and_set_bit(DW_MMC_CARD_PRESENT, &slot->flags))
980                 dev_dbg(&mmc->class_dev, "card is present\n");
981         else if (!present &&
982                         !test_and_clear_bit(DW_MMC_CARD_PRESENT, &slot->flags))
983                 dev_dbg(&mmc->class_dev, "card is not present\n");
984         spin_unlock_bh(&host->lock);
985
986         return present;
987 }
988
989 static void dw_mci_adjust_fifoth(struct dw_mci *host, struct mmc_data *data)
990 {
991         unsigned int blksz = data->blksz;
992         static const u32 mszs[] = {1, 4, 8, 16, 32, 64, 128, 256};
993         u32 fifo_width = 1 << host->data_shift;
994         u32 blksz_depth = blksz / fifo_width, fifoth_val;
995         u32 msize = 0, rx_wmark = 1, tx_wmark, tx_wmark_invers;
996         int idx = ARRAY_SIZE(mszs) - 1;
997
998         /* pio should ship this scenario */
999         if (!host->use_dma)
1000                 return;
1001
1002         tx_wmark = (host->fifo_depth) / 2;
1003         tx_wmark_invers = host->fifo_depth - tx_wmark;
1004
1005         /*
1006          * MSIZE is '1',
1007          * if blksz is not a multiple of the FIFO width
1008          */
1009         if (blksz % fifo_width)
1010                 goto done;
1011
1012         do {
1013                 if (!((blksz_depth % mszs[idx]) ||
1014                      (tx_wmark_invers % mszs[idx]))) {
1015                         msize = idx;
1016                         rx_wmark = mszs[idx] - 1;
1017                         break;
1018                 }
1019         } while (--idx > 0);
1020         /*
1021          * If idx is '0', it won't be tried
1022          * Thus, initial values are uesed
1023          */
1024 done:
1025         fifoth_val = SDMMC_SET_FIFOTH(msize, rx_wmark, tx_wmark);
1026         mci_writel(host, FIFOTH, fifoth_val);
1027 }
1028
1029 static void dw_mci_ctrl_thld(struct dw_mci *host, struct mmc_data *data)
1030 {
1031         unsigned int blksz = data->blksz;
1032         u32 blksz_depth, fifo_depth;
1033         u16 thld_size;
1034         u8 enable;
1035
1036         /*
1037          * CDTHRCTL doesn't exist prior to 240A (in fact that register offset is
1038          * in the FIFO region, so we really shouldn't access it).
1039          */
1040         if (host->verid < DW_MMC_240A ||
1041                 (host->verid < DW_MMC_280A && data->flags & MMC_DATA_WRITE))
1042                 return;
1043
1044         /*
1045          * Card write Threshold is introduced since 2.80a
1046          * It's used when HS400 mode is enabled.
1047          */
1048         if (data->flags & MMC_DATA_WRITE &&
1049                 host->timing != MMC_TIMING_MMC_HS400)
1050                 goto disable;
1051
1052         if (data->flags & MMC_DATA_WRITE)
1053                 enable = SDMMC_CARD_WR_THR_EN;
1054         else
1055                 enable = SDMMC_CARD_RD_THR_EN;
1056
1057         if (host->timing != MMC_TIMING_MMC_HS200 &&
1058             host->timing != MMC_TIMING_UHS_SDR104 &&
1059             host->timing != MMC_TIMING_MMC_HS400)
1060                 goto disable;
1061
1062         blksz_depth = blksz / (1 << host->data_shift);
1063         fifo_depth = host->fifo_depth;
1064
1065         if (blksz_depth > fifo_depth)
1066                 goto disable;
1067
1068         /*
1069          * If (blksz_depth) >= (fifo_depth >> 1), should be 'thld_size <= blksz'
1070          * If (blksz_depth) <  (fifo_depth >> 1), should be thld_size = blksz
1071          * Currently just choose blksz.
1072          */
1073         thld_size = blksz;
1074         mci_writel(host, CDTHRCTL, SDMMC_SET_THLD(thld_size, enable));
1075         return;
1076
1077 disable:
1078         mci_writel(host, CDTHRCTL, 0);
1079 }
1080
1081 static int dw_mci_submit_data_dma(struct dw_mci *host, struct mmc_data *data)
1082 {
1083         unsigned long irqflags;
1084         int sg_len;
1085         u32 temp;
1086
1087         host->using_dma = 0;
1088
1089         /* If we don't have a channel, we can't do DMA */
1090         if (!host->use_dma)
1091                 return -ENODEV;
1092
1093         sg_len = dw_mci_pre_dma_transfer(host, data, COOKIE_MAPPED);
1094         if (sg_len < 0) {
1095                 host->dma_ops->stop(host);
1096                 return sg_len;
1097         }
1098
1099         host->using_dma = 1;
1100
1101         if (host->use_dma == TRANS_MODE_IDMAC)
1102                 dev_vdbg(host->dev,
1103                          "sd sg_cpu: %#lx sg_dma: %#lx sg_len: %d\n",
1104                          (unsigned long)host->sg_cpu,
1105                          (unsigned long)host->sg_dma,
1106                          sg_len);
1107
1108         /*
1109          * Decide the MSIZE and RX/TX Watermark.
1110          * If current block size is same with previous size,
1111          * no need to update fifoth.
1112          */
1113         if (host->prev_blksz != data->blksz)
1114                 dw_mci_adjust_fifoth(host, data);
1115
1116         /* Enable the DMA interface */
1117         temp = mci_readl(host, CTRL);
1118         temp |= SDMMC_CTRL_DMA_ENABLE;
1119         mci_writel(host, CTRL, temp);
1120
1121         /* Disable RX/TX IRQs, let DMA handle it */
1122         spin_lock_irqsave(&host->irq_lock, irqflags);
1123         temp = mci_readl(host, INTMASK);
1124         temp  &= ~(SDMMC_INT_RXDR | SDMMC_INT_TXDR);
1125         mci_writel(host, INTMASK, temp);
1126         spin_unlock_irqrestore(&host->irq_lock, irqflags);
1127
1128         if (host->dma_ops->start(host, sg_len)) {
1129                 host->dma_ops->stop(host);
1130                 /* We can't do DMA, try PIO for this one */
1131                 dev_dbg(host->dev,
1132                         "%s: fall back to PIO mode for current transfer\n",
1133                         __func__);
1134                 return -ENODEV;
1135         }
1136
1137         return 0;
1138 }
1139
1140 static void dw_mci_submit_data(struct dw_mci *host, struct mmc_data *data)
1141 {
1142         unsigned long irqflags;
1143         int flags = SG_MITER_ATOMIC;
1144         u32 temp;
1145
1146         data->error = -EINPROGRESS;
1147
1148         WARN_ON(host->data);
1149         host->sg = NULL;
1150         host->data = data;
1151
1152         if (data->flags & MMC_DATA_READ)
1153                 host->dir_status = DW_MCI_RECV_STATUS;
1154         else
1155                 host->dir_status = DW_MCI_SEND_STATUS;
1156
1157         dw_mci_ctrl_thld(host, data);
1158
1159         if (dw_mci_submit_data_dma(host, data)) {
1160                 if (host->data->flags & MMC_DATA_READ)
1161                         flags |= SG_MITER_TO_SG;
1162                 else
1163                         flags |= SG_MITER_FROM_SG;
1164
1165                 sg_miter_start(&host->sg_miter, data->sg, data->sg_len, flags);
1166                 host->sg = data->sg;
1167                 host->part_buf_start = 0;
1168                 host->part_buf_count = 0;
1169
1170                 mci_writel(host, RINTSTS, SDMMC_INT_TXDR | SDMMC_INT_RXDR);
1171
1172                 spin_lock_irqsave(&host->irq_lock, irqflags);
1173                 temp = mci_readl(host, INTMASK);
1174                 temp |= SDMMC_INT_TXDR | SDMMC_INT_RXDR;
1175                 mci_writel(host, INTMASK, temp);
1176                 spin_unlock_irqrestore(&host->irq_lock, irqflags);
1177
1178                 temp = mci_readl(host, CTRL);
1179                 temp &= ~SDMMC_CTRL_DMA_ENABLE;
1180                 mci_writel(host, CTRL, temp);
1181
1182                 /*
1183                  * Use the initial fifoth_val for PIO mode. If wm_algined
1184                  * is set, we set watermark same as data size.
1185                  * If next issued data may be transfered by DMA mode,
1186                  * prev_blksz should be invalidated.
1187                  */
1188                 if (host->wm_aligned)
1189                         dw_mci_adjust_fifoth(host, data);
1190                 else
1191                         mci_writel(host, FIFOTH, host->fifoth_val);
1192                 host->prev_blksz = 0;
1193         } else {
1194                 /*
1195                  * Keep the current block size.
1196                  * It will be used to decide whether to update
1197                  * fifoth register next time.
1198                  */
1199                 host->prev_blksz = data->blksz;
1200         }
1201 }
1202
1203 static void dw_mci_setup_bus(struct dw_mci_slot *slot, bool force_clkinit)
1204 {
1205         struct dw_mci *host = slot->host;
1206         unsigned int clock = slot->clock;
1207         u32 div;
1208         u32 clk_en_a;
1209         u32 sdmmc_cmd_bits = SDMMC_CMD_UPD_CLK | SDMMC_CMD_PRV_DAT_WAIT;
1210
1211         /* We must continue to set bit 28 in CMD until the change is complete */
1212         if (host->state == STATE_WAITING_CMD11_DONE)
1213                 sdmmc_cmd_bits |= SDMMC_CMD_VOLT_SWITCH;
1214
1215         slot->mmc->actual_clock = 0;
1216
1217         if (!clock) {
1218                 mci_writel(host, CLKENA, 0);
1219                 mci_send_cmd(slot, sdmmc_cmd_bits, 0);
1220         } else if (clock != host->current_speed || force_clkinit) {
1221                 div = host->bus_hz / clock;
1222                 if (host->bus_hz % clock && host->bus_hz > clock)
1223                         /*
1224                          * move the + 1 after the divide to prevent
1225                          * over-clocking the card.
1226                          */
1227                         div += 1;
1228
1229                 div = (host->bus_hz != clock) ? DIV_ROUND_UP(div, 2) : 0;
1230
1231                 if ((clock != slot->__clk_old &&
1232                         !test_bit(DW_MMC_CARD_NEEDS_POLL, &slot->flags)) ||
1233                         force_clkinit) {
1234                         /* Silent the verbose log if calling from PM context */
1235                         if (!force_clkinit)
1236                                 dev_info(&slot->mmc->class_dev,
1237                                          "Bus speed (slot %d) = %dHz (slot req %dHz, actual %dHZ div = %d)\n",
1238                                          slot->id, host->bus_hz, clock,
1239                                          div ? ((host->bus_hz / div) >> 1) :
1240                                          host->bus_hz, div);
1241
1242                         /*
1243                          * If card is polling, display the message only
1244                          * one time at boot time.
1245                          */
1246                         if (slot->mmc->caps & MMC_CAP_NEEDS_POLL &&
1247                                         slot->mmc->f_min == clock)
1248                                 set_bit(DW_MMC_CARD_NEEDS_POLL, &slot->flags);
1249                 }
1250
1251                 /* disable clock */
1252                 mci_writel(host, CLKENA, 0);
1253                 mci_writel(host, CLKSRC, 0);
1254
1255                 /* inform CIU */
1256                 mci_send_cmd(slot, sdmmc_cmd_bits, 0);
1257
1258                 /* set clock to desired speed */
1259                 mci_writel(host, CLKDIV, div);
1260
1261                 /* inform CIU */
1262                 mci_send_cmd(slot, sdmmc_cmd_bits, 0);
1263
1264                 /* enable clock; only low power if no SDIO */
1265                 clk_en_a = SDMMC_CLKEN_ENABLE << slot->id;
1266                 if (!test_bit(DW_MMC_CARD_NO_LOW_PWR, &slot->flags))
1267                         clk_en_a |= SDMMC_CLKEN_LOW_PWR << slot->id;
1268                 mci_writel(host, CLKENA, clk_en_a);
1269
1270                 /* inform CIU */
1271                 mci_send_cmd(slot, sdmmc_cmd_bits, 0);
1272
1273                 /* keep the last clock value that was requested from core */
1274                 slot->__clk_old = clock;
1275                 slot->mmc->actual_clock = div ? ((host->bus_hz / div) >> 1) :
1276                                           host->bus_hz;
1277         }
1278
1279         host->current_speed = clock;
1280
1281         /* Set the current slot bus width */
1282         mci_writel(host, CTYPE, (slot->ctype << slot->id));
1283 }
1284
1285 static void __dw_mci_start_request(struct dw_mci *host,
1286                                    struct dw_mci_slot *slot,
1287                                    struct mmc_command *cmd)
1288 {
1289         struct mmc_request *mrq;
1290         struct mmc_data *data;
1291         u32 cmdflags;
1292
1293         mrq = slot->mrq;
1294
1295         host->mrq = mrq;
1296
1297         host->pending_events = 0;
1298         host->completed_events = 0;
1299         host->cmd_status = 0;
1300         host->data_status = 0;
1301         host->dir_status = 0;
1302
1303         data = cmd->data;
1304         if (data) {
1305                 mci_writel(host, TMOUT, 0xFFFFFFFF);
1306                 mci_writel(host, BYTCNT, data->blksz*data->blocks);
1307                 mci_writel(host, BLKSIZ, data->blksz);
1308         }
1309
1310         cmdflags = dw_mci_prepare_command(slot->mmc, cmd);
1311
1312         /* this is the first command, send the initialization clock */
1313         if (test_and_clear_bit(DW_MMC_CARD_NEED_INIT, &slot->flags))
1314                 cmdflags |= SDMMC_CMD_INIT;
1315
1316         if (data) {
1317                 dw_mci_submit_data(host, data);
1318                 wmb(); /* drain writebuffer */
1319         }
1320
1321         dw_mci_start_command(host, cmd, cmdflags);
1322
1323         if (cmd->opcode == SD_SWITCH_VOLTAGE) {
1324                 unsigned long irqflags;
1325
1326                 /*
1327                  * Databook says to fail after 2ms w/ no response, but evidence
1328                  * shows that sometimes the cmd11 interrupt takes over 130ms.
1329                  * We'll set to 500ms, plus an extra jiffy just in case jiffies
1330                  * is just about to roll over.
1331                  *
1332                  * We do this whole thing under spinlock and only if the
1333                  * command hasn't already completed (indicating the the irq
1334                  * already ran so we don't want the timeout).
1335                  */
1336                 spin_lock_irqsave(&host->irq_lock, irqflags);
1337                 if (!test_bit(EVENT_CMD_COMPLETE, &host->pending_events))
1338                         mod_timer(&host->cmd11_timer,
1339                                 jiffies + msecs_to_jiffies(500) + 1);
1340                 spin_unlock_irqrestore(&host->irq_lock, irqflags);
1341         }
1342
1343         host->stop_cmdr = dw_mci_prep_stop_abort(host, cmd);
1344 }
1345
1346 static void dw_mci_start_request(struct dw_mci *host,
1347                                  struct dw_mci_slot *slot)
1348 {
1349         struct mmc_request *mrq = slot->mrq;
1350         struct mmc_command *cmd;
1351
1352         cmd = mrq->sbc ? mrq->sbc : mrq->cmd;
1353         __dw_mci_start_request(host, slot, cmd);
1354 }
1355
1356 /* must be called with host->lock held */
1357 static void dw_mci_queue_request(struct dw_mci *host, struct dw_mci_slot *slot,
1358                                  struct mmc_request *mrq)
1359 {
1360         dev_vdbg(&slot->mmc->class_dev, "queue request: state=%d\n",
1361                  host->state);
1362
1363         slot->mrq = mrq;
1364
1365         if (host->state == STATE_WAITING_CMD11_DONE) {
1366                 dev_warn(&slot->mmc->class_dev,
1367                          "Voltage change didn't complete\n");
1368                 /*
1369                  * this case isn't expected to happen, so we can
1370                  * either crash here or just try to continue on
1371                  * in the closest possible state
1372                  */
1373                 host->state = STATE_IDLE;
1374         }
1375
1376         if (host->state == STATE_IDLE) {
1377                 host->state = STATE_SENDING_CMD;
1378                 dw_mci_start_request(host, slot);
1379         } else {
1380                 list_add_tail(&slot->queue_node, &host->queue);
1381         }
1382 }
1383
1384 static void dw_mci_request(struct mmc_host *mmc, struct mmc_request *mrq)
1385 {
1386         struct dw_mci_slot *slot = mmc_priv(mmc);
1387         struct dw_mci *host = slot->host;
1388
1389         WARN_ON(slot->mrq);
1390
1391         /*
1392          * The check for card presence and queueing of the request must be
1393          * atomic, otherwise the card could be removed in between and the
1394          * request wouldn't fail until another card was inserted.
1395          */
1396
1397         if (!dw_mci_get_cd(mmc)) {
1398                 mrq->cmd->error = -ENOMEDIUM;
1399                 mmc_request_done(mmc, mrq);
1400                 return;
1401         }
1402
1403         spin_lock_bh(&host->lock);
1404
1405         dw_mci_queue_request(host, slot, mrq);
1406
1407         spin_unlock_bh(&host->lock);
1408 }
1409
1410 static void dw_mci_set_ios(struct mmc_host *mmc, struct mmc_ios *ios)
1411 {
1412         struct dw_mci_slot *slot = mmc_priv(mmc);
1413         const struct dw_mci_drv_data *drv_data = slot->host->drv_data;
1414         u32 regs;
1415         int ret;
1416
1417         switch (ios->bus_width) {
1418         case MMC_BUS_WIDTH_4:
1419                 slot->ctype = SDMMC_CTYPE_4BIT;
1420                 break;
1421         case MMC_BUS_WIDTH_8:
1422                 slot->ctype = SDMMC_CTYPE_8BIT;
1423                 break;
1424         default:
1425                 /* set default 1 bit mode */
1426                 slot->ctype = SDMMC_CTYPE_1BIT;
1427         }
1428
1429         regs = mci_readl(slot->host, UHS_REG);
1430
1431         /* DDR mode set */
1432         if (ios->timing == MMC_TIMING_MMC_DDR52 ||
1433             ios->timing == MMC_TIMING_UHS_DDR50 ||
1434             ios->timing == MMC_TIMING_MMC_HS400)
1435                 regs |= ((0x1 << slot->id) << 16);
1436         else
1437                 regs &= ~((0x1 << slot->id) << 16);
1438
1439         mci_writel(slot->host, UHS_REG, regs);
1440         slot->host->timing = ios->timing;
1441
1442         /*
1443          * Use mirror of ios->clock to prevent race with mmc
1444          * core ios update when finding the minimum.
1445          */
1446         slot->clock = ios->clock;
1447
1448         if (drv_data && drv_data->set_ios)
1449                 drv_data->set_ios(slot->host, ios);
1450
1451         switch (ios->power_mode) {
1452         case MMC_POWER_UP:
1453                 if (!IS_ERR(mmc->supply.vmmc)) {
1454                         ret = mmc_regulator_set_ocr(mmc, mmc->supply.vmmc,
1455                                         ios->vdd);
1456                         if (ret) {
1457                                 dev_err(slot->host->dev,
1458                                         "failed to enable vmmc regulator\n");
1459                                 /*return, if failed turn on vmmc*/
1460                                 return;
1461                         }
1462                 }
1463                 set_bit(DW_MMC_CARD_NEED_INIT, &slot->flags);
1464                 regs = mci_readl(slot->host, PWREN);
1465                 regs |= (1 << slot->id);
1466                 mci_writel(slot->host, PWREN, regs);
1467                 break;
1468         case MMC_POWER_ON:
1469                 if (!slot->host->vqmmc_enabled) {
1470                         if (!IS_ERR(mmc->supply.vqmmc)) {
1471                                 ret = regulator_enable(mmc->supply.vqmmc);
1472                                 if (ret < 0)
1473                                         dev_err(slot->host->dev,
1474                                                 "failed to enable vqmmc\n");
1475                                 else
1476                                         slot->host->vqmmc_enabled = true;
1477
1478                         } else {
1479                                 /* Keep track so we don't reset again */
1480                                 slot->host->vqmmc_enabled = true;
1481                         }
1482
1483                         /* Reset our state machine after powering on */
1484                         dw_mci_ctrl_reset(slot->host,
1485                                           SDMMC_CTRL_ALL_RESET_FLAGS);
1486                 }
1487
1488                 /* Adjust clock / bus width after power is up */
1489                 dw_mci_setup_bus(slot, false);
1490
1491                 break;
1492         case MMC_POWER_OFF:
1493                 /* Turn clock off before power goes down */
1494                 dw_mci_setup_bus(slot, false);
1495
1496                 if (!IS_ERR(mmc->supply.vmmc))
1497                         mmc_regulator_set_ocr(mmc, mmc->supply.vmmc, 0);
1498
1499                 if (!IS_ERR(mmc->supply.vqmmc) && slot->host->vqmmc_enabled)
1500                         regulator_disable(mmc->supply.vqmmc);
1501                 slot->host->vqmmc_enabled = false;
1502
1503                 regs = mci_readl(slot->host, PWREN);
1504                 regs &= ~(1 << slot->id);
1505                 mci_writel(slot->host, PWREN, regs);
1506                 break;
1507         default:
1508                 break;
1509         }
1510
1511         if (slot->host->state == STATE_WAITING_CMD11_DONE && ios->clock != 0)
1512                 slot->host->state = STATE_IDLE;
1513 }
1514
1515 static int dw_mci_card_busy(struct mmc_host *mmc)
1516 {
1517         struct dw_mci_slot *slot = mmc_priv(mmc);
1518         u32 status;
1519
1520         /*
1521          * Check the busy bit which is low when DAT[3:0]
1522          * (the data lines) are 0000
1523          */
1524         status = mci_readl(slot->host, STATUS);
1525
1526         return !!(status & SDMMC_STATUS_BUSY);
1527 }
1528
1529 static int dw_mci_switch_voltage(struct mmc_host *mmc, struct mmc_ios *ios)
1530 {
1531         struct dw_mci_slot *slot = mmc_priv(mmc);
1532         struct dw_mci *host = slot->host;
1533         const struct dw_mci_drv_data *drv_data = host->drv_data;
1534         u32 uhs;
1535         u32 v18 = SDMMC_UHS_18V << slot->id;
1536         int ret;
1537
1538         if (drv_data && drv_data->switch_voltage)
1539                 return drv_data->switch_voltage(mmc, ios);
1540
1541         /*
1542          * Program the voltage.  Note that some instances of dw_mmc may use
1543          * the UHS_REG for this.  For other instances (like exynos) the UHS_REG
1544          * does no harm but you need to set the regulator directly.  Try both.
1545          */
1546         uhs = mci_readl(host, UHS_REG);
1547         if (ios->signal_voltage == MMC_SIGNAL_VOLTAGE_330)
1548                 uhs &= ~v18;
1549         else
1550                 uhs |= v18;
1551
1552         if (!IS_ERR(mmc->supply.vqmmc)) {
1553                 ret = mmc_regulator_set_vqmmc(mmc, ios);
1554                 if (ret < 0) {
1555                         dev_dbg(&mmc->class_dev,
1556                                          "Regulator set error %d - %s V\n",
1557                                          ret, uhs & v18 ? "1.8" : "3.3");
1558                         return ret;
1559                 }
1560         }
1561         mci_writel(host, UHS_REG, uhs);
1562
1563         return 0;
1564 }
1565
1566 static int dw_mci_get_ro(struct mmc_host *mmc)
1567 {
1568         int read_only;
1569         struct dw_mci_slot *slot = mmc_priv(mmc);
1570         int gpio_ro = mmc_gpio_get_ro(mmc);
1571
1572         /* Use platform get_ro function, else try on board write protect */
1573         if (gpio_ro >= 0)
1574                 read_only = gpio_ro;
1575         else
1576                 read_only =
1577                         mci_readl(slot->host, WRTPRT) & (1 << slot->id) ? 1 : 0;
1578
1579         dev_dbg(&mmc->class_dev, "card is %s\n",
1580                 read_only ? "read-only" : "read-write");
1581
1582         return read_only;
1583 }
1584
1585 static void dw_mci_hw_reset(struct mmc_host *mmc)
1586 {
1587         struct dw_mci_slot *slot = mmc_priv(mmc);
1588         struct dw_mci *host = slot->host;
1589         int reset;
1590
1591         if (host->use_dma == TRANS_MODE_IDMAC)
1592                 dw_mci_idmac_reset(host);
1593
1594         if (!dw_mci_ctrl_reset(host, SDMMC_CTRL_DMA_RESET |
1595                                      SDMMC_CTRL_FIFO_RESET))
1596                 return;
1597
1598         /*
1599          * According to eMMC spec, card reset procedure:
1600          * tRstW >= 1us:   RST_n pulse width
1601          * tRSCA >= 200us: RST_n to Command time
1602          * tRSTH >= 1us:   RST_n high period
1603          */
1604         reset = mci_readl(host, RST_N);
1605         reset &= ~(SDMMC_RST_HWACTIVE << slot->id);
1606         mci_writel(host, RST_N, reset);
1607         usleep_range(1, 2);
1608         reset |= SDMMC_RST_HWACTIVE << slot->id;
1609         mci_writel(host, RST_N, reset);
1610         usleep_range(200, 300);
1611 }
1612
1613 static void dw_mci_init_card(struct mmc_host *mmc, struct mmc_card *card)
1614 {
1615         struct dw_mci_slot *slot = mmc_priv(mmc);
1616         struct dw_mci *host = slot->host;
1617
1618         /*
1619          * Low power mode will stop the card clock when idle.  According to the
1620          * description of the CLKENA register we should disable low power mode
1621          * for SDIO cards if we need SDIO interrupts to work.
1622          */
1623         if (mmc->caps & MMC_CAP_SDIO_IRQ) {
1624                 const u32 clken_low_pwr = SDMMC_CLKEN_LOW_PWR << slot->id;
1625                 u32 clk_en_a_old;
1626                 u32 clk_en_a;
1627
1628                 clk_en_a_old = mci_readl(host, CLKENA);
1629
1630                 if (card->type == MMC_TYPE_SDIO ||
1631                     card->type == MMC_TYPE_SD_COMBO) {
1632                         set_bit(DW_MMC_CARD_NO_LOW_PWR, &slot->flags);
1633                         clk_en_a = clk_en_a_old & ~clken_low_pwr;
1634                 } else {
1635                         clear_bit(DW_MMC_CARD_NO_LOW_PWR, &slot->flags);
1636                         clk_en_a = clk_en_a_old | clken_low_pwr;
1637                 }
1638
1639                 if (clk_en_a != clk_en_a_old) {
1640                         mci_writel(host, CLKENA, clk_en_a);
1641                         mci_send_cmd(slot, SDMMC_CMD_UPD_CLK |
1642                                      SDMMC_CMD_PRV_DAT_WAIT, 0);
1643                 }
1644         }
1645 }
1646
1647 static void __dw_mci_enable_sdio_irq(struct dw_mci_slot *slot, int enb)
1648 {
1649         struct dw_mci *host = slot->host;
1650         unsigned long irqflags;
1651         u32 int_mask;
1652
1653         spin_lock_irqsave(&host->irq_lock, irqflags);
1654
1655         /* Enable/disable Slot Specific SDIO interrupt */
1656         int_mask = mci_readl(host, INTMASK);
1657         if (enb)
1658                 int_mask |= SDMMC_INT_SDIO(slot->sdio_id);
1659         else
1660                 int_mask &= ~SDMMC_INT_SDIO(slot->sdio_id);
1661         mci_writel(host, INTMASK, int_mask);
1662
1663         spin_unlock_irqrestore(&host->irq_lock, irqflags);
1664 }
1665
1666 static void dw_mci_enable_sdio_irq(struct mmc_host *mmc, int enb)
1667 {
1668         struct dw_mci_slot *slot = mmc_priv(mmc);
1669         struct dw_mci *host = slot->host;
1670
1671         __dw_mci_enable_sdio_irq(slot, enb);
1672
1673         /* Avoid runtime suspending the device when SDIO IRQ is enabled */
1674         if (enb)
1675                 pm_runtime_get_noresume(host->dev);
1676         else
1677                 pm_runtime_put_noidle(host->dev);
1678 }
1679
1680 static void dw_mci_ack_sdio_irq(struct mmc_host *mmc)
1681 {
1682         struct dw_mci_slot *slot = mmc_priv(mmc);
1683
1684         __dw_mci_enable_sdio_irq(slot, 1);
1685 }
1686
1687 static int dw_mci_execute_tuning(struct mmc_host *mmc, u32 opcode)
1688 {
1689         struct dw_mci_slot *slot = mmc_priv(mmc);
1690         struct dw_mci *host = slot->host;
1691         const struct dw_mci_drv_data *drv_data = host->drv_data;
1692         int err = -EINVAL;
1693
1694         if (drv_data && drv_data->execute_tuning)
1695                 err = drv_data->execute_tuning(slot, opcode);
1696         return err;
1697 }
1698
1699 static int dw_mci_prepare_hs400_tuning(struct mmc_host *mmc,
1700                                        struct mmc_ios *ios)
1701 {
1702         struct dw_mci_slot *slot = mmc_priv(mmc);
1703         struct dw_mci *host = slot->host;
1704         const struct dw_mci_drv_data *drv_data = host->drv_data;
1705
1706         if (drv_data && drv_data->prepare_hs400_tuning)
1707                 return drv_data->prepare_hs400_tuning(host, ios);
1708
1709         return 0;
1710 }
1711
1712 static bool dw_mci_reset(struct dw_mci *host)
1713 {
1714         u32 flags = SDMMC_CTRL_RESET | SDMMC_CTRL_FIFO_RESET;
1715         bool ret = false;
1716         u32 status = 0;
1717
1718         /*
1719          * Resetting generates a block interrupt, hence setting
1720          * the scatter-gather pointer to NULL.
1721          */
1722         if (host->sg) {
1723                 sg_miter_stop(&host->sg_miter);
1724                 host->sg = NULL;
1725         }
1726
1727         if (host->use_dma)
1728                 flags |= SDMMC_CTRL_DMA_RESET;
1729
1730         if (dw_mci_ctrl_reset(host, flags)) {
1731                 /*
1732                  * In all cases we clear the RAWINTS
1733                  * register to clear any interrupts.
1734                  */
1735                 mci_writel(host, RINTSTS, 0xFFFFFFFF);
1736
1737                 if (!host->use_dma) {
1738                         ret = true;
1739                         goto ciu_out;
1740                 }
1741
1742                 /* Wait for dma_req to be cleared */
1743                 if (readl_poll_timeout_atomic(host->regs + SDMMC_STATUS,
1744                                               status,
1745                                               !(status & SDMMC_STATUS_DMA_REQ),
1746                                               1, 500 * USEC_PER_MSEC)) {
1747                         dev_err(host->dev,
1748                                 "%s: Timeout waiting for dma_req to be cleared\n",
1749                                 __func__);
1750                         goto ciu_out;
1751                 }
1752
1753                 /* when using DMA next we reset the fifo again */
1754                 if (!dw_mci_ctrl_reset(host, SDMMC_CTRL_FIFO_RESET))
1755                         goto ciu_out;
1756         } else {
1757                 /* if the controller reset bit did clear, then set clock regs */
1758                 if (!(mci_readl(host, CTRL) & SDMMC_CTRL_RESET)) {
1759                         dev_err(host->dev,
1760                                 "%s: fifo/dma reset bits didn't clear but ciu was reset, doing clock update\n",
1761                                 __func__);
1762                         goto ciu_out;
1763                 }
1764         }
1765
1766         if (host->use_dma == TRANS_MODE_IDMAC)
1767                 /* It is also required that we reinit idmac */
1768                 dw_mci_idmac_init(host);
1769
1770         ret = true;
1771
1772 ciu_out:
1773         /* After a CTRL reset we need to have CIU set clock registers  */
1774         mci_send_cmd(host->slot, SDMMC_CMD_UPD_CLK, 0);
1775
1776         return ret;
1777 }
1778
1779 static const struct mmc_host_ops dw_mci_ops = {
1780         .request                = dw_mci_request,
1781         .pre_req                = dw_mci_pre_req,
1782         .post_req               = dw_mci_post_req,
1783         .set_ios                = dw_mci_set_ios,
1784         .get_ro                 = dw_mci_get_ro,
1785         .get_cd                 = dw_mci_get_cd,
1786         .hw_reset               = dw_mci_hw_reset,
1787         .enable_sdio_irq        = dw_mci_enable_sdio_irq,
1788         .ack_sdio_irq           = dw_mci_ack_sdio_irq,
1789         .execute_tuning         = dw_mci_execute_tuning,
1790         .card_busy              = dw_mci_card_busy,
1791         .start_signal_voltage_switch = dw_mci_switch_voltage,
1792         .init_card              = dw_mci_init_card,
1793         .prepare_hs400_tuning   = dw_mci_prepare_hs400_tuning,
1794 };
1795
1796 #ifdef CONFIG_FAULT_INJECTION
1797 static enum hrtimer_restart dw_mci_fault_timer(struct hrtimer *t)
1798 {
1799         struct dw_mci *host = container_of(t, struct dw_mci, fault_timer);
1800         unsigned long flags;
1801
1802         spin_lock_irqsave(&host->irq_lock, flags);
1803
1804         if (!host->data_status)
1805                 host->data_status = SDMMC_INT_DCRC;
1806         set_bit(EVENT_DATA_ERROR, &host->pending_events);
1807         tasklet_schedule(&host->tasklet);
1808
1809         spin_unlock_irqrestore(&host->irq_lock, flags);
1810
1811         return HRTIMER_NORESTART;
1812 }
1813
1814 static void dw_mci_start_fault_timer(struct dw_mci *host)
1815 {
1816         struct mmc_data *data = host->data;
1817
1818         if (!data || data->blocks <= 1)
1819                 return;
1820
1821         if (!should_fail(&host->fail_data_crc, 1))
1822                 return;
1823
1824         /*
1825          * Try to inject the error at random points during the data transfer.
1826          */
1827         hrtimer_start(&host->fault_timer,
1828                       ms_to_ktime(prandom_u32() % 25),
1829                       HRTIMER_MODE_REL);
1830 }
1831
1832 static void dw_mci_stop_fault_timer(struct dw_mci *host)
1833 {
1834         hrtimer_cancel(&host->fault_timer);
1835 }
1836
1837 static void dw_mci_init_fault(struct dw_mci *host)
1838 {
1839         host->fail_data_crc = (struct fault_attr) FAULT_ATTR_INITIALIZER;
1840
1841         hrtimer_init(&host->fault_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1842         host->fault_timer.function = dw_mci_fault_timer;
1843 }
1844 #else
1845 static void dw_mci_init_fault(struct dw_mci *host)
1846 {
1847 }
1848
1849 static void dw_mci_start_fault_timer(struct dw_mci *host)
1850 {
1851 }
1852
1853 static void dw_mci_stop_fault_timer(struct dw_mci *host)
1854 {
1855 }
1856 #endif
1857
1858 static void dw_mci_request_end(struct dw_mci *host, struct mmc_request *mrq)
1859         __releases(&host->lock)
1860         __acquires(&host->lock)
1861 {
1862         struct dw_mci_slot *slot;
1863         struct mmc_host *prev_mmc = host->slot->mmc;
1864
1865         WARN_ON(host->cmd || host->data);
1866
1867         host->slot->mrq = NULL;
1868         host->mrq = NULL;
1869         if (!list_empty(&host->queue)) {
1870                 slot = list_entry(host->queue.next,
1871                                   struct dw_mci_slot, queue_node);
1872                 list_del(&slot->queue_node);
1873                 dev_vdbg(host->dev, "list not empty: %s is next\n",
1874                          mmc_hostname(slot->mmc));
1875                 host->state = STATE_SENDING_CMD;
1876                 dw_mci_start_request(host, slot);
1877         } else {
1878                 dev_vdbg(host->dev, "list empty\n");
1879
1880                 if (host->state == STATE_SENDING_CMD11)
1881                         host->state = STATE_WAITING_CMD11_DONE;
1882                 else
1883                         host->state = STATE_IDLE;
1884         }
1885
1886         spin_unlock(&host->lock);
1887         mmc_request_done(prev_mmc, mrq);
1888         spin_lock(&host->lock);
1889 }
1890
1891 static int dw_mci_command_complete(struct dw_mci *host, struct mmc_command *cmd)
1892 {
1893         u32 status = host->cmd_status;
1894
1895         host->cmd_status = 0;
1896
1897         /* Read the response from the card (up to 16 bytes) */
1898         if (cmd->flags & MMC_RSP_PRESENT) {
1899                 if (cmd->flags & MMC_RSP_136) {
1900                         cmd->resp[3] = mci_readl(host, RESP0);
1901                         cmd->resp[2] = mci_readl(host, RESP1);
1902                         cmd->resp[1] = mci_readl(host, RESP2);
1903                         cmd->resp[0] = mci_readl(host, RESP3);
1904                 } else {
1905                         cmd->resp[0] = mci_readl(host, RESP0);
1906                         cmd->resp[1] = 0;
1907                         cmd->resp[2] = 0;
1908                         cmd->resp[3] = 0;
1909                 }
1910         }
1911
1912         if (status & SDMMC_INT_RTO)
1913                 cmd->error = -ETIMEDOUT;
1914         else if ((cmd->flags & MMC_RSP_CRC) && (status & SDMMC_INT_RCRC))
1915                 cmd->error = -EILSEQ;
1916         else if (status & SDMMC_INT_RESP_ERR)
1917                 cmd->error = -EIO;
1918         else
1919                 cmd->error = 0;
1920
1921         return cmd->error;
1922 }
1923
1924 static int dw_mci_data_complete(struct dw_mci *host, struct mmc_data *data)
1925 {
1926         u32 status = host->data_status;
1927
1928         if (status & DW_MCI_DATA_ERROR_FLAGS) {
1929                 if (status & SDMMC_INT_DRTO) {
1930                         data->error = -ETIMEDOUT;
1931                 } else if (status & SDMMC_INT_DCRC) {
1932                         data->error = -EILSEQ;
1933                 } else if (status & SDMMC_INT_EBE) {
1934                         if (host->dir_status ==
1935                                 DW_MCI_SEND_STATUS) {
1936                                 /*
1937                                  * No data CRC status was returned.
1938                                  * The number of bytes transferred
1939                                  * will be exaggerated in PIO mode.
1940                                  */
1941                                 data->bytes_xfered = 0;
1942                                 data->error = -ETIMEDOUT;
1943                         } else if (host->dir_status ==
1944                                         DW_MCI_RECV_STATUS) {
1945                                 data->error = -EILSEQ;
1946                         }
1947                 } else {
1948                         /* SDMMC_INT_SBE is included */
1949                         data->error = -EILSEQ;
1950                 }
1951
1952                 dev_dbg(host->dev, "data error, status 0x%08x\n", status);
1953
1954                 /*
1955                  * After an error, there may be data lingering
1956                  * in the FIFO
1957                  */
1958                 dw_mci_reset(host);
1959         } else {
1960                 data->bytes_xfered = data->blocks * data->blksz;
1961                 data->error = 0;
1962         }
1963
1964         return data->error;
1965 }
1966
1967 static void dw_mci_set_drto(struct dw_mci *host)
1968 {
1969         unsigned int drto_clks;
1970         unsigned int drto_div;
1971         unsigned int drto_ms;
1972         unsigned long irqflags;
1973
1974         drto_clks = mci_readl(host, TMOUT) >> 8;
1975         drto_div = (mci_readl(host, CLKDIV) & 0xff) * 2;
1976         if (drto_div == 0)
1977                 drto_div = 1;
1978
1979         drto_ms = DIV_ROUND_UP_ULL((u64)MSEC_PER_SEC * drto_clks * drto_div,
1980                                    host->bus_hz);
1981
1982         /* add a bit spare time */
1983         drto_ms += 10;
1984
1985         spin_lock_irqsave(&host->irq_lock, irqflags);
1986         if (!test_bit(EVENT_DATA_COMPLETE, &host->pending_events))
1987                 mod_timer(&host->dto_timer,
1988                           jiffies + msecs_to_jiffies(drto_ms));
1989         spin_unlock_irqrestore(&host->irq_lock, irqflags);
1990 }
1991
1992 static bool dw_mci_clear_pending_cmd_complete(struct dw_mci *host)
1993 {
1994         if (!test_bit(EVENT_CMD_COMPLETE, &host->pending_events))
1995                 return false;
1996
1997         /*
1998          * Really be certain that the timer has stopped.  This is a bit of
1999          * paranoia and could only really happen if we had really bad
2000          * interrupt latency and the interrupt routine and timeout were
2001          * running concurrently so that the del_timer() in the interrupt
2002          * handler couldn't run.
2003          */
2004         WARN_ON(del_timer_sync(&host->cto_timer));
2005         clear_bit(EVENT_CMD_COMPLETE, &host->pending_events);
2006
2007         return true;
2008 }
2009
2010 static bool dw_mci_clear_pending_data_complete(struct dw_mci *host)
2011 {
2012         if (!test_bit(EVENT_DATA_COMPLETE, &host->pending_events))
2013                 return false;
2014
2015         /* Extra paranoia just like dw_mci_clear_pending_cmd_complete() */
2016         WARN_ON(del_timer_sync(&host->dto_timer));
2017         clear_bit(EVENT_DATA_COMPLETE, &host->pending_events);
2018
2019         return true;
2020 }
2021
2022 static void dw_mci_tasklet_func(struct tasklet_struct *t)
2023 {
2024         struct dw_mci *host = from_tasklet(host, t, tasklet);
2025         struct mmc_data *data;
2026         struct mmc_command *cmd;
2027         struct mmc_request *mrq;
2028         enum dw_mci_state state;
2029         enum dw_mci_state prev_state;
2030         unsigned int err;
2031
2032         spin_lock(&host->lock);
2033
2034         state = host->state;
2035         data = host->data;
2036         mrq = host->mrq;
2037
2038         do {
2039                 prev_state = state;
2040
2041                 switch (state) {
2042                 case STATE_IDLE:
2043                 case STATE_WAITING_CMD11_DONE:
2044                         break;
2045
2046                 case STATE_SENDING_CMD11:
2047                 case STATE_SENDING_CMD:
2048                         if (!dw_mci_clear_pending_cmd_complete(host))
2049                                 break;
2050
2051                         cmd = host->cmd;
2052                         host->cmd = NULL;
2053                         set_bit(EVENT_CMD_COMPLETE, &host->completed_events);
2054                         err = dw_mci_command_complete(host, cmd);
2055                         if (cmd == mrq->sbc && !err) {
2056                                 __dw_mci_start_request(host, host->slot,
2057                                                        mrq->cmd);
2058                                 goto unlock;
2059                         }
2060
2061                         if (cmd->data && err) {
2062                                 /*
2063                                  * During UHS tuning sequence, sending the stop
2064                                  * command after the response CRC error would
2065                                  * throw the system into a confused state
2066                                  * causing all future tuning phases to report
2067                                  * failure.
2068                                  *
2069                                  * In such case controller will move into a data
2070                                  * transfer state after a response error or
2071                                  * response CRC error. Let's let that finish
2072                                  * before trying to send a stop, so we'll go to
2073                                  * STATE_SENDING_DATA.
2074                                  *
2075                                  * Although letting the data transfer take place
2076                                  * will waste a bit of time (we already know
2077                                  * the command was bad), it can't cause any
2078                                  * errors since it's possible it would have
2079                                  * taken place anyway if this tasklet got
2080                                  * delayed. Allowing the transfer to take place
2081                                  * avoids races and keeps things simple.
2082                                  */
2083                                 if (err != -ETIMEDOUT) {
2084                                         state = STATE_SENDING_DATA;
2085                                         continue;
2086                                 }
2087
2088                                 send_stop_abort(host, data);
2089                                 dw_mci_stop_dma(host);
2090                                 state = STATE_SENDING_STOP;
2091                                 break;
2092                         }
2093
2094                         if (!cmd->data || err) {
2095                                 dw_mci_request_end(host, mrq);
2096                                 goto unlock;
2097                         }
2098
2099                         prev_state = state = STATE_SENDING_DATA;
2100                         fallthrough;
2101
2102                 case STATE_SENDING_DATA:
2103                         /*
2104                          * We could get a data error and never a transfer
2105                          * complete so we'd better check for it here.
2106                          *
2107                          * Note that we don't really care if we also got a
2108                          * transfer complete; stopping the DMA and sending an
2109                          * abort won't hurt.
2110                          */
2111                         if (test_and_clear_bit(EVENT_DATA_ERROR,
2112                                                &host->pending_events)) {
2113                                 if (!(host->data_status & (SDMMC_INT_DRTO |
2114                                                            SDMMC_INT_EBE)))
2115                                         send_stop_abort(host, data);
2116                                 dw_mci_stop_dma(host);
2117                                 state = STATE_DATA_ERROR;
2118                                 break;
2119                         }
2120
2121                         if (!test_and_clear_bit(EVENT_XFER_COMPLETE,
2122                                                 &host->pending_events)) {
2123                                 /*
2124                                  * If all data-related interrupts don't come
2125                                  * within the given time in reading data state.
2126                                  */
2127                                 if (host->dir_status == DW_MCI_RECV_STATUS)
2128                                         dw_mci_set_drto(host);
2129                                 break;
2130                         }
2131
2132                         set_bit(EVENT_XFER_COMPLETE, &host->completed_events);
2133
2134                         /*
2135                          * Handle an EVENT_DATA_ERROR that might have shown up
2136                          * before the transfer completed.  This might not have
2137                          * been caught by the check above because the interrupt
2138                          * could have gone off between the previous check and
2139                          * the check for transfer complete.
2140                          *
2141                          * Technically this ought not be needed assuming we
2142                          * get a DATA_COMPLETE eventually (we'll notice the
2143                          * error and end the request), but it shouldn't hurt.
2144                          *
2145                          * This has the advantage of sending the stop command.
2146                          */
2147                         if (test_and_clear_bit(EVENT_DATA_ERROR,
2148                                                &host->pending_events)) {
2149                                 if (!(host->data_status & (SDMMC_INT_DRTO |
2150                                                            SDMMC_INT_EBE)))
2151                                         send_stop_abort(host, data);
2152                                 dw_mci_stop_dma(host);
2153                                 state = STATE_DATA_ERROR;
2154                                 break;
2155                         }
2156                         prev_state = state = STATE_DATA_BUSY;
2157
2158                         fallthrough;
2159
2160                 case STATE_DATA_BUSY:
2161                         if (!dw_mci_clear_pending_data_complete(host)) {
2162                                 /*
2163                                  * If data error interrupt comes but data over
2164                                  * interrupt doesn't come within the given time.
2165                                  * in reading data state.
2166                                  */
2167                                 if (host->dir_status == DW_MCI_RECV_STATUS)
2168                                         dw_mci_set_drto(host);
2169                                 break;
2170                         }
2171
2172                         dw_mci_stop_fault_timer(host);
2173                         host->data = NULL;
2174                         set_bit(EVENT_DATA_COMPLETE, &host->completed_events);
2175                         err = dw_mci_data_complete(host, data);
2176
2177                         if (!err) {
2178                                 if (!data->stop || mrq->sbc) {
2179                                         if (mrq->sbc && data->stop)
2180                                                 data->stop->error = 0;
2181                                         dw_mci_request_end(host, mrq);
2182                                         goto unlock;
2183                                 }
2184
2185                                 /* stop command for open-ended transfer*/
2186                                 if (data->stop)
2187                                         send_stop_abort(host, data);
2188                         } else {
2189                                 /*
2190                                  * If we don't have a command complete now we'll
2191                                  * never get one since we just reset everything;
2192                                  * better end the request.
2193                                  *
2194                                  * If we do have a command complete we'll fall
2195                                  * through to the SENDING_STOP command and
2196                                  * everything will be peachy keen.
2197                                  */
2198                                 if (!test_bit(EVENT_CMD_COMPLETE,
2199                                               &host->pending_events)) {
2200                                         host->cmd = NULL;
2201                                         dw_mci_request_end(host, mrq);
2202                                         goto unlock;
2203                                 }
2204                         }
2205
2206                         /*
2207                          * If err has non-zero,
2208                          * stop-abort command has been already issued.
2209                          */
2210                         prev_state = state = STATE_SENDING_STOP;
2211
2212                         fallthrough;
2213
2214                 case STATE_SENDING_STOP:
2215                         if (!dw_mci_clear_pending_cmd_complete(host))
2216                                 break;
2217
2218                         /* CMD error in data command */
2219                         if (mrq->cmd->error && mrq->data)
2220                                 dw_mci_reset(host);
2221
2222                         dw_mci_stop_fault_timer(host);
2223                         host->cmd = NULL;
2224                         host->data = NULL;
2225
2226                         if (!mrq->sbc && mrq->stop)
2227                                 dw_mci_command_complete(host, mrq->stop);
2228                         else
2229                                 host->cmd_status = 0;
2230
2231                         dw_mci_request_end(host, mrq);
2232                         goto unlock;
2233
2234                 case STATE_DATA_ERROR:
2235                         if (!test_and_clear_bit(EVENT_XFER_COMPLETE,
2236                                                 &host->pending_events))
2237                                 break;
2238
2239                         state = STATE_DATA_BUSY;
2240                         break;
2241                 }
2242         } while (state != prev_state);
2243
2244         host->state = state;
2245 unlock:
2246         spin_unlock(&host->lock);
2247
2248 }
2249
2250 /* push final bytes to part_buf, only use during push */
2251 static void dw_mci_set_part_bytes(struct dw_mci *host, void *buf, int cnt)
2252 {
2253         memcpy((void *)&host->part_buf, buf, cnt);
2254         host->part_buf_count = cnt;
2255 }
2256
2257 /* append bytes to part_buf, only use during push */
2258 static int dw_mci_push_part_bytes(struct dw_mci *host, void *buf, int cnt)
2259 {
2260         cnt = min(cnt, (1 << host->data_shift) - host->part_buf_count);
2261         memcpy((void *)&host->part_buf + host->part_buf_count, buf, cnt);
2262         host->part_buf_count += cnt;
2263         return cnt;
2264 }
2265
2266 /* pull first bytes from part_buf, only use during pull */
2267 static int dw_mci_pull_part_bytes(struct dw_mci *host, void *buf, int cnt)
2268 {
2269         cnt = min_t(int, cnt, host->part_buf_count);
2270         if (cnt) {
2271                 memcpy(buf, (void *)&host->part_buf + host->part_buf_start,
2272                        cnt);
2273                 host->part_buf_count -= cnt;
2274                 host->part_buf_start += cnt;
2275         }
2276         return cnt;
2277 }
2278
2279 /* pull final bytes from the part_buf, assuming it's just been filled */
2280 static void dw_mci_pull_final_bytes(struct dw_mci *host, void *buf, int cnt)
2281 {
2282         memcpy(buf, &host->part_buf, cnt);
2283         host->part_buf_start = cnt;
2284         host->part_buf_count = (1 << host->data_shift) - cnt;
2285 }
2286
2287 static void dw_mci_push_data16(struct dw_mci *host, void *buf, int cnt)
2288 {
2289         struct mmc_data *data = host->data;
2290         int init_cnt = cnt;
2291
2292         /* try and push anything in the part_buf */
2293         if (unlikely(host->part_buf_count)) {
2294                 int len = dw_mci_push_part_bytes(host, buf, cnt);
2295
2296                 buf += len;
2297                 cnt -= len;
2298                 if (host->part_buf_count == 2) {
2299                         mci_fifo_writew(host->fifo_reg, host->part_buf16);
2300                         host->part_buf_count = 0;
2301                 }
2302         }
2303 #ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
2304         if (unlikely((unsigned long)buf & 0x1)) {
2305                 while (cnt >= 2) {
2306                         u16 aligned_buf[64];
2307                         int len = min(cnt & -2, (int)sizeof(aligned_buf));
2308                         int items = len >> 1;
2309                         int i;
2310                         /* memcpy from input buffer into aligned buffer */
2311                         memcpy(aligned_buf, buf, len);
2312                         buf += len;
2313                         cnt -= len;
2314                         /* push data from aligned buffer into fifo */
2315                         for (i = 0; i < items; ++i)
2316                                 mci_fifo_writew(host->fifo_reg, aligned_buf[i]);
2317                 }
2318         } else
2319 #endif
2320         {
2321                 u16 *pdata = buf;
2322
2323                 for (; cnt >= 2; cnt -= 2)
2324                         mci_fifo_writew(host->fifo_reg, *pdata++);
2325                 buf = pdata;
2326         }
2327         /* put anything remaining in the part_buf */
2328         if (cnt) {
2329                 dw_mci_set_part_bytes(host, buf, cnt);
2330                  /* Push data if we have reached the expected data length */
2331                 if ((data->bytes_xfered + init_cnt) ==
2332                     (data->blksz * data->blocks))
2333                         mci_fifo_writew(host->fifo_reg, host->part_buf16);
2334         }
2335 }
2336
2337 static void dw_mci_pull_data16(struct dw_mci *host, void *buf, int cnt)
2338 {
2339 #ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
2340         if (unlikely((unsigned long)buf & 0x1)) {
2341                 while (cnt >= 2) {
2342                         /* pull data from fifo into aligned buffer */
2343                         u16 aligned_buf[64];
2344                         int len = min(cnt & -2, (int)sizeof(aligned_buf));
2345                         int items = len >> 1;
2346                         int i;
2347
2348                         for (i = 0; i < items; ++i)
2349                                 aligned_buf[i] = mci_fifo_readw(host->fifo_reg);
2350                         /* memcpy from aligned buffer into output buffer */
2351                         memcpy(buf, aligned_buf, len);
2352                         buf += len;
2353                         cnt -= len;
2354                 }
2355         } else
2356 #endif
2357         {
2358                 u16 *pdata = buf;
2359
2360                 for (; cnt >= 2; cnt -= 2)
2361                         *pdata++ = mci_fifo_readw(host->fifo_reg);
2362                 buf = pdata;
2363         }
2364         if (cnt) {
2365                 host->part_buf16 = mci_fifo_readw(host->fifo_reg);
2366                 dw_mci_pull_final_bytes(host, buf, cnt);
2367         }
2368 }
2369
2370 static void dw_mci_push_data32(struct dw_mci *host, void *buf, int cnt)
2371 {
2372         struct mmc_data *data = host->data;
2373         int init_cnt = cnt;
2374
2375         /* try and push anything in the part_buf */
2376         if (unlikely(host->part_buf_count)) {
2377                 int len = dw_mci_push_part_bytes(host, buf, cnt);
2378
2379                 buf += len;
2380                 cnt -= len;
2381                 if (host->part_buf_count == 4) {
2382                         mci_fifo_writel(host->fifo_reg, host->part_buf32);
2383                         host->part_buf_count = 0;
2384                 }
2385         }
2386 #ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
2387         if (unlikely((unsigned long)buf & 0x3)) {
2388                 while (cnt >= 4) {
2389                         u32 aligned_buf[32];
2390                         int len = min(cnt & -4, (int)sizeof(aligned_buf));
2391                         int items = len >> 2;
2392                         int i;
2393                         /* memcpy from input buffer into aligned buffer */
2394                         memcpy(aligned_buf, buf, len);
2395                         buf += len;
2396                         cnt -= len;
2397                         /* push data from aligned buffer into fifo */
2398                         for (i = 0; i < items; ++i)
2399                                 mci_fifo_writel(host->fifo_reg, aligned_buf[i]);
2400                 }
2401         } else
2402 #endif
2403         {
2404                 u32 *pdata = buf;
2405
2406                 for (; cnt >= 4; cnt -= 4)
2407                         mci_fifo_writel(host->fifo_reg, *pdata++);
2408                 buf = pdata;
2409         }
2410         /* put anything remaining in the part_buf */
2411         if (cnt) {
2412                 dw_mci_set_part_bytes(host, buf, cnt);
2413                  /* Push data if we have reached the expected data length */
2414                 if ((data->bytes_xfered + init_cnt) ==
2415                     (data->blksz * data->blocks))
2416                         mci_fifo_writel(host->fifo_reg, host->part_buf32);
2417         }
2418 }
2419
2420 static void dw_mci_pull_data32(struct dw_mci *host, void *buf, int cnt)
2421 {
2422 #ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
2423         if (unlikely((unsigned long)buf & 0x3)) {
2424                 while (cnt >= 4) {
2425                         /* pull data from fifo into aligned buffer */
2426                         u32 aligned_buf[32];
2427                         int len = min(cnt & -4, (int)sizeof(aligned_buf));
2428                         int items = len >> 2;
2429                         int i;
2430
2431                         for (i = 0; i < items; ++i)
2432                                 aligned_buf[i] = mci_fifo_readl(host->fifo_reg);
2433                         /* memcpy from aligned buffer into output buffer */
2434                         memcpy(buf, aligned_buf, len);
2435                         buf += len;
2436                         cnt -= len;
2437                 }
2438         } else
2439 #endif
2440         {
2441                 u32 *pdata = buf;
2442
2443                 for (; cnt >= 4; cnt -= 4)
2444                         *pdata++ = mci_fifo_readl(host->fifo_reg);
2445                 buf = pdata;
2446         }
2447         if (cnt) {
2448                 host->part_buf32 = mci_fifo_readl(host->fifo_reg);
2449                 dw_mci_pull_final_bytes(host, buf, cnt);
2450         }
2451 }
2452
2453 static void dw_mci_push_data64(struct dw_mci *host, void *buf, int cnt)
2454 {
2455         struct mmc_data *data = host->data;
2456         int init_cnt = cnt;
2457
2458         /* try and push anything in the part_buf */
2459         if (unlikely(host->part_buf_count)) {
2460                 int len = dw_mci_push_part_bytes(host, buf, cnt);
2461
2462                 buf += len;
2463                 cnt -= len;
2464
2465                 if (host->part_buf_count == 8) {
2466                         mci_fifo_writeq(host->fifo_reg, host->part_buf);
2467                         host->part_buf_count = 0;
2468                 }
2469         }
2470 #ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
2471         if (unlikely((unsigned long)buf & 0x7)) {
2472                 while (cnt >= 8) {
2473                         u64 aligned_buf[16];
2474                         int len = min(cnt & -8, (int)sizeof(aligned_buf));
2475                         int items = len >> 3;
2476                         int i;
2477                         /* memcpy from input buffer into aligned buffer */
2478                         memcpy(aligned_buf, buf, len);
2479                         buf += len;
2480                         cnt -= len;
2481                         /* push data from aligned buffer into fifo */
2482                         for (i = 0; i < items; ++i)
2483                                 mci_fifo_writeq(host->fifo_reg, aligned_buf[i]);
2484                 }
2485         } else
2486 #endif
2487         {
2488                 u64 *pdata = buf;
2489
2490                 for (; cnt >= 8; cnt -= 8)
2491                         mci_fifo_writeq(host->fifo_reg, *pdata++);
2492                 buf = pdata;
2493         }
2494         /* put anything remaining in the part_buf */
2495         if (cnt) {
2496                 dw_mci_set_part_bytes(host, buf, cnt);
2497                 /* Push data if we have reached the expected data length */
2498                 if ((data->bytes_xfered + init_cnt) ==
2499                     (data->blksz * data->blocks))
2500                         mci_fifo_writeq(host->fifo_reg, host->part_buf);
2501         }
2502 }
2503
2504 static void dw_mci_pull_data64(struct dw_mci *host, void *buf, int cnt)
2505 {
2506 #ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
2507         if (unlikely((unsigned long)buf & 0x7)) {
2508                 while (cnt >= 8) {
2509                         /* pull data from fifo into aligned buffer */
2510                         u64 aligned_buf[16];
2511                         int len = min(cnt & -8, (int)sizeof(aligned_buf));
2512                         int items = len >> 3;
2513                         int i;
2514
2515                         for (i = 0; i < items; ++i)
2516                                 aligned_buf[i] = mci_fifo_readq(host->fifo_reg);
2517
2518                         /* memcpy from aligned buffer into output buffer */
2519                         memcpy(buf, aligned_buf, len);
2520                         buf += len;
2521                         cnt -= len;
2522                 }
2523         } else
2524 #endif
2525         {
2526                 u64 *pdata = buf;
2527
2528                 for (; cnt >= 8; cnt -= 8)
2529                         *pdata++ = mci_fifo_readq(host->fifo_reg);
2530                 buf = pdata;
2531         }
2532         if (cnt) {
2533                 host->part_buf = mci_fifo_readq(host->fifo_reg);
2534                 dw_mci_pull_final_bytes(host, buf, cnt);
2535         }
2536 }
2537
2538 static void dw_mci_pull_data(struct dw_mci *host, void *buf, int cnt)
2539 {
2540         int len;
2541
2542         /* get remaining partial bytes */
2543         len = dw_mci_pull_part_bytes(host, buf, cnt);
2544         if (unlikely(len == cnt))
2545                 return;
2546         buf += len;
2547         cnt -= len;
2548
2549         /* get the rest of the data */
2550         host->pull_data(host, buf, cnt);
2551 }
2552
2553 static void dw_mci_read_data_pio(struct dw_mci *host, bool dto)
2554 {
2555         struct sg_mapping_iter *sg_miter = &host->sg_miter;
2556         void *buf;
2557         unsigned int offset;
2558         struct mmc_data *data = host->data;
2559         int shift = host->data_shift;
2560         u32 status;
2561         unsigned int len;
2562         unsigned int remain, fcnt;
2563
2564         do {
2565                 if (!sg_miter_next(sg_miter))
2566                         goto done;
2567
2568                 host->sg = sg_miter->piter.sg;
2569                 buf = sg_miter->addr;
2570                 remain = sg_miter->length;
2571                 offset = 0;
2572
2573                 do {
2574                         fcnt = (SDMMC_GET_FCNT(mci_readl(host, STATUS))
2575                                         << shift) + host->part_buf_count;
2576                         len = min(remain, fcnt);
2577                         if (!len)
2578                                 break;
2579                         dw_mci_pull_data(host, (void *)(buf + offset), len);
2580                         data->bytes_xfered += len;
2581                         offset += len;
2582                         remain -= len;
2583                 } while (remain);
2584
2585                 sg_miter->consumed = offset;
2586                 status = mci_readl(host, MINTSTS);
2587                 mci_writel(host, RINTSTS, SDMMC_INT_RXDR);
2588         /* if the RXDR is ready read again */
2589         } while ((status & SDMMC_INT_RXDR) ||
2590                  (dto && SDMMC_GET_FCNT(mci_readl(host, STATUS))));
2591
2592         if (!remain) {
2593                 if (!sg_miter_next(sg_miter))
2594                         goto done;
2595                 sg_miter->consumed = 0;
2596         }
2597         sg_miter_stop(sg_miter);
2598         return;
2599
2600 done:
2601         sg_miter_stop(sg_miter);
2602         host->sg = NULL;
2603         smp_wmb(); /* drain writebuffer */
2604         set_bit(EVENT_XFER_COMPLETE, &host->pending_events);
2605 }
2606
2607 static void dw_mci_write_data_pio(struct dw_mci *host)
2608 {
2609         struct sg_mapping_iter *sg_miter = &host->sg_miter;
2610         void *buf;
2611         unsigned int offset;
2612         struct mmc_data *data = host->data;
2613         int shift = host->data_shift;
2614         u32 status;
2615         unsigned int len;
2616         unsigned int fifo_depth = host->fifo_depth;
2617         unsigned int remain, fcnt;
2618
2619         do {
2620                 if (!sg_miter_next(sg_miter))
2621                         goto done;
2622
2623                 host->sg = sg_miter->piter.sg;
2624                 buf = sg_miter->addr;
2625                 remain = sg_miter->length;
2626                 offset = 0;
2627
2628                 do {
2629                         fcnt = ((fifo_depth -
2630                                  SDMMC_GET_FCNT(mci_readl(host, STATUS)))
2631                                         << shift) - host->part_buf_count;
2632                         len = min(remain, fcnt);
2633                         if (!len)
2634                                 break;
2635                         host->push_data(host, (void *)(buf + offset), len);
2636                         data->bytes_xfered += len;
2637                         offset += len;
2638                         remain -= len;
2639                 } while (remain);
2640
2641                 sg_miter->consumed = offset;
2642                 status = mci_readl(host, MINTSTS);
2643                 mci_writel(host, RINTSTS, SDMMC_INT_TXDR);
2644         } while (status & SDMMC_INT_TXDR); /* if TXDR write again */
2645
2646         if (!remain) {
2647                 if (!sg_miter_next(sg_miter))
2648                         goto done;
2649                 sg_miter->consumed = 0;
2650         }
2651         sg_miter_stop(sg_miter);
2652         return;
2653
2654 done:
2655         sg_miter_stop(sg_miter);
2656         host->sg = NULL;
2657         smp_wmb(); /* drain writebuffer */
2658         set_bit(EVENT_XFER_COMPLETE, &host->pending_events);
2659 }
2660
2661 static void dw_mci_cmd_interrupt(struct dw_mci *host, u32 status)
2662 {
2663         del_timer(&host->cto_timer);
2664
2665         if (!host->cmd_status)
2666                 host->cmd_status = status;
2667
2668         smp_wmb(); /* drain writebuffer */
2669
2670         set_bit(EVENT_CMD_COMPLETE, &host->pending_events);
2671         tasklet_schedule(&host->tasklet);
2672
2673         dw_mci_start_fault_timer(host);
2674 }
2675
2676 static void dw_mci_handle_cd(struct dw_mci *host)
2677 {
2678         struct dw_mci_slot *slot = host->slot;
2679
2680         mmc_detect_change(slot->mmc,
2681                 msecs_to_jiffies(host->pdata->detect_delay_ms));
2682 }
2683
2684 static irqreturn_t dw_mci_interrupt(int irq, void *dev_id)
2685 {
2686         struct dw_mci *host = dev_id;
2687         u32 pending;
2688         struct dw_mci_slot *slot = host->slot;
2689
2690         pending = mci_readl(host, MINTSTS); /* read-only mask reg */
2691
2692         if (pending) {
2693                 /* Check volt switch first, since it can look like an error */
2694                 if ((host->state == STATE_SENDING_CMD11) &&
2695                     (pending & SDMMC_INT_VOLT_SWITCH)) {
2696                         mci_writel(host, RINTSTS, SDMMC_INT_VOLT_SWITCH);
2697                         pending &= ~SDMMC_INT_VOLT_SWITCH;
2698
2699                         /*
2700                          * Hold the lock; we know cmd11_timer can't be kicked
2701                          * off after the lock is released, so safe to delete.
2702                          */
2703                         spin_lock(&host->irq_lock);
2704                         dw_mci_cmd_interrupt(host, pending);
2705                         spin_unlock(&host->irq_lock);
2706
2707                         del_timer(&host->cmd11_timer);
2708                 }
2709
2710                 if (pending & DW_MCI_CMD_ERROR_FLAGS) {
2711                         spin_lock(&host->irq_lock);
2712
2713                         del_timer(&host->cto_timer);
2714                         mci_writel(host, RINTSTS, DW_MCI_CMD_ERROR_FLAGS);
2715                         host->cmd_status = pending;
2716                         smp_wmb(); /* drain writebuffer */
2717                         set_bit(EVENT_CMD_COMPLETE, &host->pending_events);
2718
2719                         spin_unlock(&host->irq_lock);
2720                 }
2721
2722                 if (pending & DW_MCI_DATA_ERROR_FLAGS) {
2723                         /* if there is an error report DATA_ERROR */
2724                         mci_writel(host, RINTSTS, DW_MCI_DATA_ERROR_FLAGS);
2725                         host->data_status = pending;
2726                         smp_wmb(); /* drain writebuffer */
2727                         set_bit(EVENT_DATA_ERROR, &host->pending_events);
2728                         tasklet_schedule(&host->tasklet);
2729                 }
2730
2731                 if (pending & SDMMC_INT_DATA_OVER) {
2732                         spin_lock(&host->irq_lock);
2733
2734                         del_timer(&host->dto_timer);
2735
2736                         mci_writel(host, RINTSTS, SDMMC_INT_DATA_OVER);
2737                         if (!host->data_status)
2738                                 host->data_status = pending;
2739                         smp_wmb(); /* drain writebuffer */
2740                         if (host->dir_status == DW_MCI_RECV_STATUS) {
2741                                 if (host->sg != NULL)
2742                                         dw_mci_read_data_pio(host, true);
2743                         }
2744                         set_bit(EVENT_DATA_COMPLETE, &host->pending_events);
2745                         tasklet_schedule(&host->tasklet);
2746
2747                         spin_unlock(&host->irq_lock);
2748                 }
2749
2750                 if (pending & SDMMC_INT_RXDR) {
2751                         mci_writel(host, RINTSTS, SDMMC_INT_RXDR);
2752                         if (host->dir_status == DW_MCI_RECV_STATUS && host->sg)
2753                                 dw_mci_read_data_pio(host, false);
2754                 }
2755
2756                 if (pending & SDMMC_INT_TXDR) {
2757                         mci_writel(host, RINTSTS, SDMMC_INT_TXDR);
2758                         if (host->dir_status == DW_MCI_SEND_STATUS && host->sg)
2759                                 dw_mci_write_data_pio(host);
2760                 }
2761
2762                 if (pending & SDMMC_INT_CMD_DONE) {
2763                         spin_lock(&host->irq_lock);
2764
2765                         mci_writel(host, RINTSTS, SDMMC_INT_CMD_DONE);
2766                         dw_mci_cmd_interrupt(host, pending);
2767
2768                         spin_unlock(&host->irq_lock);
2769                 }
2770
2771                 if (pending & SDMMC_INT_CD) {
2772                         mci_writel(host, RINTSTS, SDMMC_INT_CD);
2773                         dw_mci_handle_cd(host);
2774                 }
2775
2776                 if (pending & SDMMC_INT_SDIO(slot->sdio_id)) {
2777                         mci_writel(host, RINTSTS,
2778                                    SDMMC_INT_SDIO(slot->sdio_id));
2779                         __dw_mci_enable_sdio_irq(slot, 0);
2780                         sdio_signal_irq(slot->mmc);
2781                 }
2782
2783         }
2784
2785         if (host->use_dma != TRANS_MODE_IDMAC)
2786                 return IRQ_HANDLED;
2787
2788         /* Handle IDMA interrupts */
2789         if (host->dma_64bit_address == 1) {
2790                 pending = mci_readl(host, IDSTS64);
2791                 if (pending & (SDMMC_IDMAC_INT_TI | SDMMC_IDMAC_INT_RI)) {
2792                         mci_writel(host, IDSTS64, SDMMC_IDMAC_INT_TI |
2793                                                         SDMMC_IDMAC_INT_RI);
2794                         mci_writel(host, IDSTS64, SDMMC_IDMAC_INT_NI);
2795                         if (!test_bit(EVENT_DATA_ERROR, &host->pending_events))
2796                                 host->dma_ops->complete((void *)host);
2797                 }
2798         } else {
2799                 pending = mci_readl(host, IDSTS);
2800                 if (pending & (SDMMC_IDMAC_INT_TI | SDMMC_IDMAC_INT_RI)) {
2801                         mci_writel(host, IDSTS, SDMMC_IDMAC_INT_TI |
2802                                                         SDMMC_IDMAC_INT_RI);
2803                         mci_writel(host, IDSTS, SDMMC_IDMAC_INT_NI);
2804                         if (!test_bit(EVENT_DATA_ERROR, &host->pending_events))
2805                                 host->dma_ops->complete((void *)host);
2806                 }
2807         }
2808
2809         return IRQ_HANDLED;
2810 }
2811
2812 static int dw_mci_init_slot_caps(struct dw_mci_slot *slot)
2813 {
2814         struct dw_mci *host = slot->host;
2815         const struct dw_mci_drv_data *drv_data = host->drv_data;
2816         struct mmc_host *mmc = slot->mmc;
2817         int ctrl_id;
2818
2819         if (host->pdata->caps)
2820                 mmc->caps = host->pdata->caps;
2821
2822         if (host->pdata->pm_caps)
2823                 mmc->pm_caps = host->pdata->pm_caps;
2824
2825         if (host->dev->of_node) {
2826                 ctrl_id = of_alias_get_id(host->dev->of_node, "mshc");
2827                 if (ctrl_id < 0)
2828                         ctrl_id = 0;
2829         } else {
2830                 ctrl_id = to_platform_device(host->dev)->id;
2831         }
2832
2833         if (drv_data && drv_data->caps) {
2834                 if (ctrl_id >= drv_data->num_caps) {
2835                         dev_err(host->dev, "invalid controller id %d\n",
2836                                 ctrl_id);
2837                         return -EINVAL;
2838                 }
2839                 mmc->caps |= drv_data->caps[ctrl_id];
2840         }
2841
2842         if (host->pdata->caps2)
2843                 mmc->caps2 = host->pdata->caps2;
2844
2845         mmc->f_min = DW_MCI_FREQ_MIN;
2846         if (!mmc->f_max)
2847                 mmc->f_max = DW_MCI_FREQ_MAX;
2848
2849         /* Process SDIO IRQs through the sdio_irq_work. */
2850         if (mmc->caps & MMC_CAP_SDIO_IRQ)
2851                 mmc->caps2 |= MMC_CAP2_SDIO_IRQ_NOTHREAD;
2852
2853         return 0;
2854 }
2855
2856 static int dw_mci_init_slot(struct dw_mci *host)
2857 {
2858         struct mmc_host *mmc;
2859         struct dw_mci_slot *slot;
2860         int ret;
2861
2862         mmc = mmc_alloc_host(sizeof(struct dw_mci_slot), host->dev);
2863         if (!mmc)
2864                 return -ENOMEM;
2865
2866         slot = mmc_priv(mmc);
2867         slot->id = 0;
2868         slot->sdio_id = host->sdio_id0 + slot->id;
2869         slot->mmc = mmc;
2870         slot->host = host;
2871         host->slot = slot;
2872
2873         mmc->ops = &dw_mci_ops;
2874
2875         /*if there are external regulators, get them*/
2876         ret = mmc_regulator_get_supply(mmc);
2877         if (ret)
2878                 goto err_host_allocated;
2879
2880         if (!mmc->ocr_avail)
2881                 mmc->ocr_avail = MMC_VDD_32_33 | MMC_VDD_33_34;
2882
2883         ret = mmc_of_parse(mmc);
2884         if (ret)
2885                 goto err_host_allocated;
2886
2887         ret = dw_mci_init_slot_caps(slot);
2888         if (ret)
2889                 goto err_host_allocated;
2890
2891         /* Useful defaults if platform data is unset. */
2892         if (host->use_dma == TRANS_MODE_IDMAC) {
2893                 mmc->max_segs = host->ring_size;
2894                 mmc->max_blk_size = 65535;
2895                 mmc->max_seg_size = 0x1000;
2896                 mmc->max_req_size = mmc->max_seg_size * host->ring_size;
2897                 mmc->max_blk_count = mmc->max_req_size / 512;
2898         } else if (host->use_dma == TRANS_MODE_EDMAC) {
2899                 mmc->max_segs = 64;
2900                 mmc->max_blk_size = 65535;
2901                 mmc->max_blk_count = 65535;
2902                 mmc->max_req_size =
2903                                 mmc->max_blk_size * mmc->max_blk_count;
2904                 mmc->max_seg_size = mmc->max_req_size;
2905         } else {
2906                 /* TRANS_MODE_PIO */
2907                 mmc->max_segs = 64;
2908                 mmc->max_blk_size = 65535; /* BLKSIZ is 16 bits */
2909                 mmc->max_blk_count = 512;
2910                 mmc->max_req_size = mmc->max_blk_size *
2911                                     mmc->max_blk_count;
2912                 mmc->max_seg_size = mmc->max_req_size;
2913         }
2914
2915         dw_mci_get_cd(mmc);
2916
2917         ret = mmc_add_host(mmc);
2918         if (ret)
2919                 goto err_host_allocated;
2920
2921 #if defined(CONFIG_DEBUG_FS)
2922         dw_mci_init_debugfs(slot);
2923 #endif
2924
2925         return 0;
2926
2927 err_host_allocated:
2928         mmc_free_host(mmc);
2929         return ret;
2930 }
2931
2932 static void dw_mci_cleanup_slot(struct dw_mci_slot *slot)
2933 {
2934         /* Debugfs stuff is cleaned up by mmc core */
2935         mmc_remove_host(slot->mmc);
2936         slot->host->slot = NULL;
2937         mmc_free_host(slot->mmc);
2938 }
2939
2940 static void dw_mci_init_dma(struct dw_mci *host)
2941 {
2942         int addr_config;
2943         struct device *dev = host->dev;
2944
2945         /*
2946         * Check tansfer mode from HCON[17:16]
2947         * Clear the ambiguous description of dw_mmc databook:
2948         * 2b'00: No DMA Interface -> Actually means using Internal DMA block
2949         * 2b'01: DesignWare DMA Interface -> Synopsys DW-DMA block
2950         * 2b'10: Generic DMA Interface -> non-Synopsys generic DMA block
2951         * 2b'11: Non DW DMA Interface -> pio only
2952         * Compared to DesignWare DMA Interface, Generic DMA Interface has a
2953         * simpler request/acknowledge handshake mechanism and both of them
2954         * are regarded as external dma master for dw_mmc.
2955         */
2956         host->use_dma = SDMMC_GET_TRANS_MODE(mci_readl(host, HCON));
2957         if (host->use_dma == DMA_INTERFACE_IDMA) {
2958                 host->use_dma = TRANS_MODE_IDMAC;
2959         } else if (host->use_dma == DMA_INTERFACE_DWDMA ||
2960                    host->use_dma == DMA_INTERFACE_GDMA) {
2961                 host->use_dma = TRANS_MODE_EDMAC;
2962         } else {
2963                 goto no_dma;
2964         }
2965
2966         /* Determine which DMA interface to use */
2967         if (host->use_dma == TRANS_MODE_IDMAC) {
2968                 /*
2969                 * Check ADDR_CONFIG bit in HCON to find
2970                 * IDMAC address bus width
2971                 */
2972                 addr_config = SDMMC_GET_ADDR_CONFIG(mci_readl(host, HCON));
2973
2974                 if (addr_config == 1) {
2975                         /* host supports IDMAC in 64-bit address mode */
2976                         host->dma_64bit_address = 1;
2977                         dev_info(host->dev,
2978                                  "IDMAC supports 64-bit address mode.\n");
2979                         if (!dma_set_mask(host->dev, DMA_BIT_MASK(64)))
2980                                 dma_set_coherent_mask(host->dev,
2981                                                       DMA_BIT_MASK(64));
2982                 } else {
2983                         /* host supports IDMAC in 32-bit address mode */
2984                         host->dma_64bit_address = 0;
2985                         dev_info(host->dev,
2986                                  "IDMAC supports 32-bit address mode.\n");
2987                 }
2988
2989                 /* Alloc memory for sg translation */
2990                 host->sg_cpu = dmam_alloc_coherent(host->dev,
2991                                                    DESC_RING_BUF_SZ,
2992                                                    &host->sg_dma, GFP_KERNEL);
2993                 if (!host->sg_cpu) {
2994                         dev_err(host->dev,
2995                                 "%s: could not alloc DMA memory\n",
2996                                 __func__);
2997                         goto no_dma;
2998                 }
2999
3000                 host->dma_ops = &dw_mci_idmac_ops;
3001                 dev_info(host->dev, "Using internal DMA controller.\n");
3002         } else {
3003                 /* TRANS_MODE_EDMAC: check dma bindings again */
3004                 if ((device_property_read_string_array(dev, "dma-names",
3005                                                        NULL, 0) < 0) ||
3006                     !device_property_present(dev, "dmas")) {
3007                         goto no_dma;
3008                 }
3009                 host->dma_ops = &dw_mci_edmac_ops;
3010                 dev_info(host->dev, "Using external DMA controller.\n");
3011         }
3012
3013         if (host->dma_ops->init && host->dma_ops->start &&
3014             host->dma_ops->stop && host->dma_ops->cleanup) {
3015                 if (host->dma_ops->init(host)) {
3016                         dev_err(host->dev, "%s: Unable to initialize DMA Controller.\n",
3017                                 __func__);
3018                         goto no_dma;
3019                 }
3020         } else {
3021                 dev_err(host->dev, "DMA initialization not found.\n");
3022                 goto no_dma;
3023         }
3024
3025         return;
3026
3027 no_dma:
3028         dev_info(host->dev, "Using PIO mode.\n");
3029         host->use_dma = TRANS_MODE_PIO;
3030 }
3031
3032 static void dw_mci_cmd11_timer(struct timer_list *t)
3033 {
3034         struct dw_mci *host = from_timer(host, t, cmd11_timer);
3035
3036         if (host->state != STATE_SENDING_CMD11) {
3037                 dev_warn(host->dev, "Unexpected CMD11 timeout\n");
3038                 return;
3039         }
3040
3041         host->cmd_status = SDMMC_INT_RTO;
3042         set_bit(EVENT_CMD_COMPLETE, &host->pending_events);
3043         tasklet_schedule(&host->tasklet);
3044 }
3045
3046 static void dw_mci_cto_timer(struct timer_list *t)
3047 {
3048         struct dw_mci *host = from_timer(host, t, cto_timer);
3049         unsigned long irqflags;
3050         u32 pending;
3051
3052         spin_lock_irqsave(&host->irq_lock, irqflags);
3053
3054         /*
3055          * If somehow we have very bad interrupt latency it's remotely possible
3056          * that the timer could fire while the interrupt is still pending or
3057          * while the interrupt is midway through running.  Let's be paranoid
3058          * and detect those two cases.  Note that this is paranoia is somewhat
3059          * justified because in this function we don't actually cancel the
3060          * pending command in the controller--we just assume it will never come.
3061          */
3062         pending = mci_readl(host, MINTSTS); /* read-only mask reg */
3063         if (pending & (DW_MCI_CMD_ERROR_FLAGS | SDMMC_INT_CMD_DONE)) {
3064                 /* The interrupt should fire; no need to act but we can warn */
3065                 dev_warn(host->dev, "Unexpected interrupt latency\n");
3066                 goto exit;
3067         }
3068         if (test_bit(EVENT_CMD_COMPLETE, &host->pending_events)) {
3069                 /* Presumably interrupt handler couldn't delete the timer */
3070                 dev_warn(host->dev, "CTO timeout when already completed\n");
3071                 goto exit;
3072         }
3073
3074         /*
3075          * Continued paranoia to make sure we're in the state we expect.
3076          * This paranoia isn't really justified but it seems good to be safe.
3077          */
3078         switch (host->state) {
3079         case STATE_SENDING_CMD11:
3080         case STATE_SENDING_CMD:
3081         case STATE_SENDING_STOP:
3082                 /*
3083                  * If CMD_DONE interrupt does NOT come in sending command
3084                  * state, we should notify the driver to terminate current
3085                  * transfer and report a command timeout to the core.
3086                  */
3087                 host->cmd_status = SDMMC_INT_RTO;
3088                 set_bit(EVENT_CMD_COMPLETE, &host->pending_events);
3089                 tasklet_schedule(&host->tasklet);
3090                 break;
3091         default:
3092                 dev_warn(host->dev, "Unexpected command timeout, state %d\n",
3093                          host->state);
3094                 break;
3095         }
3096
3097 exit:
3098         spin_unlock_irqrestore(&host->irq_lock, irqflags);
3099 }
3100
3101 static void dw_mci_dto_timer(struct timer_list *t)
3102 {
3103         struct dw_mci *host = from_timer(host, t, dto_timer);
3104         unsigned long irqflags;
3105         u32 pending;
3106
3107         spin_lock_irqsave(&host->irq_lock, irqflags);
3108
3109         /*
3110          * The DTO timer is much longer than the CTO timer, so it's even less
3111          * likely that we'll these cases, but it pays to be paranoid.
3112          */
3113         pending = mci_readl(host, MINTSTS); /* read-only mask reg */
3114         if (pending & SDMMC_INT_DATA_OVER) {
3115                 /* The interrupt should fire; no need to act but we can warn */
3116                 dev_warn(host->dev, "Unexpected data interrupt latency\n");
3117                 goto exit;
3118         }
3119         if (test_bit(EVENT_DATA_COMPLETE, &host->pending_events)) {
3120                 /* Presumably interrupt handler couldn't delete the timer */
3121                 dev_warn(host->dev, "DTO timeout when already completed\n");
3122                 goto exit;
3123         }
3124
3125         /*
3126          * Continued paranoia to make sure we're in the state we expect.
3127          * This paranoia isn't really justified but it seems good to be safe.
3128          */
3129         switch (host->state) {
3130         case STATE_SENDING_DATA:
3131         case STATE_DATA_BUSY:
3132                 /*
3133                  * If DTO interrupt does NOT come in sending data state,
3134                  * we should notify the driver to terminate current transfer
3135                  * and report a data timeout to the core.
3136                  */
3137                 host->data_status = SDMMC_INT_DRTO;
3138                 set_bit(EVENT_DATA_ERROR, &host->pending_events);
3139                 set_bit(EVENT_DATA_COMPLETE, &host->pending_events);
3140                 tasklet_schedule(&host->tasklet);
3141                 break;
3142         default:
3143                 dev_warn(host->dev, "Unexpected data timeout, state %d\n",
3144                          host->state);
3145                 break;
3146         }
3147
3148 exit:
3149         spin_unlock_irqrestore(&host->irq_lock, irqflags);
3150 }
3151
3152 #ifdef CONFIG_OF
3153 static struct dw_mci_board *dw_mci_parse_dt(struct dw_mci *host)
3154 {
3155         struct dw_mci_board *pdata;
3156         struct device *dev = host->dev;
3157         const struct dw_mci_drv_data *drv_data = host->drv_data;
3158         int ret;
3159         u32 clock_frequency;
3160
3161         pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL);
3162         if (!pdata)
3163                 return ERR_PTR(-ENOMEM);
3164
3165         /* find reset controller when exist */
3166         pdata->rstc = devm_reset_control_get_optional_exclusive(dev, "reset");
3167         if (IS_ERR(pdata->rstc))
3168                 return ERR_CAST(pdata->rstc);
3169
3170         if (device_property_read_u32(dev, "fifo-depth", &pdata->fifo_depth))
3171                 dev_info(dev,
3172                          "fifo-depth property not found, using value of FIFOTH register as default\n");
3173
3174         device_property_read_u32(dev, "card-detect-delay",
3175                                  &pdata->detect_delay_ms);
3176
3177         device_property_read_u32(dev, "data-addr", &host->data_addr_override);
3178
3179         if (device_property_present(dev, "fifo-watermark-aligned"))
3180                 host->wm_aligned = true;
3181
3182         if (!device_property_read_u32(dev, "clock-frequency", &clock_frequency))
3183                 pdata->bus_hz = clock_frequency;
3184
3185         if (drv_data && drv_data->parse_dt) {
3186                 ret = drv_data->parse_dt(host);
3187                 if (ret)
3188                         return ERR_PTR(ret);
3189         }
3190
3191         return pdata;
3192 }
3193
3194 #else /* CONFIG_OF */
3195 static struct dw_mci_board *dw_mci_parse_dt(struct dw_mci *host)
3196 {
3197         return ERR_PTR(-EINVAL);
3198 }
3199 #endif /* CONFIG_OF */
3200
3201 static void dw_mci_enable_cd(struct dw_mci *host)
3202 {
3203         unsigned long irqflags;
3204         u32 temp;
3205
3206         /*
3207          * No need for CD if all slots have a non-error GPIO
3208          * as well as broken card detection is found.
3209          */
3210         if (host->slot->mmc->caps & MMC_CAP_NEEDS_POLL)
3211                 return;
3212
3213         if (mmc_gpio_get_cd(host->slot->mmc) < 0) {
3214                 spin_lock_irqsave(&host->irq_lock, irqflags);
3215                 temp = mci_readl(host, INTMASK);
3216                 temp  |= SDMMC_INT_CD;
3217                 mci_writel(host, INTMASK, temp);
3218                 spin_unlock_irqrestore(&host->irq_lock, irqflags);
3219         }
3220 }
3221
3222 int dw_mci_probe(struct dw_mci *host)
3223 {
3224         const struct dw_mci_drv_data *drv_data = host->drv_data;
3225         int width, i, ret = 0;
3226         u32 fifo_size;
3227
3228         if (!host->pdata) {
3229                 host->pdata = dw_mci_parse_dt(host);
3230                 if (IS_ERR(host->pdata))
3231                         return dev_err_probe(host->dev, PTR_ERR(host->pdata),
3232                                              "platform data not available\n");
3233         }
3234
3235         host->biu_clk = devm_clk_get(host->dev, "biu");
3236         if (IS_ERR(host->biu_clk)) {
3237                 dev_dbg(host->dev, "biu clock not available\n");
3238         } else {
3239                 ret = clk_prepare_enable(host->biu_clk);
3240                 if (ret) {
3241                         dev_err(host->dev, "failed to enable biu clock\n");
3242                         return ret;
3243                 }
3244         }
3245
3246         host->ciu_clk = devm_clk_get(host->dev, "ciu");
3247         if (IS_ERR(host->ciu_clk)) {
3248                 dev_dbg(host->dev, "ciu clock not available\n");
3249                 host->bus_hz = host->pdata->bus_hz;
3250         } else {
3251                 ret = clk_prepare_enable(host->ciu_clk);
3252                 if (ret) {
3253                         dev_err(host->dev, "failed to enable ciu clock\n");
3254                         goto err_clk_biu;
3255                 }
3256
3257                 if (host->pdata->bus_hz) {
3258                         ret = clk_set_rate(host->ciu_clk, host->pdata->bus_hz);
3259                         if (ret)
3260                                 dev_warn(host->dev,
3261                                          "Unable to set bus rate to %uHz\n",
3262                                          host->pdata->bus_hz);
3263                 }
3264                 host->bus_hz = clk_get_rate(host->ciu_clk);
3265         }
3266
3267         if (!host->bus_hz) {
3268                 dev_err(host->dev,
3269                         "Platform data must supply bus speed\n");
3270                 ret = -ENODEV;
3271                 goto err_clk_ciu;
3272         }
3273
3274         if (host->pdata->rstc) {
3275                 reset_control_assert(host->pdata->rstc);
3276                 usleep_range(10, 50);
3277                 reset_control_deassert(host->pdata->rstc);
3278         }
3279
3280         if (drv_data && drv_data->init) {
3281                 ret = drv_data->init(host);
3282                 if (ret) {
3283                         dev_err(host->dev,
3284                                 "implementation specific init failed\n");
3285                         goto err_clk_ciu;
3286                 }
3287         }
3288
3289         timer_setup(&host->cmd11_timer, dw_mci_cmd11_timer, 0);
3290         timer_setup(&host->cto_timer, dw_mci_cto_timer, 0);
3291         timer_setup(&host->dto_timer, dw_mci_dto_timer, 0);
3292
3293         spin_lock_init(&host->lock);
3294         spin_lock_init(&host->irq_lock);
3295         INIT_LIST_HEAD(&host->queue);
3296
3297         dw_mci_init_fault(host);
3298
3299         /*
3300          * Get the host data width - this assumes that HCON has been set with
3301          * the correct values.
3302          */
3303         i = SDMMC_GET_HDATA_WIDTH(mci_readl(host, HCON));
3304         if (!i) {
3305                 host->push_data = dw_mci_push_data16;
3306                 host->pull_data = dw_mci_pull_data16;
3307                 width = 16;
3308                 host->data_shift = 1;
3309         } else if (i == 2) {
3310                 host->push_data = dw_mci_push_data64;
3311                 host->pull_data = dw_mci_pull_data64;
3312                 width = 64;
3313                 host->data_shift = 3;
3314         } else {
3315                 /* Check for a reserved value, and warn if it is */
3316                 WARN((i != 1),
3317                      "HCON reports a reserved host data width!\n"
3318                      "Defaulting to 32-bit access.\n");
3319                 host->push_data = dw_mci_push_data32;
3320                 host->pull_data = dw_mci_pull_data32;
3321                 width = 32;
3322                 host->data_shift = 2;
3323         }
3324
3325         /* Reset all blocks */
3326         if (!dw_mci_ctrl_reset(host, SDMMC_CTRL_ALL_RESET_FLAGS)) {
3327                 ret = -ENODEV;
3328                 goto err_clk_ciu;
3329         }
3330
3331         host->dma_ops = host->pdata->dma_ops;
3332         dw_mci_init_dma(host);
3333
3334         /* Clear the interrupts for the host controller */
3335         mci_writel(host, RINTSTS, 0xFFFFFFFF);
3336         mci_writel(host, INTMASK, 0); /* disable all mmc interrupt first */
3337
3338         /* Put in max timeout */
3339         mci_writel(host, TMOUT, 0xFFFFFFFF);
3340
3341         /*
3342          * FIFO threshold settings  RxMark  = fifo_size / 2 - 1,
3343          *                          Tx Mark = fifo_size / 2 DMA Size = 8
3344          */
3345         if (!host->pdata->fifo_depth) {
3346                 /*
3347                  * Power-on value of RX_WMark is FIFO_DEPTH-1, but this may
3348                  * have been overwritten by the bootloader, just like we're
3349                  * about to do, so if you know the value for your hardware, you
3350                  * should put it in the platform data.
3351                  */
3352                 fifo_size = mci_readl(host, FIFOTH);
3353                 fifo_size = 1 + ((fifo_size >> 16) & 0xfff);
3354         } else {
3355                 fifo_size = host->pdata->fifo_depth;
3356         }
3357         host->fifo_depth = fifo_size;
3358         host->fifoth_val =
3359                 SDMMC_SET_FIFOTH(0x2, fifo_size / 2 - 1, fifo_size / 2);
3360         mci_writel(host, FIFOTH, host->fifoth_val);
3361
3362         /* disable clock to CIU */
3363         mci_writel(host, CLKENA, 0);
3364         mci_writel(host, CLKSRC, 0);
3365
3366         /*
3367          * In 2.40a spec, Data offset is changed.
3368          * Need to check the version-id and set data-offset for DATA register.
3369          */
3370         host->verid = SDMMC_GET_VERID(mci_readl(host, VERID));
3371         dev_info(host->dev, "Version ID is %04x\n", host->verid);
3372
3373         if (host->data_addr_override)
3374                 host->fifo_reg = host->regs + host->data_addr_override;
3375         else if (host->verid < DW_MMC_240A)
3376                 host->fifo_reg = host->regs + DATA_OFFSET;
3377         else
3378                 host->fifo_reg = host->regs + DATA_240A_OFFSET;
3379
3380         tasklet_setup(&host->tasklet, dw_mci_tasklet_func);
3381         ret = devm_request_irq(host->dev, host->irq, dw_mci_interrupt,
3382                                host->irq_flags, "dw-mci", host);
3383         if (ret)
3384                 goto err_dmaunmap;
3385
3386         /*
3387          * Enable interrupts for command done, data over, data empty,
3388          * receive ready and error such as transmit, receive timeout, crc error
3389          */
3390         mci_writel(host, INTMASK, SDMMC_INT_CMD_DONE | SDMMC_INT_DATA_OVER |
3391                    SDMMC_INT_TXDR | SDMMC_INT_RXDR |
3392                    DW_MCI_ERROR_FLAGS);
3393         /* Enable mci interrupt */
3394         mci_writel(host, CTRL, SDMMC_CTRL_INT_ENABLE);
3395
3396         dev_info(host->dev,
3397                  "DW MMC controller at irq %d,%d bit host data width,%u deep fifo\n",
3398                  host->irq, width, fifo_size);
3399
3400         /* We need at least one slot to succeed */
3401         ret = dw_mci_init_slot(host);
3402         if (ret) {
3403                 dev_dbg(host->dev, "slot %d init failed\n", i);
3404                 goto err_dmaunmap;
3405         }
3406
3407         /* Now that slots are all setup, we can enable card detect */
3408         dw_mci_enable_cd(host);
3409
3410         return 0;
3411
3412 err_dmaunmap:
3413         if (host->use_dma && host->dma_ops->exit)
3414                 host->dma_ops->exit(host);
3415
3416         reset_control_assert(host->pdata->rstc);
3417
3418 err_clk_ciu:
3419         clk_disable_unprepare(host->ciu_clk);
3420
3421 err_clk_biu:
3422         clk_disable_unprepare(host->biu_clk);
3423
3424         return ret;
3425 }
3426 EXPORT_SYMBOL(dw_mci_probe);
3427
3428 void dw_mci_remove(struct dw_mci *host)
3429 {
3430         dev_dbg(host->dev, "remove slot\n");
3431         if (host->slot)
3432                 dw_mci_cleanup_slot(host->slot);
3433
3434         mci_writel(host, RINTSTS, 0xFFFFFFFF);
3435         mci_writel(host, INTMASK, 0); /* disable all mmc interrupt first */
3436
3437         /* disable clock to CIU */
3438         mci_writel(host, CLKENA, 0);
3439         mci_writel(host, CLKSRC, 0);
3440
3441         if (host->use_dma && host->dma_ops->exit)
3442                 host->dma_ops->exit(host);
3443
3444         reset_control_assert(host->pdata->rstc);
3445
3446         clk_disable_unprepare(host->ciu_clk);
3447         clk_disable_unprepare(host->biu_clk);
3448 }
3449 EXPORT_SYMBOL(dw_mci_remove);
3450
3451
3452
3453 #ifdef CONFIG_PM
3454 int dw_mci_runtime_suspend(struct device *dev)
3455 {
3456         struct dw_mci *host = dev_get_drvdata(dev);
3457
3458         if (host->use_dma && host->dma_ops->exit)
3459                 host->dma_ops->exit(host);
3460
3461         clk_disable_unprepare(host->ciu_clk);
3462
3463         if (host->slot &&
3464             (mmc_can_gpio_cd(host->slot->mmc) ||
3465              !mmc_card_is_removable(host->slot->mmc)))
3466                 clk_disable_unprepare(host->biu_clk);
3467
3468         return 0;
3469 }
3470 EXPORT_SYMBOL(dw_mci_runtime_suspend);
3471
3472 int dw_mci_runtime_resume(struct device *dev)
3473 {
3474         int ret = 0;
3475         struct dw_mci *host = dev_get_drvdata(dev);
3476
3477         if (host->slot &&
3478             (mmc_can_gpio_cd(host->slot->mmc) ||
3479              !mmc_card_is_removable(host->slot->mmc))) {
3480                 ret = clk_prepare_enable(host->biu_clk);
3481                 if (ret)
3482                         return ret;
3483         }
3484
3485         ret = clk_prepare_enable(host->ciu_clk);
3486         if (ret)
3487                 goto err;
3488
3489         if (!dw_mci_ctrl_reset(host, SDMMC_CTRL_ALL_RESET_FLAGS)) {
3490                 clk_disable_unprepare(host->ciu_clk);
3491                 ret = -ENODEV;
3492                 goto err;
3493         }
3494
3495         if (host->use_dma && host->dma_ops->init)
3496                 host->dma_ops->init(host);
3497
3498         /*
3499          * Restore the initial value at FIFOTH register
3500          * And Invalidate the prev_blksz with zero
3501          */
3502         mci_writel(host, FIFOTH, host->fifoth_val);
3503         host->prev_blksz = 0;
3504
3505         /* Put in max timeout */
3506         mci_writel(host, TMOUT, 0xFFFFFFFF);
3507
3508         mci_writel(host, RINTSTS, 0xFFFFFFFF);
3509         mci_writel(host, INTMASK, SDMMC_INT_CMD_DONE | SDMMC_INT_DATA_OVER |
3510                    SDMMC_INT_TXDR | SDMMC_INT_RXDR |
3511                    DW_MCI_ERROR_FLAGS);
3512         mci_writel(host, CTRL, SDMMC_CTRL_INT_ENABLE);
3513
3514
3515         if (host->slot->mmc->pm_flags & MMC_PM_KEEP_POWER)
3516                 dw_mci_set_ios(host->slot->mmc, &host->slot->mmc->ios);
3517
3518         /* Force setup bus to guarantee available clock output */
3519         dw_mci_setup_bus(host->slot, true);
3520
3521         /* Re-enable SDIO interrupts. */
3522         if (sdio_irq_claimed(host->slot->mmc))
3523                 __dw_mci_enable_sdio_irq(host->slot, 1);
3524
3525         /* Now that slots are all setup, we can enable card detect */
3526         dw_mci_enable_cd(host);
3527
3528         return 0;
3529
3530 err:
3531         if (host->slot &&
3532             (mmc_can_gpio_cd(host->slot->mmc) ||
3533              !mmc_card_is_removable(host->slot->mmc)))
3534                 clk_disable_unprepare(host->biu_clk);
3535
3536         return ret;
3537 }
3538 EXPORT_SYMBOL(dw_mci_runtime_resume);
3539 #endif /* CONFIG_PM */
3540
3541 static int __init dw_mci_init(void)
3542 {
3543         pr_info("Synopsys Designware Multimedia Card Interface Driver\n");
3544         return 0;
3545 }
3546
3547 static void __exit dw_mci_exit(void)
3548 {
3549 }
3550
3551 module_init(dw_mci_init);
3552 module_exit(dw_mci_exit);
3553
3554 MODULE_DESCRIPTION("DW Multimedia Card Interface driver");
3555 MODULE_AUTHOR("NXP Semiconductor VietNam");
3556 MODULE_AUTHOR("Imagination Technologies Ltd");
3557 MODULE_LICENSE("GPL v2");