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