mmc.c revision 187875
1/*-
2 * Copyright (c) 2006 Bernd Walter.  All rights reserved.
3 * Copyright (c) 2006 M. Warner Losh.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 *
25 * Portions of this software may have been developed with reference to
26 * the SD Simplified Specification.  The following disclaimer may apply:
27 *
28 * The following conditions apply to the release of the simplified
29 * specification ("Simplified Specification") by the SD Card Association and
30 * the SD Group. The Simplified Specification is a subset of the complete SD
31 * Specification which is owned by the SD Card Association and the SD
32 * Group. This Simplified Specification is provided on a non-confidential
33 * basis subject to the disclaimers below. Any implementation of the
34 * Simplified Specification may require a license from the SD Card
35 * Association, SD Group, SD-3C LLC or other third parties.
36 *
37 * Disclaimers:
38 *
39 * The information contained in the Simplified Specification is presented only
40 * as a standard specification for SD Cards and SD Host/Ancillary products and
41 * is provided "AS-IS" without any representations or warranties of any
42 * kind. No responsibility is assumed by the SD Group, SD-3C LLC or the SD
43 * Card Association for any damages, any infringements of patents or other
44 * right of the SD Group, SD-3C LLC, the SD Card Association or any third
45 * parties, which may result from its use. No license is granted by
46 * implication, estoppel or otherwise under any patent or other rights of the
47 * SD Group, SD-3C LLC, the SD Card Association or any third party. Nothing
48 * herein shall be construed as an obligation by the SD Group, the SD-3C LLC
49 * or the SD Card Association to disclose or distribute any technical
50 * information, know-how or other confidential information to any third party.
51 */
52
53#include <sys/cdefs.h>
54__FBSDID("$FreeBSD: head/sys/dev/mmc/mmc.c 187875 2009-01-28 22:09:00Z mav $");
55
56#include <sys/param.h>
57#include <sys/systm.h>
58#include <sys/kernel.h>
59#include <sys/malloc.h>
60#include <sys/lock.h>
61#include <sys/module.h>
62#include <sys/mutex.h>
63#include <sys/bus.h>
64#include <sys/endian.h>
65#include <sys/sysctl.h>
66
67#include <dev/mmc/mmcreg.h>
68#include <dev/mmc/mmcbrvar.h>
69#include <dev/mmc/mmcvar.h>
70#include "mmcbr_if.h"
71#include "mmcbus_if.h"
72
73struct mmc_softc {
74	device_t dev;
75	struct mtx sc_mtx;
76	struct intr_config_hook config_intrhook;
77	device_t owner;
78	uint32_t last_rca;
79};
80
81/*
82 * Per-card data
83 */
84struct mmc_ivars {
85	uint32_t raw_cid[4];	/* Raw bits of the CID */
86	uint32_t raw_csd[4];	/* Raw bits of the CSD */
87	uint32_t raw_scr[2];	/* Raw bits of the SCR */
88	uint8_t raw_ext_csd[512];	/* Raw bits of the EXT_CSD */
89	uint32_t raw_sd_status[16];	/* Raw bits of the SD_STATUS */
90	uint16_t rca;
91	enum mmc_card_mode mode;
92	struct mmc_cid cid;	/* cid decoded */
93	struct mmc_csd csd;	/* csd decoded */
94	struct mmc_scr scr;	/* scr decoded */
95	struct mmc_sd_status sd_status;	/* SD_STATUS decoded */
96	u_char read_only;	/* True when the device is read-only */
97	u_char bus_width;	/* Bus width to use */
98	u_char timing;		/* Bus timing support */
99	u_char high_cap;	/* High Capacity card (block addressed) */
100	uint32_t sec_count;	/* Card capacity in 512byte blocks */
101	uint32_t tran_speed;	/* Max speed in normal mode */
102	uint32_t hs_tran_speed;	/* Max speed in high speed mode */
103	uint32_t erase_sector;	/* Card native erase sector size */
104};
105
106#define CMD_RETRIES	3
107
108SYSCTL_NODE(_hw, OID_AUTO, mmc, CTLFLAG_RD, 0, "mmc driver");
109
110int	mmc_debug;
111SYSCTL_INT(_hw_mmc, OID_AUTO, debug, CTLFLAG_RW, &mmc_debug, 0, "Debug level");
112
113/* bus entry points */
114static int mmc_probe(device_t dev);
115static int mmc_attach(device_t dev);
116static int mmc_detach(device_t dev);
117static int mmc_suspend(device_t dev);
118static int mmc_resume(device_t dev);
119
120#define MMC_LOCK(_sc)		mtx_lock(&(_sc)->sc_mtx)
121#define	MMC_UNLOCK(_sc)		mtx_unlock(&(_sc)->sc_mtx)
122#define MMC_LOCK_INIT(_sc)					\
123	mtx_init(&_sc->sc_mtx, device_get_nameunit(_sc->dev),	\
124	    "mmc", MTX_DEF)
125#define MMC_LOCK_DESTROY(_sc)	mtx_destroy(&_sc->sc_mtx);
126#define MMC_ASSERT_LOCKED(_sc)	mtx_assert(&_sc->sc_mtx, MA_OWNED);
127#define MMC_ASSERT_UNLOCKED(_sc) mtx_assert(&_sc->sc_mtx, MA_NOTOWNED);
128
129static int mmc_calculate_clock(struct mmc_softc *sc);
130static void mmc_delayed_attach(void *);
131static void mmc_power_down(struct mmc_softc *sc);
132static int mmc_wait_for_cmd(struct mmc_softc *sc, struct mmc_command *cmd,
133    int retries);
134static int mmc_wait_for_command(struct mmc_softc *sc, uint32_t opcode,
135    uint32_t arg, uint32_t flags, uint32_t *resp, int retries);
136static int mmc_select_card(struct mmc_softc *sc, uint16_t rca);
137static int mmc_set_card_bus_width(struct mmc_softc *sc, uint16_t rca, int width);
138static int mmc_app_send_scr(struct mmc_softc *sc, uint16_t rca, uint32_t *rawscr);
139static void mmc_app_decode_scr(uint32_t *raw_scr, struct mmc_scr *scr);
140static int mmc_send_ext_csd(struct mmc_softc *sc, uint8_t *rawextcsd);
141static void mmc_scan(struct mmc_softc *sc);
142static int mmc_delete_cards(struct mmc_softc *sc);
143
144static void
145mmc_ms_delay(int ms)
146{
147	DELAY(1000 * ms);	/* XXX BAD */
148}
149
150static int
151mmc_probe(device_t dev)
152{
153
154	device_set_desc(dev, "MMC/SD bus");
155	return (0);
156}
157
158static int
159mmc_attach(device_t dev)
160{
161	struct mmc_softc *sc;
162
163	sc = device_get_softc(dev);
164	sc->dev = dev;
165	MMC_LOCK_INIT(sc);
166
167	/* We'll probe and attach our children later, but before / mount */
168	sc->config_intrhook.ich_func = mmc_delayed_attach;
169	sc->config_intrhook.ich_arg = sc;
170	if (config_intrhook_establish(&sc->config_intrhook) != 0)
171		device_printf(dev, "config_intrhook_establish failed\n");
172	return (0);
173}
174
175static int
176mmc_detach(device_t dev)
177{
178	struct mmc_softc *sc = device_get_softc(dev);
179	int err;
180
181	if ((err = mmc_delete_cards(sc)) != 0)
182		return (err);
183	mmc_power_down(sc);
184	MMC_LOCK_DESTROY(sc);
185
186	return (0);
187}
188
189static int
190mmc_suspend(device_t dev)
191{
192	struct mmc_softc *sc = device_get_softc(dev);
193	int err;
194
195	err = bus_generic_suspend(dev);
196	if (err)
197	        return (err);
198	mmc_power_down(sc);
199	return (0);
200}
201
202static int
203mmc_resume(device_t dev)
204{
205	struct mmc_softc *sc = device_get_softc(dev);
206
207	mmc_scan(sc);
208	return (bus_generic_resume(dev));
209}
210
211static int
212mmc_acquire_bus(device_t busdev, device_t dev)
213{
214	struct mmc_softc *sc;
215	struct mmc_ivars *ivar;
216	int err;
217	int rca;
218
219	err = MMCBR_ACQUIRE_HOST(device_get_parent(busdev), busdev);
220	if (err)
221		return (err);
222	sc = device_get_softc(busdev);
223	MMC_LOCK(sc);
224	if (sc->owner)
225		panic("mmc: host bridge didn't seralize us.");
226	sc->owner = dev;
227	MMC_UNLOCK(sc);
228
229	if (busdev != dev) {
230		/*
231		 * Keep track of the last rca that we've selected.  If
232		 * we're asked to do it again, don't.  We never
233		 * unselect unless the bus code itself wants the mmc
234		 * bus, and constantly reselecting causes problems.
235		 */
236		rca = mmc_get_rca(dev);
237		if (sc->last_rca != rca) {
238			mmc_select_card(sc, rca);
239			sc->last_rca = rca;
240			/* Prepare bus width for the new card. */
241			ivar = device_get_ivars(dev);
242			if (bootverbose || mmc_debug) {
243				device_printf(busdev,
244				    "setting bus width to %d bits\n",
245				    (ivar->bus_width == bus_width_4) ? 4 :
246				    (ivar->bus_width == bus_width_8) ? 8 : 1);
247			}
248			mmc_set_card_bus_width(sc, rca, ivar->bus_width);
249			mmcbr_set_bus_width(busdev, ivar->bus_width);
250			mmcbr_update_ios(busdev);
251		}
252	} else {
253		/*
254		 * If there's a card selected, stand down.
255		 */
256		if (sc->last_rca != 0) {
257			mmc_select_card(sc, 0);
258			sc->last_rca = 0;
259		}
260	}
261
262	return (0);
263}
264
265static int
266mmc_release_bus(device_t busdev, device_t dev)
267{
268	struct mmc_softc *sc;
269	int err;
270
271	sc = device_get_softc(busdev);
272
273	MMC_LOCK(sc);
274	if (!sc->owner)
275		panic("mmc: releasing unowned bus.");
276	if (sc->owner != dev)
277		panic("mmc: you don't own the bus.  game over.");
278	MMC_UNLOCK(sc);
279	err = MMCBR_RELEASE_HOST(device_get_parent(busdev), busdev);
280	if (err)
281		return (err);
282	MMC_LOCK(sc);
283	sc->owner = NULL;
284	MMC_UNLOCK(sc);
285	return (0);
286}
287
288static uint32_t
289mmc_select_vdd(struct mmc_softc *sc, uint32_t ocr)
290{
291
292	return (ocr & MMC_OCR_VOLTAGE);
293}
294
295static int
296mmc_highest_voltage(uint32_t ocr)
297{
298	int i;
299
300	for (i = 30; i >= 0; i--)
301		if (ocr & (1 << i))
302			return (i);
303	return (-1);
304}
305
306static void
307mmc_wakeup(struct mmc_request *req)
308{
309	struct mmc_softc *sc;
310
311	sc = (struct mmc_softc *)req->done_data;
312	MMC_LOCK(sc);
313	req->flags |= MMC_REQ_DONE;
314	MMC_UNLOCK(sc);
315	wakeup(req);
316}
317
318static int
319mmc_wait_for_req(struct mmc_softc *sc, struct mmc_request *req)
320{
321
322	req->done = mmc_wakeup;
323	req->done_data = sc;
324	if (mmc_debug) {
325		device_printf(sc->dev, "REQUEST: CMD%d arg %#x flags %#x",
326		    req->cmd->opcode, req->cmd->arg, req->cmd->flags);
327		if (req->cmd->data) {
328			printf(" data %d\n", (int)req->cmd->data->len);
329		} else
330			printf("\n");
331	}
332	MMCBR_REQUEST(device_get_parent(sc->dev), sc->dev, req);
333	MMC_LOCK(sc);
334	while ((req->flags & MMC_REQ_DONE) == 0)
335		msleep(req, &sc->sc_mtx, 0, "mmcreq", 0);
336	MMC_UNLOCK(sc);
337	if (mmc_debug > 1 || (mmc_debug && req->cmd->error))
338		device_printf(sc->dev, "RESULT: %d\n", req->cmd->error);
339	return (0);
340}
341
342static int
343mmc_wait_for_request(device_t brdev, device_t reqdev, struct mmc_request *req)
344{
345	struct mmc_softc *sc = device_get_softc(brdev);
346
347	return (mmc_wait_for_req(sc, req));
348}
349
350static int
351mmc_wait_for_cmd(struct mmc_softc *sc, struct mmc_command *cmd, int retries)
352{
353	struct mmc_request mreq;
354
355	memset(&mreq, 0, sizeof(mreq));
356	memset(cmd->resp, 0, sizeof(cmd->resp));
357	cmd->retries = retries;
358	mreq.cmd = cmd;
359	mmc_wait_for_req(sc, &mreq);
360	return (cmd->error);
361}
362
363static int
364mmc_wait_for_app_cmd(struct mmc_softc *sc, uint32_t rca,
365    struct mmc_command *cmd, int retries)
366{
367	struct mmc_command appcmd;
368	int err = MMC_ERR_NONE, i;
369
370	for (i = 0; i <= retries; i++) {
371		appcmd.opcode = MMC_APP_CMD;
372		appcmd.arg = rca << 16;
373		appcmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
374		appcmd.data = NULL;
375		mmc_wait_for_cmd(sc, &appcmd, 0);
376		err = appcmd.error;
377		if (err != MMC_ERR_NONE)
378			continue;
379		if (!(appcmd.resp[0] & R1_APP_CMD))
380			return MMC_ERR_FAILED;
381		mmc_wait_for_cmd(sc, cmd, 0);
382		err = cmd->error;
383		if (err == MMC_ERR_NONE)
384			break;
385	}
386	return (err);
387}
388
389static int
390mmc_wait_for_command(struct mmc_softc *sc, uint32_t opcode,
391    uint32_t arg, uint32_t flags, uint32_t *resp, int retries)
392{
393	struct mmc_command cmd;
394	int err;
395
396	memset(&cmd, 0, sizeof(cmd));
397	cmd.opcode = opcode;
398	cmd.arg = arg;
399	cmd.flags = flags;
400	cmd.data = NULL;
401	err = mmc_wait_for_cmd(sc, &cmd, retries);
402	if (err)
403		return (err);
404	if (cmd.error)
405		return (cmd.error);
406	if (resp) {
407		if (flags & MMC_RSP_136)
408			memcpy(resp, cmd.resp, 4 * sizeof(uint32_t));
409		else
410			*resp = cmd.resp[0];
411	}
412	return (0);
413}
414
415static void
416mmc_idle_cards(struct mmc_softc *sc)
417{
418	device_t dev;
419	struct mmc_command cmd;
420
421	dev = sc->dev;
422	mmcbr_set_chip_select(dev, cs_high);
423	mmcbr_update_ios(dev);
424	mmc_ms_delay(1);
425
426	memset(&cmd, 0, sizeof(cmd));
427	cmd.opcode = MMC_GO_IDLE_STATE;
428	cmd.arg = 0;
429	cmd.flags = MMC_RSP_NONE | MMC_CMD_BC;
430	cmd.data = NULL;
431	mmc_wait_for_cmd(sc, &cmd, 0);
432	mmc_ms_delay(1);
433
434	mmcbr_set_chip_select(dev, cs_dontcare);
435	mmcbr_update_ios(dev);
436	mmc_ms_delay(1);
437}
438
439static int
440mmc_send_app_op_cond(struct mmc_softc *sc, uint32_t ocr, uint32_t *rocr)
441{
442	struct mmc_command cmd;
443	int err = MMC_ERR_NONE, i;
444
445	memset(&cmd, 0, sizeof(cmd));
446	cmd.opcode = ACMD_SD_SEND_OP_COND;
447	cmd.arg = ocr;
448	cmd.flags = MMC_RSP_R3 | MMC_CMD_BCR;
449	cmd.data = NULL;
450
451	for (i = 0; i < 100; i++) {
452		err = mmc_wait_for_app_cmd(sc, 0, &cmd, CMD_RETRIES);
453		if (err != MMC_ERR_NONE)
454			break;
455		if ((cmd.resp[0] & MMC_OCR_CARD_BUSY) ||
456		    (ocr & MMC_OCR_VOLTAGE) == 0)
457			break;
458		err = MMC_ERR_TIMEOUT;
459		mmc_ms_delay(10);
460	}
461	if (rocr && err == MMC_ERR_NONE)
462		*rocr = cmd.resp[0];
463	return (err);
464}
465
466static int
467mmc_send_op_cond(struct mmc_softc *sc, uint32_t ocr, uint32_t *rocr)
468{
469	struct mmc_command cmd;
470	int err = MMC_ERR_NONE, i;
471
472	memset(&cmd, 0, sizeof(cmd));
473	cmd.opcode = MMC_SEND_OP_COND;
474	cmd.arg = ocr;
475	cmd.flags = MMC_RSP_R3 | MMC_CMD_BCR;
476	cmd.data = NULL;
477
478	for (i = 0; i < 100; i++) {
479		err = mmc_wait_for_cmd(sc, &cmd, CMD_RETRIES);
480		if (err != MMC_ERR_NONE)
481			break;
482		if ((cmd.resp[0] & MMC_OCR_CARD_BUSY) ||
483		    (ocr & MMC_OCR_VOLTAGE) == 0)
484			break;
485		err = MMC_ERR_TIMEOUT;
486		mmc_ms_delay(10);
487	}
488	if (rocr && err == MMC_ERR_NONE)
489		*rocr = cmd.resp[0];
490	return (err);
491}
492
493static int
494mmc_send_if_cond(struct mmc_softc *sc, uint8_t vhs)
495{
496	struct mmc_command cmd;
497	int err;
498
499	memset(&cmd, 0, sizeof(cmd));
500	cmd.opcode = SD_SEND_IF_COND;
501	cmd.arg = (vhs << 8) + 0xAA;
502	cmd.flags = MMC_RSP_R7 | MMC_CMD_BCR;
503	cmd.data = NULL;
504
505	err = mmc_wait_for_cmd(sc, &cmd, CMD_RETRIES);
506	return (err);
507}
508
509static void
510mmc_power_up(struct mmc_softc *sc)
511{
512	device_t dev;
513
514	dev = sc->dev;
515	mmcbr_set_vdd(dev, mmc_highest_voltage(mmcbr_get_host_ocr(dev)));
516	mmcbr_set_bus_mode(dev, opendrain);
517	mmcbr_set_chip_select(dev, cs_dontcare);
518	mmcbr_set_bus_width(dev, bus_width_1);
519	mmcbr_set_power_mode(dev, power_up);
520	mmcbr_set_clock(dev, 0);
521	mmcbr_update_ios(dev);
522	mmc_ms_delay(1);
523
524	mmcbr_set_clock(dev, mmcbr_get_f_min(sc->dev));
525	mmcbr_set_timing(dev, bus_timing_normal);
526	mmcbr_set_power_mode(dev, power_on);
527	mmcbr_update_ios(dev);
528	mmc_ms_delay(2);
529}
530
531static void
532mmc_power_down(struct mmc_softc *sc)
533{
534	device_t dev = sc->dev;
535
536	mmcbr_set_bus_mode(dev, opendrain);
537	mmcbr_set_chip_select(dev, cs_dontcare);
538	mmcbr_set_bus_width(dev, bus_width_1);
539	mmcbr_set_power_mode(dev, power_off);
540	mmcbr_set_clock(dev, 0);
541	mmcbr_set_timing(dev, bus_timing_normal);
542	mmcbr_update_ios(dev);
543}
544
545static int
546mmc_select_card(struct mmc_softc *sc, uint16_t rca)
547{
548	int flags;
549
550	flags = (rca ? MMC_RSP_R1B : MMC_RSP_NONE) | MMC_CMD_AC;
551	return (mmc_wait_for_command(sc, MMC_SELECT_CARD, (uint32_t)rca << 16,
552	    flags, NULL, CMD_RETRIES));
553}
554
555static int
556mmc_switch(struct mmc_softc *sc, uint8_t set, uint8_t index, uint8_t value)
557{
558	struct mmc_command cmd;
559	int err;
560
561	cmd.opcode = MMC_SWITCH_FUNC;
562	cmd.arg = (MMC_SWITCH_FUNC_WR << 24) |
563	    (index << 16) |
564	    (value << 8) |
565	    set;
566	cmd.flags = MMC_RSP_R1B | MMC_CMD_AC;
567	cmd.data = NULL;
568	err = mmc_wait_for_cmd(sc, &cmd, 0);
569	return (err);
570}
571
572static int
573mmc_sd_switch(struct mmc_softc *sc, uint8_t mode, uint8_t grp, uint8_t value, uint8_t *res)
574{
575	int err;
576	struct mmc_command cmd;
577	struct mmc_data data;
578
579	memset(&cmd, 0, sizeof(struct mmc_command));
580	memset(&data, 0, sizeof(struct mmc_data));
581
582	memset(res, 0, 64);
583	cmd.opcode = SD_SWITCH_FUNC;
584	cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
585	cmd.arg = mode << 31;
586	cmd.arg |= 0x00FFFFFF;
587	cmd.arg &= ~(0xF << (grp * 4));
588	cmd.arg |= value << (grp * 4);
589	cmd.data = &data;
590
591	data.data = res;
592	data.len = 64;
593	data.flags = MMC_DATA_READ;
594
595	err = mmc_wait_for_cmd(sc, &cmd, CMD_RETRIES);
596	return (err);
597}
598
599static int
600mmc_set_card_bus_width(struct mmc_softc *sc, uint16_t rca, int width)
601{
602	struct mmc_command cmd;
603	int err;
604	uint8_t	value;
605
606	if (mmcbr_get_mode(sc->dev) == mode_sd) {
607		memset(&cmd, 0, sizeof(struct mmc_command));
608		cmd.opcode = ACMD_SET_BUS_WIDTH;
609		cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
610		switch (width) {
611		case bus_width_1:
612			cmd.arg = SD_BUS_WIDTH_1;
613			break;
614		case bus_width_4:
615			cmd.arg = SD_BUS_WIDTH_4;
616			break;
617		default:
618			return (MMC_ERR_INVALID);
619		}
620		err = mmc_wait_for_app_cmd(sc, rca, &cmd, CMD_RETRIES);
621	} else {
622		switch (width) {
623		case bus_width_1:
624			value = EXT_CSD_BUS_WIDTH_1;
625			break;
626		case bus_width_4:
627			value = EXT_CSD_BUS_WIDTH_4;
628			break;
629		case bus_width_8:
630			value = EXT_CSD_BUS_WIDTH_8;
631			break;
632		default:
633			return (MMC_ERR_INVALID);
634		}
635		err = mmc_switch(sc, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_BUS_WIDTH,
636		    value);
637	}
638	return (err);
639}
640
641static int
642mmc_set_timing(struct mmc_softc *sc, int timing)
643{
644	int err;
645	uint8_t	value;
646	u_char switch_res[64];
647
648	switch (timing) {
649	case bus_timing_normal:
650		value = 0;
651		break;
652	case bus_timing_hs:
653		value = 1;
654		break;
655	default:
656		return (MMC_ERR_INVALID);
657	}
658	if (mmcbr_get_mode(sc->dev) == mode_sd)
659		err = mmc_sd_switch(sc, 1, 0, value, switch_res);
660	else
661		err = mmc_switch(sc, EXT_CSD_CMD_SET_NORMAL,
662		    EXT_CSD_HS_TIMING, value);
663	return (err);
664}
665
666static int
667mmc_test_bus_width(struct mmc_softc *sc)
668{
669	struct mmc_command cmd;
670	struct mmc_data data;
671	int err;
672	uint8_t buf[8];
673	uint8_t	p8[8] =   { 0x55, 0xAA, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
674	uint8_t	p8ok[8] = { 0xAA, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
675	uint8_t	p4[4] =   { 0x5A, 0x00, 0x00, 0x00, };
676	uint8_t	p4ok[4] = { 0xA5, 0x00, 0x00, 0x00, };
677
678	if (mmcbr_get_caps(sc->dev) & MMC_CAP_8_BIT_DATA) {
679		mmcbr_set_bus_width(sc->dev, bus_width_8);
680		mmcbr_update_ios(sc->dev);
681
682		cmd.opcode = MMC_BUSTEST_W;
683		cmd.arg = 0;
684		cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
685		cmd.data = &data;
686
687		data.data = p8;
688		data.len = 8;
689		data.flags = MMC_DATA_WRITE;
690		mmc_wait_for_cmd(sc, &cmd, 0);
691
692		cmd.opcode = MMC_BUSTEST_R;
693		cmd.arg = 0;
694		cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
695		cmd.data = &data;
696
697		data.data = buf;
698		data.len = 8;
699		data.flags = MMC_DATA_READ;
700		err = mmc_wait_for_cmd(sc, &cmd, 0);
701
702		mmcbr_set_bus_width(sc->dev, bus_width_1);
703		mmcbr_update_ios(sc->dev);
704
705		if (err == MMC_ERR_NONE && memcmp(buf, p8ok, 8) == 0)
706			return (bus_width_8);
707	}
708
709	if (mmcbr_get_caps(sc->dev) & MMC_CAP_4_BIT_DATA) {
710		mmcbr_set_bus_width(sc->dev, bus_width_4);
711		mmcbr_update_ios(sc->dev);
712
713		cmd.opcode = MMC_BUSTEST_W;
714		cmd.arg = 0;
715		cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
716		cmd.data = &data;
717
718		data.data = p4;
719		data.len = 4;
720		data.flags = MMC_DATA_WRITE;
721		mmc_wait_for_cmd(sc, &cmd, 0);
722
723		cmd.opcode = MMC_BUSTEST_R;
724		cmd.arg = 0;
725		cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
726		cmd.data = &data;
727
728		data.data = buf;
729		data.len = 4;
730		data.flags = MMC_DATA_READ;
731		err = mmc_wait_for_cmd(sc, &cmd, 0);
732
733		mmcbr_set_bus_width(sc->dev, bus_width_1);
734		mmcbr_update_ios(sc->dev);
735
736		if (err == MMC_ERR_NONE && memcmp(buf, p4ok, 4) == 0)
737			return (bus_width_4);
738	}
739	return (bus_width_1);
740}
741
742static uint32_t
743mmc_get_bits(uint32_t *bits, int bit_len, int start, int size)
744{
745	const int i = (bit_len / 32) - (start / 32) - 1;
746	const int shift = start & 31;
747	uint32_t retval = bits[i] >> shift;
748	if (size + shift > 32)
749		retval |= bits[i - 1] << (32 - shift);
750	return (retval & ((1 << size) - 1));
751}
752
753static void
754mmc_decode_cid_sd(uint32_t *raw_cid, struct mmc_cid *cid)
755{
756	int i;
757
758	/* There's no version info, so we take it on faith */
759	memset(cid, 0, sizeof(*cid));
760	cid->mid = mmc_get_bits(raw_cid, 128, 120, 8);
761	cid->oid = mmc_get_bits(raw_cid, 128, 104, 16);
762	for (i = 0; i < 5; i++)
763		cid->pnm[i] = mmc_get_bits(raw_cid, 128, 96 - i * 8, 8);
764	cid->pnm[5] = 0;
765	cid->prv = mmc_get_bits(raw_cid, 128, 56, 8);
766	cid->psn = mmc_get_bits(raw_cid, 128, 24, 32);
767	cid->mdt_year = mmc_get_bits(raw_cid, 128, 12, 8) + 2000;
768	cid->mdt_month = mmc_get_bits(raw_cid, 128, 8, 4);
769}
770
771static void
772mmc_decode_cid_mmc(uint32_t *raw_cid, struct mmc_cid *cid)
773{
774	int i;
775
776	/* There's no version info, so we take it on faith */
777	memset(cid, 0, sizeof(*cid));
778	cid->mid = mmc_get_bits(raw_cid, 128, 120, 8);
779	cid->oid = mmc_get_bits(raw_cid, 128, 104, 8);
780	for (i = 0; i < 6; i++)
781		cid->pnm[i] = mmc_get_bits(raw_cid, 128, 96 - i * 8, 8);
782	cid->pnm[6] = 0;
783	cid->prv = mmc_get_bits(raw_cid, 128, 48, 8);
784	cid->psn = mmc_get_bits(raw_cid, 128, 16, 32);
785	cid->mdt_month = mmc_get_bits(raw_cid, 128, 12, 4);
786	cid->mdt_year = mmc_get_bits(raw_cid, 128, 8, 4) + 1997;
787}
788
789static const int exp[8] = {
790	1, 10, 100, 1000, 10000, 100000, 1000000, 10000000
791};
792static const int mant[16] = {
793	10, 12, 13, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 70, 80
794};
795static const int cur_min[8] = {
796	500, 1000, 5000, 10000, 25000, 35000, 60000, 100000
797};
798static const int cur_max[8] = {
799	1000, 5000, 10000, 25000, 35000, 45000, 800000, 200000
800};
801
802static void
803mmc_decode_csd_sd(uint32_t *raw_csd, struct mmc_csd *csd)
804{
805	int v;
806	int m;
807	int e;
808
809	memset(csd, 0, sizeof(*csd));
810	csd->csd_structure = v = mmc_get_bits(raw_csd, 128, 126, 2);
811	if (v == 0) {
812		m = mmc_get_bits(raw_csd, 128, 115, 4);
813		e = mmc_get_bits(raw_csd, 128, 112, 3);
814		csd->tacc = exp[e] * mant[m] + 9 / 10;
815		csd->nsac = mmc_get_bits(raw_csd, 128, 104, 8) * 100;
816		m = mmc_get_bits(raw_csd, 128, 99, 4);
817		e = mmc_get_bits(raw_csd, 128, 96, 3);
818		csd->tran_speed = exp[e] * 10000 * mant[m];
819		csd->ccc = mmc_get_bits(raw_csd, 128, 84, 12);
820		csd->read_bl_len = 1 << mmc_get_bits(raw_csd, 128, 80, 4);
821		csd->read_bl_partial = mmc_get_bits(raw_csd, 128, 79, 1);
822		csd->write_blk_misalign = mmc_get_bits(raw_csd, 128, 78, 1);
823		csd->read_blk_misalign = mmc_get_bits(raw_csd, 128, 77, 1);
824		csd->dsr_imp = mmc_get_bits(raw_csd, 128, 76, 1);
825		csd->vdd_r_curr_min = cur_min[mmc_get_bits(raw_csd, 128, 59, 3)];
826		csd->vdd_r_curr_max = cur_max[mmc_get_bits(raw_csd, 128, 56, 3)];
827		csd->vdd_w_curr_min = cur_min[mmc_get_bits(raw_csd, 128, 53, 3)];
828		csd->vdd_w_curr_max = cur_max[mmc_get_bits(raw_csd, 128, 50, 3)];
829		m = mmc_get_bits(raw_csd, 128, 62, 12);
830		e = mmc_get_bits(raw_csd, 128, 47, 3);
831		csd->capacity = ((1 + m) << (e + 2)) * csd->read_bl_len;
832		csd->erase_blk_en = mmc_get_bits(raw_csd, 128, 46, 1);
833		csd->erase_sector = mmc_get_bits(raw_csd, 128, 39, 7) + 1;
834		csd->wp_grp_size = mmc_get_bits(raw_csd, 128, 32, 7);
835		csd->wp_grp_enable = mmc_get_bits(raw_csd, 128, 31, 1);
836		csd->r2w_factor = 1 << mmc_get_bits(raw_csd, 128, 26, 3);
837		csd->write_bl_len = 1 << mmc_get_bits(raw_csd, 128, 22, 4);
838		csd->write_bl_partial = mmc_get_bits(raw_csd, 128, 21, 1);
839	} else if (v == 1) {
840		m = mmc_get_bits(raw_csd, 128, 115, 4);
841		e = mmc_get_bits(raw_csd, 128, 112, 3);
842		csd->tacc = exp[e] * mant[m] + 9 / 10;
843		csd->nsac = mmc_get_bits(raw_csd, 128, 104, 8) * 100;
844		m = mmc_get_bits(raw_csd, 128, 99, 4);
845		e = mmc_get_bits(raw_csd, 128, 96, 3);
846		csd->tran_speed = exp[e] * 10000 * mant[m];
847		csd->ccc = mmc_get_bits(raw_csd, 128, 84, 12);
848		csd->read_bl_len = 1 << mmc_get_bits(raw_csd, 128, 80, 4);
849		csd->read_bl_partial = mmc_get_bits(raw_csd, 128, 79, 1);
850		csd->write_blk_misalign = mmc_get_bits(raw_csd, 128, 78, 1);
851		csd->read_blk_misalign = mmc_get_bits(raw_csd, 128, 77, 1);
852		csd->dsr_imp = mmc_get_bits(raw_csd, 128, 76, 1);
853		csd->capacity = ((uint64_t)mmc_get_bits(raw_csd, 128, 48, 22) + 1) *
854		    512 * 1024;
855		csd->erase_blk_en = mmc_get_bits(raw_csd, 128, 46, 1);
856		csd->erase_sector = mmc_get_bits(raw_csd, 128, 39, 7) + 1;
857		csd->wp_grp_size = mmc_get_bits(raw_csd, 128, 32, 7);
858		csd->wp_grp_enable = mmc_get_bits(raw_csd, 128, 31, 1);
859		csd->r2w_factor = 1 << mmc_get_bits(raw_csd, 128, 26, 3);
860		csd->write_bl_len = 1 << mmc_get_bits(raw_csd, 128, 22, 4);
861		csd->write_bl_partial = mmc_get_bits(raw_csd, 128, 21, 1);
862	} else
863		panic("unknown SD CSD version");
864}
865
866static void
867mmc_decode_csd_mmc(uint32_t *raw_csd, struct mmc_csd *csd)
868{
869	int m;
870	int e;
871
872	memset(csd, 0, sizeof(*csd));
873	csd->csd_structure = mmc_get_bits(raw_csd, 128, 126, 2);
874	csd->spec_vers = mmc_get_bits(raw_csd, 128, 122, 4);
875	m = mmc_get_bits(raw_csd, 128, 115, 4);
876	e = mmc_get_bits(raw_csd, 128, 112, 3);
877	csd->tacc = exp[e] * mant[m] + 9 / 10;
878	csd->nsac = mmc_get_bits(raw_csd, 128, 104, 8) * 100;
879	m = mmc_get_bits(raw_csd, 128, 99, 4);
880	e = mmc_get_bits(raw_csd, 128, 96, 3);
881	csd->tran_speed = exp[e] * 10000 * mant[m];
882	csd->ccc = mmc_get_bits(raw_csd, 128, 84, 12);
883	csd->read_bl_len = 1 << mmc_get_bits(raw_csd, 128, 80, 4);
884	csd->read_bl_partial = mmc_get_bits(raw_csd, 128, 79, 1);
885	csd->write_blk_misalign = mmc_get_bits(raw_csd, 128, 78, 1);
886	csd->read_blk_misalign = mmc_get_bits(raw_csd, 128, 77, 1);
887	csd->dsr_imp = mmc_get_bits(raw_csd, 128, 76, 1);
888	csd->vdd_r_curr_min = cur_min[mmc_get_bits(raw_csd, 128, 59, 3)];
889	csd->vdd_r_curr_max = cur_max[mmc_get_bits(raw_csd, 128, 56, 3)];
890	csd->vdd_w_curr_min = cur_min[mmc_get_bits(raw_csd, 128, 53, 3)];
891	csd->vdd_w_curr_max = cur_max[mmc_get_bits(raw_csd, 128, 50, 3)];
892	m = mmc_get_bits(raw_csd, 128, 62, 12);
893	e = mmc_get_bits(raw_csd, 128, 47, 3);
894	csd->capacity = ((1 + m) << (e + 2)) * csd->read_bl_len;
895	csd->erase_blk_en = 0;
896	csd->erase_sector = (mmc_get_bits(raw_csd, 128, 42, 5) + 1) *
897	    (mmc_get_bits(raw_csd, 128, 37, 5) + 1);
898	csd->wp_grp_size = mmc_get_bits(raw_csd, 128, 32, 5);
899	csd->wp_grp_enable = mmc_get_bits(raw_csd, 128, 31, 1);
900	csd->r2w_factor = 1 << mmc_get_bits(raw_csd, 128, 26, 3);
901	csd->write_bl_len = 1 << mmc_get_bits(raw_csd, 128, 22, 4);
902	csd->write_bl_partial = mmc_get_bits(raw_csd, 128, 21, 1);
903}
904
905static void
906mmc_app_decode_scr(uint32_t *raw_scr, struct mmc_scr *scr)
907{
908	unsigned int scr_struct;
909
910	memset(scr, 0, sizeof(*scr));
911
912	scr_struct = mmc_get_bits(raw_scr, 64, 60, 4);
913	if (scr_struct != 0) {
914		printf("Unrecognised SCR structure version %d\n",
915		    scr_struct);
916		return;
917	}
918	scr->sda_vsn = mmc_get_bits(raw_scr, 64, 56, 4);
919	scr->bus_widths = mmc_get_bits(raw_scr, 64, 48, 4);
920}
921
922static void
923mmc_app_decode_sd_status(uint32_t *raw_sd_status,
924    struct mmc_sd_status *sd_status)
925{
926
927	memset(sd_status, 0, sizeof(*sd_status));
928
929	sd_status->bus_width = mmc_get_bits(raw_sd_status, 512, 510, 2);
930	sd_status->secured_mode = mmc_get_bits(raw_sd_status, 512, 509, 1);
931	sd_status->card_type = mmc_get_bits(raw_sd_status, 512, 480, 16);
932	sd_status->prot_area = mmc_get_bits(raw_sd_status, 512, 448, 12);
933	sd_status->speed_class = mmc_get_bits(raw_sd_status, 512, 440, 8);
934	sd_status->perf_move = mmc_get_bits(raw_sd_status, 512, 432, 8);
935	sd_status->au_size = mmc_get_bits(raw_sd_status, 512, 428, 4);
936	sd_status->erase_size = mmc_get_bits(raw_sd_status, 512, 408, 16);
937	sd_status->erase_timeout = mmc_get_bits(raw_sd_status, 512, 402, 6);
938	sd_status->erase_offset = mmc_get_bits(raw_sd_status, 512, 400, 2);
939}
940
941static int
942mmc_all_send_cid(struct mmc_softc *sc, uint32_t *rawcid)
943{
944	struct mmc_command cmd;
945	int err;
946
947	cmd.opcode = MMC_ALL_SEND_CID;
948	cmd.arg = 0;
949	cmd.flags = MMC_RSP_R2 | MMC_CMD_BCR;
950	cmd.data = NULL;
951	err = mmc_wait_for_cmd(sc, &cmd, 0);
952	memcpy(rawcid, cmd.resp, 4 * sizeof(uint32_t));
953	return (err);
954}
955
956static int
957mmc_send_csd(struct mmc_softc *sc, uint16_t rca, uint32_t *rawcid)
958{
959	struct mmc_command cmd;
960	int err;
961
962	cmd.opcode = MMC_SEND_CSD;
963	cmd.arg = rca << 16;
964	cmd.flags = MMC_RSP_R2 | MMC_CMD_BCR;
965	cmd.data = NULL;
966	err = mmc_wait_for_cmd(sc, &cmd, 0);
967	memcpy(rawcid, cmd.resp, 4 * sizeof(uint32_t));
968	return (err);
969}
970
971static int
972mmc_app_send_scr(struct mmc_softc *sc, uint16_t rca, uint32_t *rawscr)
973{
974	int err;
975	struct mmc_command cmd;
976	struct mmc_data data;
977
978	memset(&cmd, 0, sizeof(struct mmc_command));
979	memset(&data, 0, sizeof(struct mmc_data));
980
981	memset(rawscr, 0, 8);
982	cmd.opcode = ACMD_SEND_SCR;
983	cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
984	cmd.arg = 0;
985	cmd.data = &data;
986
987	data.data = rawscr;
988	data.len = 8;
989	data.flags = MMC_DATA_READ;
990
991	err = mmc_wait_for_app_cmd(sc, rca, &cmd, CMD_RETRIES);
992	rawscr[0] = be32toh(rawscr[0]);
993	rawscr[1] = be32toh(rawscr[1]);
994	return (err);
995}
996
997static int
998mmc_send_ext_csd(struct mmc_softc *sc, uint8_t *rawextcsd)
999{
1000	int err;
1001	struct mmc_command cmd;
1002	struct mmc_data data;
1003
1004	memset(&cmd, 0, sizeof(struct mmc_command));
1005	memset(&data, 0, sizeof(struct mmc_data));
1006
1007	memset(rawextcsd, 0, 512);
1008	cmd.opcode = MMC_SEND_EXT_CSD;
1009	cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
1010	cmd.arg = 0;
1011	cmd.data = &data;
1012
1013	data.data = rawextcsd;
1014	data.len = 512;
1015	data.flags = MMC_DATA_READ;
1016
1017	err = mmc_wait_for_cmd(sc, &cmd, CMD_RETRIES);
1018	return (err);
1019}
1020
1021static int
1022mmc_app_sd_status(struct mmc_softc *sc, uint16_t rca, uint32_t *rawsdstatus)
1023{
1024	int err, i;
1025	struct mmc_command cmd;
1026	struct mmc_data data;
1027
1028	memset(&cmd, 0, sizeof(struct mmc_command));
1029	memset(&data, 0, sizeof(struct mmc_data));
1030
1031	memset(rawsdstatus, 0, 64);
1032	cmd.opcode = ACMD_SD_STATUS;
1033	cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
1034	cmd.arg = 0;
1035	cmd.data = &data;
1036
1037	data.data = rawsdstatus;
1038	data.len = 64;
1039	data.flags = MMC_DATA_READ;
1040
1041	err = mmc_wait_for_app_cmd(sc, rca, &cmd, CMD_RETRIES);
1042	for (i = 0; i < 16; i++)
1043	    rawsdstatus[i] = be32toh(rawsdstatus[i]);
1044	return (err);
1045}
1046
1047static int
1048mmc_set_relative_addr(struct mmc_softc *sc, uint16_t resp)
1049{
1050	struct mmc_command cmd;
1051	int err;
1052
1053	cmd.opcode = MMC_SET_RELATIVE_ADDR;
1054	cmd.arg = resp << 16;
1055	cmd.flags = MMC_RSP_R6 | MMC_CMD_BCR;
1056	cmd.data = NULL;
1057	err = mmc_wait_for_cmd(sc, &cmd, 0);
1058	return (err);
1059}
1060
1061static int
1062mmc_send_relative_addr(struct mmc_softc *sc, uint32_t *resp)
1063{
1064	struct mmc_command cmd;
1065	int err;
1066
1067	cmd.opcode = SD_SEND_RELATIVE_ADDR;
1068	cmd.arg = 0;
1069	cmd.flags = MMC_RSP_R6 | MMC_CMD_BCR;
1070	cmd.data = NULL;
1071	err = mmc_wait_for_cmd(sc, &cmd, 0);
1072	*resp = cmd.resp[0];
1073	return (err);
1074}
1075
1076static void
1077mmc_log_card(device_t dev, struct mmc_ivars *ivar, int newcard)
1078{
1079	device_printf(dev, "Card at relative address %d%s:\n",
1080	    ivar->rca, newcard ? " added" : "");
1081	device_printf(dev, " card: %s%s (0x%x/0x%x/\"%s\" rev %d.%d "
1082	    "m/d %02d.%04d s/n %08x)\n",
1083	    ivar->mode == mode_sd ? "SD" : "MMC",
1084	    ivar->high_cap ? " High Capacity" : "",
1085	    ivar->cid.mid, ivar->cid.oid,
1086	    ivar->cid.pnm, ivar->cid.prv >> 4, ivar->cid.prv & 0x0f,
1087	    ivar->cid.mdt_month, ivar->cid.mdt_year, ivar->cid.psn);
1088	device_printf(dev, " bus: %ubit, %uMHz%s\n",
1089	    (ivar->bus_width == bus_width_1 ? 1 :
1090	    (ivar->bus_width == bus_width_4 ? 4 : 8)),
1091	    (ivar->timing == bus_timing_hs ?
1092		ivar->hs_tran_speed : ivar->tran_speed) / 1000000,
1093	    ivar->timing == bus_timing_hs ? ", high speed timing" : "");
1094	device_printf(dev, " memory: %u blocks, erase sector %u blocks%s\n",
1095	    ivar->sec_count, ivar->erase_sector,
1096	    ivar->read_only ? ", read-only" : "");
1097}
1098
1099static void
1100mmc_discover_cards(struct mmc_softc *sc)
1101{
1102	struct mmc_ivars *ivar = NULL;
1103	device_t *devlist;
1104	int err, i, devcount, newcard;
1105	uint32_t raw_cid[4];
1106	uint32_t resp, sec_count;
1107	device_t child;
1108	uint16_t rca = 2;
1109	u_char switch_res[64];
1110
1111	if (bootverbose || mmc_debug)
1112		device_printf(sc->dev, "Probing cards\n");
1113	while (1) {
1114		err = mmc_all_send_cid(sc, raw_cid);
1115		if (err == MMC_ERR_TIMEOUT)
1116			break;
1117		if (err != MMC_ERR_NONE) {
1118			device_printf(sc->dev, "Error reading CID %d\n", err);
1119			break;
1120		}
1121		newcard = 1;
1122		if ((err = device_get_children(sc->dev, &devlist, &devcount)) != 0)
1123			return;
1124		for (i = 0; i < devcount; i++) {
1125			ivar = device_get_ivars(devlist[i]);
1126			if (memcmp(ivar->raw_cid, raw_cid, sizeof(raw_cid)) == 0) {
1127				newcard = 0;
1128				break;
1129			}
1130		}
1131		free(devlist, M_TEMP);
1132		if (bootverbose || mmc_debug) {
1133			device_printf(sc->dev, "%sard detected (CID %08x%08x%08x%08x)\n",
1134			    newcard ? "New c" : "C",
1135			    raw_cid[0], raw_cid[1], raw_cid[2], raw_cid[3]);
1136		}
1137		if (newcard) {
1138			ivar = malloc(sizeof(struct mmc_ivars), M_DEVBUF,
1139			    M_WAITOK | M_ZERO);
1140			if (!ivar)
1141				return;
1142			memcpy(ivar->raw_cid, raw_cid, sizeof(raw_cid));
1143		}
1144		if (mmcbr_get_ro(sc->dev))
1145			ivar->read_only = 1;
1146		ivar->bus_width = bus_width_1;
1147		ivar->mode = mmcbr_get_mode(sc->dev);
1148		if (ivar->mode == mode_sd) {
1149			mmc_decode_cid_sd(ivar->raw_cid, &ivar->cid);
1150			mmc_send_relative_addr(sc, &resp);
1151			ivar->rca = resp >> 16;
1152			/* Get card CSD. */
1153			mmc_send_csd(sc, ivar->rca, ivar->raw_csd);
1154			mmc_decode_csd_sd(ivar->raw_csd, &ivar->csd);
1155			ivar->sec_count = ivar->csd.capacity / MMC_SECTOR_SIZE;
1156			if (ivar->csd.csd_structure > 0)
1157				ivar->high_cap = 1;
1158			ivar->tran_speed = ivar->csd.tran_speed;
1159			ivar->erase_sector = ivar->csd.erase_sector *
1160			    ivar->csd.write_bl_len / MMC_SECTOR_SIZE;
1161			/* Get card SCR. Card must be selected to fetch it. */
1162			mmc_select_card(sc, ivar->rca);
1163			mmc_app_send_scr(sc, ivar->rca, ivar->raw_scr);
1164			mmc_app_decode_scr(ivar->raw_scr, &ivar->scr);
1165			/* Get card switch capabilities. */
1166			ivar->timing = bus_timing_normal;
1167			if ((ivar->scr.sda_vsn >= 1) &&
1168			    (ivar->csd.ccc & (1<<10))) {
1169				mmc_sd_switch(sc, 0, 0, 0xF, switch_res);
1170				if (switch_res[13] & 2) {
1171					ivar->timing = bus_timing_hs;
1172					ivar->hs_tran_speed = 50000000;
1173				}
1174			}
1175			mmc_app_sd_status(sc, ivar->rca, ivar->raw_sd_status);
1176			mmc_app_decode_sd_status(ivar->raw_sd_status,
1177			    &ivar->sd_status);
1178			if (ivar->sd_status.au_size != 0) {
1179				ivar->erase_sector =
1180				    16 << ivar->sd_status.au_size;
1181			}
1182			mmc_select_card(sc, 0);
1183			/* Find max supported bus width. */
1184			if ((mmcbr_get_caps(sc->dev) & MMC_CAP_4_BIT_DATA) &&
1185			    (ivar->scr.bus_widths & SD_SCR_BUS_WIDTH_4))
1186				ivar->bus_width = bus_width_4;
1187			if (bootverbose || mmc_debug)
1188				mmc_log_card(sc->dev, ivar, newcard);
1189			if (newcard) {
1190				/* Add device. */
1191				child = device_add_child(sc->dev, NULL, -1);
1192				device_set_ivars(child, ivar);
1193			}
1194			return;
1195		}
1196		mmc_decode_cid_mmc(ivar->raw_cid, &ivar->cid);
1197		ivar->rca = rca++;
1198		mmc_set_relative_addr(sc, ivar->rca);
1199		/* Get card CSD. */
1200		mmc_send_csd(sc, ivar->rca, ivar->raw_csd);
1201		mmc_decode_csd_mmc(ivar->raw_csd, &ivar->csd);
1202		ivar->sec_count = ivar->csd.capacity / MMC_SECTOR_SIZE;
1203		ivar->tran_speed = ivar->csd.tran_speed;
1204		ivar->erase_sector = ivar->csd.erase_sector *
1205		    ivar->csd.write_bl_len / MMC_SECTOR_SIZE;
1206		/* Only MMC >= 4.x cards support EXT_CSD. */
1207		if (ivar->csd.spec_vers >= 4) {
1208			/* Card must be selected to fetch EXT_CSD. */
1209			mmc_select_card(sc, ivar->rca);
1210			mmc_send_ext_csd(sc, ivar->raw_ext_csd);
1211			/* Handle extended capacity from EXT_CSD */
1212			sec_count = ivar->raw_ext_csd[EXT_CSD_SEC_CNT] +
1213			    (ivar->raw_ext_csd[EXT_CSD_SEC_CNT + 1] << 8) +
1214			    (ivar->raw_ext_csd[EXT_CSD_SEC_CNT + 2] << 16) +
1215			    (ivar->raw_ext_csd[EXT_CSD_SEC_CNT + 3] << 24);
1216			if (sec_count != 0) {
1217				ivar->sec_count = sec_count;
1218				ivar->high_cap = 1;
1219			}
1220			/* Get card speed in high speed mode. */
1221			ivar->timing = bus_timing_hs;
1222			if (ivar->raw_ext_csd[EXT_CSD_CARD_TYPE]
1223			    & EXT_CSD_CARD_TYPE_52)
1224				ivar->hs_tran_speed = 52000000;
1225			else if (ivar->raw_ext_csd[EXT_CSD_CARD_TYPE]
1226			    & EXT_CSD_CARD_TYPE_26)
1227				ivar->hs_tran_speed = 26000000;
1228			else
1229				ivar->hs_tran_speed = ivar->tran_speed;
1230			/* Find max supported bus width. */
1231			ivar->bus_width = mmc_test_bus_width(sc);
1232			mmc_select_card(sc, 0);
1233			/* Handle HC erase sector size. */
1234			if (ivar->raw_ext_csd[EXT_CSD_ERASE_GRP_SIZE] != 0) {
1235				ivar->erase_sector = 1024 *
1236				    ivar->raw_ext_csd[EXT_CSD_ERASE_GRP_SIZE];
1237				mmc_switch(sc, EXT_CSD_CMD_SET_NORMAL,
1238				    EXT_CSD_ERASE_GRP_DEF, 1);
1239			}
1240		} else {
1241			ivar->bus_width = bus_width_1;
1242			ivar->timing = bus_timing_normal;
1243		}
1244		if (bootverbose || mmc_debug)
1245			mmc_log_card(sc->dev, ivar, newcard);
1246		if (newcard) {
1247			/* Add device. */
1248			child = device_add_child(sc->dev, NULL, -1);
1249			device_set_ivars(child, ivar);
1250		}
1251	}
1252}
1253
1254static void
1255mmc_rescan_cards(struct mmc_softc *sc)
1256{
1257	struct mmc_ivars *ivar = NULL;
1258	device_t *devlist;
1259	int err, i, devcount;
1260
1261	if ((err = device_get_children(sc->dev, &devlist, &devcount)) != 0)
1262		return;
1263	for (i = 0; i < devcount; i++) {
1264		ivar = device_get_ivars(devlist[i]);
1265		if (mmc_select_card(sc, ivar->rca)) {
1266			if (bootverbose || mmc_debug)
1267				device_printf(sc->dev, "Card at relative address %d lost.\n",
1268				    ivar->rca);
1269			device_delete_child(sc->dev, devlist[i]);
1270			free(ivar, M_DEVBUF);
1271		}
1272	}
1273	free(devlist, M_TEMP);
1274	mmc_select_card(sc, 0);
1275}
1276
1277static int
1278mmc_delete_cards(struct mmc_softc *sc)
1279{
1280	struct mmc_ivars *ivar;
1281	device_t *devlist;
1282	int err, i, devcount;
1283
1284	if ((err = device_get_children(sc->dev, &devlist, &devcount)) != 0)
1285		return (err);
1286	for (i = 0; i < devcount; i++) {
1287		ivar = device_get_ivars(devlist[i]);
1288		if (bootverbose || mmc_debug)
1289			device_printf(sc->dev, "Card at relative address %d deleted.\n",
1290			    ivar->rca);
1291		device_delete_child(sc->dev, devlist[i]);
1292		free(ivar, M_DEVBUF);
1293	}
1294	free(devlist, M_TEMP);
1295	return (0);
1296}
1297
1298static void
1299mmc_go_discovery(struct mmc_softc *sc)
1300{
1301	uint32_t ocr;
1302	device_t dev;
1303	int err;
1304
1305	dev = sc->dev;
1306	if (mmcbr_get_power_mode(dev) != power_on) {
1307		/*
1308		 * First, try SD modes
1309		 */
1310		mmcbr_set_mode(dev, mode_sd);
1311		mmc_power_up(sc);
1312		mmcbr_set_bus_mode(dev, pushpull);
1313		if (bootverbose || mmc_debug)
1314			device_printf(sc->dev, "Probing bus\n");
1315		mmc_idle_cards(sc);
1316		err = mmc_send_if_cond(sc, 1);
1317		if ((bootverbose || mmc_debug) && err == 0)
1318			device_printf(sc->dev, "SD 2.0 interface conditions: OK\n");
1319		if (mmc_send_app_op_cond(sc, err ? 0 : MMC_OCR_CCS, &ocr) !=
1320		    MMC_ERR_NONE) {
1321			if (bootverbose || mmc_debug)
1322				device_printf(sc->dev, "SD probe: failed\n");
1323			/*
1324			 * Failed, try MMC
1325			 */
1326			mmcbr_set_mode(dev, mode_mmc);
1327			if (mmc_send_op_cond(sc, 0, &ocr) != MMC_ERR_NONE) {
1328				if (bootverbose || mmc_debug)
1329					device_printf(sc->dev, "MMC probe: failed\n");
1330				ocr = 0; /* Failed both, powerdown. */
1331			} else if (bootverbose || mmc_debug)
1332				device_printf(sc->dev,
1333				    "MMC probe: OK (OCR: 0x%08x)\n", ocr);
1334		} else if (bootverbose || mmc_debug)
1335			device_printf(sc->dev, "SD probe: OK (OCR: 0x%08x)\n", ocr);
1336
1337		mmcbr_set_ocr(dev, mmc_select_vdd(sc, ocr));
1338		if (mmcbr_get_ocr(dev) != 0)
1339			mmc_idle_cards(sc);
1340	} else {
1341		mmcbr_set_bus_mode(dev, opendrain);
1342		mmcbr_set_clock(dev, mmcbr_get_f_min(dev));
1343		mmcbr_update_ios(dev);
1344		/* XXX recompute vdd based on new cards? */
1345	}
1346	/*
1347	 * Make sure that we have a mutually agreeable voltage to at least
1348	 * one card on the bus.
1349	 */
1350	if (bootverbose || mmc_debug)
1351		device_printf(sc->dev, "Current OCR: 0x%08x\n", mmcbr_get_ocr(dev));
1352	if (mmcbr_get_ocr(dev) == 0) {
1353		mmc_delete_cards(sc);
1354		mmc_power_down(sc);
1355		return;
1356	}
1357	/*
1358	 * Reselect the cards after we've idled them above.
1359	 */
1360	if (mmcbr_get_mode(dev) == mode_sd) {
1361		err = mmc_send_if_cond(sc, 1);
1362		mmc_send_app_op_cond(sc,
1363		    (err ? 0 : MMC_OCR_CCS) | mmcbr_get_ocr(dev), NULL);
1364	} else
1365		mmc_send_op_cond(sc, mmcbr_get_ocr(dev), NULL);
1366	mmc_discover_cards(sc);
1367	mmc_rescan_cards(sc);
1368
1369	mmcbr_set_bus_mode(dev, pushpull);
1370	mmcbr_update_ios(dev);
1371	mmc_calculate_clock(sc);
1372	bus_generic_attach(dev);
1373/*	mmc_update_children_sysctl(dev);*/
1374}
1375
1376static int
1377mmc_calculate_clock(struct mmc_softc *sc)
1378{
1379	int max_dtr, max_hs_dtr, max_timing;
1380	int nkid, i, f_min, f_max;
1381	device_t *kids;
1382	struct mmc_ivars *ivar;
1383
1384	f_min = mmcbr_get_f_min(sc->dev);
1385	f_max = mmcbr_get_f_max(sc->dev);
1386	max_dtr = max_hs_dtr = f_max;
1387	if ((mmcbr_get_caps(sc->dev) & MMC_CAP_HSPEED))
1388		max_timing = bus_timing_hs;
1389	else
1390		max_timing = bus_timing_normal;
1391	if (device_get_children(sc->dev, &kids, &nkid) != 0)
1392		panic("can't get children");
1393	for (i = 0; i < nkid; i++) {
1394		ivar = device_get_ivars(kids[i]);
1395		if (ivar->timing < max_timing)
1396			max_timing = ivar->timing;
1397		if (ivar->tran_speed < max_dtr)
1398			max_dtr = ivar->tran_speed;
1399		if (ivar->hs_tran_speed < max_hs_dtr)
1400			max_hs_dtr = ivar->hs_tran_speed;
1401	}
1402	for (i = 0; i < nkid; i++) {
1403		ivar = device_get_ivars(kids[i]);
1404		if (ivar->timing == bus_timing_normal)
1405			continue;
1406		mmc_select_card(sc, ivar->rca);
1407		mmc_set_timing(sc, max_timing);
1408	}
1409	mmc_select_card(sc, 0);
1410	free(kids, M_TEMP);
1411	if (max_timing == bus_timing_hs)
1412		max_dtr = max_hs_dtr;
1413	if (bootverbose || mmc_debug) {
1414		device_printf(sc->dev,
1415		    "setting transfer rate to %d.%03dMHz%s\n",
1416		    max_dtr / 1000000, (max_dtr / 1000) % 1000,
1417		    max_timing == bus_timing_hs ? " (high speed timing)" : "");
1418	}
1419	mmcbr_set_timing(sc->dev, max_timing);
1420	mmcbr_set_clock(sc->dev, max_dtr);
1421	mmcbr_update_ios(sc->dev);
1422	return max_dtr;
1423}
1424
1425static void
1426mmc_scan(struct mmc_softc *sc)
1427{
1428	device_t dev = sc->dev;
1429
1430	mmc_acquire_bus(dev, dev);
1431	mmc_go_discovery(sc);
1432	mmc_release_bus(dev, dev);
1433}
1434
1435static int
1436mmc_read_ivar(device_t bus, device_t child, int which, u_char *result)
1437{
1438	struct mmc_ivars *ivar = device_get_ivars(child);
1439
1440	switch (which) {
1441	default:
1442		return (EINVAL);
1443	case MMC_IVAR_DSR_IMP:
1444		*(int *)result = ivar->csd.dsr_imp;
1445		break;
1446	case MMC_IVAR_MEDIA_SIZE:
1447		*(off_t *)result = ivar->sec_count;
1448		break;
1449	case MMC_IVAR_RCA:
1450		*(int *)result = ivar->rca;
1451		break;
1452	case MMC_IVAR_SECTOR_SIZE:
1453		*(int *)result = MMC_SECTOR_SIZE;
1454		break;
1455	case MMC_IVAR_TRAN_SPEED:
1456		*(int *)result = mmcbr_get_clock(bus);
1457		break;
1458	case MMC_IVAR_READ_ONLY:
1459		*(int *)result = ivar->read_only;
1460		break;
1461	case MMC_IVAR_HIGH_CAP:
1462		*(int *)result = ivar->high_cap;
1463		break;
1464	case MMC_IVAR_CARD_TYPE:
1465		*(int *)result = ivar->mode;
1466		break;
1467	case MMC_IVAR_BUS_WIDTH:
1468		*(int *)result = ivar->bus_width;
1469		break;
1470	case MMC_IVAR_ERASE_SECTOR:
1471		*(int *)result = ivar->erase_sector;
1472		break;
1473	case MMC_IVAR_MAX_DATA:
1474		*(int *)result = mmcbr_get_max_data(bus);
1475		break;
1476	}
1477	return (0);
1478}
1479
1480static int
1481mmc_write_ivar(device_t bus, device_t child, int which, uintptr_t value)
1482{
1483	/*
1484	 * None are writable ATM
1485	 */
1486	return (EINVAL);
1487}
1488
1489
1490static void
1491mmc_delayed_attach(void *xsc)
1492{
1493	struct mmc_softc *sc = xsc;
1494
1495	mmc_scan(sc);
1496	config_intrhook_disestablish(&sc->config_intrhook);
1497}
1498
1499static device_method_t mmc_methods[] = {
1500	/* device_if */
1501	DEVMETHOD(device_probe, mmc_probe),
1502	DEVMETHOD(device_attach, mmc_attach),
1503	DEVMETHOD(device_detach, mmc_detach),
1504	DEVMETHOD(device_suspend, mmc_suspend),
1505	DEVMETHOD(device_resume, mmc_resume),
1506
1507	/* Bus interface */
1508	DEVMETHOD(bus_read_ivar, mmc_read_ivar),
1509	DEVMETHOD(bus_write_ivar, mmc_write_ivar),
1510
1511	/* MMC Bus interface */
1512	DEVMETHOD(mmcbus_wait_for_request, mmc_wait_for_request),
1513	DEVMETHOD(mmcbus_acquire_bus, mmc_acquire_bus),
1514	DEVMETHOD(mmcbus_release_bus, mmc_release_bus),
1515
1516	{0, 0},
1517};
1518
1519static driver_t mmc_driver = {
1520	"mmc",
1521	mmc_methods,
1522	sizeof(struct mmc_softc),
1523};
1524static devclass_t mmc_devclass;
1525
1526
1527DRIVER_MODULE(mmc, at91_mci, mmc_driver, mmc_devclass, 0, 0);
1528DRIVER_MODULE(mmc, sdhci, mmc_driver, mmc_devclass, 0, 0);
1529