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