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