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