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