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