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