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