source: rtems-libbsd/freebsd/sys/dev/mmc/mmc.c

6-freebsd-12
Last change on this file was aec8db0, checked in by Sebastian Huber <sebastian.huber@…>, on 01/21/19 at 08:45:46

Update to FreeBSD stable/12 2019-01-16

Git mirror commit 4ff7d8141f665693dd8b17090d410604888f1e9a.

Update #3472.

  • Property mode set to 100644
File size: 73.7 KB
Line 
1#include <machine/rtems-bsd-kernel-space.h>
2
3/*-
4 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
5 *
6 * Copyright (c) 2006 Bernd Walter.  All rights reserved.
7 * Copyright (c) 2006 M. Warner Losh.  All rights reserved.
8 * Copyright (c) 2017 Marius Strobl <marius@FreeBSD.org>
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 *
30 * Portions of this software may have been developed with reference to
31 * the SD Simplified Specification.  The following disclaimer may apply:
32 *
33 * The following conditions apply to the release of the simplified
34 * specification ("Simplified Specification") by the SD Card Association and
35 * the SD Group. The Simplified Specification is a subset of the complete SD
36 * Specification which is owned by the SD Card Association and the SD
37 * Group. This Simplified Specification is provided on a non-confidential
38 * basis subject to the disclaimers below. Any implementation of the
39 * Simplified Specification may require a license from the SD Card
40 * Association, SD Group, SD-3C LLC or other third parties.
41 *
42 * Disclaimers:
43 *
44 * The information contained in the Simplified Specification is presented only
45 * as a standard specification for SD Cards and SD Host/Ancillary products and
46 * is provided "AS-IS" without any representations or warranties of any
47 * kind. No responsibility is assumed by the SD Group, SD-3C LLC or the SD
48 * Card Association for any damages, any infringements of patents or other
49 * right of the SD Group, SD-3C LLC, the SD Card Association or any third
50 * parties, which may result from its use. No license is granted by
51 * implication, estoppel or otherwise under any patent or other rights of the
52 * SD Group, SD-3C LLC, the SD Card Association or any third party. Nothing
53 * herein shall be construed as an obligation by the SD Group, the SD-3C LLC
54 * or the SD Card Association to disclose or distribute any technical
55 * information, know-how or other confidential information to any third party.
56 */
57
58#include <sys/cdefs.h>
59__FBSDID("$FreeBSD$");
60
61#include <sys/param.h>
62#include <sys/systm.h>
63#include <sys/kernel.h>
64#include <sys/malloc.h>
65#include <sys/lock.h>
66#include <sys/module.h>
67#include <sys/mutex.h>
68#include <sys/bus.h>
69#include <sys/endian.h>
70#include <sys/sysctl.h>
71#include <sys/time.h>
72
73#include <dev/mmc/bridge.h>
74#include <dev/mmc/mmc_private.h>
75#include <dev/mmc/mmc_subr.h>
76#include <dev/mmc/mmcreg.h>
77#include <dev/mmc/mmcbrvar.h>
78#include <dev/mmc/mmcvar.h>
79
80#include <rtems/bsd/local/mmcbr_if.h>
81#include <rtems/bsd/local/mmcbus_if.h>
82
83CTASSERT(bus_timing_max <= sizeof(uint32_t) * NBBY);
84
85/*
86 * Per-card data
87 */
88struct mmc_ivars {
89        uint32_t raw_cid[4];    /* Raw bits of the CID */
90        uint32_t raw_csd[4];    /* Raw bits of the CSD */
91        uint32_t raw_scr[2];    /* Raw bits of the SCR */
92        uint8_t raw_ext_csd[MMC_EXTCSD_SIZE]; /* Raw bits of the EXT_CSD */
93        uint32_t raw_sd_status[16];     /* Raw bits of the SD_STATUS */
94        uint16_t rca;
95        u_char read_only;       /* True when the device is read-only */
96        u_char high_cap;        /* High Capacity device (block addressed) */
97        enum mmc_card_mode mode;
98        enum mmc_bus_width bus_width;   /* Bus width to use */
99        struct mmc_cid cid;     /* cid decoded */
100        struct mmc_csd csd;     /* csd decoded */
101        struct mmc_scr scr;     /* scr decoded */
102        struct mmc_sd_status sd_status; /* SD_STATUS decoded */
103        uint32_t sec_count;     /* Card capacity in 512byte blocks */
104        uint32_t timings;       /* Mask of bus timings supported */
105        uint32_t vccq_120;      /* Mask of bus timings at VCCQ of 1.2 V */
106        uint32_t vccq_180;      /* Mask of bus timings at VCCQ of 1.8 V */
107        uint32_t tran_speed;    /* Max speed in normal mode */
108        uint32_t hs_tran_speed; /* Max speed in high speed mode */
109        uint32_t erase_sector;  /* Card native erase sector size */
110        uint32_t cmd6_time;     /* Generic switch timeout [us] */
111        uint32_t quirks;        /* Quirks as per mmc_quirk->quirks */
112        char card_id_string[64];/* Formatted CID info (serial, MFG, etc) */
113        char card_sn_string[16];/* Formatted serial # for disk->d_ident */
114};
115
116#define CMD_RETRIES     3
117
118static const struct mmc_quirk mmc_quirks[] = {
119        /*
120         * For some SanDisk iNAND devices, the CMD38 argument needs to be
121         * provided in EXT_CSD[113].
122         */
123        { 0x2, 0x100,                   "SEM02G", MMC_QUIRK_INAND_CMD38 },
124        { 0x2, 0x100,                   "SEM04G", MMC_QUIRK_INAND_CMD38 },
125        { 0x2, 0x100,                   "SEM08G", MMC_QUIRK_INAND_CMD38 },
126        { 0x2, 0x100,                   "SEM16G", MMC_QUIRK_INAND_CMD38 },
127        { 0x2, 0x100,                   "SEM32G", MMC_QUIRK_INAND_CMD38 },
128
129        /*
130         * Disable TRIM for Kingston eMMCs where a firmware bug can lead to
131         * unrecoverable data corruption.
132         */
133        { 0x70, MMC_QUIRK_OID_ANY,      "V10008", MMC_QUIRK_BROKEN_TRIM },
134        { 0x70, MMC_QUIRK_OID_ANY,      "V10016", MMC_QUIRK_BROKEN_TRIM },
135
136        { 0x0, 0x0, NULL, 0x0 }
137};
138
139static SYSCTL_NODE(_hw, OID_AUTO, mmc, CTLFLAG_RD, NULL, "mmc driver");
140
141static int mmc_debug;
142SYSCTL_INT(_hw_mmc, OID_AUTO, debug, CTLFLAG_RWTUN, &mmc_debug, 0,
143    "Debug level");
144
145/* bus entry points */
146static int mmc_acquire_bus(device_t busdev, device_t dev);
147static int mmc_attach(device_t dev);
148static int mmc_child_location_str(device_t dev, device_t child, char *buf,
149    size_t buflen);
150static int mmc_detach(device_t dev);
151static int mmc_probe(device_t dev);
152static int mmc_read_ivar(device_t bus, device_t child, int which,
153    uintptr_t *result);
154static int mmc_release_bus(device_t busdev, device_t dev);
155static int mmc_resume(device_t dev);
156static void mmc_retune_pause(device_t busdev, device_t dev, bool retune);
157static void mmc_retune_unpause(device_t busdev, device_t dev);
158static int mmc_suspend(device_t dev);
159static int mmc_wait_for_request(device_t busdev, device_t dev,
160    struct mmc_request *req);
161static int mmc_write_ivar(device_t bus, device_t child, int which,
162    uintptr_t value);
163
164#define MMC_LOCK(_sc)           mtx_lock(&(_sc)->sc_mtx)
165#define MMC_UNLOCK(_sc)         mtx_unlock(&(_sc)->sc_mtx)
166#define MMC_LOCK_INIT(_sc)                                              \
167        mtx_init(&(_sc)->sc_mtx, device_get_nameunit((_sc)->dev),       \
168            "mmc", MTX_DEF)
169#define MMC_LOCK_DESTROY(_sc)   mtx_destroy(&(_sc)->sc_mtx);
170#define MMC_ASSERT_LOCKED(_sc)  mtx_assert(&(_sc)->sc_mtx, MA_OWNED);
171#define MMC_ASSERT_UNLOCKED(_sc) mtx_assert(&(_sc)->sc_mtx, MA_NOTOWNED);
172
173static int mmc_all_send_cid(struct mmc_softc *sc, uint32_t *rawcid);
174static void mmc_app_decode_scr(uint32_t *raw_scr, struct mmc_scr *scr);
175static void mmc_app_decode_sd_status(uint32_t *raw_sd_status,
176    struct mmc_sd_status *sd_status);
177static int mmc_app_sd_status(struct mmc_softc *sc, uint16_t rca,
178    uint32_t *rawsdstatus);
179static int mmc_app_send_scr(struct mmc_softc *sc, uint16_t rca,
180    uint32_t *rawscr);
181static int mmc_calculate_clock(struct mmc_softc *sc);
182static void mmc_decode_cid_mmc(uint32_t *raw_cid, struct mmc_cid *cid,
183    bool is_4_41p);
184static void mmc_decode_cid_sd(uint32_t *raw_cid, struct mmc_cid *cid);
185static void mmc_decode_csd_mmc(uint32_t *raw_csd, struct mmc_csd *csd);
186static int mmc_decode_csd_sd(uint32_t *raw_csd, struct mmc_csd *csd);
187static void mmc_delayed_attach(void *xsc);
188static int mmc_delete_cards(struct mmc_softc *sc, bool final);
189static void mmc_discover_cards(struct mmc_softc *sc);
190static void mmc_format_card_id_string(struct mmc_ivars *ivar);
191static void mmc_go_discovery(struct mmc_softc *sc);
192static uint32_t mmc_get_bits(uint32_t *bits, int bit_len, int start,
193    int size);
194static int mmc_highest_voltage(uint32_t ocr);
195static bool mmc_host_timing(device_t dev, enum mmc_bus_timing timing);
196static void mmc_idle_cards(struct mmc_softc *sc);
197static void mmc_ms_delay(int ms);
198static void mmc_log_card(device_t dev, struct mmc_ivars *ivar, int newcard);
199static void mmc_power_down(struct mmc_softc *sc);
200static void mmc_power_up(struct mmc_softc *sc);
201static void mmc_rescan_cards(struct mmc_softc *sc);
202static int mmc_retune(device_t busdev, device_t dev, bool reset);
203static void mmc_scan(struct mmc_softc *sc);
204static int mmc_sd_switch(struct mmc_softc *sc, uint8_t mode, uint8_t grp,
205    uint8_t value, uint8_t *res);
206static int mmc_select_card(struct mmc_softc *sc, uint16_t rca);
207static uint32_t mmc_select_vdd(struct mmc_softc *sc, uint32_t ocr);
208static int mmc_send_app_op_cond(struct mmc_softc *sc, uint32_t ocr,
209    uint32_t *rocr);
210static int mmc_send_csd(struct mmc_softc *sc, uint16_t rca, uint32_t *rawcsd);
211static int mmc_send_if_cond(struct mmc_softc *sc, uint8_t vhs);
212static int mmc_send_op_cond(struct mmc_softc *sc, uint32_t ocr,
213    uint32_t *rocr);
214static int mmc_send_relative_addr(struct mmc_softc *sc, uint32_t *resp);
215static int mmc_set_blocklen(struct mmc_softc *sc, uint32_t len);
216static int mmc_set_card_bus_width(struct mmc_softc *sc, struct mmc_ivars *ivar,
217    enum mmc_bus_timing timing);
218static int mmc_set_power_class(struct mmc_softc *sc, struct mmc_ivars *ivar);
219static int mmc_set_relative_addr(struct mmc_softc *sc, uint16_t resp);
220static int mmc_set_timing(struct mmc_softc *sc, struct mmc_ivars *ivar,
221    enum mmc_bus_timing timing);
222static int mmc_set_vccq(struct mmc_softc *sc, struct mmc_ivars *ivar,
223    enum mmc_bus_timing timing);
224static int mmc_switch_to_hs200(struct mmc_softc *sc, struct mmc_ivars *ivar,
225    uint32_t clock);
226static int mmc_switch_to_hs400(struct mmc_softc *sc, struct mmc_ivars *ivar,
227    uint32_t max_dtr, enum mmc_bus_timing max_timing);
228static int mmc_test_bus_width(struct mmc_softc *sc);
229static uint32_t mmc_timing_to_dtr(struct mmc_ivars *ivar,
230    enum mmc_bus_timing timing);
231static const char *mmc_timing_to_string(enum mmc_bus_timing timing);
232static void mmc_update_child_list(struct mmc_softc *sc);
233static int mmc_wait_for_command(struct mmc_softc *sc, uint32_t opcode,
234    uint32_t arg, uint32_t flags, uint32_t *resp, int retries);
235static int mmc_wait_for_req(struct mmc_softc *sc, struct mmc_request *req);
236static void mmc_wakeup(struct mmc_request *req);
237
238static void
239mmc_ms_delay(int ms)
240{
241
242        DELAY(1000 * ms);       /* XXX BAD */
243}
244
245static int
246mmc_probe(device_t dev)
247{
248
249        device_set_desc(dev, "MMC/SD bus");
250        return (0);
251}
252
253static int
254mmc_attach(device_t dev)
255{
256        struct mmc_softc *sc;
257
258        sc = device_get_softc(dev);
259        sc->dev = dev;
260        MMC_LOCK_INIT(sc);
261
262        /* We'll probe and attach our children later, but before / mount */
263        sc->config_intrhook.ich_func = mmc_delayed_attach;
264        sc->config_intrhook.ich_arg = sc;
265        if (config_intrhook_establish(&sc->config_intrhook) != 0)
266                device_printf(dev, "config_intrhook_establish failed\n");
267        return (0);
268}
269
270static int
271mmc_detach(device_t dev)
272{
273        struct mmc_softc *sc = device_get_softc(dev);
274        int err;
275
276        err = mmc_delete_cards(sc, true);
277        if (err != 0)
278                return (err);
279        mmc_power_down(sc);
280        MMC_LOCK_DESTROY(sc);
281
282        return (0);
283}
284
285static int
286mmc_suspend(device_t dev)
287{
288        struct mmc_softc *sc = device_get_softc(dev);
289        int err;
290
291        err = bus_generic_suspend(dev);
292        if (err != 0)
293                return (err);
294        /*
295         * We power down with the bus acquired here, mainly so that no device
296         * is selected any longer and sc->last_rca gets set to 0.  Otherwise,
297         * the deselect as part of the bus acquisition in mmc_scan() may fail
298         * during resume, as the bus isn't powered up again before later in
299         * mmc_go_discovery().
300         */
301        err = mmc_acquire_bus(dev, dev);
302        if (err != 0)
303                return (err);
304        mmc_power_down(sc);
305        err = mmc_release_bus(dev, dev);
306        return (err);
307}
308
309static int
310mmc_resume(device_t dev)
311{
312        struct mmc_softc *sc = device_get_softc(dev);
313
314        mmc_scan(sc);
315        return (bus_generic_resume(dev));
316}
317
318static int
319mmc_acquire_bus(device_t busdev, device_t dev)
320{
321        struct mmc_softc *sc;
322        struct mmc_ivars *ivar;
323        int err;
324        uint16_t rca;
325        enum mmc_bus_timing timing;
326
327        err = MMCBR_ACQUIRE_HOST(device_get_parent(busdev), busdev);
328        if (err)
329                return (err);
330        sc = device_get_softc(busdev);
331        MMC_LOCK(sc);
332        if (sc->owner)
333                panic("mmc: host bridge didn't serialize us.");
334        sc->owner = dev;
335        MMC_UNLOCK(sc);
336
337        if (busdev != dev) {
338                /*
339                 * Keep track of the last rca that we've selected.  If
340                 * we're asked to do it again, don't.  We never
341                 * unselect unless the bus code itself wants the mmc
342                 * bus, and constantly reselecting causes problems.
343                 */
344                ivar = device_get_ivars(dev);
345                rca = ivar->rca;
346                if (sc->last_rca != rca) {
347                        if (mmc_select_card(sc, rca) != MMC_ERR_NONE) {
348                                device_printf(busdev, "Card at relative "
349                                    "address %d failed to select\n", rca);
350                                return (ENXIO);
351                        }
352                        sc->last_rca = rca;
353                        timing = mmcbr_get_timing(busdev);
354                        /*
355                         * For eMMC modes, setting/updating bus width and VCCQ
356                         * only really is necessary if there actually is more
357                         * than one device on the bus as generally that already
358                         * had to be done by mmc_calculate_clock() or one of
359                         * its calees.  Moreover, setting the bus width anew
360                         * can trigger re-tuning (via a CRC error on the next
361                         * CMD), even if not switching between devices an the
362                         * previously selected one is still tuned.  Obviously,
363                         * we need to re-tune the host controller if devices
364                         * are actually switched, though.
365                         */
366                        if (timing >= bus_timing_mmc_ddr52 &&
367                            sc->child_count == 1)
368                                return (0);
369                        /* Prepare bus width for the new card. */
370                        if (bootverbose || mmc_debug) {
371                                device_printf(busdev,
372                                    "setting bus width to %d bits %s timing\n",
373                                    (ivar->bus_width == bus_width_4) ? 4 :
374                                    (ivar->bus_width == bus_width_8) ? 8 : 1,
375                                    mmc_timing_to_string(timing));
376                        }
377                        if (mmc_set_card_bus_width(sc, ivar, timing) !=
378                            MMC_ERR_NONE) {
379                                device_printf(busdev, "Card at relative "
380                                    "address %d failed to set bus width\n",
381                                    rca);
382                                return (ENXIO);
383                        }
384                        mmcbr_set_bus_width(busdev, ivar->bus_width);
385                        mmcbr_update_ios(busdev);
386                        if (mmc_set_vccq(sc, ivar, timing) != MMC_ERR_NONE) {
387                                device_printf(busdev, "Failed to set VCCQ "
388                                    "for card at relative address %d\n", rca);
389                                return (ENXIO);
390                        }
391                        if (timing >= bus_timing_mmc_hs200 &&
392                            mmc_retune(busdev, dev, true) != 0) {
393                                device_printf(busdev, "Card at relative "
394                                    "address %d failed to re-tune\n", rca);
395                                return (ENXIO);
396                        }
397                }
398        } else {
399                /*
400                 * If there's a card selected, stand down.
401                 */
402                if (sc->last_rca != 0) {
403                        if (mmc_select_card(sc, 0) != MMC_ERR_NONE)
404                                return (ENXIO);
405                        sc->last_rca = 0;
406                }
407        }
408
409        return (0);
410}
411
412static int
413mmc_release_bus(device_t busdev, device_t dev)
414{
415        struct mmc_softc *sc;
416        int err;
417
418        sc = device_get_softc(busdev);
419
420        MMC_LOCK(sc);
421        if (!sc->owner)
422                panic("mmc: releasing unowned bus.");
423        if (sc->owner != dev)
424                panic("mmc: you don't own the bus.  game over.");
425        MMC_UNLOCK(sc);
426        err = MMCBR_RELEASE_HOST(device_get_parent(busdev), busdev);
427        if (err)
428                return (err);
429        MMC_LOCK(sc);
430        sc->owner = NULL;
431        MMC_UNLOCK(sc);
432        return (0);
433}
434
435static uint32_t
436mmc_select_vdd(struct mmc_softc *sc, uint32_t ocr)
437{
438
439        return (ocr & MMC_OCR_VOLTAGE);
440}
441
442static int
443mmc_highest_voltage(uint32_t ocr)
444{
445        int i;
446
447        for (i = MMC_OCR_MAX_VOLTAGE_SHIFT;
448            i >= MMC_OCR_MIN_VOLTAGE_SHIFT; i--)
449                if (ocr & (1 << i))
450                        return (i);
451        return (-1);
452}
453
454static void
455mmc_wakeup(struct mmc_request *req)
456{
457#ifndef __rtems__
458        struct mmc_softc *sc;
459
460        sc = (struct mmc_softc *)req->done_data;
461        MMC_LOCK(sc);
462        req->flags |= MMC_REQ_DONE;
463        MMC_UNLOCK(sc);
464        wakeup(req);
465#else /* __rtems__ */
466        rtems_binary_semaphore_post(&req->req_done);
467#endif /* __rtems__ */
468}
469
470static int
471mmc_wait_for_req(struct mmc_softc *sc, struct mmc_request *req)
472{
473
474#ifdef __rtems__
475        rtems_binary_semaphore_init(&req->req_done, "mmc_req_done");
476#endif /* __rtems__ */
477        req->done = mmc_wakeup;
478        req->done_data = sc;
479        if (__predict_false(mmc_debug > 1)) {
480                device_printf(sc->dev, "REQUEST: CMD%d arg %#x flags %#x",
481                    req->cmd->opcode, req->cmd->arg, req->cmd->flags);
482                if (req->cmd->data) {
483                        printf(" data %d\n", (int)req->cmd->data->len);
484                } else
485                        printf("\n");
486        }
487        MMCBR_REQUEST(device_get_parent(sc->dev), sc->dev, req);
488#ifndef __rtems__
489        MMC_LOCK(sc);
490        while ((req->flags & MMC_REQ_DONE) == 0)
491                msleep(req, &sc->sc_mtx, 0, "mmcreq", 0);
492        MMC_UNLOCK(sc);
493#else /* __rtems__ */
494        rtems_binary_semaphore_wait(&req->req_done);
495        rtems_binary_semaphore_destroy(&req->req_done);
496#endif /* __rtems__ */
497        if (__predict_false(mmc_debug > 2 || (mmc_debug > 0 &&
498            req->cmd->error != MMC_ERR_NONE)))
499                device_printf(sc->dev, "CMD%d RESULT: %d\n",
500                    req->cmd->opcode, req->cmd->error);
501        return (0);
502}
503
504static int
505mmc_wait_for_request(device_t busdev, device_t dev, struct mmc_request *req)
506{
507        struct mmc_softc *sc;
508        struct mmc_ivars *ivar;
509        int err, i;
510        enum mmc_retune_req retune_req;
511
512        sc = device_get_softc(busdev);
513        KASSERT(sc->owner != NULL,
514            ("%s: Request from %s without bus being acquired.", __func__,
515            device_get_nameunit(dev)));
516
517        /*
518         * Unless no device is selected or re-tuning is already ongoing,
519         * execute re-tuning if a) the bridge is requesting to do so and
520         * re-tuning hasn't been otherwise paused, or b) if a child asked
521         * to be re-tuned prior to pausing (see also mmc_retune_pause()).
522         */
523        if (__predict_false(sc->last_rca != 0 && sc->retune_ongoing == 0 &&
524            (((retune_req = mmcbr_get_retune_req(busdev)) != retune_req_none &&
525            sc->retune_paused == 0) || sc->retune_needed == 1))) {
526                if (__predict_false(mmc_debug > 1)) {
527                        device_printf(busdev,
528                            "Re-tuning with%s circuit reset required\n",
529                            retune_req == retune_req_reset ? "" : "out");
530                }
531                if (device_get_parent(dev) == busdev)
532                        ivar = device_get_ivars(dev);
533                else {
534                        for (i = 0; i < sc->child_count; i++) {
535                                ivar = device_get_ivars(sc->child_list[i]);
536                                if (ivar->rca == sc->last_rca)
537                                        break;
538                        }
539                        if (ivar->rca != sc->last_rca)
540                                return (EINVAL);
541                }
542                sc->retune_ongoing = 1;
543                err = mmc_retune(busdev, dev, retune_req == retune_req_reset);
544                sc->retune_ongoing = 0;
545                switch (err) {
546                case MMC_ERR_NONE:
547                case MMC_ERR_FAILED:    /* Re-tune error but still might work */
548                        break;
549                case MMC_ERR_BADCRC:    /* Switch failure on HS400 recovery */
550                        return (ENXIO);
551                case MMC_ERR_INVALID:   /* Driver implementation b0rken */
552                default:                /* Unknown error, should not happen */
553                        return (EINVAL);
554                }
555                sc->retune_needed = 0;
556        }
557        return (mmc_wait_for_req(sc, req));
558}
559
560static int
561mmc_wait_for_command(struct mmc_softc *sc, uint32_t opcode,
562    uint32_t arg, uint32_t flags, uint32_t *resp, int retries)
563{
564        struct mmc_command cmd;
565        int err;
566
567        memset(&cmd, 0, sizeof(cmd));
568        cmd.opcode = opcode;
569        cmd.arg = arg;
570        cmd.flags = flags;
571        cmd.data = NULL;
572        err = mmc_wait_for_cmd(sc->dev, sc->dev, &cmd, retries);
573        if (err)
574                return (err);
575        if (resp) {
576                if (flags & MMC_RSP_136)
577                        memcpy(resp, cmd.resp, 4 * sizeof(uint32_t));
578                else
579                        *resp = cmd.resp[0];
580        }
581        return (0);
582}
583
584static void
585mmc_idle_cards(struct mmc_softc *sc)
586{
587        device_t dev;
588        struct mmc_command cmd;
589
590        dev = sc->dev;
591        mmcbr_set_chip_select(dev, cs_high);
592        mmcbr_update_ios(dev);
593        mmc_ms_delay(1);
594
595        memset(&cmd, 0, sizeof(cmd));
596        cmd.opcode = MMC_GO_IDLE_STATE;
597        cmd.arg = 0;
598        cmd.flags = MMC_RSP_NONE | MMC_CMD_BC;
599        cmd.data = NULL;
600        mmc_wait_for_cmd(sc->dev, sc->dev, &cmd, CMD_RETRIES);
601        mmc_ms_delay(1);
602
603        mmcbr_set_chip_select(dev, cs_dontcare);
604        mmcbr_update_ios(dev);
605        mmc_ms_delay(1);
606}
607
608static int
609mmc_send_app_op_cond(struct mmc_softc *sc, uint32_t ocr, uint32_t *rocr)
610{
611        struct mmc_command cmd;
612        int err = MMC_ERR_NONE, i;
613
614        memset(&cmd, 0, sizeof(cmd));
615        cmd.opcode = ACMD_SD_SEND_OP_COND;
616        cmd.arg = ocr;
617        cmd.flags = MMC_RSP_R3 | MMC_CMD_BCR;
618        cmd.data = NULL;
619
620        for (i = 0; i < 1000; i++) {
621                err = mmc_wait_for_app_cmd(sc->dev, sc->dev, 0, &cmd,
622                    CMD_RETRIES);
623                if (err != MMC_ERR_NONE)
624                        break;
625                if ((cmd.resp[0] & MMC_OCR_CARD_BUSY) ||
626                    (ocr & MMC_OCR_VOLTAGE) == 0)
627                        break;
628                err = MMC_ERR_TIMEOUT;
629                mmc_ms_delay(10);
630        }
631        if (rocr && err == MMC_ERR_NONE)
632                *rocr = cmd.resp[0];
633        return (err);
634}
635
636static int
637mmc_send_op_cond(struct mmc_softc *sc, uint32_t ocr, uint32_t *rocr)
638{
639        struct mmc_command cmd;
640        int err = MMC_ERR_NONE, i;
641
642        memset(&cmd, 0, sizeof(cmd));
643        cmd.opcode = MMC_SEND_OP_COND;
644        cmd.arg = ocr;
645        cmd.flags = MMC_RSP_R3 | MMC_CMD_BCR;
646        cmd.data = NULL;
647
648        for (i = 0; i < 1000; i++) {
649                err = mmc_wait_for_cmd(sc->dev, sc->dev, &cmd, CMD_RETRIES);
650                if (err != MMC_ERR_NONE)
651                        break;
652                if ((cmd.resp[0] & MMC_OCR_CARD_BUSY) ||
653                    (ocr & MMC_OCR_VOLTAGE) == 0)
654                        break;
655                err = MMC_ERR_TIMEOUT;
656                mmc_ms_delay(10);
657        }
658        if (rocr && err == MMC_ERR_NONE)
659                *rocr = cmd.resp[0];
660        return (err);
661}
662
663static int
664mmc_send_if_cond(struct mmc_softc *sc, uint8_t vhs)
665{
666        struct mmc_command cmd;
667        int err;
668
669        memset(&cmd, 0, sizeof(cmd));
670        cmd.opcode = SD_SEND_IF_COND;
671        cmd.arg = (vhs << 8) + 0xAA;
672        cmd.flags = MMC_RSP_R7 | MMC_CMD_BCR;
673        cmd.data = NULL;
674
675        err = mmc_wait_for_cmd(sc->dev, sc->dev, &cmd, CMD_RETRIES);
676        return (err);
677}
678
679static void
680mmc_power_up(struct mmc_softc *sc)
681{
682        device_t dev;
683        enum mmc_vccq vccq;
684
685        dev = sc->dev;
686        mmcbr_set_vdd(dev, mmc_highest_voltage(mmcbr_get_host_ocr(dev)));
687        mmcbr_set_bus_mode(dev, opendrain);
688        mmcbr_set_chip_select(dev, cs_dontcare);
689        mmcbr_set_bus_width(dev, bus_width_1);
690        mmcbr_set_power_mode(dev, power_up);
691        mmcbr_set_clock(dev, 0);
692        mmcbr_update_ios(dev);
693        for (vccq = vccq_330; ; vccq--) {
694                mmcbr_set_vccq(dev, vccq);
695                if (mmcbr_switch_vccq(dev) == 0 || vccq == vccq_120)
696                        break;
697        }
698        mmc_ms_delay(1);
699
700        mmcbr_set_clock(dev, SD_MMC_CARD_ID_FREQUENCY);
701        mmcbr_set_timing(dev, bus_timing_normal);
702        mmcbr_set_power_mode(dev, power_on);
703        mmcbr_update_ios(dev);
704        mmc_ms_delay(2);
705}
706
707static void
708mmc_power_down(struct mmc_softc *sc)
709{
710        device_t dev = sc->dev;
711
712        mmcbr_set_bus_mode(dev, opendrain);
713        mmcbr_set_chip_select(dev, cs_dontcare);
714        mmcbr_set_bus_width(dev, bus_width_1);
715        mmcbr_set_power_mode(dev, power_off);
716        mmcbr_set_clock(dev, 0);
717        mmcbr_set_timing(dev, bus_timing_normal);
718        mmcbr_update_ios(dev);
719}
720
721static int
722mmc_select_card(struct mmc_softc *sc, uint16_t rca)
723{
724        int err, flags;
725
726        flags = (rca ? MMC_RSP_R1B : MMC_RSP_NONE) | MMC_CMD_AC;
727        sc->retune_paused++;
728        err = mmc_wait_for_command(sc, MMC_SELECT_CARD, (uint32_t)rca << 16,
729            flags, NULL, CMD_RETRIES);
730        sc->retune_paused--;
731        return (err);
732}
733
734static int
735mmc_sd_switch(struct mmc_softc *sc, uint8_t mode, uint8_t grp, uint8_t value,
736    uint8_t *res)
737{
738        int err;
739        struct mmc_command cmd;
740        struct mmc_data data;
741
742        memset(&cmd, 0, sizeof(cmd));
743        memset(&data, 0, sizeof(data));
744        memset(res, 0, 64);
745
746        cmd.opcode = SD_SWITCH_FUNC;
747        cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
748        cmd.arg = mode << 31;                   /* 0 - check, 1 - set */
749        cmd.arg |= 0x00FFFFFF;
750        cmd.arg &= ~(0xF << (grp * 4));
751        cmd.arg |= value << (grp * 4);
752        cmd.data = &data;
753
754        data.data = res;
755        data.len = 64;
756        data.flags = MMC_DATA_READ;
757
758        err = mmc_wait_for_cmd(sc->dev, sc->dev, &cmd, CMD_RETRIES);
759        return (err);
760}
761
762static int
763mmc_set_card_bus_width(struct mmc_softc *sc, struct mmc_ivars *ivar,
764    enum mmc_bus_timing timing)
765{
766        struct mmc_command cmd;
767        int err;
768        uint8_t value;
769
770        if (mmcbr_get_mode(sc->dev) == mode_sd) {
771                memset(&cmd, 0, sizeof(cmd));
772                cmd.opcode = ACMD_SET_CLR_CARD_DETECT;
773                cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
774                cmd.arg = SD_CLR_CARD_DETECT;
775                err = mmc_wait_for_app_cmd(sc->dev, sc->dev, ivar->rca, &cmd,
776                    CMD_RETRIES);
777                if (err != 0)
778                        return (err);
779                memset(&cmd, 0, sizeof(cmd));
780                cmd.opcode = ACMD_SET_BUS_WIDTH;
781                cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
782                switch (ivar->bus_width) {
783                case bus_width_1:
784                        cmd.arg = SD_BUS_WIDTH_1;
785                        break;
786                case bus_width_4:
787                        cmd.arg = SD_BUS_WIDTH_4;
788                        break;
789                default:
790                        return (MMC_ERR_INVALID);
791                }
792                err = mmc_wait_for_app_cmd(sc->dev, sc->dev, ivar->rca, &cmd,
793                    CMD_RETRIES);
794        } else {
795                switch (ivar->bus_width) {
796                case bus_width_1:
797                        if (timing == bus_timing_mmc_hs400 ||
798                            timing == bus_timing_mmc_hs400es)
799                                return (MMC_ERR_INVALID);
800                        value = EXT_CSD_BUS_WIDTH_1;
801                        break;
802                case bus_width_4:
803                        switch (timing) {
804                        case bus_timing_mmc_ddr52:
805                                value = EXT_CSD_BUS_WIDTH_4_DDR;
806                                break;
807                        case bus_timing_mmc_hs400:
808                        case bus_timing_mmc_hs400es:
809                                return (MMC_ERR_INVALID);
810                        default:
811                                value = EXT_CSD_BUS_WIDTH_4;
812                                break;
813                        }
814                        break;
815                case bus_width_8:
816                        value = 0;
817                        switch (timing) {
818                        case bus_timing_mmc_hs400es:
819                                value = EXT_CSD_BUS_WIDTH_ES;
820                                /* FALLTHROUGH */
821                        case bus_timing_mmc_ddr52:
822                        case bus_timing_mmc_hs400:
823                                value |= EXT_CSD_BUS_WIDTH_8_DDR;
824                                break;
825                        default:
826                                value = EXT_CSD_BUS_WIDTH_8;
827                                break;
828                        }
829                        break;
830                default:
831                        return (MMC_ERR_INVALID);
832                }
833                err = mmc_switch(sc->dev, sc->dev, ivar->rca,
834                    EXT_CSD_CMD_SET_NORMAL, EXT_CSD_BUS_WIDTH, value,
835                    ivar->cmd6_time, true);
836        }
837        return (err);
838}
839
840static int
841mmc_set_power_class(struct mmc_softc *sc, struct mmc_ivars *ivar)
842{
843        device_t dev;
844        const uint8_t *ext_csd;
845        uint32_t clock;
846        uint8_t value;
847        enum mmc_bus_timing timing;
848        enum mmc_bus_width bus_width;
849
850        dev = sc->dev;
851        timing = mmcbr_get_timing(dev);
852        bus_width = ivar->bus_width;
853        if (mmcbr_get_mode(dev) != mode_mmc || ivar->csd.spec_vers < 4 ||
854            timing == bus_timing_normal || bus_width == bus_width_1)
855                return (MMC_ERR_NONE);
856
857        value = 0;
858        ext_csd = ivar->raw_ext_csd;
859        clock = mmcbr_get_clock(dev);
860        switch (1 << mmcbr_get_vdd(dev)) {
861        case MMC_OCR_LOW_VOLTAGE:
862                if (clock <= MMC_TYPE_HS_26_MAX)
863                        value = ext_csd[EXT_CSD_PWR_CL_26_195];
864                else if (clock <= MMC_TYPE_HS_52_MAX) {
865                        if (timing >= bus_timing_mmc_ddr52 &&
866                            bus_width >= bus_width_4)
867                                value = ext_csd[EXT_CSD_PWR_CL_52_195_DDR];
868                        else
869                                value = ext_csd[EXT_CSD_PWR_CL_52_195];
870                } else if (clock <= MMC_TYPE_HS200_HS400ES_MAX)
871                        value = ext_csd[EXT_CSD_PWR_CL_200_195];
872                break;
873        case MMC_OCR_270_280:
874        case MMC_OCR_280_290:
875        case MMC_OCR_290_300:
876        case MMC_OCR_300_310:
877        case MMC_OCR_310_320:
878        case MMC_OCR_320_330:
879        case MMC_OCR_330_340:
880        case MMC_OCR_340_350:
881        case MMC_OCR_350_360:
882                if (clock <= MMC_TYPE_HS_26_MAX)
883                        value = ext_csd[EXT_CSD_PWR_CL_26_360];
884                else if (clock <= MMC_TYPE_HS_52_MAX) {
885                        if (timing == bus_timing_mmc_ddr52 &&
886                            bus_width >= bus_width_4)
887                                value = ext_csd[EXT_CSD_PWR_CL_52_360_DDR];
888                        else
889                                value = ext_csd[EXT_CSD_PWR_CL_52_360];
890                } else if (clock <= MMC_TYPE_HS200_HS400ES_MAX) {
891                        if (bus_width == bus_width_8)
892                                value = ext_csd[EXT_CSD_PWR_CL_200_360_DDR];
893                        else
894                                value = ext_csd[EXT_CSD_PWR_CL_200_360];
895                }
896                break;
897        default:
898                device_printf(dev, "No power class support for VDD 0x%x\n",
899                        1 << mmcbr_get_vdd(dev));
900                return (MMC_ERR_INVALID);
901        }
902
903        if (bus_width == bus_width_8)
904                value = (value & EXT_CSD_POWER_CLASS_8BIT_MASK) >>
905                    EXT_CSD_POWER_CLASS_8BIT_SHIFT;
906        else
907                value = (value & EXT_CSD_POWER_CLASS_4BIT_MASK) >>
908                    EXT_CSD_POWER_CLASS_4BIT_SHIFT;
909
910        if (value == 0)
911                return (MMC_ERR_NONE);
912
913        return (mmc_switch(dev, dev, ivar->rca, EXT_CSD_CMD_SET_NORMAL,
914            EXT_CSD_POWER_CLASS, value, ivar->cmd6_time, true));
915}
916
917static int
918mmc_set_timing(struct mmc_softc *sc, struct mmc_ivars *ivar,
919    enum mmc_bus_timing timing)
920{
921        u_char switch_res[64];
922        uint8_t value;
923        int err;
924
925        if (mmcbr_get_mode(sc->dev) == mode_sd) {
926                switch (timing) {
927                case bus_timing_normal:
928                        value = SD_SWITCH_NORMAL_MODE;
929                        break;
930                case bus_timing_hs:
931                        value = SD_SWITCH_HS_MODE;
932                        break;
933                default:
934                        return (MMC_ERR_INVALID);
935                }
936                err = mmc_sd_switch(sc, SD_SWITCH_MODE_SET, SD_SWITCH_GROUP1,
937                    value, switch_res);
938                if (err != MMC_ERR_NONE)
939                        return (err);
940                if ((switch_res[16] & 0xf) != value)
941                        return (MMC_ERR_FAILED);
942                mmcbr_set_timing(sc->dev, timing);
943                mmcbr_update_ios(sc->dev);
944        } else {
945                switch (timing) {
946                case bus_timing_normal:
947                        value = EXT_CSD_HS_TIMING_BC;
948                        break;
949                case bus_timing_hs:
950                case bus_timing_mmc_ddr52:
951                        value = EXT_CSD_HS_TIMING_HS;
952                        break;
953                case bus_timing_mmc_hs200:
954                        value = EXT_CSD_HS_TIMING_HS200;
955                        break;
956                case bus_timing_mmc_hs400:
957                case bus_timing_mmc_hs400es:
958                        value = EXT_CSD_HS_TIMING_HS400;
959                        break;
960                default:
961                        return (MMC_ERR_INVALID);
962                }
963                err = mmc_switch(sc->dev, sc->dev, ivar->rca,
964                    EXT_CSD_CMD_SET_NORMAL, EXT_CSD_HS_TIMING, value,
965                    ivar->cmd6_time, false);
966                if (err != MMC_ERR_NONE)
967                        return (err);
968                mmcbr_set_timing(sc->dev, timing);
969                mmcbr_update_ios(sc->dev);
970                err = mmc_switch_status(sc->dev, sc->dev, ivar->rca,
971                    ivar->cmd6_time);
972        }
973        return (err);
974}
975
976static int
977mmc_set_vccq(struct mmc_softc *sc, struct mmc_ivars *ivar,
978    enum mmc_bus_timing timing)
979{
980
981        if (isset(&ivar->vccq_120, timing))
982                mmcbr_set_vccq(sc->dev, vccq_120);
983        else if (isset(&ivar->vccq_180, timing))
984                mmcbr_set_vccq(sc->dev, vccq_180);
985        else
986                mmcbr_set_vccq(sc->dev, vccq_330);
987        if (mmcbr_switch_vccq(sc->dev) != 0)
988                return (MMC_ERR_INVALID);
989        else
990                return (MMC_ERR_NONE);
991}
992
993static const uint8_t p8[8] = {
994        0x55, 0xAA, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
995};
996
997static const uint8_t p8ok[8] = {
998        0xAA, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
999};
1000
1001static const uint8_t p4[4] = {
1002        0x5A, 0x00, 0x00, 0x00
1003};
1004
1005static const uint8_t p4ok[4] = {
1006        0xA5, 0x00, 0x00, 0x00
1007};
1008
1009static int
1010mmc_test_bus_width(struct mmc_softc *sc)
1011{
1012        struct mmc_command cmd;
1013        struct mmc_data data;
1014        uint8_t buf[8];
1015        int err;
1016
1017        if (mmcbr_get_caps(sc->dev) & MMC_CAP_8_BIT_DATA) {
1018                mmcbr_set_bus_width(sc->dev, bus_width_8);
1019                mmcbr_update_ios(sc->dev);
1020
1021                sc->squelched++; /* Errors are expected, squelch reporting. */
1022                memset(&cmd, 0, sizeof(cmd));
1023                memset(&data, 0, sizeof(data));
1024                cmd.opcode = MMC_BUSTEST_W;
1025                cmd.arg = 0;
1026                cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
1027                cmd.data = &data;
1028
1029                data.data = __DECONST(void *, p8);
1030                data.len = 8;
1031                data.flags = MMC_DATA_WRITE;
1032                mmc_wait_for_cmd(sc->dev, sc->dev, &cmd, 0);
1033
1034                memset(&cmd, 0, sizeof(cmd));
1035                memset(&data, 0, sizeof(data));
1036                cmd.opcode = MMC_BUSTEST_R;
1037                cmd.arg = 0;
1038                cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
1039                cmd.data = &data;
1040
1041                data.data = buf;
1042                data.len = 8;
1043                data.flags = MMC_DATA_READ;
1044                err = mmc_wait_for_cmd(sc->dev, sc->dev, &cmd, 0);
1045                sc->squelched--;
1046
1047                mmcbr_set_bus_width(sc->dev, bus_width_1);
1048                mmcbr_update_ios(sc->dev);
1049
1050                if (err == MMC_ERR_NONE && memcmp(buf, p8ok, 8) == 0)
1051                        return (bus_width_8);
1052        }
1053
1054        if (mmcbr_get_caps(sc->dev) & MMC_CAP_4_BIT_DATA) {
1055                mmcbr_set_bus_width(sc->dev, bus_width_4);
1056                mmcbr_update_ios(sc->dev);
1057
1058                sc->squelched++; /* Errors are expected, squelch reporting. */
1059                memset(&cmd, 0, sizeof(cmd));
1060                memset(&data, 0, sizeof(data));
1061                cmd.opcode = MMC_BUSTEST_W;
1062                cmd.arg = 0;
1063                cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
1064                cmd.data = &data;
1065
1066                data.data = __DECONST(void *, p4);
1067                data.len = 4;
1068                data.flags = MMC_DATA_WRITE;
1069                mmc_wait_for_cmd(sc->dev, sc->dev, &cmd, 0);
1070
1071                memset(&cmd, 0, sizeof(cmd));
1072                memset(&data, 0, sizeof(data));
1073                cmd.opcode = MMC_BUSTEST_R;
1074                cmd.arg = 0;
1075                cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
1076                cmd.data = &data;
1077
1078                data.data = buf;
1079                data.len = 4;
1080                data.flags = MMC_DATA_READ;
1081                err = mmc_wait_for_cmd(sc->dev, sc->dev, &cmd, 0);
1082                sc->squelched--;
1083
1084                mmcbr_set_bus_width(sc->dev, bus_width_1);
1085                mmcbr_update_ios(sc->dev);
1086
1087                if (err == MMC_ERR_NONE && memcmp(buf, p4ok, 4) == 0)
1088                        return (bus_width_4);
1089        }
1090        return (bus_width_1);
1091}
1092
1093static uint32_t
1094mmc_get_bits(uint32_t *bits, int bit_len, int start, int size)
1095{
1096        const int i = (bit_len / 32) - (start / 32) - 1;
1097        const int shift = start & 31;
1098        uint32_t retval = bits[i] >> shift;
1099
1100        if (size + shift > 32)
1101                retval |= bits[i - 1] << (32 - shift);
1102        return (retval & ((1llu << size) - 1));
1103}
1104
1105static void
1106mmc_decode_cid_sd(uint32_t *raw_cid, struct mmc_cid *cid)
1107{
1108        int i;
1109
1110        /* There's no version info, so we take it on faith */
1111        memset(cid, 0, sizeof(*cid));
1112        cid->mid = mmc_get_bits(raw_cid, 128, 120, 8);
1113        cid->oid = mmc_get_bits(raw_cid, 128, 104, 16);
1114        for (i = 0; i < 5; i++)
1115                cid->pnm[i] = mmc_get_bits(raw_cid, 128, 96 - i * 8, 8);
1116        cid->pnm[5] = 0;
1117        cid->prv = mmc_get_bits(raw_cid, 128, 56, 8);
1118        cid->psn = mmc_get_bits(raw_cid, 128, 24, 32);
1119        cid->mdt_year = mmc_get_bits(raw_cid, 128, 12, 8) + 2000;
1120        cid->mdt_month = mmc_get_bits(raw_cid, 128, 8, 4);
1121}
1122
1123static void
1124mmc_decode_cid_mmc(uint32_t *raw_cid, struct mmc_cid *cid, bool is_4_41p)
1125{
1126        int i;
1127
1128        /* There's no version info, so we take it on faith */
1129        memset(cid, 0, sizeof(*cid));
1130        cid->mid = mmc_get_bits(raw_cid, 128, 120, 8);
1131        cid->oid = mmc_get_bits(raw_cid, 128, 104, 8);
1132        for (i = 0; i < 6; i++)
1133                cid->pnm[i] = mmc_get_bits(raw_cid, 128, 96 - i * 8, 8);
1134        cid->pnm[6] = 0;
1135        cid->prv = mmc_get_bits(raw_cid, 128, 48, 8);
1136        cid->psn = mmc_get_bits(raw_cid, 128, 16, 32);
1137        cid->mdt_month = mmc_get_bits(raw_cid, 128, 12, 4);
1138        cid->mdt_year = mmc_get_bits(raw_cid, 128, 8, 4);
1139        if (is_4_41p)
1140                cid->mdt_year += 2013;
1141        else
1142                cid->mdt_year += 1997;
1143}
1144
1145static void
1146mmc_format_card_id_string(struct mmc_ivars *ivar)
1147{
1148        char oidstr[8];
1149        uint8_t c1;
1150        uint8_t c2;
1151
1152        /*
1153         * Format a card ID string for use by the mmcsd driver, it's what
1154         * appears between the <> in the following:
1155         * mmcsd0: 968MB <SD SD01G 8.0 SN 2686905 MFG 08/2008 by 3 TN> at mmc0
1156         * 22.5MHz/4bit/128-block
1157         *
1158         * Also format just the card serial number, which the mmcsd driver will
1159         * use as the disk->d_ident string.
1160         *
1161         * The card_id_string in mmc_ivars is currently allocated as 64 bytes,
1162         * and our max formatted length is currently 55 bytes if every field
1163         * contains the largest value.
1164         *
1165         * Sometimes the oid is two printable ascii chars; when it's not,
1166         * format it as 0xnnnn instead.
1167         */
1168        c1 = (ivar->cid.oid >> 8) & 0x0ff;
1169        c2 = ivar->cid.oid & 0x0ff;
1170        if (c1 > 0x1f && c1 < 0x7f && c2 > 0x1f && c2 < 0x7f)
1171                snprintf(oidstr, sizeof(oidstr), "%c%c", c1, c2);
1172        else
1173                snprintf(oidstr, sizeof(oidstr), "0x%04x", ivar->cid.oid);
1174        snprintf(ivar->card_sn_string, sizeof(ivar->card_sn_string),
1175            "%08X", ivar->cid.psn);
1176        snprintf(ivar->card_id_string, sizeof(ivar->card_id_string),
1177            "%s%s %s %d.%d SN %08X MFG %02d/%04d by %d %s",
1178            ivar->mode == mode_sd ? "SD" : "MMC", ivar->high_cap ? "HC" : "",
1179            ivar->cid.pnm, ivar->cid.prv >> 4, ivar->cid.prv & 0x0f,
1180            ivar->cid.psn, ivar->cid.mdt_month, ivar->cid.mdt_year,
1181            ivar->cid.mid, oidstr);
1182}
1183
1184static const int exp[8] = {
1185        1, 10, 100, 1000, 10000, 100000, 1000000, 10000000
1186};
1187
1188static const int mant[16] = {
1189        0, 10, 12, 13, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 70, 80
1190};
1191
1192static const int cur_min[8] = {
1193        500, 1000, 5000, 10000, 25000, 35000, 60000, 100000
1194};
1195
1196static const int cur_max[8] = {
1197        1000, 5000, 10000, 25000, 35000, 45000, 800000, 200000
1198};
1199
1200static int
1201mmc_decode_csd_sd(uint32_t *raw_csd, struct mmc_csd *csd)
1202{
1203        int v;
1204        int m;
1205        int e;
1206
1207        memset(csd, 0, sizeof(*csd));
1208        csd->csd_structure = v = mmc_get_bits(raw_csd, 128, 126, 2);
1209        if (v == 0) {
1210                m = mmc_get_bits(raw_csd, 128, 115, 4);
1211                e = mmc_get_bits(raw_csd, 128, 112, 3);
1212                csd->tacc = (exp[e] * mant[m] + 9) / 10;
1213                csd->nsac = mmc_get_bits(raw_csd, 128, 104, 8) * 100;
1214                m = mmc_get_bits(raw_csd, 128, 99, 4);
1215                e = mmc_get_bits(raw_csd, 128, 96, 3);
1216                csd->tran_speed = exp[e] * 10000 * mant[m];
1217                csd->ccc = mmc_get_bits(raw_csd, 128, 84, 12);
1218                csd->read_bl_len = 1 << mmc_get_bits(raw_csd, 128, 80, 4);
1219                csd->read_bl_partial = mmc_get_bits(raw_csd, 128, 79, 1);
1220                csd->write_blk_misalign = mmc_get_bits(raw_csd, 128, 78, 1);
1221                csd->read_blk_misalign = mmc_get_bits(raw_csd, 128, 77, 1);
1222                csd->dsr_imp = mmc_get_bits(raw_csd, 128, 76, 1);
1223                csd->vdd_r_curr_min =
1224                    cur_min[mmc_get_bits(raw_csd, 128, 59, 3)];
1225                csd->vdd_r_curr_max =
1226                    cur_max[mmc_get_bits(raw_csd, 128, 56, 3)];
1227                csd->vdd_w_curr_min =
1228                    cur_min[mmc_get_bits(raw_csd, 128, 53, 3)];
1229                csd->vdd_w_curr_max =
1230                    cur_max[mmc_get_bits(raw_csd, 128, 50, 3)];
1231                m = mmc_get_bits(raw_csd, 128, 62, 12);
1232                e = mmc_get_bits(raw_csd, 128, 47, 3);
1233                csd->capacity = ((1 + m) << (e + 2)) * csd->read_bl_len;
1234                csd->erase_blk_en = mmc_get_bits(raw_csd, 128, 46, 1);
1235                csd->erase_sector = mmc_get_bits(raw_csd, 128, 39, 7) + 1;
1236                csd->wp_grp_size = mmc_get_bits(raw_csd, 128, 32, 7);
1237                csd->wp_grp_enable = mmc_get_bits(raw_csd, 128, 31, 1);
1238                csd->r2w_factor = 1 << mmc_get_bits(raw_csd, 128, 26, 3);
1239                csd->write_bl_len = 1 << mmc_get_bits(raw_csd, 128, 22, 4);
1240                csd->write_bl_partial = mmc_get_bits(raw_csd, 128, 21, 1);
1241                return (MMC_ERR_NONE);
1242        } else if (v == 1) {
1243                m = mmc_get_bits(raw_csd, 128, 115, 4);
1244                e = mmc_get_bits(raw_csd, 128, 112, 3);
1245                csd->tacc = (exp[e] * mant[m] + 9) / 10;
1246                csd->nsac = mmc_get_bits(raw_csd, 128, 104, 8) * 100;
1247                m = mmc_get_bits(raw_csd, 128, 99, 4);
1248                e = mmc_get_bits(raw_csd, 128, 96, 3);
1249                csd->tran_speed = exp[e] * 10000 * mant[m];
1250                csd->ccc = mmc_get_bits(raw_csd, 128, 84, 12);
1251                csd->read_bl_len = 1 << mmc_get_bits(raw_csd, 128, 80, 4);
1252                csd->read_bl_partial = mmc_get_bits(raw_csd, 128, 79, 1);
1253                csd->write_blk_misalign = mmc_get_bits(raw_csd, 128, 78, 1);
1254                csd->read_blk_misalign = mmc_get_bits(raw_csd, 128, 77, 1);
1255                csd->dsr_imp = mmc_get_bits(raw_csd, 128, 76, 1);
1256                csd->capacity = ((uint64_t)mmc_get_bits(raw_csd, 128, 48, 22) +
1257                    1) * 512 * 1024;
1258                csd->erase_blk_en = mmc_get_bits(raw_csd, 128, 46, 1);
1259                csd->erase_sector = mmc_get_bits(raw_csd, 128, 39, 7) + 1;
1260                csd->wp_grp_size = mmc_get_bits(raw_csd, 128, 32, 7);
1261                csd->wp_grp_enable = mmc_get_bits(raw_csd, 128, 31, 1);
1262                csd->r2w_factor = 1 << mmc_get_bits(raw_csd, 128, 26, 3);
1263                csd->write_bl_len = 1 << mmc_get_bits(raw_csd, 128, 22, 4);
1264                csd->write_bl_partial = mmc_get_bits(raw_csd, 128, 21, 1);
1265                return (MMC_ERR_NONE);
1266        }
1267        return (MMC_ERR_INVALID);
1268}
1269
1270static void
1271mmc_decode_csd_mmc(uint32_t *raw_csd, struct mmc_csd *csd)
1272{
1273        int m;
1274        int e;
1275
1276        memset(csd, 0, sizeof(*csd));
1277        csd->csd_structure = mmc_get_bits(raw_csd, 128, 126, 2);
1278        csd->spec_vers = mmc_get_bits(raw_csd, 128, 122, 4);
1279        m = mmc_get_bits(raw_csd, 128, 115, 4);
1280        e = mmc_get_bits(raw_csd, 128, 112, 3);
1281        csd->tacc = exp[e] * mant[m] + 9 / 10;
1282        csd->nsac = mmc_get_bits(raw_csd, 128, 104, 8) * 100;
1283        m = mmc_get_bits(raw_csd, 128, 99, 4);
1284        e = mmc_get_bits(raw_csd, 128, 96, 3);
1285        csd->tran_speed = exp[e] * 10000 * mant[m];
1286        csd->ccc = mmc_get_bits(raw_csd, 128, 84, 12);
1287        csd->read_bl_len = 1 << mmc_get_bits(raw_csd, 128, 80, 4);
1288        csd->read_bl_partial = mmc_get_bits(raw_csd, 128, 79, 1);
1289        csd->write_blk_misalign = mmc_get_bits(raw_csd, 128, 78, 1);
1290        csd->read_blk_misalign = mmc_get_bits(raw_csd, 128, 77, 1);
1291        csd->dsr_imp = mmc_get_bits(raw_csd, 128, 76, 1);
1292        csd->vdd_r_curr_min = cur_min[mmc_get_bits(raw_csd, 128, 59, 3)];
1293        csd->vdd_r_curr_max = cur_max[mmc_get_bits(raw_csd, 128, 56, 3)];
1294        csd->vdd_w_curr_min = cur_min[mmc_get_bits(raw_csd, 128, 53, 3)];
1295        csd->vdd_w_curr_max = cur_max[mmc_get_bits(raw_csd, 128, 50, 3)];
1296        m = mmc_get_bits(raw_csd, 128, 62, 12);
1297        e = mmc_get_bits(raw_csd, 128, 47, 3);
1298        csd->capacity = ((1 + m) << (e + 2)) * csd->read_bl_len;
1299        csd->erase_blk_en = 0;
1300        csd->erase_sector = (mmc_get_bits(raw_csd, 128, 42, 5) + 1) *
1301            (mmc_get_bits(raw_csd, 128, 37, 5) + 1);
1302        csd->wp_grp_size = mmc_get_bits(raw_csd, 128, 32, 5);
1303        csd->wp_grp_enable = mmc_get_bits(raw_csd, 128, 31, 1);
1304        csd->r2w_factor = 1 << mmc_get_bits(raw_csd, 128, 26, 3);
1305        csd->write_bl_len = 1 << mmc_get_bits(raw_csd, 128, 22, 4);
1306        csd->write_bl_partial = mmc_get_bits(raw_csd, 128, 21, 1);
1307}
1308
1309static void
1310mmc_app_decode_scr(uint32_t *raw_scr, struct mmc_scr *scr)
1311{
1312        unsigned int scr_struct;
1313
1314        memset(scr, 0, sizeof(*scr));
1315
1316        scr_struct = mmc_get_bits(raw_scr, 64, 60, 4);
1317        if (scr_struct != 0) {
1318                printf("Unrecognised SCR structure version %d\n",
1319                    scr_struct);
1320                return;
1321        }
1322        scr->sda_vsn = mmc_get_bits(raw_scr, 64, 56, 4);
1323        scr->bus_widths = mmc_get_bits(raw_scr, 64, 48, 4);
1324}
1325
1326static void
1327mmc_app_decode_sd_status(uint32_t *raw_sd_status,
1328    struct mmc_sd_status *sd_status)
1329{
1330
1331        memset(sd_status, 0, sizeof(*sd_status));
1332
1333        sd_status->bus_width = mmc_get_bits(raw_sd_status, 512, 510, 2);
1334        sd_status->secured_mode = mmc_get_bits(raw_sd_status, 512, 509, 1);
1335        sd_status->card_type = mmc_get_bits(raw_sd_status, 512, 480, 16);
1336        sd_status->prot_area = mmc_get_bits(raw_sd_status, 512, 448, 12);
1337        sd_status->speed_class = mmc_get_bits(raw_sd_status, 512, 440, 8);
1338        sd_status->perf_move = mmc_get_bits(raw_sd_status, 512, 432, 8);
1339        sd_status->au_size = mmc_get_bits(raw_sd_status, 512, 428, 4);
1340        sd_status->erase_size = mmc_get_bits(raw_sd_status, 512, 408, 16);
1341        sd_status->erase_timeout = mmc_get_bits(raw_sd_status, 512, 402, 6);
1342        sd_status->erase_offset = mmc_get_bits(raw_sd_status, 512, 400, 2);
1343}
1344
1345static int
1346mmc_all_send_cid(struct mmc_softc *sc, uint32_t *rawcid)
1347{
1348        struct mmc_command cmd;
1349        int err;
1350
1351        memset(&cmd, 0, sizeof(cmd));
1352        cmd.opcode = MMC_ALL_SEND_CID;
1353        cmd.arg = 0;
1354        cmd.flags = MMC_RSP_R2 | MMC_CMD_BCR;
1355        cmd.data = NULL;
1356        err = mmc_wait_for_cmd(sc->dev, sc->dev, &cmd, CMD_RETRIES);
1357        memcpy(rawcid, cmd.resp, 4 * sizeof(uint32_t));
1358        return (err);
1359}
1360
1361static int
1362mmc_send_csd(struct mmc_softc *sc, uint16_t rca, uint32_t *rawcsd)
1363{
1364        struct mmc_command cmd;
1365        int err;
1366
1367        memset(&cmd, 0, sizeof(cmd));
1368        cmd.opcode = MMC_SEND_CSD;
1369        cmd.arg = rca << 16;
1370        cmd.flags = MMC_RSP_R2 | MMC_CMD_BCR;
1371        cmd.data = NULL;
1372        err = mmc_wait_for_cmd(sc->dev, sc->dev, &cmd, CMD_RETRIES);
1373        memcpy(rawcsd, cmd.resp, 4 * sizeof(uint32_t));
1374        return (err);
1375}
1376
1377static int
1378mmc_app_send_scr(struct mmc_softc *sc, uint16_t rca, uint32_t *rawscr)
1379{
1380        int err;
1381        struct mmc_command cmd;
1382        struct mmc_data data;
1383
1384        memset(&cmd, 0, sizeof(cmd));
1385        memset(&data, 0, sizeof(data));
1386
1387        memset(rawscr, 0, 8);
1388        cmd.opcode = ACMD_SEND_SCR;
1389        cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
1390        cmd.arg = 0;
1391        cmd.data = &data;
1392
1393        data.data = rawscr;
1394        data.len = 8;
1395        data.flags = MMC_DATA_READ;
1396
1397        err = mmc_wait_for_app_cmd(sc->dev, sc->dev, rca, &cmd, CMD_RETRIES);
1398        rawscr[0] = be32toh(rawscr[0]);
1399        rawscr[1] = be32toh(rawscr[1]);
1400        return (err);
1401}
1402
1403static int
1404mmc_app_sd_status(struct mmc_softc *sc, uint16_t rca, uint32_t *rawsdstatus)
1405{
1406        struct mmc_command cmd;
1407        struct mmc_data data;
1408        int err, i;
1409
1410        memset(&cmd, 0, sizeof(cmd));
1411        memset(&data, 0, sizeof(data));
1412
1413        memset(rawsdstatus, 0, 64);
1414        cmd.opcode = ACMD_SD_STATUS;
1415        cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
1416        cmd.arg = 0;
1417        cmd.data = &data;
1418
1419        data.data = rawsdstatus;
1420        data.len = 64;
1421        data.flags = MMC_DATA_READ;
1422
1423        err = mmc_wait_for_app_cmd(sc->dev, sc->dev, rca, &cmd, CMD_RETRIES);
1424        for (i = 0; i < 16; i++)
1425            rawsdstatus[i] = be32toh(rawsdstatus[i]);
1426        return (err);
1427}
1428
1429static int
1430mmc_set_relative_addr(struct mmc_softc *sc, uint16_t resp)
1431{
1432        struct mmc_command cmd;
1433        int err;
1434
1435        memset(&cmd, 0, sizeof(cmd));
1436        cmd.opcode = MMC_SET_RELATIVE_ADDR;
1437        cmd.arg = resp << 16;
1438        cmd.flags = MMC_RSP_R6 | MMC_CMD_BCR;
1439        cmd.data = NULL;
1440        err = mmc_wait_for_cmd(sc->dev, sc->dev, &cmd, CMD_RETRIES);
1441        return (err);
1442}
1443
1444static int
1445mmc_send_relative_addr(struct mmc_softc *sc, uint32_t *resp)
1446{
1447        struct mmc_command cmd;
1448        int err;
1449
1450        memset(&cmd, 0, sizeof(cmd));
1451        cmd.opcode = SD_SEND_RELATIVE_ADDR;
1452        cmd.arg = 0;
1453        cmd.flags = MMC_RSP_R6 | MMC_CMD_BCR;
1454        cmd.data = NULL;
1455        err = mmc_wait_for_cmd(sc->dev, sc->dev, &cmd, CMD_RETRIES);
1456        *resp = cmd.resp[0];
1457        return (err);
1458}
1459
1460static int
1461mmc_set_blocklen(struct mmc_softc *sc, uint32_t len)
1462{
1463        struct mmc_command cmd;
1464        int err;
1465
1466        memset(&cmd, 0, sizeof(cmd));
1467        cmd.opcode = MMC_SET_BLOCKLEN;
1468        cmd.arg = len;
1469        cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
1470        cmd.data = NULL;
1471        err = mmc_wait_for_cmd(sc->dev, sc->dev, &cmd, CMD_RETRIES);
1472        return (err);
1473}
1474
1475static uint32_t
1476mmc_timing_to_dtr(struct mmc_ivars *ivar, enum mmc_bus_timing timing)
1477{
1478
1479        switch (timing) {
1480        case bus_timing_normal:
1481                return (ivar->tran_speed);
1482        case bus_timing_hs:
1483                return (ivar->hs_tran_speed);
1484        case bus_timing_uhs_sdr12:
1485                return (SD_SDR12_MAX);
1486        case bus_timing_uhs_sdr25:
1487                return (SD_SDR25_MAX);
1488        case bus_timing_uhs_ddr50:
1489                return (SD_DDR50_MAX);
1490        case bus_timing_uhs_sdr50:
1491                return (SD_SDR50_MAX);
1492        case bus_timing_uhs_sdr104:
1493                return (SD_SDR104_MAX);
1494        case bus_timing_mmc_ddr52:
1495                return (MMC_TYPE_DDR52_MAX);
1496        case bus_timing_mmc_hs200:
1497        case bus_timing_mmc_hs400:
1498        case bus_timing_mmc_hs400es:
1499                return (MMC_TYPE_HS200_HS400ES_MAX);
1500        }
1501        return (0);
1502}
1503
1504static const char *
1505mmc_timing_to_string(enum mmc_bus_timing timing)
1506{
1507
1508        switch (timing) {
1509        case bus_timing_normal:
1510                return ("normal speed");
1511        case bus_timing_hs:
1512                return ("high speed");
1513        case bus_timing_uhs_sdr12:
1514        case bus_timing_uhs_sdr25:
1515        case bus_timing_uhs_sdr50:
1516        case bus_timing_uhs_sdr104:
1517                return ("single data rate");
1518        case bus_timing_uhs_ddr50:
1519        case bus_timing_mmc_ddr52:
1520                return ("dual data rate");
1521        case bus_timing_mmc_hs200:
1522                return ("HS200");
1523        case bus_timing_mmc_hs400:
1524                return ("HS400");
1525        case bus_timing_mmc_hs400es:
1526                return ("HS400 with enhanced strobe");
1527        }
1528        return ("");
1529}
1530
1531static bool
1532mmc_host_timing(device_t dev, enum mmc_bus_timing timing)
1533{
1534        int host_caps;
1535
1536        host_caps = mmcbr_get_caps(dev);
1537
1538#define HOST_TIMING_CAP(host_caps, cap) ({                              \
1539        bool retval;                                                    \
1540        if (((host_caps) & (cap)) == (cap))                             \
1541                retval = true;                                          \
1542        else                                                            \
1543                retval = false;                                         \
1544        retval;                                                         \
1545})
1546
1547        switch (timing) {
1548        case bus_timing_normal:
1549                return (true);
1550        case bus_timing_hs:
1551                return (HOST_TIMING_CAP(host_caps, MMC_CAP_HSPEED));
1552        case bus_timing_uhs_sdr12:
1553                return (HOST_TIMING_CAP(host_caps, MMC_CAP_UHS_SDR12));
1554        case bus_timing_uhs_sdr25:
1555                return (HOST_TIMING_CAP(host_caps, MMC_CAP_UHS_SDR25));
1556        case bus_timing_uhs_ddr50:
1557                return (HOST_TIMING_CAP(host_caps, MMC_CAP_UHS_DDR50));
1558        case bus_timing_uhs_sdr50:
1559                return (HOST_TIMING_CAP(host_caps, MMC_CAP_UHS_SDR50));
1560        case bus_timing_uhs_sdr104:
1561                return (HOST_TIMING_CAP(host_caps, MMC_CAP_UHS_SDR104));
1562        case bus_timing_mmc_ddr52:
1563                return (HOST_TIMING_CAP(host_caps, MMC_CAP_MMC_DDR52));
1564        case bus_timing_mmc_hs200:
1565                return (HOST_TIMING_CAP(host_caps, MMC_CAP_MMC_HS200));
1566        case bus_timing_mmc_hs400:
1567                return (HOST_TIMING_CAP(host_caps, MMC_CAP_MMC_HS400));
1568        case bus_timing_mmc_hs400es:
1569                return (HOST_TIMING_CAP(host_caps, MMC_CAP_MMC_HS400 |
1570                    MMC_CAP_MMC_ENH_STROBE));
1571        }
1572
1573#undef HOST_TIMING_CAP
1574
1575        return (false);
1576}
1577
1578static void
1579mmc_log_card(device_t dev, struct mmc_ivars *ivar, int newcard)
1580{
1581        enum mmc_bus_timing timing;
1582
1583        device_printf(dev, "Card at relative address 0x%04x%s:\n",
1584            ivar->rca, newcard ? " added" : "");
1585        device_printf(dev, " card: %s\n", ivar->card_id_string);
1586        for (timing = bus_timing_max; timing > bus_timing_normal; timing--) {
1587                if (isset(&ivar->timings, timing))
1588                        break;
1589        }
1590        device_printf(dev, " quirks: %b\n", ivar->quirks, MMC_QUIRKS_FMT);
1591        device_printf(dev, " bus: %ubit, %uMHz (%s timing)\n",
1592            (ivar->bus_width == bus_width_1 ? 1 :
1593            (ivar->bus_width == bus_width_4 ? 4 : 8)),
1594            mmc_timing_to_dtr(ivar, timing) / 1000000,
1595            mmc_timing_to_string(timing));
1596        device_printf(dev, " memory: %u blocks, erase sector %u blocks%s\n",
1597            ivar->sec_count, ivar->erase_sector,
1598            ivar->read_only ? ", read-only" : "");
1599}
1600
1601static void
1602mmc_discover_cards(struct mmc_softc *sc)
1603{
1604        u_char switch_res[64];
1605        uint32_t raw_cid[4];
1606        struct mmc_ivars *ivar = NULL;
1607        const struct mmc_quirk *quirk;
1608        const uint8_t *ext_csd;
1609        device_t child;
1610        int err, host_caps, i, newcard;
1611        uint32_t resp, sec_count, status;
1612        uint16_t rca = 2;
1613        int16_t rev;
1614        uint8_t card_type;
1615
1616        host_caps = mmcbr_get_caps(sc->dev);
1617        if (bootverbose || mmc_debug)
1618                device_printf(sc->dev, "Probing cards\n");
1619        while (1) {
1620                child = NULL;
1621                sc->squelched++; /* Errors are expected, squelch reporting. */
1622                err = mmc_all_send_cid(sc, raw_cid);
1623                sc->squelched--;
1624                if (err == MMC_ERR_TIMEOUT)
1625                        break;
1626                if (err != MMC_ERR_NONE) {
1627                        device_printf(sc->dev, "Error reading CID %d\n", err);
1628                        break;
1629                }
1630                newcard = 1;
1631                for (i = 0; i < sc->child_count; i++) {
1632                        ivar = device_get_ivars(sc->child_list[i]);
1633                        if (memcmp(ivar->raw_cid, raw_cid, sizeof(raw_cid)) ==
1634                            0) {
1635                                newcard = 0;
1636                                break;
1637                        }
1638                }
1639                if (bootverbose || mmc_debug) {
1640                        device_printf(sc->dev,
1641                            "%sard detected (CID %08x%08x%08x%08x)\n",
1642                            newcard ? "New c" : "C",
1643                            raw_cid[0], raw_cid[1], raw_cid[2], raw_cid[3]);
1644                }
1645                if (newcard) {
1646                        ivar = malloc(sizeof(struct mmc_ivars), M_DEVBUF,
1647                            M_WAITOK | M_ZERO);
1648                        memcpy(ivar->raw_cid, raw_cid, sizeof(raw_cid));
1649                }
1650                if (mmcbr_get_ro(sc->dev))
1651                        ivar->read_only = 1;
1652                ivar->bus_width = bus_width_1;
1653                setbit(&ivar->timings, bus_timing_normal);
1654                ivar->mode = mmcbr_get_mode(sc->dev);
1655                if (ivar->mode == mode_sd) {
1656                        mmc_decode_cid_sd(ivar->raw_cid, &ivar->cid);
1657                        err = mmc_send_relative_addr(sc, &resp);
1658                        if (err != MMC_ERR_NONE) {
1659                                device_printf(sc->dev,
1660                                    "Error getting RCA %d\n", err);
1661                                goto free_ivar;
1662                        }
1663                        ivar->rca = resp >> 16;
1664                        /* Get card CSD. */
1665                        err = mmc_send_csd(sc, ivar->rca, ivar->raw_csd);
1666                        if (err != MMC_ERR_NONE) {
1667                                device_printf(sc->dev,
1668                                    "Error getting CSD %d\n", err);
1669                                goto free_ivar;
1670                        }
1671                        if (bootverbose || mmc_debug)
1672                                device_printf(sc->dev,
1673                                    "%sard detected (CSD %08x%08x%08x%08x)\n",
1674                                    newcard ? "New c" : "C", ivar->raw_csd[0],
1675                                    ivar->raw_csd[1], ivar->raw_csd[2],
1676                                    ivar->raw_csd[3]);
1677                        err = mmc_decode_csd_sd(ivar->raw_csd, &ivar->csd);
1678                        if (err != MMC_ERR_NONE) {
1679                                device_printf(sc->dev, "Error decoding CSD\n");
1680                                goto free_ivar;
1681                        }
1682                        ivar->sec_count = ivar->csd.capacity / MMC_SECTOR_SIZE;
1683                        if (ivar->csd.csd_structure > 0)
1684                                ivar->high_cap = 1;
1685                        ivar->tran_speed = ivar->csd.tran_speed;
1686                        ivar->erase_sector = ivar->csd.erase_sector *
1687                            ivar->csd.write_bl_len / MMC_SECTOR_SIZE;
1688
1689                        err = mmc_send_status(sc->dev, sc->dev, ivar->rca,
1690                            &status);
1691                        if (err != MMC_ERR_NONE) {
1692                                device_printf(sc->dev,
1693                                    "Error reading card status %d\n", err);
1694                                goto free_ivar;
1695                        }
1696                        if ((status & R1_CARD_IS_LOCKED) != 0) {
1697                                device_printf(sc->dev,
1698                                    "Card is password protected, skipping\n");
1699                                goto free_ivar;
1700                        }
1701
1702                        /* Get card SCR.  Card must be selected to fetch it. */
1703                        err = mmc_select_card(sc, ivar->rca);
1704                        if (err != MMC_ERR_NONE) {
1705                                device_printf(sc->dev,
1706                                    "Error selecting card %d\n", err);
1707                                goto free_ivar;
1708                        }
1709                        err = mmc_app_send_scr(sc, ivar->rca, ivar->raw_scr);
1710                        if (err != MMC_ERR_NONE) {
1711                                device_printf(sc->dev,
1712                                    "Error reading SCR %d\n", err);
1713                                goto free_ivar;
1714                        }
1715                        mmc_app_decode_scr(ivar->raw_scr, &ivar->scr);
1716                        /* Get card switch capabilities (command class 10). */
1717                        if ((ivar->scr.sda_vsn >= 1) &&
1718                            (ivar->csd.ccc & (1 << 10))) {
1719                                err = mmc_sd_switch(sc, SD_SWITCH_MODE_CHECK,
1720                                    SD_SWITCH_GROUP1, SD_SWITCH_NOCHANGE,
1721                                    switch_res);
1722                                if (err == MMC_ERR_NONE &&
1723                                    switch_res[13] & (1 << SD_SWITCH_HS_MODE)) {
1724                                        setbit(&ivar->timings, bus_timing_hs);
1725                                        ivar->hs_tran_speed = SD_HS_MAX;
1726                                }
1727                        }
1728
1729                        /*
1730                         * We deselect then reselect the card here.  Some cards
1731                         * become unselected and timeout with the above two
1732                         * commands, although the state tables / diagrams in the
1733                         * standard suggest they go back to the transfer state.
1734                         * Other cards don't become deselected, and if we
1735                         * attempt to blindly re-select them, we get timeout
1736                         * errors from some controllers.  So we deselect then
1737                         * reselect to handle all situations.  The only thing we
1738                         * use from the sd_status is the erase sector size, but
1739                         * it is still nice to get that right.
1740                         */
1741                        (void)mmc_select_card(sc, 0);
1742                        (void)mmc_select_card(sc, ivar->rca);
1743                        (void)mmc_app_sd_status(sc, ivar->rca,
1744                            ivar->raw_sd_status);
1745                        mmc_app_decode_sd_status(ivar->raw_sd_status,
1746                            &ivar->sd_status);
1747                        if (ivar->sd_status.au_size != 0) {
1748                                ivar->erase_sector =
1749                                    16 << ivar->sd_status.au_size;
1750                        }
1751                        /* Find maximum supported bus width. */
1752                        if ((host_caps & MMC_CAP_4_BIT_DATA) &&
1753                            (ivar->scr.bus_widths & SD_SCR_BUS_WIDTH_4))
1754                                ivar->bus_width = bus_width_4;
1755
1756                        goto child_common;
1757                }
1758                ivar->rca = rca++;
1759                err = mmc_set_relative_addr(sc, ivar->rca);
1760                if (err != MMC_ERR_NONE) {
1761                        device_printf(sc->dev, "Error setting RCA %d\n", err);
1762                        goto free_ivar;
1763                }
1764                /* Get card CSD. */
1765                err = mmc_send_csd(sc, ivar->rca, ivar->raw_csd);
1766                if (err != MMC_ERR_NONE) {
1767                        device_printf(sc->dev, "Error getting CSD %d\n", err);
1768                        goto free_ivar;
1769                }
1770                if (bootverbose || mmc_debug)
1771                        device_printf(sc->dev,
1772                            "%sard detected (CSD %08x%08x%08x%08x)\n",
1773                            newcard ? "New c" : "C", ivar->raw_csd[0],
1774                            ivar->raw_csd[1], ivar->raw_csd[2],
1775                            ivar->raw_csd[3]);
1776
1777                mmc_decode_csd_mmc(ivar->raw_csd, &ivar->csd);
1778                ivar->sec_count = ivar->csd.capacity / MMC_SECTOR_SIZE;
1779                ivar->tran_speed = ivar->csd.tran_speed;
1780                ivar->erase_sector = ivar->csd.erase_sector *
1781                    ivar->csd.write_bl_len / MMC_SECTOR_SIZE;
1782
1783                err = mmc_send_status(sc->dev, sc->dev, ivar->rca, &status);
1784                if (err != MMC_ERR_NONE) {
1785                        device_printf(sc->dev,
1786                            "Error reading card status %d\n", err);
1787                        goto free_ivar;
1788                }
1789                if ((status & R1_CARD_IS_LOCKED) != 0) {
1790                        device_printf(sc->dev,
1791                            "Card is password protected, skipping\n");
1792                        goto free_ivar;
1793                }
1794
1795                err = mmc_select_card(sc, ivar->rca);
1796                if (err != MMC_ERR_NONE) {
1797                        device_printf(sc->dev, "Error selecting card %d\n",
1798                            err);
1799                        goto free_ivar;
1800                }
1801
1802                rev = -1;
1803                /* Only MMC >= 4.x devices support EXT_CSD. */
1804                if (ivar->csd.spec_vers >= 4) {
1805                        err = mmc_send_ext_csd(sc->dev, sc->dev,
1806                            ivar->raw_ext_csd);
1807                        if (err != MMC_ERR_NONE) {
1808                                device_printf(sc->dev,
1809                                    "Error reading EXT_CSD %d\n", err);
1810                                goto free_ivar;
1811                        }
1812                        ext_csd = ivar->raw_ext_csd;
1813                        rev = ext_csd[EXT_CSD_REV];
1814                        /* Handle extended capacity from EXT_CSD */
1815                        sec_count = le32dec(&ext_csd[EXT_CSD_SEC_CNT]);
1816                        if (sec_count != 0) {
1817                                ivar->sec_count = sec_count;
1818                                ivar->high_cap = 1;
1819                        }
1820                        /* Find maximum supported bus width. */
1821                        ivar->bus_width = mmc_test_bus_width(sc);
1822                        /* Get device speeds beyond normal mode. */
1823                        card_type = ext_csd[EXT_CSD_CARD_TYPE];
1824                        if ((card_type & EXT_CSD_CARD_TYPE_HS_52) != 0) {
1825                                setbit(&ivar->timings, bus_timing_hs);
1826                                ivar->hs_tran_speed = MMC_TYPE_HS_52_MAX;
1827                        } else if ((card_type & EXT_CSD_CARD_TYPE_HS_26) != 0) {
1828                                setbit(&ivar->timings, bus_timing_hs);
1829                                ivar->hs_tran_speed = MMC_TYPE_HS_26_MAX;
1830                        }
1831                        if ((card_type & EXT_CSD_CARD_TYPE_DDR_52_1_2V) != 0 &&
1832                            (host_caps & MMC_CAP_SIGNALING_120) != 0) {
1833                                setbit(&ivar->timings, bus_timing_mmc_ddr52);
1834                                setbit(&ivar->vccq_120, bus_timing_mmc_ddr52);
1835                        }
1836                        if ((card_type & EXT_CSD_CARD_TYPE_DDR_52_1_8V) != 0 &&
1837                            (host_caps & MMC_CAP_SIGNALING_180) != 0) {
1838                                setbit(&ivar->timings, bus_timing_mmc_ddr52);
1839                                setbit(&ivar->vccq_180, bus_timing_mmc_ddr52);
1840                        }
1841                        if ((card_type & EXT_CSD_CARD_TYPE_HS200_1_2V) != 0 &&
1842                            (host_caps & MMC_CAP_SIGNALING_120) != 0) {
1843                                setbit(&ivar->timings, bus_timing_mmc_hs200);
1844                                setbit(&ivar->vccq_120, bus_timing_mmc_hs200);
1845                        }
1846                        if ((card_type & EXT_CSD_CARD_TYPE_HS200_1_8V) != 0 &&
1847                            (host_caps & MMC_CAP_SIGNALING_180) != 0) {
1848                                setbit(&ivar->timings, bus_timing_mmc_hs200);
1849                                setbit(&ivar->vccq_180, bus_timing_mmc_hs200);
1850                        }
1851                        if ((card_type & EXT_CSD_CARD_TYPE_HS400_1_2V) != 0 &&
1852                            (host_caps & MMC_CAP_SIGNALING_120) != 0 &&
1853                            ivar->bus_width == bus_width_8) {
1854                                setbit(&ivar->timings, bus_timing_mmc_hs400);
1855                                setbit(&ivar->vccq_120, bus_timing_mmc_hs400);
1856                        }
1857                        if ((card_type & EXT_CSD_CARD_TYPE_HS400_1_8V) != 0 &&
1858                            (host_caps & MMC_CAP_SIGNALING_180) != 0 &&
1859                            ivar->bus_width == bus_width_8) {
1860                                setbit(&ivar->timings, bus_timing_mmc_hs400);
1861                                setbit(&ivar->vccq_180, bus_timing_mmc_hs400);
1862                        }
1863                        if ((card_type & EXT_CSD_CARD_TYPE_HS400_1_2V) != 0 &&
1864                            (ext_csd[EXT_CSD_STROBE_SUPPORT] &
1865                            EXT_CSD_STROBE_SUPPORT_EN) != 0 &&
1866                            (host_caps & MMC_CAP_SIGNALING_120) != 0 &&
1867                            ivar->bus_width == bus_width_8) {
1868                                setbit(&ivar->timings, bus_timing_mmc_hs400es);
1869                                setbit(&ivar->vccq_120, bus_timing_mmc_hs400es);
1870                        }
1871                        if ((card_type & EXT_CSD_CARD_TYPE_HS400_1_8V) != 0 &&
1872                            (ext_csd[EXT_CSD_STROBE_SUPPORT] &
1873                            EXT_CSD_STROBE_SUPPORT_EN) != 0 &&
1874                            (host_caps & MMC_CAP_SIGNALING_180) != 0 &&
1875                            ivar->bus_width == bus_width_8) {
1876                                setbit(&ivar->timings, bus_timing_mmc_hs400es);
1877                                setbit(&ivar->vccq_180, bus_timing_mmc_hs400es);
1878                        }
1879                        /*
1880                         * Determine generic switch timeout (provided in
1881                         * units of 10 ms), defaulting to 500 ms.
1882                         */
1883                        ivar->cmd6_time = 500 * 1000;
1884                        if (rev >= 6)
1885                                ivar->cmd6_time = 10 *
1886                                    ext_csd[EXT_CSD_GEN_CMD6_TIME];
1887                        /* Handle HC erase sector size. */
1888                        if (ext_csd[EXT_CSD_ERASE_GRP_SIZE] != 0) {
1889                                ivar->erase_sector = 1024 *
1890                                    ext_csd[EXT_CSD_ERASE_GRP_SIZE];
1891                                err = mmc_switch(sc->dev, sc->dev, ivar->rca,
1892                                    EXT_CSD_CMD_SET_NORMAL,
1893                                    EXT_CSD_ERASE_GRP_DEF,
1894                                    EXT_CSD_ERASE_GRP_DEF_EN,
1895                                    ivar->cmd6_time, true);
1896                                if (err != MMC_ERR_NONE) {
1897                                        device_printf(sc->dev,
1898                                            "Error setting erase group %d\n",
1899                                            err);
1900                                        goto free_ivar;
1901                                }
1902                        }
1903                }
1904
1905                mmc_decode_cid_mmc(ivar->raw_cid, &ivar->cid, rev >= 5);
1906
1907child_common:
1908                for (quirk = &mmc_quirks[0]; quirk->mid != 0x0; quirk++) {
1909                        if ((quirk->mid == MMC_QUIRK_MID_ANY ||
1910                            quirk->mid == ivar->cid.mid) &&
1911                            (quirk->oid == MMC_QUIRK_OID_ANY ||
1912                            quirk->oid == ivar->cid.oid) &&
1913                            strncmp(quirk->pnm, ivar->cid.pnm,
1914                            sizeof(ivar->cid.pnm)) == 0) {
1915                                ivar->quirks = quirk->quirks;
1916                                break;
1917                        }
1918                }
1919
1920                /*
1921                 * Some cards that report maximum I/O block sizes greater
1922                 * than 512 require the block length to be set to 512, even
1923                 * though that is supposed to be the default.  Example:
1924                 *
1925                 * Transcend 2GB SDSC card, CID:
1926                 * mid=0x1b oid=0x534d pnm="00000" prv=1.0 mdt=00.2000
1927                 */
1928                if (ivar->csd.read_bl_len != MMC_SECTOR_SIZE ||
1929                    ivar->csd.write_bl_len != MMC_SECTOR_SIZE)
1930                        mmc_set_blocklen(sc, MMC_SECTOR_SIZE);
1931
1932                mmc_format_card_id_string(ivar);
1933
1934                if (bootverbose || mmc_debug)
1935                        mmc_log_card(sc->dev, ivar, newcard);
1936                if (newcard) {
1937                        /* Add device. */
1938                        child = device_add_child(sc->dev, NULL, -1);
1939                        if (child != NULL) {
1940                                device_set_ivars(child, ivar);
1941                                sc->child_list = realloc(sc->child_list,
1942                                    sizeof(device_t) * sc->child_count + 1,
1943                                    M_DEVBUF, M_WAITOK);
1944                                sc->child_list[sc->child_count++] = child;
1945                        } else
1946                                device_printf(sc->dev, "Error adding child\n");
1947                }
1948
1949free_ivar:
1950                if (newcard && child == NULL)
1951                        free(ivar, M_DEVBUF);
1952                (void)mmc_select_card(sc, 0);
1953                /*
1954                 * Not returning here when one MMC device could no be added
1955                 * potentially would mean looping forever when that device
1956                 * is broken (in which case it also may impact the remainder
1957                 * of the bus anyway, though).
1958                 */
1959                if ((newcard && child == NULL) ||
1960                    mmcbr_get_mode(sc->dev) == mode_sd)
1961                        return;
1962        }
1963}
1964
1965static void
1966mmc_update_child_list(struct mmc_softc *sc)
1967{
1968        device_t child;
1969        int i, j;
1970
1971        if (sc->child_count == 0) {
1972                free(sc->child_list, M_DEVBUF);
1973                return;
1974        }
1975        for (i = j = 0; i < sc->child_count; i++) {
1976                for (;;) {
1977                        child = sc->child_list[j++];
1978                        if (child != NULL)
1979                                break;
1980                }
1981                if (i != j)
1982                        sc->child_list[i] = child;
1983        }
1984        sc->child_list = realloc(sc->child_list, sizeof(device_t) *
1985            sc->child_count, M_DEVBUF, M_WAITOK);
1986}
1987
1988static void
1989mmc_rescan_cards(struct mmc_softc *sc)
1990{
1991        struct mmc_ivars *ivar;
1992        int err, i, j;
1993
1994        for (i = j = 0; i < sc->child_count; i++) {
1995                ivar = device_get_ivars(sc->child_list[i]);
1996                if (mmc_select_card(sc, ivar->rca) != MMC_ERR_NONE) {
1997                        if (bootverbose || mmc_debug)
1998                                device_printf(sc->dev,
1999                                    "Card at relative address %d lost\n",
2000                                    ivar->rca);
2001                        err = device_delete_child(sc->dev, sc->child_list[i]);
2002                        if (err != 0) {
2003                                j++;
2004                                continue;
2005                        }
2006                        free(ivar, M_DEVBUF);
2007                } else
2008                        j++;
2009        }
2010        if (sc->child_count == j)
2011                goto out;
2012        sc->child_count = j;
2013        mmc_update_child_list(sc);
2014out:
2015        (void)mmc_select_card(sc, 0);
2016}
2017
2018static int
2019mmc_delete_cards(struct mmc_softc *sc, bool final)
2020{
2021        struct mmc_ivars *ivar;
2022        int err, i, j;
2023
2024        err = 0;
2025        for (i = j = 0; i < sc->child_count; i++) {
2026                ivar = device_get_ivars(sc->child_list[i]);
2027                if (bootverbose || mmc_debug)
2028                        device_printf(sc->dev,
2029                            "Card at relative address %d deleted\n",
2030                            ivar->rca);
2031                err = device_delete_child(sc->dev, sc->child_list[i]);
2032                if (err != 0) {
2033                        j++;
2034                        if (final == false)
2035                                continue;
2036                        else
2037                                break;
2038                }
2039                free(ivar, M_DEVBUF);
2040        }
2041        sc->child_count = j;
2042        mmc_update_child_list(sc);
2043        return (err);
2044}
2045
2046static void
2047mmc_go_discovery(struct mmc_softc *sc)
2048{
2049        uint32_t ocr;
2050        device_t dev;
2051        int err;
2052
2053        dev = sc->dev;
2054        if (mmcbr_get_power_mode(dev) != power_on) {
2055                /*
2056                 * First, try SD modes
2057                 */
2058                sc->squelched++; /* Errors are expected, squelch reporting. */
2059                mmcbr_set_mode(dev, mode_sd);
2060                mmc_power_up(sc);
2061                mmcbr_set_bus_mode(dev, pushpull);
2062                if (bootverbose || mmc_debug)
2063                        device_printf(sc->dev, "Probing bus\n");
2064                mmc_idle_cards(sc);
2065                err = mmc_send_if_cond(sc, 1);
2066                if ((bootverbose || mmc_debug) && err == 0)
2067                        device_printf(sc->dev,
2068                            "SD 2.0 interface conditions: OK\n");
2069                if (mmc_send_app_op_cond(sc, 0, &ocr) != MMC_ERR_NONE) {
2070                        if (bootverbose || mmc_debug)
2071                                device_printf(sc->dev, "SD probe: failed\n");
2072                        /*
2073                         * Failed, try MMC
2074                         */
2075                        mmcbr_set_mode(dev, mode_mmc);
2076                        if (mmc_send_op_cond(sc, 0, &ocr) != MMC_ERR_NONE) {
2077                                if (bootverbose || mmc_debug)
2078                                        device_printf(sc->dev,
2079                                            "MMC probe: failed\n");
2080                                ocr = 0; /* Failed both, powerdown. */
2081                        } else if (bootverbose || mmc_debug)
2082                                device_printf(sc->dev,
2083                                    "MMC probe: OK (OCR: 0x%08x)\n", ocr);
2084                } else if (bootverbose || mmc_debug)
2085                        device_printf(sc->dev, "SD probe: OK (OCR: 0x%08x)\n",
2086                            ocr);
2087                sc->squelched--;
2088
2089                mmcbr_set_ocr(dev, mmc_select_vdd(sc, ocr));
2090                if (mmcbr_get_ocr(dev) != 0)
2091                        mmc_idle_cards(sc);
2092        } else {
2093                mmcbr_set_bus_mode(dev, opendrain);
2094                mmcbr_set_clock(dev, SD_MMC_CARD_ID_FREQUENCY);
2095                mmcbr_update_ios(dev);
2096                /* XXX recompute vdd based on new cards? */
2097        }
2098        /*
2099         * Make sure that we have a mutually agreeable voltage to at least
2100         * one card on the bus.
2101         */
2102        if (bootverbose || mmc_debug)
2103                device_printf(sc->dev, "Current OCR: 0x%08x\n",
2104                    mmcbr_get_ocr(dev));
2105        if (mmcbr_get_ocr(dev) == 0) {
2106                device_printf(sc->dev, "No compatible cards found on bus\n");
2107                (void)mmc_delete_cards(sc, false);
2108                mmc_power_down(sc);
2109                return;
2110        }
2111        /*
2112         * Reselect the cards after we've idled them above.
2113         */
2114        if (mmcbr_get_mode(dev) == mode_sd) {
2115                err = mmc_send_if_cond(sc, 1);
2116                mmc_send_app_op_cond(sc,
2117                    (err ? 0 : MMC_OCR_CCS) | mmcbr_get_ocr(dev), NULL);
2118        } else
2119                mmc_send_op_cond(sc, MMC_OCR_CCS | mmcbr_get_ocr(dev), NULL);
2120        mmc_discover_cards(sc);
2121        mmc_rescan_cards(sc);
2122
2123        mmcbr_set_bus_mode(dev, pushpull);
2124        mmcbr_update_ios(dev);
2125        mmc_calculate_clock(sc);
2126}
2127
2128static int
2129mmc_calculate_clock(struct mmc_softc *sc)
2130{
2131        device_t dev;
2132        struct mmc_ivars *ivar;
2133        int i;
2134        uint32_t dtr, max_dtr;
2135        uint16_t rca;
2136        enum mmc_bus_timing max_timing, timing;
2137        bool changed, hs400;
2138
2139        dev = sc->dev;
2140        max_dtr = mmcbr_get_f_max(dev);
2141        max_timing = bus_timing_max;
2142        do {
2143                changed = false;
2144                for (i = 0; i < sc->child_count; i++) {
2145                        ivar = device_get_ivars(sc->child_list[i]);
2146                        if (isclr(&ivar->timings, max_timing) ||
2147                            !mmc_host_timing(dev, max_timing)) {
2148                                for (timing = max_timing - 1; timing >=
2149                                    bus_timing_normal; timing--) {
2150                                        if (isset(&ivar->timings, timing) &&
2151                                            mmc_host_timing(dev, timing)) {
2152                                                max_timing = timing;
2153                                                break;
2154                                        }
2155                                }
2156                                changed = true;
2157                        }
2158                        dtr = mmc_timing_to_dtr(ivar, max_timing);
2159                        if (dtr < max_dtr) {
2160                                max_dtr = dtr;
2161                                changed = true;
2162                        }
2163                }
2164        } while (changed == true);
2165
2166        if (bootverbose || mmc_debug) {
2167                device_printf(dev,
2168                    "setting transfer rate to %d.%03dMHz (%s timing)\n",
2169                    max_dtr / 1000000, (max_dtr / 1000) % 1000,
2170                    mmc_timing_to_string(max_timing));
2171        }
2172
2173        /*
2174         * HS400 must be tuned in HS200 mode, so in case of HS400 we begin
2175         * with HS200 following the sequence as described in "6.6.2.2 HS200
2176         * timing mode selection" of the eMMC specification v5.1, too, and
2177         * switch to max_timing later.  HS400ES requires no tuning and, thus,
2178         * can be switch to directly, but requires the same detour via high
2179         * speed mode as does HS400 (see mmc_switch_to_hs400()).
2180         */
2181        hs400 = max_timing == bus_timing_mmc_hs400;
2182        timing = hs400 == true ? bus_timing_mmc_hs200 : max_timing;
2183        for (i = 0; i < sc->child_count; i++) {
2184                ivar = device_get_ivars(sc->child_list[i]);
2185                if ((ivar->timings & ~(1 << bus_timing_normal)) == 0)
2186                        goto clock;
2187
2188                rca = ivar->rca;
2189                if (mmc_select_card(sc, rca) != MMC_ERR_NONE) {
2190                        device_printf(dev, "Card at relative address %d "
2191                            "failed to select\n", rca);
2192                        continue;
2193                }
2194
2195                if (timing == bus_timing_mmc_hs200 ||   /* includes HS400 */
2196                    timing == bus_timing_mmc_hs400es) {
2197                        if (mmc_set_vccq(sc, ivar, timing) != MMC_ERR_NONE) {
2198                                device_printf(dev, "Failed to set VCCQ for "
2199                                    "card at relative address %d\n", rca);
2200                                continue;
2201                        }
2202                }
2203
2204                if (timing == bus_timing_mmc_hs200) {   /* includes HS400 */
2205                        /* Set bus width (required for initial tuning). */
2206                        if (mmc_set_card_bus_width(sc, ivar, timing) !=
2207                            MMC_ERR_NONE) {
2208                                device_printf(dev, "Card at relative address "
2209                                    "%d failed to set bus width\n", rca);
2210                                continue;
2211                        }
2212                        mmcbr_set_bus_width(dev, ivar->bus_width);
2213                        mmcbr_update_ios(dev);
2214                } else if (timing == bus_timing_mmc_hs400es) {
2215                        if (mmc_switch_to_hs400(sc, ivar, max_dtr, timing) !=
2216                            MMC_ERR_NONE) {
2217                                device_printf(dev, "Card at relative address "
2218                                    "%d failed to set %s timing\n", rca,
2219                                    mmc_timing_to_string(timing));
2220                                continue;
2221                        }
2222                        goto power_class;
2223                }
2224
2225                if (mmc_set_timing(sc, ivar, timing) != MMC_ERR_NONE) {
2226                        device_printf(dev, "Card at relative address %d "
2227                            "failed to set %s timing\n", rca,
2228                            mmc_timing_to_string(timing));
2229                        continue;
2230                }
2231
2232                if (timing == bus_timing_mmc_ddr52) {
2233                        /*
2234                         * Set EXT_CSD_BUS_WIDTH_n_DDR in EXT_CSD_BUS_WIDTH
2235                         * (must be done after switching to EXT_CSD_HS_TIMING).
2236                         */
2237                        if (mmc_set_card_bus_width(sc, ivar, timing) !=
2238                            MMC_ERR_NONE) {
2239                                device_printf(dev, "Card at relative address "
2240                                    "%d failed to set bus width\n", rca);
2241                                continue;
2242                        }
2243                        mmcbr_set_bus_width(dev, ivar->bus_width);
2244                        mmcbr_update_ios(dev);
2245                        if (mmc_set_vccq(sc, ivar, timing) != MMC_ERR_NONE) {
2246                                device_printf(dev, "Failed to set VCCQ for "
2247                                    "card at relative address %d\n", rca);
2248                                continue;
2249                        }
2250                }
2251
2252clock:
2253                /* Set clock (must be done before initial tuning). */
2254                mmcbr_set_clock(dev, max_dtr);
2255                mmcbr_update_ios(dev);
2256
2257                if (mmcbr_tune(dev, hs400) != 0) {
2258                        device_printf(dev, "Card at relative address %d "
2259                            "failed to execute initial tuning\n", rca);
2260                        continue;
2261                }
2262
2263                if (hs400 == true && mmc_switch_to_hs400(sc, ivar, max_dtr,
2264                    max_timing) != MMC_ERR_NONE) {
2265                        device_printf(dev, "Card at relative address %d "
2266                            "failed to set %s timing\n", rca,
2267                            mmc_timing_to_string(max_timing));
2268                        continue;
2269                }
2270
2271power_class:
2272                if (mmc_set_power_class(sc, ivar) != MMC_ERR_NONE) {
2273                        device_printf(dev, "Card at relative address %d "
2274                            "failed to set power class\n", rca);
2275                }
2276        }
2277        (void)mmc_select_card(sc, 0);
2278        return (max_dtr);
2279}
2280
2281/*
2282 * Switch from HS200 to HS400 (either initially or for re-tuning) or directly
2283 * to HS400ES.  This follows the sequences described in "6.6.2.3 HS400 timing
2284 * mode selection" of the eMMC specification v5.1.
2285 */
2286static int
2287mmc_switch_to_hs400(struct mmc_softc *sc, struct mmc_ivars *ivar,
2288    uint32_t clock, enum mmc_bus_timing max_timing)
2289{
2290        device_t dev;
2291        int err;
2292        uint16_t rca;
2293
2294        dev = sc->dev;
2295        rca = ivar->rca;
2296
2297        /*
2298         * Both clock and timing must be set as appropriate for high speed
2299         * before eventually switching to HS400/HS400ES; mmc_set_timing()
2300         * will issue mmcbr_update_ios().
2301         */
2302        mmcbr_set_clock(dev, ivar->hs_tran_speed);
2303        err = mmc_set_timing(sc, ivar, bus_timing_hs);
2304        if (err != MMC_ERR_NONE)
2305                return (err);
2306
2307        /*
2308         * Set EXT_CSD_BUS_WIDTH_8_DDR in EXT_CSD_BUS_WIDTH (and additionally
2309         * EXT_CSD_BUS_WIDTH_ES for HS400ES).
2310         */
2311        err = mmc_set_card_bus_width(sc, ivar, max_timing);
2312        if (err != MMC_ERR_NONE)
2313                return (err);
2314        mmcbr_set_bus_width(dev, ivar->bus_width);
2315        mmcbr_update_ios(dev);
2316
2317        /* Finally, switch to HS400/HS400ES mode. */
2318        err = mmc_set_timing(sc, ivar, max_timing);
2319        if (err != MMC_ERR_NONE)
2320                return (err);
2321        mmcbr_set_clock(dev, clock);
2322        mmcbr_update_ios(dev);
2323        return (MMC_ERR_NONE);
2324}
2325
2326/*
2327 * Switch from HS400 to HS200 (for re-tuning).
2328 */
2329static int
2330mmc_switch_to_hs200(struct mmc_softc *sc, struct mmc_ivars *ivar,
2331    uint32_t clock)
2332{
2333        device_t dev;
2334        int err;
2335        uint16_t rca;
2336
2337        dev = sc->dev;
2338        rca = ivar->rca;
2339
2340        /*
2341         * Both clock and timing must initially be set as appropriate for
2342         * DDR52 before eventually switching to HS200; mmc_set_timing()
2343         * will issue mmcbr_update_ios().
2344         */
2345        mmcbr_set_clock(dev, ivar->hs_tran_speed);
2346        err = mmc_set_timing(sc, ivar, bus_timing_mmc_ddr52);
2347        if (err != MMC_ERR_NONE)
2348                return (err);
2349
2350        /*
2351         * Next, switch to high speed.  Thus, clear EXT_CSD_BUS_WIDTH_n_DDR
2352         * in EXT_CSD_BUS_WIDTH and update bus width and timing in ios.
2353         */
2354        err = mmc_set_card_bus_width(sc, ivar, bus_timing_hs);
2355        if (err != MMC_ERR_NONE)
2356                return (err);
2357        mmcbr_set_bus_width(dev, ivar->bus_width);
2358        mmcbr_set_timing(sc->dev, bus_timing_hs);
2359        mmcbr_update_ios(dev);
2360
2361        /* Finally, switch to HS200 mode. */
2362        err = mmc_set_timing(sc, ivar, bus_timing_mmc_hs200);
2363        if (err != MMC_ERR_NONE)
2364                return (err);
2365        mmcbr_set_clock(dev, clock);
2366        mmcbr_update_ios(dev);
2367        return (MMC_ERR_NONE);
2368}
2369
2370static int
2371mmc_retune(device_t busdev, device_t dev, bool reset)
2372{
2373        struct mmc_softc *sc;
2374        struct mmc_ivars *ivar;
2375        int err;
2376        uint32_t clock;
2377        enum mmc_bus_timing timing;
2378
2379        if (device_get_parent(dev) != busdev)
2380                return (MMC_ERR_INVALID);
2381
2382        sc = device_get_softc(busdev);
2383        if (sc->retune_needed != 1 && sc->retune_paused != 0)
2384                return (MMC_ERR_INVALID);
2385
2386        timing = mmcbr_get_timing(busdev);
2387        if (timing == bus_timing_mmc_hs400) {
2388                /*
2389                 * Controllers use the data strobe line to latch data from
2390                 * the devices in HS400 mode so periodic re-tuning isn't
2391                 * expected to be required, i. e. only if a CRC or tuning
2392                 * error is signaled to the bridge.  In these latter cases
2393                 * we are asked to reset the tuning circuit and need to do
2394                 * the switch timing dance.
2395                 */
2396                if (reset == false)
2397                        return (0);
2398                ivar = device_get_ivars(dev);
2399                clock = mmcbr_get_clock(busdev);
2400                if (mmc_switch_to_hs200(sc, ivar, clock) != MMC_ERR_NONE)
2401                        return (MMC_ERR_BADCRC);
2402        }
2403        err = mmcbr_retune(busdev, reset);
2404        if (err != 0 && timing == bus_timing_mmc_hs400)
2405                return (MMC_ERR_BADCRC);
2406        switch (err) {
2407        case 0:
2408                break;
2409        case EIO:
2410                return (MMC_ERR_FAILED);
2411        default:
2412                return (MMC_ERR_INVALID);
2413        }
2414        if (timing == bus_timing_mmc_hs400) {
2415                if (mmc_switch_to_hs400(sc, ivar, clock, timing) !=
2416                    MMC_ERR_NONE)
2417                        return (MMC_ERR_BADCRC);
2418        }
2419        return (MMC_ERR_NONE);
2420}
2421
2422static void
2423mmc_retune_pause(device_t busdev, device_t dev, bool retune)
2424{
2425        struct mmc_softc *sc;
2426
2427        sc = device_get_softc(busdev);
2428        KASSERT(device_get_parent(dev) == busdev,
2429            ("%s: %s is not a child of %s", __func__, device_get_nameunit(dev),
2430            device_get_nameunit(busdev)));
2431        KASSERT(sc->owner != NULL,
2432            ("%s: Request from %s without bus being acquired.", __func__,
2433            device_get_nameunit(dev)));
2434
2435        if (retune == true && sc->retune_paused == 0)
2436                sc->retune_needed = 1;
2437        sc->retune_paused++;
2438}
2439
2440static void
2441mmc_retune_unpause(device_t busdev, device_t dev)
2442{
2443        struct mmc_softc *sc;
2444
2445        sc = device_get_softc(busdev);
2446        KASSERT(device_get_parent(dev) == busdev,
2447            ("%s: %s is not a child of %s", __func__, device_get_nameunit(dev),
2448            device_get_nameunit(busdev)));
2449        KASSERT(sc->owner != NULL,
2450            ("%s: Request from %s without bus being acquired.", __func__,
2451            device_get_nameunit(dev)));
2452        KASSERT(sc->retune_paused != 0,
2453            ("%s: Re-tune pause count already at 0", __func__));
2454
2455        sc->retune_paused--;
2456}
2457
2458static void
2459mmc_scan(struct mmc_softc *sc)
2460{
2461        device_t dev = sc->dev;
2462        int err;
2463
2464        err = mmc_acquire_bus(dev, dev);
2465        if (err != 0) {
2466                device_printf(dev, "Failed to acquire bus for scanning\n");
2467                return;
2468        }
2469        mmc_go_discovery(sc);
2470        err = mmc_release_bus(dev, dev);
2471        if (err != 0) {
2472                device_printf(dev, "Failed to release bus after scanning\n");
2473                return;
2474        }
2475        (void)bus_generic_attach(dev);
2476}
2477
2478static int
2479mmc_read_ivar(device_t bus, device_t child, int which, uintptr_t *result)
2480{
2481        struct mmc_ivars *ivar = device_get_ivars(child);
2482
2483        switch (which) {
2484        default:
2485                return (EINVAL);
2486        case MMC_IVAR_SPEC_VERS:
2487                *result = ivar->csd.spec_vers;
2488                break;
2489        case MMC_IVAR_DSR_IMP:
2490                *result = ivar->csd.dsr_imp;
2491                break;
2492        case MMC_IVAR_MEDIA_SIZE:
2493                *result = ivar->sec_count;
2494                break;
2495        case MMC_IVAR_RCA:
2496                *result = ivar->rca;
2497                break;
2498        case MMC_IVAR_SECTOR_SIZE:
2499                *result = MMC_SECTOR_SIZE;
2500                break;
2501        case MMC_IVAR_TRAN_SPEED:
2502                *result = mmcbr_get_clock(bus);
2503                break;
2504        case MMC_IVAR_READ_ONLY:
2505                *result = ivar->read_only;
2506                break;
2507        case MMC_IVAR_HIGH_CAP:
2508                *result = ivar->high_cap;
2509                break;
2510        case MMC_IVAR_CARD_TYPE:
2511                *result = ivar->mode;
2512                break;
2513        case MMC_IVAR_BUS_WIDTH:
2514                *result = ivar->bus_width;
2515                break;
2516        case MMC_IVAR_ERASE_SECTOR:
2517                *result = ivar->erase_sector;
2518                break;
2519        case MMC_IVAR_MAX_DATA:
2520                *result = mmcbr_get_max_data(bus);
2521                break;
2522        case MMC_IVAR_CMD6_TIMEOUT:
2523                *result = ivar->cmd6_time;
2524                break;
2525        case MMC_IVAR_QUIRKS:
2526                *result = ivar->quirks;
2527                break;
2528        case MMC_IVAR_CARD_ID_STRING:
2529                *(char **)result = ivar->card_id_string;
2530                break;
2531        case MMC_IVAR_CARD_SN_STRING:
2532                *(char **)result = ivar->card_sn_string;
2533                break;
2534        }
2535        return (0);
2536}
2537
2538static int
2539mmc_write_ivar(device_t bus, device_t child, int which, uintptr_t value)
2540{
2541
2542        /*
2543         * None are writable ATM
2544         */
2545        return (EINVAL);
2546}
2547
2548static void
2549mmc_delayed_attach(void *xsc)
2550{
2551        struct mmc_softc *sc = xsc;
2552
2553        mmc_scan(sc);
2554        config_intrhook_disestablish(&sc->config_intrhook);
2555}
2556
2557static int
2558mmc_child_location_str(device_t dev, device_t child, char *buf,
2559    size_t buflen)
2560{
2561
2562        snprintf(buf, buflen, "rca=0x%04x", mmc_get_rca(child));
2563        return (0);
2564}
2565
2566static device_method_t mmc_methods[] = {
2567        /* device_if */
2568        DEVMETHOD(device_probe, mmc_probe),
2569        DEVMETHOD(device_attach, mmc_attach),
2570        DEVMETHOD(device_detach, mmc_detach),
2571        DEVMETHOD(device_suspend, mmc_suspend),
2572        DEVMETHOD(device_resume, mmc_resume),
2573
2574        /* Bus interface */
2575        DEVMETHOD(bus_read_ivar, mmc_read_ivar),
2576        DEVMETHOD(bus_write_ivar, mmc_write_ivar),
2577        DEVMETHOD(bus_child_location_str, mmc_child_location_str),
2578
2579        /* MMC Bus interface */
2580        DEVMETHOD(mmcbus_retune_pause, mmc_retune_pause),
2581        DEVMETHOD(mmcbus_retune_unpause, mmc_retune_unpause),
2582        DEVMETHOD(mmcbus_wait_for_request, mmc_wait_for_request),
2583        DEVMETHOD(mmcbus_acquire_bus, mmc_acquire_bus),
2584        DEVMETHOD(mmcbus_release_bus, mmc_release_bus),
2585
2586        DEVMETHOD_END
2587};
2588
2589driver_t mmc_driver = {
2590        "mmc",
2591        mmc_methods,
2592        sizeof(struct mmc_softc),
2593};
2594devclass_t mmc_devclass;
2595
2596MODULE_VERSION(mmc, MMC_VERSION);
Note: See TracBrowser for help on using the repository browser.