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