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