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