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