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