xref: /freebsd/sys/cam/mmc/mmc_da.c (revision d0b2dbfa0ecf2bbc9709efc5e20baf8e4b44bbbf)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2006 Bernd Walter <tisco@FreeBSD.org> All rights reserved.
5  * Copyright (c) 2009 Alexander Motin <mav@FreeBSD.org> All rights reserved.
6  * Copyright (c) 2015-2017 Ilya Bakulin <kibab@FreeBSD.org> All rights reserved.
7  * Copyright (c) 2006 M. Warner Losh <imp@FreeBSD.org>
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer,
14  *    without modification, immediately at the beginning of the file.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  *
30  * Some code derived from the sys/dev/mmc and sys/cam/ata
31  * Thanks to Warner Losh <imp@FreeBSD.org>, Alexander Motin <mav@FreeBSD.org>
32  * Bernd Walter <tisco@FreeBSD.org>, and other authors.
33  */
34 
35 #include <sys/cdefs.h>
36 //#include "opt_sdda.h"
37 
38 #include <sys/param.h>
39 
40 #ifdef _KERNEL
41 #include <sys/systm.h>
42 #include <sys/kernel.h>
43 #include <sys/bio.h>
44 #include <sys/sysctl.h>
45 #include <sys/endian.h>
46 #include <sys/taskqueue.h>
47 #include <sys/lock.h>
48 #include <sys/mutex.h>
49 #include <sys/conf.h>
50 #include <sys/devicestat.h>
51 #include <sys/eventhandler.h>
52 #include <sys/malloc.h>
53 #include <sys/cons.h>
54 #include <sys/proc.h>
55 #include <sys/reboot.h>
56 #include <geom/geom_disk.h>
57 #include <machine/_inttypes.h>  /* for PRIu64 */
58 #endif /* _KERNEL */
59 
60 #ifndef _KERNEL
61 #include <stdio.h>
62 #include <string.h>
63 #endif /* _KERNEL */
64 
65 #include <cam/cam.h>
66 #include <cam/cam_ccb.h>
67 #include <cam/cam_queue.h>
68 #include <cam/cam_periph.h>
69 #include <cam/cam_sim.h>
70 #include <cam/cam_xpt.h>
71 #include <cam/cam_xpt_sim.h>
72 #include <cam/cam_xpt_periph.h>
73 #include <cam/cam_xpt_internal.h>
74 #include <cam/cam_debug.h>
75 
76 #include <cam/mmc/mmc_all.h>
77 
78 #ifdef _KERNEL
79 
80 typedef enum {
81 	SDDA_FLAG_OPEN		= 0x0002,
82 	SDDA_FLAG_DIRTY		= 0x0004
83 } sdda_flags;
84 
85 typedef enum {
86 	SDDA_STATE_INIT,
87 	SDDA_STATE_INVALID,
88 	SDDA_STATE_NORMAL,
89 	SDDA_STATE_PART_SWITCH,
90 } sdda_state;
91 
92 #define	SDDA_FMT_BOOT		"sdda%dboot"
93 #define	SDDA_FMT_GP		"sdda%dgp"
94 #define	SDDA_FMT_RPMB		"sdda%drpmb"
95 #define	SDDA_LABEL_ENH		"enh"
96 
97 #define	SDDA_PART_NAMELEN	(16 + 1)
98 
99 struct sdda_softc;
100 
101 struct sdda_part {
102 	struct disk *disk;
103 	struct bio_queue_head bio_queue;
104 	sdda_flags flags;
105 	struct sdda_softc *sc;
106 	u_int cnt;
107 	u_int type;
108 	bool ro;
109 	char name[SDDA_PART_NAMELEN];
110 };
111 
112 struct sdda_softc {
113 	int	 outstanding_cmds;	/* Number of active commands */
114 	int	 refcount;		/* Active xpt_action() calls */
115 	sdda_state state;
116 	struct mmc_data *mmcdata;
117 	struct cam_periph *periph;
118 //	sdda_quirks quirks;
119 	struct task start_init_task;
120 	uint32_t raw_csd[4];
121 	uint8_t raw_ext_csd[512]; /* MMC only? */
122 	struct mmc_csd csd;
123 	struct mmc_cid cid;
124 	struct mmc_scr scr;
125 	/* Calculated from CSD */
126 	uint64_t sector_count;
127 	uint64_t mediasize;
128 
129 	/* Calculated from CID */
130 	char card_id_string[64];/* Formatted CID info (serial, MFG, etc) */
131 	char card_sn_string[16];/* Formatted serial # for disk->d_ident */
132 	/* Determined from CSD + is highspeed card*/
133 	uint32_t card_f_max;
134 
135 	/* Generic switch timeout */
136 	uint32_t cmd6_time;
137 	uint32_t timings;	/* Mask of bus timings supported */
138 	uint32_t vccq_120;	/* Mask of bus timings at VCCQ of 1.2 V */
139 	uint32_t vccq_180;	/* Mask of bus timings at VCCQ of 1.8 V */
140 	/* MMC partitions support */
141 	struct sdda_part *part[MMC_PART_MAX];
142 	uint8_t part_curr;	/* Partition currently switched to */
143 	uint8_t part_requested; /* What partition we're currently switching to */
144 	uint32_t part_time;	/* Partition switch timeout [us] */
145 	off_t enh_base;		/* Enhanced user data area slice base ... */
146 	off_t enh_size;		/* ... and size [bytes] */
147 	int log_count;
148 	struct timeval log_time;
149 };
150 
151 static const char *mmc_errmsg[] =
152 {
153 	"None",
154 	"Timeout",
155 	"Bad CRC",
156 	"Fifo",
157 	"Failed",
158 	"Invalid",
159 	"NO MEMORY"
160 };
161 
162 #define ccb_bp		ppriv_ptr1
163 
164 static	disk_strategy_t	sddastrategy;
165 static	dumper_t	sddadump;
166 static	periph_init_t	sddainit;
167 static	void		sddaasync(void *callback_arg, uint32_t code,
168 				struct cam_path *path, void *arg);
169 static	periph_ctor_t	sddaregister;
170 static	periph_dtor_t	sddacleanup;
171 static	periph_start_t	sddastart;
172 static	periph_oninv_t	sddaoninvalidate;
173 static	void		sddadone(struct cam_periph *periph,
174 			       union ccb *done_ccb);
175 static  int		sddaerror(union ccb *ccb, uint32_t cam_flags,
176 				uint32_t sense_flags);
177 
178 static int mmc_handle_reply(union ccb *ccb);
179 static uint16_t get_rca(struct cam_periph *periph);
180 static void sdda_start_init(void *context, union ccb *start_ccb);
181 static void sdda_start_init_task(void *context, int pending);
182 static void sdda_process_mmc_partitions(struct cam_periph *periph, union ccb *start_ccb);
183 static uint32_t sdda_get_host_caps(struct cam_periph *periph, union ccb *ccb);
184 static int mmc_select_card(struct cam_periph *periph, union ccb *ccb, uint32_t rca);
185 static inline uint32_t mmc_get_sector_size(struct cam_periph *periph) {return MMC_SECTOR_SIZE;}
186 
187 static SYSCTL_NODE(_kern_cam, OID_AUTO, sdda, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
188     "CAM Direct Access Disk driver");
189 
190 static int sdda_mmcsd_compat = 1;
191 SYSCTL_INT(_kern_cam_sdda, OID_AUTO, mmcsd_compat, CTLFLAG_RDTUN,
192     &sdda_mmcsd_compat, 1, "Enable creation of mmcsd aliases.");
193 
194 /* TODO: actually issue GET_TRAN_SETTINGS to get R/O status */
195 static inline bool sdda_get_read_only(struct cam_periph *periph, union ccb *start_ccb)
196 {
197 
198 	return (false);
199 }
200 
201 static uint32_t mmc_get_spec_vers(struct cam_periph *periph);
202 static uint64_t mmc_get_media_size(struct cam_periph *periph);
203 static uint32_t mmc_get_cmd6_timeout(struct cam_periph *periph);
204 static bool sdda_add_part(struct cam_periph *periph, u_int type,
205     const char *name, u_int cnt, off_t media_size, bool ro);
206 
207 static struct periph_driver sddadriver =
208 {
209 	sddainit, "sdda",
210 	TAILQ_HEAD_INITIALIZER(sddadriver.units), /* generation */ 0
211 };
212 
213 PERIPHDRIVER_DECLARE(sdda, sddadriver);
214 
215 static MALLOC_DEFINE(M_SDDA, "sd_da", "sd_da buffers");
216 
217 static const int exp[8] = {
218 	1, 10, 100, 1000, 10000, 100000, 1000000, 10000000
219 };
220 
221 static const int mant[16] = {
222 	0, 10, 12, 13, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 70, 80
223 };
224 
225 static const int cur_min[8] = {
226 	500, 1000, 5000, 10000, 25000, 35000, 60000, 100000
227 };
228 
229 static const int cur_max[8] = {
230 	1000, 5000, 10000, 25000, 35000, 45000, 800000, 200000
231 };
232 
233 static uint16_t
234 get_rca(struct cam_periph *periph) {
235 	return periph->path->device->mmc_ident_data.card_rca;
236 }
237 
238 /*
239  * Figure out if CCB execution resulted in error.
240  * Look at both CAM-level errors and on MMC protocol errors.
241  *
242  * Return value is always MMC error.
243 */
244 static int
245 mmc_handle_reply(union ccb *ccb)
246 {
247 	KASSERT(ccb->ccb_h.func_code == XPT_MMC_IO,
248 	    ("ccb %p: cannot handle non-XPT_MMC_IO errors, got func_code=%d",
249 		ccb, ccb->ccb_h.func_code));
250 
251 	/* CAM-level error should always correspond to MMC-level error */
252 	if (((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) &&
253 	  (ccb->mmcio.cmd.error != MMC_ERR_NONE))
254 		panic("CCB status is OK but MMC error != MMC_ERR_NONE");
255 
256 	if (ccb->mmcio.cmd.error != MMC_ERR_NONE) {
257 		xpt_print_path(ccb->ccb_h.path);
258 		printf("CMD%d failed, err %d (%s)\n",
259 		  ccb->mmcio.cmd.opcode,
260 		  ccb->mmcio.cmd.error,
261 		  mmc_errmsg[ccb->mmcio.cmd.error]);
262 	}
263 	return (ccb->mmcio.cmd.error);
264 }
265 
266 static uint32_t
267 mmc_get_bits(uint32_t *bits, int bit_len, int start, int size)
268 {
269 	const int i = (bit_len / 32) - (start / 32) - 1;
270 	const int shift = start & 31;
271 	uint32_t retval = bits[i] >> shift;
272 	if (size + shift > 32)
273 		retval |= bits[i - 1] << (32 - shift);
274 	return (retval & ((1llu << size) - 1));
275 }
276 
277 static void
278 mmc_decode_csd_sd(uint32_t *raw_csd, struct mmc_csd *csd)
279 {
280 	int v;
281 	int m;
282 	int e;
283 
284 	memset(csd, 0, sizeof(*csd));
285 	csd->csd_structure = v = mmc_get_bits(raw_csd, 128, 126, 2);
286 
287 	/* Common members between 1.0 and 2.0 */
288 	m = mmc_get_bits(raw_csd, 128, 115, 4);
289 	e = mmc_get_bits(raw_csd, 128, 112, 3);
290 	csd->tacc = (exp[e] * mant[m] + 9) / 10;
291 	csd->nsac = mmc_get_bits(raw_csd, 128, 104, 8) * 100;
292 	m = mmc_get_bits(raw_csd, 128, 99, 4);
293 	e = mmc_get_bits(raw_csd, 128, 96, 3);
294 	csd->tran_speed = exp[e] * 10000 * mant[m];
295 	csd->ccc = mmc_get_bits(raw_csd, 128, 84, 12);
296 	csd->read_bl_len = 1 << mmc_get_bits(raw_csd, 128, 80, 4);
297 	csd->read_bl_partial = mmc_get_bits(raw_csd, 128, 79, 1);
298 	csd->write_blk_misalign = mmc_get_bits(raw_csd, 128, 78, 1);
299 	csd->read_blk_misalign = mmc_get_bits(raw_csd, 128, 77, 1);
300 	csd->dsr_imp = mmc_get_bits(raw_csd, 128, 76, 1);
301 	csd->erase_blk_en = mmc_get_bits(raw_csd, 128, 46, 1);
302 	csd->erase_sector = mmc_get_bits(raw_csd, 128, 39, 7) + 1;
303 	csd->wp_grp_size = mmc_get_bits(raw_csd, 128, 32, 7);
304 	csd->wp_grp_enable = mmc_get_bits(raw_csd, 128, 31, 1);
305 	csd->r2w_factor = 1 << mmc_get_bits(raw_csd, 128, 26, 3);
306 	csd->write_bl_len = 1 << mmc_get_bits(raw_csd, 128, 22, 4);
307 	csd->write_bl_partial = mmc_get_bits(raw_csd, 128, 21, 1);
308 
309 	if (v == 0) {
310 		csd->vdd_r_curr_min = cur_min[mmc_get_bits(raw_csd, 128, 59, 3)];
311 		csd->vdd_r_curr_max = cur_max[mmc_get_bits(raw_csd, 128, 56, 3)];
312 		csd->vdd_w_curr_min = cur_min[mmc_get_bits(raw_csd, 128, 53, 3)];
313 		csd->vdd_w_curr_max = cur_max[mmc_get_bits(raw_csd, 128, 50, 3)];
314 		m = mmc_get_bits(raw_csd, 128, 62, 12);
315 		e = mmc_get_bits(raw_csd, 128, 47, 3);
316 		csd->capacity = ((1 + m) << (e + 2)) * csd->read_bl_len;
317 	} else if (v == 1) {
318 		csd->capacity = ((uint64_t)mmc_get_bits(raw_csd, 128, 48, 22) + 1) *
319 		    512 * 1024;
320 	} else
321 		panic("unknown SD CSD version");
322 }
323 
324 static void
325 mmc_decode_csd_mmc(uint32_t *raw_csd, struct mmc_csd *csd)
326 {
327 	int m;
328 	int e;
329 
330 	memset(csd, 0, sizeof(*csd));
331 	csd->csd_structure = mmc_get_bits(raw_csd, 128, 126, 2);
332 	csd->spec_vers = mmc_get_bits(raw_csd, 128, 122, 4);
333 	m = mmc_get_bits(raw_csd, 128, 115, 4);
334 	e = mmc_get_bits(raw_csd, 128, 112, 3);
335 	csd->tacc = exp[e] * mant[m] + 9 / 10;
336 	csd->nsac = mmc_get_bits(raw_csd, 128, 104, 8) * 100;
337 	m = mmc_get_bits(raw_csd, 128, 99, 4);
338 	e = mmc_get_bits(raw_csd, 128, 96, 3);
339 	csd->tran_speed = exp[e] * 10000 * mant[m];
340 	csd->ccc = mmc_get_bits(raw_csd, 128, 84, 12);
341 	csd->read_bl_len = 1 << mmc_get_bits(raw_csd, 128, 80, 4);
342 	csd->read_bl_partial = mmc_get_bits(raw_csd, 128, 79, 1);
343 	csd->write_blk_misalign = mmc_get_bits(raw_csd, 128, 78, 1);
344 	csd->read_blk_misalign = mmc_get_bits(raw_csd, 128, 77, 1);
345 	csd->dsr_imp = mmc_get_bits(raw_csd, 128, 76, 1);
346 	csd->vdd_r_curr_min = cur_min[mmc_get_bits(raw_csd, 128, 59, 3)];
347 	csd->vdd_r_curr_max = cur_max[mmc_get_bits(raw_csd, 128, 56, 3)];
348 	csd->vdd_w_curr_min = cur_min[mmc_get_bits(raw_csd, 128, 53, 3)];
349 	csd->vdd_w_curr_max = cur_max[mmc_get_bits(raw_csd, 128, 50, 3)];
350 	m = mmc_get_bits(raw_csd, 128, 62, 12);
351 	e = mmc_get_bits(raw_csd, 128, 47, 3);
352 	csd->capacity = ((1 + m) << (e + 2)) * csd->read_bl_len;
353 	csd->erase_blk_en = 0;
354 	csd->erase_sector = (mmc_get_bits(raw_csd, 128, 42, 5) + 1) *
355 	    (mmc_get_bits(raw_csd, 128, 37, 5) + 1);
356 	csd->wp_grp_size = mmc_get_bits(raw_csd, 128, 32, 5);
357 	csd->wp_grp_enable = mmc_get_bits(raw_csd, 128, 31, 1);
358 	csd->r2w_factor = 1 << mmc_get_bits(raw_csd, 128, 26, 3);
359 	csd->write_bl_len = 1 << mmc_get_bits(raw_csd, 128, 22, 4);
360 	csd->write_bl_partial = mmc_get_bits(raw_csd, 128, 21, 1);
361 }
362 
363 static void
364 mmc_decode_cid_sd(uint32_t *raw_cid, struct mmc_cid *cid)
365 {
366 	int i;
367 
368 	/* There's no version info, so we take it on faith */
369 	memset(cid, 0, sizeof(*cid));
370 	cid->mid = mmc_get_bits(raw_cid, 128, 120, 8);
371 	cid->oid = mmc_get_bits(raw_cid, 128, 104, 16);
372 	for (i = 0; i < 5; i++)
373 		cid->pnm[i] = mmc_get_bits(raw_cid, 128, 96 - i * 8, 8);
374 	cid->pnm[5] = 0;
375 	cid->prv = mmc_get_bits(raw_cid, 128, 56, 8);
376 	cid->psn = mmc_get_bits(raw_cid, 128, 24, 32);
377 	cid->mdt_year = mmc_get_bits(raw_cid, 128, 12, 8) + 2000;
378 	cid->mdt_month = mmc_get_bits(raw_cid, 128, 8, 4);
379 }
380 
381 static void
382 mmc_decode_cid_mmc(uint32_t *raw_cid, struct mmc_cid *cid)
383 {
384 	int i;
385 
386 	/* There's no version info, so we take it on faith */
387 	memset(cid, 0, sizeof(*cid));
388 	cid->mid = mmc_get_bits(raw_cid, 128, 120, 8);
389 	cid->oid = mmc_get_bits(raw_cid, 128, 104, 8);
390 	for (i = 0; i < 6; i++)
391 		cid->pnm[i] = mmc_get_bits(raw_cid, 128, 96 - i * 8, 8);
392 	cid->pnm[6] = 0;
393 	cid->prv = mmc_get_bits(raw_cid, 128, 48, 8);
394 	cid->psn = mmc_get_bits(raw_cid, 128, 16, 32);
395 	cid->mdt_month = mmc_get_bits(raw_cid, 128, 12, 4);
396 	cid->mdt_year = mmc_get_bits(raw_cid, 128, 8, 4) + 1997;
397 }
398 
399 static void
400 mmc_format_card_id_string(struct sdda_softc *sc, struct mmc_params *mmcp)
401 {
402 	char oidstr[8];
403 	uint8_t c1;
404 	uint8_t c2;
405 
406 	/*
407 	 * Format a card ID string for use by the mmcsd driver, it's what
408 	 * appears between the <> in the following:
409 	 * mmcsd0: 968MB <SD SD01G 8.0 SN 2686905 Mfg 08/2008 by 3 TN> at mmc0
410 	 * 22.5MHz/4bit/128-block
411 	 *
412 	 * Also format just the card serial number, which the mmcsd driver will
413 	 * use as the disk->d_ident string.
414 	 *
415 	 * The card_id_string in mmc_ivars is currently allocated as 64 bytes,
416 	 * and our max formatted length is currently 55 bytes if every field
417 	 * contains the largest value.
418 	 *
419 	 * Sometimes the oid is two printable ascii chars; when it's not,
420 	 * format it as 0xnnnn instead.
421 	 */
422 	c1 = (sc->cid.oid >> 8) & 0x0ff;
423 	c2 = sc->cid.oid & 0x0ff;
424 	if (c1 > 0x1f && c1 < 0x7f && c2 > 0x1f && c2 < 0x7f)
425 		snprintf(oidstr, sizeof(oidstr), "%c%c", c1, c2);
426 	else
427 		snprintf(oidstr, sizeof(oidstr), "0x%04x", sc->cid.oid);
428 	snprintf(sc->card_sn_string, sizeof(sc->card_sn_string),
429 	    "%08X", sc->cid.psn);
430 	snprintf(sc->card_id_string, sizeof(sc->card_id_string),
431 		 "%s%s %s %d.%d SN %08X MFG %02d/%04d by %d %s",
432 		 mmcp->card_features & CARD_FEATURE_MMC ? "MMC" : "SD",
433 		 mmcp->card_features & CARD_FEATURE_SDHC ? "HC" : "",
434 		 sc->cid.pnm, sc->cid.prv >> 4, sc->cid.prv & 0x0f,
435 		 sc->cid.psn, sc->cid.mdt_month, sc->cid.mdt_year,
436 		 sc->cid.mid, oidstr);
437 }
438 
439 static int
440 sddaopen(struct disk *dp)
441 {
442 	struct sdda_part *part;
443 	struct cam_periph *periph;
444 	struct sdda_softc *softc;
445 	int error;
446 
447 	part = (struct sdda_part *)dp->d_drv1;
448 	softc = part->sc;
449 	periph = softc->periph;
450 	if (cam_periph_acquire(periph) != 0) {
451 		return(ENXIO);
452 	}
453 
454 	cam_periph_lock(periph);
455 	if ((error = cam_periph_hold(periph, PRIBIO|PCATCH)) != 0) {
456 		cam_periph_unlock(periph);
457 		cam_periph_release(periph);
458 		return (error);
459 	}
460 
461 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sddaopen\n"));
462 
463 	part->flags |= SDDA_FLAG_OPEN;
464 
465 	cam_periph_unhold(periph);
466 	cam_periph_unlock(periph);
467 	return (0);
468 }
469 
470 static int
471 sddaclose(struct disk *dp)
472 {
473 	struct sdda_part *part;
474 	struct	cam_periph *periph;
475 	struct	sdda_softc *softc;
476 
477 	part = (struct sdda_part *)dp->d_drv1;
478 	softc = part->sc;
479 	periph = softc->periph;
480 	part->flags &= ~SDDA_FLAG_OPEN;
481 
482 	cam_periph_lock(periph);
483 
484 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sddaclose\n"));
485 
486 	while (softc->refcount != 0)
487 		cam_periph_sleep(periph, &softc->refcount, PRIBIO, "sddaclose", 1);
488 	cam_periph_unlock(periph);
489 	cam_periph_release(periph);
490 	return (0);
491 }
492 
493 static void
494 sddaschedule(struct cam_periph *periph)
495 {
496 	struct sdda_softc *softc = (struct sdda_softc *)periph->softc;
497 	struct sdda_part *part;
498 	struct bio *bp;
499 	int i;
500 
501 	/* Check if we have more work to do. */
502 	/* Find partition that has outstanding commands. Prefer current partition. */
503 	bp = bioq_first(&softc->part[softc->part_curr]->bio_queue);
504 	if (bp == NULL) {
505 		for (i = 0; i < MMC_PART_MAX; i++) {
506 			if ((part = softc->part[i]) != NULL &&
507 			    (bp = bioq_first(&softc->part[i]->bio_queue)) != NULL)
508 				break;
509 		}
510 	}
511 	if (bp != NULL) {
512 		xpt_schedule(periph, CAM_PRIORITY_NORMAL);
513 	}
514 }
515 
516 /*
517  * Actually translate the requested transfer into one the physical driver
518  * can understand.  The transfer is described by a buf and will include
519  * only one physical transfer.
520  */
521 static void
522 sddastrategy(struct bio *bp)
523 {
524 	struct cam_periph *periph;
525 	struct sdda_part *part;
526 	struct sdda_softc *softc;
527 
528 	part = (struct sdda_part *)bp->bio_disk->d_drv1;
529 	softc = part->sc;
530 	periph = softc->periph;
531 
532 	cam_periph_lock(periph);
533 
534 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sddastrategy(%p)\n", bp));
535 
536 	/*
537 	 * If the device has been made invalid, error out
538 	 */
539 	if ((periph->flags & CAM_PERIPH_INVALID) != 0) {
540 		cam_periph_unlock(periph);
541 		biofinish(bp, NULL, ENXIO);
542 		return;
543 	}
544 
545 	/*
546 	 * Place it in the queue of disk activities for this disk
547 	 */
548 	bioq_disksort(&part->bio_queue, bp);
549 
550 	/*
551 	 * Schedule ourselves for performing the work.
552 	 */
553 	sddaschedule(periph);
554 	cam_periph_unlock(periph);
555 
556 	return;
557 }
558 
559 static void
560 sddainit(void)
561 {
562 	cam_status status;
563 
564 	/*
565 	 * Install a global async callback.  This callback will
566 	 * receive async callbacks like "new device found".
567 	 */
568 	status = xpt_register_async(AC_FOUND_DEVICE, sddaasync, NULL, NULL);
569 
570 	if (status != CAM_REQ_CMP) {
571 		printf("sdda: Failed to attach master async callback "
572 		       "due to status 0x%x!\n", status);
573 	}
574 }
575 
576 /*
577  * Callback from GEOM, called when it has finished cleaning up its
578  * resources.
579  */
580 static void
581 sddadiskgonecb(struct disk *dp)
582 {
583 	struct cam_periph *periph;
584 	struct sdda_part *part;
585 
586 	part = (struct sdda_part *)dp->d_drv1;
587 	periph = part->sc->periph;
588 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sddadiskgonecb\n"));
589 
590 	cam_periph_release(periph);
591 }
592 
593 static void
594 sddaoninvalidate(struct cam_periph *periph)
595 {
596 	struct sdda_softc *softc;
597 	struct sdda_part *part;
598 
599 	softc = (struct sdda_softc *)periph->softc;
600 
601 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sddaoninvalidate\n"));
602 
603 	/*
604 	 * De-register any async callbacks.
605 	 */
606 	xpt_register_async(0, sddaasync, periph, periph->path);
607 
608 	/*
609 	 * Return all queued I/O with ENXIO.
610 	 * XXX Handle any transactions queued to the card
611 	 *     with XPT_ABORT_CCB.
612 	 */
613 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("bioq_flush start\n"));
614 	for (int i = 0; i < MMC_PART_MAX; i++) {
615 		if ((part = softc->part[i]) != NULL) {
616 			bioq_flush(&part->bio_queue, NULL, ENXIO);
617 			disk_gone(part->disk);
618 		}
619 	}
620 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("bioq_flush end\n"));
621 }
622 
623 static void
624 sddacleanup(struct cam_periph *periph)
625 {
626 	struct sdda_softc *softc;
627 	struct sdda_part *part;
628 	int i;
629 
630 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sddacleanup\n"));
631 	softc = (struct sdda_softc *)periph->softc;
632 
633 	cam_periph_unlock(periph);
634 
635 	for (i = 0; i < MMC_PART_MAX; i++) {
636 		if ((part = softc->part[i]) != NULL) {
637 			disk_destroy(part->disk);
638 			free(part, M_DEVBUF);
639 			softc->part[i] = NULL;
640 		}
641 	}
642 	free(softc, M_DEVBUF);
643 	cam_periph_lock(periph);
644 }
645 
646 static void
647 sddaasync(void *callback_arg, uint32_t code,
648 	struct cam_path *path, void *arg)
649 {
650 	struct ccb_getdev cgd;
651 	struct cam_periph *periph;
652 
653 	periph = (struct cam_periph *)callback_arg;
654         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("sddaasync(code=%d)\n", code));
655 	switch (code) {
656 	case AC_FOUND_DEVICE:
657 	{
658 		CAM_DEBUG(path, CAM_DEBUG_TRACE, ("=> AC_FOUND_DEVICE\n"));
659 		struct ccb_getdev *cgd;
660 		cam_status status;
661 
662 		cgd = (struct ccb_getdev *)arg;
663 		if (cgd == NULL)
664 			break;
665 
666 		if (cgd->protocol != PROTO_MMCSD)
667 			break;
668 
669 		if (!(path->device->mmc_ident_data.card_features & CARD_FEATURE_MEMORY)) {
670 			CAM_DEBUG(path, CAM_DEBUG_TRACE, ("No memory on the card!\n"));
671 			break;
672 		}
673 
674 		/*
675 		 * Allocate a peripheral instance for
676 		 * this device and start the probe
677 		 * process.
678 		 */
679 		status = cam_periph_alloc(sddaregister, sddaoninvalidate,
680 					  sddacleanup, sddastart,
681 					  "sdda", CAM_PERIPH_BIO,
682 					  path, sddaasync,
683 					  AC_FOUND_DEVICE, cgd);
684 
685 		if (status != CAM_REQ_CMP
686 		 && status != CAM_REQ_INPROG)
687 			printf("sddaasync: Unable to attach to new device "
688 				"due to status 0x%x\n", status);
689 		break;
690 	}
691 	case AC_GETDEV_CHANGED:
692 	{
693 		CAM_DEBUG(path, CAM_DEBUG_TRACE, ("=> AC_GETDEV_CHANGED\n"));
694 		memset(&cgd, 0, sizeof(cgd));
695 		xpt_setup_ccb(&cgd.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
696 		cgd.ccb_h.func_code = XPT_GDEV_TYPE;
697 		xpt_action((union ccb *)&cgd);
698 		cam_periph_async(periph, code, path, arg);
699 		break;
700 	}
701 	case AC_ADVINFO_CHANGED:
702 	{
703 		uintptr_t buftype;
704 		int i;
705 
706 		CAM_DEBUG(path, CAM_DEBUG_TRACE, ("=> AC_ADVINFO_CHANGED\n"));
707 		buftype = (uintptr_t)arg;
708 		if (buftype == CDAI_TYPE_PHYS_PATH) {
709 			struct sdda_softc *softc;
710 			struct sdda_part *part;
711 
712 			softc = periph->softc;
713 			for (i = 0; i < MMC_PART_MAX; i++) {
714 				if ((part = softc->part[i]) != NULL) {
715 					disk_attr_changed(part->disk, "GEOM::physpath",
716 					    M_NOWAIT);
717 				}
718 			}
719 		}
720 		break;
721 	}
722 	default:
723 		CAM_DEBUG(path, CAM_DEBUG_TRACE, ("=> default?!\n"));
724 		cam_periph_async(periph, code, path, arg);
725 		break;
726 	}
727 }
728 
729 static int
730 sddagetattr(struct bio *bp)
731 {
732 	struct cam_periph *periph;
733 	struct sdda_softc *softc;
734 	struct sdda_part *part;
735 	int ret;
736 
737 	part = (struct sdda_part *)bp->bio_disk->d_drv1;
738 	softc = part->sc;
739 	periph = softc->periph;
740 	cam_periph_lock(periph);
741 	ret = xpt_getattr(bp->bio_data, bp->bio_length, bp->bio_attribute,
742 	    periph->path);
743 	cam_periph_unlock(periph);
744 	if (ret == 0)
745 		bp->bio_completed = bp->bio_length;
746 	return (ret);
747 }
748 
749 static cam_status
750 sddaregister(struct cam_periph *periph, void *arg)
751 {
752 	struct sdda_softc *softc;
753 	struct ccb_getdev *cgd;
754 
755 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sddaregister\n"));
756 	cgd = (struct ccb_getdev *)arg;
757 	if (cgd == NULL) {
758 		printf("sddaregister: no getdev CCB, can't register device\n");
759 		return (CAM_REQ_CMP_ERR);
760 	}
761 
762 	softc = (struct sdda_softc *)malloc(sizeof(*softc), M_DEVBUF,
763 	    M_NOWAIT|M_ZERO);
764 	if (softc == NULL) {
765 		printf("sddaregister: Unable to probe new device. "
766 		    "Unable to allocate softc\n");
767 		return (CAM_REQ_CMP_ERR);
768 	}
769 
770 	softc->state = SDDA_STATE_INIT;
771 	softc->mmcdata =
772 		(struct mmc_data *)malloc(sizeof(struct mmc_data), M_DEVBUF, M_NOWAIT|M_ZERO);
773 	if (softc->mmcdata == NULL) {
774 		printf("sddaregister: Unable to probe new device. "
775 		    "Unable to allocate mmcdata\n");
776 		free(softc, M_DEVBUF);
777 		return (CAM_REQ_CMP_ERR);
778 	}
779 	periph->softc = softc;
780 	softc->periph = periph;
781 
782 	xpt_schedule(periph, CAM_PRIORITY_XPT);
783 	TASK_INIT(&softc->start_init_task, 0, sdda_start_init_task, periph);
784 	taskqueue_enqueue(taskqueue_thread, &softc->start_init_task);
785 
786 	return (CAM_REQ_CMP);
787 }
788 
789 static int
790 mmc_exec_app_cmd(struct cam_periph *periph, union ccb *ccb,
791 	struct mmc_command *cmd) {
792 	int err;
793 
794 	/* Send APP_CMD first */
795 	memset(&ccb->mmcio.cmd, 0, sizeof(struct mmc_command));
796 	memset(&ccb->mmcio.stop, 0, sizeof(struct mmc_command));
797 	cam_fill_mmcio(&ccb->mmcio,
798 		       /*retries*/ 0,
799 		       /*cbfcnp*/ NULL,
800 		       /*flags*/ CAM_DIR_NONE,
801 		       /*mmc_opcode*/ MMC_APP_CMD,
802 		       /*mmc_arg*/ get_rca(periph) << 16,
803 		       /*mmc_flags*/ MMC_RSP_R1 | MMC_CMD_AC,
804 		       /*mmc_data*/ NULL,
805 		       /*timeout*/ 0);
806 
807 	cam_periph_runccb(ccb, sddaerror, CAM_FLAG_NONE, /*sense_flags*/0, NULL);
808 	err = mmc_handle_reply(ccb);
809 	if (err != 0)
810 		return (err);
811 	if (!(ccb->mmcio.cmd.resp[0] & R1_APP_CMD))
812 		return (EIO);
813 
814 	/* Now exec actual command */
815 	int flags = 0;
816 	if (cmd->data != NULL) {
817 		ccb->mmcio.cmd.data = cmd->data;
818 		if (cmd->data->flags & MMC_DATA_READ)
819 			flags |= CAM_DIR_IN;
820 		if (cmd->data->flags & MMC_DATA_WRITE)
821 			flags |= CAM_DIR_OUT;
822 	} else flags = CAM_DIR_NONE;
823 
824 	cam_fill_mmcio(&ccb->mmcio,
825 		       /*retries*/ 0,
826 		       /*cbfcnp*/ NULL,
827 		       /*flags*/ flags,
828 		       /*mmc_opcode*/ cmd->opcode,
829 		       /*mmc_arg*/ cmd->arg,
830 		       /*mmc_flags*/ cmd->flags,
831 		       /*mmc_data*/ cmd->data,
832 		       /*timeout*/ 0);
833 
834 	cam_periph_runccb(ccb, sddaerror, CAM_FLAG_NONE, /*sense_flags*/0, NULL);
835 	err = mmc_handle_reply(ccb);
836 	if (err != 0)
837 		return (err);
838 	memcpy(cmd->resp, ccb->mmcio.cmd.resp, sizeof(cmd->resp));
839 	cmd->error = ccb->mmcio.cmd.error;
840 
841 	return (0);
842 }
843 
844 static int
845 mmc_app_get_scr(struct cam_periph *periph, union ccb *ccb, uint32_t *rawscr) {
846 	int err;
847 	struct mmc_command cmd;
848 	struct mmc_data d;
849 
850 	memset(&cmd, 0, sizeof(cmd));
851 	memset(&d, 0, sizeof(d));
852 
853 	memset(rawscr, 0, 8);
854 	cmd.opcode = ACMD_SEND_SCR;
855 	cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
856 	cmd.arg = 0;
857 
858 	d.data = rawscr;
859 	d.len = 8;
860 	d.flags = MMC_DATA_READ;
861 	cmd.data = &d;
862 
863 	err = mmc_exec_app_cmd(periph, ccb, &cmd);
864 	rawscr[0] = be32toh(rawscr[0]);
865 	rawscr[1] = be32toh(rawscr[1]);
866 	return (err);
867 }
868 
869 static int
870 mmc_send_ext_csd(struct cam_periph *periph, union ccb *ccb,
871 		 uint8_t *rawextcsd, size_t buf_len) {
872 	int err;
873 	struct mmc_data d;
874 
875 	KASSERT(buf_len == 512, ("Buffer for ext csd must be 512 bytes"));
876 	memset(&d, 0, sizeof(d));
877 	d.data = rawextcsd;
878 	d.len = buf_len;
879 	d.flags = MMC_DATA_READ;
880 	memset(d.data, 0, d.len);
881 
882 	cam_fill_mmcio(&ccb->mmcio,
883 		       /*retries*/ 0,
884 		       /*cbfcnp*/ NULL,
885 		       /*flags*/ CAM_DIR_IN,
886 		       /*mmc_opcode*/ MMC_SEND_EXT_CSD,
887 		       /*mmc_arg*/ 0,
888 		       /*mmc_flags*/ MMC_RSP_R1 | MMC_CMD_ADTC,
889 		       /*mmc_data*/ &d,
890 		       /*timeout*/ 0);
891 
892 	cam_periph_runccb(ccb, sddaerror, CAM_FLAG_NONE, /*sense_flags*/0, NULL);
893 	err = mmc_handle_reply(ccb);
894 	return (err);
895 }
896 
897 static void
898 mmc_app_decode_scr(uint32_t *raw_scr, struct mmc_scr *scr)
899 {
900 	unsigned int scr_struct;
901 
902 	memset(scr, 0, sizeof(*scr));
903 
904 	scr_struct = mmc_get_bits(raw_scr, 64, 60, 4);
905 	if (scr_struct != 0) {
906 		printf("Unrecognised SCR structure version %d\n",
907 		    scr_struct);
908 		return;
909 	}
910 	scr->sda_vsn = mmc_get_bits(raw_scr, 64, 56, 4);
911 	scr->bus_widths = mmc_get_bits(raw_scr, 64, 48, 4);
912 }
913 
914 static inline void
915 mmc_switch_fill_mmcio(union ccb *ccb,
916     uint8_t set, uint8_t index, uint8_t value, u_int timeout)
917 {
918 	int arg = (MMC_SWITCH_FUNC_WR << 24) |
919 	    (index << 16) |
920 	    (value << 8) |
921 	    set;
922 
923 	cam_fill_mmcio(&ccb->mmcio,
924 		       /*retries*/ 0,
925 		       /*cbfcnp*/ NULL,
926 		       /*flags*/ CAM_DIR_NONE,
927 		       /*mmc_opcode*/ MMC_SWITCH_FUNC,
928 		       /*mmc_arg*/ arg,
929 		       /*mmc_flags*/ MMC_RSP_R1B | MMC_CMD_AC,
930 		       /*mmc_data*/ NULL,
931 		       /*timeout*/ timeout);
932 }
933 
934 static int
935 mmc_select_card(struct cam_periph *periph, union ccb *ccb, uint32_t rca)
936 {
937 	int flags, err;
938 
939 	flags = (rca ? MMC_RSP_R1B : MMC_RSP_NONE) | MMC_CMD_AC;
940 	cam_fill_mmcio(&ccb->mmcio,
941 		       /*retries*/ 0,
942 		       /*cbfcnp*/ NULL,
943 		       /*flags*/ CAM_DIR_IN,
944 		       /*mmc_opcode*/ MMC_SELECT_CARD,
945 		       /*mmc_arg*/ rca << 16,
946 		       /*mmc_flags*/ flags,
947 		       /*mmc_data*/ NULL,
948 		       /*timeout*/ 0);
949 
950 	cam_periph_runccb(ccb, sddaerror, CAM_FLAG_NONE, /*sense_flags*/0, NULL);
951 	err = mmc_handle_reply(ccb);
952 	return (err);
953 }
954 
955 static int
956 mmc_switch(struct cam_periph *periph, union ccb *ccb,
957     uint8_t set, uint8_t index, uint8_t value, u_int timeout)
958 {
959 	int err;
960 
961 	mmc_switch_fill_mmcio(ccb, set, index, value, timeout);
962 	cam_periph_runccb(ccb, sddaerror, CAM_FLAG_NONE, /*sense_flags*/0, NULL);
963 	err = mmc_handle_reply(ccb);
964 	return (err);
965 }
966 
967 static uint32_t
968 mmc_get_spec_vers(struct cam_periph *periph) {
969 	struct sdda_softc *softc = (struct sdda_softc *)periph->softc;
970 
971 	return (softc->csd.spec_vers);
972 }
973 
974 static uint64_t
975 mmc_get_media_size(struct cam_periph *periph) {
976 	struct sdda_softc *softc = (struct sdda_softc *)periph->softc;
977 
978 	return (softc->mediasize);
979 }
980 
981 static uint32_t
982 mmc_get_cmd6_timeout(struct cam_periph *periph)
983 {
984 	struct sdda_softc *softc = (struct sdda_softc *)periph->softc;
985 
986 	if (mmc_get_spec_vers(periph) >= 6)
987 		return (softc->raw_ext_csd[EXT_CSD_GEN_CMD6_TIME] * 10);
988 	return (500 * 1000);
989 }
990 
991 static int
992 mmc_sd_switch(struct cam_periph *periph, union ccb *ccb,
993 	      uint8_t mode, uint8_t grp, uint8_t value,
994 	      uint8_t *res) {
995 	struct mmc_data mmc_d;
996 	uint32_t arg;
997 	int err;
998 
999 	memset(res, 0, 64);
1000 	memset(&mmc_d, 0, sizeof(mmc_d));
1001 	mmc_d.len = 64;
1002 	mmc_d.data = res;
1003 	mmc_d.flags = MMC_DATA_READ;
1004 
1005 	arg = mode << 31;			/* 0 - check, 1 - set */
1006 	arg |= 0x00FFFFFF;
1007 	arg &= ~(0xF << (grp * 4));
1008 	arg |= value << (grp * 4);
1009 
1010 	cam_fill_mmcio(&ccb->mmcio,
1011 		       /*retries*/ 0,
1012 		       /*cbfcnp*/ NULL,
1013 		       /*flags*/ CAM_DIR_IN,
1014 		       /*mmc_opcode*/ SD_SWITCH_FUNC,
1015 		       /*mmc_arg*/ arg,
1016 		       /*mmc_flags*/ MMC_RSP_R1 | MMC_CMD_ADTC,
1017 		       /*mmc_data*/ &mmc_d,
1018 		       /*timeout*/ 0);
1019 
1020 	cam_periph_runccb(ccb, sddaerror, CAM_FLAG_NONE, /*sense_flags*/0, NULL);
1021 	err = mmc_handle_reply(ccb);
1022 	return (err);
1023 }
1024 
1025 static int
1026 mmc_set_timing(struct cam_periph *periph,
1027 	       union ccb *ccb,
1028 	       enum mmc_bus_timing timing)
1029 {
1030 	u_char switch_res[64];
1031 	int err;
1032 	uint8_t	value;
1033 	struct sdda_softc *softc = (struct sdda_softc *)periph->softc;
1034 	struct mmc_params *mmcp = &periph->path->device->mmc_ident_data;
1035 
1036 	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE,
1037 		  ("mmc_set_timing(timing=%d)", timing));
1038 	switch (timing) {
1039 	case bus_timing_normal:
1040 		value = 0;
1041 		break;
1042 	case bus_timing_hs:
1043 		value = 1;
1044 		break;
1045 	default:
1046 		return (MMC_ERR_INVALID);
1047 	}
1048 	if (mmcp->card_features & CARD_FEATURE_MMC) {
1049 		err = mmc_switch(periph, ccb, EXT_CSD_CMD_SET_NORMAL,
1050 		    EXT_CSD_HS_TIMING, value, softc->cmd6_time);
1051 	} else {
1052 		err = mmc_sd_switch(periph, ccb, SD_SWITCH_MODE_SET, SD_SWITCH_GROUP1, value, switch_res);
1053 	}
1054 
1055 	/* Set high-speed timing on the host */
1056 	struct ccb_trans_settings_mmc *cts;
1057 	cts = &ccb->cts.proto_specific.mmc;
1058 	ccb->ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
1059 	ccb->ccb_h.flags = CAM_DIR_NONE;
1060 	ccb->ccb_h.retry_count = 0;
1061 	ccb->ccb_h.timeout = 100;
1062 	ccb->ccb_h.cbfcnp = NULL;
1063 	cts->ios.timing = timing;
1064 	cts->ios_valid = MMC_BT;
1065 	xpt_action(ccb);
1066 
1067 	return (err);
1068 }
1069 
1070 static void
1071 sdda_start_init_task(void *context, int pending) {
1072 	union ccb *new_ccb;
1073 	struct cam_periph *periph;
1074 
1075 	periph = (struct cam_periph *)context;
1076 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sdda_start_init_task\n"));
1077 	new_ccb = xpt_alloc_ccb();
1078 	xpt_setup_ccb(&new_ccb->ccb_h, periph->path,
1079 		      CAM_PRIORITY_NONE);
1080 
1081 	cam_periph_lock(periph);
1082 	cam_periph_hold(periph, PRIBIO|PCATCH);
1083 	sdda_start_init(context, new_ccb);
1084 	cam_periph_unhold(periph);
1085 	cam_periph_unlock(periph);
1086 	xpt_free_ccb(new_ccb);
1087 }
1088 
1089 static void
1090 sdda_set_bus_width(struct cam_periph *periph, union ccb *ccb, int width) {
1091 	struct sdda_softc *softc = (struct sdda_softc *)periph->softc;
1092 	struct mmc_params *mmcp = &periph->path->device->mmc_ident_data;
1093 	int err;
1094 
1095 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sdda_set_bus_width\n"));
1096 
1097 	/* First set for the card, then for the host */
1098 	if (mmcp->card_features & CARD_FEATURE_MMC) {
1099 		uint8_t	value;
1100 		switch (width) {
1101 		case bus_width_1:
1102 			value = EXT_CSD_BUS_WIDTH_1;
1103 			break;
1104 		case bus_width_4:
1105 			value = EXT_CSD_BUS_WIDTH_4;
1106 			break;
1107 		case bus_width_8:
1108 			value = EXT_CSD_BUS_WIDTH_8;
1109 			break;
1110 		default:
1111 			panic("Invalid bus width %d", width);
1112 		}
1113 		err = mmc_switch(periph, ccb, EXT_CSD_CMD_SET_NORMAL,
1114 		    EXT_CSD_BUS_WIDTH, value, softc->cmd6_time);
1115 	} else {
1116 		/* For SD cards we send ACMD6 with the required bus width in arg */
1117 		struct mmc_command cmd;
1118 		memset(&cmd, 0, sizeof(struct mmc_command));
1119 		cmd.opcode = ACMD_SET_BUS_WIDTH;
1120 		cmd.arg = width;
1121 		cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
1122 		err = mmc_exec_app_cmd(periph, ccb, &cmd);
1123 	}
1124 
1125 	if (err != MMC_ERR_NONE) {
1126 		CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH, ("Error %d when setting bus width on the card\n", err));
1127 		return;
1128 	}
1129 	/* Now card is done, set the host to the same width */
1130 	struct ccb_trans_settings_mmc *cts;
1131 	cts = &ccb->cts.proto_specific.mmc;
1132 	ccb->ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
1133 	ccb->ccb_h.flags = CAM_DIR_NONE;
1134 	ccb->ccb_h.retry_count = 0;
1135 	ccb->ccb_h.timeout = 100;
1136 	ccb->ccb_h.cbfcnp = NULL;
1137 	cts->ios.bus_width = width;
1138 	cts->ios_valid = MMC_BW;
1139 	xpt_action(ccb);
1140 }
1141 
1142 static inline const char
1143 *part_type(u_int type)
1144 {
1145 
1146 	switch (type) {
1147 	case EXT_CSD_PART_CONFIG_ACC_RPMB:
1148 		return ("RPMB");
1149 	case EXT_CSD_PART_CONFIG_ACC_DEFAULT:
1150 		return ("default");
1151 	case EXT_CSD_PART_CONFIG_ACC_BOOT0:
1152 		return ("boot0");
1153 	case EXT_CSD_PART_CONFIG_ACC_BOOT1:
1154 		return ("boot1");
1155 	case EXT_CSD_PART_CONFIG_ACC_GP0:
1156 	case EXT_CSD_PART_CONFIG_ACC_GP1:
1157 	case EXT_CSD_PART_CONFIG_ACC_GP2:
1158 	case EXT_CSD_PART_CONFIG_ACC_GP3:
1159 		return ("general purpose");
1160 	default:
1161 		return ("(unknown type)");
1162 	}
1163 }
1164 
1165 static inline const char
1166 *bus_width_str(enum mmc_bus_width w)
1167 {
1168 
1169 	switch (w) {
1170 	case bus_width_1:
1171 		return ("1-bit");
1172 	case bus_width_4:
1173 		return ("4-bit");
1174 	case bus_width_8:
1175 		return ("8-bit");
1176 	default:
1177 		__assert_unreachable();
1178 	}
1179 }
1180 
1181 static uint32_t
1182 sdda_get_host_caps(struct cam_periph *periph, union ccb *ccb)
1183 {
1184 	struct ccb_trans_settings_mmc *cts;
1185 
1186 	cts = &ccb->cts.proto_specific.mmc;
1187 
1188 	ccb->ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
1189 	ccb->ccb_h.flags = CAM_DIR_NONE;
1190 	ccb->ccb_h.retry_count = 0;
1191 	ccb->ccb_h.timeout = 100;
1192 	ccb->ccb_h.cbfcnp = NULL;
1193 	xpt_action(ccb);
1194 
1195 	if (ccb->ccb_h.status != CAM_REQ_CMP)
1196 		panic("Cannot get host caps");
1197 	return (cts->host_caps);
1198 }
1199 
1200 static uint32_t
1201 sdda_get_max_data(struct cam_periph *periph, union ccb *ccb)
1202 {
1203 	struct ccb_trans_settings_mmc *cts;
1204 
1205 	cts = &ccb->cts.proto_specific.mmc;
1206 	memset(cts, 0, sizeof(struct ccb_trans_settings_mmc));
1207 
1208 	ccb->ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
1209 	ccb->ccb_h.flags = CAM_DIR_NONE;
1210 	ccb->ccb_h.retry_count = 0;
1211 	ccb->ccb_h.timeout = 100;
1212 	ccb->ccb_h.cbfcnp = NULL;
1213 	xpt_action(ccb);
1214 
1215 	if (ccb->ccb_h.status != CAM_REQ_CMP)
1216 		panic("Cannot get host max data");
1217 	KASSERT(cts->host_max_data != 0, ("host_max_data == 0?!"));
1218 	return (cts->host_max_data);
1219 }
1220 
1221 static void
1222 sdda_start_init(void *context, union ccb *start_ccb)
1223 {
1224 	struct cam_periph *periph = (struct cam_periph *)context;
1225 	struct ccb_trans_settings_mmc *cts;
1226 	uint32_t host_caps;
1227 	uint32_t sec_count;
1228 	int err;
1229 	int host_f_max;
1230 	uint8_t card_type;
1231 
1232 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sdda_start_init\n"));
1233 	/* periph was held for us when this task was enqueued */
1234 	if ((periph->flags & CAM_PERIPH_INVALID) != 0) {
1235 		cam_periph_release(periph);
1236 		return;
1237 	}
1238 
1239 	struct sdda_softc *softc = (struct sdda_softc *)periph->softc;
1240 	struct mmc_params *mmcp = &periph->path->device->mmc_ident_data;
1241 	struct cam_ed *device = periph->path->device;
1242 
1243 	if (mmcp->card_features & CARD_FEATURE_MMC) {
1244 		mmc_decode_csd_mmc(mmcp->card_csd, &softc->csd);
1245 		mmc_decode_cid_mmc(mmcp->card_cid, &softc->cid);
1246 		if (mmc_get_spec_vers(periph) >= 4) {
1247 			err = mmc_send_ext_csd(periph, start_ccb,
1248 					       (uint8_t *)&softc->raw_ext_csd,
1249 					       sizeof(softc->raw_ext_csd));
1250 			if (err != 0) {
1251 				CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH,
1252 				    ("Cannot read EXT_CSD, err %d", err));
1253 				return;
1254 			}
1255 		}
1256 	} else {
1257 		mmc_decode_csd_sd(mmcp->card_csd, &softc->csd);
1258 		mmc_decode_cid_sd(mmcp->card_cid, &softc->cid);
1259 	}
1260 
1261 	softc->sector_count = softc->csd.capacity / MMC_SECTOR_SIZE;
1262 	softc->mediasize = softc->csd.capacity;
1263 	softc->cmd6_time = mmc_get_cmd6_timeout(periph);
1264 
1265 	/* MMC >= 4.x have EXT_CSD that has its own opinion about capacity */
1266 	if (mmc_get_spec_vers(periph) >= 4) {
1267 		sec_count = softc->raw_ext_csd[EXT_CSD_SEC_CNT] +
1268 		    (softc->raw_ext_csd[EXT_CSD_SEC_CNT + 1] << 8) +
1269 		    (softc->raw_ext_csd[EXT_CSD_SEC_CNT + 2] << 16) +
1270 		    (softc->raw_ext_csd[EXT_CSD_SEC_CNT + 3] << 24);
1271 		if (sec_count != 0) {
1272 			softc->sector_count = sec_count;
1273 			softc->mediasize = softc->sector_count * MMC_SECTOR_SIZE;
1274 			/* FIXME: there should be a better name for this option...*/
1275 			mmcp->card_features |= CARD_FEATURE_SDHC;
1276 		}
1277 	}
1278 	CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH,
1279 	    ("Capacity: %"PRIu64", sectors: %"PRIu64"\n",
1280 		softc->mediasize,
1281 		softc->sector_count));
1282 	mmc_format_card_id_string(softc, mmcp);
1283 
1284 	/* Update info for CAM */
1285 	device->serial_num_len = strlen(softc->card_sn_string);
1286 	device->serial_num = (uint8_t *)malloc((device->serial_num_len + 1),
1287 	    M_CAMXPT, M_NOWAIT);
1288 	strlcpy(device->serial_num, softc->card_sn_string, device->serial_num_len + 1);
1289 
1290 	device->device_id_len = strlen(softc->card_id_string);
1291 	device->device_id = (uint8_t *)malloc((device->device_id_len + 1),
1292 	    M_CAMXPT, M_NOWAIT);
1293 	strlcpy(device->device_id, softc->card_id_string, device->device_id_len + 1);
1294 
1295 	strlcpy(mmcp->model, softc->card_id_string, sizeof(mmcp->model));
1296 
1297 	/* Set the clock frequency that the card can handle */
1298 	cts = &start_ccb->cts.proto_specific.mmc;
1299 
1300 	/* First, get the host's max freq */
1301 	start_ccb->ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
1302 	start_ccb->ccb_h.flags = CAM_DIR_NONE;
1303 	start_ccb->ccb_h.retry_count = 0;
1304 	start_ccb->ccb_h.timeout = 100;
1305 	start_ccb->ccb_h.cbfcnp = NULL;
1306 	xpt_action(start_ccb);
1307 
1308 	if (start_ccb->ccb_h.status != CAM_REQ_CMP)
1309 		panic("Cannot get max host freq");
1310 	host_f_max = cts->host_f_max;
1311 	host_caps = cts->host_caps;
1312 	if (cts->ios.bus_width != bus_width_1)
1313 		panic("Bus width in ios is not 1-bit");
1314 
1315 	/* Now check if the card supports High-speed */
1316 	softc->card_f_max = softc->csd.tran_speed;
1317 
1318 	if (host_caps & MMC_CAP_HSPEED) {
1319 		/* Find out if the card supports High speed timing */
1320 		if (mmcp->card_features & CARD_FEATURE_SD20) {
1321 			/* Get and decode SCR */
1322 			uint32_t rawscr[2];
1323 			uint8_t res[64];
1324 			if (mmc_app_get_scr(periph, start_ccb, rawscr)) {
1325 				CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH, ("Cannot get SCR\n"));
1326 				goto finish_hs_tests;
1327 			}
1328 			mmc_app_decode_scr(rawscr, &softc->scr);
1329 
1330 			if ((softc->scr.sda_vsn >= 1) && (softc->csd.ccc & (1<<10))) {
1331 				mmc_sd_switch(periph, start_ccb, SD_SWITCH_MODE_CHECK,
1332 					      SD_SWITCH_GROUP1, SD_SWITCH_NOCHANGE, res);
1333 				if (res[13] & 2) {
1334 					CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH, ("Card supports HS\n"));
1335 					softc->card_f_max = SD_HS_MAX;
1336 				}
1337 
1338 				/*
1339 				 * We deselect then reselect the card here.  Some cards
1340 				 * become unselected and timeout with the above two
1341 				 * commands, although the state tables / diagrams in the
1342 				 * standard suggest they go back to the transfer state.
1343 				 * Other cards don't become deselected, and if we
1344 				 * attempt to blindly re-select them, we get timeout
1345 				 * errors from some controllers.  So we deselect then
1346 				 * reselect to handle all situations.
1347 				 */
1348 				mmc_select_card(periph, start_ccb, 0);
1349 				mmc_select_card(periph, start_ccb, get_rca(periph));
1350 			} else {
1351 				CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH, ("Not trying the switch\n"));
1352 				goto finish_hs_tests;
1353 			}
1354 		}
1355 
1356 		if (mmcp->card_features & CARD_FEATURE_MMC && mmc_get_spec_vers(periph) >= 4) {
1357 			card_type = softc->raw_ext_csd[EXT_CSD_CARD_TYPE];
1358 			if (card_type & EXT_CSD_CARD_TYPE_HS_52)
1359 				softc->card_f_max = MMC_TYPE_HS_52_MAX;
1360 			else if (card_type & EXT_CSD_CARD_TYPE_HS_26)
1361 				softc->card_f_max = MMC_TYPE_HS_26_MAX;
1362 			if ((card_type & EXT_CSD_CARD_TYPE_DDR_52_1_2V) != 0 &&
1363 			    (host_caps & MMC_CAP_SIGNALING_120) != 0) {
1364 				setbit(&softc->timings, bus_timing_mmc_ddr52);
1365 				setbit(&softc->vccq_120, bus_timing_mmc_ddr52);
1366 				CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH, ("Card supports DDR52 at 1.2V\n"));
1367 			}
1368 			if ((card_type & EXT_CSD_CARD_TYPE_DDR_52_1_8V) != 0 &&
1369 			    (host_caps & MMC_CAP_SIGNALING_180) != 0) {
1370 				setbit(&softc->timings, bus_timing_mmc_ddr52);
1371 				setbit(&softc->vccq_180, bus_timing_mmc_ddr52);
1372 				CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH, ("Card supports DDR52 at 1.8V\n"));
1373 			}
1374 			if ((card_type & EXT_CSD_CARD_TYPE_HS200_1_2V) != 0 &&
1375 			    (host_caps & MMC_CAP_SIGNALING_120) != 0) {
1376 				setbit(&softc->timings, bus_timing_mmc_hs200);
1377 				setbit(&softc->vccq_120, bus_timing_mmc_hs200);
1378 				CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH, ("Card supports HS200 at 1.2V\n"));
1379 			}
1380 			if ((card_type & EXT_CSD_CARD_TYPE_HS200_1_8V) != 0 &&
1381 			    (host_caps & MMC_CAP_SIGNALING_180) != 0) {
1382 				setbit(&softc->timings, bus_timing_mmc_hs200);
1383 				setbit(&softc->vccq_180, bus_timing_mmc_hs200);
1384 				CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH, ("Card supports HS200 at 1.8V\n"));
1385 			}
1386 		}
1387 	}
1388 	int f_max;
1389 finish_hs_tests:
1390 	f_max = min(host_f_max, softc->card_f_max);
1391 	CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH, ("Set SD freq to %d MHz (min out of host f=%d MHz and card f=%d MHz)\n", f_max  / 1000000, host_f_max / 1000000, softc->card_f_max / 1000000));
1392 
1393 	/* Enable high-speed timing on the card */
1394 	if (f_max > 25000000) {
1395 		err = mmc_set_timing(periph, start_ccb, bus_timing_hs);
1396 		if (err != MMC_ERR_NONE) {
1397 			CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("Cannot switch card to high-speed mode"));
1398 			f_max = 25000000;
1399 		}
1400 	}
1401 	/* If possible, set lower-level signaling */
1402 	enum mmc_bus_timing timing;
1403 	/* FIXME: MMCCAM supports max. bus_timing_mmc_ddr52 at the moment. */
1404 	for (timing = bus_timing_mmc_ddr52; timing > bus_timing_normal; timing--) {
1405 		if (isset(&softc->vccq_120, timing)) {
1406 			/* Set VCCQ = 1.2V */
1407 			start_ccb->ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
1408 			start_ccb->ccb_h.flags = CAM_DIR_NONE;
1409 			start_ccb->ccb_h.retry_count = 0;
1410 			start_ccb->ccb_h.timeout = 100;
1411 			start_ccb->ccb_h.cbfcnp = NULL;
1412 			cts->ios.vccq = vccq_120;
1413 			cts->ios_valid = MMC_VCCQ;
1414 			xpt_action(start_ccb);
1415 			break;
1416 		} else if (isset(&softc->vccq_180, timing)) {
1417 			/* Set VCCQ = 1.8V */
1418 			start_ccb->ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
1419 			start_ccb->ccb_h.flags = CAM_DIR_NONE;
1420 			start_ccb->ccb_h.retry_count = 0;
1421 			start_ccb->ccb_h.timeout = 100;
1422 			start_ccb->ccb_h.cbfcnp = NULL;
1423 			cts->ios.vccq = vccq_180;
1424 			cts->ios_valid = MMC_VCCQ;
1425 			xpt_action(start_ccb);
1426 			break;
1427 		} else {
1428 			/* Set VCCQ = 3.3V */
1429 			start_ccb->ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
1430 			start_ccb->ccb_h.flags = CAM_DIR_NONE;
1431 			start_ccb->ccb_h.retry_count = 0;
1432 			start_ccb->ccb_h.timeout = 100;
1433 			start_ccb->ccb_h.cbfcnp = NULL;
1434 			cts->ios.vccq = vccq_330;
1435 			cts->ios_valid = MMC_VCCQ;
1436 			xpt_action(start_ccb);
1437 			break;
1438 		}
1439 	}
1440 
1441 	/* Set frequency on the controller */
1442 	start_ccb->ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
1443 	start_ccb->ccb_h.flags = CAM_DIR_NONE;
1444 	start_ccb->ccb_h.retry_count = 0;
1445 	start_ccb->ccb_h.timeout = 100;
1446 	start_ccb->ccb_h.cbfcnp = NULL;
1447 	cts->ios.clock = f_max;
1448 	cts->ios_valid = MMC_CLK;
1449 	xpt_action(start_ccb);
1450 
1451 	/* Set bus width */
1452 	enum mmc_bus_width desired_bus_width = bus_width_1;
1453 	enum mmc_bus_width max_host_bus_width =
1454 		(host_caps & MMC_CAP_8_BIT_DATA ? bus_width_8 :
1455 		 host_caps & MMC_CAP_4_BIT_DATA ? bus_width_4 : bus_width_1);
1456 	enum mmc_bus_width max_card_bus_width = bus_width_1;
1457 	if (mmcp->card_features & CARD_FEATURE_SD20 &&
1458 	    softc->scr.bus_widths & SD_SCR_BUS_WIDTH_4)
1459 		max_card_bus_width = bus_width_4;
1460 	/*
1461 	 * Unlike SD, MMC cards don't have any information about supported bus width...
1462 	 * So we need to perform read/write test to find out the width.
1463 	 */
1464 	/* TODO: figure out bus width for MMC; use 8-bit for now (to test on BBB) */
1465 	if (mmcp->card_features & CARD_FEATURE_MMC)
1466 		max_card_bus_width = bus_width_8;
1467 
1468 	desired_bus_width = min(max_host_bus_width, max_card_bus_width);
1469 	CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH,
1470 		  ("Set bus width to %s (min of host %s and card %s)\n",
1471 		   bus_width_str(desired_bus_width),
1472 		   bus_width_str(max_host_bus_width),
1473 		   bus_width_str(max_card_bus_width)));
1474 	sdda_set_bus_width(periph, start_ccb, desired_bus_width);
1475 
1476 	softc->state = SDDA_STATE_NORMAL;
1477 
1478 	cam_periph_unhold(periph);
1479 	/* MMC partitions support */
1480 	if (mmcp->card_features & CARD_FEATURE_MMC && mmc_get_spec_vers(periph) >= 4) {
1481 		sdda_process_mmc_partitions(periph, start_ccb);
1482 	} else if (mmcp->card_features & CARD_FEATURE_MEMORY) {
1483 		/* For SD[HC] cards, just add one partition that is the whole card */
1484 		if (sdda_add_part(periph, 0, "sdda",
1485 		    periph->unit_number,
1486 		    mmc_get_media_size(periph),
1487 		    sdda_get_read_only(periph, start_ccb)) == false)
1488 			return;
1489 		softc->part_curr = 0;
1490 	}
1491 	cam_periph_hold(periph, PRIBIO|PCATCH);
1492 
1493 	xpt_announce_periph(periph, softc->card_id_string);
1494 	/*
1495 	 * Add async callbacks for bus reset and bus device reset calls.
1496 	 * I don't bother checking if this fails as, in most cases,
1497 	 * the system will function just fine without them and the only
1498 	 * alternative would be to not attach the device on failure.
1499 	 */
1500 	xpt_register_async(AC_LOST_DEVICE | AC_GETDEV_CHANGED |
1501 	    AC_ADVINFO_CHANGED, sddaasync, periph, periph->path);
1502 }
1503 
1504 static bool
1505 sdda_add_part(struct cam_periph *periph, u_int type, const char *name,
1506     u_int cnt, off_t media_size, bool ro)
1507 {
1508 	struct sdda_softc *sc = (struct sdda_softc *)periph->softc;
1509 	struct sdda_part *part;
1510 	struct ccb_pathinq cpi;
1511 
1512 	CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH,
1513 	    ("Partition type '%s', size %ju %s\n",
1514 	    part_type(type),
1515 	    media_size,
1516 	    ro ? "(read-only)" : ""));
1517 
1518 	part = sc->part[type] = malloc(sizeof(*part), M_DEVBUF,
1519 	    M_NOWAIT | M_ZERO);
1520 	if (part == NULL) {
1521 		printf("Cannot add partition for sdda\n");
1522 		return (false);
1523 	}
1524 
1525 	part->cnt = cnt;
1526 	part->type = type;
1527 	part->ro = ro;
1528 	part->sc = sc;
1529 	snprintf(part->name, sizeof(part->name), name, periph->unit_number);
1530 
1531 	/*
1532 	 * Due to the nature of RPMB partition it doesn't make much sense
1533 	 * to add it as a disk. It would be more appropriate to create a
1534 	 * userland tool to operate on the partition or leverage the existing
1535 	 * tools from sysutils/mmc-utils.
1536 	 */
1537 	if (type == EXT_CSD_PART_CONFIG_ACC_RPMB) {
1538 		/* TODO: Create device, assign IOCTL handler */
1539 		CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH,
1540 		    ("Don't know what to do with RPMB partitions yet\n"));
1541 		return (false);
1542 	}
1543 
1544 	bioq_init(&part->bio_queue);
1545 
1546 	bzero(&cpi, sizeof(cpi));
1547 	xpt_setup_ccb(&cpi.ccb_h, periph->path, CAM_PRIORITY_NONE);
1548 	cpi.ccb_h.func_code = XPT_PATH_INQ;
1549 	xpt_action((union ccb *)&cpi);
1550 
1551 	/*
1552 	 * Register this media as a disk
1553 	 */
1554 	(void)cam_periph_hold(periph, PRIBIO);
1555 	cam_periph_unlock(periph);
1556 
1557 	part->disk = disk_alloc();
1558 	part->disk->d_rotation_rate = DISK_RR_NON_ROTATING;
1559 	part->disk->d_devstat = devstat_new_entry(part->name,
1560 	    cnt, MMC_SECTOR_SIZE,
1561 	    DEVSTAT_ALL_SUPPORTED,
1562 	    DEVSTAT_TYPE_DIRECT | XPORT_DEVSTAT_TYPE(cpi.transport),
1563 	    DEVSTAT_PRIORITY_DISK);
1564 
1565 	part->disk->d_open = sddaopen;
1566 	part->disk->d_close = sddaclose;
1567 	part->disk->d_strategy = sddastrategy;
1568 	if (cam_sim_pollable(periph->sim))
1569 		part->disk->d_dump = sddadump;
1570 	part->disk->d_getattr = sddagetattr;
1571 	part->disk->d_gone = sddadiskgonecb;
1572 	part->disk->d_name = part->name;
1573 	part->disk->d_drv1 = part;
1574 	part->disk->d_maxsize =
1575 	    MIN(maxphys, sdda_get_max_data(periph,
1576 		    (union ccb *)&cpi) * mmc_get_sector_size(periph));
1577 	part->disk->d_unit = cnt;
1578 	part->disk->d_flags = 0;
1579 	strlcpy(part->disk->d_descr, sc->card_id_string,
1580 	    MIN(sizeof(part->disk->d_descr), sizeof(sc->card_id_string)));
1581 	strlcpy(part->disk->d_ident, sc->card_sn_string,
1582 	    MIN(sizeof(part->disk->d_ident), sizeof(sc->card_sn_string)));
1583 	part->disk->d_hba_vendor = cpi.hba_vendor;
1584 	part->disk->d_hba_device = cpi.hba_device;
1585 	part->disk->d_hba_subvendor = cpi.hba_subvendor;
1586 	part->disk->d_hba_subdevice = cpi.hba_subdevice;
1587 	snprintf(part->disk->d_attachment, sizeof(part->disk->d_attachment),
1588 	    "%s%d", cpi.dev_name, cpi.unit_number);
1589 
1590 	part->disk->d_sectorsize = mmc_get_sector_size(periph);
1591 	part->disk->d_mediasize = media_size;
1592 	part->disk->d_stripesize = 0;
1593 	part->disk->d_fwsectors = 0;
1594 	part->disk->d_fwheads = 0;
1595 
1596 	if (sdda_mmcsd_compat)
1597 		disk_add_alias(part->disk, "mmcsd");
1598 
1599 	/*
1600 	 * Acquire a reference to the periph before we register with GEOM.
1601 	 * We'll release this reference once GEOM calls us back (via
1602 	 * sddadiskgonecb()) telling us that our provider has been freed.
1603 	 */
1604 	if (cam_periph_acquire(periph) != 0) {
1605 		xpt_print(periph->path, "%s: lost periph during "
1606 		    "registration!\n", __func__);
1607 		cam_periph_lock(periph);
1608 		return (false);
1609 	}
1610 	disk_create(part->disk, DISK_VERSION);
1611 	cam_periph_lock(periph);
1612 	cam_periph_unhold(periph);
1613 
1614 	return (true);
1615 }
1616 
1617 /*
1618  * For MMC cards, process EXT_CSD and add partitions that are supported by
1619  * this device.
1620  */
1621 static void
1622 sdda_process_mmc_partitions(struct cam_periph *periph, union ccb *ccb)
1623 {
1624 	struct sdda_softc *sc = (struct sdda_softc *)periph->softc;
1625 	struct mmc_params *mmcp = &periph->path->device->mmc_ident_data;
1626 	off_t erase_size, sector_size, size, wp_size;
1627 	int i;
1628 	const uint8_t *ext_csd;
1629 	uint8_t rev;
1630 	bool comp, ro;
1631 
1632 	ext_csd = sc->raw_ext_csd;
1633 
1634 	/*
1635 	 * Enhanced user data area and general purpose partitions are only
1636 	 * supported in revision 1.4 (EXT_CSD_REV == 4) and later, the RPMB
1637 	 * partition in revision 1.5 (MMC v4.41, EXT_CSD_REV == 5) and later.
1638 	 */
1639 	rev = ext_csd[EXT_CSD_REV];
1640 
1641 	/*
1642 	 * Ignore user-creatable enhanced user data area and general purpose
1643 	 * partitions partitions as long as partitioning hasn't been finished.
1644 	 */
1645 	comp = (ext_csd[EXT_CSD_PART_SET] & EXT_CSD_PART_SET_COMPLETED) != 0;
1646 
1647 	/*
1648 	 * Add enhanced user data area slice, unless it spans the entirety of
1649 	 * the user data area.  The enhanced area is of a multiple of high
1650 	 * capacity write protect groups ((ERASE_GRP_SIZE + HC_WP_GRP_SIZE) *
1651 	 * 512 KB) and its offset given in either sectors or bytes, depending
1652 	 * on whether it's a high capacity device or not.
1653 	 * NB: The slicer and its slices need to be registered before adding
1654 	 *     the disk for the corresponding user data area as re-tasting is
1655 	 *     racy.
1656 	 */
1657 	sector_size = mmc_get_sector_size(periph);
1658 	size = ext_csd[EXT_CSD_ENH_SIZE_MULT] +
1659 		(ext_csd[EXT_CSD_ENH_SIZE_MULT + 1] << 8) +
1660 		(ext_csd[EXT_CSD_ENH_SIZE_MULT + 2] << 16);
1661 	if (rev >= 4 && comp == TRUE && size > 0 &&
1662 	    (ext_csd[EXT_CSD_PART_SUPPORT] &
1663 		EXT_CSD_PART_SUPPORT_ENH_ATTR_EN) != 0 &&
1664 	    (ext_csd[EXT_CSD_PART_ATTR] & (EXT_CSD_PART_ATTR_ENH_USR)) != 0) {
1665 		erase_size = ext_csd[EXT_CSD_ERASE_GRP_SIZE] * 1024 *
1666 			MMC_SECTOR_SIZE;
1667 		wp_size = ext_csd[EXT_CSD_HC_WP_GRP_SIZE];
1668 		size *= erase_size * wp_size;
1669 		if (size != mmc_get_media_size(periph) * sector_size) {
1670 			sc->enh_size = size;
1671 			sc->enh_base = (ext_csd[EXT_CSD_ENH_START_ADDR] +
1672 			    (ext_csd[EXT_CSD_ENH_START_ADDR + 1] << 8) +
1673 			    (ext_csd[EXT_CSD_ENH_START_ADDR + 2] << 16) +
1674 			    (ext_csd[EXT_CSD_ENH_START_ADDR + 3] << 24)) *
1675 				((mmcp->card_features & CARD_FEATURE_SDHC) ? 1: MMC_SECTOR_SIZE);
1676 		} else
1677 			CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH,
1678 			    ("enhanced user data area spans entire device"));
1679 	}
1680 
1681 	/*
1682 	 * Add default partition.  This may be the only one or the user
1683 	 * data area in case partitions are supported.
1684 	 */
1685 	ro = sdda_get_read_only(periph, ccb);
1686 	sdda_add_part(periph, EXT_CSD_PART_CONFIG_ACC_DEFAULT, "sdda",
1687 	    periph->unit_number, mmc_get_media_size(periph), ro);
1688 	sc->part_curr = EXT_CSD_PART_CONFIG_ACC_DEFAULT;
1689 
1690 	if (mmc_get_spec_vers(periph) < 3)
1691 		return;
1692 
1693 	/* Belatedly announce enhanced user data slice. */
1694 	if (sc->enh_size != 0) {
1695 		CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH,
1696 		    ("enhanced user data area off 0x%jx size %ju bytes\n",
1697 			sc->enh_base, sc->enh_size));
1698 	}
1699 
1700 	/*
1701 	 * Determine partition switch timeout (provided in units of 10 ms)
1702 	 * and ensure it's at least 300 ms as some eMMC chips lie.
1703 	 */
1704 	sc->part_time = max(ext_csd[EXT_CSD_PART_SWITCH_TO] * 10 * 1000,
1705 	    300 * 1000);
1706 
1707 	/* Add boot partitions, which are of a fixed multiple of 128 KB. */
1708 	size = ext_csd[EXT_CSD_BOOT_SIZE_MULT] * MMC_BOOT_RPMB_BLOCK_SIZE;
1709 	if (size > 0 && (sdda_get_host_caps(periph, ccb) & MMC_CAP_BOOT_NOACC) == 0) {
1710 		sdda_add_part(periph, EXT_CSD_PART_CONFIG_ACC_BOOT0,
1711 		    SDDA_FMT_BOOT, 0, size,
1712 		    ro | ((ext_csd[EXT_CSD_BOOT_WP_STATUS] &
1713 		    EXT_CSD_BOOT_WP_STATUS_BOOT0_MASK) != 0));
1714 		sdda_add_part(periph, EXT_CSD_PART_CONFIG_ACC_BOOT1,
1715 		    SDDA_FMT_BOOT, 1, size,
1716 		    ro | ((ext_csd[EXT_CSD_BOOT_WP_STATUS] &
1717 		    EXT_CSD_BOOT_WP_STATUS_BOOT1_MASK) != 0));
1718 	}
1719 
1720 	/* Add RPMB partition, which also is of a fixed multiple of 128 KB. */
1721 	size = ext_csd[EXT_CSD_RPMB_MULT] * MMC_BOOT_RPMB_BLOCK_SIZE;
1722 	if (rev >= 5 && size > 0)
1723 		sdda_add_part(periph, EXT_CSD_PART_CONFIG_ACC_RPMB,
1724 		    SDDA_FMT_RPMB, 0, size, ro);
1725 
1726 	if (rev <= 3 || comp == FALSE)
1727 		return;
1728 
1729 	/*
1730 	 * Add general purpose partitions, which are of a multiple of high
1731 	 * capacity write protect groups, too.
1732 	 */
1733 	if ((ext_csd[EXT_CSD_PART_SUPPORT] & EXT_CSD_PART_SUPPORT_EN) != 0) {
1734 		erase_size = ext_csd[EXT_CSD_ERASE_GRP_SIZE] * 1024 *
1735 			MMC_SECTOR_SIZE;
1736 		wp_size = ext_csd[EXT_CSD_HC_WP_GRP_SIZE];
1737 		for (i = 0; i < MMC_PART_GP_MAX; i++) {
1738 			size = ext_csd[EXT_CSD_GP_SIZE_MULT + i * 3] +
1739 				(ext_csd[EXT_CSD_GP_SIZE_MULT + i * 3 + 1] << 8) +
1740 				(ext_csd[EXT_CSD_GP_SIZE_MULT + i * 3 + 2] << 16);
1741 			if (size == 0)
1742 				continue;
1743 			sdda_add_part(periph, EXT_CSD_PART_CONFIG_ACC_GP0 + i,
1744 			    SDDA_FMT_GP, i, size * erase_size * wp_size, ro);
1745 		}
1746 	}
1747 }
1748 
1749 /*
1750  * We cannot just call mmc_switch() since it will sleep, and we are in
1751  * GEOM context and cannot sleep. Instead, create an MMCIO request to switch
1752  * partitions and send it to h/w, and upon completion resume processing
1753  * the I/O queue.
1754  * This function cannot fail, instead check switch errors in sddadone().
1755  */
1756 static void
1757 sdda_init_switch_part(struct cam_periph *periph, union ccb *start_ccb,
1758     uint8_t part)
1759 {
1760 	struct sdda_softc *sc = (struct sdda_softc *)periph->softc;
1761 	uint8_t value;
1762 
1763 	KASSERT(part < MMC_PART_MAX, ("%s: invalid partition index", __func__));
1764 	sc->part_requested = part;
1765 
1766 	value = (sc->raw_ext_csd[EXT_CSD_PART_CONFIG] &
1767 	    ~EXT_CSD_PART_CONFIG_ACC_MASK) | part;
1768 
1769 	mmc_switch_fill_mmcio(start_ccb, EXT_CSD_CMD_SET_NORMAL,
1770 	    EXT_CSD_PART_CONFIG, value, sc->part_time);
1771 	start_ccb->ccb_h.cbfcnp = sddadone;
1772 
1773 	sc->outstanding_cmds++;
1774 	cam_periph_unlock(periph);
1775 	xpt_action(start_ccb);
1776 	cam_periph_lock(periph);
1777 }
1778 
1779 /* Called with periph lock held! */
1780 static void
1781 sddastart(struct cam_periph *periph, union ccb *start_ccb)
1782 {
1783 	struct bio *bp;
1784 	struct sdda_softc *softc = (struct sdda_softc *)periph->softc;
1785 	struct sdda_part *part;
1786 	struct mmc_params *mmcp = &periph->path->device->mmc_ident_data;
1787 	uint8_t part_index;
1788 
1789 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sddastart\n"));
1790 
1791 	if (softc->state != SDDA_STATE_NORMAL) {
1792 		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("device is not in SDDA_STATE_NORMAL yet\n"));
1793 		xpt_release_ccb(start_ccb);
1794 		return;
1795 	}
1796 
1797 	/* Find partition that has outstanding commands.  Prefer current partition. */
1798 	part_index = softc->part_curr;
1799 	part = softc->part[softc->part_curr];
1800 	bp = bioq_first(&part->bio_queue);
1801 	if (bp == NULL) {
1802 		for (part_index = 0; part_index < MMC_PART_MAX; part_index++) {
1803 			if ((part = softc->part[part_index]) != NULL &&
1804 			    (bp = bioq_first(&softc->part[part_index]->bio_queue)) != NULL)
1805 				break;
1806 		}
1807 	}
1808 	if (bp == NULL) {
1809 		xpt_release_ccb(start_ccb);
1810 		return;
1811 	}
1812 	if (part_index != softc->part_curr) {
1813 		CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH,
1814 		    ("Partition  %d -> %d\n", softc->part_curr, part_index));
1815 		/*
1816 		 * According to section "6.2.2 Command restrictions" of the eMMC
1817 		 * specification v5.1, CMD19/CMD21 aren't allowed to be used with
1818 		 * RPMB partitions.  So we pause re-tuning along with triggering
1819 		 * it up-front to decrease the likelihood of re-tuning becoming
1820 		 * necessary while accessing an RPMB partition.  Consequently, an
1821 		 * RPMB partition should immediately be switched away from again
1822 		 * after an access in order to allow for re-tuning to take place
1823 		 * anew.
1824 		 */
1825 		/* TODO: pause retune if switching to RPMB partition */
1826 		softc->state = SDDA_STATE_PART_SWITCH;
1827 		sdda_init_switch_part(periph, start_ccb, part_index);
1828 		return;
1829 	}
1830 
1831 	bioq_remove(&part->bio_queue, bp);
1832 
1833 	switch (bp->bio_cmd) {
1834 	case BIO_WRITE:
1835 		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("BIO_WRITE\n"));
1836 		part->flags |= SDDA_FLAG_DIRTY;
1837 		/* FALLTHROUGH */
1838 	case BIO_READ:
1839 	{
1840 		struct ccb_mmcio *mmcio;
1841 		uint64_t blockno = bp->bio_pblkno;
1842 		uint16_t count = bp->bio_bcount / MMC_SECTOR_SIZE;
1843 		uint16_t opcode;
1844 
1845 		if (bp->bio_cmd == BIO_READ)
1846 			CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("BIO_READ\n"));
1847 		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
1848 		    ("Block %"PRIu64" cnt %u\n", blockno, count));
1849 
1850 		/* Construct new MMC command */
1851 		if (bp->bio_cmd == BIO_READ) {
1852 			if (count > 1)
1853 				opcode = MMC_READ_MULTIPLE_BLOCK;
1854 			else
1855 				opcode = MMC_READ_SINGLE_BLOCK;
1856 		} else {
1857 			if (count > 1)
1858 				opcode = MMC_WRITE_MULTIPLE_BLOCK;
1859 			else
1860 				opcode = MMC_WRITE_BLOCK;
1861 		}
1862 
1863 		start_ccb->ccb_h.func_code = XPT_MMC_IO;
1864 		start_ccb->ccb_h.flags = (bp->bio_cmd == BIO_READ ? CAM_DIR_IN : CAM_DIR_OUT);
1865 		start_ccb->ccb_h.retry_count = 0;
1866 		start_ccb->ccb_h.timeout = 15 * 1000;
1867 		start_ccb->ccb_h.cbfcnp = sddadone;
1868 
1869 		mmcio = &start_ccb->mmcio;
1870 		mmcio->cmd.opcode = opcode;
1871 		mmcio->cmd.arg = blockno;
1872 		if (!(mmcp->card_features & CARD_FEATURE_SDHC))
1873 			mmcio->cmd.arg <<= 9;
1874 
1875 		mmcio->cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
1876 		mmcio->cmd.data = softc->mmcdata;
1877 		memset(mmcio->cmd.data, 0, sizeof(struct mmc_data));
1878 		mmcio->cmd.data->data = bp->bio_data;
1879 		mmcio->cmd.data->len = MMC_SECTOR_SIZE * count;
1880 		mmcio->cmd.data->flags = (bp->bio_cmd == BIO_READ ? MMC_DATA_READ : MMC_DATA_WRITE);
1881 		/* Direct h/w to issue CMD12 upon completion */
1882 		if (count > 1) {
1883 			mmcio->cmd.data->flags |= MMC_DATA_MULTI;
1884 			mmcio->stop.opcode = MMC_STOP_TRANSMISSION;
1885 			mmcio->stop.flags = MMC_RSP_R1B | MMC_CMD_AC;
1886 			mmcio->stop.arg = 0;
1887 		}
1888 
1889 		break;
1890 	}
1891 	case BIO_FLUSH:
1892 		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("BIO_FLUSH\n"));
1893 		sddaschedule(periph);
1894 		break;
1895 	case BIO_DELETE:
1896 		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("BIO_DELETE\n"));
1897 		sddaschedule(periph);
1898 		break;
1899 	default:
1900 		biofinish(bp, NULL, EOPNOTSUPP);
1901 		xpt_release_ccb(start_ccb);
1902 		return;
1903 	}
1904 	start_ccb->ccb_h.ccb_bp = bp;
1905 	softc->outstanding_cmds++;
1906 	softc->refcount++;
1907 	cam_periph_unlock(periph);
1908 	xpt_action(start_ccb);
1909 	cam_periph_lock(periph);
1910 
1911 	/* May have more work to do, so ensure we stay scheduled */
1912 	sddaschedule(periph);
1913 }
1914 
1915 static void
1916 sddadone(struct cam_periph *periph, union ccb *done_ccb)
1917 {
1918 	struct bio *bp;
1919 	struct sdda_softc *softc;
1920 	struct ccb_mmcio *mmcio;
1921 	struct cam_path *path;
1922 	uint32_t card_status;
1923 	int error = 0;
1924 
1925 	softc = (struct sdda_softc *)periph->softc;
1926 	mmcio = &done_ccb->mmcio;
1927 	path = done_ccb->ccb_h.path;
1928 
1929 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("sddadone\n"));
1930 	if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1931 		CAM_DEBUG(path, CAM_DEBUG_TRACE, ("Error!!!\n"));
1932 		if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1933 			cam_release_devq(path,
1934 			    /*relsim_flags*/0,
1935 			    /*reduction*/0,
1936 			    /*timeout*/0,
1937 			    /*getcount_only*/0);
1938 		error = EIO;
1939 	} else {
1940 		if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1941 			panic("REQ_CMP with QFRZN");
1942 		error = 0;
1943 	}
1944 
1945 	card_status = mmcio->cmd.resp[0];
1946 	CAM_DEBUG(path, CAM_DEBUG_TRACE,
1947 	    ("Card status: %08x\n", R1_STATUS(card_status)));
1948 	CAM_DEBUG(path, CAM_DEBUG_TRACE,
1949 	    ("Current state: %d\n", R1_CURRENT_STATE(card_status)));
1950 
1951 	/* Process result of switching MMC partitions */
1952 	if (softc->state == SDDA_STATE_PART_SWITCH) {
1953 		CAM_DEBUG(path, CAM_DEBUG_TRACE,
1954 		    ("Completing partition switch to %d\n",
1955 		    softc->part_requested));
1956 		softc->outstanding_cmds--;
1957 		/* Complete partition switch */
1958 		softc->state = SDDA_STATE_NORMAL;
1959 		if (error != 0) {
1960 			/* TODO: Unpause retune if accessing RPMB */
1961 			xpt_release_ccb(done_ccb);
1962 			xpt_schedule(periph, CAM_PRIORITY_NORMAL);
1963 			return;
1964 		}
1965 
1966 		softc->raw_ext_csd[EXT_CSD_PART_CONFIG] =
1967 		    (softc->raw_ext_csd[EXT_CSD_PART_CONFIG] &
1968 			~EXT_CSD_PART_CONFIG_ACC_MASK) | softc->part_requested;
1969 		/* TODO: Unpause retune if accessing RPMB */
1970 		softc->part_curr = softc->part_requested;
1971 		xpt_release_ccb(done_ccb);
1972 
1973 		/* Return to processing BIO requests */
1974 		xpt_schedule(periph, CAM_PRIORITY_NORMAL);
1975 		return;
1976 	}
1977 
1978 	bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
1979 	bp->bio_error = error;
1980 	if (error != 0) {
1981 		bp->bio_resid = bp->bio_bcount;
1982 		bp->bio_flags |= BIO_ERROR;
1983 	} else {
1984 		/* XXX: How many bytes remaining? */
1985 		bp->bio_resid = 0;
1986 		if (bp->bio_resid > 0)
1987 			bp->bio_flags |= BIO_ERROR;
1988 	}
1989 
1990 	softc->outstanding_cmds--;
1991 	xpt_release_ccb(done_ccb);
1992 	/*
1993 	 * Release the periph refcount taken in sddastart() for each CCB.
1994 	 */
1995 	KASSERT(softc->refcount >= 1, ("sddadone softc %p refcount %d", softc, softc->refcount));
1996 	softc->refcount--;
1997 	biodone(bp);
1998 }
1999 
2000 static int
2001 sddaerror(union ccb *ccb, uint32_t cam_flags, uint32_t sense_flags)
2002 {
2003 	return(cam_periph_error(ccb, cam_flags, sense_flags));
2004 }
2005 
2006 static int
2007 sddadump(void *arg, void *virtual, off_t offset, size_t length)
2008 {
2009 	struct ccb_mmcio mmcio;
2010 	struct disk *dp;
2011 	struct sdda_part *part;
2012 	struct sdda_softc *softc;
2013 	struct cam_periph *periph;
2014 	struct mmc_params *mmcp;
2015 	uint16_t count;
2016 	uint16_t opcode;
2017 	int error;
2018 
2019 	dp = arg;
2020 	part = dp->d_drv1;
2021 	softc = part->sc;
2022 	periph = softc->periph;
2023 	mmcp = &periph->path->device->mmc_ident_data;
2024 
2025 	if (softc->state != SDDA_STATE_NORMAL)
2026 		return (ENXIO);
2027 
2028 	count = length / MMC_SECTOR_SIZE;
2029 	if (count == 0)
2030 		return (0);
2031 
2032 	if (softc->part[softc->part_curr] != part)
2033 		return (EIO);	/* TODO implement polled partition switch */
2034 
2035 	memset(&mmcio, 0, sizeof(mmcio));
2036 	xpt_setup_ccb(&mmcio.ccb_h, periph->path, CAM_PRIORITY_NORMAL); /* XXX needed? */
2037 
2038 	mmcio.ccb_h.func_code = XPT_MMC_IO;
2039 	mmcio.ccb_h.flags = CAM_DIR_OUT;
2040 	mmcio.ccb_h.retry_count = 0;
2041 	mmcio.ccb_h.timeout = 15 * 1000;
2042 
2043 	if (count > 1)
2044 		opcode = MMC_WRITE_MULTIPLE_BLOCK;
2045 	else
2046 		opcode = MMC_WRITE_BLOCK;
2047 	mmcio.cmd.opcode = opcode;
2048 	mmcio.cmd.arg = offset / MMC_SECTOR_SIZE;
2049 	if (!(mmcp->card_features & CARD_FEATURE_SDHC))
2050 		mmcio.cmd.arg <<= 9;
2051 
2052 	mmcio.cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
2053 	mmcio.cmd.data = softc->mmcdata;
2054 	memset(mmcio.cmd.data, 0, sizeof(struct mmc_data));
2055 	mmcio.cmd.data->data = virtual;
2056 	mmcio.cmd.data->len = MMC_SECTOR_SIZE * count;
2057 	mmcio.cmd.data->flags = MMC_DATA_WRITE;
2058 
2059 	/* Direct h/w to issue CMD12 upon completion */
2060 	if (count > 1) {
2061 		mmcio.cmd.data->flags |= MMC_DATA_MULTI;
2062 		mmcio.stop.opcode = MMC_STOP_TRANSMISSION;
2063 		mmcio.stop.flags = MMC_RSP_R1B | MMC_CMD_AC;
2064 		mmcio.stop.arg = 0;
2065 	}
2066 
2067 	error = cam_periph_runccb((union ccb *)&mmcio, cam_periph_error,
2068 	    0, SF_NO_RECOVERY | SF_NO_RETRY, NULL);
2069 	if (error != 0)
2070 		printf("Aborting dump due to I/O error.\n");
2071 	return (error);
2072 }
2073 
2074 #endif /* _KERNEL */
2075