5e10d3663ab593ac2dbb71cfb34f022c31118819
[linux-2.6.git] / drivers / mmc / host / atmel-mci.c
1 /*
2  * Atmel MultiMedia Card Interface driver
3  *
4  * Copyright (C) 2004-2008 Atmel Corporation
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 as
8  * published by the Free Software Foundation.
9  */
10 #include <linux/blkdev.h>
11 #include <linux/clk.h>
12 #include <linux/debugfs.h>
13 #include <linux/device.h>
14 #include <linux/dmaengine.h>
15 #include <linux/dma-mapping.h>
16 #include <linux/err.h>
17 #include <linux/gpio.h>
18 #include <linux/init.h>
19 #include <linux/interrupt.h>
20 #include <linux/ioport.h>
21 #include <linux/module.h>
22 #include <linux/platform_device.h>
23 #include <linux/scatterlist.h>
24 #include <linux/seq_file.h>
25 #include <linux/stat.h>
26
27 #include <linux/mmc/host.h>
28 #include <linux/atmel-mci.h>
29
30 #include <asm/io.h>
31 #include <asm/unaligned.h>
32
33 #include <mach/board.h>
34
35 #include "atmel-mci-regs.h"
36
37 #define ATMCI_DATA_ERROR_FLAGS  (MCI_DCRCE | MCI_DTOE | MCI_OVRE | MCI_UNRE)
38 #define ATMCI_DMA_THRESHOLD     16
39
40 enum {
41         EVENT_CMD_COMPLETE = 0,
42         EVENT_XFER_COMPLETE,
43         EVENT_DATA_COMPLETE,
44         EVENT_DATA_ERROR,
45 };
46
47 enum atmel_mci_state {
48         STATE_IDLE = 0,
49         STATE_SENDING_CMD,
50         STATE_SENDING_DATA,
51         STATE_DATA_BUSY,
52         STATE_SENDING_STOP,
53         STATE_DATA_ERROR,
54 };
55
56 struct atmel_mci_dma {
57 #ifdef CONFIG_MMC_ATMELMCI_DMA
58         struct dma_chan                 *chan;
59         struct dma_async_tx_descriptor  *data_desc;
60 #endif
61 };
62
63 /**
64  * struct atmel_mci - MMC controller state shared between all slots
65  * @lock: Spinlock protecting the queue and associated data.
66  * @regs: Pointer to MMIO registers.
67  * @sg: Scatterlist entry currently being processed by PIO code, if any.
68  * @pio_offset: Offset into the current scatterlist entry.
69  * @cur_slot: The slot which is currently using the controller.
70  * @mrq: The request currently being processed on @cur_slot,
71  *      or NULL if the controller is idle.
72  * @cmd: The command currently being sent to the card, or NULL.
73  * @data: The data currently being transferred, or NULL if no data
74  *      transfer is in progress.
75  * @dma: DMA client state.
76  * @data_chan: DMA channel being used for the current data transfer.
77  * @cmd_status: Snapshot of SR taken upon completion of the current
78  *      command. Only valid when EVENT_CMD_COMPLETE is pending.
79  * @data_status: Snapshot of SR taken upon completion of the current
80  *      data transfer. Only valid when EVENT_DATA_COMPLETE or
81  *      EVENT_DATA_ERROR is pending.
82  * @stop_cmdr: Value to be loaded into CMDR when the stop command is
83  *      to be sent.
84  * @tasklet: Tasklet running the request state machine.
85  * @pending_events: Bitmask of events flagged by the interrupt handler
86  *      to be processed by the tasklet.
87  * @completed_events: Bitmask of events which the state machine has
88  *      processed.
89  * @state: Tasklet state.
90  * @queue: List of slots waiting for access to the controller.
91  * @need_clock_update: Update the clock rate before the next request.
92  * @need_reset: Reset controller before next request.
93  * @mode_reg: Value of the MR register.
94  * @bus_hz: The rate of @mck in Hz. This forms the basis for MMC bus
95  *      rate and timeout calculations.
96  * @mapbase: Physical address of the MMIO registers.
97  * @mck: The peripheral bus clock hooked up to the MMC controller.
98  * @pdev: Platform device associated with the MMC controller.
99  * @slot: Slots sharing this MMC controller.
100  *
101  * Locking
102  * =======
103  *
104  * @lock is a softirq-safe spinlock protecting @queue as well as
105  * @cur_slot, @mrq and @state. These must always be updated
106  * at the same time while holding @lock.
107  *
108  * @lock also protects mode_reg and need_clock_update since these are
109  * used to synchronize mode register updates with the queue
110  * processing.
111  *
112  * The @mrq field of struct atmel_mci_slot is also protected by @lock,
113  * and must always be written at the same time as the slot is added to
114  * @queue.
115  *
116  * @pending_events and @completed_events are accessed using atomic bit
117  * operations, so they don't need any locking.
118  *
119  * None of the fields touched by the interrupt handler need any
120  * locking. However, ordering is important: Before EVENT_DATA_ERROR or
121  * EVENT_DATA_COMPLETE is set in @pending_events, all data-related
122  * interrupts must be disabled and @data_status updated with a
123  * snapshot of SR. Similarly, before EVENT_CMD_COMPLETE is set, the
124  * CMDRDY interupt must be disabled and @cmd_status updated with a
125  * snapshot of SR, and before EVENT_XFER_COMPLETE can be set, the
126  * bytes_xfered field of @data must be written. This is ensured by
127  * using barriers.
128  */
129 struct atmel_mci {
130         spinlock_t              lock;
131         void __iomem            *regs;
132
133         struct scatterlist      *sg;
134         unsigned int            pio_offset;
135
136         struct atmel_mci_slot   *cur_slot;
137         struct mmc_request      *mrq;
138         struct mmc_command      *cmd;
139         struct mmc_data         *data;
140
141         struct atmel_mci_dma    dma;
142         struct dma_chan         *data_chan;
143
144         u32                     cmd_status;
145         u32                     data_status;
146         u32                     stop_cmdr;
147
148         struct tasklet_struct   tasklet;
149         unsigned long           pending_events;
150         unsigned long           completed_events;
151         enum atmel_mci_state    state;
152         struct list_head        queue;
153
154         bool                    need_clock_update;
155         bool                    need_reset;
156         u32                     mode_reg;
157         unsigned long           bus_hz;
158         unsigned long           mapbase;
159         struct clk              *mck;
160         struct platform_device  *pdev;
161
162         struct atmel_mci_slot   *slot[ATMEL_MCI_MAX_NR_SLOTS];
163 };
164
165 /**
166  * struct atmel_mci_slot - MMC slot state
167  * @mmc: The mmc_host representing this slot.
168  * @host: The MMC controller this slot is using.
169  * @sdc_reg: Value of SDCR to be written before using this slot.
170  * @mrq: mmc_request currently being processed or waiting to be
171  *      processed, or NULL when the slot is idle.
172  * @queue_node: List node for placing this node in the @queue list of
173  *      &struct atmel_mci.
174  * @clock: Clock rate configured by set_ios(). Protected by host->lock.
175  * @flags: Random state bits associated with the slot.
176  * @detect_pin: GPIO pin used for card detection, or negative if not
177  *      available.
178  * @wp_pin: GPIO pin used for card write protect sending, or negative
179  *      if not available.
180  * @detect_is_active_high: The state of the detect pin when it is active.
181  * @detect_timer: Timer used for debouncing @detect_pin interrupts.
182  */
183 struct atmel_mci_slot {
184         struct mmc_host         *mmc;
185         struct atmel_mci        *host;
186
187         u32                     sdc_reg;
188
189         struct mmc_request      *mrq;
190         struct list_head        queue_node;
191
192         unsigned int            clock;
193         unsigned long           flags;
194 #define ATMCI_CARD_PRESENT      0
195 #define ATMCI_CARD_NEED_INIT    1
196 #define ATMCI_SHUTDOWN          2
197
198         int                     detect_pin;
199         int                     wp_pin;
200         bool                    detect_is_active_high;
201
202         struct timer_list       detect_timer;
203 };
204
205 #define atmci_test_and_clear_pending(host, event)               \
206         test_and_clear_bit(event, &host->pending_events)
207 #define atmci_set_completed(host, event)                        \
208         set_bit(event, &host->completed_events)
209 #define atmci_set_pending(host, event)                          \
210         set_bit(event, &host->pending_events)
211
212 /*
213  * The debugfs stuff below is mostly optimized away when
214  * CONFIG_DEBUG_FS is not set.
215  */
216 static int atmci_req_show(struct seq_file *s, void *v)
217 {
218         struct atmel_mci_slot   *slot = s->private;
219         struct mmc_request      *mrq;
220         struct mmc_command      *cmd;
221         struct mmc_command      *stop;
222         struct mmc_data         *data;
223
224         /* Make sure we get a consistent snapshot */
225         spin_lock_bh(&slot->host->lock);
226         mrq = slot->mrq;
227
228         if (mrq) {
229                 cmd = mrq->cmd;
230                 data = mrq->data;
231                 stop = mrq->stop;
232
233                 if (cmd)
234                         seq_printf(s,
235                                 "CMD%u(0x%x) flg %x rsp %x %x %x %x err %d\n",
236                                 cmd->opcode, cmd->arg, cmd->flags,
237                                 cmd->resp[0], cmd->resp[1], cmd->resp[2],
238                                 cmd->resp[2], cmd->error);
239                 if (data)
240                         seq_printf(s, "DATA %u / %u * %u flg %x err %d\n",
241                                 data->bytes_xfered, data->blocks,
242                                 data->blksz, data->flags, data->error);
243                 if (stop)
244                         seq_printf(s,
245                                 "CMD%u(0x%x) flg %x rsp %x %x %x %x err %d\n",
246                                 stop->opcode, stop->arg, stop->flags,
247                                 stop->resp[0], stop->resp[1], stop->resp[2],
248                                 stop->resp[2], stop->error);
249         }
250
251         spin_unlock_bh(&slot->host->lock);
252
253         return 0;
254 }
255
256 static int atmci_req_open(struct inode *inode, struct file *file)
257 {
258         return single_open(file, atmci_req_show, inode->i_private);
259 }
260
261 static const struct file_operations atmci_req_fops = {
262         .owner          = THIS_MODULE,
263         .open           = atmci_req_open,
264         .read           = seq_read,
265         .llseek         = seq_lseek,
266         .release        = single_release,
267 };
268
269 static void atmci_show_status_reg(struct seq_file *s,
270                 const char *regname, u32 value)
271 {
272         static const char       *sr_bit[] = {
273                 [0]     = "CMDRDY",
274                 [1]     = "RXRDY",
275                 [2]     = "TXRDY",
276                 [3]     = "BLKE",
277                 [4]     = "DTIP",
278                 [5]     = "NOTBUSY",
279                 [8]     = "SDIOIRQA",
280                 [9]     = "SDIOIRQB",
281                 [16]    = "RINDE",
282                 [17]    = "RDIRE",
283                 [18]    = "RCRCE",
284                 [19]    = "RENDE",
285                 [20]    = "RTOE",
286                 [21]    = "DCRCE",
287                 [22]    = "DTOE",
288                 [30]    = "OVRE",
289                 [31]    = "UNRE",
290         };
291         unsigned int            i;
292
293         seq_printf(s, "%s:\t0x%08x", regname, value);
294         for (i = 0; i < ARRAY_SIZE(sr_bit); i++) {
295                 if (value & (1 << i)) {
296                         if (sr_bit[i])
297                                 seq_printf(s, " %s", sr_bit[i]);
298                         else
299                                 seq_puts(s, " UNKNOWN");
300                 }
301         }
302         seq_putc(s, '\n');
303 }
304
305 static int atmci_regs_show(struct seq_file *s, void *v)
306 {
307         struct atmel_mci        *host = s->private;
308         u32                     *buf;
309
310         buf = kmalloc(MCI_REGS_SIZE, GFP_KERNEL);
311         if (!buf)
312                 return -ENOMEM;
313
314         /*
315          * Grab a more or less consistent snapshot. Note that we're
316          * not disabling interrupts, so IMR and SR may not be
317          * consistent.
318          */
319         spin_lock_bh(&host->lock);
320         clk_enable(host->mck);
321         memcpy_fromio(buf, host->regs, MCI_REGS_SIZE);
322         clk_disable(host->mck);
323         spin_unlock_bh(&host->lock);
324
325         seq_printf(s, "MR:\t0x%08x%s%s CLKDIV=%u\n",
326                         buf[MCI_MR / 4],
327                         buf[MCI_MR / 4] & MCI_MR_RDPROOF ? " RDPROOF" : "",
328                         buf[MCI_MR / 4] & MCI_MR_WRPROOF ? " WRPROOF" : "",
329                         buf[MCI_MR / 4] & 0xff);
330         seq_printf(s, "DTOR:\t0x%08x\n", buf[MCI_DTOR / 4]);
331         seq_printf(s, "SDCR:\t0x%08x\n", buf[MCI_SDCR / 4]);
332         seq_printf(s, "ARGR:\t0x%08x\n", buf[MCI_ARGR / 4]);
333         seq_printf(s, "BLKR:\t0x%08x BCNT=%u BLKLEN=%u\n",
334                         buf[MCI_BLKR / 4],
335                         buf[MCI_BLKR / 4] & 0xffff,
336                         (buf[MCI_BLKR / 4] >> 16) & 0xffff);
337
338         /* Don't read RSPR and RDR; it will consume the data there */
339
340         atmci_show_status_reg(s, "SR", buf[MCI_SR / 4]);
341         atmci_show_status_reg(s, "IMR", buf[MCI_IMR / 4]);
342
343         kfree(buf);
344
345         return 0;
346 }
347
348 static int atmci_regs_open(struct inode *inode, struct file *file)
349 {
350         return single_open(file, atmci_regs_show, inode->i_private);
351 }
352
353 static const struct file_operations atmci_regs_fops = {
354         .owner          = THIS_MODULE,
355         .open           = atmci_regs_open,
356         .read           = seq_read,
357         .llseek         = seq_lseek,
358         .release        = single_release,
359 };
360
361 static void atmci_init_debugfs(struct atmel_mci_slot *slot)
362 {
363         struct mmc_host         *mmc = slot->mmc;
364         struct atmel_mci        *host = slot->host;
365         struct dentry           *root;
366         struct dentry           *node;
367
368         root = mmc->debugfs_root;
369         if (!root)
370                 return;
371
372         node = debugfs_create_file("regs", S_IRUSR, root, host,
373                         &atmci_regs_fops);
374         if (IS_ERR(node))
375                 return;
376         if (!node)
377                 goto err;
378
379         node = debugfs_create_file("req", S_IRUSR, root, slot, &atmci_req_fops);
380         if (!node)
381                 goto err;
382
383         node = debugfs_create_u32("state", S_IRUSR, root, (u32 *)&host->state);
384         if (!node)
385                 goto err;
386
387         node = debugfs_create_x32("pending_events", S_IRUSR, root,
388                                      (u32 *)&host->pending_events);
389         if (!node)
390                 goto err;
391
392         node = debugfs_create_x32("completed_events", S_IRUSR, root,
393                                      (u32 *)&host->completed_events);
394         if (!node)
395                 goto err;
396
397         return;
398
399 err:
400         dev_err(&mmc->class_dev, "failed to initialize debugfs for slot\n");
401 }
402
403 static inline unsigned int ns_to_clocks(struct atmel_mci *host,
404                                         unsigned int ns)
405 {
406         return (ns * (host->bus_hz / 1000000) + 999) / 1000;
407 }
408
409 static void atmci_set_timeout(struct atmel_mci *host,
410                 struct atmel_mci_slot *slot, struct mmc_data *data)
411 {
412         static unsigned dtomul_to_shift[] = {
413                 0, 4, 7, 8, 10, 12, 16, 20
414         };
415         unsigned        timeout;
416         unsigned        dtocyc;
417         unsigned        dtomul;
418
419         timeout = ns_to_clocks(host, data->timeout_ns) + data->timeout_clks;
420
421         for (dtomul = 0; dtomul < 8; dtomul++) {
422                 unsigned shift = dtomul_to_shift[dtomul];
423                 dtocyc = (timeout + (1 << shift) - 1) >> shift;
424                 if (dtocyc < 15)
425                         break;
426         }
427
428         if (dtomul >= 8) {
429                 dtomul = 7;
430                 dtocyc = 15;
431         }
432
433         dev_vdbg(&slot->mmc->class_dev, "setting timeout to %u cycles\n",
434                         dtocyc << dtomul_to_shift[dtomul]);
435         mci_writel(host, DTOR, (MCI_DTOMUL(dtomul) | MCI_DTOCYC(dtocyc)));
436 }
437
438 /*
439  * Return mask with command flags to be enabled for this command.
440  */
441 static u32 atmci_prepare_command(struct mmc_host *mmc,
442                                  struct mmc_command *cmd)
443 {
444         struct mmc_data *data;
445         u32             cmdr;
446
447         cmd->error = -EINPROGRESS;
448
449         cmdr = MCI_CMDR_CMDNB(cmd->opcode);
450
451         if (cmd->flags & MMC_RSP_PRESENT) {
452                 if (cmd->flags & MMC_RSP_136)
453                         cmdr |= MCI_CMDR_RSPTYP_136BIT;
454                 else
455                         cmdr |= MCI_CMDR_RSPTYP_48BIT;
456         }
457
458         /*
459          * This should really be MAXLAT_5 for CMD2 and ACMD41, but
460          * it's too difficult to determine whether this is an ACMD or
461          * not. Better make it 64.
462          */
463         cmdr |= MCI_CMDR_MAXLAT_64CYC;
464
465         if (mmc->ios.bus_mode == MMC_BUSMODE_OPENDRAIN)
466                 cmdr |= MCI_CMDR_OPDCMD;
467
468         data = cmd->data;
469         if (data) {
470                 cmdr |= MCI_CMDR_START_XFER;
471                 if (data->flags & MMC_DATA_STREAM)
472                         cmdr |= MCI_CMDR_STREAM;
473                 else if (data->blocks > 1)
474                         cmdr |= MCI_CMDR_MULTI_BLOCK;
475                 else
476                         cmdr |= MCI_CMDR_BLOCK;
477
478                 if (data->flags & MMC_DATA_READ)
479                         cmdr |= MCI_CMDR_TRDIR_READ;
480         }
481
482         return cmdr;
483 }
484
485 static void atmci_start_command(struct atmel_mci *host,
486                 struct mmc_command *cmd, u32 cmd_flags)
487 {
488         WARN_ON(host->cmd);
489         host->cmd = cmd;
490
491         dev_vdbg(&host->pdev->dev,
492                         "start command: ARGR=0x%08x CMDR=0x%08x\n",
493                         cmd->arg, cmd_flags);
494
495         mci_writel(host, ARGR, cmd->arg);
496         mci_writel(host, CMDR, cmd_flags);
497 }
498
499 static void send_stop_cmd(struct atmel_mci *host, struct mmc_data *data)
500 {
501         atmci_start_command(host, data->stop, host->stop_cmdr);
502         mci_writel(host, IER, MCI_CMDRDY);
503 }
504
505 #ifdef CONFIG_MMC_ATMELMCI_DMA
506 static void atmci_dma_cleanup(struct atmel_mci *host)
507 {
508         struct mmc_data                 *data = host->data;
509
510         dma_unmap_sg(&host->pdev->dev, data->sg, data->sg_len,
511                      ((data->flags & MMC_DATA_WRITE)
512                       ? DMA_TO_DEVICE : DMA_FROM_DEVICE));
513 }
514
515 static void atmci_stop_dma(struct atmel_mci *host)
516 {
517         struct dma_chan *chan = host->data_chan;
518
519         if (chan) {
520                 chan->device->device_terminate_all(chan);
521                 atmci_dma_cleanup(host);
522         } else {
523                 /* Data transfer was stopped by the interrupt handler */
524                 atmci_set_pending(host, EVENT_XFER_COMPLETE);
525                 mci_writel(host, IER, MCI_NOTBUSY);
526         }
527 }
528
529 /* This function is called by the DMA driver from tasklet context. */
530 static void atmci_dma_complete(void *arg)
531 {
532         struct atmel_mci        *host = arg;
533         struct mmc_data         *data = host->data;
534
535         dev_vdbg(&host->pdev->dev, "DMA complete\n");
536
537         atmci_dma_cleanup(host);
538
539         /*
540          * If the card was removed, data will be NULL. No point trying
541          * to send the stop command or waiting for NBUSY in this case.
542          */
543         if (data) {
544                 atmci_set_pending(host, EVENT_XFER_COMPLETE);
545                 tasklet_schedule(&host->tasklet);
546
547                 /*
548                  * Regardless of what the documentation says, we have
549                  * to wait for NOTBUSY even after block read
550                  * operations.
551                  *
552                  * When the DMA transfer is complete, the controller
553                  * may still be reading the CRC from the card, i.e.
554                  * the data transfer is still in progress and we
555                  * haven't seen all the potential error bits yet.
556                  *
557                  * The interrupt handler will schedule a different
558                  * tasklet to finish things up when the data transfer
559                  * is completely done.
560                  *
561                  * We may not complete the mmc request here anyway
562                  * because the mmc layer may call back and cause us to
563                  * violate the "don't submit new operations from the
564                  * completion callback" rule of the dma engine
565                  * framework.
566                  */
567                 mci_writel(host, IER, MCI_NOTBUSY);
568         }
569 }
570
571 static int
572 atmci_submit_data_dma(struct atmel_mci *host, struct mmc_data *data)
573 {
574         struct dma_chan                 *chan;
575         struct dma_async_tx_descriptor  *desc;
576         struct scatterlist              *sg;
577         unsigned int                    i;
578         enum dma_data_direction         direction;
579         unsigned int                    sglen;
580
581         /*
582          * We don't do DMA on "complex" transfers, i.e. with
583          * non-word-aligned buffers or lengths. Also, we don't bother
584          * with all the DMA setup overhead for short transfers.
585          */
586         if (data->blocks * data->blksz < ATMCI_DMA_THRESHOLD)
587                 return -EINVAL;
588         if (data->blksz & 3)
589                 return -EINVAL;
590
591         for_each_sg(data->sg, sg, data->sg_len, i) {
592                 if (sg->offset & 3 || sg->length & 3)
593                         return -EINVAL;
594         }
595
596         /* If we don't have a channel, we can't do DMA */
597         chan = host->dma.chan;
598         if (chan)
599                 host->data_chan = chan;
600
601         if (!chan)
602                 return -ENODEV;
603
604         if (data->flags & MMC_DATA_READ)
605                 direction = DMA_FROM_DEVICE;
606         else
607                 direction = DMA_TO_DEVICE;
608
609         sglen = dma_map_sg(&host->pdev->dev, data->sg, data->sg_len, direction);
610         if (sglen != data->sg_len)
611                 goto unmap_exit;
612         desc = chan->device->device_prep_slave_sg(chan,
613                         data->sg, data->sg_len, direction,
614                         DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
615         if (!desc)
616                 goto unmap_exit;
617
618         host->dma.data_desc = desc;
619         desc->callback = atmci_dma_complete;
620         desc->callback_param = host;
621         desc->tx_submit(desc);
622
623         /* Go! */
624         chan->device->device_issue_pending(chan);
625
626         return 0;
627 unmap_exit:
628         dma_unmap_sg(&host->pdev->dev, data->sg, sglen, direction);
629         return -ENOMEM;
630 }
631
632 #else /* CONFIG_MMC_ATMELMCI_DMA */
633
634 static int atmci_submit_data_dma(struct atmel_mci *host, struct mmc_data *data)
635 {
636         return -ENOSYS;
637 }
638
639 static void atmci_stop_dma(struct atmel_mci *host)
640 {
641         /* Data transfer was stopped by the interrupt handler */
642         atmci_set_pending(host, EVENT_XFER_COMPLETE);
643         mci_writel(host, IER, MCI_NOTBUSY);
644 }
645
646 #endif /* CONFIG_MMC_ATMELMCI_DMA */
647
648 /*
649  * Returns a mask of interrupt flags to be enabled after the whole
650  * request has been prepared.
651  */
652 static u32 atmci_submit_data(struct atmel_mci *host, struct mmc_data *data)
653 {
654         u32 iflags;
655
656         data->error = -EINPROGRESS;
657
658         WARN_ON(host->data);
659         host->sg = NULL;
660         host->data = data;
661
662         iflags = ATMCI_DATA_ERROR_FLAGS;
663         if (atmci_submit_data_dma(host, data)) {
664                 host->data_chan = NULL;
665
666                 /*
667                  * Errata: MMC data write operation with less than 12
668                  * bytes is impossible.
669                  *
670                  * Errata: MCI Transmit Data Register (TDR) FIFO
671                  * corruption when length is not multiple of 4.
672                  */
673                 if (data->blocks * data->blksz < 12
674                                 || (data->blocks * data->blksz) & 3)
675                         host->need_reset = true;
676
677                 host->sg = data->sg;
678                 host->pio_offset = 0;
679                 if (data->flags & MMC_DATA_READ)
680                         iflags |= MCI_RXRDY;
681                 else
682                         iflags |= MCI_TXRDY;
683         }
684
685         return iflags;
686 }
687
688 static void atmci_start_request(struct atmel_mci *host,
689                 struct atmel_mci_slot *slot)
690 {
691         struct mmc_request      *mrq;
692         struct mmc_command      *cmd;
693         struct mmc_data         *data;
694         u32                     iflags;
695         u32                     cmdflags;
696
697         mrq = slot->mrq;
698         host->cur_slot = slot;
699         host->mrq = mrq;
700
701         host->pending_events = 0;
702         host->completed_events = 0;
703         host->data_status = 0;
704
705         if (host->need_reset) {
706                 mci_writel(host, CR, MCI_CR_SWRST);
707                 mci_writel(host, CR, MCI_CR_MCIEN);
708                 mci_writel(host, MR, host->mode_reg);
709                 host->need_reset = false;
710         }
711         mci_writel(host, SDCR, slot->sdc_reg);
712
713         iflags = mci_readl(host, IMR);
714         if (iflags)
715                 dev_warn(&slot->mmc->class_dev, "WARNING: IMR=0x%08x\n",
716                                 iflags);
717
718         if (unlikely(test_and_clear_bit(ATMCI_CARD_NEED_INIT, &slot->flags))) {
719                 /* Send init sequence (74 clock cycles) */
720                 mci_writel(host, CMDR, MCI_CMDR_SPCMD_INIT);
721                 while (!(mci_readl(host, SR) & MCI_CMDRDY))
722                         cpu_relax();
723         }
724         data = mrq->data;
725         if (data) {
726                 atmci_set_timeout(host, slot, data);
727
728                 /* Must set block count/size before sending command */
729                 mci_writel(host, BLKR, MCI_BCNT(data->blocks)
730                                 | MCI_BLKLEN(data->blksz));
731                 dev_vdbg(&slot->mmc->class_dev, "BLKR=0x%08x\n",
732                         MCI_BCNT(data->blocks) | MCI_BLKLEN(data->blksz));
733         }
734
735         iflags = MCI_CMDRDY;
736         cmd = mrq->cmd;
737         cmdflags = atmci_prepare_command(slot->mmc, cmd);
738         atmci_start_command(host, cmd, cmdflags);
739
740         if (data)
741                 iflags |= atmci_submit_data(host, data);
742
743         if (mrq->stop) {
744                 host->stop_cmdr = atmci_prepare_command(slot->mmc, mrq->stop);
745                 host->stop_cmdr |= MCI_CMDR_STOP_XFER;
746                 if (!(data->flags & MMC_DATA_WRITE))
747                         host->stop_cmdr |= MCI_CMDR_TRDIR_READ;
748                 if (data->flags & MMC_DATA_STREAM)
749                         host->stop_cmdr |= MCI_CMDR_STREAM;
750                 else
751                         host->stop_cmdr |= MCI_CMDR_MULTI_BLOCK;
752         }
753
754         /*
755          * We could have enabled interrupts earlier, but I suspect
756          * that would open up a nice can of interesting race
757          * conditions (e.g. command and data complete, but stop not
758          * prepared yet.)
759          */
760         mci_writel(host, IER, iflags);
761 }
762
763 static void atmci_queue_request(struct atmel_mci *host,
764                 struct atmel_mci_slot *slot, struct mmc_request *mrq)
765 {
766         dev_vdbg(&slot->mmc->class_dev, "queue request: state=%d\n",
767                         host->state);
768
769         spin_lock_bh(&host->lock);
770         slot->mrq = mrq;
771         if (host->state == STATE_IDLE) {
772                 host->state = STATE_SENDING_CMD;
773                 atmci_start_request(host, slot);
774         } else {
775                 list_add_tail(&slot->queue_node, &host->queue);
776         }
777         spin_unlock_bh(&host->lock);
778 }
779
780 static void atmci_request(struct mmc_host *mmc, struct mmc_request *mrq)
781 {
782         struct atmel_mci_slot   *slot = mmc_priv(mmc);
783         struct atmel_mci        *host = slot->host;
784         struct mmc_data         *data;
785
786         WARN_ON(slot->mrq);
787
788         /*
789          * We may "know" the card is gone even though there's still an
790          * electrical connection. If so, we really need to communicate
791          * this to the MMC core since there won't be any more
792          * interrupts as the card is completely removed. Otherwise,
793          * the MMC core might believe the card is still there even
794          * though the card was just removed very slowly.
795          */
796         if (!test_bit(ATMCI_CARD_PRESENT, &slot->flags)) {
797                 mrq->cmd->error = -ENOMEDIUM;
798                 mmc_request_done(mmc, mrq);
799                 return;
800         }
801
802         /* We don't support multiple blocks of weird lengths. */
803         data = mrq->data;
804         if (data && data->blocks > 1 && data->blksz & 3) {
805                 mrq->cmd->error = -EINVAL;
806                 mmc_request_done(mmc, mrq);
807         }
808
809         atmci_queue_request(host, slot, mrq);
810 }
811
812 static void atmci_set_ios(struct mmc_host *mmc, struct mmc_ios *ios)
813 {
814         struct atmel_mci_slot   *slot = mmc_priv(mmc);
815         struct atmel_mci        *host = slot->host;
816         unsigned int            i;
817
818         slot->sdc_reg &= ~MCI_SDCBUS_MASK;
819         switch (ios->bus_width) {
820         case MMC_BUS_WIDTH_1:
821                 slot->sdc_reg |= MCI_SDCBUS_1BIT;
822                 break;
823         case MMC_BUS_WIDTH_4:
824                 slot->sdc_reg |= MCI_SDCBUS_4BIT;
825                 break;
826         }
827
828         if (ios->clock) {
829                 unsigned int clock_min = ~0U;
830                 u32 clkdiv;
831
832                 spin_lock_bh(&host->lock);
833                 if (!host->mode_reg) {
834                         clk_enable(host->mck);
835                         mci_writel(host, CR, MCI_CR_SWRST);
836                         mci_writel(host, CR, MCI_CR_MCIEN);
837                 }
838
839                 /*
840                  * Use mirror of ios->clock to prevent race with mmc
841                  * core ios update when finding the minimum.
842                  */
843                 slot->clock = ios->clock;
844                 for (i = 0; i < ATMEL_MCI_MAX_NR_SLOTS; i++) {
845                         if (host->slot[i] && host->slot[i]->clock
846                                         && host->slot[i]->clock < clock_min)
847                                 clock_min = host->slot[i]->clock;
848                 }
849
850                 /* Calculate clock divider */
851                 clkdiv = DIV_ROUND_UP(host->bus_hz, 2 * clock_min) - 1;
852                 if (clkdiv > 255) {
853                         dev_warn(&mmc->class_dev,
854                                 "clock %u too slow; using %lu\n",
855                                 clock_min, host->bus_hz / (2 * 256));
856                         clkdiv = 255;
857                 }
858
859                 /*
860                  * WRPROOF and RDPROOF prevent overruns/underruns by
861                  * stopping the clock when the FIFO is full/empty.
862                  * This state is not expected to last for long.
863                  */
864                 host->mode_reg = MCI_MR_CLKDIV(clkdiv) | MCI_MR_WRPROOF
865                                         | MCI_MR_RDPROOF;
866
867                 if (list_empty(&host->queue))
868                         mci_writel(host, MR, host->mode_reg);
869                 else
870                         host->need_clock_update = true;
871
872                 spin_unlock_bh(&host->lock);
873         } else {
874                 bool any_slot_active = false;
875
876                 spin_lock_bh(&host->lock);
877                 slot->clock = 0;
878                 for (i = 0; i < ATMEL_MCI_MAX_NR_SLOTS; i++) {
879                         if (host->slot[i] && host->slot[i]->clock) {
880                                 any_slot_active = true;
881                                 break;
882                         }
883                 }
884                 if (!any_slot_active) {
885                         mci_writel(host, CR, MCI_CR_MCIDIS);
886                         if (host->mode_reg) {
887                                 mci_readl(host, MR);
888                                 clk_disable(host->mck);
889                         }
890                         host->mode_reg = 0;
891                 }
892                 spin_unlock_bh(&host->lock);
893         }
894
895         switch (ios->power_mode) {
896         case MMC_POWER_UP:
897                 set_bit(ATMCI_CARD_NEED_INIT, &slot->flags);
898                 break;
899         default:
900                 /*
901                  * TODO: None of the currently available AVR32-based
902                  * boards allow MMC power to be turned off. Implement
903                  * power control when this can be tested properly.
904                  *
905                  * We also need to hook this into the clock management
906                  * somehow so that newly inserted cards aren't
907                  * subjected to a fast clock before we have a chance
908                  * to figure out what the maximum rate is. Currently,
909                  * there's no way to avoid this, and there never will
910                  * be for boards that don't support power control.
911                  */
912                 break;
913         }
914 }
915
916 static int atmci_get_ro(struct mmc_host *mmc)
917 {
918         int                     read_only = -ENOSYS;
919         struct atmel_mci_slot   *slot = mmc_priv(mmc);
920
921         if (gpio_is_valid(slot->wp_pin)) {
922                 read_only = gpio_get_value(slot->wp_pin);
923                 dev_dbg(&mmc->class_dev, "card is %s\n",
924                                 read_only ? "read-only" : "read-write");
925         }
926
927         return read_only;
928 }
929
930 static int atmci_get_cd(struct mmc_host *mmc)
931 {
932         int                     present = -ENOSYS;
933         struct atmel_mci_slot   *slot = mmc_priv(mmc);
934
935         if (gpio_is_valid(slot->detect_pin)) {
936                 present = !(gpio_get_value(slot->detect_pin) ^
937                             slot->detect_is_active_high);
938                 dev_dbg(&mmc->class_dev, "card is %spresent\n",
939                                 present ? "" : "not ");
940         }
941
942         return present;
943 }
944
945 static const struct mmc_host_ops atmci_ops = {
946         .request        = atmci_request,
947         .set_ios        = atmci_set_ios,
948         .get_ro         = atmci_get_ro,
949         .get_cd         = atmci_get_cd,
950 };
951
952 /* Called with host->lock held */
953 static void atmci_request_end(struct atmel_mci *host, struct mmc_request *mrq)
954         __releases(&host->lock)
955         __acquires(&host->lock)
956 {
957         struct atmel_mci_slot   *slot = NULL;
958         struct mmc_host         *prev_mmc = host->cur_slot->mmc;
959
960         WARN_ON(host->cmd || host->data);
961
962         /*
963          * Update the MMC clock rate if necessary. This may be
964          * necessary if set_ios() is called when a different slot is
965          * busy transfering data.
966          */
967         if (host->need_clock_update)
968                 mci_writel(host, MR, host->mode_reg);
969
970         host->cur_slot->mrq = NULL;
971         host->mrq = NULL;
972         if (!list_empty(&host->queue)) {
973                 slot = list_entry(host->queue.next,
974                                 struct atmel_mci_slot, queue_node);
975                 list_del(&slot->queue_node);
976                 dev_vdbg(&host->pdev->dev, "list not empty: %s is next\n",
977                                 mmc_hostname(slot->mmc));
978                 host->state = STATE_SENDING_CMD;
979                 atmci_start_request(host, slot);
980         } else {
981                 dev_vdbg(&host->pdev->dev, "list empty\n");
982                 host->state = STATE_IDLE;
983         }
984
985         spin_unlock(&host->lock);
986         mmc_request_done(prev_mmc, mrq);
987         spin_lock(&host->lock);
988 }
989
990 static void atmci_command_complete(struct atmel_mci *host,
991                         struct mmc_command *cmd)
992 {
993         u32             status = host->cmd_status;
994
995         /* Read the response from the card (up to 16 bytes) */
996         cmd->resp[0] = mci_readl(host, RSPR);
997         cmd->resp[1] = mci_readl(host, RSPR);
998         cmd->resp[2] = mci_readl(host, RSPR);
999         cmd->resp[3] = mci_readl(host, RSPR);
1000
1001         if (status & MCI_RTOE)
1002                 cmd->error = -ETIMEDOUT;
1003         else if ((cmd->flags & MMC_RSP_CRC) && (status & MCI_RCRCE))
1004                 cmd->error = -EILSEQ;
1005         else if (status & (MCI_RINDE | MCI_RDIRE | MCI_RENDE))
1006                 cmd->error = -EIO;
1007         else
1008                 cmd->error = 0;
1009
1010         if (cmd->error) {
1011                 dev_dbg(&host->pdev->dev,
1012                         "command error: status=0x%08x\n", status);
1013
1014                 if (cmd->data) {
1015                         host->data = NULL;
1016                         atmci_stop_dma(host);
1017                         mci_writel(host, IDR, MCI_NOTBUSY
1018                                         | MCI_TXRDY | MCI_RXRDY
1019                                         | ATMCI_DATA_ERROR_FLAGS);
1020                 }
1021         }
1022 }
1023
1024 static void atmci_detect_change(unsigned long data)
1025 {
1026         struct atmel_mci_slot   *slot = (struct atmel_mci_slot *)data;
1027         bool                    present;
1028         bool                    present_old;
1029
1030         /*
1031          * atmci_cleanup_slot() sets the ATMCI_SHUTDOWN flag before
1032          * freeing the interrupt. We must not re-enable the interrupt
1033          * if it has been freed, and if we're shutting down, it
1034          * doesn't really matter whether the card is present or not.
1035          */
1036         smp_rmb();
1037         if (test_bit(ATMCI_SHUTDOWN, &slot->flags))
1038                 return;
1039
1040         enable_irq(gpio_to_irq(slot->detect_pin));
1041         present = !(gpio_get_value(slot->detect_pin) ^
1042                     slot->detect_is_active_high);
1043         present_old = test_bit(ATMCI_CARD_PRESENT, &slot->flags);
1044
1045         dev_vdbg(&slot->mmc->class_dev, "detect change: %d (was %d)\n",
1046                         present, present_old);
1047
1048         if (present != present_old) {
1049                 struct atmel_mci        *host = slot->host;
1050                 struct mmc_request      *mrq;
1051
1052                 dev_dbg(&slot->mmc->class_dev, "card %s\n",
1053                         present ? "inserted" : "removed");
1054
1055                 spin_lock(&host->lock);
1056
1057                 if (!present)
1058                         clear_bit(ATMCI_CARD_PRESENT, &slot->flags);
1059                 else
1060                         set_bit(ATMCI_CARD_PRESENT, &slot->flags);
1061
1062                 /* Clean up queue if present */
1063                 mrq = slot->mrq;
1064                 if (mrq) {
1065                         if (mrq == host->mrq) {
1066                                 /*
1067                                  * Reset controller to terminate any ongoing
1068                                  * commands or data transfers.
1069                                  */
1070                                 mci_writel(host, CR, MCI_CR_SWRST);
1071                                 mci_writel(host, CR, MCI_CR_MCIEN);
1072                                 mci_writel(host, MR, host->mode_reg);
1073
1074                                 host->data = NULL;
1075                                 host->cmd = NULL;
1076
1077                                 switch (host->state) {
1078                                 case STATE_IDLE:
1079                                         break;
1080                                 case STATE_SENDING_CMD:
1081                                         mrq->cmd->error = -ENOMEDIUM;
1082                                         if (!mrq->data)
1083                                                 break;
1084                                         /* fall through */
1085                                 case STATE_SENDING_DATA:
1086                                         mrq->data->error = -ENOMEDIUM;
1087                                         atmci_stop_dma(host);
1088                                         break;
1089                                 case STATE_DATA_BUSY:
1090                                 case STATE_DATA_ERROR:
1091                                         if (mrq->data->error == -EINPROGRESS)
1092                                                 mrq->data->error = -ENOMEDIUM;
1093                                         if (!mrq->stop)
1094                                                 break;
1095                                         /* fall through */
1096                                 case STATE_SENDING_STOP:
1097                                         mrq->stop->error = -ENOMEDIUM;
1098                                         break;
1099                                 }
1100
1101                                 atmci_request_end(host, mrq);
1102                         } else {
1103                                 list_del(&slot->queue_node);
1104                                 mrq->cmd->error = -ENOMEDIUM;
1105                                 if (mrq->data)
1106                                         mrq->data->error = -ENOMEDIUM;
1107                                 if (mrq->stop)
1108                                         mrq->stop->error = -ENOMEDIUM;
1109
1110                                 spin_unlock(&host->lock);
1111                                 mmc_request_done(slot->mmc, mrq);
1112                                 spin_lock(&host->lock);
1113                         }
1114                 }
1115                 spin_unlock(&host->lock);
1116
1117                 mmc_detect_change(slot->mmc, 0);
1118         }
1119 }
1120
1121 static void atmci_tasklet_func(unsigned long priv)
1122 {
1123         struct atmel_mci        *host = (struct atmel_mci *)priv;
1124         struct mmc_request      *mrq = host->mrq;
1125         struct mmc_data         *data = host->data;
1126         struct mmc_command      *cmd = host->cmd;
1127         enum atmel_mci_state    state = host->state;
1128         enum atmel_mci_state    prev_state;
1129         u32                     status;
1130
1131         spin_lock(&host->lock);
1132
1133         state = host->state;
1134
1135         dev_vdbg(&host->pdev->dev,
1136                 "tasklet: state %u pending/completed/mask %lx/%lx/%x\n",
1137                 state, host->pending_events, host->completed_events,
1138                 mci_readl(host, IMR));
1139
1140         do {
1141                 prev_state = state;
1142
1143                 switch (state) {
1144                 case STATE_IDLE:
1145                         break;
1146
1147                 case STATE_SENDING_CMD:
1148                         if (!atmci_test_and_clear_pending(host,
1149                                                 EVENT_CMD_COMPLETE))
1150                                 break;
1151
1152                         host->cmd = NULL;
1153                         atmci_set_completed(host, EVENT_CMD_COMPLETE);
1154                         atmci_command_complete(host, mrq->cmd);
1155                         if (!mrq->data || cmd->error) {
1156                                 atmci_request_end(host, host->mrq);
1157                                 goto unlock;
1158                         }
1159
1160                         prev_state = state = STATE_SENDING_DATA;
1161                         /* fall through */
1162
1163                 case STATE_SENDING_DATA:
1164                         if (atmci_test_and_clear_pending(host,
1165                                                 EVENT_DATA_ERROR)) {
1166                                 atmci_stop_dma(host);
1167                                 if (data->stop)
1168                                         send_stop_cmd(host, data);
1169                                 state = STATE_DATA_ERROR;
1170                                 break;
1171                         }
1172
1173                         if (!atmci_test_and_clear_pending(host,
1174                                                 EVENT_XFER_COMPLETE))
1175                                 break;
1176
1177                         atmci_set_completed(host, EVENT_XFER_COMPLETE);
1178                         prev_state = state = STATE_DATA_BUSY;
1179                         /* fall through */
1180
1181                 case STATE_DATA_BUSY:
1182                         if (!atmci_test_and_clear_pending(host,
1183                                                 EVENT_DATA_COMPLETE))
1184                                 break;
1185
1186                         host->data = NULL;
1187                         atmci_set_completed(host, EVENT_DATA_COMPLETE);
1188                         status = host->data_status;
1189                         if (unlikely(status & ATMCI_DATA_ERROR_FLAGS)) {
1190                                 if (status & MCI_DTOE) {
1191                                         dev_dbg(&host->pdev->dev,
1192                                                         "data timeout error\n");
1193                                         data->error = -ETIMEDOUT;
1194                                 } else if (status & MCI_DCRCE) {
1195                                         dev_dbg(&host->pdev->dev,
1196                                                         "data CRC error\n");
1197                                         data->error = -EILSEQ;
1198                                 } else {
1199                                         dev_dbg(&host->pdev->dev,
1200                                                 "data FIFO error (status=%08x)\n",
1201                                                 status);
1202                                         data->error = -EIO;
1203                                 }
1204                         } else {
1205                                 data->bytes_xfered = data->blocks * data->blksz;
1206                                 data->error = 0;
1207                         }
1208
1209                         if (!data->stop) {
1210                                 atmci_request_end(host, host->mrq);
1211                                 goto unlock;
1212                         }
1213
1214                         prev_state = state = STATE_SENDING_STOP;
1215                         if (!data->error)
1216                                 send_stop_cmd(host, data);
1217                         /* fall through */
1218
1219                 case STATE_SENDING_STOP:
1220                         if (!atmci_test_and_clear_pending(host,
1221                                                 EVENT_CMD_COMPLETE))
1222                                 break;
1223
1224                         host->cmd = NULL;
1225                         atmci_command_complete(host, mrq->stop);
1226                         atmci_request_end(host, host->mrq);
1227                         goto unlock;
1228
1229                 case STATE_DATA_ERROR:
1230                         if (!atmci_test_and_clear_pending(host,
1231                                                 EVENT_XFER_COMPLETE))
1232                                 break;
1233
1234                         state = STATE_DATA_BUSY;
1235                         break;
1236                 }
1237         } while (state != prev_state);
1238
1239         host->state = state;
1240
1241 unlock:
1242         spin_unlock(&host->lock);
1243 }
1244
1245 static void atmci_read_data_pio(struct atmel_mci *host)
1246 {
1247         struct scatterlist      *sg = host->sg;
1248         void                    *buf = sg_virt(sg);
1249         unsigned int            offset = host->pio_offset;
1250         struct mmc_data         *data = host->data;
1251         u32                     value;
1252         u32                     status;
1253         unsigned int            nbytes = 0;
1254
1255         do {
1256                 value = mci_readl(host, RDR);
1257                 if (likely(offset + 4 <= sg->length)) {
1258                         put_unaligned(value, (u32 *)(buf + offset));
1259
1260                         offset += 4;
1261                         nbytes += 4;
1262
1263                         if (offset == sg->length) {
1264                                 flush_dcache_page(sg_page(sg));
1265                                 host->sg = sg = sg_next(sg);
1266                                 if (!sg)
1267                                         goto done;
1268
1269                                 offset = 0;
1270                                 buf = sg_virt(sg);
1271                         }
1272                 } else {
1273                         unsigned int remaining = sg->length - offset;
1274                         memcpy(buf + offset, &value, remaining);
1275                         nbytes += remaining;
1276
1277                         flush_dcache_page(sg_page(sg));
1278                         host->sg = sg = sg_next(sg);
1279                         if (!sg)
1280                                 goto done;
1281
1282                         offset = 4 - remaining;
1283                         buf = sg_virt(sg);
1284                         memcpy(buf, (u8 *)&value + remaining, offset);
1285                         nbytes += offset;
1286                 }
1287
1288                 status = mci_readl(host, SR);
1289                 if (status & ATMCI_DATA_ERROR_FLAGS) {
1290                         mci_writel(host, IDR, (MCI_NOTBUSY | MCI_RXRDY
1291                                                 | ATMCI_DATA_ERROR_FLAGS));
1292                         host->data_status = status;
1293                         data->bytes_xfered += nbytes;
1294                         smp_wmb();
1295                         atmci_set_pending(host, EVENT_DATA_ERROR);
1296                         tasklet_schedule(&host->tasklet);
1297                         return;
1298                 }
1299         } while (status & MCI_RXRDY);
1300
1301         host->pio_offset = offset;
1302         data->bytes_xfered += nbytes;
1303
1304         return;
1305
1306 done:
1307         mci_writel(host, IDR, MCI_RXRDY);
1308         mci_writel(host, IER, MCI_NOTBUSY);
1309         data->bytes_xfered += nbytes;
1310         smp_wmb();
1311         atmci_set_pending(host, EVENT_XFER_COMPLETE);
1312 }
1313
1314 static void atmci_write_data_pio(struct atmel_mci *host)
1315 {
1316         struct scatterlist      *sg = host->sg;
1317         void                    *buf = sg_virt(sg);
1318         unsigned int            offset = host->pio_offset;
1319         struct mmc_data         *data = host->data;
1320         u32                     value;
1321         u32                     status;
1322         unsigned int            nbytes = 0;
1323
1324         do {
1325                 if (likely(offset + 4 <= sg->length)) {
1326                         value = get_unaligned((u32 *)(buf + offset));
1327                         mci_writel(host, TDR, value);
1328
1329                         offset += 4;
1330                         nbytes += 4;
1331                         if (offset == sg->length) {
1332                                 host->sg = sg = sg_next(sg);
1333                                 if (!sg)
1334                                         goto done;
1335
1336                                 offset = 0;
1337                                 buf = sg_virt(sg);
1338                         }
1339                 } else {
1340                         unsigned int remaining = sg->length - offset;
1341
1342                         value = 0;
1343                         memcpy(&value, buf + offset, remaining);
1344                         nbytes += remaining;
1345
1346                         host->sg = sg = sg_next(sg);
1347                         if (!sg) {
1348                                 mci_writel(host, TDR, value);
1349                                 goto done;
1350                         }
1351
1352                         offset = 4 - remaining;
1353                         buf = sg_virt(sg);
1354                         memcpy((u8 *)&value + remaining, buf, offset);
1355                         mci_writel(host, TDR, value);
1356                         nbytes += offset;
1357                 }
1358
1359                 status = mci_readl(host, SR);
1360                 if (status & ATMCI_DATA_ERROR_FLAGS) {
1361                         mci_writel(host, IDR, (MCI_NOTBUSY | MCI_TXRDY
1362                                                 | ATMCI_DATA_ERROR_FLAGS));
1363                         host->data_status = status;
1364                         data->bytes_xfered += nbytes;
1365                         smp_wmb();
1366                         atmci_set_pending(host, EVENT_DATA_ERROR);
1367                         tasklet_schedule(&host->tasklet);
1368                         return;
1369                 }
1370         } while (status & MCI_TXRDY);
1371
1372         host->pio_offset = offset;
1373         data->bytes_xfered += nbytes;
1374
1375         return;
1376
1377 done:
1378         mci_writel(host, IDR, MCI_TXRDY);
1379         mci_writel(host, IER, MCI_NOTBUSY);
1380         data->bytes_xfered += nbytes;
1381         smp_wmb();
1382         atmci_set_pending(host, EVENT_XFER_COMPLETE);
1383 }
1384
1385 static void atmci_cmd_interrupt(struct atmel_mci *host, u32 status)
1386 {
1387         mci_writel(host, IDR, MCI_CMDRDY);
1388
1389         host->cmd_status = status;
1390         smp_wmb();
1391         atmci_set_pending(host, EVENT_CMD_COMPLETE);
1392         tasklet_schedule(&host->tasklet);
1393 }
1394
1395 static irqreturn_t atmci_interrupt(int irq, void *dev_id)
1396 {
1397         struct atmel_mci        *host = dev_id;
1398         u32                     status, mask, pending;
1399         unsigned int            pass_count = 0;
1400
1401         do {
1402                 status = mci_readl(host, SR);
1403                 mask = mci_readl(host, IMR);
1404                 pending = status & mask;
1405                 if (!pending)
1406                         break;
1407
1408                 if (pending & ATMCI_DATA_ERROR_FLAGS) {
1409                         mci_writel(host, IDR, ATMCI_DATA_ERROR_FLAGS
1410                                         | MCI_RXRDY | MCI_TXRDY);
1411                         pending &= mci_readl(host, IMR);
1412
1413                         host->data_status = status;
1414                         smp_wmb();
1415                         atmci_set_pending(host, EVENT_DATA_ERROR);
1416                         tasklet_schedule(&host->tasklet);
1417                 }
1418                 if (pending & MCI_NOTBUSY) {
1419                         mci_writel(host, IDR,
1420                                         ATMCI_DATA_ERROR_FLAGS | MCI_NOTBUSY);
1421                         if (!host->data_status)
1422                                 host->data_status = status;
1423                         smp_wmb();
1424                         atmci_set_pending(host, EVENT_DATA_COMPLETE);
1425                         tasklet_schedule(&host->tasklet);
1426                 }
1427                 if (pending & MCI_RXRDY)
1428                         atmci_read_data_pio(host);
1429                 if (pending & MCI_TXRDY)
1430                         atmci_write_data_pio(host);
1431
1432                 if (pending & MCI_CMDRDY)
1433                         atmci_cmd_interrupt(host, status);
1434         } while (pass_count++ < 5);
1435
1436         return pass_count ? IRQ_HANDLED : IRQ_NONE;
1437 }
1438
1439 static irqreturn_t atmci_detect_interrupt(int irq, void *dev_id)
1440 {
1441         struct atmel_mci_slot   *slot = dev_id;
1442
1443         /*
1444          * Disable interrupts until the pin has stabilized and check
1445          * the state then. Use mod_timer() since we may be in the
1446          * middle of the timer routine when this interrupt triggers.
1447          */
1448         disable_irq_nosync(irq);
1449         mod_timer(&slot->detect_timer, jiffies + msecs_to_jiffies(20));
1450
1451         return IRQ_HANDLED;
1452 }
1453
1454 static int __init atmci_init_slot(struct atmel_mci *host,
1455                 struct mci_slot_pdata *slot_data, unsigned int id,
1456                 u32 sdc_reg)
1457 {
1458         struct mmc_host                 *mmc;
1459         struct atmel_mci_slot           *slot;
1460
1461         mmc = mmc_alloc_host(sizeof(struct atmel_mci_slot), &host->pdev->dev);
1462         if (!mmc)
1463                 return -ENOMEM;
1464
1465         slot = mmc_priv(mmc);
1466         slot->mmc = mmc;
1467         slot->host = host;
1468         slot->detect_pin = slot_data->detect_pin;
1469         slot->wp_pin = slot_data->wp_pin;
1470         slot->detect_is_active_high = slot_data->detect_is_active_high;
1471         slot->sdc_reg = sdc_reg;
1472
1473         mmc->ops = &atmci_ops;
1474         mmc->f_min = DIV_ROUND_UP(host->bus_hz, 512);
1475         mmc->f_max = host->bus_hz / 2;
1476         mmc->ocr_avail  = MMC_VDD_32_33 | MMC_VDD_33_34;
1477         if (slot_data->bus_width >= 4)
1478                 mmc->caps |= MMC_CAP_4_BIT_DATA;
1479
1480         mmc->max_hw_segs = 64;
1481         mmc->max_phys_segs = 64;
1482         mmc->max_req_size = 32768 * 512;
1483         mmc->max_blk_size = 32768;
1484         mmc->max_blk_count = 512;
1485
1486         /* Assume card is present initially */
1487         set_bit(ATMCI_CARD_PRESENT, &slot->flags);
1488         if (gpio_is_valid(slot->detect_pin)) {
1489                 if (gpio_request(slot->detect_pin, "mmc_detect")) {
1490                         dev_dbg(&mmc->class_dev, "no detect pin available\n");
1491                         slot->detect_pin = -EBUSY;
1492                 } else if (gpio_get_value(slot->detect_pin) ^
1493                                 slot->detect_is_active_high) {
1494                         clear_bit(ATMCI_CARD_PRESENT, &slot->flags);
1495                 }
1496         }
1497
1498         if (!gpio_is_valid(slot->detect_pin))
1499                 mmc->caps |= MMC_CAP_NEEDS_POLL;
1500
1501         if (gpio_is_valid(slot->wp_pin)) {
1502                 if (gpio_request(slot->wp_pin, "mmc_wp")) {
1503                         dev_dbg(&mmc->class_dev, "no WP pin available\n");
1504                         slot->wp_pin = -EBUSY;
1505                 }
1506         }
1507
1508         host->slot[id] = slot;
1509         mmc_add_host(mmc);
1510
1511         if (gpio_is_valid(slot->detect_pin)) {
1512                 int ret;
1513
1514                 setup_timer(&slot->detect_timer, atmci_detect_change,
1515                                 (unsigned long)slot);
1516
1517                 ret = request_irq(gpio_to_irq(slot->detect_pin),
1518                                 atmci_detect_interrupt,
1519                                 IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING,
1520                                 "mmc-detect", slot);
1521                 if (ret) {
1522                         dev_dbg(&mmc->class_dev,
1523                                 "could not request IRQ %d for detect pin\n",
1524                                 gpio_to_irq(slot->detect_pin));
1525                         gpio_free(slot->detect_pin);
1526                         slot->detect_pin = -EBUSY;
1527                 }
1528         }
1529
1530         atmci_init_debugfs(slot);
1531
1532         return 0;
1533 }
1534
1535 static void __exit atmci_cleanup_slot(struct atmel_mci_slot *slot,
1536                 unsigned int id)
1537 {
1538         /* Debugfs stuff is cleaned up by mmc core */
1539
1540         set_bit(ATMCI_SHUTDOWN, &slot->flags);
1541         smp_wmb();
1542
1543         mmc_remove_host(slot->mmc);
1544
1545         if (gpio_is_valid(slot->detect_pin)) {
1546                 int pin = slot->detect_pin;
1547
1548                 free_irq(gpio_to_irq(pin), slot);
1549                 del_timer_sync(&slot->detect_timer);
1550                 gpio_free(pin);
1551         }
1552         if (gpio_is_valid(slot->wp_pin))
1553                 gpio_free(slot->wp_pin);
1554
1555         slot->host->slot[id] = NULL;
1556         mmc_free_host(slot->mmc);
1557 }
1558
1559 #ifdef CONFIG_MMC_ATMELMCI_DMA
1560 static bool filter(struct dma_chan *chan, void *slave)
1561 {
1562         struct dw_dma_slave *dws = slave;
1563
1564         if (dws->dma_dev == chan->device->dev) {
1565                 chan->private = dws;
1566                 return true;
1567         } else
1568                 return false;
1569 }
1570 #endif
1571
1572 static int __init atmci_probe(struct platform_device *pdev)
1573 {
1574         struct mci_platform_data        *pdata;
1575         struct atmel_mci                *host;
1576         struct resource                 *regs;
1577         unsigned int                    nr_slots;
1578         int                             irq;
1579         int                             ret;
1580
1581         regs = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1582         if (!regs)
1583                 return -ENXIO;
1584         pdata = pdev->dev.platform_data;
1585         if (!pdata)
1586                 return -ENXIO;
1587         irq = platform_get_irq(pdev, 0);
1588         if (irq < 0)
1589                 return irq;
1590
1591         host = kzalloc(sizeof(struct atmel_mci), GFP_KERNEL);
1592         if (!host)
1593                 return -ENOMEM;
1594
1595         host->pdev = pdev;
1596         spin_lock_init(&host->lock);
1597         INIT_LIST_HEAD(&host->queue);
1598
1599         host->mck = clk_get(&pdev->dev, "mci_clk");
1600         if (IS_ERR(host->mck)) {
1601                 ret = PTR_ERR(host->mck);
1602                 goto err_clk_get;
1603         }
1604
1605         ret = -ENOMEM;
1606         host->regs = ioremap(regs->start, regs->end - regs->start + 1);
1607         if (!host->regs)
1608                 goto err_ioremap;
1609
1610         clk_enable(host->mck);
1611         mci_writel(host, CR, MCI_CR_SWRST);
1612         host->bus_hz = clk_get_rate(host->mck);
1613         clk_disable(host->mck);
1614
1615         host->mapbase = regs->start;
1616
1617         tasklet_init(&host->tasklet, atmci_tasklet_func, (unsigned long)host);
1618
1619         ret = request_irq(irq, atmci_interrupt, 0, dev_name(&pdev->dev), host);
1620         if (ret)
1621                 goto err_request_irq;
1622
1623 #ifdef CONFIG_MMC_ATMELMCI_DMA
1624         if (pdata->dma_slave.dma_dev) {
1625                 struct dw_dma_slave *dws = &pdata->dma_slave;
1626                 dma_cap_mask_t mask;
1627
1628                 dws->tx_reg = regs->start + MCI_TDR;
1629                 dws->rx_reg = regs->start + MCI_RDR;
1630
1631                 /* Try to grab a DMA channel */
1632                 dma_cap_zero(mask);
1633                 dma_cap_set(DMA_SLAVE, mask);
1634                 host->dma.chan = dma_request_channel(mask, filter, dws);
1635         }
1636         if (!host->dma.chan)
1637                 dev_notice(&pdev->dev, "DMA not available, using PIO\n");
1638 #endif /* CONFIG_MMC_ATMELMCI_DMA */
1639
1640         platform_set_drvdata(pdev, host);
1641
1642         /* We need at least one slot to succeed */
1643         nr_slots = 0;
1644         ret = -ENODEV;
1645         if (pdata->slot[0].bus_width) {
1646                 ret = atmci_init_slot(host, &pdata->slot[0],
1647                                 MCI_SDCSEL_SLOT_A, 0);
1648                 if (!ret)
1649                         nr_slots++;
1650         }
1651         if (pdata->slot[1].bus_width) {
1652                 ret = atmci_init_slot(host, &pdata->slot[1],
1653                                 MCI_SDCSEL_SLOT_B, 1);
1654                 if (!ret)
1655                         nr_slots++;
1656         }
1657
1658         if (!nr_slots)
1659                 goto err_init_slot;
1660
1661         dev_info(&pdev->dev,
1662                         "Atmel MCI controller at 0x%08lx irq %d, %u slots\n",
1663                         host->mapbase, irq, nr_slots);
1664
1665         return 0;
1666
1667 err_init_slot:
1668 #ifdef CONFIG_MMC_ATMELMCI_DMA
1669         if (host->dma.chan)
1670                 dma_release_channel(host->dma.chan);
1671 #endif
1672         free_irq(irq, host);
1673 err_request_irq:
1674         iounmap(host->regs);
1675 err_ioremap:
1676         clk_put(host->mck);
1677 err_clk_get:
1678         kfree(host);
1679         return ret;
1680 }
1681
1682 static int __exit atmci_remove(struct platform_device *pdev)
1683 {
1684         struct atmel_mci        *host = platform_get_drvdata(pdev);
1685         unsigned int            i;
1686
1687         platform_set_drvdata(pdev, NULL);
1688
1689         for (i = 0; i < ATMEL_MCI_MAX_NR_SLOTS; i++) {
1690                 if (host->slot[i])
1691                         atmci_cleanup_slot(host->slot[i], i);
1692         }
1693
1694         clk_enable(host->mck);
1695         mci_writel(host, IDR, ~0UL);
1696         mci_writel(host, CR, MCI_CR_MCIDIS);
1697         mci_readl(host, SR);
1698         clk_disable(host->mck);
1699
1700 #ifdef CONFIG_MMC_ATMELMCI_DMA
1701         if (host->dma.chan)
1702                 dma_release_channel(host->dma.chan);
1703 #endif
1704
1705         free_irq(platform_get_irq(pdev, 0), host);
1706         iounmap(host->regs);
1707
1708         clk_put(host->mck);
1709         kfree(host);
1710
1711         return 0;
1712 }
1713
1714 static struct platform_driver atmci_driver = {
1715         .remove         = __exit_p(atmci_remove),
1716         .driver         = {
1717                 .name           = "atmel_mci",
1718         },
1719 };
1720
1721 static int __init atmci_init(void)
1722 {
1723         return platform_driver_probe(&atmci_driver, atmci_probe);
1724 }
1725
1726 static void __exit atmci_exit(void)
1727 {
1728         platform_driver_unregister(&atmci_driver);
1729 }
1730
1731 late_initcall(atmci_init); /* try to load after dma driver when built-in */
1732 module_exit(atmci_exit);
1733
1734 MODULE_DESCRIPTION("Atmel Multimedia Card Interface driver");
1735 MODULE_AUTHOR("Haavard Skinnemoen <haavard.skinnemoen@atmel.com>");
1736 MODULE_LICENSE("GPL v2");