xref: /openbmc/linux/drivers/mmc/host/atmel-mci.c (revision 04d699c3)
1 /*
2  * Atmel MultiMedia Card Interface driver
3  *
4  * Copyright (C) 2004-2008 Atmel Corporation
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 as
8  * published by the Free Software Foundation.
9  */
10 #include <linux/blkdev.h>
11 #include <linux/clk.h>
12 #include <linux/debugfs.h>
13 #include <linux/device.h>
14 #include <linux/dmaengine.h>
15 #include <linux/dma-mapping.h>
16 #include <linux/err.h>
17 #include <linux/gpio.h>
18 #include <linux/init.h>
19 #include <linux/interrupt.h>
20 #include <linux/ioport.h>
21 #include <linux/module.h>
22 #include <linux/platform_device.h>
23 #include <linux/scatterlist.h>
24 #include <linux/seq_file.h>
25 #include <linux/stat.h>
26 
27 #include <linux/mmc/host.h>
28 #include <linux/atmel-mci.h>
29 
30 #include <asm/io.h>
31 #include <asm/unaligned.h>
32 
33 #include <mach/cpu.h>
34 #include <mach/board.h>
35 
36 #include "atmel-mci-regs.h"
37 
38 #define ATMCI_DATA_ERROR_FLAGS	(MCI_DCRCE | MCI_DTOE | MCI_OVRE | MCI_UNRE)
39 #define ATMCI_DMA_THRESHOLD	16
40 
41 enum {
42 	EVENT_CMD_COMPLETE = 0,
43 	EVENT_XFER_COMPLETE,
44 	EVENT_DATA_COMPLETE,
45 	EVENT_DATA_ERROR,
46 };
47 
48 enum atmel_mci_state {
49 	STATE_IDLE = 0,
50 	STATE_SENDING_CMD,
51 	STATE_SENDING_DATA,
52 	STATE_DATA_BUSY,
53 	STATE_SENDING_STOP,
54 	STATE_DATA_ERROR,
55 };
56 
57 struct atmel_mci_dma {
58 #ifdef CONFIG_MMC_ATMELMCI_DMA
59 	struct dma_chan			*chan;
60 	struct dma_async_tx_descriptor	*data_desc;
61 #endif
62 };
63 
64 /**
65  * struct atmel_mci - MMC controller state shared between all slots
66  * @lock: Spinlock protecting the queue and associated data.
67  * @regs: Pointer to MMIO registers.
68  * @sg: Scatterlist entry currently being processed by PIO code, if any.
69  * @pio_offset: Offset into the current scatterlist entry.
70  * @cur_slot: The slot which is currently using the controller.
71  * @mrq: The request currently being processed on @cur_slot,
72  *	or NULL if the controller is idle.
73  * @cmd: The command currently being sent to the card, or NULL.
74  * @data: The data currently being transferred, or NULL if no data
75  *	transfer is in progress.
76  * @dma: DMA client state.
77  * @data_chan: DMA channel being used for the current data transfer.
78  * @cmd_status: Snapshot of SR taken upon completion of the current
79  *	command. Only valid when EVENT_CMD_COMPLETE is pending.
80  * @data_status: Snapshot of SR taken upon completion of the current
81  *	data transfer. Only valid when EVENT_DATA_COMPLETE or
82  *	EVENT_DATA_ERROR is pending.
83  * @stop_cmdr: Value to be loaded into CMDR when the stop command is
84  *	to be sent.
85  * @tasklet: Tasklet running the request state machine.
86  * @pending_events: Bitmask of events flagged by the interrupt handler
87  *	to be processed by the tasklet.
88  * @completed_events: Bitmask of events which the state machine has
89  *	processed.
90  * @state: Tasklet state.
91  * @queue: List of slots waiting for access to the controller.
92  * @need_clock_update: Update the clock rate before the next request.
93  * @need_reset: Reset controller before next request.
94  * @mode_reg: Value of the MR register.
95  * @bus_hz: The rate of @mck in Hz. This forms the basis for MMC bus
96  *	rate and timeout calculations.
97  * @mapbase: Physical address of the MMIO registers.
98  * @mck: The peripheral bus clock hooked up to the MMC controller.
99  * @pdev: Platform device associated with the MMC controller.
100  * @slot: Slots sharing this MMC controller.
101  *
102  * Locking
103  * =======
104  *
105  * @lock is a softirq-safe spinlock protecting @queue as well as
106  * @cur_slot, @mrq and @state. These must always be updated
107  * at the same time while holding @lock.
108  *
109  * @lock also protects mode_reg and need_clock_update since these are
110  * used to synchronize mode register updates with the queue
111  * processing.
112  *
113  * The @mrq field of struct atmel_mci_slot is also protected by @lock,
114  * and must always be written at the same time as the slot is added to
115  * @queue.
116  *
117  * @pending_events and @completed_events are accessed using atomic bit
118  * operations, so they don't need any locking.
119  *
120  * None of the fields touched by the interrupt handler need any
121  * locking. However, ordering is important: Before EVENT_DATA_ERROR or
122  * EVENT_DATA_COMPLETE is set in @pending_events, all data-related
123  * interrupts must be disabled and @data_status updated with a
124  * snapshot of SR. Similarly, before EVENT_CMD_COMPLETE is set, the
125  * CMDRDY interupt must be disabled and @cmd_status updated with a
126  * snapshot of SR, and before EVENT_XFER_COMPLETE can be set, the
127  * bytes_xfered field of @data must be written. This is ensured by
128  * using barriers.
129  */
130 struct atmel_mci {
131 	spinlock_t		lock;
132 	void __iomem		*regs;
133 
134 	struct scatterlist	*sg;
135 	unsigned int		pio_offset;
136 
137 	struct atmel_mci_slot	*cur_slot;
138 	struct mmc_request	*mrq;
139 	struct mmc_command	*cmd;
140 	struct mmc_data		*data;
141 
142 	struct atmel_mci_dma	dma;
143 	struct dma_chan		*data_chan;
144 
145 	u32			cmd_status;
146 	u32			data_status;
147 	u32			stop_cmdr;
148 
149 	struct tasklet_struct	tasklet;
150 	unsigned long		pending_events;
151 	unsigned long		completed_events;
152 	enum atmel_mci_state	state;
153 	struct list_head	queue;
154 
155 	bool			need_clock_update;
156 	bool			need_reset;
157 	u32			mode_reg;
158 	unsigned long		bus_hz;
159 	unsigned long		mapbase;
160 	struct clk		*mck;
161 	struct platform_device	*pdev;
162 
163 	struct atmel_mci_slot	*slot[ATMEL_MCI_MAX_NR_SLOTS];
164 };
165 
166 /**
167  * struct atmel_mci_slot - MMC slot state
168  * @mmc: The mmc_host representing this slot.
169  * @host: The MMC controller this slot is using.
170  * @sdc_reg: Value of SDCR to be written before using this slot.
171  * @mrq: mmc_request currently being processed or waiting to be
172  *	processed, or NULL when the slot is idle.
173  * @queue_node: List node for placing this node in the @queue list of
174  *	&struct atmel_mci.
175  * @clock: Clock rate configured by set_ios(). Protected by host->lock.
176  * @flags: Random state bits associated with the slot.
177  * @detect_pin: GPIO pin used for card detection, or negative if not
178  *	available.
179  * @wp_pin: GPIO pin used for card write protect sending, or negative
180  *	if not available.
181  * @detect_is_active_high: The state of the detect pin when it is active.
182  * @detect_timer: Timer used for debouncing @detect_pin interrupts.
183  */
184 struct atmel_mci_slot {
185 	struct mmc_host		*mmc;
186 	struct atmel_mci	*host;
187 
188 	u32			sdc_reg;
189 
190 	struct mmc_request	*mrq;
191 	struct list_head	queue_node;
192 
193 	unsigned int		clock;
194 	unsigned long		flags;
195 #define ATMCI_CARD_PRESENT	0
196 #define ATMCI_CARD_NEED_INIT	1
197 #define ATMCI_SHUTDOWN		2
198 
199 	int			detect_pin;
200 	int			wp_pin;
201 	bool			detect_is_active_high;
202 
203 	struct timer_list	detect_timer;
204 };
205 
206 #define atmci_test_and_clear_pending(host, event)		\
207 	test_and_clear_bit(event, &host->pending_events)
208 #define atmci_set_completed(host, event)			\
209 	set_bit(event, &host->completed_events)
210 #define atmci_set_pending(host, event)				\
211 	set_bit(event, &host->pending_events)
212 
213 /*
214  * Enable or disable features/registers based on
215  * whether the processor supports them
216  */
217 static bool mci_has_rwproof(void)
218 {
219 	if (cpu_is_at91sam9261() || cpu_is_at91rm9200())
220 		return false;
221 	else
222 		return true;
223 }
224 
225 /*
226  * The debugfs stuff below is mostly optimized away when
227  * CONFIG_DEBUG_FS is not set.
228  */
229 static int atmci_req_show(struct seq_file *s, void *v)
230 {
231 	struct atmel_mci_slot	*slot = s->private;
232 	struct mmc_request	*mrq;
233 	struct mmc_command	*cmd;
234 	struct mmc_command	*stop;
235 	struct mmc_data		*data;
236 
237 	/* Make sure we get a consistent snapshot */
238 	spin_lock_bh(&slot->host->lock);
239 	mrq = slot->mrq;
240 
241 	if (mrq) {
242 		cmd = mrq->cmd;
243 		data = mrq->data;
244 		stop = mrq->stop;
245 
246 		if (cmd)
247 			seq_printf(s,
248 				"CMD%u(0x%x) flg %x rsp %x %x %x %x err %d\n",
249 				cmd->opcode, cmd->arg, cmd->flags,
250 				cmd->resp[0], cmd->resp[1], cmd->resp[2],
251 				cmd->resp[2], cmd->error);
252 		if (data)
253 			seq_printf(s, "DATA %u / %u * %u flg %x err %d\n",
254 				data->bytes_xfered, data->blocks,
255 				data->blksz, data->flags, data->error);
256 		if (stop)
257 			seq_printf(s,
258 				"CMD%u(0x%x) flg %x rsp %x %x %x %x err %d\n",
259 				stop->opcode, stop->arg, stop->flags,
260 				stop->resp[0], stop->resp[1], stop->resp[2],
261 				stop->resp[2], stop->error);
262 	}
263 
264 	spin_unlock_bh(&slot->host->lock);
265 
266 	return 0;
267 }
268 
269 static int atmci_req_open(struct inode *inode, struct file *file)
270 {
271 	return single_open(file, atmci_req_show, inode->i_private);
272 }
273 
274 static const struct file_operations atmci_req_fops = {
275 	.owner		= THIS_MODULE,
276 	.open		= atmci_req_open,
277 	.read		= seq_read,
278 	.llseek		= seq_lseek,
279 	.release	= single_release,
280 };
281 
282 static void atmci_show_status_reg(struct seq_file *s,
283 		const char *regname, u32 value)
284 {
285 	static const char	*sr_bit[] = {
286 		[0]	= "CMDRDY",
287 		[1]	= "RXRDY",
288 		[2]	= "TXRDY",
289 		[3]	= "BLKE",
290 		[4]	= "DTIP",
291 		[5]	= "NOTBUSY",
292 		[6]	= "ENDRX",
293 		[7]	= "ENDTX",
294 		[8]	= "SDIOIRQA",
295 		[9]	= "SDIOIRQB",
296 		[12]	= "SDIOWAIT",
297 		[14]	= "RXBUFF",
298 		[15]	= "TXBUFE",
299 		[16]	= "RINDE",
300 		[17]	= "RDIRE",
301 		[18]	= "RCRCE",
302 		[19]	= "RENDE",
303 		[20]	= "RTOE",
304 		[21]	= "DCRCE",
305 		[22]	= "DTOE",
306 		[23]	= "CSTOE",
307 		[24]	= "BLKOVRE",
308 		[25]	= "DMADONE",
309 		[26]	= "FIFOEMPTY",
310 		[27]	= "XFRDONE",
311 		[30]	= "OVRE",
312 		[31]	= "UNRE",
313 	};
314 	unsigned int		i;
315 
316 	seq_printf(s, "%s:\t0x%08x", regname, value);
317 	for (i = 0; i < ARRAY_SIZE(sr_bit); i++) {
318 		if (value & (1 << i)) {
319 			if (sr_bit[i])
320 				seq_printf(s, " %s", sr_bit[i]);
321 			else
322 				seq_puts(s, " UNKNOWN");
323 		}
324 	}
325 	seq_putc(s, '\n');
326 }
327 
328 static int atmci_regs_show(struct seq_file *s, void *v)
329 {
330 	struct atmel_mci	*host = s->private;
331 	u32			*buf;
332 
333 	buf = kmalloc(MCI_REGS_SIZE, GFP_KERNEL);
334 	if (!buf)
335 		return -ENOMEM;
336 
337 	/*
338 	 * Grab a more or less consistent snapshot. Note that we're
339 	 * not disabling interrupts, so IMR and SR may not be
340 	 * consistent.
341 	 */
342 	spin_lock_bh(&host->lock);
343 	clk_enable(host->mck);
344 	memcpy_fromio(buf, host->regs, MCI_REGS_SIZE);
345 	clk_disable(host->mck);
346 	spin_unlock_bh(&host->lock);
347 
348 	seq_printf(s, "MR:\t0x%08x%s%s CLKDIV=%u\n",
349 			buf[MCI_MR / 4],
350 			buf[MCI_MR / 4] & MCI_MR_RDPROOF ? " RDPROOF" : "",
351 			buf[MCI_MR / 4] & MCI_MR_WRPROOF ? " WRPROOF" : "",
352 			buf[MCI_MR / 4] & 0xff);
353 	seq_printf(s, "DTOR:\t0x%08x\n", buf[MCI_DTOR / 4]);
354 	seq_printf(s, "SDCR:\t0x%08x\n", buf[MCI_SDCR / 4]);
355 	seq_printf(s, "ARGR:\t0x%08x\n", buf[MCI_ARGR / 4]);
356 	seq_printf(s, "BLKR:\t0x%08x BCNT=%u BLKLEN=%u\n",
357 			buf[MCI_BLKR / 4],
358 			buf[MCI_BLKR / 4] & 0xffff,
359 			(buf[MCI_BLKR / 4] >> 16) & 0xffff);
360 
361 	/* Don't read RSPR and RDR; it will consume the data there */
362 
363 	atmci_show_status_reg(s, "SR", buf[MCI_SR / 4]);
364 	atmci_show_status_reg(s, "IMR", buf[MCI_IMR / 4]);
365 
366 	kfree(buf);
367 
368 	return 0;
369 }
370 
371 static int atmci_regs_open(struct inode *inode, struct file *file)
372 {
373 	return single_open(file, atmci_regs_show, inode->i_private);
374 }
375 
376 static const struct file_operations atmci_regs_fops = {
377 	.owner		= THIS_MODULE,
378 	.open		= atmci_regs_open,
379 	.read		= seq_read,
380 	.llseek		= seq_lseek,
381 	.release	= single_release,
382 };
383 
384 static void atmci_init_debugfs(struct atmel_mci_slot *slot)
385 {
386 	struct mmc_host		*mmc = slot->mmc;
387 	struct atmel_mci	*host = slot->host;
388 	struct dentry		*root;
389 	struct dentry		*node;
390 
391 	root = mmc->debugfs_root;
392 	if (!root)
393 		return;
394 
395 	node = debugfs_create_file("regs", S_IRUSR, root, host,
396 			&atmci_regs_fops);
397 	if (IS_ERR(node))
398 		return;
399 	if (!node)
400 		goto err;
401 
402 	node = debugfs_create_file("req", S_IRUSR, root, slot, &atmci_req_fops);
403 	if (!node)
404 		goto err;
405 
406 	node = debugfs_create_u32("state", S_IRUSR, root, (u32 *)&host->state);
407 	if (!node)
408 		goto err;
409 
410 	node = debugfs_create_x32("pending_events", S_IRUSR, root,
411 				     (u32 *)&host->pending_events);
412 	if (!node)
413 		goto err;
414 
415 	node = debugfs_create_x32("completed_events", S_IRUSR, root,
416 				     (u32 *)&host->completed_events);
417 	if (!node)
418 		goto err;
419 
420 	return;
421 
422 err:
423 	dev_err(&mmc->class_dev, "failed to initialize debugfs for slot\n");
424 }
425 
426 static inline unsigned int ns_to_clocks(struct atmel_mci *host,
427 					unsigned int ns)
428 {
429 	return (ns * (host->bus_hz / 1000000) + 999) / 1000;
430 }
431 
432 static void atmci_set_timeout(struct atmel_mci *host,
433 		struct atmel_mci_slot *slot, struct mmc_data *data)
434 {
435 	static unsigned	dtomul_to_shift[] = {
436 		0, 4, 7, 8, 10, 12, 16, 20
437 	};
438 	unsigned	timeout;
439 	unsigned	dtocyc;
440 	unsigned	dtomul;
441 
442 	timeout = ns_to_clocks(host, data->timeout_ns) + data->timeout_clks;
443 
444 	for (dtomul = 0; dtomul < 8; dtomul++) {
445 		unsigned shift = dtomul_to_shift[dtomul];
446 		dtocyc = (timeout + (1 << shift) - 1) >> shift;
447 		if (dtocyc < 15)
448 			break;
449 	}
450 
451 	if (dtomul >= 8) {
452 		dtomul = 7;
453 		dtocyc = 15;
454 	}
455 
456 	dev_vdbg(&slot->mmc->class_dev, "setting timeout to %u cycles\n",
457 			dtocyc << dtomul_to_shift[dtomul]);
458 	mci_writel(host, DTOR, (MCI_DTOMUL(dtomul) | MCI_DTOCYC(dtocyc)));
459 }
460 
461 /*
462  * Return mask with command flags to be enabled for this command.
463  */
464 static u32 atmci_prepare_command(struct mmc_host *mmc,
465 				 struct mmc_command *cmd)
466 {
467 	struct mmc_data	*data;
468 	u32		cmdr;
469 
470 	cmd->error = -EINPROGRESS;
471 
472 	cmdr = MCI_CMDR_CMDNB(cmd->opcode);
473 
474 	if (cmd->flags & MMC_RSP_PRESENT) {
475 		if (cmd->flags & MMC_RSP_136)
476 			cmdr |= MCI_CMDR_RSPTYP_136BIT;
477 		else
478 			cmdr |= MCI_CMDR_RSPTYP_48BIT;
479 	}
480 
481 	/*
482 	 * This should really be MAXLAT_5 for CMD2 and ACMD41, but
483 	 * it's too difficult to determine whether this is an ACMD or
484 	 * not. Better make it 64.
485 	 */
486 	cmdr |= MCI_CMDR_MAXLAT_64CYC;
487 
488 	if (mmc->ios.bus_mode == MMC_BUSMODE_OPENDRAIN)
489 		cmdr |= MCI_CMDR_OPDCMD;
490 
491 	data = cmd->data;
492 	if (data) {
493 		cmdr |= MCI_CMDR_START_XFER;
494 		if (data->flags & MMC_DATA_STREAM)
495 			cmdr |= MCI_CMDR_STREAM;
496 		else if (data->blocks > 1)
497 			cmdr |= MCI_CMDR_MULTI_BLOCK;
498 		else
499 			cmdr |= MCI_CMDR_BLOCK;
500 
501 		if (data->flags & MMC_DATA_READ)
502 			cmdr |= MCI_CMDR_TRDIR_READ;
503 	}
504 
505 	return cmdr;
506 }
507 
508 static void atmci_start_command(struct atmel_mci *host,
509 		struct mmc_command *cmd, u32 cmd_flags)
510 {
511 	WARN_ON(host->cmd);
512 	host->cmd = cmd;
513 
514 	dev_vdbg(&host->pdev->dev,
515 			"start command: ARGR=0x%08x CMDR=0x%08x\n",
516 			cmd->arg, cmd_flags);
517 
518 	mci_writel(host, ARGR, cmd->arg);
519 	mci_writel(host, CMDR, cmd_flags);
520 }
521 
522 static void send_stop_cmd(struct atmel_mci *host, struct mmc_data *data)
523 {
524 	atmci_start_command(host, data->stop, host->stop_cmdr);
525 	mci_writel(host, IER, MCI_CMDRDY);
526 }
527 
528 #ifdef CONFIG_MMC_ATMELMCI_DMA
529 static void atmci_dma_cleanup(struct atmel_mci *host)
530 {
531 	struct mmc_data			*data = host->data;
532 
533 	dma_unmap_sg(&host->pdev->dev, data->sg, data->sg_len,
534 		     ((data->flags & MMC_DATA_WRITE)
535 		      ? DMA_TO_DEVICE : DMA_FROM_DEVICE));
536 }
537 
538 static void atmci_stop_dma(struct atmel_mci *host)
539 {
540 	struct dma_chan *chan = host->data_chan;
541 
542 	if (chan) {
543 		chan->device->device_terminate_all(chan);
544 		atmci_dma_cleanup(host);
545 	} else {
546 		/* Data transfer was stopped by the interrupt handler */
547 		atmci_set_pending(host, EVENT_XFER_COMPLETE);
548 		mci_writel(host, IER, MCI_NOTBUSY);
549 	}
550 }
551 
552 /* This function is called by the DMA driver from tasklet context. */
553 static void atmci_dma_complete(void *arg)
554 {
555 	struct atmel_mci	*host = arg;
556 	struct mmc_data		*data = host->data;
557 
558 	dev_vdbg(&host->pdev->dev, "DMA complete\n");
559 
560 	atmci_dma_cleanup(host);
561 
562 	/*
563 	 * If the card was removed, data will be NULL. No point trying
564 	 * to send the stop command or waiting for NBUSY in this case.
565 	 */
566 	if (data) {
567 		atmci_set_pending(host, EVENT_XFER_COMPLETE);
568 		tasklet_schedule(&host->tasklet);
569 
570 		/*
571 		 * Regardless of what the documentation says, we have
572 		 * to wait for NOTBUSY even after block read
573 		 * operations.
574 		 *
575 		 * When the DMA transfer is complete, the controller
576 		 * may still be reading the CRC from the card, i.e.
577 		 * the data transfer is still in progress and we
578 		 * haven't seen all the potential error bits yet.
579 		 *
580 		 * The interrupt handler will schedule a different
581 		 * tasklet to finish things up when the data transfer
582 		 * is completely done.
583 		 *
584 		 * We may not complete the mmc request here anyway
585 		 * because the mmc layer may call back and cause us to
586 		 * violate the "don't submit new operations from the
587 		 * completion callback" rule of the dma engine
588 		 * framework.
589 		 */
590 		mci_writel(host, IER, MCI_NOTBUSY);
591 	}
592 }
593 
594 static int
595 atmci_submit_data_dma(struct atmel_mci *host, struct mmc_data *data)
596 {
597 	struct dma_chan			*chan;
598 	struct dma_async_tx_descriptor	*desc;
599 	struct scatterlist		*sg;
600 	unsigned int			i;
601 	enum dma_data_direction		direction;
602 
603 	/*
604 	 * We don't do DMA on "complex" transfers, i.e. with
605 	 * non-word-aligned buffers or lengths. Also, we don't bother
606 	 * with all the DMA setup overhead for short transfers.
607 	 */
608 	if (data->blocks * data->blksz < ATMCI_DMA_THRESHOLD)
609 		return -EINVAL;
610 	if (data->blksz & 3)
611 		return -EINVAL;
612 
613 	for_each_sg(data->sg, sg, data->sg_len, i) {
614 		if (sg->offset & 3 || sg->length & 3)
615 			return -EINVAL;
616 	}
617 
618 	/* If we don't have a channel, we can't do DMA */
619 	chan = host->dma.chan;
620 	if (chan)
621 		host->data_chan = chan;
622 
623 	if (!chan)
624 		return -ENODEV;
625 
626 	if (data->flags & MMC_DATA_READ)
627 		direction = DMA_FROM_DEVICE;
628 	else
629 		direction = DMA_TO_DEVICE;
630 
631 	desc = chan->device->device_prep_slave_sg(chan,
632 			data->sg, data->sg_len, direction,
633 			DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
634 	if (!desc)
635 		return -ENOMEM;
636 
637 	host->dma.data_desc = desc;
638 	desc->callback = atmci_dma_complete;
639 	desc->callback_param = host;
640 	desc->tx_submit(desc);
641 
642 	/* Go! */
643 	chan->device->device_issue_pending(chan);
644 
645 	return 0;
646 }
647 
648 #else /* CONFIG_MMC_ATMELMCI_DMA */
649 
650 static int atmci_submit_data_dma(struct atmel_mci *host, struct mmc_data *data)
651 {
652 	return -ENOSYS;
653 }
654 
655 static void atmci_stop_dma(struct atmel_mci *host)
656 {
657 	/* Data transfer was stopped by the interrupt handler */
658 	atmci_set_pending(host, EVENT_XFER_COMPLETE);
659 	mci_writel(host, IER, MCI_NOTBUSY);
660 }
661 
662 #endif /* CONFIG_MMC_ATMELMCI_DMA */
663 
664 /*
665  * Returns a mask of interrupt flags to be enabled after the whole
666  * request has been prepared.
667  */
668 static u32 atmci_submit_data(struct atmel_mci *host, struct mmc_data *data)
669 {
670 	u32 iflags;
671 
672 	data->error = -EINPROGRESS;
673 
674 	WARN_ON(host->data);
675 	host->sg = NULL;
676 	host->data = data;
677 
678 	iflags = ATMCI_DATA_ERROR_FLAGS;
679 	if (atmci_submit_data_dma(host, data)) {
680 		host->data_chan = NULL;
681 
682 		/*
683 		 * Errata: MMC data write operation with less than 12
684 		 * bytes is impossible.
685 		 *
686 		 * Errata: MCI Transmit Data Register (TDR) FIFO
687 		 * corruption when length is not multiple of 4.
688 		 */
689 		if (data->blocks * data->blksz < 12
690 				|| (data->blocks * data->blksz) & 3)
691 			host->need_reset = true;
692 
693 		host->sg = data->sg;
694 		host->pio_offset = 0;
695 		if (data->flags & MMC_DATA_READ)
696 			iflags |= MCI_RXRDY;
697 		else
698 			iflags |= MCI_TXRDY;
699 	}
700 
701 	return iflags;
702 }
703 
704 static void atmci_start_request(struct atmel_mci *host,
705 		struct atmel_mci_slot *slot)
706 {
707 	struct mmc_request	*mrq;
708 	struct mmc_command	*cmd;
709 	struct mmc_data		*data;
710 	u32			iflags;
711 	u32			cmdflags;
712 
713 	mrq = slot->mrq;
714 	host->cur_slot = slot;
715 	host->mrq = mrq;
716 
717 	host->pending_events = 0;
718 	host->completed_events = 0;
719 	host->data_status = 0;
720 
721 	if (host->need_reset) {
722 		mci_writel(host, CR, MCI_CR_SWRST);
723 		mci_writel(host, CR, MCI_CR_MCIEN);
724 		mci_writel(host, MR, host->mode_reg);
725 		host->need_reset = false;
726 	}
727 	mci_writel(host, SDCR, slot->sdc_reg);
728 
729 	iflags = mci_readl(host, IMR);
730 	if (iflags)
731 		dev_warn(&slot->mmc->class_dev, "WARNING: IMR=0x%08x\n",
732 				iflags);
733 
734 	if (unlikely(test_and_clear_bit(ATMCI_CARD_NEED_INIT, &slot->flags))) {
735 		/* Send init sequence (74 clock cycles) */
736 		mci_writel(host, CMDR, MCI_CMDR_SPCMD_INIT);
737 		while (!(mci_readl(host, SR) & MCI_CMDRDY))
738 			cpu_relax();
739 	}
740 	data = mrq->data;
741 	if (data) {
742 		atmci_set_timeout(host, slot, data);
743 
744 		/* Must set block count/size before sending command */
745 		mci_writel(host, BLKR, MCI_BCNT(data->blocks)
746 				| MCI_BLKLEN(data->blksz));
747 		dev_vdbg(&slot->mmc->class_dev, "BLKR=0x%08x\n",
748 			MCI_BCNT(data->blocks) | MCI_BLKLEN(data->blksz));
749 	}
750 
751 	iflags = MCI_CMDRDY;
752 	cmd = mrq->cmd;
753 	cmdflags = atmci_prepare_command(slot->mmc, cmd);
754 	atmci_start_command(host, cmd, cmdflags);
755 
756 	if (data)
757 		iflags |= atmci_submit_data(host, data);
758 
759 	if (mrq->stop) {
760 		host->stop_cmdr = atmci_prepare_command(slot->mmc, mrq->stop);
761 		host->stop_cmdr |= MCI_CMDR_STOP_XFER;
762 		if (!(data->flags & MMC_DATA_WRITE))
763 			host->stop_cmdr |= MCI_CMDR_TRDIR_READ;
764 		if (data->flags & MMC_DATA_STREAM)
765 			host->stop_cmdr |= MCI_CMDR_STREAM;
766 		else
767 			host->stop_cmdr |= MCI_CMDR_MULTI_BLOCK;
768 	}
769 
770 	/*
771 	 * We could have enabled interrupts earlier, but I suspect
772 	 * that would open up a nice can of interesting race
773 	 * conditions (e.g. command and data complete, but stop not
774 	 * prepared yet.)
775 	 */
776 	mci_writel(host, IER, iflags);
777 }
778 
779 static void atmci_queue_request(struct atmel_mci *host,
780 		struct atmel_mci_slot *slot, struct mmc_request *mrq)
781 {
782 	dev_vdbg(&slot->mmc->class_dev, "queue request: state=%d\n",
783 			host->state);
784 
785 	spin_lock_bh(&host->lock);
786 	slot->mrq = mrq;
787 	if (host->state == STATE_IDLE) {
788 		host->state = STATE_SENDING_CMD;
789 		atmci_start_request(host, slot);
790 	} else {
791 		list_add_tail(&slot->queue_node, &host->queue);
792 	}
793 	spin_unlock_bh(&host->lock);
794 }
795 
796 static void atmci_request(struct mmc_host *mmc, struct mmc_request *mrq)
797 {
798 	struct atmel_mci_slot	*slot = mmc_priv(mmc);
799 	struct atmel_mci	*host = slot->host;
800 	struct mmc_data		*data;
801 
802 	WARN_ON(slot->mrq);
803 
804 	/*
805 	 * We may "know" the card is gone even though there's still an
806 	 * electrical connection. If so, we really need to communicate
807 	 * this to the MMC core since there won't be any more
808 	 * interrupts as the card is completely removed. Otherwise,
809 	 * the MMC core might believe the card is still there even
810 	 * though the card was just removed very slowly.
811 	 */
812 	if (!test_bit(ATMCI_CARD_PRESENT, &slot->flags)) {
813 		mrq->cmd->error = -ENOMEDIUM;
814 		mmc_request_done(mmc, mrq);
815 		return;
816 	}
817 
818 	/* We don't support multiple blocks of weird lengths. */
819 	data = mrq->data;
820 	if (data && data->blocks > 1 && data->blksz & 3) {
821 		mrq->cmd->error = -EINVAL;
822 		mmc_request_done(mmc, mrq);
823 	}
824 
825 	atmci_queue_request(host, slot, mrq);
826 }
827 
828 static void atmci_set_ios(struct mmc_host *mmc, struct mmc_ios *ios)
829 {
830 	struct atmel_mci_slot	*slot = mmc_priv(mmc);
831 	struct atmel_mci	*host = slot->host;
832 	unsigned int		i;
833 
834 	slot->sdc_reg &= ~MCI_SDCBUS_MASK;
835 	switch (ios->bus_width) {
836 	case MMC_BUS_WIDTH_1:
837 		slot->sdc_reg |= MCI_SDCBUS_1BIT;
838 		break;
839 	case MMC_BUS_WIDTH_4:
840 		slot->sdc_reg |= MCI_SDCBUS_4BIT;
841 		break;
842 	}
843 
844 	if (ios->clock) {
845 		unsigned int clock_min = ~0U;
846 		u32 clkdiv;
847 
848 		spin_lock_bh(&host->lock);
849 		if (!host->mode_reg) {
850 			clk_enable(host->mck);
851 			mci_writel(host, CR, MCI_CR_SWRST);
852 			mci_writel(host, CR, MCI_CR_MCIEN);
853 		}
854 
855 		/*
856 		 * Use mirror of ios->clock to prevent race with mmc
857 		 * core ios update when finding the minimum.
858 		 */
859 		slot->clock = ios->clock;
860 		for (i = 0; i < ATMEL_MCI_MAX_NR_SLOTS; i++) {
861 			if (host->slot[i] && host->slot[i]->clock
862 					&& host->slot[i]->clock < clock_min)
863 				clock_min = host->slot[i]->clock;
864 		}
865 
866 		/* Calculate clock divider */
867 		clkdiv = DIV_ROUND_UP(host->bus_hz, 2 * clock_min) - 1;
868 		if (clkdiv > 255) {
869 			dev_warn(&mmc->class_dev,
870 				"clock %u too slow; using %lu\n",
871 				clock_min, host->bus_hz / (2 * 256));
872 			clkdiv = 255;
873 		}
874 
875 		host->mode_reg = MCI_MR_CLKDIV(clkdiv);
876 
877 		/*
878 		 * WRPROOF and RDPROOF prevent overruns/underruns by
879 		 * stopping the clock when the FIFO is full/empty.
880 		 * This state is not expected to last for long.
881 		 */
882 		if (mci_has_rwproof())
883 			host->mode_reg |= (MCI_MR_WRPROOF | MCI_MR_RDPROOF);
884 
885 		if (list_empty(&host->queue))
886 			mci_writel(host, MR, host->mode_reg);
887 		else
888 			host->need_clock_update = true;
889 
890 		spin_unlock_bh(&host->lock);
891 	} else {
892 		bool any_slot_active = false;
893 
894 		spin_lock_bh(&host->lock);
895 		slot->clock = 0;
896 		for (i = 0; i < ATMEL_MCI_MAX_NR_SLOTS; i++) {
897 			if (host->slot[i] && host->slot[i]->clock) {
898 				any_slot_active = true;
899 				break;
900 			}
901 		}
902 		if (!any_slot_active) {
903 			mci_writel(host, CR, MCI_CR_MCIDIS);
904 			if (host->mode_reg) {
905 				mci_readl(host, MR);
906 				clk_disable(host->mck);
907 			}
908 			host->mode_reg = 0;
909 		}
910 		spin_unlock_bh(&host->lock);
911 	}
912 
913 	switch (ios->power_mode) {
914 	case MMC_POWER_UP:
915 		set_bit(ATMCI_CARD_NEED_INIT, &slot->flags);
916 		break;
917 	default:
918 		/*
919 		 * TODO: None of the currently available AVR32-based
920 		 * boards allow MMC power to be turned off. Implement
921 		 * power control when this can be tested properly.
922 		 *
923 		 * We also need to hook this into the clock management
924 		 * somehow so that newly inserted cards aren't
925 		 * subjected to a fast clock before we have a chance
926 		 * to figure out what the maximum rate is. Currently,
927 		 * there's no way to avoid this, and there never will
928 		 * be for boards that don't support power control.
929 		 */
930 		break;
931 	}
932 }
933 
934 static int atmci_get_ro(struct mmc_host *mmc)
935 {
936 	int			read_only = -ENOSYS;
937 	struct atmel_mci_slot	*slot = mmc_priv(mmc);
938 
939 	if (gpio_is_valid(slot->wp_pin)) {
940 		read_only = gpio_get_value(slot->wp_pin);
941 		dev_dbg(&mmc->class_dev, "card is %s\n",
942 				read_only ? "read-only" : "read-write");
943 	}
944 
945 	return read_only;
946 }
947 
948 static int atmci_get_cd(struct mmc_host *mmc)
949 {
950 	int			present = -ENOSYS;
951 	struct atmel_mci_slot	*slot = mmc_priv(mmc);
952 
953 	if (gpio_is_valid(slot->detect_pin)) {
954 		present = !(gpio_get_value(slot->detect_pin) ^
955 			    slot->detect_is_active_high);
956 		dev_dbg(&mmc->class_dev, "card is %spresent\n",
957 				present ? "" : "not ");
958 	}
959 
960 	return present;
961 }
962 
963 static const struct mmc_host_ops atmci_ops = {
964 	.request	= atmci_request,
965 	.set_ios	= atmci_set_ios,
966 	.get_ro		= atmci_get_ro,
967 	.get_cd		= atmci_get_cd,
968 };
969 
970 /* Called with host->lock held */
971 static void atmci_request_end(struct atmel_mci *host, struct mmc_request *mrq)
972 	__releases(&host->lock)
973 	__acquires(&host->lock)
974 {
975 	struct atmel_mci_slot	*slot = NULL;
976 	struct mmc_host		*prev_mmc = host->cur_slot->mmc;
977 
978 	WARN_ON(host->cmd || host->data);
979 
980 	/*
981 	 * Update the MMC clock rate if necessary. This may be
982 	 * necessary if set_ios() is called when a different slot is
983 	 * busy transfering data.
984 	 */
985 	if (host->need_clock_update)
986 		mci_writel(host, MR, host->mode_reg);
987 
988 	host->cur_slot->mrq = NULL;
989 	host->mrq = NULL;
990 	if (!list_empty(&host->queue)) {
991 		slot = list_entry(host->queue.next,
992 				struct atmel_mci_slot, queue_node);
993 		list_del(&slot->queue_node);
994 		dev_vdbg(&host->pdev->dev, "list not empty: %s is next\n",
995 				mmc_hostname(slot->mmc));
996 		host->state = STATE_SENDING_CMD;
997 		atmci_start_request(host, slot);
998 	} else {
999 		dev_vdbg(&host->pdev->dev, "list empty\n");
1000 		host->state = STATE_IDLE;
1001 	}
1002 
1003 	spin_unlock(&host->lock);
1004 	mmc_request_done(prev_mmc, mrq);
1005 	spin_lock(&host->lock);
1006 }
1007 
1008 static void atmci_command_complete(struct atmel_mci *host,
1009 			struct mmc_command *cmd)
1010 {
1011 	u32		status = host->cmd_status;
1012 
1013 	/* Read the response from the card (up to 16 bytes) */
1014 	cmd->resp[0] = mci_readl(host, RSPR);
1015 	cmd->resp[1] = mci_readl(host, RSPR);
1016 	cmd->resp[2] = mci_readl(host, RSPR);
1017 	cmd->resp[3] = mci_readl(host, RSPR);
1018 
1019 	if (status & MCI_RTOE)
1020 		cmd->error = -ETIMEDOUT;
1021 	else if ((cmd->flags & MMC_RSP_CRC) && (status & MCI_RCRCE))
1022 		cmd->error = -EILSEQ;
1023 	else if (status & (MCI_RINDE | MCI_RDIRE | MCI_RENDE))
1024 		cmd->error = -EIO;
1025 	else
1026 		cmd->error = 0;
1027 
1028 	if (cmd->error) {
1029 		dev_dbg(&host->pdev->dev,
1030 			"command error: status=0x%08x\n", status);
1031 
1032 		if (cmd->data) {
1033 			host->data = NULL;
1034 			atmci_stop_dma(host);
1035 			mci_writel(host, IDR, MCI_NOTBUSY
1036 					| MCI_TXRDY | MCI_RXRDY
1037 					| ATMCI_DATA_ERROR_FLAGS);
1038 		}
1039 	}
1040 }
1041 
1042 static void atmci_detect_change(unsigned long data)
1043 {
1044 	struct atmel_mci_slot	*slot = (struct atmel_mci_slot *)data;
1045 	bool			present;
1046 	bool			present_old;
1047 
1048 	/*
1049 	 * atmci_cleanup_slot() sets the ATMCI_SHUTDOWN flag before
1050 	 * freeing the interrupt. We must not re-enable the interrupt
1051 	 * if it has been freed, and if we're shutting down, it
1052 	 * doesn't really matter whether the card is present or not.
1053 	 */
1054 	smp_rmb();
1055 	if (test_bit(ATMCI_SHUTDOWN, &slot->flags))
1056 		return;
1057 
1058 	enable_irq(gpio_to_irq(slot->detect_pin));
1059 	present = !(gpio_get_value(slot->detect_pin) ^
1060 		    slot->detect_is_active_high);
1061 	present_old = test_bit(ATMCI_CARD_PRESENT, &slot->flags);
1062 
1063 	dev_vdbg(&slot->mmc->class_dev, "detect change: %d (was %d)\n",
1064 			present, present_old);
1065 
1066 	if (present != present_old) {
1067 		struct atmel_mci	*host = slot->host;
1068 		struct mmc_request	*mrq;
1069 
1070 		dev_dbg(&slot->mmc->class_dev, "card %s\n",
1071 			present ? "inserted" : "removed");
1072 
1073 		spin_lock(&host->lock);
1074 
1075 		if (!present)
1076 			clear_bit(ATMCI_CARD_PRESENT, &slot->flags);
1077 		else
1078 			set_bit(ATMCI_CARD_PRESENT, &slot->flags);
1079 
1080 		/* Clean up queue if present */
1081 		mrq = slot->mrq;
1082 		if (mrq) {
1083 			if (mrq == host->mrq) {
1084 				/*
1085 				 * Reset controller to terminate any ongoing
1086 				 * commands or data transfers.
1087 				 */
1088 				mci_writel(host, CR, MCI_CR_SWRST);
1089 				mci_writel(host, CR, MCI_CR_MCIEN);
1090 				mci_writel(host, MR, host->mode_reg);
1091 
1092 				host->data = NULL;
1093 				host->cmd = NULL;
1094 
1095 				switch (host->state) {
1096 				case STATE_IDLE:
1097 					break;
1098 				case STATE_SENDING_CMD:
1099 					mrq->cmd->error = -ENOMEDIUM;
1100 					if (!mrq->data)
1101 						break;
1102 					/* fall through */
1103 				case STATE_SENDING_DATA:
1104 					mrq->data->error = -ENOMEDIUM;
1105 					atmci_stop_dma(host);
1106 					break;
1107 				case STATE_DATA_BUSY:
1108 				case STATE_DATA_ERROR:
1109 					if (mrq->data->error == -EINPROGRESS)
1110 						mrq->data->error = -ENOMEDIUM;
1111 					if (!mrq->stop)
1112 						break;
1113 					/* fall through */
1114 				case STATE_SENDING_STOP:
1115 					mrq->stop->error = -ENOMEDIUM;
1116 					break;
1117 				}
1118 
1119 				atmci_request_end(host, mrq);
1120 			} else {
1121 				list_del(&slot->queue_node);
1122 				mrq->cmd->error = -ENOMEDIUM;
1123 				if (mrq->data)
1124 					mrq->data->error = -ENOMEDIUM;
1125 				if (mrq->stop)
1126 					mrq->stop->error = -ENOMEDIUM;
1127 
1128 				spin_unlock(&host->lock);
1129 				mmc_request_done(slot->mmc, mrq);
1130 				spin_lock(&host->lock);
1131 			}
1132 		}
1133 		spin_unlock(&host->lock);
1134 
1135 		mmc_detect_change(slot->mmc, 0);
1136 	}
1137 }
1138 
1139 static void atmci_tasklet_func(unsigned long priv)
1140 {
1141 	struct atmel_mci	*host = (struct atmel_mci *)priv;
1142 	struct mmc_request	*mrq = host->mrq;
1143 	struct mmc_data		*data = host->data;
1144 	struct mmc_command	*cmd = host->cmd;
1145 	enum atmel_mci_state	state = host->state;
1146 	enum atmel_mci_state	prev_state;
1147 	u32			status;
1148 
1149 	spin_lock(&host->lock);
1150 
1151 	state = host->state;
1152 
1153 	dev_vdbg(&host->pdev->dev,
1154 		"tasklet: state %u pending/completed/mask %lx/%lx/%x\n",
1155 		state, host->pending_events, host->completed_events,
1156 		mci_readl(host, IMR));
1157 
1158 	do {
1159 		prev_state = state;
1160 
1161 		switch (state) {
1162 		case STATE_IDLE:
1163 			break;
1164 
1165 		case STATE_SENDING_CMD:
1166 			if (!atmci_test_and_clear_pending(host,
1167 						EVENT_CMD_COMPLETE))
1168 				break;
1169 
1170 			host->cmd = NULL;
1171 			atmci_set_completed(host, EVENT_CMD_COMPLETE);
1172 			atmci_command_complete(host, mrq->cmd);
1173 			if (!mrq->data || cmd->error) {
1174 				atmci_request_end(host, host->mrq);
1175 				goto unlock;
1176 			}
1177 
1178 			prev_state = state = STATE_SENDING_DATA;
1179 			/* fall through */
1180 
1181 		case STATE_SENDING_DATA:
1182 			if (atmci_test_and_clear_pending(host,
1183 						EVENT_DATA_ERROR)) {
1184 				atmci_stop_dma(host);
1185 				if (data->stop)
1186 					send_stop_cmd(host, data);
1187 				state = STATE_DATA_ERROR;
1188 				break;
1189 			}
1190 
1191 			if (!atmci_test_and_clear_pending(host,
1192 						EVENT_XFER_COMPLETE))
1193 				break;
1194 
1195 			atmci_set_completed(host, EVENT_XFER_COMPLETE);
1196 			prev_state = state = STATE_DATA_BUSY;
1197 			/* fall through */
1198 
1199 		case STATE_DATA_BUSY:
1200 			if (!atmci_test_and_clear_pending(host,
1201 						EVENT_DATA_COMPLETE))
1202 				break;
1203 
1204 			host->data = NULL;
1205 			atmci_set_completed(host, EVENT_DATA_COMPLETE);
1206 			status = host->data_status;
1207 			if (unlikely(status & ATMCI_DATA_ERROR_FLAGS)) {
1208 				if (status & MCI_DTOE) {
1209 					dev_dbg(&host->pdev->dev,
1210 							"data timeout error\n");
1211 					data->error = -ETIMEDOUT;
1212 				} else if (status & MCI_DCRCE) {
1213 					dev_dbg(&host->pdev->dev,
1214 							"data CRC error\n");
1215 					data->error = -EILSEQ;
1216 				} else {
1217 					dev_dbg(&host->pdev->dev,
1218 						"data FIFO error (status=%08x)\n",
1219 						status);
1220 					data->error = -EIO;
1221 				}
1222 			} else {
1223 				data->bytes_xfered = data->blocks * data->blksz;
1224 				data->error = 0;
1225 			}
1226 
1227 			if (!data->stop) {
1228 				atmci_request_end(host, host->mrq);
1229 				goto unlock;
1230 			}
1231 
1232 			prev_state = state = STATE_SENDING_STOP;
1233 			if (!data->error)
1234 				send_stop_cmd(host, data);
1235 			/* fall through */
1236 
1237 		case STATE_SENDING_STOP:
1238 			if (!atmci_test_and_clear_pending(host,
1239 						EVENT_CMD_COMPLETE))
1240 				break;
1241 
1242 			host->cmd = NULL;
1243 			atmci_command_complete(host, mrq->stop);
1244 			atmci_request_end(host, host->mrq);
1245 			goto unlock;
1246 
1247 		case STATE_DATA_ERROR:
1248 			if (!atmci_test_and_clear_pending(host,
1249 						EVENT_XFER_COMPLETE))
1250 				break;
1251 
1252 			state = STATE_DATA_BUSY;
1253 			break;
1254 		}
1255 	} while (state != prev_state);
1256 
1257 	host->state = state;
1258 
1259 unlock:
1260 	spin_unlock(&host->lock);
1261 }
1262 
1263 static void atmci_read_data_pio(struct atmel_mci *host)
1264 {
1265 	struct scatterlist	*sg = host->sg;
1266 	void			*buf = sg_virt(sg);
1267 	unsigned int		offset = host->pio_offset;
1268 	struct mmc_data		*data = host->data;
1269 	u32			value;
1270 	u32			status;
1271 	unsigned int		nbytes = 0;
1272 
1273 	do {
1274 		value = mci_readl(host, RDR);
1275 		if (likely(offset + 4 <= sg->length)) {
1276 			put_unaligned(value, (u32 *)(buf + offset));
1277 
1278 			offset += 4;
1279 			nbytes += 4;
1280 
1281 			if (offset == sg->length) {
1282 				flush_dcache_page(sg_page(sg));
1283 				host->sg = sg = sg_next(sg);
1284 				if (!sg)
1285 					goto done;
1286 
1287 				offset = 0;
1288 				buf = sg_virt(sg);
1289 			}
1290 		} else {
1291 			unsigned int remaining = sg->length - offset;
1292 			memcpy(buf + offset, &value, remaining);
1293 			nbytes += remaining;
1294 
1295 			flush_dcache_page(sg_page(sg));
1296 			host->sg = sg = sg_next(sg);
1297 			if (!sg)
1298 				goto done;
1299 
1300 			offset = 4 - remaining;
1301 			buf = sg_virt(sg);
1302 			memcpy(buf, (u8 *)&value + remaining, offset);
1303 			nbytes += offset;
1304 		}
1305 
1306 		status = mci_readl(host, SR);
1307 		if (status & ATMCI_DATA_ERROR_FLAGS) {
1308 			mci_writel(host, IDR, (MCI_NOTBUSY | MCI_RXRDY
1309 						| ATMCI_DATA_ERROR_FLAGS));
1310 			host->data_status = status;
1311 			data->bytes_xfered += nbytes;
1312 			smp_wmb();
1313 			atmci_set_pending(host, EVENT_DATA_ERROR);
1314 			tasklet_schedule(&host->tasklet);
1315 			return;
1316 		}
1317 	} while (status & MCI_RXRDY);
1318 
1319 	host->pio_offset = offset;
1320 	data->bytes_xfered += nbytes;
1321 
1322 	return;
1323 
1324 done:
1325 	mci_writel(host, IDR, MCI_RXRDY);
1326 	mci_writel(host, IER, MCI_NOTBUSY);
1327 	data->bytes_xfered += nbytes;
1328 	smp_wmb();
1329 	atmci_set_pending(host, EVENT_XFER_COMPLETE);
1330 }
1331 
1332 static void atmci_write_data_pio(struct atmel_mci *host)
1333 {
1334 	struct scatterlist	*sg = host->sg;
1335 	void			*buf = sg_virt(sg);
1336 	unsigned int		offset = host->pio_offset;
1337 	struct mmc_data		*data = host->data;
1338 	u32			value;
1339 	u32			status;
1340 	unsigned int		nbytes = 0;
1341 
1342 	do {
1343 		if (likely(offset + 4 <= sg->length)) {
1344 			value = get_unaligned((u32 *)(buf + offset));
1345 			mci_writel(host, TDR, value);
1346 
1347 			offset += 4;
1348 			nbytes += 4;
1349 			if (offset == sg->length) {
1350 				host->sg = sg = sg_next(sg);
1351 				if (!sg)
1352 					goto done;
1353 
1354 				offset = 0;
1355 				buf = sg_virt(sg);
1356 			}
1357 		} else {
1358 			unsigned int remaining = sg->length - offset;
1359 
1360 			value = 0;
1361 			memcpy(&value, buf + offset, remaining);
1362 			nbytes += remaining;
1363 
1364 			host->sg = sg = sg_next(sg);
1365 			if (!sg) {
1366 				mci_writel(host, TDR, value);
1367 				goto done;
1368 			}
1369 
1370 			offset = 4 - remaining;
1371 			buf = sg_virt(sg);
1372 			memcpy((u8 *)&value + remaining, buf, offset);
1373 			mci_writel(host, TDR, value);
1374 			nbytes += offset;
1375 		}
1376 
1377 		status = mci_readl(host, SR);
1378 		if (status & ATMCI_DATA_ERROR_FLAGS) {
1379 			mci_writel(host, IDR, (MCI_NOTBUSY | MCI_TXRDY
1380 						| ATMCI_DATA_ERROR_FLAGS));
1381 			host->data_status = status;
1382 			data->bytes_xfered += nbytes;
1383 			smp_wmb();
1384 			atmci_set_pending(host, EVENT_DATA_ERROR);
1385 			tasklet_schedule(&host->tasklet);
1386 			return;
1387 		}
1388 	} while (status & MCI_TXRDY);
1389 
1390 	host->pio_offset = offset;
1391 	data->bytes_xfered += nbytes;
1392 
1393 	return;
1394 
1395 done:
1396 	mci_writel(host, IDR, MCI_TXRDY);
1397 	mci_writel(host, IER, MCI_NOTBUSY);
1398 	data->bytes_xfered += nbytes;
1399 	smp_wmb();
1400 	atmci_set_pending(host, EVENT_XFER_COMPLETE);
1401 }
1402 
1403 static void atmci_cmd_interrupt(struct atmel_mci *host, u32 status)
1404 {
1405 	mci_writel(host, IDR, MCI_CMDRDY);
1406 
1407 	host->cmd_status = status;
1408 	smp_wmb();
1409 	atmci_set_pending(host, EVENT_CMD_COMPLETE);
1410 	tasklet_schedule(&host->tasklet);
1411 }
1412 
1413 static irqreturn_t atmci_interrupt(int irq, void *dev_id)
1414 {
1415 	struct atmel_mci	*host = dev_id;
1416 	u32			status, mask, pending;
1417 	unsigned int		pass_count = 0;
1418 
1419 	do {
1420 		status = mci_readl(host, SR);
1421 		mask = mci_readl(host, IMR);
1422 		pending = status & mask;
1423 		if (!pending)
1424 			break;
1425 
1426 		if (pending & ATMCI_DATA_ERROR_FLAGS) {
1427 			mci_writel(host, IDR, ATMCI_DATA_ERROR_FLAGS
1428 					| MCI_RXRDY | MCI_TXRDY);
1429 			pending &= mci_readl(host, IMR);
1430 
1431 			host->data_status = status;
1432 			smp_wmb();
1433 			atmci_set_pending(host, EVENT_DATA_ERROR);
1434 			tasklet_schedule(&host->tasklet);
1435 		}
1436 		if (pending & MCI_NOTBUSY) {
1437 			mci_writel(host, IDR,
1438 					ATMCI_DATA_ERROR_FLAGS | MCI_NOTBUSY);
1439 			if (!host->data_status)
1440 				host->data_status = status;
1441 			smp_wmb();
1442 			atmci_set_pending(host, EVENT_DATA_COMPLETE);
1443 			tasklet_schedule(&host->tasklet);
1444 		}
1445 		if (pending & MCI_RXRDY)
1446 			atmci_read_data_pio(host);
1447 		if (pending & MCI_TXRDY)
1448 			atmci_write_data_pio(host);
1449 
1450 		if (pending & MCI_CMDRDY)
1451 			atmci_cmd_interrupt(host, status);
1452 	} while (pass_count++ < 5);
1453 
1454 	return pass_count ? IRQ_HANDLED : IRQ_NONE;
1455 }
1456 
1457 static irqreturn_t atmci_detect_interrupt(int irq, void *dev_id)
1458 {
1459 	struct atmel_mci_slot	*slot = dev_id;
1460 
1461 	/*
1462 	 * Disable interrupts until the pin has stabilized and check
1463 	 * the state then. Use mod_timer() since we may be in the
1464 	 * middle of the timer routine when this interrupt triggers.
1465 	 */
1466 	disable_irq_nosync(irq);
1467 	mod_timer(&slot->detect_timer, jiffies + msecs_to_jiffies(20));
1468 
1469 	return IRQ_HANDLED;
1470 }
1471 
1472 static int __init atmci_init_slot(struct atmel_mci *host,
1473 		struct mci_slot_pdata *slot_data, unsigned int id,
1474 		u32 sdc_reg)
1475 {
1476 	struct mmc_host			*mmc;
1477 	struct atmel_mci_slot		*slot;
1478 
1479 	mmc = mmc_alloc_host(sizeof(struct atmel_mci_slot), &host->pdev->dev);
1480 	if (!mmc)
1481 		return -ENOMEM;
1482 
1483 	slot = mmc_priv(mmc);
1484 	slot->mmc = mmc;
1485 	slot->host = host;
1486 	slot->detect_pin = slot_data->detect_pin;
1487 	slot->wp_pin = slot_data->wp_pin;
1488 	slot->detect_is_active_high = slot_data->detect_is_active_high;
1489 	slot->sdc_reg = sdc_reg;
1490 
1491 	mmc->ops = &atmci_ops;
1492 	mmc->f_min = DIV_ROUND_UP(host->bus_hz, 512);
1493 	mmc->f_max = host->bus_hz / 2;
1494 	mmc->ocr_avail	= MMC_VDD_32_33 | MMC_VDD_33_34;
1495 	if (slot_data->bus_width >= 4)
1496 		mmc->caps |= MMC_CAP_4_BIT_DATA;
1497 
1498 	mmc->max_hw_segs = 64;
1499 	mmc->max_phys_segs = 64;
1500 	mmc->max_req_size = 32768 * 512;
1501 	mmc->max_blk_size = 32768;
1502 	mmc->max_blk_count = 512;
1503 
1504 	/* Assume card is present initially */
1505 	set_bit(ATMCI_CARD_PRESENT, &slot->flags);
1506 	if (gpio_is_valid(slot->detect_pin)) {
1507 		if (gpio_request(slot->detect_pin, "mmc_detect")) {
1508 			dev_dbg(&mmc->class_dev, "no detect pin available\n");
1509 			slot->detect_pin = -EBUSY;
1510 		} else if (gpio_get_value(slot->detect_pin) ^
1511 				slot->detect_is_active_high) {
1512 			clear_bit(ATMCI_CARD_PRESENT, &slot->flags);
1513 		}
1514 	}
1515 
1516 	if (!gpio_is_valid(slot->detect_pin))
1517 		mmc->caps |= MMC_CAP_NEEDS_POLL;
1518 
1519 	if (gpio_is_valid(slot->wp_pin)) {
1520 		if (gpio_request(slot->wp_pin, "mmc_wp")) {
1521 			dev_dbg(&mmc->class_dev, "no WP pin available\n");
1522 			slot->wp_pin = -EBUSY;
1523 		}
1524 	}
1525 
1526 	host->slot[id] = slot;
1527 	mmc_add_host(mmc);
1528 
1529 	if (gpio_is_valid(slot->detect_pin)) {
1530 		int ret;
1531 
1532 		setup_timer(&slot->detect_timer, atmci_detect_change,
1533 				(unsigned long)slot);
1534 
1535 		ret = request_irq(gpio_to_irq(slot->detect_pin),
1536 				atmci_detect_interrupt,
1537 				IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING,
1538 				"mmc-detect", slot);
1539 		if (ret) {
1540 			dev_dbg(&mmc->class_dev,
1541 				"could not request IRQ %d for detect pin\n",
1542 				gpio_to_irq(slot->detect_pin));
1543 			gpio_free(slot->detect_pin);
1544 			slot->detect_pin = -EBUSY;
1545 		}
1546 	}
1547 
1548 	atmci_init_debugfs(slot);
1549 
1550 	return 0;
1551 }
1552 
1553 static void __exit atmci_cleanup_slot(struct atmel_mci_slot *slot,
1554 		unsigned int id)
1555 {
1556 	/* Debugfs stuff is cleaned up by mmc core */
1557 
1558 	set_bit(ATMCI_SHUTDOWN, &slot->flags);
1559 	smp_wmb();
1560 
1561 	mmc_remove_host(slot->mmc);
1562 
1563 	if (gpio_is_valid(slot->detect_pin)) {
1564 		int pin = slot->detect_pin;
1565 
1566 		free_irq(gpio_to_irq(pin), slot);
1567 		del_timer_sync(&slot->detect_timer);
1568 		gpio_free(pin);
1569 	}
1570 	if (gpio_is_valid(slot->wp_pin))
1571 		gpio_free(slot->wp_pin);
1572 
1573 	slot->host->slot[id] = NULL;
1574 	mmc_free_host(slot->mmc);
1575 }
1576 
1577 #ifdef CONFIG_MMC_ATMELMCI_DMA
1578 static bool filter(struct dma_chan *chan, void *slave)
1579 {
1580 	struct dw_dma_slave *dws = slave;
1581 
1582 	if (dws->dma_dev == chan->device->dev) {
1583 		chan->private = dws;
1584 		return true;
1585 	} else
1586 		return false;
1587 }
1588 #endif
1589 
1590 static int __init atmci_probe(struct platform_device *pdev)
1591 {
1592 	struct mci_platform_data	*pdata;
1593 	struct atmel_mci		*host;
1594 	struct resource			*regs;
1595 	unsigned int			nr_slots;
1596 	int				irq;
1597 	int				ret;
1598 
1599 	regs = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1600 	if (!regs)
1601 		return -ENXIO;
1602 	pdata = pdev->dev.platform_data;
1603 	if (!pdata)
1604 		return -ENXIO;
1605 	irq = platform_get_irq(pdev, 0);
1606 	if (irq < 0)
1607 		return irq;
1608 
1609 	host = kzalloc(sizeof(struct atmel_mci), GFP_KERNEL);
1610 	if (!host)
1611 		return -ENOMEM;
1612 
1613 	host->pdev = pdev;
1614 	spin_lock_init(&host->lock);
1615 	INIT_LIST_HEAD(&host->queue);
1616 
1617 	host->mck = clk_get(&pdev->dev, "mci_clk");
1618 	if (IS_ERR(host->mck)) {
1619 		ret = PTR_ERR(host->mck);
1620 		goto err_clk_get;
1621 	}
1622 
1623 	ret = -ENOMEM;
1624 	host->regs = ioremap(regs->start, regs->end - regs->start + 1);
1625 	if (!host->regs)
1626 		goto err_ioremap;
1627 
1628 	clk_enable(host->mck);
1629 	mci_writel(host, CR, MCI_CR_SWRST);
1630 	host->bus_hz = clk_get_rate(host->mck);
1631 	clk_disable(host->mck);
1632 
1633 	host->mapbase = regs->start;
1634 
1635 	tasklet_init(&host->tasklet, atmci_tasklet_func, (unsigned long)host);
1636 
1637 	ret = request_irq(irq, atmci_interrupt, 0, dev_name(&pdev->dev), host);
1638 	if (ret)
1639 		goto err_request_irq;
1640 
1641 #ifdef CONFIG_MMC_ATMELMCI_DMA
1642 	if (pdata->dma_slave.dma_dev) {
1643 		struct dw_dma_slave *dws = &pdata->dma_slave;
1644 		dma_cap_mask_t mask;
1645 
1646 		dws->tx_reg = regs->start + MCI_TDR;
1647 		dws->rx_reg = regs->start + MCI_RDR;
1648 
1649 		/* Try to grab a DMA channel */
1650 		dma_cap_zero(mask);
1651 		dma_cap_set(DMA_SLAVE, mask);
1652 		host->dma.chan = dma_request_channel(mask, filter, dws);
1653 	}
1654 	if (!host->dma.chan)
1655 		dev_notice(&pdev->dev, "DMA not available, using PIO\n");
1656 #endif /* CONFIG_MMC_ATMELMCI_DMA */
1657 
1658 	platform_set_drvdata(pdev, host);
1659 
1660 	/* We need at least one slot to succeed */
1661 	nr_slots = 0;
1662 	ret = -ENODEV;
1663 	if (pdata->slot[0].bus_width) {
1664 		ret = atmci_init_slot(host, &pdata->slot[0],
1665 				MCI_SDCSEL_SLOT_A, 0);
1666 		if (!ret)
1667 			nr_slots++;
1668 	}
1669 	if (pdata->slot[1].bus_width) {
1670 		ret = atmci_init_slot(host, &pdata->slot[1],
1671 				MCI_SDCSEL_SLOT_B, 1);
1672 		if (!ret)
1673 			nr_slots++;
1674 	}
1675 
1676 	if (!nr_slots) {
1677 		dev_err(&pdev->dev, "init failed: no slot defined\n");
1678 		goto err_init_slot;
1679 	}
1680 
1681 	dev_info(&pdev->dev,
1682 			"Atmel MCI controller at 0x%08lx irq %d, %u slots\n",
1683 			host->mapbase, irq, nr_slots);
1684 
1685 	return 0;
1686 
1687 err_init_slot:
1688 #ifdef CONFIG_MMC_ATMELMCI_DMA
1689 	if (host->dma.chan)
1690 		dma_release_channel(host->dma.chan);
1691 #endif
1692 	free_irq(irq, host);
1693 err_request_irq:
1694 	iounmap(host->regs);
1695 err_ioremap:
1696 	clk_put(host->mck);
1697 err_clk_get:
1698 	kfree(host);
1699 	return ret;
1700 }
1701 
1702 static int __exit atmci_remove(struct platform_device *pdev)
1703 {
1704 	struct atmel_mci	*host = platform_get_drvdata(pdev);
1705 	unsigned int		i;
1706 
1707 	platform_set_drvdata(pdev, NULL);
1708 
1709 	for (i = 0; i < ATMEL_MCI_MAX_NR_SLOTS; i++) {
1710 		if (host->slot[i])
1711 			atmci_cleanup_slot(host->slot[i], i);
1712 	}
1713 
1714 	clk_enable(host->mck);
1715 	mci_writel(host, IDR, ~0UL);
1716 	mci_writel(host, CR, MCI_CR_MCIDIS);
1717 	mci_readl(host, SR);
1718 	clk_disable(host->mck);
1719 
1720 #ifdef CONFIG_MMC_ATMELMCI_DMA
1721 	if (host->dma.chan)
1722 		dma_release_channel(host->dma.chan);
1723 #endif
1724 
1725 	free_irq(platform_get_irq(pdev, 0), host);
1726 	iounmap(host->regs);
1727 
1728 	clk_put(host->mck);
1729 	kfree(host);
1730 
1731 	return 0;
1732 }
1733 
1734 static struct platform_driver atmci_driver = {
1735 	.remove		= __exit_p(atmci_remove),
1736 	.driver		= {
1737 		.name		= "atmel_mci",
1738 	},
1739 };
1740 
1741 static int __init atmci_init(void)
1742 {
1743 	return platform_driver_probe(&atmci_driver, atmci_probe);
1744 }
1745 
1746 static void __exit atmci_exit(void)
1747 {
1748 	platform_driver_unregister(&atmci_driver);
1749 }
1750 
1751 late_initcall(atmci_init); /* try to load after dma driver when built-in */
1752 module_exit(atmci_exit);
1753 
1754 MODULE_DESCRIPTION("Atmel Multimedia Card Interface driver");
1755 MODULE_AUTHOR("Haavard Skinnemoen <haavard.skinnemoen@atmel.com>");
1756 MODULE_LICENSE("GPL v2");
1757