]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cam/mmc/mmc_da.c
Upgrade our copies of clang, llvm and libc++ to r310316 from the
[FreeBSD/FreeBSD.git] / sys / cam / mmc / mmc_da.c
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 | CAM_DEBUG_PERIPH,
382             ("sddaopen\n"));
383
384         softc = (struct sdda_softc *)periph->softc;
385         softc->flags |= SDDA_FLAG_OPEN;
386
387         cam_periph_unhold(periph);
388         cam_periph_unlock(periph);
389         return (0);
390 }
391
392 static int
393 sddaclose(struct disk *dp)
394 {
395         struct  cam_periph *periph;
396         struct  sdda_softc *softc;
397 //      union ccb *ccb;
398 //      int error;
399
400         periph = (struct cam_periph *)dp->d_drv1;
401         softc = (struct sdda_softc *)periph->softc;
402         softc->flags &= ~SDDA_FLAG_OPEN;
403
404         cam_periph_lock(periph);
405
406         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
407             ("sddaclose\n"));
408
409         while (softc->refcount != 0)
410                 cam_periph_sleep(periph, &softc->refcount, PRIBIO, "sddaclose", 1);
411         cam_periph_unlock(periph);
412         cam_periph_release(periph);
413         return (0);
414 }
415
416 static void
417 sddaschedule(struct cam_periph *periph)
418 {
419         struct sdda_softc *softc = (struct sdda_softc *)periph->softc;
420
421         /* Check if we have more work to do. */
422         if (bioq_first(&softc->bio_queue)) {
423                 xpt_schedule(periph, CAM_PRIORITY_NORMAL);
424         }
425 }
426
427 /*
428  * Actually translate the requested transfer into one the physical driver
429  * can understand.  The transfer is described by a buf and will include
430  * only one physical transfer.
431  */
432 static void
433 sddastrategy(struct bio *bp)
434 {
435         struct cam_periph *periph;
436         struct sdda_softc *softc;
437
438         periph = (struct cam_periph *)bp->bio_disk->d_drv1;
439         softc = (struct sdda_softc *)periph->softc;
440
441         cam_periph_lock(periph);
442
443         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sddastrategy(%p)\n", bp));
444
445         /*
446          * If the device has been made invalid, error out
447          */
448         if ((periph->flags & CAM_PERIPH_INVALID) != 0) {
449                 cam_periph_unlock(periph);
450                 biofinish(bp, NULL, ENXIO);
451                 return;
452         }
453
454         /*
455          * Place it in the queue of disk activities for this disk
456          */
457         bioq_disksort(&softc->bio_queue, bp);
458
459         /*
460          * Schedule ourselves for performing the work.
461          */
462         sddaschedule(periph);
463         cam_periph_unlock(periph);
464
465         return;
466 }
467
468 static void
469 sddainit(void)
470 {
471         cam_status status;
472
473         /*
474          * Install a global async callback.  This callback will
475          * receive async callbacks like "new device found".
476          */
477         status = xpt_register_async(AC_FOUND_DEVICE, sddaasync, NULL, NULL);
478
479         if (status != CAM_REQ_CMP) {
480                 printf("sdda: Failed to attach master async callback "
481                        "due to status 0x%x!\n", status);
482         }
483 }
484
485 /*
486  * Callback from GEOM, called when it has finished cleaning up its
487  * resources.
488  */
489 static void
490 sddadiskgonecb(struct disk *dp)
491 {
492         struct cam_periph *periph;
493
494         periph = (struct cam_periph *)dp->d_drv1;
495         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sddadiskgonecb\n"));
496
497         cam_periph_release(periph);
498 }
499
500 static void
501 sddaoninvalidate(struct cam_periph *periph)
502 {
503         struct sdda_softc *softc;
504
505         softc = (struct sdda_softc *)periph->softc;
506
507         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sddaoninvalidate\n"));
508
509         /*
510          * De-register any async callbacks.
511          */
512         xpt_register_async(0, sddaasync, periph, periph->path);
513
514         /*
515          * Return all queued I/O with ENXIO.
516          * XXX Handle any transactions queued to the card
517          *     with XPT_ABORT_CCB.
518          */
519         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("bioq_flush start\n"));
520         bioq_flush(&softc->bio_queue, NULL, ENXIO);
521         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("bioq_flush end\n"));
522
523         disk_gone(softc->disk);
524 }
525
526 static void
527 sddacleanup(struct cam_periph *periph)
528 {
529         struct sdda_softc *softc;
530
531         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sddacleanup\n"));
532         softc = (struct sdda_softc *)periph->softc;
533
534         cam_periph_unlock(periph);
535
536         disk_destroy(softc->disk);
537         free(softc, M_DEVBUF);
538         cam_periph_lock(periph);
539 }
540
541 static void
542 sddaasync(void *callback_arg, u_int32_t code,
543         struct cam_path *path, void *arg)
544 {
545         struct ccb_getdev cgd;
546         struct cam_periph *periph;
547         struct sdda_softc *softc;
548
549         periph = (struct cam_periph *)callback_arg;
550         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("sddaasync(code=%d)\n", code));
551         switch (code) {
552         case AC_FOUND_DEVICE:
553         {
554                 CAM_DEBUG(path, CAM_DEBUG_TRACE, ("=> AC_FOUND_DEVICE\n"));
555                 struct ccb_getdev *cgd;
556                 cam_status status;
557
558                 cgd = (struct ccb_getdev *)arg;
559                 if (cgd == NULL)
560                         break;
561
562                 if (cgd->protocol != PROTO_MMCSD)
563                         break;
564
565                 if (!(path->device->mmc_ident_data.card_features & CARD_FEATURE_MEMORY)) {
566                         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("No memory on the card!\n"));
567                         break;
568                 }
569
570                 /*
571                  * Allocate a peripheral instance for
572                  * this device and start the probe
573                  * process.
574                  */
575                 status = cam_periph_alloc(sddaregister, sddaoninvalidate,
576                                           sddacleanup, sddastart,
577                                           "sdda", CAM_PERIPH_BIO,
578                                           path, sddaasync,
579                                           AC_FOUND_DEVICE, cgd);
580
581                 if (status != CAM_REQ_CMP
582                  && status != CAM_REQ_INPROG)
583                         printf("sddaasync: Unable to attach to new device "
584                                 "due to status 0x%x\n", status);
585                 break;
586         }
587         case AC_GETDEV_CHANGED:
588         {
589                 CAM_DEBUG(path, CAM_DEBUG_TRACE, ("=> AC_GETDEV_CHANGED\n"));
590                 softc = (struct sdda_softc *)periph->softc;
591                 xpt_setup_ccb(&cgd.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
592                 cgd.ccb_h.func_code = XPT_GDEV_TYPE;
593                 xpt_action((union ccb *)&cgd);
594                 cam_periph_async(periph, code, path, arg);
595                 break;
596         }
597         case AC_ADVINFO_CHANGED:
598         {
599                 uintptr_t buftype;
600                 CAM_DEBUG(path, CAM_DEBUG_TRACE, ("=> AC_ADVINFO_CHANGED\n"));
601                 buftype = (uintptr_t)arg;
602                 if (buftype == CDAI_TYPE_PHYS_PATH) {
603                         struct sdda_softc *softc;
604
605                         softc = periph->softc;
606                         disk_attr_changed(softc->disk, "GEOM::physpath",
607                                           M_NOWAIT);
608                 }
609                 break;
610         }
611         case AC_SENT_BDR:
612         case AC_BUS_RESET:
613         {
614                 CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("AC_BUS_RESET"));
615         }
616         default:
617                 CAM_DEBUG(path, CAM_DEBUG_TRACE, ("=> default?!\n"));
618                 cam_periph_async(periph, code, path, arg);
619                 break;
620         }
621 }
622
623
624 static int
625 sddagetattr(struct bio *bp)
626 {
627         int ret;
628         struct cam_periph *periph;
629
630         periph = (struct cam_periph *)bp->bio_disk->d_drv1;
631         cam_periph_lock(periph);
632         ret = xpt_getattr(bp->bio_data, bp->bio_length, bp->bio_attribute,
633             periph->path);
634         cam_periph_unlock(periph);
635         if (ret == 0)
636                 bp->bio_completed = bp->bio_length;
637         return ret;
638 }
639
640 static cam_status
641 sddaregister(struct cam_periph *periph, void *arg)
642 {
643         struct sdda_softc *softc;
644 //      struct ccb_pathinq cpi;
645         struct ccb_getdev *cgd;
646 //      char   announce_buf[80], buf1[32];
647 //      caddr_t match;
648         union ccb *request_ccb; /* CCB representing the probe request */
649
650         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sddaregister\n"));
651         cgd = (struct ccb_getdev *)arg;
652         if (cgd == NULL) {
653                 printf("sddaregister: no getdev CCB, can't register device\n");
654                 return(CAM_REQ_CMP_ERR);
655         }
656
657         softc = (struct sdda_softc *)malloc(sizeof(*softc), M_DEVBUF,
658             M_NOWAIT|M_ZERO);
659
660         if (softc == NULL) {
661                 printf("sddaregister: Unable to probe new device. "
662                     "Unable to allocate softc\n");
663                 return(CAM_REQ_CMP_ERR);
664         }
665
666         bioq_init(&softc->bio_queue);
667         softc->state = SDDA_STATE_INIT;
668         softc->mmcdata =
669                 (struct mmc_data *) malloc(sizeof(struct mmc_data), M_DEVBUF, M_NOWAIT|M_ZERO);
670         periph->softc = softc;
671
672         request_ccb = (union ccb*) arg;
673         xpt_schedule(periph, CAM_PRIORITY_XPT);
674         TASK_INIT(&softc->start_init_task, 0, sdda_start_init_task, periph);
675         taskqueue_enqueue(taskqueue_thread, &softc->start_init_task);
676
677         return (CAM_REQ_CMP);
678 }
679
680 static cam_status
681 sdda_hook_into_geom(struct cam_periph *periph)
682 {
683         struct sdda_softc *softc;
684         struct ccb_pathinq cpi;
685         struct ccb_getdev cgd;
686         u_int maxio;
687
688         softc = (struct sdda_softc*) periph->softc;
689
690         bzero(&cpi, sizeof(cpi));
691         xpt_setup_ccb(&cpi.ccb_h, periph->path, CAM_PRIORITY_NONE);
692         cpi.ccb_h.func_code = XPT_PATH_INQ;
693         xpt_action((union ccb *)&cpi);
694
695         bzero(&cgd, sizeof(cgd));
696         xpt_setup_ccb(&cgd.ccb_h, periph->path, CAM_PRIORITY_NONE);
697         cpi.ccb_h.func_code = XPT_GDEV_TYPE;
698         xpt_action((union ccb *)&cgd);
699
700         /*
701          * Register this media as a disk
702          */
703         (void)cam_periph_hold(periph, PRIBIO);
704         cam_periph_unlock(periph);
705
706         softc->disk = disk_alloc();
707         softc->disk->d_rotation_rate = 0;
708         softc->disk->d_devstat = devstat_new_entry(periph->periph_name,
709                           periph->unit_number, 512,
710                           DEVSTAT_ALL_SUPPORTED,
711                           DEVSTAT_TYPE_DIRECT |
712                           XPORT_DEVSTAT_TYPE(cpi.transport),
713                           DEVSTAT_PRIORITY_DISK);
714         softc->disk->d_open = sddaopen;
715         softc->disk->d_close = sddaclose;
716         softc->disk->d_strategy = sddastrategy;
717         softc->disk->d_getattr = sddagetattr;
718 //      softc->disk->d_dump = sddadump;
719         softc->disk->d_gone = sddadiskgonecb;
720         softc->disk->d_name = "sdda";
721         softc->disk->d_drv1 = periph;
722         maxio = cpi.maxio;              /* Honor max I/O size of SIM */
723         if (maxio == 0)
724                 maxio = DFLTPHYS;       /* traditional default */
725         else if (maxio > MAXPHYS)
726                 maxio = MAXPHYS;        /* for safety */
727         softc->disk->d_maxsize = maxio;
728         softc->disk->d_unit = periph->unit_number;
729         softc->disk->d_flags = DISKFLAG_CANDELETE;
730         strlcpy(softc->disk->d_descr, softc->card_id_string,
731             MIN(sizeof(softc->disk->d_descr), sizeof(softc->card_id_string)));
732         strlcpy(softc->disk->d_ident, softc->card_sn_string,
733             MIN(sizeof(softc->disk->d_ident), sizeof(softc->card_sn_string)));
734         softc->disk->d_hba_vendor = cpi.hba_vendor;
735         softc->disk->d_hba_device = cpi.hba_device;
736         softc->disk->d_hba_subvendor = cpi.hba_subvendor;
737         softc->disk->d_hba_subdevice = cpi.hba_subdevice;
738
739         softc->disk->d_sectorsize = 512;
740         softc->disk->d_mediasize = softc->mediasize;
741         softc->disk->d_stripesize = 0;
742         softc->disk->d_fwsectors = 0;
743         softc->disk->d_fwheads = 0;
744
745         /*
746          * Acquire a reference to the periph before we register with GEOM.
747          * We'll release this reference once GEOM calls us back (via
748          * sddadiskgonecb()) telling us that our provider has been freed.
749          */
750         if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
751                 xpt_print(periph->path, "%s: lost periph during "
752                           "registration!\n", __func__);
753                 cam_periph_lock(periph);
754                 return (CAM_REQ_CMP_ERR);
755         }
756         disk_create(softc->disk, DISK_VERSION);
757         cam_periph_lock(periph);
758         cam_periph_unhold(periph);
759
760         xpt_announce_periph(periph, softc->card_id_string);
761
762         /*
763          * Add async callbacks for bus reset and
764          * bus device reset calls.  I don't bother
765          * checking if this fails as, in most cases,
766          * the system will function just fine without
767          * them and the only alternative would be to
768          * not attach the device on failure.
769          */
770         xpt_register_async(AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE |
771             AC_GETDEV_CHANGED | AC_ADVINFO_CHANGED,
772             sddaasync, periph, periph->path);
773
774         return(CAM_REQ_CMP);
775 }
776
777 static int
778 mmc_exec_app_cmd(struct cam_periph *periph, union ccb *ccb,
779         struct mmc_command *cmd) {
780         int err;
781
782         /* Send APP_CMD first */
783         memset(&ccb->mmcio.cmd, 0, sizeof(struct mmc_command));
784         memset(&ccb->mmcio.stop, 0, sizeof(struct mmc_command));
785         cam_fill_mmcio(&ccb->mmcio,
786                        /*retries*/ 0,
787                        /*cbfcnp*/ NULL,
788                        /*flags*/ CAM_DIR_NONE,
789                        /*mmc_opcode*/ MMC_APP_CMD,
790                        /*mmc_arg*/ get_rca(periph) << 16,
791                        /*mmc_flags*/ MMC_RSP_R1 | MMC_CMD_AC,
792                        /*mmc_data*/ NULL,
793                        /*timeout*/ 0);
794
795         err = cam_periph_runccb(ccb, sddaerror, CAM_FLAG_NONE, /*sense_flags*/0, NULL);
796         if (err != 0)
797                 return err;
798         if (!(ccb->mmcio.cmd.resp[0] & R1_APP_CMD))
799                 return MMC_ERR_FAILED;
800
801         /* Now exec actual command */
802         int flags = 0;
803         if (cmd->data != NULL) {
804                 ccb->mmcio.cmd.data = cmd->data;
805                 if (cmd->data->flags & MMC_DATA_READ)
806                         flags |= CAM_DIR_IN;
807                 if (cmd->data->flags & MMC_DATA_WRITE)
808                         flags |= CAM_DIR_OUT;
809         } else flags = CAM_DIR_NONE;
810
811         cam_fill_mmcio(&ccb->mmcio,
812                        /*retries*/ 0,
813                        /*cbfcnp*/ NULL,
814                        /*flags*/ flags,
815                        /*mmc_opcode*/ cmd->opcode,
816                        /*mmc_arg*/ cmd->arg,
817                        /*mmc_flags*/ cmd->flags,
818                        /*mmc_data*/ cmd->data,
819                        /*timeout*/ 0);
820
821         err = cam_periph_runccb(ccb, sddaerror, CAM_FLAG_NONE, /*sense_flags*/0, NULL);
822         memcpy(cmd->resp, ccb->mmcio.cmd.resp, sizeof(cmd->resp));
823         cmd->error = ccb->mmcio.cmd.error;
824         if (err != 0)
825                 return err;
826         return 0;
827 }
828
829 static int
830 mmc_app_get_scr(struct cam_periph *periph, union ccb *ccb, uint32_t *rawscr) {
831         int err;
832         struct mmc_command cmd;
833         struct mmc_data d;
834
835         memset(&cmd, 0, sizeof(cmd));
836
837         memset(rawscr, 0, 8);
838         cmd.opcode = ACMD_SEND_SCR;
839         cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
840         cmd.arg = 0;
841
842         d.data = rawscr;
843         d.len = 8;
844         d.flags = MMC_DATA_READ;
845         cmd.data = &d;
846
847         err = mmc_exec_app_cmd(periph, ccb, &cmd);
848         rawscr[0] = be32toh(rawscr[0]);
849         rawscr[1] = be32toh(rawscr[1]);
850         return (err);
851 }
852
853 static int
854 mmc_send_ext_csd(struct cam_periph *periph, union ccb *ccb,
855                  uint8_t *rawextcsd, size_t buf_len) {
856         int err;
857         struct mmc_data d;
858
859         KASSERT(buf_len == 512, ("Buffer for ext csd must be 512 bytes"));
860         d.data = rawextcsd;
861         d.len = buf_len;
862         d.flags = MMC_DATA_READ;
863         memset(d.data, 0, d.len);
864
865         cam_fill_mmcio(&ccb->mmcio,
866                        /*retries*/ 0,
867                        /*cbfcnp*/ NULL,
868                        /*flags*/ CAM_DIR_IN,
869                        /*mmc_opcode*/ MMC_SEND_EXT_CSD,
870                        /*mmc_arg*/ 0,
871                        /*mmc_flags*/ MMC_RSP_R1 | MMC_CMD_ADTC,
872                        /*mmc_data*/ &d,
873                        /*timeout*/ 0);
874
875         err = cam_periph_runccb(ccb, sddaerror, CAM_FLAG_NONE, /*sense_flags*/0, NULL);
876         if (err != 0)
877                 return err;
878         if (!(ccb->mmcio.cmd.resp[0] & R1_APP_CMD))
879                 return MMC_ERR_FAILED;
880
881         return MMC_ERR_NONE;
882 }
883
884 static void
885 mmc_app_decode_scr(uint32_t *raw_scr, struct mmc_scr *scr)
886 {
887         unsigned int scr_struct;
888
889         memset(scr, 0, sizeof(*scr));
890
891         scr_struct = mmc_get_bits(raw_scr, 64, 60, 4);
892         if (scr_struct != 0) {
893                 printf("Unrecognised SCR structure version %d\n",
894                     scr_struct);
895                 return;
896         }
897         scr->sda_vsn = mmc_get_bits(raw_scr, 64, 56, 4);
898         scr->bus_widths = mmc_get_bits(raw_scr, 64, 48, 4);
899 }
900
901 static int
902 mmc_switch(struct cam_periph *periph, union ccb *ccb,
903            uint8_t set, uint8_t index, uint8_t value)
904 {
905         int arg = (MMC_SWITCH_FUNC_WR << 24) |
906             (index << 16) |
907             (value << 8) |
908             set;
909         cam_fill_mmcio(&ccb->mmcio,
910                        /*retries*/ 0,
911                        /*cbfcnp*/ NULL,
912                        /*flags*/ CAM_DIR_NONE,
913                        /*mmc_opcode*/ MMC_SWITCH_FUNC,
914                        /*mmc_arg*/ arg,
915                        /*mmc_flags*/ MMC_RSP_R1B | MMC_CMD_AC,
916                        /*mmc_data*/ NULL,
917                        /*timeout*/ 0);
918
919         cam_periph_runccb(ccb, sddaerror, CAM_FLAG_NONE, /*sense_flags*/0, NULL);
920
921         if (((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)) {
922                 if (ccb->mmcio.cmd.error != 0) {
923                         CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_PERIPH,
924                                   ("%s: MMC command failed", __func__));
925                         return EIO;
926                 }
927                 return 0; /* Normal return */
928         } else {
929                 CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_PERIPH,
930                           ("%s: CAM request failed\n", __func__));
931                 return EIO;
932         }
933
934 }
935
936 static int
937 mmc_sd_switch(struct cam_periph *periph, union ccb *ccb,
938               uint8_t mode, uint8_t grp, uint8_t value,
939               uint8_t *res) {
940
941         struct mmc_data mmc_d;
942
943         memset(res, 0, 64);
944         mmc_d.len = 64;
945         mmc_d.data = res;
946         mmc_d.flags = MMC_DATA_READ;
947
948         cam_fill_mmcio(&ccb->mmcio,
949                        /*retries*/ 0,
950                        /*cbfcnp*/ NULL,
951                        /*flags*/ CAM_DIR_IN,
952                        /*mmc_opcode*/ SD_SWITCH_FUNC,
953                        /*mmc_arg*/ mode << 31,
954                        /*mmc_flags*/ MMC_RSP_R1 | MMC_CMD_ADTC,
955                        /*mmc_data*/ &mmc_d,
956                        /*timeout*/ 0);
957
958         cam_periph_runccb(ccb, sddaerror, CAM_FLAG_NONE, /*sense_flags*/0, NULL);
959
960         if (((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)) {
961                 if (ccb->mmcio.cmd.error != 0) {
962                         CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_PERIPH,
963                                   ("%s: MMC command failed", __func__));
964                         return EIO;
965                 }
966                 return 0; /* Normal return */
967         } else {
968                 CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_PERIPH,
969                           ("%s: CAM request failed\n", __func__));
970                 return EIO;
971         }
972 }
973
974 static int
975 mmc_set_timing(struct cam_periph *periph,
976                union ccb *ccb,
977                enum mmc_bus_timing timing)
978 {
979         u_char switch_res[64];
980         int err;
981         uint8_t value;
982         struct mmc_params *mmcp = &periph->path->device->mmc_ident_data;
983
984         CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE,
985                   ("mmc_set_timing(timing=%d)", timing));
986         switch (timing) {
987         case bus_timing_normal:
988                 value = 0;
989                 break;
990         case bus_timing_hs:
991                 value = 1;
992                 break;
993         default:
994                 return (MMC_ERR_INVALID);
995         }
996         if (mmcp->card_features & CARD_FEATURE_MMC) {
997                 err = mmc_switch(periph, ccb, EXT_CSD_CMD_SET_NORMAL,
998                                  EXT_CSD_HS_TIMING, value);
999         } else {
1000                 err = mmc_sd_switch(periph, ccb, SD_SWITCH_MODE_SET, SD_SWITCH_GROUP1, value, switch_res);
1001         }
1002
1003         /* Set high-speed timing on the host */
1004         struct ccb_trans_settings_mmc *cts;
1005         cts = &ccb->cts.proto_specific.mmc;
1006         ccb->ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
1007         ccb->ccb_h.flags = CAM_DIR_NONE;
1008         ccb->ccb_h.retry_count = 0;
1009         ccb->ccb_h.timeout = 100;
1010         ccb->ccb_h.cbfcnp = NULL;
1011         cts->ios.timing = timing;
1012         cts->ios_valid = MMC_BT;
1013         xpt_action(ccb);
1014
1015         return (err);
1016 }
1017
1018 static void
1019 sdda_start_init_task(void *context, int pending) {
1020         union ccb *new_ccb;
1021         struct cam_periph *periph;
1022
1023         periph = (struct cam_periph *)context;
1024         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sdda_start_init_task\n"));
1025         new_ccb = xpt_alloc_ccb();
1026         xpt_setup_ccb(&new_ccb->ccb_h, periph->path,
1027                       CAM_PRIORITY_NONE);
1028
1029         cam_periph_lock(periph);
1030         sdda_start_init(context, new_ccb);
1031         cam_periph_unlock(periph);
1032         xpt_free_ccb(new_ccb);
1033 }
1034
1035 static void
1036 sdda_set_bus_width(struct cam_periph *periph, union ccb *ccb, int width) {
1037         struct mmc_params *mmcp = &periph->path->device->mmc_ident_data;
1038         int err;
1039
1040         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sdda_set_bus_width\n"));
1041
1042         /* First set for the card, then for the host */
1043         if (mmcp->card_features & CARD_FEATURE_MMC) {
1044                 uint8_t value;
1045                 switch (width) {
1046                 case bus_width_1:
1047                         value = EXT_CSD_BUS_WIDTH_1;
1048                         break;
1049                 case bus_width_4:
1050                         value = EXT_CSD_BUS_WIDTH_4;
1051                         break;
1052                 case bus_width_8:
1053                         value = EXT_CSD_BUS_WIDTH_8;
1054                         break;
1055                 default:
1056                         panic("Invalid bus width %d", width);
1057                 }
1058                 err = mmc_switch(periph, ccb, EXT_CSD_CMD_SET_NORMAL,
1059                                  EXT_CSD_BUS_WIDTH, value);
1060         } else {
1061                 /* For SD cards we send ACMD6 with the required bus width in arg */
1062                 struct mmc_command cmd;
1063                 memset(&cmd, 0, sizeof(struct mmc_command));
1064                 cmd.opcode = ACMD_SET_BUS_WIDTH;
1065                 cmd.arg = width;
1066                 cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
1067                 err = mmc_exec_app_cmd(periph, ccb, &cmd);
1068         }
1069
1070         if (err != MMC_ERR_NONE) {
1071                 CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH, ("Error %d when setting bus width on the card\n", err));
1072                 return;
1073         }
1074         /* Now card is done, set the host to the same width */
1075         struct ccb_trans_settings_mmc *cts;
1076         cts = &ccb->cts.proto_specific.mmc;
1077         ccb->ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
1078         ccb->ccb_h.flags = CAM_DIR_NONE;
1079         ccb->ccb_h.retry_count = 0;
1080         ccb->ccb_h.timeout = 100;
1081         ccb->ccb_h.cbfcnp = NULL;
1082         cts->ios.bus_width = width;
1083         cts->ios_valid = MMC_BW;
1084         xpt_action(ccb);
1085 }
1086
1087 static inline const char *bus_width_str(enum mmc_bus_width w) {
1088         switch (w) {
1089         case bus_width_1:
1090                 return "1-bit";
1091         case bus_width_4:
1092                 return "4-bit";
1093         case bus_width_8:
1094                 return "8-bit";
1095         }
1096 }
1097
1098 static void
1099 sdda_start_init(void *context, union ccb *start_ccb) {
1100         struct cam_periph *periph;
1101         periph = (struct cam_periph *)context;
1102         int err;
1103
1104         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sdda_start_init\n"));
1105         /* periph was held for us when this task was enqueued */
1106         if ((periph->flags & CAM_PERIPH_INVALID) != 0) {
1107                 cam_periph_release(periph);
1108                 return;
1109         }
1110
1111         struct sdda_softc *softc = (struct sdda_softc *)periph->softc;
1112         //struct ccb_mmcio *mmcio = &start_ccb->mmcio;
1113         struct mmc_params *mmcp = &periph->path->device->mmc_ident_data;
1114         struct cam_ed *device = periph->path->device;
1115
1116         if (mmcp->card_features & CARD_FEATURE_MMC) {
1117                 mmc_decode_csd_mmc(mmcp->card_csd, &softc->csd);
1118                 mmc_decode_cid_mmc(mmcp->card_cid, &softc->cid);
1119                 if (softc->csd.spec_vers >= 4)
1120                         err = mmc_send_ext_csd(periph, start_ccb,
1121                                                (uint8_t *)&softc->raw_ext_csd,
1122                                                sizeof(softc->raw_ext_csd));
1123         } else {
1124                 mmc_decode_csd_sd(mmcp->card_csd, &softc->csd);
1125                 mmc_decode_cid_sd(mmcp->card_cid, &softc->cid);
1126         }
1127
1128         softc->sector_count = softc->csd.capacity / 512;
1129         softc->mediasize = softc->csd.capacity;
1130
1131         /* MMC >= 4.x have EXT_CSD that has its own opinion about capacity */
1132         if (softc->csd.spec_vers >= 4) {
1133                 uint32_t sec_count = softc->raw_ext_csd[EXT_CSD_SEC_CNT] +
1134                         (softc->raw_ext_csd[EXT_CSD_SEC_CNT + 1] << 8) +
1135                         (softc->raw_ext_csd[EXT_CSD_SEC_CNT + 2] << 16) +
1136                         (softc->raw_ext_csd[EXT_CSD_SEC_CNT + 3] << 24);
1137                 if (sec_count != 0) {
1138                         softc->sector_count = sec_count;
1139                         softc->mediasize = softc->sector_count * 512;
1140                         /* FIXME: there should be a better name for this option...*/
1141                         mmcp->card_features |= CARD_FEATURE_SDHC;
1142                 }
1143
1144         }
1145         CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH,
1146                   ("Capacity: %"PRIu64", sectors: %"PRIu64"\n",
1147                    softc->mediasize,
1148                    softc->sector_count));
1149         mmc_format_card_id_string(softc, mmcp);
1150
1151         /* Update info for CAM */
1152         device->serial_num_len = strlen(softc->card_sn_string);
1153         device->serial_num =
1154                 (u_int8_t *)malloc((device->serial_num_len + 1),
1155                                    M_CAMXPT, M_NOWAIT);
1156         strlcpy(device->serial_num, softc->card_sn_string, device->serial_num_len);
1157
1158         device->device_id_len = strlen(softc->card_id_string);
1159         device->device_id =
1160                 (u_int8_t *)malloc((device->device_id_len + 1),
1161                                    M_CAMXPT, M_NOWAIT);
1162         strlcpy(device->device_id, softc->card_id_string, device->device_id_len);
1163
1164         strlcpy(mmcp->model, softc->card_id_string, sizeof(mmcp->model));
1165
1166         /* Set the clock frequency that the card can handle */
1167         struct ccb_trans_settings_mmc *cts;
1168         cts = &start_ccb->cts.proto_specific.mmc;
1169
1170         /* First, get the host's max freq */
1171         start_ccb->ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
1172         start_ccb->ccb_h.flags = CAM_DIR_NONE;
1173         start_ccb->ccb_h.retry_count = 0;
1174         start_ccb->ccb_h.timeout = 100;
1175         start_ccb->ccb_h.cbfcnp = NULL;
1176         xpt_action(start_ccb);
1177
1178         if (start_ccb->ccb_h.status != CAM_REQ_CMP)
1179                 panic("Cannot get max host freq");
1180         int host_f_max = cts->host_f_max;
1181         uint32_t host_caps = cts->host_caps;
1182         if (cts->ios.bus_width != bus_width_1)
1183                 panic("Bus width in ios is not 1-bit");
1184
1185         /* Now check if the card supports High-speed */
1186         softc->card_f_max = softc->csd.tran_speed;
1187
1188         if (host_caps & MMC_CAP_HSPEED) {
1189                 /* Find out if the card supports High speed timing */
1190                 if (mmcp->card_features & CARD_FEATURE_SD20) {
1191                         /* Get and decode SCR */
1192                         uint32_t rawscr;
1193                         uint8_t res[64];
1194                         if (mmc_app_get_scr(periph, start_ccb, &rawscr)) {
1195                                 CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH, ("Cannot get SCR\n"));
1196                                 goto finish_hs_tests;
1197                         }
1198                         mmc_app_decode_scr(&rawscr, &softc->scr);
1199
1200                         if ((softc->scr.sda_vsn >= 1) && (softc->csd.ccc & (1<<10))) {
1201                                 mmc_sd_switch(periph, start_ccb, SD_SWITCH_MODE_CHECK,
1202                                               SD_SWITCH_GROUP1, SD_SWITCH_NOCHANGE, res);
1203                                 if (res[13] & 2) {
1204                                         CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH, ("Card supports HS\n"));
1205                                         softc->card_f_max = SD_HS_MAX;
1206                                 }
1207                         } else {
1208                                 CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH, ("Not trying the switch\n"));
1209                                 goto finish_hs_tests;
1210                         }
1211                 }
1212
1213                 if (mmcp->card_features & CARD_FEATURE_MMC && softc->csd.spec_vers >= 4) {
1214                         if (softc->raw_ext_csd[EXT_CSD_CARD_TYPE]
1215                             & EXT_CSD_CARD_TYPE_HS_52)
1216                                 softc->card_f_max = MMC_TYPE_HS_52_MAX;
1217                         else if (softc->raw_ext_csd[EXT_CSD_CARD_TYPE]
1218                                  & EXT_CSD_CARD_TYPE_HS_26)
1219                                 softc->card_f_max = MMC_TYPE_HS_26_MAX;
1220                 }
1221         }
1222         int f_max;
1223 finish_hs_tests:
1224         f_max = min(host_f_max, softc->card_f_max);
1225         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));
1226
1227         start_ccb->ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
1228         start_ccb->ccb_h.flags = CAM_DIR_NONE;
1229         start_ccb->ccb_h.retry_count = 0;
1230         start_ccb->ccb_h.timeout = 100;
1231         start_ccb->ccb_h.cbfcnp = NULL;
1232         cts->ios.clock = f_max;
1233         cts->ios_valid = MMC_CLK;
1234         xpt_action(start_ccb);
1235
1236         /* Set bus width */
1237         enum mmc_bus_width desired_bus_width = bus_width_1;
1238         enum mmc_bus_width max_host_bus_width =
1239                 (host_caps & MMC_CAP_8_BIT_DATA ? bus_width_8 :
1240                  host_caps & MMC_CAP_4_BIT_DATA ? bus_width_4 : bus_width_1);
1241         enum mmc_bus_width max_card_bus_width = bus_width_1;
1242         if (mmcp->card_features & CARD_FEATURE_SD20 &&
1243             softc->scr.bus_widths & SD_SCR_BUS_WIDTH_4)
1244                 max_card_bus_width = bus_width_4;
1245         /*
1246          * Unlike SD, MMC cards don't have any information about supported bus width...
1247          * So we need to perform read/write test to find out the width.
1248          */
1249         /* TODO: figure out bus width for MMC; use 8-bit for now (to test on BBB) */
1250         if (mmcp->card_features & CARD_FEATURE_MMC)
1251                 max_card_bus_width = bus_width_8;
1252
1253         desired_bus_width = min(max_host_bus_width, max_card_bus_width);
1254         CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH,
1255                   ("Set bus width to %s (min of host %s and card %s)\n",
1256                    bus_width_str(desired_bus_width),
1257                    bus_width_str(max_host_bus_width),
1258                    bus_width_str(max_card_bus_width)));
1259         sdda_set_bus_width(periph, start_ccb, desired_bus_width);
1260
1261         if (f_max > 25000000) {
1262                 err = mmc_set_timing(periph, start_ccb, bus_timing_hs);
1263                 if (err != MMC_ERR_NONE)
1264                         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("Cannot switch card to high-speed mode"));
1265         }
1266         softc->state = SDDA_STATE_NORMAL;
1267         sdda_hook_into_geom(periph);
1268 }
1269
1270 /* Called with periph lock held! */
1271 static void
1272 sddastart(struct cam_periph *periph, union ccb *start_ccb)
1273 {
1274         struct sdda_softc *softc = (struct sdda_softc *)periph->softc;
1275         struct mmc_params *mmcp = &periph->path->device->mmc_ident_data;
1276
1277         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sddastart\n"));
1278
1279         if (softc->state != SDDA_STATE_NORMAL) {
1280                 CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("device is not in SDDA_STATE_NORMAL yet"));
1281                 xpt_release_ccb(start_ccb);
1282                 return;
1283         }
1284         struct bio *bp;
1285
1286         /* Run regular command. */
1287         bp = bioq_first(&softc->bio_queue);
1288         if (bp == NULL) {
1289                 xpt_release_ccb(start_ccb);
1290                 return;
1291         }
1292         bioq_remove(&softc->bio_queue, bp);
1293
1294         switch (bp->bio_cmd) {
1295         case BIO_WRITE:
1296                 CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("BIO_WRITE\n"));
1297                 softc->flags |= SDDA_FLAG_DIRTY;
1298                 /* FALLTHROUGH */
1299         case BIO_READ:
1300         {
1301                 CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("BIO_READ\n"));
1302                 uint64_t blockno = bp->bio_pblkno;
1303                 uint16_t count = bp->bio_bcount / 512;
1304                 uint16_t opcode;
1305
1306                 CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("Block %"PRIu64" cnt %u\n", blockno, count));
1307
1308                 /* Construct new MMC command */
1309                 if (bp->bio_cmd == BIO_READ) {
1310                         if (count > 1)
1311                                 opcode = MMC_READ_MULTIPLE_BLOCK;
1312                         else
1313                                 opcode = MMC_READ_SINGLE_BLOCK;
1314                 } else {
1315                         if (count > 1)
1316                                 opcode = MMC_WRITE_MULTIPLE_BLOCK;
1317                         else
1318                                 opcode = MMC_WRITE_BLOCK;
1319                 }
1320
1321                 start_ccb->ccb_h.func_code = XPT_MMC_IO;
1322                 start_ccb->ccb_h.flags = (bp->bio_cmd == BIO_READ ? CAM_DIR_IN : CAM_DIR_OUT);
1323                 start_ccb->ccb_h.retry_count = 0;
1324                 start_ccb->ccb_h.timeout = 15 * 1000;
1325                 start_ccb->ccb_h.cbfcnp = sddadone;
1326                 struct ccb_mmcio *mmcio;
1327
1328                 mmcio = &start_ccb->mmcio;
1329                 mmcio->cmd.opcode = opcode;
1330                 mmcio->cmd.arg = blockno;
1331                 if (!(mmcp->card_features & CARD_FEATURE_SDHC))
1332                         mmcio->cmd.arg <<= 9;
1333
1334                 mmcio->cmd.flags = MMC_RSP_R1 | MMC_CMD_ADTC;
1335                 mmcio->cmd.data = softc->mmcdata;
1336                 mmcio->cmd.data->data = bp->bio_data;
1337                 mmcio->cmd.data->len = 512 * count;
1338                 mmcio->cmd.data->flags = (bp->bio_cmd == BIO_READ ? MMC_DATA_READ : MMC_DATA_WRITE);
1339                 /* Direct h/w to issue CMD12 upon completion */
1340                 if (count > 1) {
1341                         mmcio->stop.opcode = MMC_STOP_TRANSMISSION;
1342                         mmcio->stop.flags = MMC_RSP_R1B | MMC_CMD_AC;
1343                         mmcio->stop.arg = 0;
1344                 }
1345
1346                 break;
1347         }
1348         case BIO_FLUSH:
1349                 CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("BIO_FLUSH\n"));
1350                 sddaschedule(periph);
1351                 break;
1352         case BIO_DELETE:
1353                 CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("BIO_DELETE\n"));
1354                 sddaschedule(periph);
1355                 break;
1356         }
1357         start_ccb->ccb_h.ccb_bp = bp;
1358         softc->outstanding_cmds++;
1359         softc->refcount++;
1360         cam_periph_unlock(periph);
1361         xpt_action(start_ccb);
1362         cam_periph_lock(periph);
1363         softc->refcount--;
1364
1365         /* May have more work to do, so ensure we stay scheduled */
1366         sddaschedule(periph);
1367 }
1368
1369 static void
1370 sddadone(struct cam_periph *periph, union ccb *done_ccb)
1371 {
1372         struct sdda_softc *softc;
1373         struct ccb_mmcio *mmcio;
1374 //      struct ccb_getdev *cgd;
1375         struct cam_path *path;
1376 //      int state;
1377
1378         softc = (struct sdda_softc *)periph->softc;
1379         mmcio = &done_ccb->mmcio;
1380         path = done_ccb->ccb_h.path;
1381
1382         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("sddadone\n"));
1383
1384         struct bio *bp;
1385         int error = 0;
1386
1387 //        cam_periph_lock(periph);
1388         if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1389                 CAM_DEBUG(path, CAM_DEBUG_TRACE, ("Error!!!\n"));
1390                 if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1391                         cam_release_devq(path,
1392                                          /*relsim_flags*/0,
1393                                          /*reduction*/0,
1394                                          /*timeout*/0,
1395                                          /*getcount_only*/0);
1396                 error = 5; /* EIO */
1397         } else {
1398                 if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1399                         panic("REQ_CMP with QFRZN");
1400                 error = 0;
1401         }
1402
1403
1404         bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
1405         bp->bio_error = error;
1406         if (error != 0) {
1407                 bp->bio_resid = bp->bio_bcount;
1408                 bp->bio_flags |= BIO_ERROR;
1409         } else {
1410                 /* XXX: How many bytes remaining? */
1411                 bp->bio_resid = 0;
1412                 if (bp->bio_resid > 0)
1413                         bp->bio_flags |= BIO_ERROR;
1414         }
1415
1416         uint32_t card_status = mmcio->cmd.resp[0];
1417         CAM_DEBUG(path, CAM_DEBUG_TRACE,
1418                   ("Card status: %08x\n", R1_STATUS(card_status)));
1419         CAM_DEBUG(path, CAM_DEBUG_TRACE,
1420                   ("Current state: %d\n", R1_CURRENT_STATE(card_status)));
1421
1422         softc->outstanding_cmds--;
1423         xpt_release_ccb(done_ccb);
1424         biodone(bp);
1425 }
1426
1427 static int
1428 sddaerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
1429 {
1430         return(cam_periph_error(ccb, cam_flags, sense_flags, NULL));
1431 }
1432 #endif /* _KERNEL */