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