]> git.karo-electronics.de Git - mv-sheeva.git/blob - drivers/mmc/host/atmel-mci.c
mmc-host: move to dma_transfer_direction
[mv-sheeva.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  (MCI_DCRCE | MCI_DTOE | MCI_OVRE | MCI_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[ATMEL_MCI_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 mci_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(MCI_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, MCI_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[MCI_MR / 4],
372                         buf[MCI_MR / 4] & MCI_MR_RDPROOF ? " RDPROOF" : "",
373                         buf[MCI_MR / 4] & MCI_MR_WRPROOF ? " WRPROOF" : "",
374                         buf[MCI_MR / 4] & 0xff);
375         seq_printf(s, "DTOR:\t0x%08x\n", buf[MCI_DTOR / 4]);
376         seq_printf(s, "SDCR:\t0x%08x\n", buf[MCI_SDCR / 4]);
377         seq_printf(s, "ARGR:\t0x%08x\n", buf[MCI_ARGR / 4]);
378         seq_printf(s, "BLKR:\t0x%08x BCNT=%u BLKLEN=%u\n",
379                         buf[MCI_BLKR / 4],
380                         buf[MCI_BLKR / 4] & 0xffff,
381                         (buf[MCI_BLKR / 4] >> 16) & 0xffff);
382         if (atmci_is_mci2())
383                 seq_printf(s, "CSTOR:\t0x%08x\n", buf[MCI_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[MCI_SR / 4]);
388         atmci_show_status_reg(s, "IMR", buf[MCI_IMR / 4]);
389
390         if (atmci_is_mci2()) {
391                 u32 val;
392
393                 val = buf[MCI_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 & MCI_DMAEN ? " DMAEN" : "");
399
400                 val = buf[MCI_CFG / 4];
401                 seq_printf(s, "CFG:\t0x%08x%s%s%s%s\n",
402                                 val,
403                                 val & MCI_CFG_FIFOMODE_1DATA ? " FIFOMODE_ONE_DATA" : "",
404                                 val & MCI_CFG_FERRCTRL_COR ? " FERRCTRL_CLEAR_ON_READ" : "",
405                                 val & MCI_CFG_HSMODE ? " HSMODE" : "",
406                                 val & MCI_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 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 = ns_to_clocks(host, data->timeout_ns) + data->timeout_clks;
486
487         for (dtomul = 0; dtomul < 8; dtomul++) {
488                 unsigned shift = dtomul_to_shift[dtomul];
489                 dtocyc = (timeout + (1 << shift) - 1) >> shift;
490                 if (dtocyc < 15)
491                         break;
492         }
493
494         if (dtomul >= 8) {
495                 dtomul = 7;
496                 dtocyc = 15;
497         }
498
499         dev_vdbg(&slot->mmc->class_dev, "setting timeout to %u cycles\n",
500                         dtocyc << dtomul_to_shift[dtomul]);
501         mci_writel(host, DTOR, (MCI_DTOMUL(dtomul) | MCI_DTOCYC(dtocyc)));
502 }
503
504 /*
505  * Return mask with command flags to be enabled for this command.
506  */
507 static u32 atmci_prepare_command(struct mmc_host *mmc,
508                                  struct mmc_command *cmd)
509 {
510         struct mmc_data *data;
511         u32             cmdr;
512
513         cmd->error = -EINPROGRESS;
514
515         cmdr = MCI_CMDR_CMDNB(cmd->opcode);
516
517         if (cmd->flags & MMC_RSP_PRESENT) {
518                 if (cmd->flags & MMC_RSP_136)
519                         cmdr |= MCI_CMDR_RSPTYP_136BIT;
520                 else
521                         cmdr |= MCI_CMDR_RSPTYP_48BIT;
522         }
523
524         /*
525          * This should really be MAXLAT_5 for CMD2 and ACMD41, but
526          * it's too difficult to determine whether this is an ACMD or
527          * not. Better make it 64.
528          */
529         cmdr |= MCI_CMDR_MAXLAT_64CYC;
530
531         if (mmc->ios.bus_mode == MMC_BUSMODE_OPENDRAIN)
532                 cmdr |= MCI_CMDR_OPDCMD;
533
534         data = cmd->data;
535         if (data) {
536                 cmdr |= MCI_CMDR_START_XFER;
537
538                 if (cmd->opcode == SD_IO_RW_EXTENDED) {
539                         cmdr |= MCI_CMDR_SDIO_BLOCK;
540                 } else {
541                         if (data->flags & MMC_DATA_STREAM)
542                                 cmdr |= MCI_CMDR_STREAM;
543                         else if (data->blocks > 1)
544                                 cmdr |= MCI_CMDR_MULTI_BLOCK;
545                         else
546                                 cmdr |= MCI_CMDR_BLOCK;
547                 }
548
549                 if (data->flags & MMC_DATA_READ)
550                         cmdr |= MCI_CMDR_TRDIR_READ;
551         }
552
553         return cmdr;
554 }
555
556 static void atmci_start_command(struct atmel_mci *host,
557                 struct mmc_command *cmd, u32 cmd_flags)
558 {
559         WARN_ON(host->cmd);
560         host->cmd = cmd;
561
562         dev_vdbg(&host->pdev->dev,
563                         "start command: ARGR=0x%08x CMDR=0x%08x\n",
564                         cmd->arg, cmd_flags);
565
566         mci_writel(host, ARGR, cmd->arg);
567         mci_writel(host, CMDR, cmd_flags);
568 }
569
570 static void send_stop_cmd(struct atmel_mci *host, struct mmc_data *data)
571 {
572         atmci_start_command(host, data->stop, host->stop_cmdr);
573         mci_writel(host, IER, MCI_CMDRDY);
574 }
575
576 #ifdef CONFIG_MMC_ATMELMCI_DMA
577 static void atmci_dma_cleanup(struct atmel_mci *host)
578 {
579         struct mmc_data                 *data = host->data;
580
581         if (data)
582                 dma_unmap_sg(host->dma.chan->device->dev,
583                              data->sg, data->sg_len,
584                              ((data->flags & MMC_DATA_WRITE)
585                               ? DMA_TO_DEVICE : DMA_FROM_DEVICE));
586 }
587
588 static void atmci_stop_dma(struct atmel_mci *host)
589 {
590         struct dma_chan *chan = host->data_chan;
591
592         if (chan) {
593                 dmaengine_terminate_all(chan);
594                 atmci_dma_cleanup(host);
595         } else {
596                 /* Data transfer was stopped by the interrupt handler */
597                 atmci_set_pending(host, EVENT_XFER_COMPLETE);
598                 mci_writel(host, IER, MCI_NOTBUSY);
599         }
600 }
601
602 /* This function is called by the DMA driver from tasklet context. */
603 static void atmci_dma_complete(void *arg)
604 {
605         struct atmel_mci        *host = arg;
606         struct mmc_data         *data = host->data;
607
608         dev_vdbg(&host->pdev->dev, "DMA complete\n");
609
610         if (atmci_is_mci2())
611                 /* Disable DMA hardware handshaking on MCI */
612                 mci_writel(host, DMA, mci_readl(host, DMA) & ~MCI_DMAEN);
613
614         atmci_dma_cleanup(host);
615
616         /*
617          * If the card was removed, data will be NULL. No point trying
618          * to send the stop command or waiting for NBUSY in this case.
619          */
620         if (data) {
621                 atmci_set_pending(host, EVENT_XFER_COMPLETE);
622                 tasklet_schedule(&host->tasklet);
623
624                 /*
625                  * Regardless of what the documentation says, we have
626                  * to wait for NOTBUSY even after block read
627                  * operations.
628                  *
629                  * When the DMA transfer is complete, the controller
630                  * may still be reading the CRC from the card, i.e.
631                  * the data transfer is still in progress and we
632                  * haven't seen all the potential error bits yet.
633                  *
634                  * The interrupt handler will schedule a different
635                  * tasklet to finish things up when the data transfer
636                  * is completely done.
637                  *
638                  * We may not complete the mmc request here anyway
639                  * because the mmc layer may call back and cause us to
640                  * violate the "don't submit new operations from the
641                  * completion callback" rule of the dma engine
642                  * framework.
643                  */
644                 mci_writel(host, IER, MCI_NOTBUSY);
645         }
646 }
647
648 static int
649 atmci_prepare_data_dma(struct atmel_mci *host, struct mmc_data *data)
650 {
651         struct dma_chan                 *chan;
652         struct dma_async_tx_descriptor  *desc;
653         struct scatterlist              *sg;
654         unsigned int                    i;
655         enum dma_data_direction         direction;
656         enum dma_transfer_direction     slave_dirn;
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 < ATMCI_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                 mci_writel(host, DMA, MCI_DMA_CHKSIZE(3) | MCI_DMAEN);
684
685         if (data->flags & MMC_DATA_READ) {
686                 direction = DMA_FROM_DEVICE;
687                 slave_dirn = DMA_DEV_TO_MEM;
688         } else {
689                 direction = DMA_TO_DEVICE;
690                 slave_dirn = DMA_MEM_TO_DEV;
691         }
692
693         sglen = dma_map_sg(chan->device->dev, data->sg,
694                            data->sg_len, direction);
695
696         desc = chan->device->device_prep_slave_sg(chan,
697                         data->sg, sglen, slave_dirn,
698                         DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
699         if (!desc)
700                 goto unmap_exit;
701
702         host->dma.data_desc = desc;
703         desc->callback = atmci_dma_complete;
704         desc->callback_param = host;
705
706         return 0;
707 unmap_exit:
708         dma_unmap_sg(chan->device->dev, data->sg, data->sg_len, direction);
709         return -ENOMEM;
710 }
711
712 static void atmci_submit_data(struct atmel_mci *host)
713 {
714         struct dma_chan                 *chan = host->data_chan;
715         struct dma_async_tx_descriptor  *desc = host->dma.data_desc;
716
717         if (chan) {
718                 dmaengine_submit(desc);
719                 dma_async_issue_pending(chan);
720         }
721 }
722
723 #else /* CONFIG_MMC_ATMELMCI_DMA */
724
725 static int atmci_prepare_data_dma(struct atmel_mci *host, struct mmc_data *data)
726 {
727         return -ENOSYS;
728 }
729
730 static void atmci_submit_data(struct atmel_mci *host) {}
731
732 static void atmci_stop_dma(struct atmel_mci *host)
733 {
734         /* Data transfer was stopped by the interrupt handler */
735         atmci_set_pending(host, EVENT_XFER_COMPLETE);
736         mci_writel(host, IER, MCI_NOTBUSY);
737 }
738
739 #endif /* CONFIG_MMC_ATMELMCI_DMA */
740
741 /*
742  * Returns a mask of interrupt flags to be enabled after the whole
743  * request has been prepared.
744  */
745 static u32 atmci_prepare_data(struct atmel_mci *host, struct mmc_data *data)
746 {
747         u32 iflags;
748
749         data->error = -EINPROGRESS;
750
751         WARN_ON(host->data);
752         host->sg = NULL;
753         host->data = data;
754
755         iflags = ATMCI_DATA_ERROR_FLAGS;
756         if (atmci_prepare_data_dma(host, data)) {
757                 host->data_chan = NULL;
758
759                 /*
760                  * Errata: MMC data write operation with less than 12
761                  * bytes is impossible.
762                  *
763                  * Errata: MCI Transmit Data Register (TDR) FIFO
764                  * corruption when length is not multiple of 4.
765                  */
766                 if (data->blocks * data->blksz < 12
767                                 || (data->blocks * data->blksz) & 3)
768                         host->need_reset = true;
769
770                 host->sg = data->sg;
771                 host->pio_offset = 0;
772                 if (data->flags & MMC_DATA_READ)
773                         iflags |= MCI_RXRDY;
774                 else
775                         iflags |= MCI_TXRDY;
776         }
777
778         return iflags;
779 }
780
781 static void atmci_start_request(struct atmel_mci *host,
782                 struct atmel_mci_slot *slot)
783 {
784         struct mmc_request      *mrq;
785         struct mmc_command      *cmd;
786         struct mmc_data         *data;
787         u32                     iflags;
788         u32                     cmdflags;
789
790         mrq = slot->mrq;
791         host->cur_slot = slot;
792         host->mrq = mrq;
793
794         host->pending_events = 0;
795         host->completed_events = 0;
796         host->data_status = 0;
797
798         if (host->need_reset) {
799                 mci_writel(host, CR, MCI_CR_SWRST);
800                 mci_writel(host, CR, MCI_CR_MCIEN);
801                 mci_writel(host, MR, host->mode_reg);
802                 if (atmci_is_mci2())
803                         mci_writel(host, CFG, host->cfg_reg);
804                 host->need_reset = false;
805         }
806         mci_writel(host, SDCR, slot->sdc_reg);
807
808         iflags = mci_readl(host, IMR);
809         if (iflags & ~(MCI_SDIOIRQA | MCI_SDIOIRQB))
810                 dev_warn(&slot->mmc->class_dev, "WARNING: IMR=0x%08x\n",
811                                 iflags);
812
813         if (unlikely(test_and_clear_bit(ATMCI_CARD_NEED_INIT, &slot->flags))) {
814                 /* Send init sequence (74 clock cycles) */
815                 mci_writel(host, CMDR, MCI_CMDR_SPCMD_INIT);
816                 while (!(mci_readl(host, SR) & MCI_CMDRDY))
817                         cpu_relax();
818         }
819         iflags = 0;
820         data = mrq->data;
821         if (data) {
822                 atmci_set_timeout(host, slot, data);
823
824                 /* Must set block count/size before sending command */
825                 mci_writel(host, BLKR, MCI_BCNT(data->blocks)
826                                 | MCI_BLKLEN(data->blksz));
827                 dev_vdbg(&slot->mmc->class_dev, "BLKR=0x%08x\n",
828                         MCI_BCNT(data->blocks) | MCI_BLKLEN(data->blksz));
829
830                 iflags |= atmci_prepare_data(host, data);
831         }
832
833         iflags |= MCI_CMDRDY;
834         cmd = mrq->cmd;
835         cmdflags = atmci_prepare_command(slot->mmc, cmd);
836         atmci_start_command(host, cmd, cmdflags);
837
838         if (data)
839                 atmci_submit_data(host);
840
841         if (mrq->stop) {
842                 host->stop_cmdr = atmci_prepare_command(slot->mmc, mrq->stop);
843                 host->stop_cmdr |= MCI_CMDR_STOP_XFER;
844                 if (!(data->flags & MMC_DATA_WRITE))
845                         host->stop_cmdr |= MCI_CMDR_TRDIR_READ;
846                 if (data->flags & MMC_DATA_STREAM)
847                         host->stop_cmdr |= MCI_CMDR_STREAM;
848                 else
849                         host->stop_cmdr |= MCI_CMDR_MULTI_BLOCK;
850         }
851
852         /*
853          * We could have enabled interrupts earlier, but I suspect
854          * that would open up a nice can of interesting race
855          * conditions (e.g. command and data complete, but stop not
856          * prepared yet.)
857          */
858         mci_writel(host, IER, iflags);
859 }
860
861 static void atmci_queue_request(struct atmel_mci *host,
862                 struct atmel_mci_slot *slot, struct mmc_request *mrq)
863 {
864         dev_vdbg(&slot->mmc->class_dev, "queue request: state=%d\n",
865                         host->state);
866
867         spin_lock_bh(&host->lock);
868         slot->mrq = mrq;
869         if (host->state == STATE_IDLE) {
870                 host->state = STATE_SENDING_CMD;
871                 atmci_start_request(host, slot);
872         } else {
873                 list_add_tail(&slot->queue_node, &host->queue);
874         }
875         spin_unlock_bh(&host->lock);
876 }
877
878 static void atmci_request(struct mmc_host *mmc, struct mmc_request *mrq)
879 {
880         struct atmel_mci_slot   *slot = mmc_priv(mmc);
881         struct atmel_mci        *host = slot->host;
882         struct mmc_data         *data;
883
884         WARN_ON(slot->mrq);
885
886         /*
887          * We may "know" the card is gone even though there's still an
888          * electrical connection. If so, we really need to communicate
889          * this to the MMC core since there won't be any more
890          * interrupts as the card is completely removed. Otherwise,
891          * the MMC core might believe the card is still there even
892          * though the card was just removed very slowly.
893          */
894         if (!test_bit(ATMCI_CARD_PRESENT, &slot->flags)) {
895                 mrq->cmd->error = -ENOMEDIUM;
896                 mmc_request_done(mmc, mrq);
897                 return;
898         }
899
900         /* We don't support multiple blocks of weird lengths. */
901         data = mrq->data;
902         if (data && data->blocks > 1 && data->blksz & 3) {
903                 mrq->cmd->error = -EINVAL;
904                 mmc_request_done(mmc, mrq);
905         }
906
907         atmci_queue_request(host, slot, mrq);
908 }
909
910 static void atmci_set_ios(struct mmc_host *mmc, struct mmc_ios *ios)
911 {
912         struct atmel_mci_slot   *slot = mmc_priv(mmc);
913         struct atmel_mci        *host = slot->host;
914         unsigned int            i;
915
916         slot->sdc_reg &= ~MCI_SDCBUS_MASK;
917         switch (ios->bus_width) {
918         case MMC_BUS_WIDTH_1:
919                 slot->sdc_reg |= MCI_SDCBUS_1BIT;
920                 break;
921         case MMC_BUS_WIDTH_4:
922                 slot->sdc_reg |= MCI_SDCBUS_4BIT;
923                 break;
924         }
925
926         if (ios->clock) {
927                 unsigned int clock_min = ~0U;
928                 u32 clkdiv;
929
930                 spin_lock_bh(&host->lock);
931                 if (!host->mode_reg) {
932                         clk_enable(host->mck);
933                         mci_writel(host, CR, MCI_CR_SWRST);
934                         mci_writel(host, CR, MCI_CR_MCIEN);
935                         if (atmci_is_mci2())
936                                 mci_writel(host, CFG, host->cfg_reg);
937                 }
938
939                 /*
940                  * Use mirror of ios->clock to prevent race with mmc
941                  * core ios update when finding the minimum.
942                  */
943                 slot->clock = ios->clock;
944                 for (i = 0; i < ATMEL_MCI_MAX_NR_SLOTS; i++) {
945                         if (host->slot[i] && host->slot[i]->clock
946                                         && host->slot[i]->clock < clock_min)
947                                 clock_min = host->slot[i]->clock;
948                 }
949
950                 /* Calculate clock divider */
951                 clkdiv = DIV_ROUND_UP(host->bus_hz, 2 * clock_min) - 1;
952                 if (clkdiv > 255) {
953                         dev_warn(&mmc->class_dev,
954                                 "clock %u too slow; using %lu\n",
955                                 clock_min, host->bus_hz / (2 * 256));
956                         clkdiv = 255;
957                 }
958
959                 host->mode_reg = MCI_MR_CLKDIV(clkdiv);
960
961                 /*
962                  * WRPROOF and RDPROOF prevent overruns/underruns by
963                  * stopping the clock when the FIFO is full/empty.
964                  * This state is not expected to last for long.
965                  */
966                 if (mci_has_rwproof())
967                         host->mode_reg |= (MCI_MR_WRPROOF | MCI_MR_RDPROOF);
968
969                 if (atmci_is_mci2()) {
970                         /* setup High Speed mode in relation with card capacity */
971                         if (ios->timing == MMC_TIMING_SD_HS)
972                                 host->cfg_reg |= MCI_CFG_HSMODE;
973                         else
974                                 host->cfg_reg &= ~MCI_CFG_HSMODE;
975                 }
976
977                 if (list_empty(&host->queue)) {
978                         mci_writel(host, MR, host->mode_reg);
979                         if (atmci_is_mci2())
980                                 mci_writel(host, CFG, host->cfg_reg);
981                 } else {
982                         host->need_clock_update = true;
983                 }
984
985                 spin_unlock_bh(&host->lock);
986         } else {
987                 bool any_slot_active = false;
988
989                 spin_lock_bh(&host->lock);
990                 slot->clock = 0;
991                 for (i = 0; i < ATMEL_MCI_MAX_NR_SLOTS; i++) {
992                         if (host->slot[i] && host->slot[i]->clock) {
993                                 any_slot_active = true;
994                                 break;
995                         }
996                 }
997                 if (!any_slot_active) {
998                         mci_writel(host, CR, MCI_CR_MCIDIS);
999                         if (host->mode_reg) {
1000                                 mci_readl(host, MR);
1001                                 clk_disable(host->mck);
1002                         }
1003                         host->mode_reg = 0;
1004                 }
1005                 spin_unlock_bh(&host->lock);
1006         }
1007
1008         switch (ios->power_mode) {
1009         case MMC_POWER_UP:
1010                 set_bit(ATMCI_CARD_NEED_INIT, &slot->flags);
1011                 break;
1012         default:
1013                 /*
1014                  * TODO: None of the currently available AVR32-based
1015                  * boards allow MMC power to be turned off. Implement
1016                  * power control when this can be tested properly.
1017                  *
1018                  * We also need to hook this into the clock management
1019                  * somehow so that newly inserted cards aren't
1020                  * subjected to a fast clock before we have a chance
1021                  * to figure out what the maximum rate is. Currently,
1022                  * there's no way to avoid this, and there never will
1023                  * be for boards that don't support power control.
1024                  */
1025                 break;
1026         }
1027 }
1028
1029 static int atmci_get_ro(struct mmc_host *mmc)
1030 {
1031         int                     read_only = -ENOSYS;
1032         struct atmel_mci_slot   *slot = mmc_priv(mmc);
1033
1034         if (gpio_is_valid(slot->wp_pin)) {
1035                 read_only = gpio_get_value(slot->wp_pin);
1036                 dev_dbg(&mmc->class_dev, "card is %s\n",
1037                                 read_only ? "read-only" : "read-write");
1038         }
1039
1040         return read_only;
1041 }
1042
1043 static int atmci_get_cd(struct mmc_host *mmc)
1044 {
1045         int                     present = -ENOSYS;
1046         struct atmel_mci_slot   *slot = mmc_priv(mmc);
1047
1048         if (gpio_is_valid(slot->detect_pin)) {
1049                 present = !(gpio_get_value(slot->detect_pin) ^
1050                             slot->detect_is_active_high);
1051                 dev_dbg(&mmc->class_dev, "card is %spresent\n",
1052                                 present ? "" : "not ");
1053         }
1054
1055         return present;
1056 }
1057
1058 static void atmci_enable_sdio_irq(struct mmc_host *mmc, int enable)
1059 {
1060         struct atmel_mci_slot   *slot = mmc_priv(mmc);
1061         struct atmel_mci        *host = slot->host;
1062
1063         if (enable)
1064                 mci_writel(host, IER, slot->sdio_irq);
1065         else
1066                 mci_writel(host, IDR, slot->sdio_irq);
1067 }
1068
1069 static const struct mmc_host_ops atmci_ops = {
1070         .request        = atmci_request,
1071         .set_ios        = atmci_set_ios,
1072         .get_ro         = atmci_get_ro,
1073         .get_cd         = atmci_get_cd,
1074         .enable_sdio_irq = atmci_enable_sdio_irq,
1075 };
1076
1077 /* Called with host->lock held */
1078 static void atmci_request_end(struct atmel_mci *host, struct mmc_request *mrq)
1079         __releases(&host->lock)
1080         __acquires(&host->lock)
1081 {
1082         struct atmel_mci_slot   *slot = NULL;
1083         struct mmc_host         *prev_mmc = host->cur_slot->mmc;
1084
1085         WARN_ON(host->cmd || host->data);
1086
1087         /*
1088          * Update the MMC clock rate if necessary. This may be
1089          * necessary if set_ios() is called when a different slot is
1090          * busy transferring data.
1091          */
1092         if (host->need_clock_update) {
1093                 mci_writel(host, MR, host->mode_reg);
1094                 if (atmci_is_mci2())
1095                         mci_writel(host, CFG, host->cfg_reg);
1096         }
1097
1098         host->cur_slot->mrq = NULL;
1099         host->mrq = NULL;
1100         if (!list_empty(&host->queue)) {
1101                 slot = list_entry(host->queue.next,
1102                                 struct atmel_mci_slot, queue_node);
1103                 list_del(&slot->queue_node);
1104                 dev_vdbg(&host->pdev->dev, "list not empty: %s is next\n",
1105                                 mmc_hostname(slot->mmc));
1106                 host->state = STATE_SENDING_CMD;
1107                 atmci_start_request(host, slot);
1108         } else {
1109                 dev_vdbg(&host->pdev->dev, "list empty\n");
1110                 host->state = STATE_IDLE;
1111         }
1112
1113         spin_unlock(&host->lock);
1114         mmc_request_done(prev_mmc, mrq);
1115         spin_lock(&host->lock);
1116 }
1117
1118 static void atmci_command_complete(struct atmel_mci *host,
1119                         struct mmc_command *cmd)
1120 {
1121         u32             status = host->cmd_status;
1122
1123         /* Read the response from the card (up to 16 bytes) */
1124         cmd->resp[0] = mci_readl(host, RSPR);
1125         cmd->resp[1] = mci_readl(host, RSPR);
1126         cmd->resp[2] = mci_readl(host, RSPR);
1127         cmd->resp[3] = mci_readl(host, RSPR);
1128
1129         if (status & MCI_RTOE)
1130                 cmd->error = -ETIMEDOUT;
1131         else if ((cmd->flags & MMC_RSP_CRC) && (status & MCI_RCRCE))
1132                 cmd->error = -EILSEQ;
1133         else if (status & (MCI_RINDE | MCI_RDIRE | MCI_RENDE))
1134                 cmd->error = -EIO;
1135         else
1136                 cmd->error = 0;
1137
1138         if (cmd->error) {
1139                 dev_dbg(&host->pdev->dev,
1140                         "command error: status=0x%08x\n", status);
1141
1142                 if (cmd->data) {
1143                         atmci_stop_dma(host);
1144                         host->data = NULL;
1145                         mci_writel(host, IDR, MCI_NOTBUSY
1146                                         | MCI_TXRDY | MCI_RXRDY
1147                                         | ATMCI_DATA_ERROR_FLAGS);
1148                 }
1149         }
1150 }
1151
1152 static void atmci_detect_change(unsigned long data)
1153 {
1154         struct atmel_mci_slot   *slot = (struct atmel_mci_slot *)data;
1155         bool                    present;
1156         bool                    present_old;
1157
1158         /*
1159          * atmci_cleanup_slot() sets the ATMCI_SHUTDOWN flag before
1160          * freeing the interrupt. We must not re-enable the interrupt
1161          * if it has been freed, and if we're shutting down, it
1162          * doesn't really matter whether the card is present or not.
1163          */
1164         smp_rmb();
1165         if (test_bit(ATMCI_SHUTDOWN, &slot->flags))
1166                 return;
1167
1168         enable_irq(gpio_to_irq(slot->detect_pin));
1169         present = !(gpio_get_value(slot->detect_pin) ^
1170                     slot->detect_is_active_high);
1171         present_old = test_bit(ATMCI_CARD_PRESENT, &slot->flags);
1172
1173         dev_vdbg(&slot->mmc->class_dev, "detect change: %d (was %d)\n",
1174                         present, present_old);
1175
1176         if (present != present_old) {
1177                 struct atmel_mci        *host = slot->host;
1178                 struct mmc_request      *mrq;
1179
1180                 dev_dbg(&slot->mmc->class_dev, "card %s\n",
1181                         present ? "inserted" : "removed");
1182
1183                 spin_lock(&host->lock);
1184
1185                 if (!present)
1186                         clear_bit(ATMCI_CARD_PRESENT, &slot->flags);
1187                 else
1188                         set_bit(ATMCI_CARD_PRESENT, &slot->flags);
1189
1190                 /* Clean up queue if present */
1191                 mrq = slot->mrq;
1192                 if (mrq) {
1193                         if (mrq == host->mrq) {
1194                                 /*
1195                                  * Reset controller to terminate any ongoing
1196                                  * commands or data transfers.
1197                                  */
1198                                 mci_writel(host, CR, MCI_CR_SWRST);
1199                                 mci_writel(host, CR, MCI_CR_MCIEN);
1200                                 mci_writel(host, MR, host->mode_reg);
1201                                 if (atmci_is_mci2())
1202                                         mci_writel(host, CFG, host->cfg_reg);
1203
1204                                 host->data = NULL;
1205                                 host->cmd = NULL;
1206
1207                                 switch (host->state) {
1208                                 case STATE_IDLE:
1209                                         break;
1210                                 case STATE_SENDING_CMD:
1211                                         mrq->cmd->error = -ENOMEDIUM;
1212                                         if (!mrq->data)
1213                                                 break;
1214                                         /* fall through */
1215                                 case STATE_SENDING_DATA:
1216                                         mrq->data->error = -ENOMEDIUM;
1217                                         atmci_stop_dma(host);
1218                                         break;
1219                                 case STATE_DATA_BUSY:
1220                                 case STATE_DATA_ERROR:
1221                                         if (mrq->data->error == -EINPROGRESS)
1222                                                 mrq->data->error = -ENOMEDIUM;
1223                                         if (!mrq->stop)
1224                                                 break;
1225                                         /* fall through */
1226                                 case STATE_SENDING_STOP:
1227                                         mrq->stop->error = -ENOMEDIUM;
1228                                         break;
1229                                 }
1230
1231                                 atmci_request_end(host, mrq);
1232                         } else {
1233                                 list_del(&slot->queue_node);
1234                                 mrq->cmd->error = -ENOMEDIUM;
1235                                 if (mrq->data)
1236                                         mrq->data->error = -ENOMEDIUM;
1237                                 if (mrq->stop)
1238                                         mrq->stop->error = -ENOMEDIUM;
1239
1240                                 spin_unlock(&host->lock);
1241                                 mmc_request_done(slot->mmc, mrq);
1242                                 spin_lock(&host->lock);
1243                         }
1244                 }
1245                 spin_unlock(&host->lock);
1246
1247                 mmc_detect_change(slot->mmc, 0);
1248         }
1249 }
1250
1251 static void atmci_tasklet_func(unsigned long priv)
1252 {
1253         struct atmel_mci        *host = (struct atmel_mci *)priv;
1254         struct mmc_request      *mrq = host->mrq;
1255         struct mmc_data         *data = host->data;
1256         struct mmc_command      *cmd = host->cmd;
1257         enum atmel_mci_state    state = host->state;
1258         enum atmel_mci_state    prev_state;
1259         u32                     status;
1260
1261         spin_lock(&host->lock);
1262
1263         state = host->state;
1264
1265         dev_vdbg(&host->pdev->dev,
1266                 "tasklet: state %u pending/completed/mask %lx/%lx/%x\n",
1267                 state, host->pending_events, host->completed_events,
1268                 mci_readl(host, IMR));
1269
1270         do {
1271                 prev_state = state;
1272
1273                 switch (state) {
1274                 case STATE_IDLE:
1275                         break;
1276
1277                 case STATE_SENDING_CMD:
1278                         if (!atmci_test_and_clear_pending(host,
1279                                                 EVENT_CMD_COMPLETE))
1280                                 break;
1281
1282                         host->cmd = NULL;
1283                         atmci_set_completed(host, EVENT_CMD_COMPLETE);
1284                         atmci_command_complete(host, mrq->cmd);
1285                         if (!mrq->data || cmd->error) {
1286                                 atmci_request_end(host, host->mrq);
1287                                 goto unlock;
1288                         }
1289
1290                         prev_state = state = STATE_SENDING_DATA;
1291                         /* fall through */
1292
1293                 case STATE_SENDING_DATA:
1294                         if (atmci_test_and_clear_pending(host,
1295                                                 EVENT_DATA_ERROR)) {
1296                                 atmci_stop_dma(host);
1297                                 if (data->stop)
1298                                         send_stop_cmd(host, data);
1299                                 state = STATE_DATA_ERROR;
1300                                 break;
1301                         }
1302
1303                         if (!atmci_test_and_clear_pending(host,
1304                                                 EVENT_XFER_COMPLETE))
1305                                 break;
1306
1307                         atmci_set_completed(host, EVENT_XFER_COMPLETE);
1308                         prev_state = state = STATE_DATA_BUSY;
1309                         /* fall through */
1310
1311                 case STATE_DATA_BUSY:
1312                         if (!atmci_test_and_clear_pending(host,
1313                                                 EVENT_DATA_COMPLETE))
1314                                 break;
1315
1316                         host->data = NULL;
1317                         atmci_set_completed(host, EVENT_DATA_COMPLETE);
1318                         status = host->data_status;
1319                         if (unlikely(status & ATMCI_DATA_ERROR_FLAGS)) {
1320                                 if (status & MCI_DTOE) {
1321                                         dev_dbg(&host->pdev->dev,
1322                                                         "data timeout error\n");
1323                                         data->error = -ETIMEDOUT;
1324                                 } else if (status & MCI_DCRCE) {
1325                                         dev_dbg(&host->pdev->dev,
1326                                                         "data CRC error\n");
1327                                         data->error = -EILSEQ;
1328                                 } else {
1329                                         dev_dbg(&host->pdev->dev,
1330                                                 "data FIFO error (status=%08x)\n",
1331                                                 status);
1332                                         data->error = -EIO;
1333                                 }
1334                         } else {
1335                                 data->bytes_xfered = data->blocks * data->blksz;
1336                                 data->error = 0;
1337                                 mci_writel(host, IDR, ATMCI_DATA_ERROR_FLAGS);
1338                         }
1339
1340                         if (!data->stop) {
1341                                 atmci_request_end(host, host->mrq);
1342                                 goto unlock;
1343                         }
1344
1345                         prev_state = state = STATE_SENDING_STOP;
1346                         if (!data->error)
1347                                 send_stop_cmd(host, data);
1348                         /* fall through */
1349
1350                 case STATE_SENDING_STOP:
1351                         if (!atmci_test_and_clear_pending(host,
1352                                                 EVENT_CMD_COMPLETE))
1353                                 break;
1354
1355                         host->cmd = NULL;
1356                         atmci_command_complete(host, mrq->stop);
1357                         atmci_request_end(host, host->mrq);
1358                         goto unlock;
1359
1360                 case STATE_DATA_ERROR:
1361                         if (!atmci_test_and_clear_pending(host,
1362                                                 EVENT_XFER_COMPLETE))
1363                                 break;
1364
1365                         state = STATE_DATA_BUSY;
1366                         break;
1367                 }
1368         } while (state != prev_state);
1369
1370         host->state = state;
1371
1372 unlock:
1373         spin_unlock(&host->lock);
1374 }
1375
1376 static void atmci_read_data_pio(struct atmel_mci *host)
1377 {
1378         struct scatterlist      *sg = host->sg;
1379         void                    *buf = sg_virt(sg);
1380         unsigned int            offset = host->pio_offset;
1381         struct mmc_data         *data = host->data;
1382         u32                     value;
1383         u32                     status;
1384         unsigned int            nbytes = 0;
1385
1386         do {
1387                 value = mci_readl(host, RDR);
1388                 if (likely(offset + 4 <= sg->length)) {
1389                         put_unaligned(value, (u32 *)(buf + offset));
1390
1391                         offset += 4;
1392                         nbytes += 4;
1393
1394                         if (offset == sg->length) {
1395                                 flush_dcache_page(sg_page(sg));
1396                                 host->sg = sg = sg_next(sg);
1397                                 if (!sg)
1398                                         goto done;
1399
1400                                 offset = 0;
1401                                 buf = sg_virt(sg);
1402                         }
1403                 } else {
1404                         unsigned int remaining = sg->length - offset;
1405                         memcpy(buf + offset, &value, remaining);
1406                         nbytes += remaining;
1407
1408                         flush_dcache_page(sg_page(sg));
1409                         host->sg = sg = sg_next(sg);
1410                         if (!sg)
1411                                 goto done;
1412
1413                         offset = 4 - remaining;
1414                         buf = sg_virt(sg);
1415                         memcpy(buf, (u8 *)&value + remaining, offset);
1416                         nbytes += offset;
1417                 }
1418
1419                 status = mci_readl(host, SR);
1420                 if (status & ATMCI_DATA_ERROR_FLAGS) {
1421                         mci_writel(host, IDR, (MCI_NOTBUSY | MCI_RXRDY
1422                                                 | ATMCI_DATA_ERROR_FLAGS));
1423                         host->data_status = status;
1424                         data->bytes_xfered += nbytes;
1425                         smp_wmb();
1426                         atmci_set_pending(host, EVENT_DATA_ERROR);
1427                         tasklet_schedule(&host->tasklet);
1428                         return;
1429                 }
1430         } while (status & MCI_RXRDY);
1431
1432         host->pio_offset = offset;
1433         data->bytes_xfered += nbytes;
1434
1435         return;
1436
1437 done:
1438         mci_writel(host, IDR, MCI_RXRDY);
1439         mci_writel(host, IER, MCI_NOTBUSY);
1440         data->bytes_xfered += nbytes;
1441         smp_wmb();
1442         atmci_set_pending(host, EVENT_XFER_COMPLETE);
1443 }
1444
1445 static void atmci_write_data_pio(struct atmel_mci *host)
1446 {
1447         struct scatterlist      *sg = host->sg;
1448         void                    *buf = sg_virt(sg);
1449         unsigned int            offset = host->pio_offset;
1450         struct mmc_data         *data = host->data;
1451         u32                     value;
1452         u32                     status;
1453         unsigned int            nbytes = 0;
1454
1455         do {
1456                 if (likely(offset + 4 <= sg->length)) {
1457                         value = get_unaligned((u32 *)(buf + offset));
1458                         mci_writel(host, TDR, value);
1459
1460                         offset += 4;
1461                         nbytes += 4;
1462                         if (offset == sg->length) {
1463                                 host->sg = sg = sg_next(sg);
1464                                 if (!sg)
1465                                         goto done;
1466
1467                                 offset = 0;
1468                                 buf = sg_virt(sg);
1469                         }
1470                 } else {
1471                         unsigned int remaining = sg->length - offset;
1472
1473                         value = 0;
1474                         memcpy(&value, buf + offset, remaining);
1475                         nbytes += remaining;
1476
1477                         host->sg = sg = sg_next(sg);
1478                         if (!sg) {
1479                                 mci_writel(host, TDR, value);
1480                                 goto done;
1481                         }
1482
1483                         offset = 4 - remaining;
1484                         buf = sg_virt(sg);
1485                         memcpy((u8 *)&value + remaining, buf, offset);
1486                         mci_writel(host, TDR, value);
1487                         nbytes += offset;
1488                 }
1489
1490                 status = mci_readl(host, SR);
1491                 if (status & ATMCI_DATA_ERROR_FLAGS) {
1492                         mci_writel(host, IDR, (MCI_NOTBUSY | MCI_TXRDY
1493                                                 | ATMCI_DATA_ERROR_FLAGS));
1494                         host->data_status = status;
1495                         data->bytes_xfered += nbytes;
1496                         smp_wmb();
1497                         atmci_set_pending(host, EVENT_DATA_ERROR);
1498                         tasklet_schedule(&host->tasklet);
1499                         return;
1500                 }
1501         } while (status & MCI_TXRDY);
1502
1503         host->pio_offset = offset;
1504         data->bytes_xfered += nbytes;
1505
1506         return;
1507
1508 done:
1509         mci_writel(host, IDR, MCI_TXRDY);
1510         mci_writel(host, IER, MCI_NOTBUSY);
1511         data->bytes_xfered += nbytes;
1512         smp_wmb();
1513         atmci_set_pending(host, EVENT_XFER_COMPLETE);
1514 }
1515
1516 static void atmci_cmd_interrupt(struct atmel_mci *host, u32 status)
1517 {
1518         mci_writel(host, IDR, MCI_CMDRDY);
1519
1520         host->cmd_status = status;
1521         smp_wmb();
1522         atmci_set_pending(host, EVENT_CMD_COMPLETE);
1523         tasklet_schedule(&host->tasklet);
1524 }
1525
1526 static void atmci_sdio_interrupt(struct atmel_mci *host, u32 status)
1527 {
1528         int     i;
1529
1530         for (i = 0; i < ATMEL_MCI_MAX_NR_SLOTS; i++) {
1531                 struct atmel_mci_slot *slot = host->slot[i];
1532                 if (slot && (status & slot->sdio_irq)) {
1533                         mmc_signal_sdio_irq(slot->mmc);
1534                 }
1535         }
1536 }
1537
1538
1539 static irqreturn_t atmci_interrupt(int irq, void *dev_id)
1540 {
1541         struct atmel_mci        *host = dev_id;
1542         u32                     status, mask, pending;
1543         unsigned int            pass_count = 0;
1544
1545         do {
1546                 status = mci_readl(host, SR);
1547                 mask = mci_readl(host, IMR);
1548                 pending = status & mask;
1549                 if (!pending)
1550                         break;
1551
1552                 if (pending & ATMCI_DATA_ERROR_FLAGS) {
1553                         mci_writel(host, IDR, ATMCI_DATA_ERROR_FLAGS
1554                                         | MCI_RXRDY | MCI_TXRDY);
1555                         pending &= mci_readl(host, IMR);
1556
1557                         host->data_status = status;
1558                         smp_wmb();
1559                         atmci_set_pending(host, EVENT_DATA_ERROR);
1560                         tasklet_schedule(&host->tasklet);
1561                 }
1562                 if (pending & MCI_NOTBUSY) {
1563                         mci_writel(host, IDR,
1564                                         ATMCI_DATA_ERROR_FLAGS | MCI_NOTBUSY);
1565                         if (!host->data_status)
1566                                 host->data_status = status;
1567                         smp_wmb();
1568                         atmci_set_pending(host, EVENT_DATA_COMPLETE);
1569                         tasklet_schedule(&host->tasklet);
1570                 }
1571                 if (pending & MCI_RXRDY)
1572                         atmci_read_data_pio(host);
1573                 if (pending & MCI_TXRDY)
1574                         atmci_write_data_pio(host);
1575
1576                 if (pending & MCI_CMDRDY)
1577                         atmci_cmd_interrupt(host, status);
1578
1579                 if (pending & (MCI_SDIOIRQA | MCI_SDIOIRQB))
1580                         atmci_sdio_interrupt(host, status);
1581
1582         } while (pass_count++ < 5);
1583
1584         return pass_count ? IRQ_HANDLED : IRQ_NONE;
1585 }
1586
1587 static irqreturn_t atmci_detect_interrupt(int irq, void *dev_id)
1588 {
1589         struct atmel_mci_slot   *slot = dev_id;
1590
1591         /*
1592          * Disable interrupts until the pin has stabilized and check
1593          * the state then. Use mod_timer() since we may be in the
1594          * middle of the timer routine when this interrupt triggers.
1595          */
1596         disable_irq_nosync(irq);
1597         mod_timer(&slot->detect_timer, jiffies + msecs_to_jiffies(20));
1598
1599         return IRQ_HANDLED;
1600 }
1601
1602 static int __init atmci_init_slot(struct atmel_mci *host,
1603                 struct mci_slot_pdata *slot_data, unsigned int id,
1604                 u32 sdc_reg, u32 sdio_irq)
1605 {
1606         struct mmc_host                 *mmc;
1607         struct atmel_mci_slot           *slot;
1608
1609         mmc = mmc_alloc_host(sizeof(struct atmel_mci_slot), &host->pdev->dev);
1610         if (!mmc)
1611                 return -ENOMEM;
1612
1613         slot = mmc_priv(mmc);
1614         slot->mmc = mmc;
1615         slot->host = host;
1616         slot->detect_pin = slot_data->detect_pin;
1617         slot->wp_pin = slot_data->wp_pin;
1618         slot->detect_is_active_high = slot_data->detect_is_active_high;
1619         slot->sdc_reg = sdc_reg;
1620         slot->sdio_irq = sdio_irq;
1621
1622         mmc->ops = &atmci_ops;
1623         mmc->f_min = DIV_ROUND_UP(host->bus_hz, 512);
1624         mmc->f_max = host->bus_hz / 2;
1625         mmc->ocr_avail  = MMC_VDD_32_33 | MMC_VDD_33_34;
1626         if (sdio_irq)
1627                 mmc->caps |= MMC_CAP_SDIO_IRQ;
1628         if (atmci_is_mci2())
1629                 mmc->caps |= MMC_CAP_SD_HIGHSPEED;
1630         if (slot_data->bus_width >= 4)
1631                 mmc->caps |= MMC_CAP_4_BIT_DATA;
1632
1633         mmc->max_segs = 64;
1634         mmc->max_req_size = 32768 * 512;
1635         mmc->max_blk_size = 32768;
1636         mmc->max_blk_count = 512;
1637
1638         /* Assume card is present initially */
1639         set_bit(ATMCI_CARD_PRESENT, &slot->flags);
1640         if (gpio_is_valid(slot->detect_pin)) {
1641                 if (gpio_request(slot->detect_pin, "mmc_detect")) {
1642                         dev_dbg(&mmc->class_dev, "no detect pin available\n");
1643                         slot->detect_pin = -EBUSY;
1644                 } else if (gpio_get_value(slot->detect_pin) ^
1645                                 slot->detect_is_active_high) {
1646                         clear_bit(ATMCI_CARD_PRESENT, &slot->flags);
1647                 }
1648         }
1649
1650         if (!gpio_is_valid(slot->detect_pin))
1651                 mmc->caps |= MMC_CAP_NEEDS_POLL;
1652
1653         if (gpio_is_valid(slot->wp_pin)) {
1654                 if (gpio_request(slot->wp_pin, "mmc_wp")) {
1655                         dev_dbg(&mmc->class_dev, "no WP pin available\n");
1656                         slot->wp_pin = -EBUSY;
1657                 }
1658         }
1659
1660         host->slot[id] = slot;
1661         mmc_add_host(mmc);
1662
1663         if (gpio_is_valid(slot->detect_pin)) {
1664                 int ret;
1665
1666                 setup_timer(&slot->detect_timer, atmci_detect_change,
1667                                 (unsigned long)slot);
1668
1669                 ret = request_irq(gpio_to_irq(slot->detect_pin),
1670                                 atmci_detect_interrupt,
1671                                 IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING,
1672                                 "mmc-detect", slot);
1673                 if (ret) {
1674                         dev_dbg(&mmc->class_dev,
1675                                 "could not request IRQ %d for detect pin\n",
1676                                 gpio_to_irq(slot->detect_pin));
1677                         gpio_free(slot->detect_pin);
1678                         slot->detect_pin = -EBUSY;
1679                 }
1680         }
1681
1682         atmci_init_debugfs(slot);
1683
1684         return 0;
1685 }
1686
1687 static void __exit atmci_cleanup_slot(struct atmel_mci_slot *slot,
1688                 unsigned int id)
1689 {
1690         /* Debugfs stuff is cleaned up by mmc core */
1691
1692         set_bit(ATMCI_SHUTDOWN, &slot->flags);
1693         smp_wmb();
1694
1695         mmc_remove_host(slot->mmc);
1696
1697         if (gpio_is_valid(slot->detect_pin)) {
1698                 int pin = slot->detect_pin;
1699
1700                 free_irq(gpio_to_irq(pin), slot);
1701                 del_timer_sync(&slot->detect_timer);
1702                 gpio_free(pin);
1703         }
1704         if (gpio_is_valid(slot->wp_pin))
1705                 gpio_free(slot->wp_pin);
1706
1707         slot->host->slot[id] = NULL;
1708         mmc_free_host(slot->mmc);
1709 }
1710
1711 #ifdef CONFIG_MMC_ATMELMCI_DMA
1712 static bool filter(struct dma_chan *chan, void *slave)
1713 {
1714         struct mci_dma_data     *sl = slave;
1715
1716         if (sl && find_slave_dev(sl) == chan->device->dev) {
1717                 chan->private = slave_data_ptr(sl);
1718                 return true;
1719         } else {
1720                 return false;
1721         }
1722 }
1723
1724 static void atmci_configure_dma(struct atmel_mci *host)
1725 {
1726         struct mci_platform_data        *pdata;
1727
1728         if (host == NULL)
1729                 return;
1730
1731         pdata = host->pdev->dev.platform_data;
1732
1733         if (pdata && find_slave_dev(pdata->dma_slave)) {
1734                 dma_cap_mask_t mask;
1735
1736                 setup_dma_addr(pdata->dma_slave,
1737                                host->mapbase + MCI_TDR,
1738                                host->mapbase + MCI_RDR);
1739
1740                 /* Try to grab a DMA channel */
1741                 dma_cap_zero(mask);
1742                 dma_cap_set(DMA_SLAVE, mask);
1743                 host->dma.chan =
1744                         dma_request_channel(mask, filter, pdata->dma_slave);
1745         }
1746         if (!host->dma.chan)
1747                 dev_notice(&host->pdev->dev, "DMA not available, using PIO\n");
1748         else
1749                 dev_info(&host->pdev->dev,
1750                                         "Using %s for DMA transfers\n",
1751                                         dma_chan_name(host->dma.chan));
1752 }
1753 #else
1754 static void atmci_configure_dma(struct atmel_mci *host) {}
1755 #endif
1756
1757 static int __init atmci_probe(struct platform_device *pdev)
1758 {
1759         struct mci_platform_data        *pdata;
1760         struct atmel_mci                *host;
1761         struct resource                 *regs;
1762         unsigned int                    nr_slots;
1763         int                             irq;
1764         int                             ret;
1765
1766         regs = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1767         if (!regs)
1768                 return -ENXIO;
1769         pdata = pdev->dev.platform_data;
1770         if (!pdata)
1771                 return -ENXIO;
1772         irq = platform_get_irq(pdev, 0);
1773         if (irq < 0)
1774                 return irq;
1775
1776         host = kzalloc(sizeof(struct atmel_mci), GFP_KERNEL);
1777         if (!host)
1778                 return -ENOMEM;
1779
1780         host->pdev = pdev;
1781         spin_lock_init(&host->lock);
1782         INIT_LIST_HEAD(&host->queue);
1783
1784         host->mck = clk_get(&pdev->dev, "mci_clk");
1785         if (IS_ERR(host->mck)) {
1786                 ret = PTR_ERR(host->mck);
1787                 goto err_clk_get;
1788         }
1789
1790         ret = -ENOMEM;
1791         host->regs = ioremap(regs->start, resource_size(regs));
1792         if (!host->regs)
1793                 goto err_ioremap;
1794
1795         clk_enable(host->mck);
1796         mci_writel(host, CR, MCI_CR_SWRST);
1797         host->bus_hz = clk_get_rate(host->mck);
1798         clk_disable(host->mck);
1799
1800         host->mapbase = regs->start;
1801
1802         tasklet_init(&host->tasklet, atmci_tasklet_func, (unsigned long)host);
1803
1804         ret = request_irq(irq, atmci_interrupt, 0, dev_name(&pdev->dev), host);
1805         if (ret)
1806                 goto err_request_irq;
1807
1808         atmci_configure_dma(host);
1809
1810         platform_set_drvdata(pdev, host);
1811
1812         /* We need at least one slot to succeed */
1813         nr_slots = 0;
1814         ret = -ENODEV;
1815         if (pdata->slot[0].bus_width) {
1816                 ret = atmci_init_slot(host, &pdata->slot[0],
1817                                 0, MCI_SDCSEL_SLOT_A, MCI_SDIOIRQA);
1818                 if (!ret)
1819                         nr_slots++;
1820         }
1821         if (pdata->slot[1].bus_width) {
1822                 ret = atmci_init_slot(host, &pdata->slot[1],
1823                                 1, MCI_SDCSEL_SLOT_B, MCI_SDIOIRQB);
1824                 if (!ret)
1825                         nr_slots++;
1826         }
1827
1828         if (!nr_slots) {
1829                 dev_err(&pdev->dev, "init failed: no slot defined\n");
1830                 goto err_init_slot;
1831         }
1832
1833         dev_info(&pdev->dev,
1834                         "Atmel MCI controller at 0x%08lx irq %d, %u slots\n",
1835                         host->mapbase, irq, nr_slots);
1836
1837         return 0;
1838
1839 err_init_slot:
1840 #ifdef CONFIG_MMC_ATMELMCI_DMA
1841         if (host->dma.chan)
1842                 dma_release_channel(host->dma.chan);
1843 #endif
1844         free_irq(irq, host);
1845 err_request_irq:
1846         iounmap(host->regs);
1847 err_ioremap:
1848         clk_put(host->mck);
1849 err_clk_get:
1850         kfree(host);
1851         return ret;
1852 }
1853
1854 static int __exit atmci_remove(struct platform_device *pdev)
1855 {
1856         struct atmel_mci        *host = platform_get_drvdata(pdev);
1857         unsigned int            i;
1858
1859         platform_set_drvdata(pdev, NULL);
1860
1861         for (i = 0; i < ATMEL_MCI_MAX_NR_SLOTS; i++) {
1862                 if (host->slot[i])
1863                         atmci_cleanup_slot(host->slot[i], i);
1864         }
1865
1866         clk_enable(host->mck);
1867         mci_writel(host, IDR, ~0UL);
1868         mci_writel(host, CR, MCI_CR_MCIDIS);
1869         mci_readl(host, SR);
1870         clk_disable(host->mck);
1871
1872 #ifdef CONFIG_MMC_ATMELMCI_DMA
1873         if (host->dma.chan)
1874                 dma_release_channel(host->dma.chan);
1875 #endif
1876
1877         free_irq(platform_get_irq(pdev, 0), host);
1878         iounmap(host->regs);
1879
1880         clk_put(host->mck);
1881         kfree(host);
1882
1883         return 0;
1884 }
1885
1886 #ifdef CONFIG_PM
1887 static int atmci_suspend(struct device *dev)
1888 {
1889         struct atmel_mci *host = dev_get_drvdata(dev);
1890         int i;
1891
1892          for (i = 0; i < ATMEL_MCI_MAX_NR_SLOTS; i++) {
1893                 struct atmel_mci_slot *slot = host->slot[i];
1894                 int ret;
1895
1896                 if (!slot)
1897                         continue;
1898                 ret = mmc_suspend_host(slot->mmc);
1899                 if (ret < 0) {
1900                         while (--i >= 0) {
1901                                 slot = host->slot[i];
1902                                 if (slot
1903                                 && test_bit(ATMCI_SUSPENDED, &slot->flags)) {
1904                                         mmc_resume_host(host->slot[i]->mmc);
1905                                         clear_bit(ATMCI_SUSPENDED, &slot->flags);
1906                                 }
1907                         }
1908                         return ret;
1909                 } else {
1910                         set_bit(ATMCI_SUSPENDED, &slot->flags);
1911                 }
1912         }
1913
1914         return 0;
1915 }
1916
1917 static int atmci_resume(struct device *dev)
1918 {
1919         struct atmel_mci *host = dev_get_drvdata(dev);
1920         int i;
1921         int ret = 0;
1922
1923         for (i = 0; i < ATMEL_MCI_MAX_NR_SLOTS; i++) {
1924                 struct atmel_mci_slot *slot = host->slot[i];
1925                 int err;
1926
1927                 slot = host->slot[i];
1928                 if (!slot)
1929                         continue;
1930                 if (!test_bit(ATMCI_SUSPENDED, &slot->flags))
1931                         continue;
1932                 err = mmc_resume_host(slot->mmc);
1933                 if (err < 0)
1934                         ret = err;
1935                 else
1936                         clear_bit(ATMCI_SUSPENDED, &slot->flags);
1937         }
1938
1939         return ret;
1940 }
1941 static SIMPLE_DEV_PM_OPS(atmci_pm, atmci_suspend, atmci_resume);
1942 #define ATMCI_PM_OPS    (&atmci_pm)
1943 #else
1944 #define ATMCI_PM_OPS    NULL
1945 #endif
1946
1947 static struct platform_driver atmci_driver = {
1948         .remove         = __exit_p(atmci_remove),
1949         .driver         = {
1950                 .name           = "atmel_mci",
1951                 .pm             = ATMCI_PM_OPS,
1952         },
1953 };
1954
1955 static int __init atmci_init(void)
1956 {
1957         return platform_driver_probe(&atmci_driver, atmci_probe);
1958 }
1959
1960 static void __exit atmci_exit(void)
1961 {
1962         platform_driver_unregister(&atmci_driver);
1963 }
1964
1965 late_initcall(atmci_init); /* try to load after dma driver when built-in */
1966 module_exit(atmci_exit);
1967
1968 MODULE_DESCRIPTION("Atmel Multimedia Card Interface driver");
1969 MODULE_AUTHOR("Haavard Skinnemoen (Atmel)");
1970 MODULE_LICENSE("GPL v2");