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