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