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