]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/arm/at91/at91_mci.c
Further cleanup of per-CPU armv6 pmap data:
[FreeBSD/FreeBSD.git] / sys / arm / at91 / at91_mci.c
1 /*-
2  * Copyright (c) 2006 Bernd Walter.  All rights reserved.
3  * Copyright (c) 2006 M. Warner Losh.  All rights reserved.
4  * Copyright (c) 2010 Greg Ansley.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27
28 #include "opt_platform.h"
29
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/bio.h>
36 #include <sys/bus.h>
37 #include <sys/conf.h>
38 #include <sys/endian.h>
39 #include <sys/kernel.h>
40 #include <sys/kthread.h>
41 #include <sys/lock.h>
42 #include <sys/malloc.h>
43 #include <sys/module.h>
44 #include <sys/mutex.h>
45 #include <sys/queue.h>
46 #include <sys/resource.h>
47 #include <sys/rman.h>
48 #include <sys/sysctl.h>
49 #include <sys/time.h>
50 #include <sys/timetc.h>
51 #include <sys/watchdog.h>
52
53 #include <machine/bus.h>
54 #include <machine/resource.h>
55 #include <machine/intr.h>
56
57 #include <arm/at91/at91var.h>
58 #include <arm/at91/at91_mcireg.h>
59 #include <arm/at91/at91_pdcreg.h>
60
61 #include <dev/mmc/bridge.h>
62 #include <dev/mmc/mmcreg.h>
63 #include <dev/mmc/mmcbrvar.h>
64
65 #ifdef FDT
66 #include <dev/ofw/ofw_bus.h>
67 #include <dev/ofw/ofw_bus_subr.h>
68 #endif
69
70 #include "mmcbr_if.h"
71
72 #include "opt_at91.h"
73
74 /*
75  * About running the MCI bus above 25MHz
76  *
77  * Historically, the MCI bus has been run at 30MHz on systems with a 60MHz
78  * master clock, in part due to a bug in dev/mmc.c making always request
79  * 30MHz, and in part over clocking the bus because 15MHz was too slow.
80  * Fixing that bug causes the mmc driver to request a 25MHz clock (as it
81  * should) and the logic in at91_mci_update_ios() picks the highest speed that
82  * doesn't exceed that limit.  With a 60MHz MCK that would be 15MHz, and
83  * that's a real performance buzzkill when you've been getting away with 30MHz
84  * all along.
85  *
86  * By defining AT91_MCI_ALLOW_OVERCLOCK (or setting the allow_overclock=1
87  * device hint or sysctl) you can enable logic in at91_mci_update_ios() to
88  * overlcock the SD bus a little by running it at MCK / 2 when the requested
89  * speed is 25MHz and the next highest speed is 15MHz or less.  This appears
90  * to work on virtually all SD cards, since it is what this driver has been
91  * doing prior to the introduction of this option, where the overclocking vs
92  * underclocking decision was automatically "overclock".  Modern SD cards can
93  * run at 45mhz/1-bit in standard mode (high speed mode enable commands not
94  * sent) without problems.
95  *
96  * Speaking of high-speed mode, the rm9200 manual says the MCI device supports
97  * the SD v1.0 specification and can run up to 50MHz.  This is interesting in
98  * that the SD v1.0 spec caps the speed at 25MHz; high speed mode was added in
99  * the v1.10 spec.  Furthermore, high speed mode doesn't just crank up the
100  * clock, it alters the signal timing.  The rm9200 MCI device doesn't support
101  * these altered timings.  So while speeds over 25MHz may work, they only work
102  * in what the SD spec calls "default" speed mode, and it amounts to violating
103  * the spec by overclocking the bus.
104  *
105  * If you also enable 4-wire mode it's possible transfers faster than 25MHz
106  * will fail.  On the AT91RM9200, due to bugs in the bus contention logic, if
107  * you have the USB host device and OHCI driver enabled will fail.  Even
108  * underclocking to 15MHz, intermittant overrun and underrun errors occur.
109  * Note that you don't even need to have usb devices attached to the system,
110  * the errors begin to occur as soon as the OHCI driver sets the register bit
111  * to enable periodic transfers.  It appears (based on brief investigation)
112  * that the usb host controller uses so much ASB bandwidth that sometimes the
113  * DMA for MCI transfers doesn't get a bus grant in time and data gets
114  * dropped.  Adding even a modicum of network activity changes the symptom
115  * from intermittant to very frequent.  Members of the AT91SAM9 family have
116  * corrected this problem, or are at least better about their use of the bus.
117  */
118 #ifndef AT91_MCI_ALLOW_OVERCLOCK
119 #define AT91_MCI_ALLOW_OVERCLOCK 1
120 #endif
121
122 /*
123  * Allocate 2 bounce buffers we'll use to endian-swap the data due to the rm9200
124  * erratum.  We use a pair of buffers because when reading that lets us begin
125  * endian-swapping the data in the first buffer while the DMA is reading into
126  * the second buffer.  (We can't use the same trick for writing because we might
127  * not get all the data in the 2nd buffer swapped before the hardware needs it;
128  * dealing with that would add complexity to the driver.)
129  *
130  * The buffers are sized at 16K each due to the way the busdma cache sync
131  * operations work on arm.  A dcache_inv_range() operation on a range larger
132  * than 16K gets turned into a dcache_wbinv_all().  That needlessly flushes the
133  * entire data cache, impacting overall system performance.
134  */
135 #define BBCOUNT     2
136 #define BBSIZE      (16*1024)
137 #define MAX_BLOCKS  ((BBSIZE*BBCOUNT)/512)
138
139 static int mci_debug;
140
141 struct at91_mci_softc {
142         void *intrhand;                 /* Interrupt handle */
143         device_t dev;
144         int sc_cap;
145 #define CAP_HAS_4WIRE           1       /* Has 4 wire bus */
146 #define CAP_NEEDS_BYTESWAP      2       /* broken hardware needing bounce */
147 #define CAP_MCI1_REV2XX         4       /* MCI 1 rev 2.x */
148         int flags;
149 #define PENDING_CMD     0x01
150 #define PENDING_STOP    0x02
151 #define CMD_MULTIREAD   0x10
152 #define CMD_MULTIWRITE  0x20
153         int has_4wire;
154         int allow_overclock;
155         struct resource *irq_res;       /* IRQ resource */
156         struct resource *mem_res;       /* Memory resource */
157         struct mtx sc_mtx;
158         bus_dma_tag_t dmatag;
159         struct mmc_host host;
160         int bus_busy;
161         struct mmc_request *req;
162         struct mmc_command *curcmd;
163         bus_dmamap_t bbuf_map[BBCOUNT];
164         char      *  bbuf_vaddr[BBCOUNT]; /* bounce bufs in KVA space */
165         uint32_t     bbuf_len[BBCOUNT];   /* len currently queued for bounce buf */
166         uint32_t     bbuf_curidx;         /* which bbuf is the active DMA buffer */
167         uint32_t     xfer_offset;         /* offset so far into caller's buf */
168 };
169
170 /* bus entry points */
171 static int at91_mci_probe(device_t dev);
172 static int at91_mci_attach(device_t dev);
173 static int at91_mci_detach(device_t dev);
174 static void at91_mci_intr(void *);
175
176 /* helper routines */
177 static int at91_mci_activate(device_t dev);
178 static void at91_mci_deactivate(device_t dev);
179 static int at91_mci_is_mci1rev2xx(void);
180
181 #define AT91_MCI_LOCK(_sc)              mtx_lock(&(_sc)->sc_mtx)
182 #define AT91_MCI_UNLOCK(_sc)            mtx_unlock(&(_sc)->sc_mtx)
183 #define AT91_MCI_LOCK_INIT(_sc) \
184         mtx_init(&_sc->sc_mtx, device_get_nameunit(_sc->dev), \
185             "mci", MTX_DEF)
186 #define AT91_MCI_LOCK_DESTROY(_sc)      mtx_destroy(&_sc->sc_mtx);
187 #define AT91_MCI_ASSERT_LOCKED(_sc)     mtx_assert(&_sc->sc_mtx, MA_OWNED);
188 #define AT91_MCI_ASSERT_UNLOCKED(_sc) mtx_assert(&_sc->sc_mtx, MA_NOTOWNED);
189
190 static inline uint32_t
191 RD4(struct at91_mci_softc *sc, bus_size_t off)
192 {
193         return (bus_read_4(sc->mem_res, off));
194 }
195
196 static inline void
197 WR4(struct at91_mci_softc *sc, bus_size_t off, uint32_t val)
198 {
199         bus_write_4(sc->mem_res, off, val);
200 }
201
202 static void
203 at91_bswap_buf(struct at91_mci_softc *sc, void * dptr, void * sptr, uint32_t memsize)
204 {
205         uint32_t * dst = (uint32_t *)dptr;
206         uint32_t * src = (uint32_t *)sptr;
207         uint32_t   i;
208
209         /*
210          * If the hardware doesn't need byte-swapping, let bcopy() do the
211          * work.  Use bounce buffer even if we don't need byteswap, since
212          * buffer may straddle a page boundary, and we don't handle
213          * multi-segment transfers in hardware.  Seen from 'bsdlabel -w' which
214          * uses raw geom access to the volume.  Greg Ansley (gja (at)
215          * ansley.com)
216          */
217         if (!(sc->sc_cap & CAP_NEEDS_BYTESWAP)) {
218                 memcpy(dptr, sptr, memsize);
219                 return;
220         }
221
222         /*
223          * Nice performance boost for slightly unrolling this loop.
224          * (But very little extra boost for further unrolling it.)
225          */
226         for (i = 0; i < memsize; i += 16) {
227                 *dst++ = bswap32(*src++);
228                 *dst++ = bswap32(*src++);
229                 *dst++ = bswap32(*src++);
230                 *dst++ = bswap32(*src++);
231         }
232
233         /* Mop up the last 1-3 words, if any. */
234         for (i = 0; i < (memsize & 0x0F); i += 4) {
235                 *dst++ = bswap32(*src++);
236         }
237 }
238
239 static void
240 at91_mci_getaddr(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
241 {
242         if (error != 0)
243                 return;
244         *(bus_addr_t *)arg = segs[0].ds_addr;
245 }
246
247 static void
248 at91_mci_pdc_disable(struct at91_mci_softc *sc)
249 {
250         WR4(sc, PDC_PTCR, PDC_PTCR_TXTDIS | PDC_PTCR_RXTDIS);
251         WR4(sc, PDC_RPR, 0);
252         WR4(sc, PDC_RCR, 0);
253         WR4(sc, PDC_RNPR, 0);
254         WR4(sc, PDC_RNCR, 0);
255         WR4(sc, PDC_TPR, 0);
256         WR4(sc, PDC_TCR, 0);
257         WR4(sc, PDC_TNPR, 0);
258         WR4(sc, PDC_TNCR, 0);
259 }
260
261 /*
262  * Reset the controller, then restore most of the current state.
263  *
264  * This is called after detecting an error.  It's also called after stopping a
265  * multi-block write, to un-wedge the device so that it will handle the NOTBUSY
266  * signal correctly.  See comments in at91_mci_stop_done() for more details.
267  */
268 static void at91_mci_reset(struct at91_mci_softc *sc)
269 {
270         uint32_t mr;
271         uint32_t sdcr;
272         uint32_t dtor;
273         uint32_t imr;
274
275         at91_mci_pdc_disable(sc);
276
277         /* save current state */
278
279         imr  = RD4(sc, MCI_IMR);
280         mr   = RD4(sc, MCI_MR) & 0x7fff;
281         sdcr = RD4(sc, MCI_SDCR);
282         dtor = RD4(sc, MCI_DTOR);
283
284         /* reset the controller */
285
286         WR4(sc, MCI_IDR, 0xffffffff);
287         WR4(sc, MCI_CR, MCI_CR_MCIDIS | MCI_CR_SWRST);
288
289         /* restore state */
290
291         WR4(sc, MCI_CR, MCI_CR_MCIEN|MCI_CR_PWSEN);
292         WR4(sc, MCI_MR, mr);
293         WR4(sc, MCI_SDCR, sdcr);
294         WR4(sc, MCI_DTOR, dtor);
295         WR4(sc, MCI_IER, imr);
296
297         /*
298          * Make sure sdio interrupts will fire.  Not sure why reading
299          * SR ensures that, but this is in the linux driver.
300          */
301
302         RD4(sc, MCI_SR);
303 }
304
305 static void
306 at91_mci_init(device_t dev)
307 {
308         struct at91_mci_softc *sc = device_get_softc(dev);
309         uint32_t val;
310
311         WR4(sc, MCI_CR, MCI_CR_MCIDIS | MCI_CR_SWRST); /* device into reset */
312         WR4(sc, MCI_IDR, 0xffffffff);           /* Turn off interrupts */
313         WR4(sc, MCI_DTOR, MCI_DTOR_DTOMUL_1M | 1);
314         val = MCI_MR_PDCMODE;
315         val |= 0x34a;                           /* PWSDIV = 3; CLKDIV = 74 */
316 //      if (sc->sc_cap & CAP_MCI1_REV2XX)
317 //              val |= MCI_MR_RDPROOF | MCI_MR_WRPROOF;
318         WR4(sc, MCI_MR, val);
319 #ifndef  AT91_MCI_SLOT_B
320         WR4(sc, MCI_SDCR, 0);                   /* SLOT A, 1 bit bus */
321 #else
322         /*
323          * XXX Really should add second "unit" but nobody using using
324          * a two slot card that we know of. XXX
325          */
326         WR4(sc, MCI_SDCR, 1);                   /* SLOT B, 1 bit bus */
327 #endif
328         /*
329          * Enable controller, including power-save.  The slower clock
330          * of the power-save mode is only in effect when there is no
331          * transfer in progress, so it can be left in this mode all
332          * the time.
333          */
334         WR4(sc, MCI_CR, MCI_CR_MCIEN|MCI_CR_PWSEN);
335 }
336
337 static void
338 at91_mci_fini(device_t dev)
339 {
340         struct at91_mci_softc *sc = device_get_softc(dev);
341
342         WR4(sc, MCI_IDR, 0xffffffff);           /* Turn off interrupts */
343         at91_mci_pdc_disable(sc);
344         WR4(sc, MCI_CR, MCI_CR_MCIDIS | MCI_CR_SWRST); /* device into reset */
345 }
346
347 static int
348 at91_mci_probe(device_t dev)
349 {
350 #ifdef FDT
351         if (!ofw_bus_is_compatible(dev, "atmel,hsmci"))
352                 return (ENXIO);
353 #endif
354         device_set_desc(dev, "MCI mmc/sd host bridge");
355         return (0);
356 }
357
358 static int
359 at91_mci_attach(device_t dev)
360 {
361         struct at91_mci_softc *sc = device_get_softc(dev);
362         struct sysctl_ctx_list *sctx;
363         struct sysctl_oid *soid;
364         device_t child;
365         int err, i;
366
367         sctx = device_get_sysctl_ctx(dev);
368         soid = device_get_sysctl_tree(dev);
369
370         sc->dev = dev;
371         sc->sc_cap = 0;
372         if (at91_is_rm92())
373                 sc->sc_cap |= CAP_NEEDS_BYTESWAP;
374         /*
375          * MCI1 Rev 2 controllers need some workarounds, flag if so.
376          */
377         if (at91_mci_is_mci1rev2xx())
378                 sc->sc_cap |= CAP_MCI1_REV2XX;
379
380         err = at91_mci_activate(dev);
381         if (err)
382                 goto out;
383
384         AT91_MCI_LOCK_INIT(sc);
385
386         at91_mci_fini(dev);
387         at91_mci_init(dev);
388
389         /*
390          * Allocate DMA tags and maps and bounce buffers.
391          *
392          * The parms in the tag_create call cause the dmamem_alloc call to
393          * create each bounce buffer as a single contiguous buffer of BBSIZE
394          * bytes aligned to a 4096 byte boundary.
395          *
396          * Do not use DMA_COHERENT for these buffers because that maps the
397          * memory as non-cachable, which prevents cache line burst fills/writes,
398          * which is something we need since we're trying to overlap the
399          * byte-swapping with the DMA operations.
400          */
401         err = bus_dma_tag_create(bus_get_dma_tag(dev), 4096, 0,
402             BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
403             BBSIZE, 1, BBSIZE, 0, NULL, NULL, &sc->dmatag);
404         if (err != 0)
405                 goto out;
406
407         for (i = 0; i < BBCOUNT; ++i) {
408                 err = bus_dmamem_alloc(sc->dmatag, (void **)&sc->bbuf_vaddr[i],
409                     BUS_DMA_NOWAIT, &sc->bbuf_map[i]);
410                 if (err != 0)
411                         goto out;
412         }
413
414         /*
415          * Activate the interrupt
416          */
417         err = bus_setup_intr(dev, sc->irq_res, INTR_TYPE_MISC | INTR_MPSAFE,
418             NULL, at91_mci_intr, sc, &sc->intrhand);
419         if (err) {
420                 AT91_MCI_LOCK_DESTROY(sc);
421                 goto out;
422         }
423
424         /*
425          * Allow 4-wire to be initially set via #define.
426          * Allow a device hint to override that.
427          * Allow a sysctl to override that.
428          */
429 #if defined(AT91_MCI_HAS_4WIRE) && AT91_MCI_HAS_4WIRE != 0
430         sc->has_4wire = 1;
431 #endif
432         resource_int_value(device_get_name(dev), device_get_unit(dev),
433                            "4wire", &sc->has_4wire);
434         SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "4wire",
435             CTLFLAG_RW, &sc->has_4wire, 0, "has 4 wire SD Card bus");
436         if (sc->has_4wire)
437                 sc->sc_cap |= CAP_HAS_4WIRE;
438
439         sc->allow_overclock = AT91_MCI_ALLOW_OVERCLOCK;
440         resource_int_value(device_get_name(dev), device_get_unit(dev),
441                            "allow_overclock", &sc->allow_overclock);
442         SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "allow_overclock",
443             CTLFLAG_RW, &sc->allow_overclock, 0,
444             "Allow up to 30MHz clock for 25MHz request when next highest speed 15MHz or less.");
445
446         SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "debug",
447             CTLFLAG_RWTUN, &mci_debug, 0, "enable debug output");
448
449         /*
450          * Our real min freq is master_clock/512, but upper driver layers are
451          * going to set the min speed during card discovery, and the right speed
452          * for that is 400kHz, so advertise a safe value just under that.
453          *
454          * For max speed, while the rm9200 manual says the max is 50mhz, it also
455          * says it supports only the SD v1.0 spec, which means the real limit is
456          * 25mhz. On the other hand, historical use has been to slightly violate
457          * the standard by running the bus at 30MHz.  For more information on
458          * that, see the comments at the top of this file.
459          */
460         sc->host.f_min = 375000;
461         sc->host.f_max = at91_master_clock / 2;
462         if (sc->host.f_max > 25000000)
463                 sc->host.f_max = 25000000;
464         sc->host.host_ocr = MMC_OCR_320_330 | MMC_OCR_330_340;
465         sc->host.caps = 0;
466         if (sc->sc_cap & CAP_HAS_4WIRE)
467                 sc->host.caps |= MMC_CAP_4_BIT_DATA;
468
469         child = device_add_child(dev, "mmc", 0);
470         device_set_ivars(dev, &sc->host);
471         err = bus_generic_attach(dev);
472 out:
473         if (err)
474                 at91_mci_deactivate(dev);
475         return (err);
476 }
477
478 static int
479 at91_mci_detach(device_t dev)
480 {
481         struct at91_mci_softc *sc = device_get_softc(dev);
482
483         at91_mci_fini(dev);
484         at91_mci_deactivate(dev);
485
486         bus_dmamem_free(sc->dmatag, sc->bbuf_vaddr[0], sc->bbuf_map[0]);
487         bus_dmamem_free(sc->dmatag, sc->bbuf_vaddr[1], sc->bbuf_map[1]);
488         bus_dma_tag_destroy(sc->dmatag);
489
490         return (EBUSY); /* XXX */
491 }
492
493 static int
494 at91_mci_activate(device_t dev)
495 {
496         struct at91_mci_softc *sc;
497         int rid;
498
499         sc = device_get_softc(dev);
500         rid = 0;
501         sc->mem_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
502             RF_ACTIVE);
503         if (sc->mem_res == NULL)
504                 goto errout;
505
506         rid = 0;
507         sc->irq_res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
508             RF_ACTIVE);
509         if (sc->irq_res == NULL)
510                 goto errout;
511
512         return (0);
513 errout:
514         at91_mci_deactivate(dev);
515         return (ENOMEM);
516 }
517
518 static void
519 at91_mci_deactivate(device_t dev)
520 {
521         struct at91_mci_softc *sc;
522
523         sc = device_get_softc(dev);
524         if (sc->intrhand)
525                 bus_teardown_intr(dev, sc->irq_res, sc->intrhand);
526         sc->intrhand = NULL;
527         bus_generic_detach(sc->dev);
528         if (sc->mem_res)
529                 bus_release_resource(dev, SYS_RES_MEMORY,
530                     rman_get_rid(sc->mem_res), sc->mem_res);
531         sc->mem_res = NULL;
532         if (sc->irq_res)
533                 bus_release_resource(dev, SYS_RES_IRQ,
534                     rman_get_rid(sc->irq_res), sc->irq_res);
535         sc->irq_res = NULL;
536         return;
537 }
538
539 static int
540 at91_mci_is_mci1rev2xx(void)
541 {
542
543         switch (soc_info.type) {
544         case AT91_T_SAM9260:
545         case AT91_T_SAM9263:
546         case AT91_T_CAP9:
547         case AT91_T_SAM9G10:
548         case AT91_T_SAM9G20:
549         case AT91_T_SAM9RL:
550                 return(1);
551         default:
552                 return (0);
553         }
554 }
555
556 static int
557 at91_mci_update_ios(device_t brdev, device_t reqdev)
558 {
559         struct at91_mci_softc *sc;
560         struct mmc_ios *ios;
561         uint32_t clkdiv;
562         uint32_t freq;
563
564         sc = device_get_softc(brdev);
565         ios = &sc->host.ios;
566
567         /*
568          * Calculate our closest available clock speed that doesn't exceed the
569          * requested speed.
570          *
571          * When overclocking is allowed, the requested clock is 25MHz, the
572          * computed frequency is 15MHz or smaller and clockdiv is 1, use
573          * clockdiv of 0 to double that.  If less than 12.5MHz, double
574          * regardless of the overclocking setting.
575          *
576          * Whatever we come up with, store it back into ios->clock so that the
577          * upper layer drivers can report the actual speed of the bus.
578          */
579         if (ios->clock == 0) {
580                 WR4(sc, MCI_CR, MCI_CR_MCIDIS);
581                 clkdiv = 0;
582         } else {
583                 WR4(sc, MCI_CR, MCI_CR_MCIEN|MCI_CR_PWSEN);
584                 if ((at91_master_clock % (ios->clock * 2)) == 0)
585                         clkdiv = ((at91_master_clock / ios->clock) / 2) - 1;
586                 else
587                         clkdiv = (at91_master_clock / ios->clock) / 2;
588                 freq = at91_master_clock / ((clkdiv+1) * 2);
589                 if (clkdiv == 1 && ios->clock == 25000000 && freq <= 15000000) {
590                         if (sc->allow_overclock || freq <= 12500000) {
591                                 clkdiv = 0;
592                                 freq = at91_master_clock / ((clkdiv+1) * 2);
593                         }
594                 }
595                 ios->clock = freq;
596         }
597         if (ios->bus_width == bus_width_4)
598                 WR4(sc, MCI_SDCR, RD4(sc, MCI_SDCR) | MCI_SDCR_SDCBUS);
599         else
600                 WR4(sc, MCI_SDCR, RD4(sc, MCI_SDCR) & ~MCI_SDCR_SDCBUS);
601         WR4(sc, MCI_MR, (RD4(sc, MCI_MR) & ~MCI_MR_CLKDIV) | clkdiv);
602         /* Do we need a settle time here? */
603         /* XXX We need to turn the device on/off here with a GPIO pin */
604         return (0);
605 }
606
607 static void
608 at91_mci_start_cmd(struct at91_mci_softc *sc, struct mmc_command *cmd)
609 {
610         uint32_t cmdr, mr;
611         struct mmc_data *data;
612
613         sc->curcmd = cmd;
614         data = cmd->data;
615
616         /* XXX Upper layers don't always set this */
617         cmd->mrq = sc->req;
618
619         /* Begin setting up command register. */
620
621         cmdr = cmd->opcode;
622
623         if (sc->host.ios.bus_mode == opendrain)
624                 cmdr |= MCI_CMDR_OPDCMD;
625
626         /* Set up response handling.  Allow max timeout for responses. */
627
628         if (MMC_RSP(cmd->flags) == MMC_RSP_NONE)
629                 cmdr |= MCI_CMDR_RSPTYP_NO;
630         else {
631                 cmdr |= MCI_CMDR_MAXLAT;
632                 if (cmd->flags & MMC_RSP_136)
633                         cmdr |= MCI_CMDR_RSPTYP_136;
634                 else
635                         cmdr |= MCI_CMDR_RSPTYP_48;
636         }
637
638         /*
639          * If there is no data transfer, just set up the right interrupt mask
640          * and start the command.
641          *
642          * The interrupt mask needs to be CMDRDY plus all non-data-transfer
643          * errors. It's important to leave the transfer-related errors out, to
644          * avoid spurious timeout or crc errors on a STOP command following a
645          * multiblock read.  When a multiblock read is in progress, sending a
646          * STOP in the middle of a block occasionally triggers such errors, but
647          * we're totally disinterested in them because we've already gotten all
648          * the data we wanted without error before sending the STOP command.
649          */
650
651         if (data == NULL) {
652                 uint32_t ier = MCI_SR_CMDRDY |
653                     MCI_SR_RTOE | MCI_SR_RENDE |
654                     MCI_SR_RCRCE | MCI_SR_RDIRE | MCI_SR_RINDE;
655
656                 at91_mci_pdc_disable(sc);
657
658                 if (cmd->opcode == MMC_STOP_TRANSMISSION)
659                         cmdr |= MCI_CMDR_TRCMD_STOP;
660
661                 /* Ignore response CRC on CMD2 and ACMD41, per standard. */
662
663                 if (cmd->opcode == MMC_SEND_OP_COND ||
664                     cmd->opcode == ACMD_SD_SEND_OP_COND)
665                         ier &= ~MCI_SR_RCRCE;
666
667                 if (mci_debug)
668                         printf("CMDR %x (opcode %d) ARGR %x no data\n",
669                             cmdr, cmd->opcode, cmd->arg);
670
671                 WR4(sc, MCI_ARGR, cmd->arg);
672                 WR4(sc, MCI_CMDR, cmdr);
673                 WR4(sc, MCI_IDR, 0xffffffff);
674                 WR4(sc, MCI_IER, ier);
675                 return;
676         }
677
678         /* There is data, set up the transfer-related parts of the command. */
679
680         if (data->flags & MMC_DATA_READ)
681                 cmdr |= MCI_CMDR_TRDIR;
682
683         if (data->flags & (MMC_DATA_READ | MMC_DATA_WRITE))
684                 cmdr |= MCI_CMDR_TRCMD_START;
685
686         if (data->flags & MMC_DATA_STREAM)
687                 cmdr |= MCI_CMDR_TRTYP_STREAM;
688         else if (data->flags & MMC_DATA_MULTI) {
689                 cmdr |= MCI_CMDR_TRTYP_MULTIPLE;
690                 sc->flags |= (data->flags & MMC_DATA_READ) ?
691                     CMD_MULTIREAD : CMD_MULTIWRITE;
692         }
693
694         /*
695          * Disable PDC until we're ready.
696          *
697          * Set block size and turn on PDC mode for dma xfer.
698          * Note that the block size is the smaller of the amount of data to be
699          * transferred, or 512 bytes.  The 512 size is fixed by the standard;
700          * smaller blocks are possible, but never larger.
701          */
702
703         WR4(sc, PDC_PTCR, PDC_PTCR_RXTDIS | PDC_PTCR_TXTDIS);
704
705         mr = RD4(sc,MCI_MR) & ~MCI_MR_BLKLEN;
706         mr |=  min(data->len, 512) << 16;
707         WR4(sc, MCI_MR, mr | MCI_MR_PDCMODE|MCI_MR_PDCPADV);
708
709         /*
710          * Set up DMA.
711          *
712          * Use bounce buffers even if we don't need to byteswap, because doing
713          * multi-block IO with large DMA buffers is way fast (compared to
714          * single-block IO), even after incurring the overhead of also copying
715          * from/to the caller's buffers (which may be in non-contiguous physical
716          * pages).
717          *
718          * In an ideal non-byteswap world we could create a dma tag that allows
719          * for discontiguous segments and do the IO directly from/to the
720          * caller's buffer(s), using ENDRX/ENDTX interrupts to chain the
721          * discontiguous buffers through the PDC. Someday.
722          *
723          * If a read is bigger than 2k, split it in half so that we can start
724          * byte-swapping the first half while the second half is on the wire.
725          * It would be best if we could split it into 8k chunks, but we can't
726          * always keep up with the byte-swapping due to other system activity,
727          * and if an RXBUFF interrupt happens while we're still handling the
728          * byte-swap from the prior buffer (IE, we haven't returned from
729          * handling the prior interrupt yet), then data will get dropped on the
730          * floor and we can't easily recover from that.  The right fix for that
731          * would be to have the interrupt handling only keep the DMA flowing and
732          * enqueue filled buffers to be byte-swapped in a non-interrupt context.
733          * Even that won't work on the write side of things though; in that
734          * context we have to have all the data ready to go before starting the
735          * dma.
736          *
737          * XXX what about stream transfers?
738          */
739         sc->xfer_offset = 0;
740         sc->bbuf_curidx = 0;
741
742         if (data->flags & (MMC_DATA_READ | MMC_DATA_WRITE)) {
743                 uint32_t len;
744                 uint32_t remaining = data->len;
745                 bus_addr_t paddr;
746                 int err;
747
748                 if (remaining > (BBCOUNT*BBSIZE))
749                         panic("IO read size exceeds MAXDATA\n");
750
751                 if (data->flags & MMC_DATA_READ) {
752                         if (remaining > 2048) // XXX
753                                 len = remaining / 2;
754                         else
755                                 len = remaining;
756                         err = bus_dmamap_load(sc->dmatag, sc->bbuf_map[0],
757                             sc->bbuf_vaddr[0], len, at91_mci_getaddr,
758                             &paddr, BUS_DMA_NOWAIT);
759                         if (err != 0)
760                                 panic("IO read dmamap_load failed\n");
761                         bus_dmamap_sync(sc->dmatag, sc->bbuf_map[0],
762                             BUS_DMASYNC_PREREAD);
763                         WR4(sc, PDC_RPR, paddr);
764                         WR4(sc, PDC_RCR, len / 4);
765                         sc->bbuf_len[0] = len;
766                         remaining -= len;
767                         if (remaining == 0) {
768                                 sc->bbuf_len[1] = 0;
769                         } else {
770                                 len = remaining;
771                                 err = bus_dmamap_load(sc->dmatag, sc->bbuf_map[1],
772                                     sc->bbuf_vaddr[1], len, at91_mci_getaddr,
773                                     &paddr, BUS_DMA_NOWAIT);
774                                 if (err != 0)
775                                         panic("IO read dmamap_load failed\n");
776                                 bus_dmamap_sync(sc->dmatag, sc->bbuf_map[1],
777                                     BUS_DMASYNC_PREREAD);
778                                 WR4(sc, PDC_RNPR, paddr);
779                                 WR4(sc, PDC_RNCR, len / 4);
780                                 sc->bbuf_len[1] = len;
781                                 remaining -= len;
782                         }
783                         WR4(sc, PDC_PTCR, PDC_PTCR_RXTEN);
784                 } else {
785                         len = min(BBSIZE, remaining);
786                         at91_bswap_buf(sc, sc->bbuf_vaddr[0], data->data, len);
787                         err = bus_dmamap_load(sc->dmatag, sc->bbuf_map[0],
788                             sc->bbuf_vaddr[0], len, at91_mci_getaddr,
789                             &paddr, BUS_DMA_NOWAIT);
790                         if (err != 0)
791                                 panic("IO write dmamap_load failed\n");
792                         bus_dmamap_sync(sc->dmatag, sc->bbuf_map[0],
793                             BUS_DMASYNC_PREWRITE);
794                         /*
795                          * Erratum workaround:  PDC transfer length on a write
796                          * must not be smaller than 12 bytes (3 words); only
797                          * blklen bytes (set above) are actually transferred.
798                          */
799                         WR4(sc, PDC_TPR,paddr);
800                         WR4(sc, PDC_TCR, (len < 12) ? 3 : len / 4);
801                         sc->bbuf_len[0] = len;
802                         remaining -= len;
803                         if (remaining == 0) {
804                                 sc->bbuf_len[1] = 0;
805                         } else {
806                                 len = remaining;
807                                 at91_bswap_buf(sc, sc->bbuf_vaddr[1],
808                                     ((char *)data->data)+BBSIZE, len);
809                                 err = bus_dmamap_load(sc->dmatag, sc->bbuf_map[1],
810                                     sc->bbuf_vaddr[1], len, at91_mci_getaddr,
811                                     &paddr, BUS_DMA_NOWAIT);
812                                 if (err != 0)
813                                         panic("IO write dmamap_load failed\n");
814                                 bus_dmamap_sync(sc->dmatag, sc->bbuf_map[1],
815                                     BUS_DMASYNC_PREWRITE);
816                                 WR4(sc, PDC_TNPR, paddr);
817                                 WR4(sc, PDC_TNCR, (len < 12) ? 3 : len / 4);
818                                 sc->bbuf_len[1] = len;
819                                 remaining -= len;
820                         }
821                         /* do not enable PDC xfer until CMDRDY asserted */
822                 }
823                 data->xfer_len = 0; /* XXX what's this? appears to be unused. */
824         }
825
826         if (mci_debug)
827                 printf("CMDR %x (opcode %d) ARGR %x with data len %d\n",
828                        cmdr, cmd->opcode, cmd->arg, cmd->data->len);
829
830         WR4(sc, MCI_ARGR, cmd->arg);
831         WR4(sc, MCI_CMDR, cmdr);
832         WR4(sc, MCI_IER, MCI_SR_ERROR | MCI_SR_CMDRDY);
833 }
834
835 static void
836 at91_mci_next_operation(struct at91_mci_softc *sc)
837 {
838         struct mmc_request *req;
839
840         req = sc->req;
841         if (req == NULL)
842                 return;
843
844         if (sc->flags & PENDING_CMD) {
845                 sc->flags &= ~PENDING_CMD;
846                 at91_mci_start_cmd(sc, req->cmd);
847                 return;
848         } else if (sc->flags & PENDING_STOP) {
849                 sc->flags &= ~PENDING_STOP;
850                 at91_mci_start_cmd(sc, req->stop);
851                 return;
852         }
853
854         WR4(sc, MCI_IDR, 0xffffffff);
855         sc->req = NULL;
856         sc->curcmd = NULL;
857         //printf("req done\n");
858         req->done(req);
859 }
860
861 static int
862 at91_mci_request(device_t brdev, device_t reqdev, struct mmc_request *req)
863 {
864         struct at91_mci_softc *sc = device_get_softc(brdev);
865
866         AT91_MCI_LOCK(sc);
867         if (sc->req != NULL) {
868                 AT91_MCI_UNLOCK(sc);
869                 return (EBUSY);
870         }
871         //printf("new req\n");
872         sc->req = req;
873         sc->flags = PENDING_CMD;
874         if (sc->req->stop)
875                 sc->flags |= PENDING_STOP;
876         at91_mci_next_operation(sc);
877         AT91_MCI_UNLOCK(sc);
878         return (0);
879 }
880
881 static int
882 at91_mci_get_ro(device_t brdev, device_t reqdev)
883 {
884         return (0);
885 }
886
887 static int
888 at91_mci_acquire_host(device_t brdev, device_t reqdev)
889 {
890         struct at91_mci_softc *sc = device_get_softc(brdev);
891         int err = 0;
892
893         AT91_MCI_LOCK(sc);
894         while (sc->bus_busy)
895                 msleep(sc, &sc->sc_mtx, PZERO, "mciah", hz / 5);
896         sc->bus_busy++;
897         AT91_MCI_UNLOCK(sc);
898         return (err);
899 }
900
901 static int
902 at91_mci_release_host(device_t brdev, device_t reqdev)
903 {
904         struct at91_mci_softc *sc = device_get_softc(brdev);
905
906         AT91_MCI_LOCK(sc);
907         sc->bus_busy--;
908         wakeup(sc);
909         AT91_MCI_UNLOCK(sc);
910         return (0);
911 }
912
913 static void
914 at91_mci_read_done(struct at91_mci_softc *sc, uint32_t sr)
915 {
916         struct mmc_command *cmd = sc->curcmd;
917         char * dataptr = (char *)cmd->data->data;
918         uint32_t curidx = sc->bbuf_curidx;
919         uint32_t len = sc->bbuf_len[curidx];
920
921         /*
922          * We arrive here when a DMA transfer for a read is done, whether it's
923          * a single or multi-block read.
924          *
925          * We byte-swap the buffer that just completed, and if that is the
926          * last buffer that's part of this read then we move on to the next
927          * operation, otherwise we wait for another ENDRX for the next bufer.
928          */
929
930         bus_dmamap_sync(sc->dmatag, sc->bbuf_map[curidx], BUS_DMASYNC_POSTREAD);
931         bus_dmamap_unload(sc->dmatag, sc->bbuf_map[curidx]);
932
933         at91_bswap_buf(sc, dataptr + sc->xfer_offset, sc->bbuf_vaddr[curidx], len);
934
935         if (mci_debug) {
936                 printf("read done sr %x curidx %d len %d xfer_offset %d\n",
937                        sr, curidx, len, sc->xfer_offset);
938         }
939
940         sc->xfer_offset += len;
941         sc->bbuf_curidx = !curidx; /* swap buffers */
942
943         /*
944          * If we've transferred all the data, move on to the next operation.
945          *
946          * If we're still transferring the last buffer, RNCR is already zero but
947          * we have to write a zero anyway to clear the ENDRX status so we don't
948          * re-interrupt until the last buffer is done.
949          */
950         if (sc->xfer_offset == cmd->data->len) {
951                 WR4(sc, PDC_PTCR, PDC_PTCR_RXTDIS | PDC_PTCR_TXTDIS);
952                 cmd->error = MMC_ERR_NONE;
953                 at91_mci_next_operation(sc);
954         } else {
955                 WR4(sc, PDC_RNCR, 0);
956                 WR4(sc, MCI_IER, MCI_SR_ERROR | MCI_SR_ENDRX);
957         }
958 }
959
960 static void
961 at91_mci_write_done(struct at91_mci_softc *sc, uint32_t sr)
962 {
963         struct mmc_command *cmd = sc->curcmd;
964
965         /*
966          * We arrive here when the entire DMA transfer for a write is done,
967          * whether it's a single or multi-block write.  If it's multi-block we
968          * have to immediately move on to the next operation which is to send
969          * the stop command.  If it's a single-block transfer we need to wait
970          * for NOTBUSY, but if that's already asserted we can avoid another
971          * interrupt and just move on to completing the request right away.
972          */
973
974         WR4(sc, PDC_PTCR, PDC_PTCR_RXTDIS | PDC_PTCR_TXTDIS);
975
976         bus_dmamap_sync(sc->dmatag, sc->bbuf_map[sc->bbuf_curidx],
977             BUS_DMASYNC_POSTWRITE);
978         bus_dmamap_unload(sc->dmatag, sc->bbuf_map[sc->bbuf_curidx]);
979
980         if ((cmd->data->flags & MMC_DATA_MULTI) || (sr & MCI_SR_NOTBUSY)) {
981                 cmd->error = MMC_ERR_NONE;
982                 at91_mci_next_operation(sc);
983         } else {
984                 WR4(sc, MCI_IER, MCI_SR_ERROR | MCI_SR_NOTBUSY);
985         }
986 }
987
988 static void
989 at91_mci_notbusy(struct at91_mci_softc *sc)
990 {
991         struct mmc_command *cmd = sc->curcmd;
992
993         /*
994          * We arrive here by either completion of a single-block write, or
995          * completion of the stop command that ended a multi-block write (and,
996          * I suppose, after a card-select or erase, but I haven't tested
997          * those).  Anyway, we're done and it's time to move on to the next
998          * command.
999          */
1000
1001         cmd->error = MMC_ERR_NONE;
1002         at91_mci_next_operation(sc);
1003 }
1004
1005 static void
1006 at91_mci_stop_done(struct at91_mci_softc *sc, uint32_t sr)
1007 {
1008         struct mmc_command *cmd = sc->curcmd;
1009
1010         /*
1011          * We arrive here after receiving CMDRDY for a MMC_STOP_TRANSMISSION
1012          * command.  Depending on the operation being stopped, we may have to
1013          * do some unusual things to work around hardware bugs.
1014          */
1015
1016         /*
1017          * This is known to be true of at91rm9200 hardware; it may or may not
1018          * apply to more recent chips:
1019          *
1020          * After stopping a multi-block write, the NOTBUSY bit in MCI_SR does
1021          * not properly reflect the actual busy state of the card as signaled
1022          * on the DAT0 line; it always claims the card is not-busy.  If we
1023          * believe that and let operations continue, following commands will
1024          * fail with response timeouts (except of course MMC_SEND_STATUS -- it
1025          * indicates the card is busy in the PRG state, which was the smoking
1026          * gun that showed MCI_SR NOTBUSY was not tracking DAT0 correctly).
1027          *
1028          * The atmel docs are emphatic: "This flag [NOTBUSY] must be used only
1029          * for Write Operations."  I guess technically since we sent a stop
1030          * it's not a write operation anymore.  But then just what did they
1031          * think it meant for the stop command to have "...an optional busy
1032          * signal transmitted on the data line" according to the SD spec?
1033          *
1034          * I tried a variety of things to un-wedge the MCI and get the status
1035          * register to reflect NOTBUSY correctly again, but the only thing
1036          * that worked was a full device reset.  It feels like an awfully big
1037          * hammer, but doing a full reset after every multiblock write is
1038          * still faster than doing single-block IO (by almost two orders of
1039          * magnitude: 20KB/sec improves to about 1.8MB/sec best case).
1040          *
1041          * After doing the reset, wait for a NOTBUSY interrupt before
1042          * continuing with the next operation.
1043          *
1044          * This workaround breaks multiwrite on the rev2xx parts, but some other
1045          * workaround is needed.
1046          */
1047         if ((sc->flags & CMD_MULTIWRITE) && (sc->sc_cap & CAP_NEEDS_BYTESWAP)) {
1048                 at91_mci_reset(sc);
1049                 WR4(sc, MCI_IER, MCI_SR_ERROR | MCI_SR_NOTBUSY);
1050                 return;
1051         }
1052
1053         /*
1054          * This is known to be true of at91rm9200 hardware; it may or may not
1055          * apply to more recent chips:
1056          *
1057          * After stopping a multi-block read, loop to read and discard any
1058          * data that coasts in after we sent the stop command.  The docs don't
1059          * say anything about it, but empirical testing shows that 1-3
1060          * additional words of data get buffered up in some unmentioned
1061          * internal fifo and if we don't read and discard them here they end
1062          * up on the front of the next read DMA transfer we do.
1063          *
1064          * This appears to be unnecessary for rev2xx parts.
1065          */
1066         if ((sc->flags & CMD_MULTIREAD) && (sc->sc_cap & CAP_NEEDS_BYTESWAP)) {
1067                 uint32_t sr;
1068                 int count = 0;
1069
1070                 do {
1071                         sr = RD4(sc, MCI_SR);
1072                         if (sr & MCI_SR_RXRDY) {
1073                                 RD4(sc,  MCI_RDR);
1074                                 ++count;
1075                         }
1076                 } while (sr & MCI_SR_RXRDY);
1077                 at91_mci_reset(sc);
1078         }
1079
1080         cmd->error = MMC_ERR_NONE;
1081         at91_mci_next_operation(sc);
1082
1083 }
1084
1085 static void
1086 at91_mci_cmdrdy(struct at91_mci_softc *sc, uint32_t sr)
1087 {
1088         struct mmc_command *cmd = sc->curcmd;
1089         int i;
1090
1091         if (cmd == NULL)
1092                 return;
1093
1094         /*
1095          * We get here at the end of EVERY command.  We retrieve the command
1096          * response (if any) then decide what to do next based on the command.
1097          */
1098
1099         if (cmd->flags & MMC_RSP_PRESENT) {
1100                 for (i = 0; i < ((cmd->flags & MMC_RSP_136) ? 4 : 1); i++) {
1101                         cmd->resp[i] = RD4(sc, MCI_RSPR + i * 4);
1102                         if (mci_debug)
1103                                 printf("RSPR[%d] = %x sr=%x\n", i, cmd->resp[i],  sr);
1104                 }
1105         }
1106
1107         /*
1108          * If this was a stop command, go handle the various special
1109          * conditions (read: bugs) that have to be dealt with following a stop.
1110          */
1111         if (cmd->opcode == MMC_STOP_TRANSMISSION) {
1112                 at91_mci_stop_done(sc, sr);
1113                 return;
1114         }
1115
1116         /*
1117          * If this command can continue to assert BUSY beyond the response then
1118          * we need to wait for NOTBUSY before the command is really done.
1119          *
1120          * Note that this may not work properly on the at91rm9200.  It certainly
1121          * doesn't work for the STOP command that follows a multi-block write,
1122          * so post-stop CMDRDY is handled separately; see the special handling
1123          * in at91_mci_stop_done().
1124          *
1125          * Beside STOP, there are other R1B-type commands that use the busy
1126          * signal after CMDRDY: CMD7 (card select), CMD28-29 (write protect),
1127          * CMD38 (erase). I haven't tested any of them, but I rather expect
1128          * them all to have the same sort of problem with MCI_SR not actually
1129          * reflecting the state of the DAT0-line busy indicator.  So this code
1130          * may need to grow some sort of special handling for them too. (This
1131          * just in: CMD7 isn't a problem right now because dev/mmc.c incorrectly
1132          * sets the response flags to R1 rather than R1B.) XXX
1133          */
1134         if ((cmd->flags & MMC_RSP_BUSY)) {
1135                 WR4(sc, MCI_IER, MCI_SR_ERROR | MCI_SR_NOTBUSY);
1136                 return;
1137         }
1138
1139         /*
1140          * If there is a data transfer with this command, then...
1141          * - If it's a read, we need to wait for ENDRX.
1142          * - If it's a write, now is the time to enable the PDC, and we need
1143          *   to wait for a BLKE that follows a TXBUFE, because if we're doing
1144          *   a split transfer we get a BLKE after the first half (when TPR/TCR
1145          *   get loaded from TNPR/TNCR).  So first we wait for the TXBUFE, and
1146          *   the handling for that interrupt will then invoke the wait for the
1147          *   subsequent BLKE which indicates actual completion.
1148          */
1149         if (cmd->data) {
1150                 uint32_t ier;
1151                 if (cmd->data->flags & MMC_DATA_READ) {
1152                         ier = MCI_SR_ENDRX;
1153                 } else {
1154                         ier = MCI_SR_TXBUFE;
1155                         WR4(sc, PDC_PTCR, PDC_PTCR_TXTEN);
1156                 }
1157                 WR4(sc, MCI_IER, MCI_SR_ERROR | ier);
1158                 return;
1159         }
1160
1161         /*
1162          * If we made it to here, we don't need to wait for anything more for
1163          * the current command, move on to the next command (will complete the
1164          * request if there is no next command).
1165          */
1166         cmd->error = MMC_ERR_NONE;
1167         at91_mci_next_operation(sc);
1168 }
1169
1170 static void
1171 at91_mci_intr(void *arg)
1172 {
1173         struct at91_mci_softc *sc = (struct at91_mci_softc*)arg;
1174         struct mmc_command *cmd = sc->curcmd;
1175         uint32_t sr, isr;
1176
1177         AT91_MCI_LOCK(sc);
1178
1179         sr = RD4(sc, MCI_SR);
1180         isr = sr & RD4(sc, MCI_IMR);
1181
1182         if (mci_debug)
1183                 printf("i 0x%x sr 0x%x\n", isr, sr);
1184
1185         /*
1186          * All interrupts are one-shot; disable it now.
1187          * The next operation will re-enable whatever interrupts it wants.
1188          */
1189         WR4(sc, MCI_IDR, isr);
1190         if (isr & MCI_SR_ERROR) {
1191                 if (isr & (MCI_SR_RTOE | MCI_SR_DTOE))
1192                         cmd->error = MMC_ERR_TIMEOUT;
1193                 else if (isr & (MCI_SR_RCRCE | MCI_SR_DCRCE))
1194                         cmd->error = MMC_ERR_BADCRC;
1195                 else if (isr & (MCI_SR_OVRE | MCI_SR_UNRE))
1196                         cmd->error = MMC_ERR_FIFO;
1197                 else
1198                         cmd->error = MMC_ERR_FAILED;
1199                 /*
1200                  * CMD8 is used to probe for SDHC cards, a standard SD card
1201                  * will get a response timeout; don't report it because it's a
1202                  * normal and expected condition.  One might argue that all
1203                  * error reporting should be left to higher levels, but when
1204                  * they report at all it's always EIO, which isn't very
1205                  * helpful. XXX bootverbose?
1206                  */
1207                 if (cmd->opcode != 8) {
1208                         device_printf(sc->dev,
1209                             "IO error; status MCI_SR = 0x%b cmd opcode = %d%s\n",
1210                             sr, MCI_SR_BITSTRING, cmd->opcode,
1211                             (cmd->opcode != 12) ? "" :
1212                             (sc->flags & CMD_MULTIREAD) ? " after read" : " after write");
1213                         /* XXX not sure RTOE needs a full reset, just a retry */
1214                         at91_mci_reset(sc);
1215                 }
1216                 at91_mci_next_operation(sc);
1217         } else {
1218                 if (isr & MCI_SR_TXBUFE) {
1219 //                      printf("TXBUFE\n");
1220                         /*
1221                          * We need to wait for a BLKE that follows TXBUFE
1222                          * (intermediate BLKEs might happen after ENDTXes if
1223                          * we're chaining multiple buffers).  If BLKE is also
1224                          * asserted at the time we get TXBUFE, we can avoid
1225                          * another interrupt and process it right away, below.
1226                          */
1227                         if (sr & MCI_SR_BLKE)
1228                                 isr |= MCI_SR_BLKE;
1229                         else
1230                                 WR4(sc, MCI_IER, MCI_SR_BLKE);
1231                 }
1232                 if (isr & MCI_SR_RXBUFF) {
1233 //                      printf("RXBUFF\n");
1234                 }
1235                 if (isr & MCI_SR_ENDTX) {
1236 //                      printf("ENDTX\n");
1237                 }
1238                 if (isr & MCI_SR_ENDRX) {
1239 //                      printf("ENDRX\n");
1240                         at91_mci_read_done(sc, sr);
1241                 }
1242                 if (isr & MCI_SR_NOTBUSY) {
1243 //                      printf("NOTBUSY\n");
1244                         at91_mci_notbusy(sc);
1245                 }
1246                 if (isr & MCI_SR_DTIP) {
1247 //                      printf("Data transfer in progress\n");
1248                 }
1249                 if (isr & MCI_SR_BLKE) {
1250 //                      printf("Block transfer end\n");
1251                         at91_mci_write_done(sc, sr);
1252                 }
1253                 if (isr & MCI_SR_TXRDY) {
1254 //                      printf("Ready to transmit\n");
1255                 }
1256                 if (isr & MCI_SR_RXRDY) {
1257 //                      printf("Ready to receive\n");
1258                 }
1259                 if (isr & MCI_SR_CMDRDY) {
1260 //                      printf("Command ready\n");
1261                         at91_mci_cmdrdy(sc, sr);
1262                 }
1263         }
1264         AT91_MCI_UNLOCK(sc);
1265 }
1266
1267 static int
1268 at91_mci_read_ivar(device_t bus, device_t child, int which, uintptr_t *result)
1269 {
1270         struct at91_mci_softc *sc = device_get_softc(bus);
1271
1272         switch (which) {
1273         default:
1274                 return (EINVAL);
1275         case MMCBR_IVAR_BUS_MODE:
1276                 *(int *)result = sc->host.ios.bus_mode;
1277                 break;
1278         case MMCBR_IVAR_BUS_WIDTH:
1279                 *(int *)result = sc->host.ios.bus_width;
1280                 break;
1281         case MMCBR_IVAR_CHIP_SELECT:
1282                 *(int *)result = sc->host.ios.chip_select;
1283                 break;
1284         case MMCBR_IVAR_CLOCK:
1285                 *(int *)result = sc->host.ios.clock;
1286                 break;
1287         case MMCBR_IVAR_F_MIN:
1288                 *(int *)result = sc->host.f_min;
1289                 break;
1290         case MMCBR_IVAR_F_MAX:
1291                 *(int *)result = sc->host.f_max;
1292                 break;
1293         case MMCBR_IVAR_HOST_OCR:
1294                 *(int *)result = sc->host.host_ocr;
1295                 break;
1296         case MMCBR_IVAR_MODE:
1297                 *(int *)result = sc->host.mode;
1298                 break;
1299         case MMCBR_IVAR_OCR:
1300                 *(int *)result = sc->host.ocr;
1301                 break;
1302         case MMCBR_IVAR_POWER_MODE:
1303                 *(int *)result = sc->host.ios.power_mode;
1304                 break;
1305         case MMCBR_IVAR_VDD:
1306                 *(int *)result = sc->host.ios.vdd;
1307                 break;
1308         case MMCBR_IVAR_CAPS:
1309                 if (sc->has_4wire) {
1310                         sc->sc_cap |= CAP_HAS_4WIRE;
1311                         sc->host.caps |= MMC_CAP_4_BIT_DATA;
1312                 } else {
1313                         sc->sc_cap &= ~CAP_HAS_4WIRE;
1314                         sc->host.caps &= ~MMC_CAP_4_BIT_DATA;
1315                 }
1316                 *(int *)result = sc->host.caps;
1317                 break;
1318         case MMCBR_IVAR_MAX_DATA:
1319                 /*
1320                  * Something is wrong with the 2x parts and multiblock, so
1321                  * just do 1 block at a time for now, which really kills
1322                  * performance.
1323                  */
1324                 if (sc->sc_cap & CAP_MCI1_REV2XX)
1325                         *(int *)result = 1;
1326                 else
1327                         *(int *)result = MAX_BLOCKS;
1328                 break;
1329         }
1330         return (0);
1331 }
1332
1333 static int
1334 at91_mci_write_ivar(device_t bus, device_t child, int which, uintptr_t value)
1335 {
1336         struct at91_mci_softc *sc = device_get_softc(bus);
1337
1338         switch (which) {
1339         default:
1340                 return (EINVAL);
1341         case MMCBR_IVAR_BUS_MODE:
1342                 sc->host.ios.bus_mode = value;
1343                 break;
1344         case MMCBR_IVAR_BUS_WIDTH:
1345                 sc->host.ios.bus_width = value;
1346                 break;
1347         case MMCBR_IVAR_CHIP_SELECT:
1348                 sc->host.ios.chip_select = value;
1349                 break;
1350         case MMCBR_IVAR_CLOCK:
1351                 sc->host.ios.clock = value;
1352                 break;
1353         case MMCBR_IVAR_MODE:
1354                 sc->host.mode = value;
1355                 break;
1356         case MMCBR_IVAR_OCR:
1357                 sc->host.ocr = value;
1358                 break;
1359         case MMCBR_IVAR_POWER_MODE:
1360                 sc->host.ios.power_mode = value;
1361                 break;
1362         case MMCBR_IVAR_VDD:
1363                 sc->host.ios.vdd = value;
1364                 break;
1365         /* These are read-only */
1366         case MMCBR_IVAR_CAPS:
1367         case MMCBR_IVAR_HOST_OCR:
1368         case MMCBR_IVAR_F_MIN:
1369         case MMCBR_IVAR_F_MAX:
1370         case MMCBR_IVAR_MAX_DATA:
1371                 return (EINVAL);
1372         }
1373         return (0);
1374 }
1375
1376 static device_method_t at91_mci_methods[] = {
1377         /* device_if */
1378         DEVMETHOD(device_probe, at91_mci_probe),
1379         DEVMETHOD(device_attach, at91_mci_attach),
1380         DEVMETHOD(device_detach, at91_mci_detach),
1381
1382         /* Bus interface */
1383         DEVMETHOD(bus_read_ivar,        at91_mci_read_ivar),
1384         DEVMETHOD(bus_write_ivar,       at91_mci_write_ivar),
1385
1386         /* mmcbr_if */
1387         DEVMETHOD(mmcbr_update_ios, at91_mci_update_ios),
1388         DEVMETHOD(mmcbr_request, at91_mci_request),
1389         DEVMETHOD(mmcbr_get_ro, at91_mci_get_ro),
1390         DEVMETHOD(mmcbr_acquire_host, at91_mci_acquire_host),
1391         DEVMETHOD(mmcbr_release_host, at91_mci_release_host),
1392
1393         DEVMETHOD_END
1394 };
1395
1396 static driver_t at91_mci_driver = {
1397         "at91_mci",
1398         at91_mci_methods,
1399         sizeof(struct at91_mci_softc),
1400 };
1401
1402 static devclass_t at91_mci_devclass;
1403
1404 #ifdef FDT
1405 DRIVER_MODULE(at91_mci, simplebus, at91_mci_driver, at91_mci_devclass, NULL,
1406     NULL);
1407 #else
1408 DRIVER_MODULE(at91_mci, atmelarm, at91_mci_driver, at91_mci_devclass, NULL,
1409     NULL);
1410 #endif
1411 DRIVER_MODULE(mmc, at91_mci, mmc_driver, mmc_devclass, NULL, NULL);
1412 MODULE_DEPEND(at91_mci, mmc, 1, 1, 1);