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