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