xref: /freebsd/sys/cam/mmc/mmc_da.c (revision f0cfa1b168014f56c02b83e5f28412cc5f78d117)
1 /*-
2  * Copyright (c) 2006 Bernd Walter <tisco@FreeBSD.org>
3  * Copyright (c) 2006 M. Warner Losh <imp@FreeBSD.org>
4  * Copyright (c) 2009 Alexander Motin <mav@FreeBSD.org>
5  * Copyright (c) 2015-2017 Ilya Bakulin <kibab@FreeBSD.org>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer,
13  *    without modification, immediately at the beginning of the file.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  *
29  * Some code derived from the sys/dev/mmc and sys/cam/ata
30  * Thanks to Warner Losh <imp@FreeBSD.org>, Alexander Motin <mav@FreeBSD.org>
31  * Bernd Walter <tisco@FreeBSD.org>, and other authors.
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 //#include "opt_sdda.h"
38 
39 #include <sys/param.h>
40 
41 #ifdef _KERNEL
42 #include <sys/systm.h>
43 #include <sys/kernel.h>
44 #include <sys/bio.h>
45 #include <sys/endian.h>
46 #include <sys/taskqueue.h>
47 #include <sys/lock.h>
48 #include <sys/mutex.h>
49 #include <sys/conf.h>
50 #include <sys/devicestat.h>
51 #include <sys/eventhandler.h>
52 #include <sys/malloc.h>
53 #include <sys/cons.h>
54 #include <sys/proc.h>
55 #include <sys/reboot.h>
56 #include <geom/geom_disk.h>
57 #include <machine/_inttypes.h>  /* for PRIu64 */
58 #endif /* _KERNEL */
59 
60 #ifndef _KERNEL
61 #include <stdio.h>
62 #include <string.h>
63 #endif /* _KERNEL */
64 
65 #include <cam/cam.h>
66 #include <cam/cam_ccb.h>
67 #include <cam/cam_queue.h>
68 #include <cam/cam_periph.h>
69 #include <cam/cam_sim.h>
70 #include <cam/cam_xpt.h>
71 #include <cam/cam_xpt_sim.h>
72 #include <cam/cam_xpt_periph.h>
73 #include <cam/cam_xpt_internal.h>
74 #include <cam/cam_debug.h>
75 
76 
77 #include <cam/mmc/mmc_all.h>
78 
79 #include <machine/md_var.h>	/* geometry translation */
80 
81 #ifdef _KERNEL
82 
83 typedef enum {
84 	SDDA_FLAG_OPEN		= 0x0002,
85 	SDDA_FLAG_DIRTY		= 0x0004
86 } sdda_flags;
87 
88 typedef enum {
89         SDDA_STATE_INIT,
90         SDDA_STATE_INVALID,
91         SDDA_STATE_NORMAL
92 } sdda_state;
93 
94 struct sdda_softc {
95 	struct	 bio_queue_head bio_queue;
96 	int	 outstanding_cmds;	/* Number of active commands */
97 	int	 refcount;		/* Active xpt_action() calls */
98 	sdda_state state;
99 	sdda_flags flags;
100 	struct mmc_data *mmcdata;
101 //	sdda_quirks quirks;
102 	struct task start_init_task;
103 	struct	 disk *disk;
104         uint32_t raw_csd[4];
105 	uint8_t raw_ext_csd[512]; /* MMC only? */
106         struct mmc_csd csd;
107         struct mmc_cid cid;
108 	struct mmc_scr scr;
109         /* Calculated from CSD */
110         uint64_t sector_count;
111         uint64_t mediasize;
112 
113         /* Calculated from CID */
114 	char card_id_string[64];/* Formatted CID info (serial, MFG, etc) */
115 	char card_sn_string[16];/* Formatted serial # for disk->d_ident */
116 	/* Determined from CSD + is highspeed card*/
117 	uint32_t card_f_max;
118 };
119 
120 #define ccb_bp		ppriv_ptr1
121 
122 static	disk_strategy_t	sddastrategy;
123 static	periph_init_t	sddainit;
124 static	void		sddaasync(void *callback_arg, u_int32_t code,
125 				struct cam_path *path, void *arg);
126 static	periph_ctor_t	sddaregister;
127 static	periph_dtor_t	sddacleanup;
128 static	periph_start_t	sddastart;
129 static	periph_oninv_t	sddaoninvalidate;
130 static	void		sddadone(struct cam_periph *periph,
131 			       union ccb *done_ccb);
132 static  int		sddaerror(union ccb *ccb, u_int32_t cam_flags,
133 				u_int32_t sense_flags);
134 
135 static uint16_t get_rca(struct cam_periph *periph);
136 static cam_status sdda_hook_into_geom(struct cam_periph *periph);
137 static void sdda_start_init(void *context, union ccb *start_ccb);
138 static void sdda_start_init_task(void *context, int pending);
139 
140 static struct periph_driver sddadriver =
141 {
142 	sddainit, "sdda",
143 	TAILQ_HEAD_INITIALIZER(sddadriver.units), /* generation */ 0
144 };
145 
146 PERIPHDRIVER_DECLARE(sdda, sddadriver);
147 
148 static MALLOC_DEFINE(M_SDDA, "sd_da", "sd_da buffers");
149 
150 static const int exp[8] = {
151 	1, 10, 100, 1000, 10000, 100000, 1000000, 10000000
152 };
153 
154 static const int mant[16] = {
155 	0, 10, 12, 13, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 70, 80
156 };
157 
158 static const int cur_min[8] = {
159 	500, 1000, 5000, 10000, 25000, 35000, 60000, 100000
160 };
161 
162 static const int cur_max[8] = {
163 	1000, 5000, 10000, 25000, 35000, 45000, 800000, 200000
164 };
165 
166 static uint16_t
167 get_rca(struct cam_periph *periph) {
168 	return periph->path->device->mmc_ident_data.card_rca;
169 }
170 
171 static uint32_t
172 mmc_get_bits(uint32_t *bits, int bit_len, int start, int size)
173 {
174 	const int i = (bit_len / 32) - (start / 32) - 1;
175 	const int shift = start & 31;
176 	uint32_t retval = bits[i] >> shift;
177 	if (size + shift > 32)
178 		retval |= bits[i - 1] << (32 - shift);
179 	return (retval & ((1llu << size) - 1));
180 }
181 
182 
183 static void
184 mmc_decode_csd_sd(uint32_t *raw_csd, struct mmc_csd *csd)
185 {
186 	int v;
187 	int m;
188 	int e;
189 
190 	memset(csd, 0, sizeof(*csd));
191 	csd->csd_structure = v = mmc_get_bits(raw_csd, 128, 126, 2);
192 	if (v == 0) {
193 		m = mmc_get_bits(raw_csd, 128, 115, 4);
194 		e = mmc_get_bits(raw_csd, 128, 112, 3);
195 		csd->tacc = (exp[e] * mant[m] + 9) / 10;
196 		csd->nsac = mmc_get_bits(raw_csd, 128, 104, 8) * 100;
197 		m = mmc_get_bits(raw_csd, 128, 99, 4);
198 		e = mmc_get_bits(raw_csd, 128, 96, 3);
199 		csd->tran_speed = exp[e] * 10000 * mant[m];
200 		csd->ccc = mmc_get_bits(raw_csd, 128, 84, 12);
201 		csd->read_bl_len = 1 << mmc_get_bits(raw_csd, 128, 80, 4);
202 		csd->read_bl_partial = mmc_get_bits(raw_csd, 128, 79, 1);
203 		csd->write_blk_misalign = mmc_get_bits(raw_csd, 128, 78, 1);
204 		csd->read_blk_misalign = mmc_get_bits(raw_csd, 128, 77, 1);
205 		csd->dsr_imp = mmc_get_bits(raw_csd, 128, 76, 1);
206 		csd->vdd_r_curr_min = cur_min[mmc_get_bits(raw_csd, 128, 59, 3)];
207 		csd->vdd_r_curr_max = cur_max[mmc_get_bits(raw_csd, 128, 56, 3)];
208 		csd->vdd_w_curr_min = cur_min[mmc_get_bits(raw_csd, 128, 53, 3)];
209 		csd->vdd_w_curr_max = cur_max[mmc_get_bits(raw_csd, 128, 50, 3)];
210 		m = mmc_get_bits(raw_csd, 128, 62, 12);
211 		e = mmc_get_bits(raw_csd, 128, 47, 3);
212 		csd->capacity = ((1 + m) << (e + 2)) * csd->read_bl_len;
213 		csd->erase_blk_en = mmc_get_bits(raw_csd, 128, 46, 1);
214 		csd->erase_sector = mmc_get_bits(raw_csd, 128, 39, 7) + 1;
215 		csd->wp_grp_size = mmc_get_bits(raw_csd, 128, 32, 7);
216 		csd->wp_grp_enable = mmc_get_bits(raw_csd, 128, 31, 1);
217 		csd->r2w_factor = 1 << mmc_get_bits(raw_csd, 128, 26, 3);
218 		csd->write_bl_len = 1 << mmc_get_bits(raw_csd, 128, 22, 4);
219 		csd->write_bl_partial = mmc_get_bits(raw_csd, 128, 21, 1);
220 	} else if (v == 1) {
221 		m = mmc_get_bits(raw_csd, 128, 115, 4);
222 		e = mmc_get_bits(raw_csd, 128, 112, 3);
223 		csd->tacc = (exp[e] * mant[m] + 9) / 10;
224 		csd->nsac = mmc_get_bits(raw_csd, 128, 104, 8) * 100;
225 		m = mmc_get_bits(raw_csd, 128, 99, 4);
226 		e = mmc_get_bits(raw_csd, 128, 96, 3);
227 		csd->tran_speed = exp[e] * 10000 * mant[m];
228 		csd->ccc = mmc_get_bits(raw_csd, 128, 84, 12);
229 		csd->read_bl_len = 1 << mmc_get_bits(raw_csd, 128, 80, 4);
230 		csd->read_bl_partial = mmc_get_bits(raw_csd, 128, 79, 1);
231 		csd->write_blk_misalign = mmc_get_bits(raw_csd, 128, 78, 1);
232 		csd->read_blk_misalign = mmc_get_bits(raw_csd, 128, 77, 1);
233 		csd->dsr_imp = mmc_get_bits(raw_csd, 128, 76, 1);
234 		csd->capacity = ((uint64_t)mmc_get_bits(raw_csd, 128, 48, 22) + 1) *
235 		    512 * 1024;
236 		csd->erase_blk_en = mmc_get_bits(raw_csd, 128, 46, 1);
237 		csd->erase_sector = mmc_get_bits(raw_csd, 128, 39, 7) + 1;
238 		csd->wp_grp_size = mmc_get_bits(raw_csd, 128, 32, 7);
239 		csd->wp_grp_enable = mmc_get_bits(raw_csd, 128, 31, 1);
240 		csd->r2w_factor = 1 << mmc_get_bits(raw_csd, 128, 26, 3);
241 		csd->write_bl_len = 1 << mmc_get_bits(raw_csd, 128, 22, 4);
242 		csd->write_bl_partial = mmc_get_bits(raw_csd, 128, 21, 1);
243 	} else
244 		panic("unknown SD CSD version");
245 }
246 
247 static void
248 mmc_decode_csd_mmc(uint32_t *raw_csd, struct mmc_csd *csd)
249 {
250 	int m;
251 	int e;
252 
253 	memset(csd, 0, sizeof(*csd));
254 	csd->csd_structure = mmc_get_bits(raw_csd, 128, 126, 2);
255 	csd->spec_vers = mmc_get_bits(raw_csd, 128, 122, 4);
256 	m = mmc_get_bits(raw_csd, 128, 115, 4);
257 	e = mmc_get_bits(raw_csd, 128, 112, 3);
258 	csd->tacc = exp[e] * mant[m] + 9 / 10;
259 	csd->nsac = mmc_get_bits(raw_csd, 128, 104, 8) * 100;
260 	m = mmc_get_bits(raw_csd, 128, 99, 4);
261 	e = mmc_get_bits(raw_csd, 128, 96, 3);
262 	csd->tran_speed = exp[e] * 10000 * mant[m];
263 	csd->ccc = mmc_get_bits(raw_csd, 128, 84, 12);
264 	csd->read_bl_len = 1 << mmc_get_bits(raw_csd, 128, 80, 4);
265 	csd->read_bl_partial = mmc_get_bits(raw_csd, 128, 79, 1);
266 	csd->write_blk_misalign = mmc_get_bits(raw_csd, 128, 78, 1);
267 	csd->read_blk_misalign = mmc_get_bits(raw_csd, 128, 77, 1);
268 	csd->dsr_imp = mmc_get_bits(raw_csd, 128, 76, 1);
269 	csd->vdd_r_curr_min = cur_min[mmc_get_bits(raw_csd, 128, 59, 3)];
270 	csd->vdd_r_curr_max = cur_max[mmc_get_bits(raw_csd, 128, 56, 3)];
271 	csd->vdd_w_curr_min = cur_min[mmc_get_bits(raw_csd, 128, 53, 3)];
272 	csd->vdd_w_curr_max = cur_max[mmc_get_bits(raw_csd, 128, 50, 3)];
273 	m = mmc_get_bits(raw_csd, 128, 62, 12);
274 	e = mmc_get_bits(raw_csd, 128, 47, 3);
275 	csd->capacity = ((1 + m) << (e + 2)) * csd->read_bl_len;
276 	csd->erase_blk_en = 0;
277 	csd->erase_sector = (mmc_get_bits(raw_csd, 128, 42, 5) + 1) *
278 	    (mmc_get_bits(raw_csd, 128, 37, 5) + 1);
279 	csd->wp_grp_size = mmc_get_bits(raw_csd, 128, 32, 5);
280 	csd->wp_grp_enable = mmc_get_bits(raw_csd, 128, 31, 1);
281 	csd->r2w_factor = 1 << mmc_get_bits(raw_csd, 128, 26, 3);
282 	csd->write_bl_len = 1 << mmc_get_bits(raw_csd, 128, 22, 4);
283 	csd->write_bl_partial = mmc_get_bits(raw_csd, 128, 21, 1);
284 }
285 
286 static void
287 mmc_decode_cid_sd(uint32_t *raw_cid, struct mmc_cid *cid)
288 {
289 	int i;
290 
291 	/* There's no version info, so we take it on faith */
292 	memset(cid, 0, sizeof(*cid));
293 	cid->mid = mmc_get_bits(raw_cid, 128, 120, 8);
294 	cid->oid = mmc_get_bits(raw_cid, 128, 104, 16);
295 	for (i = 0; i < 5; i++)
296 		cid->pnm[i] = mmc_get_bits(raw_cid, 128, 96 - i * 8, 8);
297 	cid->pnm[5] = 0;
298 	cid->prv = mmc_get_bits(raw_cid, 128, 56, 8);
299 	cid->psn = mmc_get_bits(raw_cid, 128, 24, 32);
300 	cid->mdt_year = mmc_get_bits(raw_cid, 128, 12, 8) + 2000;
301 	cid->mdt_month = mmc_get_bits(raw_cid, 128, 8, 4);
302 }
303 
304 static void
305 mmc_decode_cid_mmc(uint32_t *raw_cid, struct mmc_cid *cid)
306 {
307 	int i;
308 
309 	/* There's no version info, so we take it on faith */
310 	memset(cid, 0, sizeof(*cid));
311 	cid->mid = mmc_get_bits(raw_cid, 128, 120, 8);
312 	cid->oid = mmc_get_bits(raw_cid, 128, 104, 8);
313 	for (i = 0; i < 6; i++)
314 		cid->pnm[i] = mmc_get_bits(raw_cid, 128, 96 - i * 8, 8);
315 	cid->pnm[6] = 0;
316 	cid->prv = mmc_get_bits(raw_cid, 128, 48, 8);
317 	cid->psn = mmc_get_bits(raw_cid, 128, 16, 32);
318 	cid->mdt_month = mmc_get_bits(raw_cid, 128, 12, 4);
319 	cid->mdt_year = mmc_get_bits(raw_cid, 128, 8, 4) + 1997;
320 }
321 
322 static void
323 mmc_format_card_id_string(struct sdda_softc *sc, struct mmc_params *mmcp)
324 {
325 	char oidstr[8];
326 	uint8_t c1;
327 	uint8_t c2;
328 
329 	/*
330 	 * Format a card ID string for use by the mmcsd driver, it's what
331 	 * appears between the <> in the following:
332 	 * mmcsd0: 968MB <SD SD01G 8.0 SN 2686905 Mfg 08/2008 by 3 TN> at mmc0
333 	 * 22.5MHz/4bit/128-block
334 	 *
335 	 * Also format just the card serial number, which the mmcsd driver will
336 	 * use as the disk->d_ident string.
337 	 *
338 	 * The card_id_string in mmc_ivars is currently allocated as 64 bytes,
339 	 * and our max formatted length is currently 55 bytes if every field
340 	 * contains the largest value.
341 	 *
342 	 * Sometimes the oid is two printable ascii chars; when it's not,
343 	 * format it as 0xnnnn instead.
344 	 */
345 	c1 = (sc->cid.oid >> 8) & 0x0ff;
346 	c2 = sc->cid.oid & 0x0ff;
347 	if (c1 > 0x1f && c1 < 0x7f && c2 > 0x1f && c2 < 0x7f)
348 		snprintf(oidstr, sizeof(oidstr), "%c%c", c1, c2);
349 	else
350 		snprintf(oidstr, sizeof(oidstr), "0x%04x", sc->cid.oid);
351 	snprintf(sc->card_sn_string, sizeof(sc->card_sn_string),
352 	    "%08X", sc->cid.psn);
353 	snprintf(sc->card_id_string, sizeof(sc->card_id_string),
354                  "%s%s %s %d.%d SN %08X MFG %02d/%04d by %d %s",
355                  mmcp->card_features & CARD_FEATURE_MMC ? "MMC" : "SD",
356                  mmcp->card_features & CARD_FEATURE_SDHC ? "HC" : "",
357                  sc->cid.pnm, sc->cid.prv >> 4, sc->cid.prv & 0x0f,
358                  sc->cid.psn, sc->cid.mdt_month, sc->cid.mdt_year,
359                  sc->cid.mid, oidstr);
360 }
361 
362 static int
363 sddaopen(struct disk *dp)
364 {
365 	struct cam_periph *periph;
366 	struct sdda_softc *softc;
367 	int error;
368 
369 	periph = (struct cam_periph *)dp->d_drv1;
370 	if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
371 		return(ENXIO);
372 	}
373 
374 	cam_periph_lock(periph);
375 	if ((error = cam_periph_hold(periph, PRIBIO|PCATCH)) != 0) {
376 		cam_periph_unlock(periph);
377 		cam_periph_release(periph);
378 		return (error);
379 	}
380 
381 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sddaopen\n"));
382 
383 	softc = (struct sdda_softc *)periph->softc;
384 	softc->flags |= SDDA_FLAG_OPEN;
385 
386 	cam_periph_unhold(periph);
387 	cam_periph_unlock(periph);
388 	return (0);
389 }
390 
391 static int
392 sddaclose(struct disk *dp)
393 {
394 	struct	cam_periph *periph;
395 	struct	sdda_softc *softc;
396 //	union ccb *ccb;
397 //	int error;
398 
399 	periph = (struct cam_periph *)dp->d_drv1;
400 	softc = (struct sdda_softc *)periph->softc;
401         softc->flags &= ~SDDA_FLAG_OPEN;
402 
403 	cam_periph_lock(periph);
404 
405 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sddaclose\n"));
406 
407 	while (softc->refcount != 0)
408 		cam_periph_sleep(periph, &softc->refcount, PRIBIO, "sddaclose", 1);
409 	cam_periph_unlock(periph);
410 	cam_periph_release(periph);
411 	return (0);
412 }
413 
414 static void
415 sddaschedule(struct cam_periph *periph)
416 {
417 	struct sdda_softc *softc = (struct sdda_softc *)periph->softc;
418 
419 	/* Check if we have more work to do. */
420 	if (bioq_first(&softc->bio_queue)) {
421 		xpt_schedule(periph, CAM_PRIORITY_NORMAL);
422 	}
423 }
424 
425 /*
426  * Actually translate the requested transfer into one the physical driver
427  * can understand.  The transfer is described by a buf and will include
428  * only one physical transfer.
429  */
430 static void
431 sddastrategy(struct bio *bp)
432 {
433 	struct cam_periph *periph;
434 	struct sdda_softc *softc;
435 
436 	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
437 	softc = (struct sdda_softc *)periph->softc;
438 
439 	cam_periph_lock(periph);
440 
441 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sddastrategy(%p)\n", bp));
442 
443 	/*
444 	 * If the device has been made invalid, error out
445 	 */
446 	if ((periph->flags & CAM_PERIPH_INVALID) != 0) {
447 		cam_periph_unlock(periph);
448 		biofinish(bp, NULL, ENXIO);
449 		return;
450 	}
451 
452 	/*
453 	 * Place it in the queue of disk activities for this disk
454 	 */
455         bioq_disksort(&softc->bio_queue, bp);
456 
457 	/*
458 	 * Schedule ourselves for performing the work.
459 	 */
460 	sddaschedule(periph);
461 	cam_periph_unlock(periph);
462 
463 	return;
464 }
465 
466 static void
467 sddainit(void)
468 {
469 	cam_status status;
470 
471 	/*
472 	 * Install a global async callback.  This callback will
473 	 * receive async callbacks like "new device found".
474 	 */
475 	status = xpt_register_async(AC_FOUND_DEVICE, sddaasync, NULL, NULL);
476 
477 	if (status != CAM_REQ_CMP) {
478 		printf("sdda: Failed to attach master async callback "
479 		       "due to status 0x%x!\n", status);
480 	}
481 }
482 
483 /*
484  * Callback from GEOM, called when it has finished cleaning up its
485  * resources.
486  */
487 static void
488 sddadiskgonecb(struct disk *dp)
489 {
490 	struct cam_periph *periph;
491 
492 	periph = (struct cam_periph *)dp->d_drv1;
493         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sddadiskgonecb\n"));
494 
495 	cam_periph_release(periph);
496 }
497 
498 static void
499 sddaoninvalidate(struct cam_periph *periph)
500 {
501 	struct sdda_softc *softc;
502 
503 	softc = (struct sdda_softc *)periph->softc;
504 
505         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sddaoninvalidate\n"));
506 
507 	/*
508 	 * De-register any async callbacks.
509 	 */
510 	xpt_register_async(0, sddaasync, periph, periph->path);
511 
512 	/*
513 	 * Return all queued I/O with ENXIO.
514 	 * XXX Handle any transactions queued to the card
515 	 *     with XPT_ABORT_CCB.
516 	 */
517         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("bioq_flush start\n"));
518 	bioq_flush(&softc->bio_queue, NULL, ENXIO);
519         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("bioq_flush end\n"));
520 
521 	disk_gone(softc->disk);
522 }
523 
524 static void
525 sddacleanup(struct cam_periph *periph)
526 {
527 	struct sdda_softc *softc;
528 
529 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sddacleanup\n"));
530 	softc = (struct sdda_softc *)periph->softc;
531 
532 	cam_periph_unlock(periph);
533 
534 	disk_destroy(softc->disk);
535 	free(softc, M_DEVBUF);
536 	cam_periph_lock(periph);
537 }
538 
539 static void
540 sddaasync(void *callback_arg, u_int32_t code,
541 	struct cam_path *path, void *arg)
542 {
543 	struct ccb_getdev cgd;
544 	struct cam_periph *periph;
545 	struct sdda_softc *softc;
546 
547 	periph = (struct cam_periph *)callback_arg;
548         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("sddaasync(code=%d)\n", code));
549 	switch (code) {
550 	case AC_FOUND_DEVICE:
551 	{
552                 CAM_DEBUG(path, CAM_DEBUG_TRACE, ("=> AC_FOUND_DEVICE\n"));
553 		struct ccb_getdev *cgd;
554 		cam_status status;
555 
556 		cgd = (struct ccb_getdev *)arg;
557 		if (cgd == NULL)
558 			break;
559 
560 		if (cgd->protocol != PROTO_MMCSD)
561 			break;
562 
563                 if (!(path->device->mmc_ident_data.card_features & CARD_FEATURE_MEMORY)) {
564                         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("No memory on the card!\n"));
565                         break;
566                 }
567 
568 		/*
569 		 * Allocate a peripheral instance for
570 		 * this device and start the probe
571 		 * process.
572 		 */
573 		status = cam_periph_alloc(sddaregister, sddaoninvalidate,
574 					  sddacleanup, sddastart,
575 					  "sdda", CAM_PERIPH_BIO,
576 					  path, sddaasync,
577 					  AC_FOUND_DEVICE, cgd);
578 
579 		if (status != CAM_REQ_CMP
580 		 && status != CAM_REQ_INPROG)
581 			printf("sddaasync: Unable to attach to new device "
582 				"due to status 0x%x\n", status);
583 		break;
584 	}
585 	case AC_GETDEV_CHANGED:
586 	{
587 		CAM_DEBUG(path, CAM_DEBUG_TRACE, ("=> AC_GETDEV_CHANGED\n"));
588 		softc = (struct sdda_softc *)periph->softc;
589 		xpt_setup_ccb(&cgd.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
590 		cgd.ccb_h.func_code = XPT_GDEV_TYPE;
591 		xpt_action((union ccb *)&cgd);
592 		cam_periph_async(periph, code, path, arg);
593 		break;
594 	}
595 	case AC_ADVINFO_CHANGED:
596 	{
597 		uintptr_t buftype;
598 		CAM_DEBUG(path, CAM_DEBUG_TRACE, ("=> AC_ADVINFO_CHANGED\n"));
599 		buftype = (uintptr_t)arg;
600 		if (buftype == CDAI_TYPE_PHYS_PATH) {
601 			struct sdda_softc *softc;
602 
603 			softc = periph->softc;
604 			disk_attr_changed(softc->disk, "GEOM::physpath",
605 					  M_NOWAIT);
606 		}
607 		break;
608 	}
609 	case AC_SENT_BDR:
610 	case AC_BUS_RESET:
611 	{
612 		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("AC_BUS_RESET"));
613 	}
614 	default:
615 		CAM_DEBUG(path, CAM_DEBUG_TRACE, ("=> default?!\n"));
616 		cam_periph_async(periph, code, path, arg);
617 		break;
618 	}
619 }
620 
621 
622 static int
623 sddagetattr(struct bio *bp)
624 {
625 	int ret;
626 	struct cam_periph *periph;
627 
628 	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
629 	cam_periph_lock(periph);
630 	ret = xpt_getattr(bp->bio_data, bp->bio_length, bp->bio_attribute,
631 	    periph->path);
632 	cam_periph_unlock(periph);
633 	if (ret == 0)
634 		bp->bio_completed = bp->bio_length;
635 	return ret;
636 }
637 
638 static cam_status
639 sddaregister(struct cam_periph *periph, void *arg)
640 {
641 	struct sdda_softc *softc;
642 //	struct ccb_pathinq cpi;
643 	struct ccb_getdev *cgd;
644 //	char   announce_buf[80], buf1[32];
645 //	caddr_t match;
646 	union ccb *request_ccb;	/* CCB representing the probe request */
647 
648         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sddaregister\n"));
649 	cgd = (struct ccb_getdev *)arg;
650 	if (cgd == NULL) {
651 		printf("sddaregister: no getdev CCB, can't register device\n");
652 		return(CAM_REQ_CMP_ERR);
653 	}
654 
655 	softc = (struct sdda_softc *)malloc(sizeof(*softc), M_DEVBUF,
656 	    M_NOWAIT|M_ZERO);
657 
658 	if (softc == NULL) {
659 		printf("sddaregister: Unable to probe new device. "
660 		    "Unable to allocate softc\n");
661 		return(CAM_REQ_CMP_ERR);
662 	}
663 
664 	bioq_init(&softc->bio_queue);
665 	softc->state = SDDA_STATE_INIT;
666 	softc->mmcdata =
667 		(struct mmc_data *) malloc(sizeof(struct mmc_data), M_DEVBUF, M_NOWAIT|M_ZERO);
668 	periph->softc = softc;
669 
670 	request_ccb = (union ccb*) arg;
671 	xpt_schedule(periph, CAM_PRIORITY_XPT);
672 	TASK_INIT(&softc->start_init_task, 0, sdda_start_init_task, periph);
673 	taskqueue_enqueue(taskqueue_thread, &softc->start_init_task);
674 
675 	return (CAM_REQ_CMP);
676 }
677 
678 static cam_status
679 sdda_hook_into_geom(struct cam_periph *periph)
680 {
681 	struct sdda_softc *softc;
682 	struct ccb_pathinq cpi;
683 	struct ccb_getdev cgd;
684 	u_int maxio;
685 
686 	softc = (struct sdda_softc*) periph->softc;
687 
688 	bzero(&cpi, sizeof(cpi));
689 	xpt_setup_ccb(&cpi.ccb_h, periph->path, CAM_PRIORITY_NONE);
690 	cpi.ccb_h.func_code = XPT_PATH_INQ;
691 	xpt_action((union ccb *)&cpi);
692 
693 	bzero(&cgd, sizeof(cgd));
694 	xpt_setup_ccb(&cgd.ccb_h, periph->path, CAM_PRIORITY_NONE);
695 	cpi.ccb_h.func_code = XPT_GDEV_TYPE;
696 	xpt_action((union ccb *)&cgd);
697 
698 	/*
699 	 * Register this media as a disk
700 	 */
701 	(void)cam_periph_hold(periph, PRIBIO);
702 	cam_periph_unlock(periph);
703 
704 	softc->disk = disk_alloc();
705 	softc->disk->d_rotation_rate = 0;
706 	softc->disk->d_devstat = devstat_new_entry(periph->periph_name,
707 			  periph->unit_number, 512,
708 			  DEVSTAT_ALL_SUPPORTED,
709 			  DEVSTAT_TYPE_DIRECT |
710 			  XPORT_DEVSTAT_TYPE(cpi.transport),
711 			  DEVSTAT_PRIORITY_DISK);
712 	softc->disk->d_open = sddaopen;
713 	softc->disk->d_close = sddaclose;
714 	softc->disk->d_strategy = sddastrategy;
715 	softc->disk->d_getattr = sddagetattr;
716 //	softc->disk->d_dump = sddadump;
717 	softc->disk->d_gone = sddadiskgonecb;
718 	softc->disk->d_name = "sdda";
719 	softc->disk->d_drv1 = periph;
720 	maxio = cpi.maxio;		/* Honor max I/O size of SIM */
721 	if (maxio == 0)
722 		maxio = DFLTPHYS;	/* traditional default */
723 	else if (maxio > MAXPHYS)
724 		maxio = MAXPHYS;	/* for safety */
725 	softc->disk->d_maxsize = maxio;
726 	softc->disk->d_unit = periph->unit_number;
727 	softc->disk->d_flags = DISKFLAG_CANDELETE;
728 	strlcpy(softc->disk->d_descr, softc->card_id_string,
729 	    MIN(sizeof(softc->disk->d_descr), sizeof(softc->card_id_string)));
730 	strlcpy(softc->disk->d_ident, softc->card_sn_string,
731 	    MIN(sizeof(softc->disk->d_ident), sizeof(softc->card_sn_string)));
732 	softc->disk->d_hba_vendor = cpi.hba_vendor;
733 	softc->disk->d_hba_device = cpi.hba_device;
734 	softc->disk->d_hba_subvendor = cpi.hba_subvendor;
735 	softc->disk->d_hba_subdevice = cpi.hba_subdevice;
736 
737 	softc->disk->d_sectorsize = 512;
738 	softc->disk->d_mediasize = softc->mediasize;
739 	softc->disk->d_stripesize = 0;
740 	softc->disk->d_fwsectors = 0;
741 	softc->disk->d_fwheads = 0;
742 
743 	/*
744 	 * Acquire a reference to the periph before we register with GEOM.
745 	 * We'll release this reference once GEOM calls us back (via
746 	 * sddadiskgonecb()) telling us that our provider has been freed.
747 	 */
748 	if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
749 		xpt_print(periph->path, "%s: lost periph during "
750 			  "registration!\n", __func__);
751 		cam_periph_lock(periph);
752 		return (CAM_REQ_CMP_ERR);
753 	}
754 	disk_create(softc->disk, DISK_VERSION);
755 	cam_periph_lock(periph);
756 	cam_periph_unhold(periph);
757 
758 	xpt_announce_periph(periph, softc->card_id_string);
759 
760 	/*
761 	 * Add async callbacks for bus reset and
762 	 * bus device reset calls.  I don't bother
763 	 * checking if this fails as, in most cases,
764 	 * the system will function just fine without
765 	 * them and the only alternative would be to
766 	 * not attach the device on failure.
767 	 */
768 	xpt_register_async(AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE |
769 	    AC_GETDEV_CHANGED | AC_ADVINFO_CHANGED,
770 	    sddaasync, periph, periph->path);
771 
772 	return(CAM_REQ_CMP);
773 }
774 
775 static int
776 mmc_exec_app_cmd(struct cam_periph *periph, union ccb *ccb,
777 	struct mmc_command *cmd) {
778 	int err;
779 
780 	/* Send APP_CMD first */
781 	memset(&ccb->mmcio.cmd, 0, sizeof(struct mmc_command));
782 	memset(&ccb->mmcio.stop, 0, sizeof(struct mmc_command));
783 	cam_fill_mmcio(&ccb->mmcio,
784 		       /*retries*/ 0,
785 		       /*cbfcnp*/ NULL,
786 		       /*flags*/ CAM_DIR_NONE,
787 		       /*mmc_opcode*/ MMC_APP_CMD,
788 		       /*mmc_arg*/ get_rca(periph) << 16,
789 		       /*mmc_flags*/ MMC_RSP_R1 | MMC_CMD_AC,
790 		       /*mmc_data*/ NULL,
791 		       /*timeout*/ 0);
792 
793 	err = cam_periph_runccb(ccb, sddaerror, CAM_FLAG_NONE, /*sense_flags*/0, NULL);
794 	if (err != 0)
795 		return err;
796 	if (!(ccb->mmcio.cmd.resp[0] & R1_APP_CMD))
797 		return MMC_ERR_FAILED;
798 
799 	/* Now exec actual command */
800 	int flags = 0;
801 	if (cmd->data != NULL) {
802 		ccb->mmcio.cmd.data = cmd->data;
803 		if (cmd->data->flags & MMC_DATA_READ)
804 			flags |= CAM_DIR_IN;
805 		if (cmd->data->flags & MMC_DATA_WRITE)
806 			flags |= CAM_DIR_OUT;
807 	} else flags = CAM_DIR_NONE;
808 
809 	cam_fill_mmcio(&ccb->mmcio,
810 		       /*retries*/ 0,
811 		       /*cbfcnp*/ NULL,
812 		       /*flags*/ flags,
813 		       /*mmc_opcode*/ cmd->opcode,
814 		       /*mmc_arg*/ cmd->arg,
815 		       /*mmc_flags*/ cmd->flags,
816 		       /*mmc_data*/ cmd->data,
817 		       /*timeout*/ 0);
818 
819 	err = cam_periph_runccb(ccb, sddaerror, CAM_FLAG_NONE, /*sense_flags*/0, NULL);
820 	memcpy(cmd->resp, ccb->mmcio.cmd.resp, sizeof(cmd->resp));
821 	cmd->error = ccb->mmcio.cmd.error;
822 	if (err != 0)
823 		return err;
824 	return 0;
825 }
826 
827 static int
828 mmc_app_get_scr(struct cam_periph *periph, union ccb *ccb, uint32_t *rawscr) {
829 	int err;
830 	struct mmc_command cmd;
831 	struct mmc_data d;
832 
833 	memset(&cmd, 0, sizeof(cmd));
834 
835 	memset(rawscr, 0, 8);
836 	cmd.opcode = ACMD_SEND_SCR;
837 	cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
838 	cmd.arg = 0;
839 
840 	d.data = rawscr;
841 	d.len = 8;
842 	d.flags = MMC_DATA_READ;
843 	cmd.data = &d;
844 
845 	err = mmc_exec_app_cmd(periph, ccb, &cmd);
846 	rawscr[0] = be32toh(rawscr[0]);
847 	rawscr[1] = be32toh(rawscr[1]);
848 	return (err);
849 }
850 
851 static int
852 mmc_send_ext_csd(struct cam_periph *periph, union ccb *ccb,
853 		 uint8_t *rawextcsd, size_t buf_len) {
854 	int err;
855 	struct mmc_data d;
856 
857 	KASSERT(buf_len == 512, ("Buffer for ext csd must be 512 bytes"));
858 	d.data = rawextcsd;
859 	d.len = buf_len;
860 	d.flags = MMC_DATA_READ;
861 	memset(d.data, 0, d.len);
862 
863 	cam_fill_mmcio(&ccb->mmcio,
864 		       /*retries*/ 0,
865 		       /*cbfcnp*/ NULL,
866 		       /*flags*/ CAM_DIR_IN,
867 		       /*mmc_opcode*/ MMC_SEND_EXT_CSD,
868 		       /*mmc_arg*/ 0,
869 		       /*mmc_flags*/ MMC_RSP_R1 | MMC_CMD_ADTC,
870 		       /*mmc_data*/ &d,
871 		       /*timeout*/ 0);
872 
873 	err = cam_periph_runccb(ccb, sddaerror, CAM_FLAG_NONE, /*sense_flags*/0, NULL);
874 	if (err != 0)
875 		return err;
876 	if (!(ccb->mmcio.cmd.resp[0] & R1_APP_CMD))
877 		return MMC_ERR_FAILED;
878 
879 	return MMC_ERR_NONE;
880 }
881 
882 static void
883 mmc_app_decode_scr(uint32_t *raw_scr, struct mmc_scr *scr)
884 {
885 	unsigned int scr_struct;
886 
887 	memset(scr, 0, sizeof(*scr));
888 
889 	scr_struct = mmc_get_bits(raw_scr, 64, 60, 4);
890 	if (scr_struct != 0) {
891 		printf("Unrecognised SCR structure version %d\n",
892 		    scr_struct);
893 		return;
894 	}
895 	scr->sda_vsn = mmc_get_bits(raw_scr, 64, 56, 4);
896 	scr->bus_widths = mmc_get_bits(raw_scr, 64, 48, 4);
897 }
898 
899 static int
900 mmc_switch(struct cam_periph *periph, union ccb *ccb,
901 	   uint8_t set, uint8_t index, uint8_t value)
902 {
903 	int arg = (MMC_SWITCH_FUNC_WR << 24) |
904 	    (index << 16) |
905 	    (value << 8) |
906 	    set;
907 	cam_fill_mmcio(&ccb->mmcio,
908 		       /*retries*/ 0,
909 		       /*cbfcnp*/ NULL,
910 		       /*flags*/ CAM_DIR_NONE,
911 		       /*mmc_opcode*/ MMC_SWITCH_FUNC,
912 		       /*mmc_arg*/ arg,
913 		       /*mmc_flags*/ MMC_RSP_R1B | MMC_CMD_AC,
914 		       /*mmc_data*/ NULL,
915 		       /*timeout*/ 0);
916 
917 	cam_periph_runccb(ccb, sddaerror, CAM_FLAG_NONE, /*sense_flags*/0, NULL);
918 
919 	if (((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)) {
920 		if (ccb->mmcio.cmd.error != 0) {
921 			CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_PERIPH,
922 				  ("%s: MMC command failed", __func__));
923 			return EIO;
924 		}
925 		return 0; /* Normal return */
926 	} else {
927 		CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_PERIPH,
928 			  ("%s: CAM request failed\n", __func__));
929 		return EIO;
930 	}
931 
932 }
933 
934 static int
935 mmc_sd_switch(struct cam_periph *periph, union ccb *ccb,
936 	      uint8_t mode, uint8_t grp, uint8_t value,
937 	      uint8_t *res) {
938 
939 	struct mmc_data mmc_d;
940 
941 	memset(res, 0, 64);
942 	mmc_d.len = 64;
943 	mmc_d.data = res;
944 	mmc_d.flags = MMC_DATA_READ;
945 
946 	cam_fill_mmcio(&ccb->mmcio,
947 		       /*retries*/ 0,
948 		       /*cbfcnp*/ NULL,
949 		       /*flags*/ CAM_DIR_IN,
950 		       /*mmc_opcode*/ SD_SWITCH_FUNC,
951 		       /*mmc_arg*/ mode << 31,
952 		       /*mmc_flags*/ MMC_RSP_R1 | MMC_CMD_ADTC,
953 		       /*mmc_data*/ &mmc_d,
954 		       /*timeout*/ 0);
955 
956 	cam_periph_runccb(ccb, sddaerror, CAM_FLAG_NONE, /*sense_flags*/0, NULL);
957 
958 	if (((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)) {
959 		if (ccb->mmcio.cmd.error != 0) {
960 			CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_PERIPH,
961 				  ("%s: MMC command failed", __func__));
962 			return EIO;
963 		}
964 		return 0; /* Normal return */
965 	} else {
966 		CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_PERIPH,
967 			  ("%s: CAM request failed\n", __func__));
968 		return EIO;
969 	}
970 }
971 
972 static int
973 mmc_set_timing(struct cam_periph *periph,
974 	       union ccb *ccb,
975 	       enum mmc_bus_timing timing)
976 {
977 	u_char switch_res[64];
978 	int err;
979 	uint8_t	value;
980 	struct mmc_params *mmcp = &periph->path->device->mmc_ident_data;
981 
982 	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE,
983 		  ("mmc_set_timing(timing=%d)", timing));
984 	switch (timing) {
985 	case bus_timing_normal:
986 		value = 0;
987 		break;
988 	case bus_timing_hs:
989 		value = 1;
990 		break;
991 	default:
992 		return (MMC_ERR_INVALID);
993 	}
994 	if (mmcp->card_features & CARD_FEATURE_MMC) {
995 		err = mmc_switch(periph, ccb, EXT_CSD_CMD_SET_NORMAL,
996 				 EXT_CSD_HS_TIMING, value);
997 	} else {
998 		err = mmc_sd_switch(periph, ccb, SD_SWITCH_MODE_SET, SD_SWITCH_GROUP1, value, switch_res);
999 	}
1000 
1001 	/* Set high-speed timing on the host */
1002 	struct ccb_trans_settings_mmc *cts;
1003 	cts = &ccb->cts.proto_specific.mmc;
1004 	ccb->ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
1005 	ccb->ccb_h.flags = CAM_DIR_NONE;
1006 	ccb->ccb_h.retry_count = 0;
1007 	ccb->ccb_h.timeout = 100;
1008 	ccb->ccb_h.cbfcnp = NULL;
1009 	cts->ios.timing = timing;
1010 	cts->ios_valid = MMC_BT;
1011 	xpt_action(ccb);
1012 
1013 	return (err);
1014 }
1015 
1016 static void
1017 sdda_start_init_task(void *context, int pending) {
1018 	union ccb *new_ccb;
1019 	struct cam_periph *periph;
1020 
1021 	periph = (struct cam_periph *)context;
1022 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sdda_start_init_task\n"));
1023 	new_ccb = xpt_alloc_ccb();
1024 	xpt_setup_ccb(&new_ccb->ccb_h, periph->path,
1025 		      CAM_PRIORITY_NONE);
1026 
1027 	cam_periph_lock(periph);
1028 	sdda_start_init(context, new_ccb);
1029 	cam_periph_unlock(periph);
1030 	xpt_free_ccb(new_ccb);
1031 }
1032 
1033 static void
1034 sdda_set_bus_width(struct cam_periph *periph, union ccb *ccb, int width) {
1035 	struct mmc_params *mmcp = &periph->path->device->mmc_ident_data;
1036 	int err;
1037 
1038 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sdda_set_bus_width\n"));
1039 
1040 	/* First set for the card, then for the host */
1041 	if (mmcp->card_features & CARD_FEATURE_MMC) {
1042 		uint8_t	value;
1043 		switch (width) {
1044 		case bus_width_1:
1045 			value = EXT_CSD_BUS_WIDTH_1;
1046 			break;
1047 		case bus_width_4:
1048 			value = EXT_CSD_BUS_WIDTH_4;
1049 			break;
1050 		case bus_width_8:
1051 			value = EXT_CSD_BUS_WIDTH_8;
1052 			break;
1053 		default:
1054 			panic("Invalid bus width %d", width);
1055 		}
1056 		err = mmc_switch(periph, ccb, EXT_CSD_CMD_SET_NORMAL,
1057 				 EXT_CSD_BUS_WIDTH, value);
1058 	} else {
1059 		/* For SD cards we send ACMD6 with the required bus width in arg */
1060 		struct mmc_command cmd;
1061 		memset(&cmd, 0, sizeof(struct mmc_command));
1062 		cmd.opcode = ACMD_SET_BUS_WIDTH;
1063 		cmd.arg = width;
1064 		cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
1065 		err = mmc_exec_app_cmd(periph, ccb, &cmd);
1066 	}
1067 
1068 	if (err != MMC_ERR_NONE) {
1069 		CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH, ("Error %d when setting bus width on the card\n", err));
1070 		return;
1071 	}
1072 	/* Now card is done, set the host to the same width */
1073 	struct ccb_trans_settings_mmc *cts;
1074 	cts = &ccb->cts.proto_specific.mmc;
1075 	ccb->ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
1076 	ccb->ccb_h.flags = CAM_DIR_NONE;
1077 	ccb->ccb_h.retry_count = 0;
1078 	ccb->ccb_h.timeout = 100;
1079 	ccb->ccb_h.cbfcnp = NULL;
1080 	cts->ios.bus_width = width;
1081 	cts->ios_valid = MMC_BW;
1082 	xpt_action(ccb);
1083 }
1084 
1085 static inline const char *bus_width_str(enum mmc_bus_width w) {
1086 	switch (w) {
1087 	case bus_width_1:
1088 		return "1-bit";
1089 	case bus_width_4:
1090 		return "4-bit";
1091 	case bus_width_8:
1092 		return "8-bit";
1093 	}
1094 }
1095 
1096 static void
1097 sdda_start_init(void *context, union ccb *start_ccb) {
1098 	struct cam_periph *periph;
1099 	periph = (struct cam_periph *)context;
1100 	int err;
1101 
1102 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sdda_start_init\n"));
1103 	/* periph was held for us when this task was enqueued */
1104 	if ((periph->flags & CAM_PERIPH_INVALID) != 0) {
1105 		cam_periph_release(periph);
1106 		return;
1107 	}
1108 
1109 	struct sdda_softc *softc = (struct sdda_softc *)periph->softc;
1110 	//struct ccb_mmcio *mmcio = &start_ccb->mmcio;
1111 	struct mmc_params *mmcp = &periph->path->device->mmc_ident_data;
1112 	struct cam_ed *device = periph->path->device;
1113 
1114 	if (mmcp->card_features & CARD_FEATURE_MMC) {
1115 		mmc_decode_csd_mmc(mmcp->card_csd, &softc->csd);
1116 		mmc_decode_cid_mmc(mmcp->card_cid, &softc->cid);
1117 		if (softc->csd.spec_vers >= 4)
1118 			err = mmc_send_ext_csd(periph, start_ccb,
1119 					       (uint8_t *)&softc->raw_ext_csd,
1120 					       sizeof(softc->raw_ext_csd));
1121 	} else {
1122 		mmc_decode_csd_sd(mmcp->card_csd, &softc->csd);
1123 		mmc_decode_cid_sd(mmcp->card_cid, &softc->cid);
1124 	}
1125 
1126 	softc->sector_count = softc->csd.capacity / 512;
1127 	softc->mediasize = softc->csd.capacity;
1128 
1129 	/* MMC >= 4.x have EXT_CSD that has its own opinion about capacity */
1130 	if (softc->csd.spec_vers >= 4) {
1131 		uint32_t sec_count = softc->raw_ext_csd[EXT_CSD_SEC_CNT] +
1132 			(softc->raw_ext_csd[EXT_CSD_SEC_CNT + 1] << 8) +
1133 			(softc->raw_ext_csd[EXT_CSD_SEC_CNT + 2] << 16) +
1134 			(softc->raw_ext_csd[EXT_CSD_SEC_CNT + 3] << 24);
1135 		if (sec_count != 0) {
1136 			softc->sector_count = sec_count;
1137 			softc->mediasize = softc->sector_count * 512;
1138 			/* FIXME: there should be a better name for this option...*/
1139 			mmcp->card_features |= CARD_FEATURE_SDHC;
1140 		}
1141 
1142 	}
1143 	CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH,
1144 		  ("Capacity: %"PRIu64", sectors: %"PRIu64"\n",
1145 		   softc->mediasize,
1146 		   softc->sector_count));
1147 	mmc_format_card_id_string(softc, mmcp);
1148 
1149 	/* Update info for CAM */
1150 	device->serial_num_len = strlen(softc->card_sn_string);
1151 	device->serial_num =
1152 		(u_int8_t *)malloc((device->serial_num_len + 1),
1153 				   M_CAMXPT, M_NOWAIT);
1154 	strlcpy(device->serial_num, softc->card_sn_string, device->serial_num_len);
1155 
1156 	device->device_id_len = strlen(softc->card_id_string);
1157 	device->device_id =
1158 		(u_int8_t *)malloc((device->device_id_len + 1),
1159 				   M_CAMXPT, M_NOWAIT);
1160 	strlcpy(device->device_id, softc->card_id_string, device->device_id_len);
1161 
1162 	strlcpy(mmcp->model, softc->card_id_string, sizeof(mmcp->model));
1163 
1164 	/* Set the clock frequency that the card can handle */
1165 	struct ccb_trans_settings_mmc *cts;
1166 	cts = &start_ccb->cts.proto_specific.mmc;
1167 
1168 	/* First, get the host's max freq */
1169 	start_ccb->ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
1170 	start_ccb->ccb_h.flags = CAM_DIR_NONE;
1171 	start_ccb->ccb_h.retry_count = 0;
1172 	start_ccb->ccb_h.timeout = 100;
1173 	start_ccb->ccb_h.cbfcnp = NULL;
1174 	xpt_action(start_ccb);
1175 
1176 	if (start_ccb->ccb_h.status != CAM_REQ_CMP)
1177 		panic("Cannot get max host freq");
1178 	int host_f_max = cts->host_f_max;
1179 	uint32_t host_caps = cts->host_caps;
1180 	if (cts->ios.bus_width != bus_width_1)
1181 		panic("Bus width in ios is not 1-bit");
1182 
1183 	/* Now check if the card supports High-speed */
1184 	softc->card_f_max = softc->csd.tran_speed;
1185 
1186 	if (host_caps & MMC_CAP_HSPEED) {
1187 		/* Find out if the card supports High speed timing */
1188 		if (mmcp->card_features & CARD_FEATURE_SD20) {
1189 			/* Get and decode SCR */
1190 			uint32_t rawscr;
1191 			uint8_t res[64];
1192 			if (mmc_app_get_scr(periph, start_ccb, &rawscr)) {
1193 				CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH, ("Cannot get SCR\n"));
1194 				goto finish_hs_tests;
1195 			}
1196 			mmc_app_decode_scr(&rawscr, &softc->scr);
1197 
1198 			if ((softc->scr.sda_vsn >= 1) && (softc->csd.ccc & (1<<10))) {
1199 				mmc_sd_switch(periph, start_ccb, SD_SWITCH_MODE_CHECK,
1200 					      SD_SWITCH_GROUP1, SD_SWITCH_NOCHANGE, res);
1201 				if (res[13] & 2) {
1202 					CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH, ("Card supports HS\n"));
1203 					softc->card_f_max = SD_HS_MAX;
1204 				}
1205 			} else {
1206 				CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH, ("Not trying the switch\n"));
1207 				goto finish_hs_tests;
1208 			}
1209 		}
1210 
1211 		if (mmcp->card_features & CARD_FEATURE_MMC && softc->csd.spec_vers >= 4) {
1212 			if (softc->raw_ext_csd[EXT_CSD_CARD_TYPE]
1213 			    & EXT_CSD_CARD_TYPE_HS_52)
1214 				softc->card_f_max = MMC_TYPE_HS_52_MAX;
1215 			else if (softc->raw_ext_csd[EXT_CSD_CARD_TYPE]
1216 				 & EXT_CSD_CARD_TYPE_HS_26)
1217 				softc->card_f_max = MMC_TYPE_HS_26_MAX;
1218 		}
1219 	}
1220 	int f_max;
1221 finish_hs_tests:
1222 	f_max = min(host_f_max, softc->card_f_max);
1223 	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));
1224 
1225 	start_ccb->ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
1226 	start_ccb->ccb_h.flags = CAM_DIR_NONE;
1227 	start_ccb->ccb_h.retry_count = 0;
1228 	start_ccb->ccb_h.timeout = 100;
1229 	start_ccb->ccb_h.cbfcnp = NULL;
1230 	cts->ios.clock = f_max;
1231 	cts->ios_valid = MMC_CLK;
1232 	xpt_action(start_ccb);
1233 
1234 	/* Set bus width */
1235 	enum mmc_bus_width desired_bus_width = bus_width_1;
1236 	enum mmc_bus_width max_host_bus_width =
1237 		(host_caps & MMC_CAP_8_BIT_DATA ? bus_width_8 :
1238 		 host_caps & MMC_CAP_4_BIT_DATA ? bus_width_4 : bus_width_1);
1239 	enum mmc_bus_width max_card_bus_width = bus_width_1;
1240 	if (mmcp->card_features & CARD_FEATURE_SD20 &&
1241 	    softc->scr.bus_widths & SD_SCR_BUS_WIDTH_4)
1242 		max_card_bus_width = bus_width_4;
1243 	/*
1244 	 * Unlike SD, MMC cards don't have any information about supported bus width...
1245 	 * So we need to perform read/write test to find out the width.
1246 	 */
1247 	/* TODO: figure out bus width for MMC; use 8-bit for now (to test on BBB) */
1248 	if (mmcp->card_features & CARD_FEATURE_MMC)
1249 		max_card_bus_width = bus_width_8;
1250 
1251 	desired_bus_width = min(max_host_bus_width, max_card_bus_width);
1252 	CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH,
1253 		  ("Set bus width to %s (min of host %s and card %s)\n",
1254 		   bus_width_str(desired_bus_width),
1255 		   bus_width_str(max_host_bus_width),
1256 		   bus_width_str(max_card_bus_width)));
1257 	sdda_set_bus_width(periph, start_ccb, desired_bus_width);
1258 
1259 	if (f_max > 25000000) {
1260 		err = mmc_set_timing(periph, start_ccb, bus_timing_hs);
1261 		if (err != MMC_ERR_NONE)
1262 			CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("Cannot switch card to high-speed mode"));
1263 	}
1264 	softc->state = SDDA_STATE_NORMAL;
1265 	sdda_hook_into_geom(periph);
1266 }
1267 
1268 /* Called with periph lock held! */
1269 static void
1270 sddastart(struct cam_periph *periph, union ccb *start_ccb)
1271 {
1272 	struct sdda_softc *softc = (struct sdda_softc *)periph->softc;
1273 	struct mmc_params *mmcp = &periph->path->device->mmc_ident_data;
1274 
1275 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sddastart\n"));
1276 
1277 	if (softc->state != SDDA_STATE_NORMAL) {
1278 		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("device is not in SDDA_STATE_NORMAL yet"));
1279 		xpt_release_ccb(start_ccb);
1280 		return;
1281 	}
1282 	struct bio *bp;
1283 
1284 	/* Run regular command. */
1285 	bp = bioq_first(&softc->bio_queue);
1286 	if (bp == NULL) {
1287 		xpt_release_ccb(start_ccb);
1288 		return;
1289 	}
1290 	bioq_remove(&softc->bio_queue, bp);
1291 
1292 	switch (bp->bio_cmd) {
1293 	case BIO_WRITE:
1294 		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("BIO_WRITE\n"));
1295 		softc->flags |= SDDA_FLAG_DIRTY;
1296 		/* FALLTHROUGH */
1297 	case BIO_READ:
1298 	{
1299 		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("BIO_READ\n"));
1300 		uint64_t blockno = bp->bio_pblkno;
1301 		uint16_t count = bp->bio_bcount / 512;
1302 		uint16_t opcode;
1303 
1304 		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("Block %"PRIu64" cnt %u\n", blockno, count));
1305 
1306 		/* Construct new MMC command */
1307 		if (bp->bio_cmd == BIO_READ) {
1308 			if (count > 1)
1309 				opcode = MMC_READ_MULTIPLE_BLOCK;
1310 			else
1311 				opcode = MMC_READ_SINGLE_BLOCK;
1312 		} else {
1313 			if (count > 1)
1314 				opcode = MMC_WRITE_MULTIPLE_BLOCK;
1315 			else
1316 				opcode = MMC_WRITE_BLOCK;
1317 		}
1318 
1319 		start_ccb->ccb_h.func_code = XPT_MMC_IO;
1320 		start_ccb->ccb_h.flags = (bp->bio_cmd == BIO_READ ? CAM_DIR_IN : CAM_DIR_OUT);
1321 		start_ccb->ccb_h.retry_count = 0;
1322 		start_ccb->ccb_h.timeout = 15 * 1000;
1323 		start_ccb->ccb_h.cbfcnp = sddadone;
1324 		struct ccb_mmcio *mmcio;
1325 
1326 		mmcio = &start_ccb->mmcio;
1327 		mmcio->cmd.opcode = opcode;
1328 		mmcio->cmd.arg = blockno;
1329 		if (!(mmcp->card_features & CARD_FEATURE_SDHC))
1330 			mmcio->cmd.arg <<= 9;
1331 
1332 		mmcio->cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
1333 		mmcio->cmd.data = softc->mmcdata;
1334 		mmcio->cmd.data->data = bp->bio_data;
1335 		mmcio->cmd.data->len = 512 * count;
1336 		mmcio->cmd.data->flags = (bp->bio_cmd == BIO_READ ? MMC_DATA_READ : MMC_DATA_WRITE);
1337 		/* Direct h/w to issue CMD12 upon completion */
1338 		if (count > 1) {
1339 			mmcio->stop.opcode = MMC_STOP_TRANSMISSION;
1340 			mmcio->stop.flags = MMC_RSP_R1B | MMC_CMD_AC;
1341 			mmcio->stop.arg = 0;
1342 		}
1343 
1344 		break;
1345 	}
1346 	case BIO_FLUSH:
1347 		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("BIO_FLUSH\n"));
1348 		sddaschedule(periph);
1349 		break;
1350 	case BIO_DELETE:
1351 		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("BIO_DELETE\n"));
1352 		sddaschedule(periph);
1353 		break;
1354 	}
1355 	start_ccb->ccb_h.ccb_bp = bp;
1356 	softc->outstanding_cmds++;
1357 	softc->refcount++;
1358 	cam_periph_unlock(periph);
1359 	xpt_action(start_ccb);
1360 	cam_periph_lock(periph);
1361 	softc->refcount--;
1362 
1363 	/* May have more work to do, so ensure we stay scheduled */
1364 	sddaschedule(periph);
1365 }
1366 
1367 static void
1368 sddadone(struct cam_periph *periph, union ccb *done_ccb)
1369 {
1370 	struct sdda_softc *softc;
1371 	struct ccb_mmcio *mmcio;
1372 //	struct ccb_getdev *cgd;
1373 	struct cam_path *path;
1374 //	int state;
1375 
1376 	softc = (struct sdda_softc *)periph->softc;
1377 	mmcio = &done_ccb->mmcio;
1378 	path = done_ccb->ccb_h.path;
1379 
1380 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("sddadone\n"));
1381 
1382 	struct bio *bp;
1383 	int error = 0;
1384 
1385 //        cam_periph_lock(periph);
1386 	if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1387 		CAM_DEBUG(path, CAM_DEBUG_TRACE, ("Error!!!\n"));
1388 		if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1389 			cam_release_devq(path,
1390 					 /*relsim_flags*/0,
1391 					 /*reduction*/0,
1392 					 /*timeout*/0,
1393 					 /*getcount_only*/0);
1394 		error = 5; /* EIO */
1395 	} else {
1396 		if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1397 			panic("REQ_CMP with QFRZN");
1398 		error = 0;
1399 	}
1400 
1401 
1402 	bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
1403 	bp->bio_error = error;
1404 	if (error != 0) {
1405 		bp->bio_resid = bp->bio_bcount;
1406 		bp->bio_flags |= BIO_ERROR;
1407 	} else {
1408 		/* XXX: How many bytes remaining? */
1409 		bp->bio_resid = 0;
1410 		if (bp->bio_resid > 0)
1411 			bp->bio_flags |= BIO_ERROR;
1412 	}
1413 
1414 	uint32_t card_status = mmcio->cmd.resp[0];
1415 	CAM_DEBUG(path, CAM_DEBUG_TRACE,
1416 		  ("Card status: %08x\n", R1_STATUS(card_status)));
1417 	CAM_DEBUG(path, CAM_DEBUG_TRACE,
1418 		  ("Current state: %d\n", R1_CURRENT_STATE(card_status)));
1419 
1420 	softc->outstanding_cmds--;
1421 	xpt_release_ccb(done_ccb);
1422 	biodone(bp);
1423 }
1424 
1425 static int
1426 sddaerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
1427 {
1428 	return(cam_periph_error(ccb, cam_flags, sense_flags, NULL));
1429 }
1430 #endif /* _KERNEL */
1431