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