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