xref: /freebsd/sys/dev/mmc/mmcsd.c (revision c685956956793831f724177309eace82c4b347b9)
1 /*-
2  * Copyright (c) 2006 Bernd Walter.  All rights reserved.
3  * Copyright (c) 2006 M. Warner Losh.  All rights reserved.
4  * Copyright (c) 2017 Marius Strobl <marius@FreeBSD.org>
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  *
26  * Portions of this software may have been developed with reference to
27  * the SD Simplified Specification.  The following disclaimer may apply:
28  *
29  * The following conditions apply to the release of the simplified
30  * specification ("Simplified Specification") by the SD Card Association and
31  * the SD Group. The Simplified Specification is a subset of the complete SD
32  * Specification which is owned by the SD Card Association and the SD
33  * Group. This Simplified Specification is provided on a non-confidential
34  * basis subject to the disclaimers below. Any implementation of the
35  * Simplified Specification may require a license from the SD Card
36  * Association, SD Group, SD-3C LLC or other third parties.
37  *
38  * Disclaimers:
39  *
40  * The information contained in the Simplified Specification is presented only
41  * as a standard specification for SD Cards and SD Host/Ancillary products and
42  * is provided "AS-IS" without any representations or warranties of any
43  * kind. No responsibility is assumed by the SD Group, SD-3C LLC or the SD
44  * Card Association for any damages, any infringements of patents or other
45  * right of the SD Group, SD-3C LLC, the SD Card Association or any third
46  * parties, which may result from its use. No license is granted by
47  * implication, estoppel or otherwise under any patent or other rights of the
48  * SD Group, SD-3C LLC, the SD Card Association or any third party. Nothing
49  * herein shall be construed as an obligation by the SD Group, the SD-3C LLC
50  * or the SD Card Association to disclose or distribute any technical
51  * information, know-how or other confidential information to any third party.
52  */
53 
54 #include <sys/cdefs.h>
55 __FBSDID("$FreeBSD$");
56 
57 #include <sys/param.h>
58 #include <sys/systm.h>
59 #include <sys/bio.h>
60 #include <sys/bus.h>
61 #include <sys/conf.h>
62 #include <sys/fcntl.h>
63 #include <sys/ioccom.h>
64 #include <sys/kernel.h>
65 #include <sys/kthread.h>
66 #include <sys/lock.h>
67 #include <sys/malloc.h>
68 #include <sys/module.h>
69 #include <sys/mutex.h>
70 #include <sys/slicer.h>
71 #include <sys/time.h>
72 
73 #include <geom/geom.h>
74 #include <geom/geom_disk.h>
75 
76 #include <dev/mmc/bridge.h>
77 #include <dev/mmc/mmc_ioctl.h>
78 #include <dev/mmc/mmc_subr.h>
79 #include <dev/mmc/mmcbrvar.h>
80 #include <dev/mmc/mmcreg.h>
81 #include <dev/mmc/mmcvar.h>
82 
83 #include "mmcbus_if.h"
84 
85 #if __FreeBSD_version < 800002
86 #define	kproc_create	kthread_create
87 #define	kproc_exit	kthread_exit
88 #endif
89 
90 #define	MMCSD_CMD_RETRIES	5
91 
92 #define	MMCSD_FMT_BOOT		"mmcsd%dboot"
93 #define	MMCSD_FMT_GP		"mmcsd%dgp"
94 #define	MMCSD_FMT_RPMB		"mmcsd%drpmb"
95 #define	MMCSD_LABEL_ENH		"enh"
96 
97 #define	MMCSD_PART_NAMELEN	(16 + 1)
98 
99 struct mmcsd_softc;
100 
101 struct mmcsd_part {
102 	struct mtx disk_mtx;
103 	struct mtx ioctl_mtx;
104 	struct mmcsd_softc *sc;
105 	struct disk *disk;
106 	struct proc *p;
107 	struct bio_queue_head bio_queue;
108 	daddr_t eblock, eend;	/* Range remaining after the last erase. */
109 	u_int cnt;
110 	u_int type;
111 	int running;
112 	int suspend;
113 	int ioctl;
114 	bool ro;
115 	char name[MMCSD_PART_NAMELEN];
116 };
117 
118 struct mmcsd_softc {
119 	device_t dev;
120 	device_t mmcbr;
121 	struct mmcsd_part *part[MMC_PART_MAX];
122 	enum mmc_card_mode mode;
123 	u_int max_data;		/* Maximum data size [blocks] */
124 	u_int erase_sector;	/* Device native erase sector size [blocks] */
125 	uint8_t	high_cap;	/* High Capacity device (block addressed) */
126 	uint8_t part_curr;	/* Partition currently switched to */
127 	uint8_t ext_csd[MMC_EXTCSD_SIZE];
128 	uint16_t rca;
129 	uint32_t part_time;	/* Partition switch timeout [us] */
130 	off_t enh_base;		/* Enhanced user data area slice base ... */
131 	off_t enh_size;		/* ... and size [bytes] */
132 	int log_count;
133 	struct timeval log_time;
134 	struct cdev *rpmb_dev;
135 };
136 
137 static const char *errmsg[] =
138 {
139 	"None",
140 	"Timeout",
141 	"Bad CRC",
142 	"Fifo",
143 	"Failed",
144 	"Invalid",
145 	"NO MEMORY"
146 };
147 
148 #define	LOG_PPS		5 /* Log no more than 5 errors per second. */
149 
150 /* bus entry points */
151 static int mmcsd_attach(device_t dev);
152 static int mmcsd_detach(device_t dev);
153 static int mmcsd_probe(device_t dev);
154 
155 /* disk routines */
156 static int mmcsd_close(struct disk *dp);
157 static int mmcsd_dump(void *arg, void *virtual, vm_offset_t physical,
158     off_t offset, size_t length);
159 static int mmcsd_getattr(struct bio *);
160 static int mmcsd_ioctl_disk(struct disk *disk, u_long cmd, void *data,
161     int fflag, struct thread *td);
162 static int mmcsd_open(struct disk *dp);
163 static void mmcsd_strategy(struct bio *bp);
164 static void mmcsd_task(void *arg);
165 
166 /* RMPB cdev interface */
167 static int mmcsd_ioctl_rpmb(struct cdev *dev, u_long cmd, caddr_t data,
168     int fflag, struct thread *td);
169 
170 static void mmcsd_add_part(struct mmcsd_softc *sc, u_int type,
171     const char *name, u_int cnt, off_t media_size, off_t erase_size, bool ro);
172 static int mmcsd_bus_bit_width(device_t dev);
173 static daddr_t mmcsd_delete(struct mmcsd_part *part, struct bio *bp);
174 static int mmcsd_ioctl(struct mmcsd_part *part, u_long cmd, void *data,
175     int fflag);
176 static int mmcsd_ioctl_cmd(struct mmcsd_part *part, struct mmc_ioc_cmd *mic,
177     int fflag);
178 static uintmax_t mmcsd_pretty_size(off_t size, char *unit);
179 static daddr_t mmcsd_rw(struct mmcsd_part *part, struct bio *bp);
180 static int mmcsd_set_blockcount(struct mmcsd_softc *sc, u_int count, bool rel);
181 static int mmcsd_slicer(device_t dev, const char *provider,
182     struct flash_slice *slices, int *nslices);
183 static int mmcsd_switch_part(device_t bus, device_t dev, uint16_t rca,
184     u_int part);
185 
186 #define	MMCSD_DISK_LOCK(_part)		mtx_lock(&(_part)->disk_mtx)
187 #define	MMCSD_DISK_UNLOCK(_part)	mtx_unlock(&(_part)->disk_mtx)
188 #define	MMCSD_DISK_LOCK_INIT(_part)					\
189 	mtx_init(&(_part)->disk_mtx, (_part)->name, "mmcsd disk", MTX_DEF)
190 #define	MMCSD_DISK_LOCK_DESTROY(_part)	mtx_destroy(&(_part)->disk_mtx);
191 #define	MMCSD_DISK_ASSERT_LOCKED(_part)					\
192 	mtx_assert(&(_part)->disk_mtx, MA_OWNED);
193 #define	MMCSD_DISK_ASSERT_UNLOCKED(_part)				\
194 	mtx_assert(&(_part)->disk_mtx, MA_NOTOWNED);
195 
196 #define	MMCSD_IOCTL_LOCK(_part)		mtx_lock(&(_part)->ioctl_mtx)
197 #define	MMCSD_IOCTL_UNLOCK(_part)	mtx_unlock(&(_part)->ioctl_mtx)
198 #define	MMCSD_IOCTL_LOCK_INIT(_part)					\
199 	mtx_init(&(_part)->ioctl_mtx, (_part)->name, "mmcsd IOCTL", MTX_DEF)
200 #define	MMCSD_IOCTL_LOCK_DESTROY(_part)	mtx_destroy(&(_part)->ioctl_mtx);
201 #define	MMCSD_IOCTL_ASSERT_LOCKED(_part)				\
202 	mtx_assert(&(_part)->ioctl_mtx, MA_OWNED);
203 #define	MMCSD_IOCLT_ASSERT_UNLOCKED(_part)				\
204 	mtx_assert(&(_part)->ioctl_mtx, MA_NOTOWNED);
205 
206 static int
207 mmcsd_probe(device_t dev)
208 {
209 
210 	device_quiet(dev);
211 	device_set_desc(dev, "MMC/SD Memory Card");
212 	return (0);
213 }
214 
215 static int
216 mmcsd_attach(device_t dev)
217 {
218 	device_t mmcbr;
219 	struct mmcsd_softc *sc;
220 	const uint8_t *ext_csd;
221 	off_t erase_size, sector_size, size, wp_size;
222 	uintmax_t bytes;
223 	int err, i;
224 	uint8_t rev;
225 	bool comp, ro;
226 	char unit[2];
227 
228 	sc = device_get_softc(dev);
229 	sc->dev = dev;
230 	sc->mmcbr = mmcbr = device_get_parent(dev);
231 	sc->mode = mmcbr_get_mode(mmcbr);
232 	/*
233 	 * Note that in principle with an SDHCI-like re-tuning implementation,
234 	 * the maximum data size can change at runtime due to a device removal/
235 	 * insertion that results in switches to/from a transfer mode involving
236 	 * re-tuning, iff there are multiple devices on a given bus.  Until now
237 	 * mmc(4) lacks support for rescanning already attached buses, however,
238 	 * and sdhci(4) to date has no support for shared buses in the first
239 	 * place either.
240 	 */
241 	sc->max_data = mmc_get_max_data(dev);
242 	sc->erase_sector = mmc_get_erase_sector(dev);
243 	sc->high_cap = mmc_get_high_cap(dev);
244 	sc->rca = mmc_get_rca(dev);
245 
246 	/* Only MMC >= 4.x devices support EXT_CSD. */
247 	if (mmc_get_spec_vers(dev) >= 4) {
248 		MMCBUS_ACQUIRE_BUS(mmcbr, dev);
249 		err = mmc_send_ext_csd(mmcbr, dev, sc->ext_csd);
250 		MMCBUS_RELEASE_BUS(mmcbr, dev);
251 		if (err != MMC_ERR_NONE)
252 			bzero(sc->ext_csd, sizeof(sc->ext_csd));
253 	}
254 	ext_csd = sc->ext_csd;
255 
256 	/*
257 	 * Enhanced user data area and general purpose partitions are only
258 	 * supported in revision 1.4 (EXT_CSD_REV == 4) and later, the RPMB
259 	 * partition in revision 1.5 (MMC v4.41, EXT_CSD_REV == 5) and later.
260 	 */
261 	rev = ext_csd[EXT_CSD_REV];
262 
263 	/*
264 	 * Ignore user-creatable enhanced user data area and general purpose
265 	 * partitions partitions as long as partitioning hasn't been finished.
266 	 */
267 	comp = (ext_csd[EXT_CSD_PART_SET] & EXT_CSD_PART_SET_COMPLETED) != 0;
268 
269 	/*
270 	 * Add enhanced user data area slice, unless it spans the entirety of
271 	 * the user data area.  The enhanced area is of a multiple of high
272 	 * capacity write protect groups ((ERASE_GRP_SIZE + HC_WP_GRP_SIZE) *
273 	 * 512 KB) and its offset given in either sectors or bytes, depending
274 	 * on whether it's a high capacity device or not.
275 	 * NB: The slicer and its slices need to be registered before adding
276 	 *     the disk for the corresponding user data area as re-tasting is
277 	 *     racy.
278 	 */
279 	sector_size = mmc_get_sector_size(dev);
280 	size = ext_csd[EXT_CSD_ENH_SIZE_MULT] +
281 	    (ext_csd[EXT_CSD_ENH_SIZE_MULT + 1] << 8) +
282 	    (ext_csd[EXT_CSD_ENH_SIZE_MULT + 2] << 16);
283 	if (rev >= 4 && comp == TRUE && size > 0 &&
284 	    (ext_csd[EXT_CSD_PART_SUPPORT] &
285 	    EXT_CSD_PART_SUPPORT_ENH_ATTR_EN) != 0 &&
286 	    (ext_csd[EXT_CSD_PART_ATTR] & (EXT_CSD_PART_ATTR_ENH_USR)) != 0) {
287 		erase_size = ext_csd[EXT_CSD_ERASE_GRP_SIZE] * 1024 *
288 		    MMC_SECTOR_SIZE;
289 		wp_size = ext_csd[EXT_CSD_HC_WP_GRP_SIZE];
290 		size *= erase_size * wp_size;
291 		if (size != mmc_get_media_size(dev) * sector_size) {
292 			sc->enh_size = size;
293 			sc->enh_base = (ext_csd[EXT_CSD_ENH_START_ADDR] +
294 			    (ext_csd[EXT_CSD_ENH_START_ADDR + 1] << 8) +
295 			    (ext_csd[EXT_CSD_ENH_START_ADDR + 2] << 16) +
296 			    (ext_csd[EXT_CSD_ENH_START_ADDR + 3] << 24)) *
297 			    (sc->high_cap != 0 ? MMC_SECTOR_SIZE : 1);
298 		} else if (bootverbose)
299 			device_printf(dev,
300 			    "enhanced user data area spans entire device\n");
301 	}
302 
303 	/*
304 	 * Add default partition.  This may be the only one or the user
305 	 * data area in case partitions are supported.
306 	 */
307 	ro = mmc_get_read_only(dev);
308 	mmcsd_add_part(sc, EXT_CSD_PART_CONFIG_ACC_DEFAULT, "mmcsd",
309 	    device_get_unit(dev), mmc_get_media_size(dev) * sector_size,
310 	    sc->erase_sector * sector_size, ro);
311 
312 	if (mmc_get_spec_vers(dev) < 3)
313 		return (0);
314 
315 	/* Belatedly announce enhanced user data slice. */
316 	if (sc->enh_size != 0) {
317 		bytes = mmcsd_pretty_size(size, unit);
318 		printf(FLASH_SLICES_FMT ": %ju%sB enhanced user data area "
319 		    "slice offset 0x%jx at %s\n", device_get_nameunit(dev),
320 		    MMCSD_LABEL_ENH, bytes, unit, (uintmax_t)sc->enh_base,
321 		    device_get_nameunit(dev));
322 	}
323 
324 	/*
325 	 * Determine partition switch timeout (provided in units of 10 ms)
326 	 * and ensure it's at least 300 ms as some eMMC chips lie.
327 	 */
328 	sc->part_time = max(ext_csd[EXT_CSD_PART_SWITCH_TO] * 10 * 1000,
329 	    300 * 1000);
330 
331 	/* Add boot partitions, which are of a fixed multiple of 128 KB. */
332 	size = ext_csd[EXT_CSD_BOOT_SIZE_MULT] * MMC_BOOT_RPMB_BLOCK_SIZE;
333 	if (size > 0 && (mmcbr_get_caps(mmcbr) & MMC_CAP_BOOT_NOACC) == 0) {
334 		mmcsd_add_part(sc, EXT_CSD_PART_CONFIG_ACC_BOOT0,
335 		    MMCSD_FMT_BOOT, 0, size, MMC_BOOT_RPMB_BLOCK_SIZE,
336 		    ro | ((ext_csd[EXT_CSD_BOOT_WP_STATUS] &
337 		    EXT_CSD_BOOT_WP_STATUS_BOOT0_MASK) != 0));
338 		mmcsd_add_part(sc, EXT_CSD_PART_CONFIG_ACC_BOOT1,
339 		    MMCSD_FMT_BOOT, 1, size, MMC_BOOT_RPMB_BLOCK_SIZE,
340 		    ro | ((ext_csd[EXT_CSD_BOOT_WP_STATUS] &
341 		    EXT_CSD_BOOT_WP_STATUS_BOOT1_MASK) != 0));
342 	}
343 
344 	/* Add RPMB partition, which also is of a fixed multiple of 128 KB. */
345 	size = ext_csd[EXT_CSD_RPMB_MULT] * MMC_BOOT_RPMB_BLOCK_SIZE;
346 	if (rev >= 5 && size > 0)
347 		mmcsd_add_part(sc, EXT_CSD_PART_CONFIG_ACC_RPMB,
348 		    MMCSD_FMT_RPMB, 0, size, MMC_BOOT_RPMB_BLOCK_SIZE, ro);
349 
350 	if (rev <= 3 || comp == FALSE)
351 		return (0);
352 
353 	/*
354 	 * Add general purpose partitions, which are of a multiple of high
355 	 * capacity write protect groups, too.
356 	 */
357 	if ((ext_csd[EXT_CSD_PART_SUPPORT] & EXT_CSD_PART_SUPPORT_EN) != 0) {
358 		erase_size = ext_csd[EXT_CSD_ERASE_GRP_SIZE] * 1024 *
359 		    MMC_SECTOR_SIZE;
360 		wp_size = ext_csd[EXT_CSD_HC_WP_GRP_SIZE];
361 		for (i = 0; i < MMC_PART_GP_MAX; i++) {
362 			size = ext_csd[EXT_CSD_GP_SIZE_MULT + i * 3] +
363 			    (ext_csd[EXT_CSD_GP_SIZE_MULT + i * 3 + 1] << 8) +
364 			    (ext_csd[EXT_CSD_GP_SIZE_MULT + i * 3 + 2] << 16);
365 			if (size == 0)
366 				continue;
367 			mmcsd_add_part(sc, EXT_CSD_PART_CONFIG_ACC_GP0 + i,
368 			    MMCSD_FMT_GP, i, size * erase_size * wp_size,
369 			    erase_size, ro);
370 		}
371 	}
372 	return (0);
373 }
374 
375 static uintmax_t
376 mmcsd_pretty_size(off_t size, char *unit)
377 {
378 	uintmax_t bytes;
379 	int i;
380 
381 	/*
382 	 * Display in most natural units.  There's no card < 1MB.  However,
383 	 * RPMB partitions occasionally are smaller than that, though.  The
384 	 * SD standard goes to 2 GiB due to its reliance on FAT, but the data
385 	 * format supports up to 4 GiB and some card makers push it up to this
386 	 * limit.  The SDHC standard only goes to 32 GiB due to FAT32, but the
387 	 * data format supports up to 2 TiB however.  2048 GB isn't too ugly,
388 	 * so we note it in passing here and don't add the code to print TB).
389 	 * Since these cards are sold in terms of MB and GB not MiB and GiB,
390 	 * report them like that.  We also round to the nearest unit, since
391 	 * many cards are a few percent short, even of the power of 10 size.
392 	 */
393 	bytes = size;
394 	unit[0] = unit[1] = '\0';
395 	for (i = 0; i <= 2 && bytes >= 1000; i++) {
396 		bytes = (bytes + 1000 / 2 - 1) / 1000;
397 		switch (i) {
398 		case 0:
399 			unit[0] = 'k';
400 			break;
401 		case 1:
402 			unit[0] = 'M';
403 			break;
404 		case 2:
405 			unit[0] = 'G';
406 			break;
407 		default:
408 			break;
409 		}
410 	}
411 	return (bytes);
412 }
413 
414 static struct cdevsw mmcsd_rpmb_cdevsw = {
415 	.d_version	= D_VERSION,
416 	.d_name		= "mmcsdrpmb",
417 	.d_ioctl	= mmcsd_ioctl_rpmb
418 };
419 
420 static void
421 mmcsd_add_part(struct mmcsd_softc *sc, u_int type, const char *name, u_int cnt,
422     off_t media_size, off_t erase_size, bool ro)
423 {
424 	struct make_dev_args args;
425 	device_t dev, mmcbr;
426 	const char *ext;
427 	const uint8_t *ext_csd;
428 	struct mmcsd_part *part;
429 	struct disk *d;
430 	uintmax_t bytes;
431 	u_int gp;
432 	uint32_t speed;
433 	uint8_t extattr;
434 	bool enh;
435 	char unit[2];
436 
437 	dev = sc->dev;
438 	mmcbr = sc->mmcbr;
439 	part = sc->part[type] = malloc(sizeof(*part), M_DEVBUF,
440 	    M_WAITOK | M_ZERO);
441 	part->sc = sc;
442 	part->cnt = cnt;
443 	part->type = type;
444 	part->ro = ro;
445 	snprintf(part->name, sizeof(part->name), name, device_get_unit(dev));
446 
447 	MMCSD_IOCTL_LOCK_INIT(part);
448 
449 	/*
450 	 * For the RPMB partition, allow IOCTL access only.
451 	 * NB: If ever attaching RPMB partitions to disk(9), the re-tuning
452 	 *     implementation and especially its pausing need to be revisited,
453 	 *     because then re-tuning requests may be issued by the IOCTL half
454 	 *     of this driver while re-tuning is already paused by the disk(9)
455 	 *     one and vice versa.
456 	 */
457 	if (type == EXT_CSD_PART_CONFIG_ACC_RPMB) {
458 		make_dev_args_init(&args);
459 		args.mda_flags = MAKEDEV_CHECKNAME | MAKEDEV_WAITOK;
460 		args.mda_devsw = &mmcsd_rpmb_cdevsw;
461 		args.mda_uid = UID_ROOT;
462 		args.mda_gid = GID_OPERATOR;
463 		args.mda_mode = 0640;
464 		args.mda_si_drv1 = part;
465 		if (make_dev_s(&args, &sc->rpmb_dev, "%s", part->name) != 0) {
466 			device_printf(dev, "Failed to make RPMB device\n");
467 			free(part, M_DEVBUF);
468 			return;
469 		}
470 	} else {
471 		MMCSD_DISK_LOCK_INIT(part);
472 
473 		d = part->disk = disk_alloc();
474 		d->d_open = mmcsd_open;
475 		d->d_close = mmcsd_close;
476 		d->d_strategy = mmcsd_strategy;
477 		d->d_ioctl = mmcsd_ioctl_disk;
478 		d->d_dump = mmcsd_dump;
479 		d->d_getattr = mmcsd_getattr;
480 		d->d_name = part->name;
481 		d->d_drv1 = part;
482 		d->d_sectorsize = mmc_get_sector_size(dev);
483 		d->d_maxsize = sc->max_data * d->d_sectorsize;
484 		d->d_mediasize = media_size;
485 		d->d_stripesize = erase_size;
486 		d->d_unit = cnt;
487 		d->d_flags = DISKFLAG_CANDELETE;
488 		d->d_delmaxsize = erase_size;
489 		strlcpy(d->d_ident, mmc_get_card_sn_string(dev),
490 		    sizeof(d->d_ident));
491 		strlcpy(d->d_descr, mmc_get_card_id_string(dev),
492 		    sizeof(d->d_descr));
493 		d->d_rotation_rate = DISK_RR_NON_ROTATING;
494 
495 		disk_create(d, DISK_VERSION);
496 		bioq_init(&part->bio_queue);
497 
498 		part->running = 1;
499 		kproc_create(&mmcsd_task, part, &part->p, 0, 0,
500 		    "%s%d: mmc/sd card", part->name, cnt);
501 	}
502 
503 	bytes = mmcsd_pretty_size(media_size, unit);
504 	if (type == EXT_CSD_PART_CONFIG_ACC_DEFAULT) {
505 		speed = mmcbr_get_clock(mmcbr);
506 		printf("%s%d: %ju%sB <%s>%s at %s %d.%01dMHz/%dbit/%d-block\n",
507 		    part->name, cnt, bytes, unit, mmc_get_card_id_string(dev),
508 		    ro ? " (read-only)" : "", device_get_nameunit(mmcbr),
509 		    speed / 1000000, (speed / 100000) % 10,
510 		    mmcsd_bus_bit_width(dev), sc->max_data);
511 	} else if (type == EXT_CSD_PART_CONFIG_ACC_RPMB) {
512 		printf("%s: %ju%sB partion %d%s at %s\n", part->name, bytes,
513 		    unit, type, ro ? " (read-only)" : "",
514 		    device_get_nameunit(dev));
515 	} else {
516 		enh = false;
517 		ext = NULL;
518 		extattr = 0;
519 		if (type >= EXT_CSD_PART_CONFIG_ACC_GP0 &&
520 		    type <= EXT_CSD_PART_CONFIG_ACC_GP3) {
521 			ext_csd = sc->ext_csd;
522 			gp = type - EXT_CSD_PART_CONFIG_ACC_GP0;
523 			if ((ext_csd[EXT_CSD_PART_SUPPORT] &
524 			    EXT_CSD_PART_SUPPORT_ENH_ATTR_EN) != 0 &&
525 			    (ext_csd[EXT_CSD_PART_ATTR] &
526 			    (EXT_CSD_PART_ATTR_ENH_GP0 << gp)) != 0)
527 				enh = true;
528 			else if ((ext_csd[EXT_CSD_PART_SUPPORT] &
529 			    EXT_CSD_PART_SUPPORT_EXT_ATTR_EN) != 0) {
530 				extattr = (ext_csd[EXT_CSD_EXT_PART_ATTR +
531 				    (gp / 2)] >> (4 * (gp % 2))) & 0xF;
532 				switch (extattr) {
533 					case EXT_CSD_EXT_PART_ATTR_DEFAULT:
534 						break;
535 					case EXT_CSD_EXT_PART_ATTR_SYSTEMCODE:
536 						ext = "system code";
537 						break;
538 					case EXT_CSD_EXT_PART_ATTR_NPERSISTENT:
539 						ext = "non-persistent";
540 						break;
541 					default:
542 						ext = "reserved";
543 						break;
544 				}
545 			}
546 		}
547 		if (ext == NULL)
548 			printf("%s%d: %ju%sB partion %d%s%s at %s\n",
549 			    part->name, cnt, bytes, unit, type, enh ?
550 			    " enhanced" : "", ro ? " (read-only)" : "",
551 			    device_get_nameunit(dev));
552 		else
553 			printf("%s%d: %ju%sB partion %d extended 0x%x "
554 			    "(%s)%s at %s\n", part->name, cnt, bytes, unit,
555 			    type, extattr, ext, ro ? " (read-only)" : "",
556 			    device_get_nameunit(dev));
557 	}
558 }
559 
560 static int
561 mmcsd_slicer(device_t dev, const char *provider,
562     struct flash_slice *slices, int *nslices)
563 {
564 	char name[MMCSD_PART_NAMELEN];
565 	struct mmcsd_softc *sc;
566 	struct mmcsd_part *part;
567 
568 	*nslices = 0;
569 	if (slices == NULL)
570 		return (ENOMEM);
571 
572 	sc = device_get_softc(dev);
573 	if (sc->enh_size == 0)
574 		return (ENXIO);
575 
576 	part = sc->part[EXT_CSD_PART_CONFIG_ACC_DEFAULT];
577 	snprintf(name, sizeof(name), "%s%d", part->disk->d_name,
578 	    part->disk->d_unit);
579 	if (strcmp(name, provider) != 0)
580 		return (ENXIO);
581 
582 	*nslices = 1;
583 	slices[0].base = sc->enh_base;
584 	slices[0].size = sc->enh_size;
585 	slices[0].label = MMCSD_LABEL_ENH;
586 	return (0);
587 }
588 
589 static int
590 mmcsd_detach(device_t dev)
591 {
592 	struct mmcsd_softc *sc = device_get_softc(dev);
593 	struct mmcsd_part *part;
594 	int i;
595 
596 	for (i = 0; i < MMC_PART_MAX; i++) {
597 		part = sc->part[i];
598 		if (part != NULL) {
599 			if (part->disk != NULL) {
600 				MMCSD_DISK_LOCK(part);
601 				part->suspend = 0;
602 				if (part->running > 0) {
603 					/* kill thread */
604 					part->running = 0;
605 					wakeup(part);
606 					/* wait for thread to finish. */
607 					while (part->running != -1)
608 						msleep(part, &part->disk_mtx, 0,
609 						    "mmcsd disk detach", 0);
610 				}
611 				MMCSD_DISK_UNLOCK(part);
612 			}
613 			MMCSD_IOCTL_LOCK(part);
614 			while (part->ioctl > 0)
615 				msleep(part, &part->ioctl_mtx, 0,
616 				    "mmcsd IOCTL detach", 0);
617 			part->ioctl = -1;
618 			MMCSD_IOCTL_UNLOCK(part);
619 		}
620 	}
621 
622 	if (sc->rpmb_dev != NULL)
623 		destroy_dev(sc->rpmb_dev);
624 
625 	for (i = 0; i < MMC_PART_MAX; i++) {
626 		part = sc->part[i];
627 		if (part != NULL) {
628 			if (part->disk != NULL) {
629 				/* Flush the request queue. */
630 				bioq_flush(&part->bio_queue, NULL, ENXIO);
631 				/* kill disk */
632 				disk_destroy(part->disk);
633 
634 				MMCSD_DISK_LOCK_DESTROY(part);
635 			}
636 			MMCSD_IOCTL_LOCK_DESTROY(part);
637 			free(part, M_DEVBUF);
638 		}
639 	}
640 	return (0);
641 }
642 
643 static int
644 mmcsd_suspend(device_t dev)
645 {
646 	struct mmcsd_softc *sc = device_get_softc(dev);
647 	struct mmcsd_part *part;
648 	int i;
649 
650 	for (i = 0; i < MMC_PART_MAX; i++) {
651 		part = sc->part[i];
652 		if (part != NULL) {
653 			if (part->disk != NULL) {
654 				MMCSD_DISK_LOCK(part);
655 				part->suspend = 1;
656 				if (part->running > 0) {
657 					/* kill thread */
658 					part->running = 0;
659 					wakeup(part);
660 					/* wait for thread to finish. */
661 					while (part->running != -1)
662 						msleep(part, &part->disk_mtx, 0,
663 						    "mmcsd disk suspension", 0);
664 				}
665 				MMCSD_DISK_UNLOCK(part);
666 			}
667 			MMCSD_IOCTL_LOCK(part);
668 			while (part->ioctl > 0)
669 				msleep(part, &part->ioctl_mtx, 0,
670 				    "mmcsd IOCTL suspension", 0);
671 			part->ioctl = -1;
672 			MMCSD_IOCTL_UNLOCK(part);
673 		}
674 	}
675 	return (0);
676 }
677 
678 static int
679 mmcsd_resume(device_t dev)
680 {
681 	struct mmcsd_softc *sc = device_get_softc(dev);
682 	struct mmcsd_part *part;
683 	int i;
684 
685 	for (i = 0; i < MMC_PART_MAX; i++) {
686 		part = sc->part[i];
687 		if (part != NULL) {
688 			if (part->disk != NULL) {
689 				MMCSD_DISK_LOCK(part);
690 				part->suspend = 0;
691 				if (part->running <= 0) {
692 					part->running = 1;
693 					MMCSD_DISK_UNLOCK(part);
694 					kproc_create(&mmcsd_task, part,
695 					    &part->p, 0, 0, "%s%d: mmc/sd card",
696 					    part->name, part->cnt);
697 				} else
698 					MMCSD_DISK_UNLOCK(part);
699 			}
700 			MMCSD_IOCTL_LOCK(part);
701 			part->ioctl = 0;
702 			MMCSD_IOCTL_UNLOCK(part);
703 		}
704 	}
705 	return (0);
706 }
707 
708 static int
709 mmcsd_open(struct disk *dp __unused)
710 {
711 
712 	return (0);
713 }
714 
715 static int
716 mmcsd_close(struct disk *dp __unused)
717 {
718 
719 	return (0);
720 }
721 
722 static void
723 mmcsd_strategy(struct bio *bp)
724 {
725 	struct mmcsd_softc *sc;
726 	struct mmcsd_part *part;
727 
728 	part = bp->bio_disk->d_drv1;
729 	sc = part->sc;
730 	MMCSD_DISK_LOCK(part);
731 	if (part->running > 0 || part->suspend > 0) {
732 		bioq_disksort(&part->bio_queue, bp);
733 		MMCSD_DISK_UNLOCK(part);
734 		wakeup(part);
735 	} else {
736 		MMCSD_DISK_UNLOCK(part);
737 		biofinish(bp, NULL, ENXIO);
738 	}
739 }
740 
741 static int
742 mmcsd_ioctl_rpmb(struct cdev *dev, u_long cmd, caddr_t data,
743     int fflag, struct thread *td __unused)
744 {
745 
746 	return (mmcsd_ioctl(dev->si_drv1, cmd, data, fflag));
747 }
748 
749 static int
750 mmcsd_ioctl_disk(struct disk *disk, u_long cmd, void *data, int fflag,
751     struct thread *td __unused)
752 {
753 
754 	return (mmcsd_ioctl(disk->d_drv1, cmd, data, fflag));
755 }
756 
757 static int
758 mmcsd_ioctl(struct mmcsd_part *part, u_long cmd, void *data, int fflag)
759 {
760 	struct mmc_ioc_cmd *mic;
761 	struct mmc_ioc_multi_cmd *mimc;
762 	int i, err;
763 	u_long cnt, size;
764 
765 	if ((fflag & FREAD) == 0)
766 		return (EBADF);
767 
768 	err = 0;
769 	switch (cmd) {
770 	case MMC_IOC_CMD:
771 		mic = data;
772 		err = mmcsd_ioctl_cmd(part, mic, fflag);
773 		break;
774 	case MMC_IOC_MULTI_CMD:
775 		mimc = data;
776 		if (mimc->num_of_cmds == 0)
777 			break;
778 		if (mimc->num_of_cmds > MMC_IOC_MAX_CMDS)
779 			return (EINVAL);
780 		cnt = mimc->num_of_cmds;
781 		size = sizeof(*mic) * cnt;
782 		mic = malloc(size, M_TEMP, M_WAITOK);
783 		err = copyin((const void *)mimc->cmds, mic, size);
784 		if (err == 0) {
785 			for (i = 0; i < cnt; i++) {
786 				err = mmcsd_ioctl_cmd(part, &mic[i], fflag);
787 				if (err != 0)
788 					break;
789 			}
790 		}
791 		free(mic, M_TEMP);
792 		break;
793 	default:
794 		return (ENOIOCTL);
795 	}
796 	return (err);
797 }
798 
799 static int
800 mmcsd_ioctl_cmd(struct mmcsd_part *part, struct mmc_ioc_cmd *mic, int fflag)
801 {
802 	struct mmc_command cmd;
803 	struct mmc_data data;
804 	struct mmcsd_softc *sc;
805 	device_t dev, mmcbr;
806 	void *dp;
807 	u_long len;
808 	int err, retries;
809 	uint32_t status;
810 	uint16_t rca;
811 
812 	if ((fflag & FWRITE) == 0 && mic->write_flag != 0)
813 		return (EBADF);
814 
815 	if (part->ro == TRUE && mic->write_flag != 0)
816 		return (EROFS);
817 
818 	/*
819 	 * We don't need to explicitly lock against the disk(9) half of this
820 	 * driver as MMCBUS_ACQUIRE_BUS() will serialize us.  However, it's
821 	 * necessary to protect against races with detachment and suspension,
822 	 * especially since it's required to switch away from RPMB partitions
823 	 * again after an access (see mmcsd_switch_part()).
824 	 */
825 	MMCSD_IOCTL_LOCK(part);
826 	while (part->ioctl != 0) {
827 		if (part->ioctl < 0) {
828 			MMCSD_IOCTL_UNLOCK(part);
829 			return (ENXIO);
830 		}
831 		msleep(part, &part->ioctl_mtx, 0, "mmcsd IOCTL", 0);
832 	}
833 	part->ioctl = 1;
834 	MMCSD_IOCTL_UNLOCK(part);
835 
836 	err = 0;
837 	dp = NULL;
838 	len = mic->blksz * mic->blocks;
839 	if (len > MMC_IOC_MAX_BYTES) {
840 		err = EOVERFLOW;
841 		goto out;
842 	}
843 	if (len != 0) {
844 		dp = malloc(len, M_TEMP, M_WAITOK);
845 		err = copyin((void *)(uintptr_t)mic->data_ptr, dp, len);
846 		if (err != 0)
847 			goto out;
848 	}
849 	memset(&cmd, 0, sizeof(cmd));
850 	memset(&data, 0, sizeof(data));
851 	cmd.opcode = mic->opcode;
852 	cmd.arg = mic->arg;
853 	cmd.flags = mic->flags;
854 	if (len != 0) {
855 		data.len = len;
856 		data.data = dp;
857 		data.flags = mic->write_flag != 0 ? MMC_DATA_WRITE :
858 		    MMC_DATA_READ;
859 		cmd.data = &data;
860 	}
861 	sc = part->sc;
862 	rca = sc->rca;
863 	if (mic->is_acmd == 0) {
864 		/* Enforce/patch/restrict RCA-based commands */
865 		switch (cmd.opcode) {
866 		case MMC_SET_RELATIVE_ADDR:
867 		case MMC_SELECT_CARD:
868 			err = EPERM;
869 			goto out;
870 		case MMC_STOP_TRANSMISSION:
871 			if ((cmd.arg & 0x1) == 0)
872 				break;
873 			/* FALLTHROUGH */
874 		case MMC_SLEEP_AWAKE:
875 		case MMC_SEND_CSD:
876 		case MMC_SEND_CID:
877 		case MMC_SEND_STATUS:
878 		case MMC_GO_INACTIVE_STATE:
879 		case MMC_FAST_IO:
880 		case MMC_APP_CMD:
881 			cmd.arg = (cmd.arg & 0x0000FFFF) | (rca << 16);
882 			break;
883 		default:
884 			break;
885 		}
886 	}
887 	dev = sc->dev;
888 	mmcbr = sc->mmcbr;
889 	MMCBUS_ACQUIRE_BUS(mmcbr, dev);
890 	err = mmcsd_switch_part(mmcbr, dev, rca, part->type);
891 	if (err != MMC_ERR_NONE)
892 		goto release;
893 	if (part->type == EXT_CSD_PART_CONFIG_ACC_RPMB) {
894 		err = mmcsd_set_blockcount(sc, mic->blocks,
895 		    mic->write_flag & (1 << 31));
896 		if (err != MMC_ERR_NONE)
897 			goto switch_back;
898 	}
899 	if (mic->is_acmd != 0)
900 		(void)mmc_wait_for_app_cmd(mmcbr, dev, rca, &cmd, 0);
901 	else
902 		(void)mmc_wait_for_cmd(mmcbr, dev, &cmd, 0);
903 	if (part->type == EXT_CSD_PART_CONFIG_ACC_RPMB) {
904 		/*
905 		 * If the request went to the RPMB partition, try to ensure
906 		 * that the command actually has completed ...
907 		 */
908 		retries = MMCSD_CMD_RETRIES;
909 		do {
910 			err = mmc_send_status(mmcbr, dev, rca, &status);
911 			if (err != MMC_ERR_NONE)
912 				break;
913 			if (R1_STATUS(status) == 0 &&
914 			    R1_CURRENT_STATE(status) != R1_STATE_PRG)
915 				break;
916 			DELAY(1000);
917 		} while (retries-- > 0);
918 
919 switch_back:
920 		/* ... and always switch back to the default partition. */
921 		err = mmcsd_switch_part(mmcbr, dev, rca,
922 		    EXT_CSD_PART_CONFIG_ACC_DEFAULT);
923 		if (err != MMC_ERR_NONE)
924 			goto release;
925 	}
926 	/*
927 	 * If EXT_CSD was changed, our copy is outdated now.  Specifically,
928 	 * the upper bits of EXT_CSD_PART_CONFIG used in mmcsd_switch_part(),
929 	 * so retrieve EXT_CSD again.
930 	 */
931 	if (cmd.opcode == MMC_SWITCH_FUNC) {
932 		err = mmc_send_ext_csd(mmcbr, dev, sc->ext_csd);
933 		if (err != MMC_ERR_NONE)
934 			goto release;
935 	}
936 	MMCBUS_RELEASE_BUS(mmcbr, dev);
937 	if (cmd.error != MMC_ERR_NONE) {
938 		switch (cmd.error) {
939 		case MMC_ERR_TIMEOUT:
940 			err = ETIMEDOUT;
941 			break;
942 		case MMC_ERR_BADCRC:
943 			err = EILSEQ;
944 			break;
945 		case MMC_ERR_INVALID:
946 			err = EINVAL;
947 			break;
948 		case MMC_ERR_NO_MEMORY:
949 			err = ENOMEM;
950 			break;
951 		default:
952 			err = EIO;
953 			break;
954 		}
955 		goto out;
956 	}
957 	memcpy(mic->response, cmd.resp, 4 * sizeof(uint32_t));
958 	if (mic->write_flag == 0 && len != 0) {
959 		err = copyout(dp, (void *)(uintptr_t)mic->data_ptr, len);
960 		if (err != 0)
961 			goto out;
962 	}
963 	goto out;
964 
965 release:
966 	MMCBUS_RELEASE_BUS(mmcbr, dev);
967 	err = EIO;
968 
969 out:
970 	MMCSD_IOCTL_LOCK(part);
971 	part->ioctl = 0;
972 	MMCSD_IOCTL_UNLOCK(part);
973 	wakeup(part);
974 	if (dp != NULL)
975 		free(dp, M_TEMP);
976 	return (err);
977 }
978 
979 static int
980 mmcsd_getattr(struct bio *bp)
981 {
982 	struct mmcsd_part *part;
983 	device_t dev;
984 
985 	if (strcmp(bp->bio_attribute, "MMC::device") == 0) {
986 		if (bp->bio_length != sizeof(dev))
987 			return (EFAULT);
988 		part = bp->bio_disk->d_drv1;
989 		dev = part->sc->dev;
990 		bcopy(&dev, bp->bio_data, sizeof(dev));
991 		bp->bio_completed = bp->bio_length;
992 		return (0);
993 	}
994 	return (-1);
995 }
996 
997 static int
998 mmcsd_set_blockcount(struct mmcsd_softc *sc, u_int count, bool reliable)
999 {
1000 	struct mmc_command cmd;
1001 	struct mmc_request req;
1002 
1003 	memset(&req, 0, sizeof(req));
1004 	memset(&cmd, 0, sizeof(cmd));
1005 	cmd.mrq = &req;
1006 	req.cmd = &cmd;
1007 	cmd.opcode = MMC_SET_BLOCK_COUNT;
1008 	cmd.arg = count & 0x0000FFFF;
1009 	if (reliable)
1010 		cmd.arg |= 1 << 31;
1011 	cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
1012 	MMCBUS_WAIT_FOR_REQUEST(sc->mmcbr, sc->dev, &req);
1013 	return (cmd.error);
1014 }
1015 
1016 static int
1017 mmcsd_switch_part(device_t bus, device_t dev, uint16_t rca, u_int part)
1018 {
1019 	struct mmcsd_softc *sc;
1020 	int err;
1021 	uint8_t	value;
1022 
1023 	sc = device_get_softc(dev);
1024 
1025 	if (sc->mode == mode_sd)
1026 		return (MMC_ERR_NONE);
1027 
1028 	/*
1029 	 * According to section "6.2.2 Command restrictions" of the eMMC
1030 	 * specification v5.1, CMD19/CMD21 aren't allowed to be used with
1031 	 * RPMB partitions.  So we pause re-tuning along with triggering
1032 	 * it up-front to decrease the likelihood of re-tuning becoming
1033 	 * necessary while accessing an RPMB partition.  Consequently, an
1034 	 * RPMB partition should immediately be switched away from again
1035 	 * after an access in order to allow for re-tuning to take place
1036 	 * anew.
1037 	 */
1038 	if (part == EXT_CSD_PART_CONFIG_ACC_RPMB)
1039 		MMCBUS_RETUNE_PAUSE(sc->mmcbr, sc->dev, true);
1040 
1041 	if (sc->part_curr == part)
1042 		return (MMC_ERR_NONE);
1043 
1044 	value = (sc->ext_csd[EXT_CSD_PART_CONFIG] &
1045 	    ~EXT_CSD_PART_CONFIG_ACC_MASK) | part;
1046 	/* Jump! */
1047 	err = mmc_switch(bus, dev, rca, EXT_CSD_CMD_SET_NORMAL,
1048 	    EXT_CSD_PART_CONFIG, value, sc->part_time, true);
1049 	if (err != MMC_ERR_NONE) {
1050 		if (part == EXT_CSD_PART_CONFIG_ACC_RPMB)
1051 			MMCBUS_RETUNE_UNPAUSE(sc->mmcbr, sc->dev);
1052 		return (err);
1053 	}
1054 
1055 	sc->ext_csd[EXT_CSD_PART_CONFIG] = value;
1056 	if (sc->part_curr == EXT_CSD_PART_CONFIG_ACC_RPMB)
1057 		MMCBUS_RETUNE_UNPAUSE(sc->mmcbr, sc->dev);
1058 	sc->part_curr = part;
1059 	return (MMC_ERR_NONE);
1060 }
1061 
1062 static const char *
1063 mmcsd_errmsg(int e)
1064 {
1065 
1066 	if (e < 0 || e > MMC_ERR_MAX)
1067 		return "Bad error code";
1068 	return (errmsg[e]);
1069 }
1070 
1071 static daddr_t
1072 mmcsd_rw(struct mmcsd_part *part, struct bio *bp)
1073 {
1074 	daddr_t block, end;
1075 	struct mmc_command cmd;
1076 	struct mmc_command stop;
1077 	struct mmc_request req;
1078 	struct mmc_data data;
1079 	struct mmcsd_softc *sc;
1080 	device_t dev, mmcbr;
1081 	u_int numblocks, sz;
1082 	char *vaddr;
1083 
1084 	sc = part->sc;
1085 	dev = sc->dev;
1086 	mmcbr = sc->mmcbr;
1087 
1088 	block = bp->bio_pblkno;
1089 	sz = part->disk->d_sectorsize;
1090 	end = bp->bio_pblkno + (bp->bio_bcount / sz);
1091 	while (block < end) {
1092 		vaddr = bp->bio_data + (block - bp->bio_pblkno) * sz;
1093 		numblocks = min(end - block, sc->max_data);
1094 		memset(&req, 0, sizeof(req));
1095 		memset(&cmd, 0, sizeof(cmd));
1096 		memset(&stop, 0, sizeof(stop));
1097 		memset(&data, 0, sizeof(data));
1098 		cmd.mrq = &req;
1099 		req.cmd = &cmd;
1100 		cmd.data = &data;
1101 		if (bp->bio_cmd == BIO_READ) {
1102 			if (numblocks > 1)
1103 				cmd.opcode = MMC_READ_MULTIPLE_BLOCK;
1104 			else
1105 				cmd.opcode = MMC_READ_SINGLE_BLOCK;
1106 		} else {
1107 			if (numblocks > 1)
1108 				cmd.opcode = MMC_WRITE_MULTIPLE_BLOCK;
1109 			else
1110 				cmd.opcode = MMC_WRITE_BLOCK;
1111 		}
1112 		cmd.arg = block;
1113 		if (sc->high_cap == 0)
1114 			cmd.arg <<= 9;
1115 		cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
1116 		data.data = vaddr;
1117 		data.mrq = &req;
1118 		if (bp->bio_cmd == BIO_READ)
1119 			data.flags = MMC_DATA_READ;
1120 		else
1121 			data.flags = MMC_DATA_WRITE;
1122 		data.len = numblocks * sz;
1123 		if (numblocks > 1) {
1124 			data.flags |= MMC_DATA_MULTI;
1125 			stop.opcode = MMC_STOP_TRANSMISSION;
1126 			stop.arg = 0;
1127 			stop.flags = MMC_RSP_R1B | MMC_CMD_AC;
1128 			stop.mrq = &req;
1129 			req.stop = &stop;
1130 		}
1131 		MMCBUS_WAIT_FOR_REQUEST(mmcbr, dev, &req);
1132 		if (req.cmd->error != MMC_ERR_NONE) {
1133 			if (ppsratecheck(&sc->log_time, &sc->log_count,
1134 			    LOG_PPS))
1135 				device_printf(dev, "Error indicated: %d %s\n",
1136 				    req.cmd->error,
1137 				    mmcsd_errmsg(req.cmd->error));
1138 			break;
1139 		}
1140 		block += numblocks;
1141 	}
1142 	return (block);
1143 }
1144 
1145 static daddr_t
1146 mmcsd_delete(struct mmcsd_part *part, struct bio *bp)
1147 {
1148 	daddr_t block, end, start, stop;
1149 	struct mmc_command cmd;
1150 	struct mmc_request req;
1151 	struct mmcsd_softc *sc;
1152 	device_t dev, mmcbr;
1153 	u_int erase_sector, sz;
1154 
1155 	sc = part->sc;
1156 	dev = sc->dev;
1157 	mmcbr = sc->mmcbr;
1158 
1159 	block = bp->bio_pblkno;
1160 	sz = part->disk->d_sectorsize;
1161 	end = bp->bio_pblkno + (bp->bio_bcount / sz);
1162 	/* Coalesce with part remaining from previous request. */
1163 	if (block > part->eblock && block <= part->eend)
1164 		block = part->eblock;
1165 	if (end >= part->eblock && end < part->eend)
1166 		end = part->eend;
1167 	/* Safe round to the erase sector boundaries. */
1168 	erase_sector = sc->erase_sector;
1169 	start = block + erase_sector - 1;	 /* Round up. */
1170 	start -= start % erase_sector;
1171 	stop = end;				/* Round down. */
1172 	stop -= end % erase_sector;
1173 	/* We can't erase an area smaller than a sector, store it for later. */
1174 	if (start >= stop) {
1175 		part->eblock = block;
1176 		part->eend = end;
1177 		return (end);
1178 	}
1179 
1180 	/*
1181 	 * Pause re-tuning so it won't interfere with the order of erase
1182 	 * commands.  Note that these latter don't use the data lines, so
1183 	 * re-tuning shouldn't actually become necessary during erase.
1184 	 */
1185 	MMCBUS_RETUNE_PAUSE(mmcbr, dev, false);
1186 	/* Set erase start position. */
1187 	memset(&req, 0, sizeof(req));
1188 	memset(&cmd, 0, sizeof(cmd));
1189 	cmd.mrq = &req;
1190 	req.cmd = &cmd;
1191 	if (mmc_get_card_type(dev) == mode_sd)
1192 		cmd.opcode = SD_ERASE_WR_BLK_START;
1193 	else
1194 		cmd.opcode = MMC_ERASE_GROUP_START;
1195 	cmd.arg = start;
1196 	if (sc->high_cap == 0)
1197 		cmd.arg <<= 9;
1198 	cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
1199 	MMCBUS_WAIT_FOR_REQUEST(mmcbr, dev, &req);
1200 	if (req.cmd->error != MMC_ERR_NONE) {
1201 		device_printf(dev, "Setting erase start position failed %d\n",
1202 		    req.cmd->error);
1203 		block = bp->bio_pblkno;
1204 		goto unpause;
1205 	}
1206 	/* Set erase stop position. */
1207 	memset(&req, 0, sizeof(req));
1208 	memset(&cmd, 0, sizeof(cmd));
1209 	req.cmd = &cmd;
1210 	if (mmc_get_card_type(dev) == mode_sd)
1211 		cmd.opcode = SD_ERASE_WR_BLK_END;
1212 	else
1213 		cmd.opcode = MMC_ERASE_GROUP_END;
1214 	cmd.arg = stop;
1215 	if (sc->high_cap == 0)
1216 		cmd.arg <<= 9;
1217 	cmd.arg--;
1218 	cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
1219 	MMCBUS_WAIT_FOR_REQUEST(mmcbr, dev, &req);
1220 	if (req.cmd->error != MMC_ERR_NONE) {
1221 		device_printf(dev, "Setting erase stop position failed %d\n",
1222 		    req.cmd->error);
1223 		block = bp->bio_pblkno;
1224 		goto unpause;
1225 	}
1226 	/* Erase range. */
1227 	memset(&req, 0, sizeof(req));
1228 	memset(&cmd, 0, sizeof(cmd));
1229 	req.cmd = &cmd;
1230 	cmd.opcode = MMC_ERASE;
1231 	cmd.arg = 0;
1232 	cmd.flags = MMC_RSP_R1B | MMC_CMD_AC;
1233 	MMCBUS_WAIT_FOR_REQUEST(mmcbr, dev, &req);
1234 	if (req.cmd->error != MMC_ERR_NONE) {
1235 		device_printf(dev, "erase err3: %d\n", req.cmd->error);
1236 		device_printf(dev, "Issuing erase command failed %d\n",
1237 		    req.cmd->error);
1238 		block = bp->bio_pblkno;
1239 		goto unpause;
1240 	}
1241 	/* Store one of remaining parts for the next call. */
1242 	if (bp->bio_pblkno >= part->eblock || block == start) {
1243 		part->eblock = stop;	/* Predict next forward. */
1244 		part->eend = end;
1245 	} else {
1246 		part->eblock = block;	/* Predict next backward. */
1247 		part->eend = start;
1248 	}
1249 	block = end;
1250 unpause:
1251 	MMCBUS_RETUNE_UNPAUSE(mmcbr, dev);
1252 	return (block);
1253 }
1254 
1255 static int
1256 mmcsd_dump(void *arg, void *virtual, vm_offset_t physical, off_t offset,
1257     size_t length)
1258 {
1259 	struct bio bp;
1260 	daddr_t block, end;
1261 	struct disk *disk;
1262 	struct mmcsd_softc *sc;
1263 	struct mmcsd_part *part;
1264 	device_t dev, mmcbr;
1265 	int err;
1266 
1267 	/* length zero is special and really means flush buffers to media */
1268 	if (!length)
1269 		return (0);
1270 
1271 	disk = arg;
1272 	part = disk->d_drv1;
1273 	sc = part->sc;
1274 	dev = sc->dev;
1275 	mmcbr = sc->mmcbr;
1276 
1277 	g_reset_bio(&bp);
1278 	bp.bio_disk = disk;
1279 	bp.bio_pblkno = offset / disk->d_sectorsize;
1280 	bp.bio_bcount = length;
1281 	bp.bio_data = virtual;
1282 	bp.bio_cmd = BIO_WRITE;
1283 	end = bp.bio_pblkno + bp.bio_bcount / disk->d_sectorsize;
1284 	MMCBUS_ACQUIRE_BUS(mmcbr, dev);
1285 	err = mmcsd_switch_part(mmcbr, dev, sc->rca, part->type);
1286 	if (err != MMC_ERR_NONE) {
1287 		if (ppsratecheck(&sc->log_time, &sc->log_count, LOG_PPS))
1288 			device_printf(dev, "Partition switch error\n");
1289 		MMCBUS_RELEASE_BUS(mmcbr, dev);
1290 		return (EIO);
1291 	}
1292 	block = mmcsd_rw(part, &bp);
1293 	MMCBUS_RELEASE_BUS(mmcbr, dev);
1294 	return ((end < block) ? EIO : 0);
1295 }
1296 
1297 static void
1298 mmcsd_task(void *arg)
1299 {
1300 	daddr_t block, end;
1301 	struct mmcsd_part *part;
1302 	struct mmcsd_softc *sc;
1303 	struct bio *bp;
1304 	device_t dev, mmcbr;
1305 	int err, sz;
1306 
1307 	part = arg;
1308 	sc = part->sc;
1309 	dev = sc->dev;
1310 	mmcbr = sc->mmcbr;
1311 
1312 	while (1) {
1313 		MMCSD_DISK_LOCK(part);
1314 		do {
1315 			if (part->running == 0)
1316 				goto out;
1317 			bp = bioq_takefirst(&part->bio_queue);
1318 			if (bp == NULL)
1319 				msleep(part, &part->disk_mtx, PRIBIO,
1320 				    "mmcsd disk jobqueue", 0);
1321 		} while (bp == NULL);
1322 		MMCSD_DISK_UNLOCK(part);
1323 		if (bp->bio_cmd != BIO_READ && part->ro) {
1324 			bp->bio_error = EROFS;
1325 			bp->bio_resid = bp->bio_bcount;
1326 			bp->bio_flags |= BIO_ERROR;
1327 			biodone(bp);
1328 			continue;
1329 		}
1330 		MMCBUS_ACQUIRE_BUS(mmcbr, dev);
1331 		sz = part->disk->d_sectorsize;
1332 		block = bp->bio_pblkno;
1333 		end = bp->bio_pblkno + (bp->bio_bcount / sz);
1334 		err = mmcsd_switch_part(mmcbr, dev, sc->rca, part->type);
1335 		if (err != MMC_ERR_NONE) {
1336 			if (ppsratecheck(&sc->log_time, &sc->log_count,
1337 			    LOG_PPS))
1338 				device_printf(dev, "Partition switch error\n");
1339 			goto release;
1340 		}
1341 		if (bp->bio_cmd == BIO_READ || bp->bio_cmd == BIO_WRITE) {
1342 			/* Access to the remaining erase block obsoletes it. */
1343 			if (block < part->eend && end > part->eblock)
1344 				part->eblock = part->eend = 0;
1345 			block = mmcsd_rw(part, bp);
1346 		} else if (bp->bio_cmd == BIO_DELETE) {
1347 			block = mmcsd_delete(part, bp);
1348 		}
1349 release:
1350 		MMCBUS_RELEASE_BUS(mmcbr, dev);
1351 		if (block < end) {
1352 			bp->bio_error = EIO;
1353 			bp->bio_resid = (end - block) * sz;
1354 			bp->bio_flags |= BIO_ERROR;
1355 		} else {
1356 			bp->bio_resid = 0;
1357 		}
1358 		biodone(bp);
1359 	}
1360 out:
1361 	/* tell parent we're done */
1362 	part->running = -1;
1363 	MMCSD_DISK_UNLOCK(part);
1364 	wakeup(part);
1365 
1366 	kproc_exit(0);
1367 }
1368 
1369 static int
1370 mmcsd_bus_bit_width(device_t dev)
1371 {
1372 
1373 	if (mmc_get_bus_width(dev) == bus_width_1)
1374 		return (1);
1375 	if (mmc_get_bus_width(dev) == bus_width_4)
1376 		return (4);
1377 	return (8);
1378 }
1379 
1380 static device_method_t mmcsd_methods[] = {
1381 	DEVMETHOD(device_probe, mmcsd_probe),
1382 	DEVMETHOD(device_attach, mmcsd_attach),
1383 	DEVMETHOD(device_detach, mmcsd_detach),
1384 	DEVMETHOD(device_suspend, mmcsd_suspend),
1385 	DEVMETHOD(device_resume, mmcsd_resume),
1386 	DEVMETHOD_END
1387 };
1388 
1389 static driver_t mmcsd_driver = {
1390 	"mmcsd",
1391 	mmcsd_methods,
1392 	sizeof(struct mmcsd_softc),
1393 };
1394 static devclass_t mmcsd_devclass;
1395 
1396 static int
1397 mmcsd_handler(module_t mod __unused, int what, void *arg __unused)
1398 {
1399 
1400 	switch (what) {
1401 	case MOD_LOAD:
1402 		flash_register_slicer(mmcsd_slicer, FLASH_SLICES_TYPE_MMC,
1403 		    TRUE);
1404 		return (0);
1405 	case MOD_UNLOAD:
1406 		flash_register_slicer(NULL, FLASH_SLICES_TYPE_MMC, TRUE);
1407 		return (0);
1408 	}
1409 	return (0);
1410 }
1411 
1412 DRIVER_MODULE(mmcsd, mmc, mmcsd_driver, mmcsd_devclass, mmcsd_handler, NULL);
1413 MODULE_DEPEND(mmcsd, g_flashmap, 0, 0, 0);
1414 MMC_DEPEND(mmcsd);
1415