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