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