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