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