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