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