]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/sdhci/sdhci.c
MFV r321673:
[FreeBSD/FreeBSD.git] / sys / dev / sdhci / sdhci.c
1 /*-
2  * Copyright (c) 2008 Alexander Motin <mav@FreeBSD.org>
3  * Copyright (c) 2017 Marius Strobl <marius@FreeBSD.org>
4  * 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 THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/bus.h>
33 #include <sys/callout.h>
34 #include <sys/conf.h>
35 #include <sys/kernel.h>
36 #include <sys/kobj.h>
37 #include <sys/lock.h>
38 #include <sys/malloc.h>
39 #include <sys/module.h>
40 #include <sys/mutex.h>
41 #include <sys/resource.h>
42 #include <sys/rman.h>
43 #include <sys/sysctl.h>
44 #include <sys/taskqueue.h>
45
46 #include <machine/bus.h>
47 #include <machine/resource.h>
48 #include <machine/stdarg.h>
49
50 #include <dev/mmc/bridge.h>
51 #include <dev/mmc/mmcreg.h>
52 #include <dev/mmc/mmcbrvar.h>
53
54 #include <dev/sdhci/sdhci.h>
55
56 #include <cam/cam.h>
57 #include <cam/cam_ccb.h>
58 #include <cam/cam_debug.h>
59 #include <cam/cam_sim.h>
60 #include <cam/cam_xpt_sim.h>
61
62 #include "mmcbr_if.h"
63 #include "sdhci_if.h"
64
65 #include "opt_mmccam.h"
66
67 SYSCTL_NODE(_hw, OID_AUTO, sdhci, CTLFLAG_RD, 0, "sdhci driver");
68
69 static int sdhci_debug = 0;
70 SYSCTL_INT(_hw_sdhci, OID_AUTO, debug, CTLFLAG_RWTUN, &sdhci_debug, 0,
71     "Debug level");
72 u_int sdhci_quirk_clear = 0;
73 SYSCTL_INT(_hw_sdhci, OID_AUTO, quirk_clear, CTLFLAG_RWTUN, &sdhci_quirk_clear,
74     0, "Mask of quirks to clear");
75 u_int sdhci_quirk_set = 0;
76 SYSCTL_INT(_hw_sdhci, OID_AUTO, quirk_set, CTLFLAG_RWTUN, &sdhci_quirk_set, 0,
77     "Mask of quirks to set");
78
79 #define RD1(slot, off)  SDHCI_READ_1((slot)->bus, (slot), (off))
80 #define RD2(slot, off)  SDHCI_READ_2((slot)->bus, (slot), (off))
81 #define RD4(slot, off)  SDHCI_READ_4((slot)->bus, (slot), (off))
82 #define RD_MULTI_4(slot, off, ptr, count)       \
83     SDHCI_READ_MULTI_4((slot)->bus, (slot), (off), (ptr), (count))
84
85 #define WR1(slot, off, val)     SDHCI_WRITE_1((slot)->bus, (slot), (off), (val))
86 #define WR2(slot, off, val)     SDHCI_WRITE_2((slot)->bus, (slot), (off), (val))
87 #define WR4(slot, off, val)     SDHCI_WRITE_4((slot)->bus, (slot), (off), (val))
88 #define WR_MULTI_4(slot, off, ptr, count)       \
89     SDHCI_WRITE_MULTI_4((slot)->bus, (slot), (off), (ptr), (count))
90
91 static void sdhci_card_poll(void *arg);
92 static void sdhci_card_task(void *arg, int pending);
93 static int sdhci_exec_tuning(struct sdhci_slot *slot, bool reset);
94 static void sdhci_req_wakeup(struct mmc_request *req);
95 static void sdhci_retune(void *arg);
96 static void sdhci_set_clock(struct sdhci_slot *slot, uint32_t clock);
97 static void sdhci_start(struct sdhci_slot *slot);
98 static void sdhci_start_data(struct sdhci_slot *slot, struct mmc_data *data);
99
100 #ifdef MMCCAM
101 /* CAM-related */
102 int sdhci_cam_get_possible_host_clock(struct sdhci_slot *slot, int proposed_clock);
103 static int sdhci_cam_update_ios(struct sdhci_slot *slot);
104 static int sdhci_cam_request(struct sdhci_slot *slot, union ccb *ccb);
105 static void sdhci_cam_action(struct cam_sim *sim, union ccb *ccb);
106 static void sdhci_cam_poll(struct cam_sim *sim);
107 static int sdhci_cam_settran_settings(struct sdhci_slot *slot, union ccb *ccb);
108 #endif
109
110 /* helper routines */
111 static void sdhci_dumpregs(struct sdhci_slot *slot);
112 static int slot_printf(struct sdhci_slot *slot, const char * fmt, ...)
113     __printflike(2, 3);
114 static uint32_t sdhci_tuning_intmask(struct sdhci_slot *slot);
115
116 #define SDHCI_LOCK(_slot)               mtx_lock(&(_slot)->mtx)
117 #define SDHCI_UNLOCK(_slot)             mtx_unlock(&(_slot)->mtx)
118 #define SDHCI_LOCK_INIT(_slot) \
119         mtx_init(&_slot->mtx, "SD slot mtx", "sdhci", MTX_DEF)
120 #define SDHCI_LOCK_DESTROY(_slot)       mtx_destroy(&_slot->mtx);
121 #define SDHCI_ASSERT_LOCKED(_slot)      mtx_assert(&_slot->mtx, MA_OWNED);
122 #define SDHCI_ASSERT_UNLOCKED(_slot)    mtx_assert(&_slot->mtx, MA_NOTOWNED);
123
124 #define SDHCI_DEFAULT_MAX_FREQ  50
125
126 #define SDHCI_200_MAX_DIVIDER   256
127 #define SDHCI_300_MAX_DIVIDER   2046
128
129 #define SDHCI_CARD_PRESENT_TICKS        (hz / 5)
130 #define SDHCI_INSERT_DELAY_TICKS        (hz / 2)
131
132 /*
133  * Broadcom BCM577xx Controller Constants
134  */
135 /* Maximum divider supported by the default clock source. */
136 #define BCM577XX_DEFAULT_MAX_DIVIDER    256
137 /* Alternative clock's base frequency. */
138 #define BCM577XX_ALT_CLOCK_BASE         63000000
139
140 #define BCM577XX_HOST_CONTROL           0x198
141 #define BCM577XX_CTRL_CLKSEL_MASK       0xFFFFCFFF
142 #define BCM577XX_CTRL_CLKSEL_SHIFT      12
143 #define BCM577XX_CTRL_CLKSEL_DEFAULT    0x0
144 #define BCM577XX_CTRL_CLKSEL_64MHZ      0x3
145
146 static void
147 sdhci_getaddr(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
148 {
149
150         if (error != 0) {
151                 printf("getaddr: error %d\n", error);
152                 return;
153         }
154         *(bus_addr_t *)arg = segs[0].ds_addr;
155 }
156
157 static int
158 slot_printf(struct sdhci_slot *slot, const char * fmt, ...)
159 {
160         va_list ap;
161         int retval;
162
163         retval = printf("%s-slot%d: ",
164             device_get_nameunit(slot->bus), slot->num);
165
166         va_start(ap, fmt);
167         retval += vprintf(fmt, ap);
168         va_end(ap);
169         return (retval);
170 }
171
172 static void
173 sdhci_dumpregs(struct sdhci_slot *slot)
174 {
175
176         slot_printf(slot,
177             "============== REGISTER DUMP ==============\n");
178
179         slot_printf(slot, "Sys addr: 0x%08x | Version:  0x%08x\n",
180             RD4(slot, SDHCI_DMA_ADDRESS), RD2(slot, SDHCI_HOST_VERSION));
181         slot_printf(slot, "Blk size: 0x%08x | Blk cnt:  0x%08x\n",
182             RD2(slot, SDHCI_BLOCK_SIZE), RD2(slot, SDHCI_BLOCK_COUNT));
183         slot_printf(slot, "Argument: 0x%08x | Trn mode: 0x%08x\n",
184             RD4(slot, SDHCI_ARGUMENT), RD2(slot, SDHCI_TRANSFER_MODE));
185         slot_printf(slot, "Present:  0x%08x | Host ctl: 0x%08x\n",
186             RD4(slot, SDHCI_PRESENT_STATE), RD1(slot, SDHCI_HOST_CONTROL));
187         slot_printf(slot, "Power:    0x%08x | Blk gap:  0x%08x\n",
188             RD1(slot, SDHCI_POWER_CONTROL), RD1(slot, SDHCI_BLOCK_GAP_CONTROL));
189         slot_printf(slot, "Wake-up:  0x%08x | Clock:    0x%08x\n",
190             RD1(slot, SDHCI_WAKE_UP_CONTROL), RD2(slot, SDHCI_CLOCK_CONTROL));
191         slot_printf(slot, "Timeout:  0x%08x | Int stat: 0x%08x\n",
192             RD1(slot, SDHCI_TIMEOUT_CONTROL), RD4(slot, SDHCI_INT_STATUS));
193         slot_printf(slot, "Int enab: 0x%08x | Sig enab: 0x%08x\n",
194             RD4(slot, SDHCI_INT_ENABLE), RD4(slot, SDHCI_SIGNAL_ENABLE));
195         slot_printf(slot, "AC12 err: 0x%08x | Host ctl2:0x%08x\n",
196             RD2(slot, SDHCI_ACMD12_ERR), RD2(slot, SDHCI_HOST_CONTROL2));
197         slot_printf(slot, "Caps:     0x%08x | Caps2:    0x%08x\n",
198             RD4(slot, SDHCI_CAPABILITIES), RD4(slot, SDHCI_CAPABILITIES2));
199         slot_printf(slot, "Max curr: 0x%08x | ADMA err: 0x%08x\n",
200             RD4(slot, SDHCI_MAX_CURRENT), RD1(slot, SDHCI_ADMA_ERR));
201         slot_printf(slot, "ADMA addr:0x%08x | Slot int: 0x%08x\n",
202             RD4(slot, SDHCI_ADMA_ADDRESS_LO), RD2(slot, SDHCI_SLOT_INT_STATUS));
203
204         slot_printf(slot,
205             "===========================================\n");
206 }
207
208 static void
209 sdhci_reset(struct sdhci_slot *slot, uint8_t mask)
210 {
211         int timeout;
212         uint32_t clock;
213
214         if (slot->quirks & SDHCI_QUIRK_NO_CARD_NO_RESET) {
215                 if (!SDHCI_GET_CARD_PRESENT(slot->bus, slot))
216                         return;
217         }
218
219         /* Some controllers need this kick or reset won't work. */
220         if ((mask & SDHCI_RESET_ALL) == 0 &&
221             (slot->quirks & SDHCI_QUIRK_CLOCK_BEFORE_RESET)) {
222                 /* This is to force an update */
223                 clock = slot->clock;
224                 slot->clock = 0;
225                 sdhci_set_clock(slot, clock);
226         }
227
228         if (mask & SDHCI_RESET_ALL) {
229                 slot->clock = 0;
230                 slot->power = 0;
231         }
232
233         WR1(slot, SDHCI_SOFTWARE_RESET, mask);
234
235         if (slot->quirks & SDHCI_QUIRK_WAITFOR_RESET_ASSERTED) {
236                 /*
237                  * Resets on TI OMAPs and AM335x are incompatible with SDHCI
238                  * specification.  The reset bit has internal propagation delay,
239                  * so a fast read after write returns 0 even if reset process is
240                  * in progress.  The workaround is to poll for 1 before polling
241                  * for 0.  In the worst case, if we miss seeing it asserted the
242                  * time we spent waiting is enough to ensure the reset finishes.
243                  */
244                 timeout = 10000;
245                 while ((RD1(slot, SDHCI_SOFTWARE_RESET) & mask) != mask) {
246                         if (timeout <= 0)
247                                 break;
248                         timeout--;
249                         DELAY(1);
250                 }
251         }
252
253         /* Wait max 100 ms */
254         timeout = 10000;
255         /* Controller clears the bits when it's done */
256         while (RD1(slot, SDHCI_SOFTWARE_RESET) & mask) {
257                 if (timeout <= 0) {
258                         slot_printf(slot, "Reset 0x%x never completed.\n",
259                             mask);
260                         sdhci_dumpregs(slot);
261                         return;
262                 }
263                 timeout--;
264                 DELAY(10);
265         }
266 }
267
268 static uint32_t
269 sdhci_tuning_intmask(struct sdhci_slot *slot)
270 {
271         uint32_t intmask;
272
273         intmask = 0;
274         if (slot->opt & SDHCI_TUNING_SUPPORTED) {
275                 intmask |= SDHCI_INT_TUNEERR;
276                 if (slot->retune_mode == SDHCI_RETUNE_MODE_2 ||
277                     slot->retune_mode == SDHCI_RETUNE_MODE_3)
278                         intmask |= SDHCI_INT_RETUNE;
279         }
280         return (intmask);
281 }
282
283 static void
284 sdhci_init(struct sdhci_slot *slot)
285 {
286
287         sdhci_reset(slot, SDHCI_RESET_ALL);
288
289         /* Enable interrupts. */
290         slot->intmask = SDHCI_INT_BUS_POWER | SDHCI_INT_DATA_END_BIT |
291             SDHCI_INT_DATA_CRC | SDHCI_INT_DATA_TIMEOUT | SDHCI_INT_INDEX |
292             SDHCI_INT_END_BIT | SDHCI_INT_CRC | SDHCI_INT_TIMEOUT |
293             SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL |
294             SDHCI_INT_DMA_END | SDHCI_INT_DATA_END | SDHCI_INT_RESPONSE |
295             SDHCI_INT_ACMD12ERR;
296
297         if (!(slot->quirks & SDHCI_QUIRK_POLL_CARD_PRESENT) &&
298             !(slot->opt & SDHCI_NON_REMOVABLE)) {
299                 slot->intmask |= SDHCI_INT_CARD_REMOVE | SDHCI_INT_CARD_INSERT;
300         }
301
302         WR4(slot, SDHCI_INT_ENABLE, slot->intmask | sdhci_tuning_intmask(slot));
303         WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask);
304 }
305
306 static void
307 sdhci_set_clock(struct sdhci_slot *slot, uint32_t clock)
308 {
309         uint32_t clk_base;
310         uint32_t clk_sel;
311         uint32_t res;
312         uint16_t clk;
313         uint16_t div;
314         int timeout;
315
316         if (clock == slot->clock)
317                 return;
318         slot->clock = clock;
319
320         /* Turn off the clock. */
321         clk = RD2(slot, SDHCI_CLOCK_CONTROL);
322         WR2(slot, SDHCI_CLOCK_CONTROL, clk & ~SDHCI_CLOCK_CARD_EN);
323         /* If no clock requested - leave it so. */
324         if (clock == 0)
325                 return;
326
327         /* Determine the clock base frequency */
328         clk_base = slot->max_clk;
329         if (slot->quirks & SDHCI_QUIRK_BCM577XX_400KHZ_CLKSRC) {
330                 clk_sel = RD2(slot, BCM577XX_HOST_CONTROL) &
331                     BCM577XX_CTRL_CLKSEL_MASK;
332
333                 /*
334                  * Select clock source appropriate for the requested frequency.
335                  */
336                 if ((clk_base / BCM577XX_DEFAULT_MAX_DIVIDER) > clock) {
337                         clk_base = BCM577XX_ALT_CLOCK_BASE;
338                         clk_sel |= (BCM577XX_CTRL_CLKSEL_64MHZ <<
339                             BCM577XX_CTRL_CLKSEL_SHIFT);
340                 } else {
341                         clk_sel |= (BCM577XX_CTRL_CLKSEL_DEFAULT <<
342                             BCM577XX_CTRL_CLKSEL_SHIFT);
343                 }
344
345                 WR2(slot, BCM577XX_HOST_CONTROL, clk_sel);
346         }
347
348         /* Recalculate timeout clock frequency based on the new sd clock. */
349         if (slot->quirks & SDHCI_QUIRK_DATA_TIMEOUT_USES_SDCLK)
350                 slot->timeout_clk = slot->clock / 1000;
351
352         if (slot->version < SDHCI_SPEC_300) {
353                 /* Looking for highest freq <= clock. */
354                 res = clk_base;
355                 for (div = 1; div < SDHCI_200_MAX_DIVIDER; div <<= 1) {
356                         if (res <= clock)
357                                 break;
358                         res >>= 1;
359                 }
360                 /* Divider 1:1 is 0x00, 2:1 is 0x01, 256:1 is 0x80 ... */
361                 div >>= 1;
362         } else {
363                 /* Version 3.0 divisors are multiples of two up to 1023 * 2 */
364                 if (clock >= clk_base)
365                         div = 0;
366                 else {
367                         for (div = 2; div < SDHCI_300_MAX_DIVIDER; div += 2) {
368                                 if ((clk_base / div) <= clock)
369                                         break;
370                         }
371                 }
372                 div >>= 1;
373         }
374
375         if (bootverbose || sdhci_debug)
376                 slot_printf(slot, "Divider %d for freq %d (base %d)\n",
377                         div, clock, clk_base);
378
379         /* Now we have got divider, set it. */
380         clk = (div & SDHCI_DIVIDER_MASK) << SDHCI_DIVIDER_SHIFT;
381         clk |= ((div >> SDHCI_DIVIDER_MASK_LEN) & SDHCI_DIVIDER_HI_MASK)
382                 << SDHCI_DIVIDER_HI_SHIFT;
383
384         WR2(slot, SDHCI_CLOCK_CONTROL, clk);
385         /* Enable clock. */
386         clk |= SDHCI_CLOCK_INT_EN;
387         WR2(slot, SDHCI_CLOCK_CONTROL, clk);
388         /* Wait up to 10 ms until it stabilize. */
389         timeout = 10;
390         while (!((clk = RD2(slot, SDHCI_CLOCK_CONTROL))
391                 & SDHCI_CLOCK_INT_STABLE)) {
392                 if (timeout == 0) {
393                         slot_printf(slot,
394                             "Internal clock never stabilised.\n");
395                         sdhci_dumpregs(slot);
396                         return;
397                 }
398                 timeout--;
399                 DELAY(1000);
400         }
401         /* Pass clock signal to the bus. */
402         clk |= SDHCI_CLOCK_CARD_EN;
403         WR2(slot, SDHCI_CLOCK_CONTROL, clk);
404 }
405
406 static void
407 sdhci_set_power(struct sdhci_slot *slot, u_char power)
408 {
409         int i;
410         uint8_t pwr;
411
412         if (slot->power == power)
413                 return;
414
415         slot->power = power;
416
417         /* Turn off the power. */
418         pwr = 0;
419         WR1(slot, SDHCI_POWER_CONTROL, pwr);
420         /* If power down requested - leave it so. */
421         if (power == 0)
422                 return;
423         /* Set voltage. */
424         switch (1 << power) {
425         case MMC_OCR_LOW_VOLTAGE:
426                 pwr |= SDHCI_POWER_180;
427                 break;
428         case MMC_OCR_290_300:
429         case MMC_OCR_300_310:
430                 pwr |= SDHCI_POWER_300;
431                 break;
432         case MMC_OCR_320_330:
433         case MMC_OCR_330_340:
434                 pwr |= SDHCI_POWER_330;
435                 break;
436         }
437         WR1(slot, SDHCI_POWER_CONTROL, pwr);
438         /*
439          * Turn on VDD1 power.  Note that at least some Intel controllers can
440          * fail to enable bus power on the first try after transiting from D3
441          * to D0, so we give them up to 2 ms.
442          */
443         pwr |= SDHCI_POWER_ON;
444         for (i = 0; i < 20; i++) {
445                 WR1(slot, SDHCI_POWER_CONTROL, pwr);
446                 if (RD1(slot, SDHCI_POWER_CONTROL) & SDHCI_POWER_ON)
447                         break;
448                 DELAY(100);
449         }
450         if (!(RD1(slot, SDHCI_POWER_CONTROL) & SDHCI_POWER_ON))
451                 slot_printf(slot, "Bus power failed to enable");
452
453         if (slot->quirks & SDHCI_QUIRK_INTEL_POWER_UP_RESET) {
454                 WR1(slot, SDHCI_POWER_CONTROL, pwr | 0x10);
455                 DELAY(10);
456                 WR1(slot, SDHCI_POWER_CONTROL, pwr);
457                 DELAY(300);
458         }
459 }
460
461 static void
462 sdhci_read_block_pio(struct sdhci_slot *slot)
463 {
464         uint32_t data;
465         char *buffer;
466         size_t left;
467
468         buffer = slot->curcmd->data->data;
469         buffer += slot->offset;
470         /* Transfer one block at a time. */
471         left = min(512, slot->curcmd->data->len - slot->offset);
472         slot->offset += left;
473
474         /* If we are too fast, broken controllers return zeroes. */
475         if (slot->quirks & SDHCI_QUIRK_BROKEN_TIMINGS)
476                 DELAY(10);
477         /* Handle unaligned and aligned buffer cases. */
478         if ((intptr_t)buffer & 3) {
479                 while (left > 3) {
480                         data = RD4(slot, SDHCI_BUFFER);
481                         buffer[0] = data;
482                         buffer[1] = (data >> 8);
483                         buffer[2] = (data >> 16);
484                         buffer[3] = (data >> 24);
485                         buffer += 4;
486                         left -= 4;
487                 }
488         } else {
489                 RD_MULTI_4(slot, SDHCI_BUFFER,
490                     (uint32_t *)buffer, left >> 2);
491                 left &= 3;
492         }
493         /* Handle uneven size case. */
494         if (left > 0) {
495                 data = RD4(slot, SDHCI_BUFFER);
496                 while (left > 0) {
497                         *(buffer++) = data;
498                         data >>= 8;
499                         left--;
500                 }
501         }
502 }
503
504 static void
505 sdhci_write_block_pio(struct sdhci_slot *slot)
506 {
507         uint32_t data = 0;
508         char *buffer;
509         size_t left;
510
511         buffer = slot->curcmd->data->data;
512         buffer += slot->offset;
513         /* Transfer one block at a time. */
514         left = min(512, slot->curcmd->data->len - slot->offset);
515         slot->offset += left;
516
517         /* Handle unaligned and aligned buffer cases. */
518         if ((intptr_t)buffer & 3) {
519                 while (left > 3) {
520                         data = buffer[0] +
521                             (buffer[1] << 8) +
522                             (buffer[2] << 16) +
523                             (buffer[3] << 24);
524                         left -= 4;
525                         buffer += 4;
526                         WR4(slot, SDHCI_BUFFER, data);
527                 }
528         } else {
529                 WR_MULTI_4(slot, SDHCI_BUFFER,
530                     (uint32_t *)buffer, left >> 2);
531                 left &= 3;
532         }
533         /* Handle uneven size case. */
534         if (left > 0) {
535                 while (left > 0) {
536                         data <<= 8;
537                         data += *(buffer++);
538                         left--;
539                 }
540                 WR4(slot, SDHCI_BUFFER, data);
541         }
542 }
543
544 static void
545 sdhci_transfer_pio(struct sdhci_slot *slot)
546 {
547
548         /* Read as many blocks as possible. */
549         if (slot->curcmd->data->flags & MMC_DATA_READ) {
550                 while (RD4(slot, SDHCI_PRESENT_STATE) &
551                     SDHCI_DATA_AVAILABLE) {
552                         sdhci_read_block_pio(slot);
553                         if (slot->offset >= slot->curcmd->data->len)
554                                 break;
555                 }
556         } else {
557                 while (RD4(slot, SDHCI_PRESENT_STATE) &
558                     SDHCI_SPACE_AVAILABLE) {
559                         sdhci_write_block_pio(slot);
560                         if (slot->offset >= slot->curcmd->data->len)
561                                 break;
562                 }
563         }
564 }
565
566 static void
567 sdhci_card_task(void *arg, int pending __unused)
568 {
569         struct sdhci_slot *slot = arg;
570         device_t d;
571
572         SDHCI_LOCK(slot);
573         if (SDHCI_GET_CARD_PRESENT(slot->bus, slot)) {
574 #ifdef MMCCAM
575                 if (slot->card_present == 0) {
576 #else
577                 if (slot->dev == NULL) {
578 #endif
579                         /* If card is present - attach mmc bus. */
580                         if (bootverbose || sdhci_debug)
581                                 slot_printf(slot, "Card inserted\n");
582 #ifdef MMCCAM
583                         slot->card_present = 1;
584                         union ccb *ccb;
585                         uint32_t pathid;
586                         pathid = cam_sim_path(slot->sim);
587                         ccb = xpt_alloc_ccb_nowait();
588                         if (ccb == NULL) {
589                                 slot_printf(slot, "Unable to alloc CCB for rescan\n");
590                                 SDHCI_UNLOCK(slot);
591                                 return;
592                         }
593
594                         /*
595                          * We create a rescan request for BUS:0:0, since the card
596                          * will be at lun 0.
597                          */
598                         if (xpt_create_path(&ccb->ccb_h.path, NULL, pathid,
599                                             /* target */ 0, /* lun */ 0) != CAM_REQ_CMP) {
600                                 slot_printf(slot, "Unable to create path for rescan\n");
601                                 SDHCI_UNLOCK(slot);
602                                 xpt_free_ccb(ccb);
603                                 return;
604                         }
605                         SDHCI_UNLOCK(slot);
606                         xpt_rescan(ccb);
607 #else
608                         d = slot->dev = device_add_child(slot->bus, "mmc", -1);
609                         SDHCI_UNLOCK(slot);
610                         if (d) {
611                                 device_set_ivars(d, slot);
612                                 (void)device_probe_and_attach(d);
613                         }
614 #endif
615                 } else
616                         SDHCI_UNLOCK(slot);
617         } else {
618 #ifdef MMCCAM
619                 if (slot->card_present == 1) {
620 #else
621                 if (slot->dev != NULL) {
622 #endif
623                         /* If no card present - detach mmc bus. */
624                         if (bootverbose || sdhci_debug)
625                                 slot_printf(slot, "Card removed\n");
626                         d = slot->dev;
627                         slot->dev = NULL;
628 #ifdef MMCCAM
629                         slot->card_present = 0;
630                         union ccb *ccb;
631                         uint32_t pathid;
632                         pathid = cam_sim_path(slot->sim);
633                         ccb = xpt_alloc_ccb_nowait();
634                         if (ccb == NULL) {
635                                 slot_printf(slot, "Unable to alloc CCB for rescan\n");
636                                 SDHCI_UNLOCK(slot);
637                                 return;
638                         }
639
640                         /*
641                          * We create a rescan request for BUS:0:0, since the card
642                          * will be at lun 0.
643                          */
644                         if (xpt_create_path(&ccb->ccb_h.path, NULL, pathid,
645                                             /* target */ 0, /* lun */ 0) != CAM_REQ_CMP) {
646                                 slot_printf(slot, "Unable to create path for rescan\n");
647                                 SDHCI_UNLOCK(slot);
648                                 xpt_free_ccb(ccb);
649                                 return;
650                         }
651                         SDHCI_UNLOCK(slot);
652                         xpt_rescan(ccb);
653 #else
654                         slot->intmask &= ~sdhci_tuning_intmask(slot);
655                         WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask);
656                         slot->opt &= ~SDHCI_TUNING_ENABLED;
657                         SDHCI_UNLOCK(slot);
658                         callout_drain(&slot->retune_callout);
659                         device_delete_child(slot->bus, d);
660 #endif
661                 } else
662                         SDHCI_UNLOCK(slot);
663         }
664 }
665
666 static void
667 sdhci_handle_card_present_locked(struct sdhci_slot *slot, bool is_present)
668 {
669         bool was_present;
670
671         /*
672          * If there was no card and now there is one, schedule the task to
673          * create the child device after a short delay.  The delay is to
674          * debounce the card insert (sometimes the card detect pin stabilizes
675          * before the other pins have made good contact).
676          *
677          * If there was a card present and now it's gone, immediately schedule
678          * the task to delete the child device.  No debouncing -- gone is gone,
679          * because once power is removed, a full card re-init is needed, and
680          * that happens by deleting and recreating the child device.
681          */
682 #ifdef MMCCAM
683         was_present = slot->card_present;
684 #else
685         was_present = slot->dev != NULL;
686 #endif
687         if (!was_present && is_present) {
688                 taskqueue_enqueue_timeout(taskqueue_swi_giant,
689                     &slot->card_delayed_task, -SDHCI_INSERT_DELAY_TICKS);
690         } else if (was_present && !is_present) {
691                 taskqueue_enqueue(taskqueue_swi_giant, &slot->card_task);
692         }
693 }
694
695 void
696 sdhci_handle_card_present(struct sdhci_slot *slot, bool is_present)
697 {
698
699         SDHCI_LOCK(slot);
700         sdhci_handle_card_present_locked(slot, is_present);
701         SDHCI_UNLOCK(slot);
702 }
703
704 static void
705 sdhci_card_poll(void *arg)
706 {
707         struct sdhci_slot *slot = arg;
708
709         sdhci_handle_card_present(slot,
710             SDHCI_GET_CARD_PRESENT(slot->bus, slot));
711         callout_reset(&slot->card_poll_callout, SDHCI_CARD_PRESENT_TICKS,
712             sdhci_card_poll, slot);
713 }
714
715 int
716 sdhci_init_slot(device_t dev, struct sdhci_slot *slot, int num)
717 {
718         kobjop_desc_t kobj_desc;
719         kobj_method_t *kobj_method;
720         uint32_t caps, caps2, freq, host_caps;
721         int err;
722
723         SDHCI_LOCK_INIT(slot);
724
725         slot->num = num;
726         slot->bus = dev;
727
728         /* Allocate DMA tag. */
729         err = bus_dma_tag_create(bus_get_dma_tag(dev),
730             DMA_BLOCK_SIZE, 0, BUS_SPACE_MAXADDR_32BIT,
731             BUS_SPACE_MAXADDR, NULL, NULL,
732             DMA_BLOCK_SIZE, 1, DMA_BLOCK_SIZE,
733             BUS_DMA_ALLOCNOW, NULL, NULL,
734             &slot->dmatag);
735         if (err != 0) {
736                 device_printf(dev, "Can't create DMA tag\n");
737                 SDHCI_LOCK_DESTROY(slot);
738                 return (err);
739         }
740         /* Allocate DMA memory. */
741         err = bus_dmamem_alloc(slot->dmatag, (void **)&slot->dmamem,
742             BUS_DMA_NOWAIT, &slot->dmamap);
743         if (err != 0) {
744                 device_printf(dev, "Can't alloc DMA memory\n");
745                 bus_dma_tag_destroy(slot->dmatag);
746                 SDHCI_LOCK_DESTROY(slot);
747                 return (err);
748         }
749         /* Map the memory. */
750         err = bus_dmamap_load(slot->dmatag, slot->dmamap,
751             (void *)slot->dmamem, DMA_BLOCK_SIZE,
752             sdhci_getaddr, &slot->paddr, 0);
753         if (err != 0 || slot->paddr == 0) {
754                 device_printf(dev, "Can't load DMA memory\n");
755                 bus_dmamem_free(slot->dmatag, slot->dmamem, slot->dmamap);
756                 bus_dma_tag_destroy(slot->dmatag);
757                 SDHCI_LOCK_DESTROY(slot);
758                 if (err)
759                         return (err);
760                 else
761                         return (EFAULT);
762         }
763
764         slot->version = (RD2(slot, SDHCI_HOST_VERSION)
765                 >> SDHCI_SPEC_VER_SHIFT) & SDHCI_SPEC_VER_MASK;
766         if (slot->quirks & SDHCI_QUIRK_MISSING_CAPS) {
767                 caps = slot->caps;
768                 caps2 = slot->caps2;
769         } else {
770                 caps = RD4(slot, SDHCI_CAPABILITIES);
771                 if (slot->version >= SDHCI_SPEC_300)
772                         caps2 = RD4(slot, SDHCI_CAPABILITIES2);
773                 else
774                         caps2 = 0;
775         }
776         if (slot->version >= SDHCI_SPEC_300) {
777                 if ((caps & SDHCI_SLOTTYPE_MASK) != SDHCI_SLOTTYPE_REMOVABLE &&
778                     (caps & SDHCI_SLOTTYPE_MASK) != SDHCI_SLOTTYPE_EMBEDDED) {
779                         device_printf(dev,
780                             "Driver doesn't support shared bus slots\n");
781                         bus_dmamap_unload(slot->dmatag, slot->dmamap);
782                         bus_dmamem_free(slot->dmatag, slot->dmamem,
783                             slot->dmamap);
784                         bus_dma_tag_destroy(slot->dmatag);
785                         SDHCI_LOCK_DESTROY(slot);
786                         return (ENXIO);
787                 } else if ((caps & SDHCI_SLOTTYPE_MASK) ==
788                     SDHCI_SLOTTYPE_EMBEDDED) {
789                         slot->opt |= SDHCI_SLOT_EMBEDDED | SDHCI_NON_REMOVABLE;
790                 }
791         }
792         /* Calculate base clock frequency. */
793         if (slot->version >= SDHCI_SPEC_300)
794                 freq = (caps & SDHCI_CLOCK_V3_BASE_MASK) >>
795                     SDHCI_CLOCK_BASE_SHIFT;
796         else
797                 freq = (caps & SDHCI_CLOCK_BASE_MASK) >>
798                     SDHCI_CLOCK_BASE_SHIFT;
799         if (freq != 0)
800                 slot->max_clk = freq * 1000000;
801         /*
802          * If the frequency wasn't in the capabilities and the hardware driver
803          * hasn't already set max_clk we're probably not going to work right
804          * with an assumption, so complain about it.
805          */
806         if (slot->max_clk == 0) {
807                 slot->max_clk = SDHCI_DEFAULT_MAX_FREQ * 1000000;
808                 device_printf(dev, "Hardware doesn't specify base clock "
809                     "frequency, using %dMHz as default.\n",
810                     SDHCI_DEFAULT_MAX_FREQ);
811         }
812         /* Calculate/set timeout clock frequency. */
813         if (slot->quirks & SDHCI_QUIRK_DATA_TIMEOUT_USES_SDCLK) {
814                 slot->timeout_clk = slot->max_clk / 1000;
815         } else if (slot->quirks & SDHCI_QUIRK_DATA_TIMEOUT_1MHZ) {
816                 slot->timeout_clk = 1000;
817         } else {
818                 slot->timeout_clk = (caps & SDHCI_TIMEOUT_CLK_MASK) >>
819                     SDHCI_TIMEOUT_CLK_SHIFT;
820                 if (caps & SDHCI_TIMEOUT_CLK_UNIT)
821                         slot->timeout_clk *= 1000;
822         }
823         /*
824          * If the frequency wasn't in the capabilities and the hardware driver
825          * hasn't already set timeout_clk we'll probably work okay using the
826          * max timeout, but still mention it.
827          */
828         if (slot->timeout_clk == 0) {
829                 device_printf(dev, "Hardware doesn't specify timeout clock "
830                     "frequency, setting BROKEN_TIMEOUT quirk.\n");
831                 slot->quirks |= SDHCI_QUIRK_BROKEN_TIMEOUT_VAL;
832         }
833
834         slot->host.f_min = SDHCI_MIN_FREQ(slot->bus, slot);
835         slot->host.f_max = slot->max_clk;
836         slot->host.host_ocr = 0;
837         if (caps & SDHCI_CAN_VDD_330)
838             slot->host.host_ocr |= MMC_OCR_320_330 | MMC_OCR_330_340;
839         if (caps & SDHCI_CAN_VDD_300)
840             slot->host.host_ocr |= MMC_OCR_290_300 | MMC_OCR_300_310;
841         /* 1.8V VDD is not supposed to be used for removable cards. */
842         if ((caps & SDHCI_CAN_VDD_180) && (slot->opt & SDHCI_SLOT_EMBEDDED))
843             slot->host.host_ocr |= MMC_OCR_LOW_VOLTAGE;
844         if (slot->host.host_ocr == 0) {
845                 device_printf(dev, "Hardware doesn't report any "
846                     "support voltages.\n");
847         }
848
849         host_caps = MMC_CAP_4_BIT_DATA;
850         if (caps & SDHCI_CAN_DO_8BITBUS)
851                 host_caps |= MMC_CAP_8_BIT_DATA;
852         if (caps & SDHCI_CAN_DO_HISPD)
853                 host_caps |= MMC_CAP_HSPEED;
854         if (slot->quirks & SDHCI_QUIRK_BOOT_NOACC)
855                 host_caps |= MMC_CAP_BOOT_NOACC;
856         if (slot->quirks & SDHCI_QUIRK_WAIT_WHILE_BUSY)
857                 host_caps |= MMC_CAP_WAIT_WHILE_BUSY;
858
859         /* Determine supported UHS-I and eMMC modes. */
860         if (caps2 & (SDHCI_CAN_SDR50 | SDHCI_CAN_SDR104 | SDHCI_CAN_DDR50))
861                 host_caps |= MMC_CAP_UHS_SDR12 | MMC_CAP_UHS_SDR25;
862         if (caps2 & SDHCI_CAN_SDR104) {
863                 host_caps |= MMC_CAP_UHS_SDR104 | MMC_CAP_UHS_SDR50;
864                 if (!(slot->quirks & SDHCI_QUIRK_BROKEN_MMC_HS200))
865                         host_caps |= MMC_CAP_MMC_HS200;
866         } else if (caps2 & SDHCI_CAN_SDR50)
867                 host_caps |= MMC_CAP_UHS_SDR50;
868         if (caps2 & SDHCI_CAN_DDR50 &&
869             !(slot->quirks & SDHCI_QUIRK_BROKEN_UHS_DDR50))
870                 host_caps |= MMC_CAP_UHS_DDR50;
871         if (slot->quirks & SDHCI_QUIRK_MMC_DDR52)
872                 host_caps |= MMC_CAP_MMC_DDR52;
873         if (slot->quirks & SDHCI_QUIRK_CAPS_BIT63_FOR_MMC_HS400 &&
874             caps2 & SDHCI_CAN_MMC_HS400)
875                 host_caps |= MMC_CAP_MMC_HS400;
876
877         /*
878          * Disable UHS-I and eMMC modes if the set_uhs_timing method is the
879          * default NULL implementation.
880          */
881         kobj_desc = &sdhci_set_uhs_timing_desc;
882         kobj_method = kobj_lookup_method(((kobj_t)dev)->ops->cls, NULL,
883             kobj_desc);
884         if (kobj_method == &kobj_desc->deflt)
885                 host_caps &= ~(MMC_CAP_UHS_SDR12 | MMC_CAP_UHS_SDR25 |
886                     MMC_CAP_UHS_SDR50 | MMC_CAP_UHS_DDR50 | MMC_CAP_UHS_SDR104 |
887                     MMC_CAP_MMC_DDR52 | MMC_CAP_MMC_HS200 | MMC_CAP_MMC_HS400);
888
889 #define SDHCI_CAP_MODES_TUNING(caps2)                                   \
890     (((caps2) & SDHCI_TUNE_SDR50 ? MMC_CAP_UHS_SDR50 : 0) |             \
891     MMC_CAP_UHS_DDR50 | MMC_CAP_UHS_SDR104 | MMC_CAP_MMC_HS200 |        \
892     MMC_CAP_MMC_HS400)
893
894         /*
895          * Disable UHS-I and eMMC modes that require (re-)tuning if either
896          * the tune or re-tune method is the default NULL implementation.
897          */
898         kobj_desc = &mmcbr_tune_desc;
899         kobj_method = kobj_lookup_method(((kobj_t)dev)->ops->cls, NULL,
900             kobj_desc);
901         if (kobj_method == &kobj_desc->deflt)
902                 goto no_tuning;
903         kobj_desc = &mmcbr_retune_desc;
904         kobj_method = kobj_lookup_method(((kobj_t)dev)->ops->cls, NULL,
905             kobj_desc);
906         if (kobj_method == &kobj_desc->deflt) {
907 no_tuning:
908                 host_caps &= ~(SDHCI_CAP_MODES_TUNING(caps2));
909         }
910
911         /* Allocate tuning structures and determine tuning parameters. */
912         if (host_caps & SDHCI_CAP_MODES_TUNING(caps2)) {
913                 slot->opt |= SDHCI_TUNING_SUPPORTED;
914                 slot->tune_req = malloc(sizeof(*slot->tune_req), M_DEVBUF,
915                     M_WAITOK);
916                 slot->tune_cmd = malloc(sizeof(*slot->tune_cmd), M_DEVBUF,
917                     M_WAITOK);
918                 slot->tune_data = malloc(sizeof(*slot->tune_data), M_DEVBUF,
919                     M_WAITOK);
920                 if (caps2 & SDHCI_TUNE_SDR50)
921                         slot->opt |= SDHCI_SDR50_NEEDS_TUNING;
922                 slot->retune_mode = (caps2 & SDHCI_RETUNE_MODES_MASK) >>
923                     SDHCI_RETUNE_MODES_SHIFT;
924                 if (slot->retune_mode == SDHCI_RETUNE_MODE_1) {
925                         slot->retune_count = (caps2 & SDHCI_RETUNE_CNT_MASK) >>
926                             SDHCI_RETUNE_CNT_SHIFT;
927                         if (slot->retune_count > 0xb) {
928                                 device_printf(dev, "Unknown re-tuning count "
929                                     "%x, using 1 sec\n", slot->retune_count);
930                                 slot->retune_count = 1;
931                         } else if (slot->retune_count != 0)
932                                 slot->retune_count =
933                                     1 << (slot->retune_count - 1);
934                 }
935         }
936
937 #undef SDHCI_CAP_MODES_TUNING
938
939         /* Determine supported VCCQ signaling levels. */
940         host_caps |= MMC_CAP_SIGNALING_330;
941         if (host_caps & (MMC_CAP_UHS_SDR12 | MMC_CAP_UHS_SDR25 |
942             MMC_CAP_UHS_SDR50 | MMC_CAP_UHS_DDR50 | MMC_CAP_UHS_SDR104 |
943             MMC_CAP_MMC_DDR52_180 | MMC_CAP_MMC_HS200_180 |
944             MMC_CAP_MMC_HS400_180))
945                 host_caps |= MMC_CAP_SIGNALING_120 | MMC_CAP_SIGNALING_180;
946
947         /*
948          * Disable 1.2 V and 1.8 V signaling if the switch_vccq method is the
949          * default NULL implementation.  Disable 1.2 V support if it's the
950          * generic SDHCI implementation.
951          */
952         kobj_desc = &mmcbr_switch_vccq_desc;
953         kobj_method = kobj_lookup_method(((kobj_t)dev)->ops->cls, NULL,
954             kobj_desc);
955         if (kobj_method == &kobj_desc->deflt)
956                 host_caps &= ~(MMC_CAP_SIGNALING_120 | MMC_CAP_SIGNALING_180);
957         else if (kobj_method->func == (kobjop_t)sdhci_generic_switch_vccq)
958                 host_caps &= ~MMC_CAP_SIGNALING_120;
959
960         /* Determine supported driver types (type B is always mandatory). */
961         if (caps2 & SDHCI_CAN_DRIVE_TYPE_A)
962                 host_caps |= MMC_CAP_DRIVER_TYPE_A;
963         if (caps2 & SDHCI_CAN_DRIVE_TYPE_C)
964                 host_caps |= MMC_CAP_DRIVER_TYPE_C;
965         if (caps2 & SDHCI_CAN_DRIVE_TYPE_D)
966                 host_caps |= MMC_CAP_DRIVER_TYPE_D;
967         slot->host.caps = host_caps;
968
969         /* Decide if we have usable DMA. */
970         if (caps & SDHCI_CAN_DO_DMA)
971                 slot->opt |= SDHCI_HAVE_DMA;
972
973         if (slot->quirks & SDHCI_QUIRK_BROKEN_DMA)
974                 slot->opt &= ~SDHCI_HAVE_DMA;
975         if (slot->quirks & SDHCI_QUIRK_FORCE_DMA)
976                 slot->opt |= SDHCI_HAVE_DMA;
977         if (slot->quirks & SDHCI_QUIRK_ALL_SLOTS_NON_REMOVABLE)
978                 slot->opt |= SDHCI_NON_REMOVABLE;
979
980         /*
981          * Use platform-provided transfer backend
982          * with PIO as a fallback mechanism
983          */
984         if (slot->opt & SDHCI_PLATFORM_TRANSFER)
985                 slot->opt &= ~SDHCI_HAVE_DMA;
986
987         if (bootverbose || sdhci_debug) {
988                 slot_printf(slot,
989                     "%uMHz%s %s VDD:%s%s%s VCCQ: 3.3V%s%s DRV: B%s%s%s %s %s\n",
990                     slot->max_clk / 1000000,
991                     (caps & SDHCI_CAN_DO_HISPD) ? " HS" : "",
992                     (host_caps & MMC_CAP_8_BIT_DATA) ? "8bits" :
993                         ((host_caps & MMC_CAP_4_BIT_DATA) ? "4bits" : "1bit"),
994                     (caps & SDHCI_CAN_VDD_330) ? " 3.3V" : "",
995                     (caps & SDHCI_CAN_VDD_300) ? " 3.0V" : "",
996                     ((caps & SDHCI_CAN_VDD_180) &&
997                     (slot->opt & SDHCI_SLOT_EMBEDDED)) ? " 1.8V" : "",
998                     (host_caps & MMC_CAP_SIGNALING_180) ? " 1.8V" : "",
999                     (host_caps & MMC_CAP_SIGNALING_120) ? " 1.2V" : "",
1000                     (host_caps & MMC_CAP_DRIVER_TYPE_A) ? "A" : "",
1001                     (host_caps & MMC_CAP_DRIVER_TYPE_C) ? "C" : "",
1002                     (host_caps & MMC_CAP_DRIVER_TYPE_D) ? "D" : "",
1003                     (slot->opt & SDHCI_HAVE_DMA) ? "DMA" : "PIO",
1004                     (slot->opt & SDHCI_SLOT_EMBEDDED) ? "embedded" :
1005                     (slot->opt & SDHCI_NON_REMOVABLE) ? "non-removable" :
1006                     "removable");
1007                 if (host_caps & (MMC_CAP_MMC_DDR52 | MMC_CAP_MMC_HS200 |
1008                     MMC_CAP_MMC_HS400 | MMC_CAP_MMC_ENH_STROBE))
1009                         slot_printf(slot, "eMMC:%s%s%s%s\n",
1010                             (host_caps & MMC_CAP_MMC_DDR52) ? " DDR52" : "",
1011                             (host_caps & MMC_CAP_MMC_HS200) ? " HS200" : "",
1012                             (host_caps & MMC_CAP_MMC_HS400) ? " HS400" : "",
1013                             ((host_caps &
1014                             (MMC_CAP_MMC_HS400 | MMC_CAP_MMC_ENH_STROBE)) ==
1015                             (MMC_CAP_MMC_HS400 | MMC_CAP_MMC_ENH_STROBE)) ?
1016                             " HS400ES" : "");
1017                 if (host_caps & (MMC_CAP_UHS_SDR12 | MMC_CAP_UHS_SDR25 |
1018                     MMC_CAP_UHS_SDR50 | MMC_CAP_UHS_SDR104))
1019                         slot_printf(slot, "UHS-I:%s%s%s%s%s\n",
1020                             (host_caps & MMC_CAP_UHS_SDR12) ? " SDR12" : "",
1021                             (host_caps & MMC_CAP_UHS_SDR25) ? " SDR25" : "",
1022                             (host_caps & MMC_CAP_UHS_SDR50) ? " SDR50" : "",
1023                             (host_caps & MMC_CAP_UHS_SDR104) ? " SDR104" : "",
1024                             (host_caps & MMC_CAP_UHS_DDR50) ? " DDR50" : "");
1025                 if (slot->opt & SDHCI_TUNING_SUPPORTED)
1026                         slot_printf(slot, "Re-tuning count %d secs, mode %d\n",
1027                             slot->retune_count, slot->retune_mode + 1);
1028                 sdhci_dumpregs(slot);
1029         }
1030
1031         slot->timeout = 10;
1032         SYSCTL_ADD_INT(device_get_sysctl_ctx(slot->bus),
1033             SYSCTL_CHILDREN(device_get_sysctl_tree(slot->bus)), OID_AUTO,
1034             "timeout", CTLFLAG_RW, &slot->timeout, 0,
1035             "Maximum timeout for SDHCI transfers (in secs)");
1036         TASK_INIT(&slot->card_task, 0, sdhci_card_task, slot);
1037         TIMEOUT_TASK_INIT(taskqueue_swi_giant, &slot->card_delayed_task, 0,
1038                 sdhci_card_task, slot);
1039         callout_init(&slot->card_poll_callout, 1);
1040         callout_init_mtx(&slot->timeout_callout, &slot->mtx, 0);
1041         callout_init_mtx(&slot->retune_callout, &slot->mtx, 0);
1042
1043         if ((slot->quirks & SDHCI_QUIRK_POLL_CARD_PRESENT) &&
1044             !(slot->opt & SDHCI_NON_REMOVABLE)) {
1045                 callout_reset(&slot->card_poll_callout,
1046                     SDHCI_CARD_PRESENT_TICKS, sdhci_card_poll, slot);
1047         }
1048
1049         sdhci_init(slot);
1050
1051         return (0);
1052 }
1053
1054 void
1055 sdhci_start_slot(struct sdhci_slot *slot)
1056 {
1057
1058         sdhci_card_task(slot, 0);
1059 }
1060
1061 int
1062 sdhci_cleanup_slot(struct sdhci_slot *slot)
1063 {
1064         device_t d;
1065
1066         callout_drain(&slot->timeout_callout);
1067         callout_drain(&slot->card_poll_callout);
1068         callout_drain(&slot->retune_callout);
1069         taskqueue_drain(taskqueue_swi_giant, &slot->card_task);
1070         taskqueue_drain_timeout(taskqueue_swi_giant, &slot->card_delayed_task);
1071
1072         SDHCI_LOCK(slot);
1073         d = slot->dev;
1074         slot->dev = NULL;
1075         SDHCI_UNLOCK(slot);
1076         if (d != NULL)
1077                 device_delete_child(slot->bus, d);
1078
1079         SDHCI_LOCK(slot);
1080         sdhci_reset(slot, SDHCI_RESET_ALL);
1081         SDHCI_UNLOCK(slot);
1082         bus_dmamap_unload(slot->dmatag, slot->dmamap);
1083         bus_dmamem_free(slot->dmatag, slot->dmamem, slot->dmamap);
1084         bus_dma_tag_destroy(slot->dmatag);
1085         if (slot->opt & SDHCI_TUNING_SUPPORTED) {
1086                 free(slot->tune_req, M_DEVBUF);
1087                 free(slot->tune_cmd, M_DEVBUF);
1088                 free(slot->tune_data, M_DEVBUF);
1089         }
1090
1091         SDHCI_LOCK_DESTROY(slot);
1092
1093         return (0);
1094 }
1095
1096 int
1097 sdhci_generic_suspend(struct sdhci_slot *slot)
1098 {
1099
1100         /*
1101          * We expect the MMC layer to issue initial tuning after resume.
1102          * Otherwise, we'd need to indicate re-tuning including circuit reset
1103          * being required at least for re-tuning modes 1 and 2 ourselves.
1104          */
1105         callout_drain(&slot->retune_callout);
1106         SDHCI_LOCK(slot);
1107         slot->opt &= ~SDHCI_TUNING_ENABLED;
1108         sdhci_reset(slot, SDHCI_RESET_ALL);
1109         SDHCI_UNLOCK(slot);
1110
1111         return (0);
1112 }
1113
1114 int
1115 sdhci_generic_resume(struct sdhci_slot *slot)
1116 {
1117
1118         SDHCI_LOCK(slot);
1119         sdhci_init(slot);
1120         SDHCI_UNLOCK(slot);
1121
1122         return (0);
1123 }
1124
1125 uint32_t
1126 sdhci_generic_min_freq(device_t brdev __unused, struct sdhci_slot *slot)
1127 {
1128
1129         if (slot->version >= SDHCI_SPEC_300)
1130                 return (slot->max_clk / SDHCI_300_MAX_DIVIDER);
1131         else
1132                 return (slot->max_clk / SDHCI_200_MAX_DIVIDER);
1133 }
1134
1135 bool
1136 sdhci_generic_get_card_present(device_t brdev __unused, struct sdhci_slot *slot)
1137 {
1138
1139         if (slot->opt & SDHCI_NON_REMOVABLE)
1140                 return true;
1141
1142         return (RD4(slot, SDHCI_PRESENT_STATE) & SDHCI_CARD_PRESENT);
1143 }
1144
1145 void
1146 sdhci_generic_set_uhs_timing(device_t brdev __unused, struct sdhci_slot *slot)
1147 {
1148         struct mmc_ios *ios;
1149         uint16_t hostctrl2;
1150
1151         if (slot->version < SDHCI_SPEC_300)
1152                 return;
1153
1154         SDHCI_ASSERT_LOCKED(slot);
1155         ios = &slot->host.ios;
1156         sdhci_set_clock(slot, 0);
1157         hostctrl2 = RD2(slot, SDHCI_HOST_CONTROL2);
1158         hostctrl2 &= ~SDHCI_CTRL2_UHS_MASK;
1159         if (ios->clock > SD_SDR50_MAX) {
1160                 if (ios->timing == bus_timing_mmc_hs400 ||
1161                     ios->timing == bus_timing_mmc_hs400es)
1162                         hostctrl2 |= SDHCI_CTRL2_MMC_HS400;
1163                 else
1164                         hostctrl2 |= SDHCI_CTRL2_UHS_SDR104;
1165         }
1166         else if (ios->clock > SD_SDR25_MAX)
1167                 hostctrl2 |= SDHCI_CTRL2_UHS_SDR50;
1168         else if (ios->clock > SD_SDR12_MAX) {
1169                 if (ios->timing == bus_timing_uhs_ddr50 ||
1170                     ios->timing == bus_timing_mmc_ddr52)
1171                         hostctrl2 |= SDHCI_CTRL2_UHS_DDR50;
1172                 else
1173                         hostctrl2 |= SDHCI_CTRL2_UHS_SDR25;
1174         } else if (ios->clock > SD_MMC_CARD_ID_FREQUENCY)
1175                 hostctrl2 |= SDHCI_CTRL2_UHS_SDR12;
1176         WR2(slot, SDHCI_HOST_CONTROL2, hostctrl2);
1177         sdhci_set_clock(slot, ios->clock);
1178 }
1179
1180 int
1181 sdhci_generic_update_ios(device_t brdev, device_t reqdev)
1182 {
1183         struct sdhci_slot *slot = device_get_ivars(reqdev);
1184         struct mmc_ios *ios = &slot->host.ios;
1185
1186         SDHCI_LOCK(slot);
1187         /* Do full reset on bus power down to clear from any state. */
1188         if (ios->power_mode == power_off) {
1189                 WR4(slot, SDHCI_SIGNAL_ENABLE, 0);
1190                 sdhci_init(slot);
1191         }
1192         /* Configure the bus. */
1193         sdhci_set_clock(slot, ios->clock);
1194         sdhci_set_power(slot, (ios->power_mode == power_off) ? 0 : ios->vdd);
1195         if (ios->bus_width == bus_width_8) {
1196                 slot->hostctrl |= SDHCI_CTRL_8BITBUS;
1197                 slot->hostctrl &= ~SDHCI_CTRL_4BITBUS;
1198         } else if (ios->bus_width == bus_width_4) {
1199                 slot->hostctrl &= ~SDHCI_CTRL_8BITBUS;
1200                 slot->hostctrl |= SDHCI_CTRL_4BITBUS;
1201         } else if (ios->bus_width == bus_width_1) {
1202                 slot->hostctrl &= ~SDHCI_CTRL_8BITBUS;
1203                 slot->hostctrl &= ~SDHCI_CTRL_4BITBUS;
1204         } else {
1205                 panic("Invalid bus width: %d", ios->bus_width);
1206         }
1207         if (ios->clock > SD_SDR12_MAX &&
1208             !(slot->quirks & SDHCI_QUIRK_DONT_SET_HISPD_BIT))
1209                 slot->hostctrl |= SDHCI_CTRL_HISPD;
1210         else
1211                 slot->hostctrl &= ~SDHCI_CTRL_HISPD;
1212         WR1(slot, SDHCI_HOST_CONTROL, slot->hostctrl);
1213         SDHCI_SET_UHS_TIMING(brdev, slot);
1214         /* Some controllers like reset after bus changes. */
1215         if (slot->quirks & SDHCI_QUIRK_RESET_ON_IOS)
1216                 sdhci_reset(slot, SDHCI_RESET_CMD | SDHCI_RESET_DATA);
1217
1218         SDHCI_UNLOCK(slot);
1219         return (0);
1220 }
1221
1222 int
1223 sdhci_generic_switch_vccq(device_t brdev __unused, device_t reqdev)
1224 {
1225         struct sdhci_slot *slot = device_get_ivars(reqdev);
1226         enum mmc_vccq vccq;
1227         int err;
1228         uint16_t hostctrl2;
1229
1230         if (slot->version < SDHCI_SPEC_300)
1231                 return (0);
1232
1233         err = 0;
1234         vccq = slot->host.ios.vccq;
1235         SDHCI_LOCK(slot);
1236         sdhci_set_clock(slot, 0);
1237         hostctrl2 = RD2(slot, SDHCI_HOST_CONTROL2);
1238         switch (vccq) {
1239         case vccq_330:
1240                 if (!(hostctrl2 & SDHCI_CTRL2_S18_ENABLE))
1241                         goto done;
1242                 hostctrl2 &= ~SDHCI_CTRL2_S18_ENABLE;
1243                 WR2(slot, SDHCI_HOST_CONTROL2, hostctrl2);
1244                 DELAY(5000);
1245                 hostctrl2 = RD2(slot, SDHCI_HOST_CONTROL2);
1246                 if (!(hostctrl2 & SDHCI_CTRL2_S18_ENABLE))
1247                         goto done;
1248                 err = EAGAIN;
1249                 break;
1250         case vccq_180:
1251                 if (!(slot->host.caps & MMC_CAP_SIGNALING_180)) {
1252                         err = EINVAL;
1253                         goto done;
1254                 }
1255                 if (hostctrl2 & SDHCI_CTRL2_S18_ENABLE)
1256                         goto done;
1257                 hostctrl2 |= SDHCI_CTRL2_S18_ENABLE;
1258                 WR2(slot, SDHCI_HOST_CONTROL2, hostctrl2);
1259                 DELAY(5000);
1260                 hostctrl2 = RD2(slot, SDHCI_HOST_CONTROL2);
1261                 if (hostctrl2 & SDHCI_CTRL2_S18_ENABLE)
1262                         goto done;
1263                 err = EAGAIN;
1264                 break;
1265         default:
1266                 slot_printf(slot,
1267                     "Attempt to set unsupported signaling voltage\n");
1268                 err = EINVAL;
1269                 break;
1270         }
1271 done:
1272         sdhci_set_clock(slot, slot->host.ios.clock);
1273         SDHCI_UNLOCK(slot);
1274         return (err);
1275 }
1276
1277 int
1278 sdhci_generic_tune(device_t brdev __unused, device_t reqdev, bool hs400)
1279 {
1280         struct sdhci_slot *slot = device_get_ivars(reqdev);
1281         struct mmc_ios *ios = &slot->host.ios;
1282         struct mmc_command *tune_cmd;
1283         struct mmc_data *tune_data;
1284         uint32_t opcode;
1285         int err;
1286
1287         if (!(slot->opt & SDHCI_TUNING_SUPPORTED))
1288                 return (0);
1289
1290         slot->retune_ticks = slot->retune_count * hz;
1291         opcode = MMC_SEND_TUNING_BLOCK;
1292         SDHCI_LOCK(slot);
1293         switch (ios->timing) {
1294         case bus_timing_mmc_hs400:
1295                 slot_printf(slot, "HS400 must be tuned in HS200 mode\n");
1296                 SDHCI_UNLOCK(slot);
1297                 return (EINVAL);
1298         case bus_timing_mmc_hs200:
1299                 /*
1300                  * In HS400 mode, controllers use the data strobe line to
1301                  * latch data from the devices so periodic re-tuning isn't
1302                  * expected to be required.
1303                  */
1304                 if (hs400)
1305                         slot->retune_ticks = 0;
1306                 opcode = MMC_SEND_TUNING_BLOCK_HS200;
1307                 break;
1308         case bus_timing_uhs_ddr50:
1309         case bus_timing_uhs_sdr104:
1310                 break;
1311         case bus_timing_uhs_sdr50:
1312                 if (slot->opt & SDHCI_SDR50_NEEDS_TUNING)
1313                         break;
1314                 /* FALLTHROUGH */
1315         default:
1316                 SDHCI_UNLOCK(slot);
1317                 return (0);
1318         }
1319
1320         tune_cmd = slot->tune_cmd;
1321         memset(tune_cmd, 0, sizeof(*tune_cmd));
1322         tune_cmd->opcode = opcode;
1323         tune_cmd->flags = MMC_RSP_R1 | MMC_CMD_ADTC;
1324         tune_data = tune_cmd->data = slot->tune_data;
1325         memset(tune_data, 0, sizeof(*tune_data));
1326         tune_data->len = (opcode == MMC_SEND_TUNING_BLOCK_HS200 &&
1327             ios->bus_width == bus_width_8) ? MMC_TUNING_LEN_HS200 :
1328             MMC_TUNING_LEN;
1329         tune_data->flags = MMC_DATA_READ;
1330         tune_data->mrq = tune_cmd->mrq = slot->tune_req;
1331
1332         slot->opt &= ~SDHCI_TUNING_ENABLED;
1333         err = sdhci_exec_tuning(slot, true);
1334         if (err == 0) {
1335                 slot->opt |= SDHCI_TUNING_ENABLED;
1336                 slot->intmask |= sdhci_tuning_intmask(slot);
1337                 WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask);
1338                 if (slot->retune_ticks) {
1339                         callout_reset(&slot->retune_callout, slot->retune_ticks,
1340                             sdhci_retune, slot);
1341                 }
1342         }
1343         SDHCI_UNLOCK(slot);
1344         return (err);
1345 }
1346
1347 int
1348 sdhci_generic_retune(device_t brdev __unused, device_t reqdev, bool reset)
1349 {
1350         struct sdhci_slot *slot = device_get_ivars(reqdev);
1351         int err;
1352
1353         if (!(slot->opt & SDHCI_TUNING_ENABLED))
1354                 return (0);
1355
1356         /* HS400 must be tuned in HS200 mode. */
1357         if (slot->host.ios.timing == bus_timing_mmc_hs400)
1358                 return (EINVAL);
1359
1360         SDHCI_LOCK(slot);
1361         err = sdhci_exec_tuning(slot, reset);
1362         /*
1363          * There are two ways sdhci_exec_tuning() can fail:
1364          * EBUSY should not actually happen when requests are only issued
1365          *       with the host properly acquired, and
1366          * EIO   re-tuning failed (but it did work initially).
1367          *
1368          * In both cases, we should retry at later point if periodic re-tuning
1369          * is enabled.  Note that due to slot->retune_req not being cleared in
1370          * these failure cases, the MMC layer should trigger another attempt at
1371          * re-tuning with the next request anyway, though.
1372          */
1373         if (slot->retune_ticks) {
1374                 callout_reset(&slot->retune_callout, slot->retune_ticks,
1375                     sdhci_retune, slot);
1376         }
1377         SDHCI_UNLOCK(slot);
1378         return (err);
1379 }
1380
1381 static int
1382 sdhci_exec_tuning(struct sdhci_slot *slot, bool reset)
1383 {
1384         struct mmc_request *tune_req;
1385         struct mmc_command *tune_cmd;
1386         int i;
1387         uint32_t intmask;
1388         uint16_t hostctrl2;
1389         u_char opt;
1390
1391         SDHCI_ASSERT_LOCKED(slot);
1392         if (slot->req != NULL)
1393                 return (EBUSY);
1394
1395         /* Tuning doesn't work with DMA enabled. */
1396         opt = slot->opt;
1397         slot->opt = opt & ~SDHCI_HAVE_DMA;
1398
1399         /*
1400          * Ensure that as documented, SDHCI_INT_DATA_AVAIL is the only
1401          * kind of interrupt we receive in response to a tuning request.
1402          */
1403         intmask = slot->intmask;
1404         slot->intmask = SDHCI_INT_DATA_AVAIL;
1405         WR4(slot, SDHCI_SIGNAL_ENABLE, SDHCI_INT_DATA_AVAIL);
1406
1407         hostctrl2 = RD2(slot, SDHCI_HOST_CONTROL2);
1408         if (reset)
1409                 hostctrl2 &= ~SDHCI_CTRL2_SAMPLING_CLOCK;
1410         else
1411                 hostctrl2 |= SDHCI_CTRL2_SAMPLING_CLOCK;
1412         WR2(slot, SDHCI_HOST_CONTROL2, hostctrl2 | SDHCI_CTRL2_EXEC_TUNING);
1413
1414         tune_req = slot->tune_req;
1415         tune_cmd = slot->tune_cmd;
1416         for (i = 0; i < MMC_TUNING_MAX; i++) {
1417                 memset(tune_req, 0, sizeof(*tune_req));
1418                 tune_req->cmd = tune_cmd;
1419                 tune_req->done = sdhci_req_wakeup;
1420                 tune_req->done_data = slot;
1421                 slot->req = tune_req;
1422                 slot->flags = 0;
1423                 sdhci_start(slot);
1424                 while (!(tune_req->flags & MMC_REQ_DONE))
1425                         msleep(tune_req, &slot->mtx, 0, "sdhciet", 0);
1426                 if (!(tune_req->flags & MMC_TUNE_DONE))
1427                         break;
1428                 hostctrl2 = RD2(slot, SDHCI_HOST_CONTROL2);
1429                 if (!(hostctrl2 & SDHCI_CTRL2_EXEC_TUNING))
1430                         break;
1431                 if (tune_cmd->opcode == MMC_SEND_TUNING_BLOCK)
1432                         DELAY(1000);
1433         }
1434
1435         slot->opt = opt;
1436         slot->intmask = intmask;
1437         WR4(slot, SDHCI_SIGNAL_ENABLE, intmask);
1438
1439         if ((hostctrl2 & (SDHCI_CTRL2_EXEC_TUNING |
1440             SDHCI_CTRL2_SAMPLING_CLOCK)) == SDHCI_CTRL2_SAMPLING_CLOCK) {
1441                 slot->retune_req = 0;
1442                 return (0);
1443         }
1444
1445         slot_printf(slot, "Tuning failed, using fixed sampling clock\n");
1446         WR2(slot, SDHCI_HOST_CONTROL2, hostctrl2 & ~(SDHCI_CTRL2_EXEC_TUNING |
1447             SDHCI_CTRL2_SAMPLING_CLOCK));
1448         sdhci_reset(slot, SDHCI_RESET_CMD | SDHCI_RESET_DATA);
1449         return (EIO);
1450 }
1451
1452 static void
1453 sdhci_retune(void *arg)
1454 {
1455         struct sdhci_slot *slot = arg;
1456
1457         slot->retune_req |= SDHCI_RETUNE_REQ_NEEDED;
1458 }
1459
1460 #ifdef MMCCAM
1461 static void
1462 sdhci_req_done(struct sdhci_slot *slot)
1463 {
1464         union ccb *ccb;
1465
1466         if (__predict_false(sdhci_debug > 1))
1467                 slot_printf(slot, "%s\n", __func__);
1468         if (slot->ccb != NULL && slot->curcmd != NULL) {
1469                 callout_stop(&slot->timeout_callout);
1470                 ccb = slot->ccb;
1471                 slot->ccb = NULL;
1472                 slot->curcmd = NULL;
1473
1474                 /* Tell CAM the request is finished */
1475                 struct ccb_mmcio *mmcio;
1476                 mmcio = &ccb->mmcio;
1477
1478                 ccb->ccb_h.status =
1479                         (mmcio->cmd.error == 0 ? CAM_REQ_CMP : CAM_REQ_CMP_ERR);
1480                 xpt_done(ccb);
1481         }
1482 }
1483 #else
1484 static void
1485 sdhci_req_done(struct sdhci_slot *slot)
1486 {
1487         struct mmc_request *req;
1488
1489         if (slot->req != NULL && slot->curcmd != NULL) {
1490                 callout_stop(&slot->timeout_callout);
1491                 req = slot->req;
1492                 slot->req = NULL;
1493                 slot->curcmd = NULL;
1494                 req->done(req);
1495         }
1496 }
1497 #endif
1498
1499 static void
1500 sdhci_req_wakeup(struct mmc_request *req)
1501 {
1502         struct sdhci_slot *slot;
1503
1504         slot = req->done_data;
1505         req->flags |= MMC_REQ_DONE;
1506         wakeup(req);
1507 }
1508
1509 static void
1510 sdhci_timeout(void *arg)
1511 {
1512         struct sdhci_slot *slot = arg;
1513
1514         if (slot->curcmd != NULL) {
1515                 slot_printf(slot, "Controller timeout\n");
1516                 sdhci_dumpregs(slot);
1517                 sdhci_reset(slot, SDHCI_RESET_CMD | SDHCI_RESET_DATA);
1518                 slot->curcmd->error = MMC_ERR_TIMEOUT;
1519                 sdhci_req_done(slot);
1520         } else {
1521                 slot_printf(slot, "Spurious timeout - no active command\n");
1522         }
1523 }
1524
1525 static void
1526 sdhci_set_transfer_mode(struct sdhci_slot *slot, struct mmc_data *data)
1527 {
1528         uint16_t mode;
1529
1530         if (data == NULL)
1531                 return;
1532
1533         mode = SDHCI_TRNS_BLK_CNT_EN;
1534         if (data->len > 512)
1535                 mode |= SDHCI_TRNS_MULTI;
1536         if (data->flags & MMC_DATA_READ)
1537                 mode |= SDHCI_TRNS_READ;
1538 #ifdef MMCCAM
1539         struct ccb_mmcio *mmcio;
1540         mmcio = &slot->ccb->mmcio;
1541         if (mmcio->stop.opcode == MMC_STOP_TRANSMISSION
1542             && !(slot->quirks & SDHCI_QUIRK_BROKEN_AUTO_STOP))
1543                 mode |= SDHCI_TRNS_ACMD12;
1544 #else
1545         if (slot->req->stop && !(slot->quirks & SDHCI_QUIRK_BROKEN_AUTO_STOP))
1546                 mode |= SDHCI_TRNS_ACMD12;
1547 #endif
1548         if (slot->flags & SDHCI_USE_DMA)
1549                 mode |= SDHCI_TRNS_DMA;
1550
1551         WR2(slot, SDHCI_TRANSFER_MODE, mode);
1552 }
1553
1554 static void
1555 sdhci_start_command(struct sdhci_slot *slot, struct mmc_command *cmd)
1556 {
1557         int flags, timeout;
1558         uint32_t mask;
1559
1560         slot->curcmd = cmd;
1561         slot->cmd_done = 0;
1562
1563         cmd->error = MMC_ERR_NONE;
1564
1565         /* This flags combination is not supported by controller. */
1566         if ((cmd->flags & MMC_RSP_136) && (cmd->flags & MMC_RSP_BUSY)) {
1567                 slot_printf(slot, "Unsupported response type!\n");
1568                 cmd->error = MMC_ERR_FAILED;
1569                 sdhci_req_done(slot);
1570                 return;
1571         }
1572
1573         /*
1574          * Do not issue command if there is no card, clock or power.
1575          * Controller will not detect timeout without clock active.
1576          */
1577         if (!SDHCI_GET_CARD_PRESENT(slot->bus, slot) ||
1578             slot->power == 0 ||
1579             slot->clock == 0) {
1580                 slot_printf(slot,
1581                             "Cannot issue a command (power=%d clock=%d)",
1582                             slot->power, slot->clock);
1583                 cmd->error = MMC_ERR_FAILED;
1584                 sdhci_req_done(slot);
1585                 return;
1586         }
1587         /* Always wait for free CMD bus. */
1588         mask = SDHCI_CMD_INHIBIT;
1589         /* Wait for free DAT if we have data or busy signal. */
1590         if (cmd->data != NULL || (cmd->flags & MMC_RSP_BUSY))
1591                 mask |= SDHCI_DAT_INHIBIT;
1592         /*
1593          * We shouldn't wait for DAT for stop commands or CMD19/CMD21.  Note
1594          * that these latter are also special in that SDHCI_CMD_DATA should
1595          * be set below but no actual data is ever read from the controller.
1596         */
1597 #ifdef MMCCAM
1598         if (cmd == &slot->ccb->mmcio.stop ||
1599 #else
1600         if (cmd == slot->req->stop ||
1601 #endif
1602             __predict_false(cmd->opcode == MMC_SEND_TUNING_BLOCK ||
1603             cmd->opcode == MMC_SEND_TUNING_BLOCK_HS200))
1604                 mask &= ~SDHCI_DAT_INHIBIT;
1605         /*
1606          *  Wait for bus no more then 250 ms.  Typically there will be no wait
1607          *  here at all, but when writing a crash dump we may be bypassing the
1608          *  host platform's interrupt handler, and in some cases that handler
1609          *  may be working around hardware quirks such as not respecting r1b
1610          *  busy indications.  In those cases, this wait-loop serves the purpose
1611          *  of waiting for the prior command and data transfers to be done, and
1612          *  SD cards are allowed to take up to 250ms for write and erase ops.
1613          *  (It's usually more like 20-30ms in the real world.)
1614          */
1615         timeout = 250;
1616         while (mask & RD4(slot, SDHCI_PRESENT_STATE)) {
1617                 if (timeout == 0) {
1618                         slot_printf(slot, "Controller never released "
1619                             "inhibit bit(s).\n");
1620                         sdhci_dumpregs(slot);
1621                         cmd->error = MMC_ERR_FAILED;
1622                         sdhci_req_done(slot);
1623                         return;
1624                 }
1625                 timeout--;
1626                 DELAY(1000);
1627         }
1628
1629         /* Prepare command flags. */
1630         if (!(cmd->flags & MMC_RSP_PRESENT))
1631                 flags = SDHCI_CMD_RESP_NONE;
1632         else if (cmd->flags & MMC_RSP_136)
1633                 flags = SDHCI_CMD_RESP_LONG;
1634         else if (cmd->flags & MMC_RSP_BUSY)
1635                 flags = SDHCI_CMD_RESP_SHORT_BUSY;
1636         else
1637                 flags = SDHCI_CMD_RESP_SHORT;
1638         if (cmd->flags & MMC_RSP_CRC)
1639                 flags |= SDHCI_CMD_CRC;
1640         if (cmd->flags & MMC_RSP_OPCODE)
1641                 flags |= SDHCI_CMD_INDEX;
1642         if (cmd->data != NULL)
1643                 flags |= SDHCI_CMD_DATA;
1644         if (cmd->opcode == MMC_STOP_TRANSMISSION)
1645                 flags |= SDHCI_CMD_TYPE_ABORT;
1646         /* Prepare data. */
1647         sdhci_start_data(slot, cmd->data);
1648         /*
1649          * Interrupt aggregation: To reduce total number of interrupts
1650          * group response interrupt with data interrupt when possible.
1651          * If there going to be data interrupt, mask response one.
1652          */
1653         if (slot->data_done == 0) {
1654                 WR4(slot, SDHCI_SIGNAL_ENABLE,
1655                     slot->intmask &= ~SDHCI_INT_RESPONSE);
1656         }
1657         /* Set command argument. */
1658         WR4(slot, SDHCI_ARGUMENT, cmd->arg);
1659         /* Set data transfer mode. */
1660         sdhci_set_transfer_mode(slot, cmd->data);
1661         if (__predict_false(sdhci_debug > 1))
1662                 slot_printf(slot, "Starting command!\n");
1663         /* Start command. */
1664         WR2(slot, SDHCI_COMMAND_FLAGS, (cmd->opcode << 8) | (flags & 0xff));
1665         /* Start timeout callout. */
1666         callout_reset(&slot->timeout_callout, slot->timeout * hz,
1667             sdhci_timeout, slot);
1668 }
1669
1670 static void
1671 sdhci_finish_command(struct sdhci_slot *slot)
1672 {
1673         int i;
1674         uint32_t val;
1675         uint8_t extra;
1676
1677         if (__predict_false(sdhci_debug > 1))
1678                 slot_printf(slot, "%s: called, err %d flags %d\n",
1679                     __func__, slot->curcmd->error, slot->curcmd->flags);
1680         slot->cmd_done = 1;
1681         /*
1682          * Interrupt aggregation: Restore command interrupt.
1683          * Main restore point for the case when command interrupt
1684          * happened first.
1685          */
1686         if (__predict_true(slot->curcmd->opcode != MMC_SEND_TUNING_BLOCK &&
1687             slot->curcmd->opcode != MMC_SEND_TUNING_BLOCK_HS200))
1688                 WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask |=
1689                     SDHCI_INT_RESPONSE);
1690         /* In case of error - reset host and return. */
1691         if (slot->curcmd->error) {
1692                 if (slot->curcmd->error == MMC_ERR_BADCRC)
1693                         slot->retune_req |= SDHCI_RETUNE_REQ_RESET;
1694                 sdhci_reset(slot, SDHCI_RESET_CMD);
1695                 sdhci_reset(slot, SDHCI_RESET_DATA);
1696                 sdhci_start(slot);
1697                 return;
1698         }
1699         /* If command has response - fetch it. */
1700         if (slot->curcmd->flags & MMC_RSP_PRESENT) {
1701                 if (slot->curcmd->flags & MMC_RSP_136) {
1702                         /* CRC is stripped so we need one byte shift. */
1703                         extra = 0;
1704                         for (i = 0; i < 4; i++) {
1705                                 val = RD4(slot, SDHCI_RESPONSE + i * 4);
1706                                 if (slot->quirks &
1707                                     SDHCI_QUIRK_DONT_SHIFT_RESPONSE)
1708                                         slot->curcmd->resp[3 - i] = val;
1709                                 else {
1710                                         slot->curcmd->resp[3 - i] =
1711                                             (val << 8) | extra;
1712                                         extra = val >> 24;
1713                                 }
1714                         }
1715                 } else
1716                         slot->curcmd->resp[0] = RD4(slot, SDHCI_RESPONSE);
1717         }
1718         if (__predict_false(sdhci_debug > 1))
1719                 printf("Resp: %02x %02x %02x %02x\n",
1720                     slot->curcmd->resp[0], slot->curcmd->resp[1],
1721                     slot->curcmd->resp[2], slot->curcmd->resp[3]);
1722
1723         /* If data ready - finish. */
1724         if (slot->data_done)
1725                 sdhci_start(slot);
1726 }
1727
1728 static void
1729 sdhci_start_data(struct sdhci_slot *slot, struct mmc_data *data)
1730 {
1731         uint32_t target_timeout, current_timeout;
1732         uint8_t div;
1733
1734         if (data == NULL && (slot->curcmd->flags & MMC_RSP_BUSY) == 0) {
1735                 slot->data_done = 1;
1736                 return;
1737         }
1738
1739         slot->data_done = 0;
1740
1741         /* Calculate and set data timeout.*/
1742         /* XXX: We should have this from mmc layer, now assume 1 sec. */
1743         if (slot->quirks & SDHCI_QUIRK_BROKEN_TIMEOUT_VAL) {
1744                 div = 0xE;
1745         } else {
1746                 target_timeout = 1000000;
1747                 div = 0;
1748                 current_timeout = (1 << 13) * 1000 / slot->timeout_clk;
1749                 while (current_timeout < target_timeout && div < 0xE) {
1750                         ++div;
1751                         current_timeout <<= 1;
1752                 }
1753                 /* Compensate for an off-by-one error in the CaFe chip.*/
1754                 if (div < 0xE &&
1755                     (slot->quirks & SDHCI_QUIRK_INCR_TIMEOUT_CONTROL)) {
1756                         ++div;
1757                 }
1758         }
1759         WR1(slot, SDHCI_TIMEOUT_CONTROL, div);
1760
1761         if (data == NULL)
1762                 return;
1763
1764         /* Use DMA if possible. */
1765         if ((slot->opt & SDHCI_HAVE_DMA))
1766                 slot->flags |= SDHCI_USE_DMA;
1767         /* If data is small, broken DMA may return zeroes instead of data, */
1768         if ((slot->quirks & SDHCI_QUIRK_BROKEN_TIMINGS) &&
1769             (data->len <= 512))
1770                 slot->flags &= ~SDHCI_USE_DMA;
1771         /* Some controllers require even block sizes. */
1772         if ((slot->quirks & SDHCI_QUIRK_32BIT_DMA_SIZE) &&
1773             ((data->len) & 0x3))
1774                 slot->flags &= ~SDHCI_USE_DMA;
1775         /* Load DMA buffer. */
1776         if (slot->flags & SDHCI_USE_DMA) {
1777                 if (data->flags & MMC_DATA_READ)
1778                         bus_dmamap_sync(slot->dmatag, slot->dmamap,
1779                             BUS_DMASYNC_PREREAD);
1780                 else {
1781                         memcpy(slot->dmamem, data->data,
1782                             (data->len < DMA_BLOCK_SIZE) ?
1783                             data->len : DMA_BLOCK_SIZE);
1784                         bus_dmamap_sync(slot->dmatag, slot->dmamap,
1785                             BUS_DMASYNC_PREWRITE);
1786                 }
1787                 WR4(slot, SDHCI_DMA_ADDRESS, slot->paddr);
1788                 /* Interrupt aggregation: Mask border interrupt
1789                  * for the last page and unmask else. */
1790                 if (data->len == DMA_BLOCK_SIZE)
1791                         slot->intmask &= ~SDHCI_INT_DMA_END;
1792                 else
1793                         slot->intmask |= SDHCI_INT_DMA_END;
1794                 WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask);
1795         }
1796         /* Current data offset for both PIO and DMA. */
1797         slot->offset = 0;
1798         /* Set block size and request IRQ on 4K border. */
1799         WR2(slot, SDHCI_BLOCK_SIZE, SDHCI_MAKE_BLKSZ(DMA_BOUNDARY,
1800             (data->len < 512) ? data->len : 512));
1801         /* Set block count. */
1802         WR2(slot, SDHCI_BLOCK_COUNT, (data->len + 511) / 512);
1803
1804         if (__predict_false(sdhci_debug > 1))
1805                 slot_printf(slot, "Block size: %02x, count %lu\n",
1806                     (unsigned int)SDHCI_MAKE_BLKSZ(DMA_BOUNDARY, (data->len < 512) ? data->len : 512),
1807                     (unsigned long)(data->len + 511) / 512);
1808 }
1809
1810 void
1811 sdhci_finish_data(struct sdhci_slot *slot)
1812 {
1813         struct mmc_data *data = slot->curcmd->data;
1814         size_t left;
1815
1816         /* Interrupt aggregation: Restore command interrupt.
1817          * Auxiliary restore point for the case when data interrupt
1818          * happened first. */
1819         if (!slot->cmd_done) {
1820                 WR4(slot, SDHCI_SIGNAL_ENABLE,
1821                     slot->intmask |= SDHCI_INT_RESPONSE);
1822         }
1823         /* Unload rest of data from DMA buffer. */
1824         if (!slot->data_done && (slot->flags & SDHCI_USE_DMA) &&
1825             slot->curcmd->data != NULL) {
1826                 if (data->flags & MMC_DATA_READ) {
1827                         left = data->len - slot->offset;
1828                         bus_dmamap_sync(slot->dmatag, slot->dmamap,
1829                             BUS_DMASYNC_POSTREAD);
1830                         memcpy((u_char*)data->data + slot->offset, slot->dmamem,
1831                             (left < DMA_BLOCK_SIZE) ? left : DMA_BLOCK_SIZE);
1832                 } else
1833                         bus_dmamap_sync(slot->dmatag, slot->dmamap,
1834                             BUS_DMASYNC_POSTWRITE);
1835         }
1836         slot->data_done = 1;
1837         /* If there was error - reset the host. */
1838         if (slot->curcmd->error) {
1839                 if (slot->curcmd->error == MMC_ERR_BADCRC)
1840                         slot->retune_req |= SDHCI_RETUNE_REQ_RESET;
1841                 sdhci_reset(slot, SDHCI_RESET_CMD);
1842                 sdhci_reset(slot, SDHCI_RESET_DATA);
1843                 sdhci_start(slot);
1844                 return;
1845         }
1846         /* If we already have command response - finish. */
1847         if (slot->cmd_done)
1848                 sdhci_start(slot);
1849 }
1850
1851 #ifdef MMCCAM
1852 static void
1853 sdhci_start(struct sdhci_slot *slot)
1854 {
1855         union ccb *ccb;
1856
1857         ccb = slot->ccb;
1858         if (ccb == NULL)
1859                 return;
1860
1861         struct ccb_mmcio *mmcio;
1862         mmcio = &ccb->mmcio;
1863
1864         if (!(slot->flags & CMD_STARTED)) {
1865                 slot->flags |= CMD_STARTED;
1866                 sdhci_start_command(slot, &mmcio->cmd);
1867                 return;
1868         }
1869
1870         /*
1871          * Old stack doesn't use this!
1872          * Enabling this code causes significant performance degradation
1873          * and IRQ storms on BBB, Wandboard behaves fine.
1874          * Not using this code does no harm...
1875         if (!(slot->flags & STOP_STARTED) && mmcio->stop.opcode != 0) {
1876                 slot->flags |= STOP_STARTED;
1877                 sdhci_start_command(slot, &mmcio->stop);
1878                 return;
1879         }
1880         */
1881         if (__predict_false(sdhci_debug > 1))
1882                 slot_printf(slot, "result: %d\n", mmcio->cmd.error);
1883         if (mmcio->cmd.error == 0 &&
1884             (slot->quirks & SDHCI_QUIRK_RESET_AFTER_REQUEST)) {
1885                 sdhci_reset(slot, SDHCI_RESET_CMD);
1886                 sdhci_reset(slot, SDHCI_RESET_DATA);
1887         }
1888
1889         sdhci_req_done(slot);
1890 }
1891 #else
1892 static void
1893 sdhci_start(struct sdhci_slot *slot)
1894 {
1895         struct mmc_request *req;
1896
1897         req = slot->req;
1898         if (req == NULL)
1899                 return;
1900
1901         if (!(slot->flags & CMD_STARTED)) {
1902                 slot->flags |= CMD_STARTED;
1903                 sdhci_start_command(slot, req->cmd);
1904                 return;
1905         }
1906         if ((slot->quirks & SDHCI_QUIRK_BROKEN_AUTO_STOP) &&
1907             !(slot->flags & STOP_STARTED) && req->stop) {
1908                 slot->flags |= STOP_STARTED;
1909                 sdhci_start_command(slot, req->stop);
1910                 return;
1911         }
1912         if (__predict_false(sdhci_debug > 1))
1913                 slot_printf(slot, "result: %d\n", req->cmd->error);
1914         if (!req->cmd->error &&
1915             ((slot->curcmd == req->stop &&
1916              (slot->quirks & SDHCI_QUIRK_BROKEN_AUTO_STOP)) ||
1917              (slot->quirks & SDHCI_QUIRK_RESET_AFTER_REQUEST))) {
1918                 sdhci_reset(slot, SDHCI_RESET_CMD);
1919                 sdhci_reset(slot, SDHCI_RESET_DATA);
1920         }
1921
1922         sdhci_req_done(slot);
1923 }
1924 #endif
1925
1926 int
1927 sdhci_generic_request(device_t brdev __unused, device_t reqdev,
1928     struct mmc_request *req)
1929 {
1930         struct sdhci_slot *slot = device_get_ivars(reqdev);
1931
1932         SDHCI_LOCK(slot);
1933         if (slot->req != NULL) {
1934                 SDHCI_UNLOCK(slot);
1935                 return (EBUSY);
1936         }
1937         if (__predict_false(sdhci_debug > 1)) {
1938                 slot_printf(slot,
1939                     "CMD%u arg %#x flags %#x dlen %u dflags %#x\n",
1940                     req->cmd->opcode, req->cmd->arg, req->cmd->flags,
1941                     (req->cmd->data)?(u_int)req->cmd->data->len:0,
1942                     (req->cmd->data)?req->cmd->data->flags:0);
1943         }
1944         slot->req = req;
1945         slot->flags = 0;
1946         sdhci_start(slot);
1947         SDHCI_UNLOCK(slot);
1948         if (dumping) {
1949                 while (slot->req != NULL) {
1950                         sdhci_generic_intr(slot);
1951                         DELAY(10);
1952                 }
1953         }
1954         return (0);
1955 }
1956
1957 int
1958 sdhci_generic_get_ro(device_t brdev __unused, device_t reqdev)
1959 {
1960         struct sdhci_slot *slot = device_get_ivars(reqdev);
1961         uint32_t val;
1962
1963         SDHCI_LOCK(slot);
1964         val = RD4(slot, SDHCI_PRESENT_STATE);
1965         SDHCI_UNLOCK(slot);
1966         return (!(val & SDHCI_WRITE_PROTECT));
1967 }
1968
1969 int
1970 sdhci_generic_acquire_host(device_t brdev __unused, device_t reqdev)
1971 {
1972         struct sdhci_slot *slot = device_get_ivars(reqdev);
1973         int err = 0;
1974
1975         SDHCI_LOCK(slot);
1976         while (slot->bus_busy)
1977                 msleep(slot, &slot->mtx, 0, "sdhciah", 0);
1978         slot->bus_busy++;
1979         /* Activate led. */
1980         WR1(slot, SDHCI_HOST_CONTROL, slot->hostctrl |= SDHCI_CTRL_LED);
1981         SDHCI_UNLOCK(slot);
1982         return (err);
1983 }
1984
1985 int
1986 sdhci_generic_release_host(device_t brdev __unused, device_t reqdev)
1987 {
1988         struct sdhci_slot *slot = device_get_ivars(reqdev);
1989
1990         SDHCI_LOCK(slot);
1991         /* Deactivate led. */
1992         WR1(slot, SDHCI_HOST_CONTROL, slot->hostctrl &= ~SDHCI_CTRL_LED);
1993         slot->bus_busy--;
1994         SDHCI_UNLOCK(slot);
1995         wakeup(slot);
1996         return (0);
1997 }
1998
1999 static void
2000 sdhci_cmd_irq(struct sdhci_slot *slot, uint32_t intmask)
2001 {
2002
2003         if (!slot->curcmd) {
2004                 slot_printf(slot, "Got command interrupt 0x%08x, but "
2005                     "there is no active command.\n", intmask);
2006                 sdhci_dumpregs(slot);
2007                 return;
2008         }
2009         if (intmask & SDHCI_INT_TIMEOUT)
2010                 slot->curcmd->error = MMC_ERR_TIMEOUT;
2011         else if (intmask & SDHCI_INT_CRC)
2012                 slot->curcmd->error = MMC_ERR_BADCRC;
2013         else if (intmask & (SDHCI_INT_END_BIT | SDHCI_INT_INDEX))
2014                 slot->curcmd->error = MMC_ERR_FIFO;
2015
2016         sdhci_finish_command(slot);
2017 }
2018
2019 static void
2020 sdhci_data_irq(struct sdhci_slot *slot, uint32_t intmask)
2021 {
2022         struct mmc_data *data;
2023         size_t left;
2024
2025         if (!slot->curcmd) {
2026                 slot_printf(slot, "Got data interrupt 0x%08x, but "
2027                     "there is no active command.\n", intmask);
2028                 sdhci_dumpregs(slot);
2029                 return;
2030         }
2031         if (slot->curcmd->data == NULL &&
2032             (slot->curcmd->flags & MMC_RSP_BUSY) == 0) {
2033                 slot_printf(slot, "Got data interrupt 0x%08x, but "
2034                     "there is no active data operation.\n",
2035                     intmask);
2036                 sdhci_dumpregs(slot);
2037                 return;
2038         }
2039         if (intmask & SDHCI_INT_DATA_TIMEOUT)
2040                 slot->curcmd->error = MMC_ERR_TIMEOUT;
2041         else if (intmask & (SDHCI_INT_DATA_CRC | SDHCI_INT_DATA_END_BIT))
2042                 slot->curcmd->error = MMC_ERR_BADCRC;
2043         if (slot->curcmd->data == NULL &&
2044             (intmask & (SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL |
2045             SDHCI_INT_DMA_END))) {
2046                 slot_printf(slot, "Got data interrupt 0x%08x, but "
2047                     "there is busy-only command.\n", intmask);
2048                 sdhci_dumpregs(slot);
2049                 slot->curcmd->error = MMC_ERR_INVALID;
2050         }
2051         if (slot->curcmd->error) {
2052                 /* No need to continue after any error. */
2053                 goto done;
2054         }
2055
2056         /* Handle tuning completion interrupt. */
2057         if (__predict_false((intmask & SDHCI_INT_DATA_AVAIL) &&
2058             (slot->curcmd->opcode == MMC_SEND_TUNING_BLOCK ||
2059             slot->curcmd->opcode == MMC_SEND_TUNING_BLOCK_HS200))) {
2060                 slot->req->flags |= MMC_TUNE_DONE;
2061                 sdhci_finish_command(slot);
2062                 sdhci_finish_data(slot);
2063                 return;
2064         }
2065         /* Handle PIO interrupt. */
2066         if (intmask & (SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL)) {
2067                 if ((slot->opt & SDHCI_PLATFORM_TRANSFER) &&
2068                     SDHCI_PLATFORM_WILL_HANDLE(slot->bus, slot)) {
2069                         SDHCI_PLATFORM_START_TRANSFER(slot->bus, slot,
2070                             &intmask);
2071                         slot->flags |= PLATFORM_DATA_STARTED;
2072                 } else
2073                         sdhci_transfer_pio(slot);
2074         }
2075         /* Handle DMA border. */
2076         if (intmask & SDHCI_INT_DMA_END) {
2077                 data = slot->curcmd->data;
2078
2079                 /* Unload DMA buffer ... */
2080                 left = data->len - slot->offset;
2081                 if (data->flags & MMC_DATA_READ) {
2082                         bus_dmamap_sync(slot->dmatag, slot->dmamap,
2083                             BUS_DMASYNC_POSTREAD);
2084                         memcpy((u_char*)data->data + slot->offset, slot->dmamem,
2085                             (left < DMA_BLOCK_SIZE) ? left : DMA_BLOCK_SIZE);
2086                 } else {
2087                         bus_dmamap_sync(slot->dmatag, slot->dmamap,
2088                             BUS_DMASYNC_POSTWRITE);
2089                 }
2090                 /* ... and reload it again. */
2091                 slot->offset += DMA_BLOCK_SIZE;
2092                 left = data->len - slot->offset;
2093                 if (data->flags & MMC_DATA_READ) {
2094                         bus_dmamap_sync(slot->dmatag, slot->dmamap,
2095                             BUS_DMASYNC_PREREAD);
2096                 } else {
2097                         memcpy(slot->dmamem, (u_char*)data->data + slot->offset,
2098                             (left < DMA_BLOCK_SIZE)? left : DMA_BLOCK_SIZE);
2099                         bus_dmamap_sync(slot->dmatag, slot->dmamap,
2100                             BUS_DMASYNC_PREWRITE);
2101                 }
2102                 /* Interrupt aggregation: Mask border interrupt
2103                  * for the last page. */
2104                 if (left == DMA_BLOCK_SIZE) {
2105                         slot->intmask &= ~SDHCI_INT_DMA_END;
2106                         WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask);
2107                 }
2108                 /* Restart DMA. */
2109                 WR4(slot, SDHCI_DMA_ADDRESS, slot->paddr);
2110         }
2111         /* We have got all data. */
2112         if (intmask & SDHCI_INT_DATA_END) {
2113                 if (slot->flags & PLATFORM_DATA_STARTED) {
2114                         slot->flags &= ~PLATFORM_DATA_STARTED;
2115                         SDHCI_PLATFORM_FINISH_TRANSFER(slot->bus, slot);
2116                 } else
2117                         sdhci_finish_data(slot);
2118         }
2119 done:
2120         if (slot->curcmd != NULL && slot->curcmd->error != 0) {
2121                 if (slot->flags & PLATFORM_DATA_STARTED) {
2122                         slot->flags &= ~PLATFORM_DATA_STARTED;
2123                         SDHCI_PLATFORM_FINISH_TRANSFER(slot->bus, slot);
2124                 } else
2125                         sdhci_finish_data(slot);
2126         }
2127 }
2128
2129 static void
2130 sdhci_acmd_irq(struct sdhci_slot *slot)
2131 {
2132         uint16_t err;
2133
2134         err = RD4(slot, SDHCI_ACMD12_ERR);
2135         if (!slot->curcmd) {
2136                 slot_printf(slot, "Got AutoCMD12 error 0x%04x, but "
2137                     "there is no active command.\n", err);
2138                 sdhci_dumpregs(slot);
2139                 return;
2140         }
2141         slot_printf(slot, "Got AutoCMD12 error 0x%04x\n", err);
2142         sdhci_reset(slot, SDHCI_RESET_CMD);
2143 }
2144
2145 void
2146 sdhci_generic_intr(struct sdhci_slot *slot)
2147 {
2148         uint32_t intmask, present;
2149
2150         SDHCI_LOCK(slot);
2151         /* Read slot interrupt status. */
2152         intmask = RD4(slot, SDHCI_INT_STATUS);
2153         if (intmask == 0 || intmask == 0xffffffff) {
2154                 SDHCI_UNLOCK(slot);
2155                 return;
2156         }
2157         if (__predict_false(sdhci_debug > 2))
2158                 slot_printf(slot, "Interrupt %#x\n", intmask);
2159
2160         /* Handle tuning error interrupt. */
2161         if (__predict_false(intmask & SDHCI_INT_TUNEERR)) {
2162                 slot_printf(slot, "Tuning error indicated\n");
2163                 slot->retune_req |= SDHCI_RETUNE_REQ_RESET;
2164                 if (slot->curcmd) {
2165                         slot->curcmd->error = MMC_ERR_BADCRC;
2166                         sdhci_finish_command(slot);
2167                 }
2168         }
2169         /* Handle re-tuning interrupt. */
2170         if (__predict_false(intmask & SDHCI_INT_RETUNE))
2171                 slot->retune_req |= SDHCI_RETUNE_REQ_NEEDED;
2172         /* Handle card presence interrupts. */
2173         if (intmask & (SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE)) {
2174                 present = (intmask & SDHCI_INT_CARD_INSERT) != 0;
2175                 slot->intmask &=
2176                     ~(SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE);
2177                 slot->intmask |= present ? SDHCI_INT_CARD_REMOVE :
2178                     SDHCI_INT_CARD_INSERT;
2179                 WR4(slot, SDHCI_INT_ENABLE, slot->intmask);
2180                 WR4(slot, SDHCI_SIGNAL_ENABLE, slot->intmask);
2181                 WR4(slot, SDHCI_INT_STATUS, intmask &
2182                     (SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE));
2183                 sdhci_handle_card_present_locked(slot, present);
2184         }
2185         /* Handle command interrupts. */
2186         if (intmask & SDHCI_INT_CMD_MASK) {
2187                 WR4(slot, SDHCI_INT_STATUS, intmask & SDHCI_INT_CMD_MASK);
2188                 sdhci_cmd_irq(slot, intmask & SDHCI_INT_CMD_MASK);
2189         }
2190         /* Handle data interrupts. */
2191         if (intmask & SDHCI_INT_DATA_MASK) {
2192                 WR4(slot, SDHCI_INT_STATUS, intmask & SDHCI_INT_DATA_MASK);
2193                 /* Don't call data_irq in case of errored command. */
2194                 if ((intmask & SDHCI_INT_CMD_ERROR_MASK) == 0)
2195                         sdhci_data_irq(slot, intmask & SDHCI_INT_DATA_MASK);
2196         }
2197         /* Handle AutoCMD12 error interrupt. */
2198         if (intmask & SDHCI_INT_ACMD12ERR) {
2199                 WR4(slot, SDHCI_INT_STATUS, SDHCI_INT_ACMD12ERR);
2200                 sdhci_acmd_irq(slot);
2201         }
2202         /* Handle bus power interrupt. */
2203         if (intmask & SDHCI_INT_BUS_POWER) {
2204                 WR4(slot, SDHCI_INT_STATUS, SDHCI_INT_BUS_POWER);
2205                 slot_printf(slot, "Card is consuming too much power!\n");
2206         }
2207         intmask &= ~(SDHCI_INT_ERROR | SDHCI_INT_TUNEERR | SDHCI_INT_RETUNE |
2208             SDHCI_INT_CARD_INSERT | SDHCI_INT_CARD_REMOVE | SDHCI_INT_CMD_MASK |
2209             SDHCI_INT_DATA_MASK | SDHCI_INT_ACMD12ERR | SDHCI_INT_BUS_POWER);
2210         /* The rest is unknown. */
2211         if (intmask) {
2212                 WR4(slot, SDHCI_INT_STATUS, intmask);
2213                 slot_printf(slot, "Unexpected interrupt 0x%08x.\n",
2214                     intmask);
2215                 sdhci_dumpregs(slot);
2216         }
2217
2218         SDHCI_UNLOCK(slot);
2219 }
2220
2221 int
2222 sdhci_generic_read_ivar(device_t bus, device_t child, int which,
2223     uintptr_t *result)
2224 {
2225         struct sdhci_slot *slot = device_get_ivars(child);
2226
2227         switch (which) {
2228         default:
2229                 return (EINVAL);
2230         case MMCBR_IVAR_BUS_MODE:
2231                 *result = slot->host.ios.bus_mode;
2232                 break;
2233         case MMCBR_IVAR_BUS_WIDTH:
2234                 *result = slot->host.ios.bus_width;
2235                 break;
2236         case MMCBR_IVAR_CHIP_SELECT:
2237                 *result = slot->host.ios.chip_select;
2238                 break;
2239         case MMCBR_IVAR_CLOCK:
2240                 *result = slot->host.ios.clock;
2241                 break;
2242         case MMCBR_IVAR_F_MIN:
2243                 *result = slot->host.f_min;
2244                 break;
2245         case MMCBR_IVAR_F_MAX:
2246                 *result = slot->host.f_max;
2247                 break;
2248         case MMCBR_IVAR_HOST_OCR:
2249                 *result = slot->host.host_ocr;
2250                 break;
2251         case MMCBR_IVAR_MODE:
2252                 *result = slot->host.mode;
2253                 break;
2254         case MMCBR_IVAR_OCR:
2255                 *result = slot->host.ocr;
2256                 break;
2257         case MMCBR_IVAR_POWER_MODE:
2258                 *result = slot->host.ios.power_mode;
2259                 break;
2260         case MMCBR_IVAR_VDD:
2261                 *result = slot->host.ios.vdd;
2262                 break;
2263         case MMCBR_IVAR_RETUNE_REQ:
2264                 if (slot->opt & SDHCI_TUNING_ENABLED) {
2265                         if (slot->retune_req & SDHCI_RETUNE_REQ_RESET) {
2266                                 *result = retune_req_reset;
2267                                 break;
2268                         }
2269                         if (slot->retune_req & SDHCI_RETUNE_REQ_NEEDED) {
2270                                 *result = retune_req_normal;
2271                                 break;
2272                         }
2273                 }
2274                 *result = retune_req_none;
2275                 break;
2276         case MMCBR_IVAR_VCCQ:
2277                 *result = slot->host.ios.vccq;
2278                 break;
2279         case MMCBR_IVAR_CAPS:
2280                 *result = slot->host.caps;
2281                 break;
2282         case MMCBR_IVAR_TIMING:
2283                 *result = slot->host.ios.timing;
2284                 break;
2285         case MMCBR_IVAR_MAX_DATA:
2286                 /*
2287                  * Re-tuning modes 1 and 2 restrict the maximum data length
2288                  * per read/write command to 4 MiB.
2289                  */
2290                 if (slot->opt & SDHCI_TUNING_ENABLED &&
2291                     (slot->retune_mode == SDHCI_RETUNE_MODE_1 ||
2292                     slot->retune_mode == SDHCI_RETUNE_MODE_2)) {
2293                         *result = 4 * 1024 * 1024 / MMC_SECTOR_SIZE;
2294                         break;
2295                 }
2296                 *result = 65535;
2297                 break;
2298         case MMCBR_IVAR_MAX_BUSY_TIMEOUT:
2299                 /*
2300                  * Currently, sdhci_start_data() hardcodes 1 s for all CMDs.
2301                  */
2302                 *result = 1000000;
2303                 break;
2304         }
2305         return (0);
2306 }
2307
2308 int
2309 sdhci_generic_write_ivar(device_t bus, device_t child, int which,
2310     uintptr_t value)
2311 {
2312         struct sdhci_slot *slot = device_get_ivars(child);
2313         uint32_t clock, max_clock;
2314         int i;
2315
2316         if (sdhci_debug > 1)
2317                 slot_printf(slot, "%s: var=%d\n", __func__, which);
2318         switch (which) {
2319         default:
2320                 return (EINVAL);
2321         case MMCBR_IVAR_BUS_MODE:
2322                 slot->host.ios.bus_mode = value;
2323                 break;
2324         case MMCBR_IVAR_BUS_WIDTH:
2325                 slot->host.ios.bus_width = value;
2326                 break;
2327         case MMCBR_IVAR_CHIP_SELECT:
2328                 slot->host.ios.chip_select = value;
2329                 break;
2330         case MMCBR_IVAR_CLOCK:
2331                 if (value > 0) {
2332                         max_clock = slot->max_clk;
2333                         clock = max_clock;
2334
2335                         if (slot->version < SDHCI_SPEC_300) {
2336                                 for (i = 0; i < SDHCI_200_MAX_DIVIDER;
2337                                     i <<= 1) {
2338                                         if (clock <= value)
2339                                                 break;
2340                                         clock >>= 1;
2341                                 }
2342                         } else {
2343                                 for (i = 0; i < SDHCI_300_MAX_DIVIDER;
2344                                     i += 2) {
2345                                         if (clock <= value)
2346                                                 break;
2347                                         clock = max_clock / (i + 2);
2348                                 }
2349                         }
2350
2351                         slot->host.ios.clock = clock;
2352                 } else
2353                         slot->host.ios.clock = 0;
2354                 break;
2355         case MMCBR_IVAR_MODE:
2356                 slot->host.mode = value;
2357                 break;
2358         case MMCBR_IVAR_OCR:
2359                 slot->host.ocr = value;
2360                 break;
2361         case MMCBR_IVAR_POWER_MODE:
2362                 slot->host.ios.power_mode = value;
2363                 break;
2364         case MMCBR_IVAR_VDD:
2365                 slot->host.ios.vdd = value;
2366                 break;
2367         case MMCBR_IVAR_VCCQ:
2368                 slot->host.ios.vccq = value;
2369                 break;
2370         case MMCBR_IVAR_TIMING:
2371                 slot->host.ios.timing = value;
2372                 break;
2373         case MMCBR_IVAR_CAPS:
2374         case MMCBR_IVAR_HOST_OCR:
2375         case MMCBR_IVAR_F_MIN:
2376         case MMCBR_IVAR_F_MAX:
2377         case MMCBR_IVAR_MAX_DATA:
2378         case MMCBR_IVAR_RETUNE_REQ:
2379                 return (EINVAL);
2380         }
2381         return (0);
2382 }
2383
2384 #ifdef MMCCAM
2385 void
2386 sdhci_cam_start_slot(struct sdhci_slot *slot)
2387 {
2388         if ((slot->devq = cam_simq_alloc(1)) == NULL) {
2389                 goto fail;
2390         }
2391
2392         mtx_init(&slot->sim_mtx, "sdhcisim", NULL, MTX_DEF);
2393         slot->sim = cam_sim_alloc(sdhci_cam_action, sdhci_cam_poll,
2394                                   "sdhci_slot", slot, device_get_unit(slot->bus),
2395                                   &slot->sim_mtx, 1, 1, slot->devq);
2396
2397         if (slot->sim == NULL) {
2398                 cam_simq_free(slot->devq);
2399                 slot_printf(slot, "cannot allocate CAM SIM\n");
2400                 goto fail;
2401         }
2402
2403         mtx_lock(&slot->sim_mtx);
2404         if (xpt_bus_register(slot->sim, slot->bus, 0) != 0) {
2405                 slot_printf(slot,
2406                               "cannot register SCSI pass-through bus\n");
2407                 cam_sim_free(slot->sim, FALSE);
2408                 cam_simq_free(slot->devq);
2409                 mtx_unlock(&slot->sim_mtx);
2410                 goto fail;
2411         }
2412
2413         mtx_unlock(&slot->sim_mtx);
2414         /* End CAM-specific init */
2415         slot->card_present = 0;
2416         sdhci_card_task(slot, 0);
2417         return;
2418
2419 fail:
2420         if (slot->sim != NULL) {
2421                 mtx_lock(&slot->sim_mtx);
2422                 xpt_bus_deregister(cam_sim_path(slot->sim));
2423                 cam_sim_free(slot->sim, FALSE);
2424                 mtx_unlock(&slot->sim_mtx);
2425         }
2426
2427         if (slot->devq != NULL)
2428                 cam_simq_free(slot->devq);
2429 }
2430
2431 static void
2432 sdhci_cam_handle_mmcio(struct cam_sim *sim, union ccb *ccb)
2433 {
2434         struct sdhci_slot *slot;
2435
2436         slot = cam_sim_softc(sim);
2437
2438         sdhci_cam_request(slot, ccb);
2439 }
2440
2441 void
2442 sdhci_cam_action(struct cam_sim *sim, union ccb *ccb)
2443 {
2444         struct sdhci_slot *slot;
2445
2446         slot = cam_sim_softc(sim);
2447         if (slot == NULL) {
2448                 ccb->ccb_h.status = CAM_SEL_TIMEOUT;
2449                 xpt_done(ccb);
2450                 return;
2451         }
2452
2453         mtx_assert(&slot->sim_mtx, MA_OWNED);
2454
2455         switch (ccb->ccb_h.func_code) {
2456         case XPT_PATH_INQ:
2457         {
2458                 struct ccb_pathinq *cpi;
2459
2460                 cpi = &ccb->cpi;
2461                 cpi->version_num = 1;
2462                 cpi->hba_inquiry = 0;
2463                 cpi->target_sprt = 0;
2464                 cpi->hba_misc = PIM_NOBUSRESET | PIM_SEQSCAN;
2465                 cpi->hba_eng_cnt = 0;
2466                 cpi->max_target = 0;
2467                 cpi->max_lun = 0;
2468                 cpi->initiator_id = 1;
2469                 cpi->maxio = MAXPHYS;
2470                 strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2471                 strncpy(cpi->hba_vid, "Deglitch Networks", HBA_IDLEN);
2472                 strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2473                 cpi->unit_number = cam_sim_unit(sim);
2474                 cpi->bus_id = cam_sim_bus(sim);
2475                 cpi->base_transfer_speed = 100; /* XXX WTF? */
2476                 cpi->protocol = PROTO_MMCSD;
2477                 cpi->protocol_version = SCSI_REV_0;
2478                 cpi->transport = XPORT_MMCSD;
2479                 cpi->transport_version = 0;
2480
2481                 cpi->ccb_h.status = CAM_REQ_CMP;
2482                 break;
2483         }
2484         case XPT_GET_TRAN_SETTINGS:
2485         {
2486                 struct ccb_trans_settings *cts = &ccb->cts;
2487
2488                 if (sdhci_debug > 1)
2489                         slot_printf(slot, "Got XPT_GET_TRAN_SETTINGS\n");
2490
2491                 cts->protocol = PROTO_MMCSD;
2492                 cts->protocol_version = 1;
2493                 cts->transport = XPORT_MMCSD;
2494                 cts->transport_version = 1;
2495                 cts->xport_specific.valid = 0;
2496                 cts->proto_specific.mmc.host_ocr = slot->host.host_ocr;
2497                 cts->proto_specific.mmc.host_f_min = slot->host.f_min;
2498                 cts->proto_specific.mmc.host_f_max = slot->host.f_max;
2499                 cts->proto_specific.mmc.host_caps = slot->host.caps;
2500                 memcpy(&cts->proto_specific.mmc.ios, &slot->host.ios, sizeof(struct mmc_ios));
2501                 ccb->ccb_h.status = CAM_REQ_CMP;
2502                 break;
2503         }
2504         case XPT_SET_TRAN_SETTINGS:
2505         {
2506                 if (sdhci_debug > 1)
2507                         slot_printf(slot, "Got XPT_SET_TRAN_SETTINGS\n");
2508                 sdhci_cam_settran_settings(slot, ccb);
2509                 ccb->ccb_h.status = CAM_REQ_CMP;
2510                 break;
2511         }
2512         case XPT_RESET_BUS:
2513                 if (sdhci_debug > 1)
2514                         slot_printf(slot, "Got XPT_RESET_BUS, ACK it...\n");
2515                 ccb->ccb_h.status = CAM_REQ_CMP;
2516                 break;
2517         case XPT_MMC_IO:
2518                 /*
2519                  * Here is the HW-dependent part of
2520                  * sending the command to the underlying h/w
2521                  * At some point in the future an interrupt comes.
2522                  * Then the request will be marked as completed.
2523                  */
2524                 if (__predict_false(sdhci_debug > 1))
2525                         slot_printf(slot, "Got XPT_MMC_IO\n");
2526                 ccb->ccb_h.status = CAM_REQ_INPROG;
2527
2528                 sdhci_cam_handle_mmcio(sim, ccb);
2529                 return;
2530                 /* NOTREACHED */
2531                 break;
2532         default:
2533                 ccb->ccb_h.status = CAM_REQ_INVALID;
2534                 break;
2535         }
2536         xpt_done(ccb);
2537         return;
2538 }
2539
2540 void
2541 sdhci_cam_poll(struct cam_sim *sim)
2542 {
2543         return;
2544 }
2545
2546 int sdhci_cam_get_possible_host_clock(struct sdhci_slot *slot, int proposed_clock) {
2547         int max_clock, clock, i;
2548
2549         if (proposed_clock == 0)
2550                 return 0;
2551         max_clock = slot->max_clk;
2552         clock = max_clock;
2553
2554         if (slot->version < SDHCI_SPEC_300) {
2555                 for (i = 0; i < SDHCI_200_MAX_DIVIDER;
2556                      i <<= 1) {
2557                         if (clock <= proposed_clock)
2558                                 break;
2559                         clock >>= 1;
2560                 }
2561         } else {
2562                 for (i = 0; i < SDHCI_300_MAX_DIVIDER;
2563                      i += 2) {
2564                         if (clock <= proposed_clock)
2565                                 break;
2566                         clock = max_clock / (i + 2);
2567                 }
2568         }
2569         return clock;
2570 }
2571
2572 int
2573 sdhci_cam_settran_settings(struct sdhci_slot *slot, union ccb *ccb)
2574 {
2575         struct mmc_ios *ios;
2576         struct mmc_ios *new_ios;
2577         struct ccb_trans_settings_mmc *cts;
2578
2579         ios = &slot->host.ios;
2580
2581         cts = &ccb->cts.proto_specific.mmc;
2582         new_ios = &cts->ios;
2583
2584         /* Update only requested fields */
2585         if (cts->ios_valid & MMC_CLK) {
2586                 ios->clock = sdhci_cam_get_possible_host_clock(slot, new_ios->clock);
2587                 slot_printf(slot, "Clock => %d\n", ios->clock);
2588         }
2589         if (cts->ios_valid & MMC_VDD) {
2590                 ios->vdd = new_ios->vdd;
2591                 slot_printf(slot, "VDD => %d\n", ios->vdd);
2592         }
2593         if (cts->ios_valid & MMC_CS) {
2594                 ios->chip_select = new_ios->chip_select;
2595                 slot_printf(slot, "CS => %d\n", ios->chip_select);
2596         }
2597         if (cts->ios_valid & MMC_BW) {
2598                 ios->bus_width = new_ios->bus_width;
2599                 slot_printf(slot, "Bus width => %d\n", ios->bus_width);
2600         }
2601         if (cts->ios_valid & MMC_PM) {
2602                 ios->power_mode = new_ios->power_mode;
2603                 slot_printf(slot, "Power mode => %d\n", ios->power_mode);
2604         }
2605         if (cts->ios_valid & MMC_BT) {
2606                 ios->timing = new_ios->timing;
2607                 slot_printf(slot, "Timing => %d\n", ios->timing);
2608         }
2609         if (cts->ios_valid & MMC_BM) {
2610                 ios->bus_mode = new_ios->bus_mode;
2611                 slot_printf(slot, "Bus mode => %d\n", ios->bus_mode);
2612         }
2613
2614         /* XXX Provide a way to call a chip-specific IOS update, required for TI */
2615         return (sdhci_cam_update_ios(slot));
2616 }
2617
2618 int
2619 sdhci_cam_update_ios(struct sdhci_slot *slot)
2620 {
2621         struct mmc_ios *ios = &slot->host.ios;
2622
2623         slot_printf(slot, "%s: power_mode=%d, clk=%d, bus_width=%d, timing=%d\n",
2624                     __func__, ios->power_mode, ios->clock, ios->bus_width, ios->timing);
2625         SDHCI_LOCK(slot);
2626         /* Do full reset on bus power down to clear from any state. */
2627         if (ios->power_mode == power_off) {
2628                 WR4(slot, SDHCI_SIGNAL_ENABLE, 0);
2629                 sdhci_init(slot);
2630         }
2631         /* Configure the bus. */
2632         sdhci_set_clock(slot, ios->clock);
2633         sdhci_set_power(slot, (ios->power_mode == power_off) ? 0 : ios->vdd);
2634         if (ios->bus_width == bus_width_8) {
2635                 slot->hostctrl |= SDHCI_CTRL_8BITBUS;
2636                 slot->hostctrl &= ~SDHCI_CTRL_4BITBUS;
2637         } else if (ios->bus_width == bus_width_4) {
2638                 slot->hostctrl &= ~SDHCI_CTRL_8BITBUS;
2639                 slot->hostctrl |= SDHCI_CTRL_4BITBUS;
2640         } else if (ios->bus_width == bus_width_1) {
2641                 slot->hostctrl &= ~SDHCI_CTRL_8BITBUS;
2642                 slot->hostctrl &= ~SDHCI_CTRL_4BITBUS;
2643         } else {
2644                 panic("Invalid bus width: %d", ios->bus_width);
2645         }
2646         if (ios->timing == bus_timing_hs &&
2647             !(slot->quirks & SDHCI_QUIRK_DONT_SET_HISPD_BIT))
2648                 slot->hostctrl |= SDHCI_CTRL_HISPD;
2649         else
2650                 slot->hostctrl &= ~SDHCI_CTRL_HISPD;
2651         WR1(slot, SDHCI_HOST_CONTROL, slot->hostctrl);
2652         /* Some controllers like reset after bus changes. */
2653         if(slot->quirks & SDHCI_QUIRK_RESET_ON_IOS)
2654                 sdhci_reset(slot, SDHCI_RESET_CMD | SDHCI_RESET_DATA);
2655
2656         SDHCI_UNLOCK(slot);
2657         return (0);
2658 }
2659
2660 int
2661 sdhci_cam_request(struct sdhci_slot *slot, union ccb *ccb)
2662 {
2663         struct ccb_mmcio *mmcio;
2664
2665         mmcio = &ccb->mmcio;
2666
2667         SDHCI_LOCK(slot);
2668 /*      if (slot->req != NULL) {
2669                 SDHCI_UNLOCK(slot);
2670                 return (EBUSY);
2671         }
2672 */
2673         if (__predict_false(sdhci_debug > 1)) {
2674                 slot_printf(slot, "CMD%u arg %#x flags %#x dlen %u dflags %#x\n",
2675                             mmcio->cmd.opcode, mmcio->cmd.arg, mmcio->cmd.flags,
2676                             mmcio->cmd.data != NULL ? (unsigned int) mmcio->cmd.data->len : 0,
2677                             mmcio->cmd.data != NULL ? mmcio->cmd.data->flags: 0);
2678         }
2679         if (mmcio->cmd.data != NULL) {
2680                 if (mmcio->cmd.data->len == 0 || mmcio->cmd.data->flags == 0)
2681                         panic("data->len = %d, data->flags = %d -- something is b0rked",
2682                               (int)mmcio->cmd.data->len, mmcio->cmd.data->flags);
2683         }
2684         slot->ccb = ccb;
2685         slot->flags = 0;
2686         sdhci_start(slot);
2687         SDHCI_UNLOCK(slot);
2688         if (dumping) {
2689                 while (slot->ccb != NULL) {
2690                         sdhci_generic_intr(slot);
2691                         DELAY(10);
2692                 }
2693         }
2694         return (0);
2695 }
2696 #endif /* MMCCAM */
2697
2698 MODULE_VERSION(sdhci, 1);