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