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