]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/dev/sdhci/sdhci.c
MFC: r273180, r283754, r297329, r299414, r300707, r310309, r310340 (partial),
[FreeBSD/stable/10.git] / sys / dev / sdhci / sdhci.c
1 /*-
2  * Copyright (c) 2008 Alexander Motin <mav@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include <sys/cdefs.h>
27 __FBSDID("$FreeBSD$");
28
29 #include <sys/param.h>
30 #include <sys/systm.h>
31 #include <sys/bus.h>
32 #include <sys/callout.h>
33 #include <sys/conf.h>
34 #include <sys/kernel.h>
35 #include <sys/lock.h>
36 #include <sys/module.h>
37 #include <sys/mutex.h>
38 #include <sys/resource.h>
39 #include <sys/rman.h>
40 #include <sys/sysctl.h>
41 #include <sys/taskqueue.h>
42
43 #include <machine/bus.h>
44 #include <machine/resource.h>
45 #include <machine/stdarg.h>
46
47 #include <dev/mmc/bridge.h>
48 #include <dev/mmc/mmcreg.h>
49 #include <dev/mmc/mmcbrvar.h>
50
51 #include "mmcbr_if.h"
52 #include "sdhci.h"
53 #include "sdhci_if.h"
54
55 SYSCTL_NODE(_hw, OID_AUTO, sdhci, CTLFLAG_RD, 0, "sdhci driver");
56
57 static int sdhci_debug;
58 TUNABLE_INT("hw.sdhci.debug", &sdhci_debug);
59 SYSCTL_INT(_hw_sdhci, OID_AUTO, debug, CTLFLAG_RWTUN, &sdhci_debug, 0, "Debug level");
60
61 #define RD1(slot, off)  SDHCI_READ_1((slot)->bus, (slot), (off))
62 #define RD2(slot, off)  SDHCI_READ_2((slot)->bus, (slot), (off))
63 #define RD4(slot, off)  SDHCI_READ_4((slot)->bus, (slot), (off))
64 #define RD_MULTI_4(slot, off, ptr, count)       \
65     SDHCI_READ_MULTI_4((slot)->bus, (slot), (off), (ptr), (count))
66
67 #define WR1(slot, off, val)     SDHCI_WRITE_1((slot)->bus, (slot), (off), (val))
68 #define WR2(slot, off, val)     SDHCI_WRITE_2((slot)->bus, (slot), (off), (val))
69 #define WR4(slot, off, val)     SDHCI_WRITE_4((slot)->bus, (slot), (off), (val))
70 #define WR_MULTI_4(slot, off, ptr, count)       \
71     SDHCI_WRITE_MULTI_4((slot)->bus, (slot), (off), (ptr), (count))
72
73 static void sdhci_set_clock(struct sdhci_slot *slot, uint32_t clock);
74 static void sdhci_start(struct sdhci_slot *slot);
75 static void sdhci_start_data(struct sdhci_slot *slot, struct mmc_data *data);
76
77 static void sdhci_card_poll(void *);
78 static void sdhci_card_task(void *, int);
79
80 /* helper routines */
81 #define SDHCI_LOCK(_slot)               mtx_lock(&(_slot)->mtx)
82 #define SDHCI_UNLOCK(_slot)             mtx_unlock(&(_slot)->mtx)
83 #define SDHCI_LOCK_INIT(_slot) \
84         mtx_init(&_slot->mtx, "SD slot mtx", "sdhci", MTX_DEF)
85 #define SDHCI_LOCK_DESTROY(_slot)       mtx_destroy(&_slot->mtx);
86 #define SDHCI_ASSERT_LOCKED(_slot)      mtx_assert(&_slot->mtx, MA_OWNED);
87 #define SDHCI_ASSERT_UNLOCKED(_slot)    mtx_assert(&_slot->mtx, MA_NOTOWNED);
88
89 #define SDHCI_DEFAULT_MAX_FREQ  50
90
91 #define SDHCI_200_MAX_DIVIDER   256
92 #define SDHCI_300_MAX_DIVIDER   2046
93
94 #define SDHCI_CARD_PRESENT_TICKS        (hz / 5)
95 #define SDHCI_INSERT_DELAY_TICKS        (hz / 2)
96
97 /*
98  * Broadcom BCM577xx Controller Constants
99  */
100 #define BCM577XX_DEFAULT_MAX_DIVIDER    256             /* Maximum divider supported by the default clock source. */
101 #define BCM577XX_ALT_CLOCK_BASE         63000000        /* Alternative clock's base frequency. */
102
103 #define BCM577XX_HOST_CONTROL           0x198
104 #define BCM577XX_CTRL_CLKSEL_MASK       0xFFFFCFFF
105 #define BCM577XX_CTRL_CLKSEL_SHIFT      12
106 #define BCM577XX_CTRL_CLKSEL_DEFAULT    0x0
107 #define BCM577XX_CTRL_CLKSEL_64MHZ      0x3
108
109
110 static void
111 sdhci_getaddr(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
112 {
113         if (error != 0) {
114                 printf("getaddr: error %d\n", error);
115                 return;
116         }
117         *(bus_addr_t *)arg = segs[0].ds_addr;
118 }
119
120 static int
121 slot_printf(struct sdhci_slot *slot, const char * fmt, ...)
122 {
123         va_list ap;
124         int retval;
125
126         retval = printf("%s-slot%d: ",
127             device_get_nameunit(slot->bus), slot->num);
128
129         va_start(ap, fmt);
130         retval += vprintf(fmt, ap);
131         va_end(ap);
132         return (retval);
133 }
134
135 static void
136 sdhci_dumpregs(struct sdhci_slot *slot)
137 {
138         slot_printf(slot,
139             "============== REGISTER DUMP ==============\n");
140
141         slot_printf(slot, "Sys addr: 0x%08x | Version:  0x%08x\n",
142             RD4(slot, SDHCI_DMA_ADDRESS), RD2(slot, SDHCI_HOST_VERSION));
143         slot_printf(slot, "Blk size: 0x%08x | Blk cnt:  0x%08x\n",
144             RD2(slot, SDHCI_BLOCK_SIZE), RD2(slot, SDHCI_BLOCK_COUNT));
145         slot_printf(slot, "Argument: 0x%08x | Trn mode: 0x%08x\n",
146             RD4(slot, SDHCI_ARGUMENT), RD2(slot, SDHCI_TRANSFER_MODE));
147         slot_printf(slot, "Present:  0x%08x | Host ctl: 0x%08x\n",
148             RD4(slot, SDHCI_PRESENT_STATE), RD1(slot, SDHCI_HOST_CONTROL));
149         slot_printf(slot, "Power:    0x%08x | Blk gap:  0x%08x\n",
150             RD1(slot, SDHCI_POWER_CONTROL), RD1(slot, SDHCI_BLOCK_GAP_CONTROL));
151         slot_printf(slot, "Wake-up:  0x%08x | Clock:    0x%08x\n",
152             RD1(slot, SDHCI_WAKE_UP_CONTROL), RD2(slot, SDHCI_CLOCK_CONTROL));
153         slot_printf(slot, "Timeout:  0x%08x | Int stat: 0x%08x\n",
154             RD1(slot, SDHCI_TIMEOUT_CONTROL), RD4(slot, SDHCI_INT_STATUS));
155         slot_printf(slot, "Int enab: 0x%08x | Sig enab: 0x%08x\n",
156             RD4(slot, SDHCI_INT_ENABLE), RD4(slot, SDHCI_SIGNAL_ENABLE));
157         slot_printf(slot, "AC12 err: 0x%08x | Slot int: 0x%08x\n",
158             RD2(slot, SDHCI_ACMD12_ERR), RD2(slot, SDHCI_SLOT_INT_STATUS));
159         slot_printf(slot, "Caps:     0x%08x | Max curr: 0x%08x\n",
160             RD4(slot, SDHCI_CAPABILITIES), RD4(slot, SDHCI_MAX_CURRENT));
161
162         slot_printf(slot,
163             "===========================================\n");
164 }
165
166 static void
167 sdhci_reset(struct sdhci_slot *slot, uint8_t mask)
168 {
169         int timeout;
170
171         if (slot->quirks & SDHCI_QUIRK_NO_CARD_NO_RESET) {
172                 if (!SDHCI_GET_CARD_PRESENT(slot->bus, slot))
173                         return;
174         }
175
176         /* Some controllers need this kick or reset won't work. */
177         if ((mask & SDHCI_RESET_ALL) == 0 &&
178             (slot->quirks & SDHCI_QUIRK_CLOCK_BEFORE_RESET)) {
179                 uint32_t clock;
180
181                 /* This is to force an update */
182                 clock = slot->clock;
183                 slot->clock = 0;
184                 sdhci_set_clock(slot, clock);
185         }
186
187         if (mask & SDHCI_RESET_ALL) {
188                 slot->clock = 0;
189                 slot->power = 0;
190         }
191
192         WR1(slot, SDHCI_SOFTWARE_RESET, mask);
193
194         if (slot->quirks & SDHCI_QUIRK_WAITFOR_RESET_ASSERTED) {
195                 /*
196                  * Resets on TI OMAPs and AM335x are incompatible with SDHCI
197                  * specification.  The reset bit has internal propagation delay,
198                  * so a fast read after write returns 0 even if reset process is
199                  * in progress. The workaround is to poll for 1 before polling
200                  * for 0.  In the worst case, if we miss seeing it asserted the
201                  * time we spent waiting is enough to ensure the reset finishes.
202                  */
203                 timeout = 10000;
204                 while ((RD1(slot, SDHCI_SOFTWARE_RESET) & mask) != mask) {
205                         if (timeout <= 0)
206                                 break;
207                         timeout--;
208                         DELAY(1);
209                 }
210         }
211
212         /* Wait max 100 ms */
213         timeout = 10000;
214         /* Controller clears the bits when it's done */
215         while (RD1(slot, SDHCI_SOFTWARE_RESET) & mask) {
216                 if (timeout <= 0) {
217                         slot_printf(slot, "Reset 0x%x never completed.\n",
218                             mask);
219                         sdhci_dumpregs(slot);
220                         return;
221                 }
222                 timeout--;
223                 DELAY(10);
224         }
225 }
226
227 static void
228 sdhci_init(struct sdhci_slot *slot)
229 {
230
231         sdhci_reset(slot, SDHCI_RESET_ALL);
232
233         /* Enable interrupts. */
234         slot->intmask = SDHCI_INT_BUS_POWER | SDHCI_INT_DATA_END_BIT |
235             SDHCI_INT_DATA_CRC | SDHCI_INT_DATA_TIMEOUT | SDHCI_INT_INDEX |
236             SDHCI_INT_END_BIT | SDHCI_INT_CRC | SDHCI_INT_TIMEOUT |
237             SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL |
238             SDHCI_INT_DMA_END | SDHCI_INT_DATA_END | SDHCI_INT_RESPONSE |
239             SDHCI_INT_ACMD12ERR;
240
241         if (!(slot->quirks & SDHCI_QUIRK_POLL_CARD_PRESENT) &&
242             !(slot->opt & SDHCI_NON_REMOVABLE)) {
243                 slot->intmask |= SDHCI_INT_CARD_REMOVE | SDHCI_INT_CARD_INSERT;
244         }
245
246         WR4(slot, SDHCI_INT_ENABLE, slot->intmask);
247         WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask);
248 }
249
250 static void
251 sdhci_set_clock(struct sdhci_slot *slot, uint32_t clock)
252 {
253         uint32_t clk_base;
254         uint32_t clk_sel;
255         uint32_t res;
256         uint16_t clk;
257         uint16_t div;
258         int timeout;
259
260         if (clock == slot->clock)
261                 return;
262         slot->clock = clock;
263
264         /* Turn off the clock. */
265         clk = RD2(slot, SDHCI_CLOCK_CONTROL);
266         WR2(slot, SDHCI_CLOCK_CONTROL, clk & ~SDHCI_CLOCK_CARD_EN);
267         /* If no clock requested - left it so. */
268         if (clock == 0)
269                 return;
270         
271         /* Determine the clock base frequency */
272         clk_base = slot->max_clk;
273         if (slot->quirks & SDHCI_QUIRK_BCM577XX_400KHZ_CLKSRC) {
274                 clk_sel = RD2(slot, BCM577XX_HOST_CONTROL) & BCM577XX_CTRL_CLKSEL_MASK;
275
276                 /* Select clock source appropriate for the requested frequency. */
277                 if ((clk_base / BCM577XX_DEFAULT_MAX_DIVIDER) > clock) {
278                         clk_base = BCM577XX_ALT_CLOCK_BASE;
279                         clk_sel |= (BCM577XX_CTRL_CLKSEL_64MHZ << BCM577XX_CTRL_CLKSEL_SHIFT);
280                 } else {
281                         clk_sel |= (BCM577XX_CTRL_CLKSEL_DEFAULT << BCM577XX_CTRL_CLKSEL_SHIFT);
282                 }
283                 
284                 WR2(slot, BCM577XX_HOST_CONTROL, clk_sel);
285         }
286
287         /* Recalculate timeout clock frequency based on the new sd clock. */
288         if (slot->quirks & SDHCI_QUIRK_DATA_TIMEOUT_USES_SDCLK)
289                 slot->timeout_clk = slot->clock / 1000;
290
291         if (slot->version < SDHCI_SPEC_300) {
292                 /* Looking for highest freq <= clock. */
293                 res = clk_base;
294                 for (div = 1; div < SDHCI_200_MAX_DIVIDER; div <<= 1) {
295                         if (res <= clock)
296                                 break;
297                         res >>= 1;
298                 }
299                 /* Divider 1:1 is 0x00, 2:1 is 0x01, 256:1 is 0x80 ... */
300                 div >>= 1;
301         }
302         else {
303                 /* Version 3.0 divisors are multiples of two up to 1023*2 */
304                 if (clock >= clk_base)
305                         div = 0;
306                 else {
307                         for (div = 2; div < SDHCI_300_MAX_DIVIDER; div += 2) { 
308                                 if ((clk_base / div) <= clock) 
309                                         break;
310                         }
311                 }
312                 div >>= 1;
313         }
314
315         if (bootverbose || sdhci_debug)
316                 slot_printf(slot, "Divider %d for freq %d (base %d)\n", 
317                         div, clock, clk_base);
318
319         /* Now we have got divider, set it. */
320         clk = (div & SDHCI_DIVIDER_MASK) << SDHCI_DIVIDER_SHIFT;
321         clk |= ((div >> SDHCI_DIVIDER_MASK_LEN) & SDHCI_DIVIDER_HI_MASK)
322                 << SDHCI_DIVIDER_HI_SHIFT;
323
324         WR2(slot, SDHCI_CLOCK_CONTROL, clk);
325         /* Enable clock. */
326         clk |= SDHCI_CLOCK_INT_EN;
327         WR2(slot, SDHCI_CLOCK_CONTROL, clk);
328         /* Wait up to 10 ms until it stabilize. */
329         timeout = 10;
330         while (!((clk = RD2(slot, SDHCI_CLOCK_CONTROL))
331                 & SDHCI_CLOCK_INT_STABLE)) {
332                 if (timeout == 0) {
333                         slot_printf(slot, 
334                             "Internal clock never stabilised.\n");
335                         sdhci_dumpregs(slot);
336                         return;
337                 }
338                 timeout--;
339                 DELAY(1000);
340         }
341         /* Pass clock signal to the bus. */
342         clk |= SDHCI_CLOCK_CARD_EN;
343         WR2(slot, SDHCI_CLOCK_CONTROL, clk);
344 }
345
346 static void
347 sdhci_set_power(struct sdhci_slot *slot, u_char power)
348 {
349         uint8_t pwr;
350
351         if (slot->power == power)
352                 return;
353
354         slot->power = power;
355
356         /* Turn off the power. */
357         pwr = 0;
358         WR1(slot, SDHCI_POWER_CONTROL, pwr);
359         /* If power down requested - left it so. */
360         if (power == 0)
361                 return;
362         /* Set voltage. */
363         switch (1 << power) {
364         case MMC_OCR_LOW_VOLTAGE:
365                 pwr |= SDHCI_POWER_180;
366                 break;
367         case MMC_OCR_290_300:
368         case MMC_OCR_300_310:
369                 pwr |= SDHCI_POWER_300;
370                 break;
371         case MMC_OCR_320_330:
372         case MMC_OCR_330_340:
373                 pwr |= SDHCI_POWER_330;
374                 break;
375         }
376         WR1(slot, SDHCI_POWER_CONTROL, pwr);
377         /* Turn on the power. */
378         pwr |= SDHCI_POWER_ON;
379         WR1(slot, SDHCI_POWER_CONTROL, pwr);
380
381         if (slot->quirks & SDHCI_QUIRK_INTEL_POWER_UP_RESET) {
382                 WR1(slot, SDHCI_POWER_CONTROL, pwr | 0x10);
383                 DELAY(10);
384                 WR1(slot, SDHCI_POWER_CONTROL, pwr);
385                 DELAY(300);
386         }
387 }
388
389 static void
390 sdhci_read_block_pio(struct sdhci_slot *slot)
391 {
392         uint32_t data;
393         char *buffer;
394         size_t left;
395
396         buffer = slot->curcmd->data->data;
397         buffer += slot->offset;
398         /* Transfer one block at a time. */
399         left = min(512, slot->curcmd->data->len - slot->offset);
400         slot->offset += left;
401
402         /* If we are too fast, broken controllers return zeroes. */
403         if (slot->quirks & SDHCI_QUIRK_BROKEN_TIMINGS)
404                 DELAY(10);
405         /* Handle unaligned and aligned buffer cases. */
406         if ((intptr_t)buffer & 3) {
407                 while (left > 3) {
408                         data = RD4(slot, SDHCI_BUFFER);
409                         buffer[0] = data;
410                         buffer[1] = (data >> 8);
411                         buffer[2] = (data >> 16);
412                         buffer[3] = (data >> 24);
413                         buffer += 4;
414                         left -= 4;
415                 }
416         } else {
417                 RD_MULTI_4(slot, SDHCI_BUFFER,
418                     (uint32_t *)buffer, left >> 2);
419                 left &= 3;
420         }
421         /* Handle uneven size case. */
422         if (left > 0) {
423                 data = RD4(slot, SDHCI_BUFFER);
424                 while (left > 0) {
425                         *(buffer++) = data;
426                         data >>= 8;
427                         left--;
428                 }
429         }
430 }
431
432 static void
433 sdhci_write_block_pio(struct sdhci_slot *slot)
434 {
435         uint32_t data = 0;
436         char *buffer;
437         size_t left;
438
439         buffer = slot->curcmd->data->data;
440         buffer += slot->offset;
441         /* Transfer one block at a time. */
442         left = min(512, slot->curcmd->data->len - slot->offset);
443         slot->offset += left;
444
445         /* Handle unaligned and aligned buffer cases. */
446         if ((intptr_t)buffer & 3) {
447                 while (left > 3) {
448                         data = buffer[0] +
449                             (buffer[1] << 8) +
450                             (buffer[2] << 16) +
451                             (buffer[3] << 24);
452                         left -= 4;
453                         buffer += 4;
454                         WR4(slot, SDHCI_BUFFER, data);
455                 }
456         } else {
457                 WR_MULTI_4(slot, SDHCI_BUFFER,
458                     (uint32_t *)buffer, left >> 2);
459                 left &= 3;
460         }
461         /* Handle uneven size case. */
462         if (left > 0) {
463                 while (left > 0) {
464                         data <<= 8;
465                         data += *(buffer++);
466                         left--;
467                 }
468                 WR4(slot, SDHCI_BUFFER, data);
469         }
470 }
471
472 static void
473 sdhci_transfer_pio(struct sdhci_slot *slot)
474 {
475
476         /* Read as many blocks as possible. */
477         if (slot->curcmd->data->flags & MMC_DATA_READ) {
478                 while (RD4(slot, SDHCI_PRESENT_STATE) &
479                     SDHCI_DATA_AVAILABLE) {
480                         sdhci_read_block_pio(slot);
481                         if (slot->offset >= slot->curcmd->data->len)
482                                 break;
483                 }
484         } else {
485                 while (RD4(slot, SDHCI_PRESENT_STATE) &
486                     SDHCI_SPACE_AVAILABLE) {
487                         sdhci_write_block_pio(slot);
488                         if (slot->offset >= slot->curcmd->data->len)
489                                 break;
490                 }
491         }
492 }
493
494 static void
495 sdhci_card_task(void *arg, int pending)
496 {
497         struct sdhci_slot *slot = arg;
498
499         SDHCI_LOCK(slot);
500         if (SDHCI_GET_CARD_PRESENT(slot->bus, slot)) {
501                 if (slot->dev == NULL) {
502                         /* If card is present - attach mmc bus. */
503                         if (bootverbose || sdhci_debug)
504                                 slot_printf(slot, "Card inserted\n");
505                         slot->dev = device_add_child(slot->bus, "mmc", -1);
506                         device_set_ivars(slot->dev, slot);
507                         SDHCI_UNLOCK(slot);
508                         device_probe_and_attach(slot->dev);
509                 } else
510                         SDHCI_UNLOCK(slot);
511         } else {
512                 if (slot->dev != NULL) {
513                         /* If no card present - detach mmc bus. */
514                         if (bootverbose || sdhci_debug)
515                                 slot_printf(slot, "Card removed\n");
516                         device_t d = slot->dev;
517                         slot->dev = NULL;
518                         SDHCI_UNLOCK(slot);
519                         device_delete_child(slot->bus, d);
520                 } else
521                         SDHCI_UNLOCK(slot);
522         }
523 }
524
525 static void
526 sdhci_handle_card_present_locked(struct sdhci_slot *slot, bool is_present)
527 {
528         bool was_present;
529
530         /*
531          * If there was no card and now there is one, schedule the task to
532          * create the child device after a short delay.  The delay is to
533          * debounce the card insert (sometimes the card detect pin stabilizes
534          * before the other pins have made good contact).
535          *
536          * If there was a card present and now it's gone, immediately schedule
537          * the task to delete the child device.  No debouncing -- gone is gone,
538          * because once power is removed, a full card re-init is needed, and
539          * that happens by deleting and recreating the child device.
540          */
541         was_present = slot->dev != NULL;
542         if (!was_present && is_present) {
543                 taskqueue_enqueue_timeout(taskqueue_swi_giant,
544                     &slot->card_delayed_task, -SDHCI_INSERT_DELAY_TICKS);
545         } else if (was_present && !is_present) {
546                 taskqueue_enqueue(taskqueue_swi_giant, &slot->card_task);
547         }
548 }
549
550 void
551 sdhci_handle_card_present(struct sdhci_slot *slot, bool is_present)
552 {
553
554         SDHCI_LOCK(slot);
555         sdhci_handle_card_present_locked(slot, is_present);
556         SDHCI_UNLOCK(slot);
557 }
558
559 static void 
560 sdhci_card_poll(void *arg)
561 {
562         struct sdhci_slot *slot = arg;
563
564         sdhci_handle_card_present(slot,
565             SDHCI_GET_CARD_PRESENT(slot->bus, slot));
566         callout_reset(&slot->card_poll_callout, SDHCI_CARD_PRESENT_TICKS,
567             sdhci_card_poll, slot);
568 }
569  
570 int
571 sdhci_init_slot(device_t dev, struct sdhci_slot *slot, int num)
572 {
573         uint32_t caps, freq;
574         int err;
575
576         SDHCI_LOCK_INIT(slot);
577         slot->num = num;
578         slot->bus = dev;
579
580         /* Allocate DMA tag. */
581         err = bus_dma_tag_create(bus_get_dma_tag(dev),
582             DMA_BLOCK_SIZE, 0, BUS_SPACE_MAXADDR_32BIT,
583             BUS_SPACE_MAXADDR, NULL, NULL,
584             DMA_BLOCK_SIZE, 1, DMA_BLOCK_SIZE,
585             BUS_DMA_ALLOCNOW, NULL, NULL,
586             &slot->dmatag);
587         if (err != 0) {
588                 device_printf(dev, "Can't create DMA tag\n");
589                 SDHCI_LOCK_DESTROY(slot);
590                 return (err);
591         }
592         /* Allocate DMA memory. */
593         err = bus_dmamem_alloc(slot->dmatag, (void **)&slot->dmamem,
594             BUS_DMA_NOWAIT, &slot->dmamap);
595         if (err != 0) {
596                 device_printf(dev, "Can't alloc DMA memory\n");
597                 SDHCI_LOCK_DESTROY(slot);
598                 return (err);
599         }
600         /* Map the memory. */
601         err = bus_dmamap_load(slot->dmatag, slot->dmamap,
602             (void *)slot->dmamem, DMA_BLOCK_SIZE,
603             sdhci_getaddr, &slot->paddr, 0);
604         if (err != 0 || slot->paddr == 0) {
605                 device_printf(dev, "Can't load DMA memory\n");
606                 SDHCI_LOCK_DESTROY(slot);
607                 if(err)
608                         return (err);
609                 else
610                         return (EFAULT);
611         }
612
613         /* Initialize slot. */
614         sdhci_init(slot);
615         slot->version = (RD2(slot, SDHCI_HOST_VERSION) 
616                 >> SDHCI_SPEC_VER_SHIFT) & SDHCI_SPEC_VER_MASK;
617         if (slot->quirks & SDHCI_QUIRK_MISSING_CAPS)
618                 caps = slot->caps;
619         else
620                 caps = RD4(slot, SDHCI_CAPABILITIES);
621         /* Calculate base clock frequency. */
622         if (slot->version >= SDHCI_SPEC_300)
623                 freq = (caps & SDHCI_CLOCK_V3_BASE_MASK) >>
624                     SDHCI_CLOCK_BASE_SHIFT;
625         else    
626                 freq = (caps & SDHCI_CLOCK_BASE_MASK) >>
627                     SDHCI_CLOCK_BASE_SHIFT;
628         if (freq != 0)
629                 slot->max_clk = freq * 1000000;
630         /*
631          * If the frequency wasn't in the capabilities and the hardware driver
632          * hasn't already set max_clk we're probably not going to work right
633          * with an assumption, so complain about it.
634          */
635         if (slot->max_clk == 0) {
636                 slot->max_clk = SDHCI_DEFAULT_MAX_FREQ * 1000000;
637                 device_printf(dev, "Hardware doesn't specify base clock "
638                     "frequency, using %dMHz as default.\n", SDHCI_DEFAULT_MAX_FREQ);
639         }
640         /* Calculate/set timeout clock frequency. */
641         if (slot->quirks & SDHCI_QUIRK_DATA_TIMEOUT_USES_SDCLK) {
642                 slot->timeout_clk = slot->max_clk / 1000;
643         } else if (slot->quirks & SDHCI_QUIRK_DATA_TIMEOUT_1MHZ) {
644                 slot->timeout_clk = 1000;
645         } else {
646                 slot->timeout_clk =
647                         (caps & SDHCI_TIMEOUT_CLK_MASK) >> SDHCI_TIMEOUT_CLK_SHIFT;
648                 if (caps & SDHCI_TIMEOUT_CLK_UNIT)
649                         slot->timeout_clk *= 1000;
650         }
651         /*
652          * If the frequency wasn't in the capabilities and the hardware driver
653          * hasn't already set timeout_clk we'll probably work okay using the
654          * max timeout, but still mention it.
655          */
656         if (slot->timeout_clk == 0) {
657                 device_printf(dev, "Hardware doesn't specify timeout clock "
658                     "frequency, setting BROKEN_TIMEOUT quirk.\n");
659                 slot->quirks |= SDHCI_QUIRK_BROKEN_TIMEOUT_VAL;
660         }
661
662         slot->host.f_min = SDHCI_MIN_FREQ(slot->bus, slot);
663         slot->host.f_max = slot->max_clk;
664         slot->host.host_ocr = 0;
665         if (caps & SDHCI_CAN_VDD_330)
666             slot->host.host_ocr |= MMC_OCR_320_330 | MMC_OCR_330_340;
667         if (caps & SDHCI_CAN_VDD_300)
668             slot->host.host_ocr |= MMC_OCR_290_300 | MMC_OCR_300_310;
669         if (caps & SDHCI_CAN_VDD_180)
670             slot->host.host_ocr |= MMC_OCR_LOW_VOLTAGE;
671         if (slot->host.host_ocr == 0) {
672                 device_printf(dev, "Hardware doesn't report any "
673                     "support voltages.\n");
674         }
675         slot->host.caps = MMC_CAP_4_BIT_DATA;
676         if (caps & SDHCI_CAN_DO_8BITBUS)
677                 slot->host.caps |= MMC_CAP_8_BIT_DATA;
678         if (caps & SDHCI_CAN_DO_HISPD)
679                 slot->host.caps |= MMC_CAP_HSPEED;
680         /* Decide if we have usable DMA. */
681         if (caps & SDHCI_CAN_DO_DMA)
682                 slot->opt |= SDHCI_HAVE_DMA;
683
684         if (slot->quirks & SDHCI_QUIRK_BROKEN_DMA)
685                 slot->opt &= ~SDHCI_HAVE_DMA;
686         if (slot->quirks & SDHCI_QUIRK_FORCE_DMA)
687                 slot->opt |= SDHCI_HAVE_DMA;
688         if (slot->quirks & SDHCI_QUIRK_ALL_SLOTS_NON_REMOVABLE)
689                 slot->opt |= SDHCI_NON_REMOVABLE;
690
691         /* 
692          * Use platform-provided transfer backend
693          * with PIO as a fallback mechanism
694          */
695         if (slot->opt & SDHCI_PLATFORM_TRANSFER)
696                 slot->opt &= ~SDHCI_HAVE_DMA;
697
698         if (bootverbose || sdhci_debug) {
699                 slot_printf(slot, "%uMHz%s %s%s%s%s %s\n",
700                     slot->max_clk / 1000000,
701                     (caps & SDHCI_CAN_DO_HISPD) ? " HS" : "",
702                     (slot->host.caps & MMC_CAP_8_BIT_DATA) ? "8bits" :
703                         ((slot->host.caps & MMC_CAP_4_BIT_DATA) ? "4bits" :
704                         "1bit"),
705                     (caps & SDHCI_CAN_VDD_330) ? " 3.3V" : "",
706                     (caps & SDHCI_CAN_VDD_300) ? " 3.0V" : "",
707                     (caps & SDHCI_CAN_VDD_180) ? " 1.8V" : "",
708                     (slot->opt & SDHCI_HAVE_DMA) ? "DMA" : "PIO");
709                 sdhci_dumpregs(slot);
710         }
711
712         slot->timeout = 10;
713         SYSCTL_ADD_INT(device_get_sysctl_ctx(slot->bus),
714             SYSCTL_CHILDREN(device_get_sysctl_tree(slot->bus)), OID_AUTO,
715             "timeout", CTLFLAG_RW, &slot->timeout, 0,
716             "Maximum timeout for SDHCI transfers (in secs)");
717         TASK_INIT(&slot->card_task, 0, sdhci_card_task, slot);
718         TIMEOUT_TASK_INIT(taskqueue_swi_giant, &slot->card_delayed_task, 0,
719                 sdhci_card_task, slot);
720         callout_init(&slot->card_poll_callout, 1);
721         callout_init_mtx(&slot->timeout_callout, &slot->mtx, 0);
722
723         if ((slot->quirks & SDHCI_QUIRK_POLL_CARD_PRESENT) &&
724             !(slot->opt & SDHCI_NON_REMOVABLE)) {
725                 callout_reset(&slot->card_poll_callout,
726                     SDHCI_CARD_PRESENT_TICKS, sdhci_card_poll, slot);
727         }
728
729         return (0);
730 }
731
732 void
733 sdhci_start_slot(struct sdhci_slot *slot)
734 {
735         sdhci_card_task(slot, 0);
736 }
737
738 int
739 sdhci_cleanup_slot(struct sdhci_slot *slot)
740 {
741         device_t d;
742
743         callout_drain(&slot->timeout_callout);
744         callout_drain(&slot->card_poll_callout);
745         taskqueue_drain(taskqueue_swi_giant, &slot->card_task);
746         taskqueue_drain_timeout(taskqueue_swi_giant, &slot->card_delayed_task);
747
748         SDHCI_LOCK(slot);
749         d = slot->dev;
750         slot->dev = NULL;
751         SDHCI_UNLOCK(slot);
752         if (d != NULL)
753                 device_delete_child(slot->bus, d);
754
755         SDHCI_LOCK(slot);
756         sdhci_reset(slot, SDHCI_RESET_ALL);
757         SDHCI_UNLOCK(slot);
758         bus_dmamap_unload(slot->dmatag, slot->dmamap);
759         bus_dmamem_free(slot->dmatag, slot->dmamem, slot->dmamap);
760         bus_dma_tag_destroy(slot->dmatag);
761
762         SDHCI_LOCK_DESTROY(slot);
763
764         return (0);
765 }
766
767 int
768 sdhci_generic_suspend(struct sdhci_slot *slot)
769 {
770         sdhci_reset(slot, SDHCI_RESET_ALL);
771
772         return (0);
773 }
774
775 int
776 sdhci_generic_resume(struct sdhci_slot *slot)
777 {
778         sdhci_init(slot);
779
780         return (0);
781 }
782
783 uint32_t
784 sdhci_generic_min_freq(device_t brdev, struct sdhci_slot *slot)
785 {
786         if (slot->version >= SDHCI_SPEC_300)
787                 return (slot->max_clk / SDHCI_300_MAX_DIVIDER);
788         else
789                 return (slot->max_clk / SDHCI_200_MAX_DIVIDER);
790 }
791
792 bool
793 sdhci_generic_get_card_present(device_t brdev, struct sdhci_slot *slot)
794 {
795
796         if (slot->opt & SDHCI_NON_REMOVABLE)
797                 return true;
798
799         return (RD4(slot, SDHCI_PRESENT_STATE) & SDHCI_CARD_PRESENT);
800 }
801
802 int
803 sdhci_generic_update_ios(device_t brdev, device_t reqdev)
804 {
805         struct sdhci_slot *slot = device_get_ivars(reqdev);
806         struct mmc_ios *ios = &slot->host.ios;
807
808         SDHCI_LOCK(slot);
809         /* Do full reset on bus power down to clear from any state. */
810         if (ios->power_mode == power_off) {
811                 WR4(slot, SDHCI_SIGNAL_ENABLE, 0);
812                 sdhci_init(slot);
813         }
814         /* Configure the bus. */
815         sdhci_set_clock(slot, ios->clock);
816         sdhci_set_power(slot, (ios->power_mode == power_off) ? 0 : ios->vdd);
817         if (ios->bus_width == bus_width_8) {
818                 slot->hostctrl |= SDHCI_CTRL_8BITBUS;
819                 slot->hostctrl &= ~SDHCI_CTRL_4BITBUS;
820         } else if (ios->bus_width == bus_width_4) {
821                 slot->hostctrl &= ~SDHCI_CTRL_8BITBUS;
822                 slot->hostctrl |= SDHCI_CTRL_4BITBUS;
823         } else if (ios->bus_width == bus_width_1) {
824                 slot->hostctrl &= ~SDHCI_CTRL_8BITBUS;
825                 slot->hostctrl &= ~SDHCI_CTRL_4BITBUS;
826         } else {
827                 panic("Invalid bus width: %d", ios->bus_width);
828         }
829         if (ios->timing == bus_timing_hs && 
830             !(slot->quirks & SDHCI_QUIRK_DONT_SET_HISPD_BIT))
831                 slot->hostctrl |= SDHCI_CTRL_HISPD;
832         else
833                 slot->hostctrl &= ~SDHCI_CTRL_HISPD;
834         WR1(slot, SDHCI_HOST_CONTROL, slot->hostctrl);
835         /* Some controllers like reset after bus changes. */
836         if(slot->quirks & SDHCI_QUIRK_RESET_ON_IOS)
837                 sdhci_reset(slot, SDHCI_RESET_CMD | SDHCI_RESET_DATA);
838
839         SDHCI_UNLOCK(slot);
840         return (0);
841 }
842
843 static void 
844 sdhci_req_done(struct sdhci_slot *slot)
845 {
846         struct mmc_request *req;
847
848         if (slot->req != NULL && slot->curcmd != NULL) {
849                 callout_stop(&slot->timeout_callout);
850                 req = slot->req;
851                 slot->req = NULL;
852                 slot->curcmd = NULL;
853                 req->done(req);
854         }
855 }
856  
857 static void 
858 sdhci_timeout(void *arg)
859 {
860         struct sdhci_slot *slot = arg;
861
862         if (slot->curcmd != NULL) {
863                 slot_printf(slot, " Controller timeout\n");
864                 sdhci_dumpregs(slot);
865                 sdhci_reset(slot, SDHCI_RESET_CMD|SDHCI_RESET_DATA);
866                 slot->curcmd->error = MMC_ERR_TIMEOUT;
867                 sdhci_req_done(slot);
868         } else {
869                 slot_printf(slot, " Spurious timeout - no active command\n");
870         }
871 }
872  
873 static void
874 sdhci_set_transfer_mode(struct sdhci_slot *slot,
875         struct mmc_data *data)
876 {
877         uint16_t mode;
878
879         if (data == NULL)
880                 return;
881
882         mode = SDHCI_TRNS_BLK_CNT_EN;
883         if (data->len > 512)
884                 mode |= SDHCI_TRNS_MULTI;
885         if (data->flags & MMC_DATA_READ)
886                 mode |= SDHCI_TRNS_READ;
887         if (slot->req->stop)
888                 mode |= SDHCI_TRNS_ACMD12;
889         if (slot->flags & SDHCI_USE_DMA)
890                 mode |= SDHCI_TRNS_DMA;
891
892         WR2(slot, SDHCI_TRANSFER_MODE, mode);
893 }
894
895 static void
896 sdhci_start_command(struct sdhci_slot *slot, struct mmc_command *cmd)
897 {
898         int flags, timeout;
899         uint32_t mask;
900
901         slot->curcmd = cmd;
902         slot->cmd_done = 0;
903
904         cmd->error = MMC_ERR_NONE;
905
906         /* This flags combination is not supported by controller. */
907         if ((cmd->flags & MMC_RSP_136) && (cmd->flags & MMC_RSP_BUSY)) {
908                 slot_printf(slot, "Unsupported response type!\n");
909                 cmd->error = MMC_ERR_FAILED;
910                 sdhci_req_done(slot);
911                 return;
912         }
913
914         /* Do not issue command if there is no card, clock or power.
915          * Controller will not detect timeout without clock active. */
916         if (!SDHCI_GET_CARD_PRESENT(slot->bus, slot) ||
917             slot->power == 0 ||
918             slot->clock == 0) {
919                 cmd->error = MMC_ERR_FAILED;
920                 sdhci_req_done(slot);
921                 return;
922         }
923         /* Always wait for free CMD bus. */
924         mask = SDHCI_CMD_INHIBIT;
925         /* Wait for free DAT if we have data or busy signal. */
926         if (cmd->data || (cmd->flags & MMC_RSP_BUSY))
927                 mask |= SDHCI_DAT_INHIBIT;
928         /* We shouldn't wait for DAT for stop commands. */
929         if (cmd == slot->req->stop)
930                 mask &= ~SDHCI_DAT_INHIBIT;
931         /*
932          *  Wait for bus no more then 250 ms.  Typically there will be no wait
933          *  here at all, but when writing a crash dump we may be bypassing the
934          *  host platform's interrupt handler, and in some cases that handler
935          *  may be working around hardware quirks such as not respecting r1b
936          *  busy indications.  In those cases, this wait-loop serves the purpose
937          *  of waiting for the prior command and data transfers to be done, and
938          *  SD cards are allowed to take up to 250ms for write and erase ops.
939          *  (It's usually more like 20-30ms in the real world.)
940          */
941         timeout = 250;
942         while (mask & RD4(slot, SDHCI_PRESENT_STATE)) {
943                 if (timeout == 0) {
944                         slot_printf(slot, "Controller never released "
945                             "inhibit bit(s).\n");
946                         sdhci_dumpregs(slot);
947                         cmd->error = MMC_ERR_FAILED;
948                         sdhci_req_done(slot);
949                         return;
950                 }
951                 timeout--;
952                 DELAY(1000);
953         }
954
955         /* Prepare command flags. */
956         if (!(cmd->flags & MMC_RSP_PRESENT))
957                 flags = SDHCI_CMD_RESP_NONE;
958         else if (cmd->flags & MMC_RSP_136)
959                 flags = SDHCI_CMD_RESP_LONG;
960         else if (cmd->flags & MMC_RSP_BUSY)
961                 flags = SDHCI_CMD_RESP_SHORT_BUSY;
962         else
963                 flags = SDHCI_CMD_RESP_SHORT;
964         if (cmd->flags & MMC_RSP_CRC)
965                 flags |= SDHCI_CMD_CRC;
966         if (cmd->flags & MMC_RSP_OPCODE)
967                 flags |= SDHCI_CMD_INDEX;
968         if (cmd->data)
969                 flags |= SDHCI_CMD_DATA;
970         if (cmd->opcode == MMC_STOP_TRANSMISSION)
971                 flags |= SDHCI_CMD_TYPE_ABORT;
972         /* Prepare data. */
973         sdhci_start_data(slot, cmd->data);
974         /* 
975          * Interrupt aggregation: To reduce total number of interrupts
976          * group response interrupt with data interrupt when possible.
977          * If there going to be data interrupt, mask response one.
978          */
979         if (slot->data_done == 0) {
980                 WR4(slot, SDHCI_SIGNAL_ENABLE,
981                     slot->intmask &= ~SDHCI_INT_RESPONSE);
982         }
983         /* Set command argument. */
984         WR4(slot, SDHCI_ARGUMENT, cmd->arg);
985         /* Set data transfer mode. */
986         sdhci_set_transfer_mode(slot, cmd->data);
987         /* Start command. */
988         WR2(slot, SDHCI_COMMAND_FLAGS, (cmd->opcode << 8) | (flags & 0xff));
989         /* Start timeout callout. */
990         callout_reset(&slot->timeout_callout, slot->timeout * hz,
991             sdhci_timeout, slot);
992 }
993
994 static void
995 sdhci_finish_command(struct sdhci_slot *slot)
996 {
997         int i;
998
999         slot->cmd_done = 1;
1000         /* Interrupt aggregation: Restore command interrupt.
1001          * Main restore point for the case when command interrupt
1002          * happened first. */
1003         WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask |= SDHCI_INT_RESPONSE);
1004         /* In case of error - reset host and return. */
1005         if (slot->curcmd->error) {
1006                 sdhci_reset(slot, SDHCI_RESET_CMD);
1007                 sdhci_reset(slot, SDHCI_RESET_DATA);
1008                 sdhci_start(slot);
1009                 return;
1010         }
1011         /* If command has response - fetch it. */
1012         if (slot->curcmd->flags & MMC_RSP_PRESENT) {
1013                 if (slot->curcmd->flags & MMC_RSP_136) {
1014                         /* CRC is stripped so we need one byte shift. */
1015                         uint8_t extra = 0;
1016                         for (i = 0; i < 4; i++) {
1017                                 uint32_t val = RD4(slot, SDHCI_RESPONSE + i * 4);
1018                                 if (slot->quirks & SDHCI_QUIRK_DONT_SHIFT_RESPONSE)
1019                                         slot->curcmd->resp[3 - i] = val;
1020                                 else {
1021                                         slot->curcmd->resp[3 - i] = 
1022                                             (val << 8) | extra;
1023                                         extra = val >> 24;
1024                                 }
1025                         }
1026                 } else
1027                         slot->curcmd->resp[0] = RD4(slot, SDHCI_RESPONSE);
1028         }
1029         /* If data ready - finish. */
1030         if (slot->data_done)
1031                 sdhci_start(slot);
1032 }
1033
1034 static void
1035 sdhci_start_data(struct sdhci_slot *slot, struct mmc_data *data)
1036 {
1037         uint32_t target_timeout, current_timeout;
1038         uint8_t div;
1039
1040         if (data == NULL && (slot->curcmd->flags & MMC_RSP_BUSY) == 0) {
1041                 slot->data_done = 1;
1042                 return;
1043         }
1044
1045         slot->data_done = 0;
1046
1047         /* Calculate and set data timeout.*/
1048         /* XXX: We should have this from mmc layer, now assume 1 sec. */
1049         if (slot->quirks & SDHCI_QUIRK_BROKEN_TIMEOUT_VAL) {
1050                 div = 0xE;
1051         } else {
1052                 target_timeout = 1000000;
1053                 div = 0;
1054                 current_timeout = (1 << 13) * 1000 / slot->timeout_clk;
1055                 while (current_timeout < target_timeout && div < 0xE) {
1056                         ++div;
1057                         current_timeout <<= 1;
1058                 }
1059                 /* Compensate for an off-by-one error in the CaFe chip.*/
1060                 if (div < 0xE && 
1061                     (slot->quirks & SDHCI_QUIRK_INCR_TIMEOUT_CONTROL)) {
1062                         ++div;
1063                 }
1064         }
1065         WR1(slot, SDHCI_TIMEOUT_CONTROL, div);
1066
1067         if (data == NULL)
1068                 return;
1069
1070         /* Use DMA if possible. */
1071         if ((slot->opt & SDHCI_HAVE_DMA))
1072                 slot->flags |= SDHCI_USE_DMA;
1073         /* If data is small, broken DMA may return zeroes instead of data, */
1074         if ((slot->quirks & SDHCI_QUIRK_BROKEN_TIMINGS) &&
1075             (data->len <= 512))
1076                 slot->flags &= ~SDHCI_USE_DMA;
1077         /* Some controllers require even block sizes. */
1078         if ((slot->quirks & SDHCI_QUIRK_32BIT_DMA_SIZE) &&
1079             ((data->len) & 0x3))
1080                 slot->flags &= ~SDHCI_USE_DMA;
1081         /* Load DMA buffer. */
1082         if (slot->flags & SDHCI_USE_DMA) {
1083                 if (data->flags & MMC_DATA_READ)
1084                         bus_dmamap_sync(slot->dmatag, slot->dmamap, 
1085                             BUS_DMASYNC_PREREAD);
1086                 else {
1087                         memcpy(slot->dmamem, data->data,
1088                             (data->len < DMA_BLOCK_SIZE) ? 
1089                             data->len : DMA_BLOCK_SIZE);
1090                         bus_dmamap_sync(slot->dmatag, slot->dmamap, 
1091                             BUS_DMASYNC_PREWRITE);
1092                 }
1093                 WR4(slot, SDHCI_DMA_ADDRESS, slot->paddr);
1094                 /* Interrupt aggregation: Mask border interrupt
1095                  * for the last page and unmask else. */
1096                 if (data->len == DMA_BLOCK_SIZE)
1097                         slot->intmask &= ~SDHCI_INT_DMA_END;
1098                 else
1099                         slot->intmask |= SDHCI_INT_DMA_END;
1100                 WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask);
1101         }
1102         /* Current data offset for both PIO and DMA. */
1103         slot->offset = 0;
1104         /* Set block size and request IRQ on 4K border. */
1105         WR2(slot, SDHCI_BLOCK_SIZE,
1106             SDHCI_MAKE_BLKSZ(DMA_BOUNDARY, (data->len < 512)?data->len:512));
1107         /* Set block count. */
1108         WR2(slot, SDHCI_BLOCK_COUNT, (data->len + 511) / 512);
1109 }
1110
1111 void
1112 sdhci_finish_data(struct sdhci_slot *slot)
1113 {
1114         struct mmc_data *data = slot->curcmd->data;
1115
1116         /* Interrupt aggregation: Restore command interrupt.
1117          * Auxiliary restore point for the case when data interrupt
1118          * happened first. */
1119         if (!slot->cmd_done) {
1120                 WR4(slot, SDHCI_SIGNAL_ENABLE,
1121                     slot->intmask |= SDHCI_INT_RESPONSE);
1122         }
1123         /* Unload rest of data from DMA buffer. */
1124         if (!slot->data_done && (slot->flags & SDHCI_USE_DMA)) {
1125                 if (data->flags & MMC_DATA_READ) {
1126                         size_t left = data->len - slot->offset;
1127                         bus_dmamap_sync(slot->dmatag, slot->dmamap, 
1128                             BUS_DMASYNC_POSTREAD);
1129                         memcpy((u_char*)data->data + slot->offset, slot->dmamem,
1130                             (left < DMA_BLOCK_SIZE)?left:DMA_BLOCK_SIZE);
1131                 } else
1132                         bus_dmamap_sync(slot->dmatag, slot->dmamap, 
1133                             BUS_DMASYNC_POSTWRITE);
1134         }
1135         slot->data_done = 1;
1136         /* If there was error - reset the host. */
1137         if (slot->curcmd->error) {
1138                 sdhci_reset(slot, SDHCI_RESET_CMD);
1139                 sdhci_reset(slot, SDHCI_RESET_DATA);
1140                 sdhci_start(slot);
1141                 return;
1142         }
1143         /* If we already have command response - finish. */
1144         if (slot->cmd_done)
1145                 sdhci_start(slot);
1146 }
1147
1148 static void
1149 sdhci_start(struct sdhci_slot *slot)
1150 {
1151         struct mmc_request *req;
1152
1153         req = slot->req;
1154         if (req == NULL)
1155                 return;
1156
1157         if (!(slot->flags & CMD_STARTED)) {
1158                 slot->flags |= CMD_STARTED;
1159                 sdhci_start_command(slot, req->cmd);
1160                 return;
1161         }
1162 /*      We don't need this until using Auto-CMD12 feature
1163         if (!(slot->flags & STOP_STARTED) && req->stop) {
1164                 slot->flags |= STOP_STARTED;
1165                 sdhci_start_command(slot, req->stop);
1166                 return;
1167         }
1168 */
1169         if (sdhci_debug > 1)
1170                 slot_printf(slot, "result: %d\n", req->cmd->error);
1171         if (!req->cmd->error &&
1172             (slot->quirks & SDHCI_QUIRK_RESET_AFTER_REQUEST)) {
1173                 sdhci_reset(slot, SDHCI_RESET_CMD);
1174                 sdhci_reset(slot, SDHCI_RESET_DATA);
1175         }
1176
1177         sdhci_req_done(slot);
1178 }
1179
1180 int
1181 sdhci_generic_request(device_t brdev, device_t reqdev, struct mmc_request *req)
1182 {
1183         struct sdhci_slot *slot = device_get_ivars(reqdev);
1184
1185         SDHCI_LOCK(slot);
1186         if (slot->req != NULL) {
1187                 SDHCI_UNLOCK(slot);
1188                 return (EBUSY);
1189         }
1190         if (sdhci_debug > 1) {
1191                 slot_printf(slot, "CMD%u arg %#x flags %#x dlen %u dflags %#x\n",
1192                     req->cmd->opcode, req->cmd->arg, req->cmd->flags,
1193                     (req->cmd->data)?(u_int)req->cmd->data->len:0,
1194                     (req->cmd->data)?req->cmd->data->flags:0);
1195         }
1196         slot->req = req;
1197         slot->flags = 0;
1198         sdhci_start(slot);
1199         SDHCI_UNLOCK(slot);
1200         if (dumping) {
1201                 while (slot->req != NULL) {
1202                         sdhci_generic_intr(slot);
1203                         DELAY(10);
1204                 }
1205         }
1206         return (0);
1207 }
1208
1209 int
1210 sdhci_generic_get_ro(device_t brdev, device_t reqdev)
1211 {
1212         struct sdhci_slot *slot = device_get_ivars(reqdev);
1213         uint32_t val;
1214
1215         SDHCI_LOCK(slot);
1216         val = RD4(slot, SDHCI_PRESENT_STATE);
1217         SDHCI_UNLOCK(slot);
1218         return (!(val & SDHCI_WRITE_PROTECT));
1219 }
1220
1221 int
1222 sdhci_generic_acquire_host(device_t brdev, device_t reqdev)
1223 {
1224         struct sdhci_slot *slot = device_get_ivars(reqdev);
1225         int err = 0;
1226
1227         SDHCI_LOCK(slot);
1228         while (slot->bus_busy)
1229                 msleep(slot, &slot->mtx, 0, "sdhciah", 0);
1230         slot->bus_busy++;
1231         /* Activate led. */
1232         WR1(slot, SDHCI_HOST_CONTROL, slot->hostctrl |= SDHCI_CTRL_LED);
1233         SDHCI_UNLOCK(slot);
1234         return (err);
1235 }
1236
1237 int
1238 sdhci_generic_release_host(device_t brdev, device_t reqdev)
1239 {
1240         struct sdhci_slot *slot = device_get_ivars(reqdev);
1241
1242         SDHCI_LOCK(slot);
1243         /* Deactivate led. */
1244         WR1(slot, SDHCI_HOST_CONTROL, slot->hostctrl &= ~SDHCI_CTRL_LED);
1245         slot->bus_busy--;
1246         SDHCI_UNLOCK(slot);
1247         wakeup(slot);
1248         return (0);
1249 }
1250
1251 static void
1252 sdhci_cmd_irq(struct sdhci_slot *slot, uint32_t intmask)
1253 {
1254
1255         if (!slot->curcmd) {
1256                 slot_printf(slot, "Got command interrupt 0x%08x, but "
1257                     "there is no active command.\n", intmask);
1258                 sdhci_dumpregs(slot);
1259                 return;
1260         }
1261         if (intmask & SDHCI_INT_TIMEOUT)
1262                 slot->curcmd->error = MMC_ERR_TIMEOUT;
1263         else if (intmask & SDHCI_INT_CRC)
1264                 slot->curcmd->error = MMC_ERR_BADCRC;
1265         else if (intmask & (SDHCI_INT_END_BIT | SDHCI_INT_INDEX))
1266                 slot->curcmd->error = MMC_ERR_FIFO;
1267
1268         sdhci_finish_command(slot);
1269 }
1270
1271 static void
1272 sdhci_data_irq(struct sdhci_slot *slot, uint32_t intmask)
1273 {
1274
1275         if (!slot->curcmd) {
1276                 slot_printf(slot, "Got data interrupt 0x%08x, but "
1277                     "there is no active command.\n", intmask);
1278                 sdhci_dumpregs(slot);
1279                 return;
1280         }
1281         if (slot->curcmd->data == NULL &&
1282             (slot->curcmd->flags & MMC_RSP_BUSY) == 0) {
1283                 slot_printf(slot, "Got data interrupt 0x%08x, but "
1284                     "there is no active data operation.\n",
1285                     intmask);
1286                 sdhci_dumpregs(slot);
1287                 return;
1288         }
1289         if (intmask & SDHCI_INT_DATA_TIMEOUT)
1290                 slot->curcmd->error = MMC_ERR_TIMEOUT;
1291         else if (intmask & (SDHCI_INT_DATA_CRC | SDHCI_INT_DATA_END_BIT))
1292                 slot->curcmd->error = MMC_ERR_BADCRC;
1293         if (slot->curcmd->data == NULL &&
1294             (intmask & (SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL |
1295             SDHCI_INT_DMA_END))) {
1296                 slot_printf(slot, "Got data interrupt 0x%08x, but "
1297                     "there is busy-only command.\n", intmask);
1298                 sdhci_dumpregs(slot);
1299                 slot->curcmd->error = MMC_ERR_INVALID;
1300         }
1301         if (slot->curcmd->error) {
1302                 /* No need to continue after any error. */
1303                 goto done;
1304         }
1305
1306         /* Handle PIO interrupt. */
1307         if (intmask & (SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL)) {
1308                 if ((slot->opt & SDHCI_PLATFORM_TRANSFER) && 
1309                     SDHCI_PLATFORM_WILL_HANDLE(slot->bus, slot)) {
1310                         SDHCI_PLATFORM_START_TRANSFER(slot->bus, slot, &intmask);
1311                         slot->flags |= PLATFORM_DATA_STARTED;
1312                 } else
1313                         sdhci_transfer_pio(slot);
1314         }
1315         /* Handle DMA border. */
1316         if (intmask & SDHCI_INT_DMA_END) {
1317                 struct mmc_data *data = slot->curcmd->data;
1318                 size_t left;
1319
1320                 /* Unload DMA buffer... */
1321                 left = data->len - slot->offset;
1322                 if (data->flags & MMC_DATA_READ) {
1323                         bus_dmamap_sync(slot->dmatag, slot->dmamap,
1324                             BUS_DMASYNC_POSTREAD);
1325                         memcpy((u_char*)data->data + slot->offset, slot->dmamem,
1326                             (left < DMA_BLOCK_SIZE)?left:DMA_BLOCK_SIZE);
1327                 } else {
1328                         bus_dmamap_sync(slot->dmatag, slot->dmamap,
1329                             BUS_DMASYNC_POSTWRITE);
1330                 }
1331                 /* ... and reload it again. */
1332                 slot->offset += DMA_BLOCK_SIZE;
1333                 left = data->len - slot->offset;
1334                 if (data->flags & MMC_DATA_READ) {
1335                         bus_dmamap_sync(slot->dmatag, slot->dmamap,
1336                             BUS_DMASYNC_PREREAD);
1337                 } else {
1338                         memcpy(slot->dmamem, (u_char*)data->data + slot->offset,
1339                             (left < DMA_BLOCK_SIZE)?left:DMA_BLOCK_SIZE);
1340                         bus_dmamap_sync(slot->dmatag, slot->dmamap,
1341                             BUS_DMASYNC_PREWRITE);
1342                 }
1343                 /* Interrupt aggregation: Mask border interrupt
1344                  * for the last page. */
1345                 if (left == DMA_BLOCK_SIZE) {
1346                         slot->intmask &= ~SDHCI_INT_DMA_END;
1347                         WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask);
1348                 }
1349                 /* Restart DMA. */
1350                 WR4(slot, SDHCI_DMA_ADDRESS, slot->paddr);
1351         }
1352         /* We have got all data. */
1353         if (intmask & SDHCI_INT_DATA_END) {
1354                 if (slot->flags & PLATFORM_DATA_STARTED) {
1355                         slot->flags &= ~PLATFORM_DATA_STARTED;
1356                         SDHCI_PLATFORM_FINISH_TRANSFER(slot->bus, slot);
1357                 } else
1358                         sdhci_finish_data(slot);
1359         }
1360 done:
1361         if (slot->curcmd != NULL && slot->curcmd->error != 0) {
1362                 if (slot->flags & PLATFORM_DATA_STARTED) {
1363                         slot->flags &= ~PLATFORM_DATA_STARTED;
1364                         SDHCI_PLATFORM_FINISH_TRANSFER(slot->bus, slot);
1365                 } else
1366                         sdhci_finish_data(slot);
1367                 return;
1368         }
1369 }
1370
1371 static void
1372 sdhci_acmd_irq(struct sdhci_slot *slot)
1373 {
1374         uint16_t err;
1375         
1376         err = RD4(slot, SDHCI_ACMD12_ERR);
1377         if (!slot->curcmd) {
1378                 slot_printf(slot, "Got AutoCMD12 error 0x%04x, but "
1379                     "there is no active command.\n", err);
1380                 sdhci_dumpregs(slot);
1381                 return;
1382         }
1383         slot_printf(slot, "Got AutoCMD12 error 0x%04x\n", err);
1384         sdhci_reset(slot, SDHCI_RESET_CMD);
1385 }
1386
1387 void
1388 sdhci_generic_intr(struct sdhci_slot *slot)
1389 {
1390         uint32_t intmask, present;
1391         
1392         SDHCI_LOCK(slot);
1393         /* Read slot interrupt status. */
1394         intmask = RD4(slot, SDHCI_INT_STATUS);
1395         if (intmask == 0 || intmask == 0xffffffff) {
1396                 SDHCI_UNLOCK(slot);
1397                 return;
1398         }
1399         if (sdhci_debug > 2)
1400                 slot_printf(slot, "Interrupt %#x\n", intmask);
1401
1402         /* Handle card presence interrupts. */
1403         if (intmask & (SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE)) {
1404                 present = (intmask & SDHCI_INT_CARD_INSERT) != 0;
1405                 slot->intmask &=
1406                     ~(SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE);
1407                 slot->intmask |= present ? SDHCI_INT_CARD_REMOVE :
1408                     SDHCI_INT_CARD_INSERT;
1409                 WR4(slot, SDHCI_INT_ENABLE, slot->intmask);
1410                 WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask);
1411                 WR4(slot, SDHCI_INT_STATUS, intmask & 
1412                     (SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE));
1413                 sdhci_handle_card_present_locked(slot, present);
1414                 intmask &= ~(SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE);
1415         }
1416         /* Handle command interrupts. */
1417         if (intmask & SDHCI_INT_CMD_MASK) {
1418                 WR4(slot, SDHCI_INT_STATUS, intmask & SDHCI_INT_CMD_MASK);
1419                 sdhci_cmd_irq(slot, intmask & SDHCI_INT_CMD_MASK);
1420         }
1421         /* Handle data interrupts. */
1422         if (intmask & SDHCI_INT_DATA_MASK) {
1423                 WR4(slot, SDHCI_INT_STATUS, intmask & SDHCI_INT_DATA_MASK);
1424                 /* Dont call data_irq in case of errored command */
1425                 if ((intmask & SDHCI_INT_CMD_ERROR_MASK) == 0)
1426                         sdhci_data_irq(slot, intmask & SDHCI_INT_DATA_MASK);
1427         }
1428         /* Handle AutoCMD12 error interrupt. */
1429         if (intmask & SDHCI_INT_ACMD12ERR) {
1430                 WR4(slot, SDHCI_INT_STATUS, SDHCI_INT_ACMD12ERR);
1431                 sdhci_acmd_irq(slot);
1432         }
1433         intmask &= ~(SDHCI_INT_CMD_MASK | SDHCI_INT_DATA_MASK);
1434         intmask &= ~SDHCI_INT_ACMD12ERR;
1435         intmask &= ~SDHCI_INT_ERROR;
1436         /* Handle bus power interrupt. */
1437         if (intmask & SDHCI_INT_BUS_POWER) {
1438                 WR4(slot, SDHCI_INT_STATUS, SDHCI_INT_BUS_POWER);
1439                 slot_printf(slot,
1440                     "Card is consuming too much power!\n");
1441                 intmask &= ~SDHCI_INT_BUS_POWER;
1442         }
1443         /* The rest is unknown. */
1444         if (intmask) {
1445                 WR4(slot, SDHCI_INT_STATUS, intmask);
1446                 slot_printf(slot, "Unexpected interrupt 0x%08x.\n",
1447                     intmask);
1448                 sdhci_dumpregs(slot);
1449         }
1450         
1451         SDHCI_UNLOCK(slot);
1452 }
1453
1454 int
1455 sdhci_generic_read_ivar(device_t bus, device_t child, int which, uintptr_t *result)
1456 {
1457         struct sdhci_slot *slot = device_get_ivars(child);
1458
1459         switch (which) {
1460         default:
1461                 return (EINVAL);
1462         case MMCBR_IVAR_BUS_MODE:
1463                 *result = slot->host.ios.bus_mode;
1464                 break;
1465         case MMCBR_IVAR_BUS_WIDTH:
1466                 *result = slot->host.ios.bus_width;
1467                 break;
1468         case MMCBR_IVAR_CHIP_SELECT:
1469                 *result = slot->host.ios.chip_select;
1470                 break;
1471         case MMCBR_IVAR_CLOCK:
1472                 *result = slot->host.ios.clock;
1473                 break;
1474         case MMCBR_IVAR_F_MIN:
1475                 *result = slot->host.f_min;
1476                 break;
1477         case MMCBR_IVAR_F_MAX:
1478                 *result = slot->host.f_max;
1479                 break;
1480         case MMCBR_IVAR_HOST_OCR:
1481                 *result = slot->host.host_ocr;
1482                 break;
1483         case MMCBR_IVAR_MODE:
1484                 *result = slot->host.mode;
1485                 break;
1486         case MMCBR_IVAR_OCR:
1487                 *result = slot->host.ocr;
1488                 break;
1489         case MMCBR_IVAR_POWER_MODE:
1490                 *result = slot->host.ios.power_mode;
1491                 break;
1492         case MMCBR_IVAR_VDD:
1493                 *result = slot->host.ios.vdd;
1494                 break;
1495         case MMCBR_IVAR_CAPS:
1496                 *result = slot->host.caps;
1497                 break;
1498         case MMCBR_IVAR_TIMING:
1499                 *result = slot->host.ios.timing;
1500                 break;
1501         case MMCBR_IVAR_MAX_DATA:
1502                 *result = 65535;
1503                 break;
1504         }
1505         return (0);
1506 }
1507
1508 int
1509 sdhci_generic_write_ivar(device_t bus, device_t child, int which, uintptr_t value)
1510 {
1511         struct sdhci_slot *slot = device_get_ivars(child);
1512
1513         switch (which) {
1514         default:
1515                 return (EINVAL);
1516         case MMCBR_IVAR_BUS_MODE:
1517                 slot->host.ios.bus_mode = value;
1518                 break;
1519         case MMCBR_IVAR_BUS_WIDTH:
1520                 slot->host.ios.bus_width = value;
1521                 break;
1522         case MMCBR_IVAR_CHIP_SELECT:
1523                 slot->host.ios.chip_select = value;
1524                 break;
1525         case MMCBR_IVAR_CLOCK:
1526                 if (value > 0) {
1527                         uint32_t max_clock;
1528                         uint32_t clock;
1529                         int i;
1530
1531                         max_clock = slot->max_clk;
1532                         clock = max_clock;
1533
1534                         if (slot->version < SDHCI_SPEC_300) {
1535                                 for (i = 0; i < SDHCI_200_MAX_DIVIDER;
1536                                     i <<= 1) {
1537                                         if (clock <= value)
1538                                                 break;
1539                                         clock >>= 1;
1540                                 }
1541                         }
1542                         else {
1543                                 for (i = 0; i < SDHCI_300_MAX_DIVIDER;
1544                                     i += 2) {
1545                                         if (clock <= value)
1546                                                 break;
1547                                         clock = max_clock / (i + 2);
1548                                 }
1549                         }
1550
1551                         slot->host.ios.clock = clock;
1552                 } else
1553                         slot->host.ios.clock = 0;
1554                 break;
1555         case MMCBR_IVAR_MODE:
1556                 slot->host.mode = value;
1557                 break;
1558         case MMCBR_IVAR_OCR:
1559                 slot->host.ocr = value;
1560                 break;
1561         case MMCBR_IVAR_POWER_MODE:
1562                 slot->host.ios.power_mode = value;
1563                 break;
1564         case MMCBR_IVAR_VDD:
1565                 slot->host.ios.vdd = value;
1566                 break;
1567         case MMCBR_IVAR_TIMING:
1568                 slot->host.ios.timing = value;
1569                 break;
1570         case MMCBR_IVAR_CAPS:
1571         case MMCBR_IVAR_HOST_OCR:
1572         case MMCBR_IVAR_F_MIN:
1573         case MMCBR_IVAR_F_MAX:
1574         case MMCBR_IVAR_MAX_DATA:
1575                 return (EINVAL);
1576         }
1577         return (0);
1578 }
1579
1580 MODULE_VERSION(sdhci, 1);