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