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