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