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