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