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