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