xref: /openbmc/qemu/hw/sd/sd.c (revision feb58e3b)
1 /*
2  * SD Memory Card emulation as defined in the "SD Memory Card Physical
3  * layer specification, Version 2.00."
4  *
5  * eMMC emulation defined in "JEDEC Standard No. 84-A43"
6  *
7  * Copyright (c) 2006 Andrzej Zaborowski  <balrog@zabor.org>
8  * Copyright (c) 2007 CodeSourcery
9  * Copyright (c) 2018 Philippe Mathieu-Daudé <f4bug@amsat.org>
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  *
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in
19  *    the documentation and/or other materials provided with the
20  *    distribution.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
23  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
24  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
25  * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR
26  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
27  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
28  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
29  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
30  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 #include "qemu/osdep.h"
36 #include "qemu/units.h"
37 #include "qemu/cutils.h"
38 #include "hw/irq.h"
39 #include "hw/registerfields.h"
40 #include "sysemu/block-backend.h"
41 #include "hw/sd/sd.h"
42 #include "hw/sd/sdcard_legacy.h"
43 #include "migration/vmstate.h"
44 #include "qapi/error.h"
45 #include "qemu/bitmap.h"
46 #include "hw/qdev-properties.h"
47 #include "hw/qdev-properties-system.h"
48 #include "qemu/error-report.h"
49 #include "qemu/timer.h"
50 #include "qemu/log.h"
51 #include "qemu/guest-random.h"
52 #include "qemu/module.h"
53 #include "sdmmc-internal.h"
54 #include "trace.h"
55 
56 //#define DEBUG_SD 1
57 
58 #define SDSC_MAX_CAPACITY   (2 * GiB)
59 
60 #define INVALID_ADDRESS     UINT32_MAX
61 
62 typedef enum {
63     sd_r0 = 0,    /* no response */
64     sd_r1,        /* normal response command */
65     sd_r2_i,      /* CID register */
66     sd_r2_s,      /* CSD register */
67     sd_r3,        /* OCR register */
68     sd_r6 = 6,    /* Published RCA response */
69     sd_r7,        /* Operating voltage */
70     sd_r1b = -1,
71     sd_illegal = -2,
72 } sd_rsp_type_t;
73 
74 typedef enum {
75     sd_spi,
76     sd_bc,     /* broadcast -- no response */
77     sd_bcr,    /* broadcast with response */
78     sd_ac,     /* addressed -- no data transfer */
79     sd_adtc,   /* addressed with data transfer */
80 } sd_cmd_type_t;
81 
82 enum SDCardModes {
83     sd_inactive,
84     sd_card_identification_mode,
85     sd_data_transfer_mode,
86 };
87 
88 enum SDCardStates {
89     sd_waitirq_state        = -2, /* emmc */
90     sd_inactive_state       = -1,
91 
92     sd_idle_state           = 0,
93     sd_ready_state          = 1,
94     sd_identification_state = 2,
95     sd_standby_state        = 3,
96     sd_transfer_state       = 4,
97     sd_sendingdata_state    = 5,
98     sd_receivingdata_state  = 6,
99     sd_programming_state    = 7,
100     sd_disconnect_state     = 8,
101     sd_bus_test_state       = 9,  /* emmc */
102     sd_sleep_state          = 10, /* emmc */
103     sd_io_state             = 15  /* sd */
104 };
105 
106 #define SDMMC_CMD_MAX 64
107 
108 typedef sd_rsp_type_t (*sd_cmd_handler)(SDState *sd, SDRequest req);
109 
110 typedef struct SDProto {
111     const char *name;
112     struct {
113         const unsigned class;
114         const sd_cmd_type_t type;
115         const char *name;
116         sd_cmd_handler handler;
117     } cmd[SDMMC_CMD_MAX], acmd[SDMMC_CMD_MAX];
118 } SDProto;
119 
120 struct SDState {
121     DeviceState parent_obj;
122 
123     /* If true, created by sd_init() for a non-qdevified caller */
124     /* TODO purge them with fire */
125     bool me_no_qdev_me_kill_mammoth_with_rocks;
126 
127     /* SD Memory Card Registers */
128     uint32_t ocr;
129     uint8_t scr[8];
130     uint8_t cid[16];
131     uint8_t csd[16];
132     uint16_t rca;
133     uint32_t card_status;
134     uint8_t sd_status[64];
135     union {
136         uint8_t ext_csd[512];
137         struct {
138             uint8_t ext_csd_rw[192]; /* Modes segment */
139             uint8_t ext_csd_ro[320]; /* Properties segment */
140         };
141     };
142 
143     /* Static properties */
144 
145     uint8_t spec_version;
146     uint64_t boot_part_size;
147     BlockBackend *blk;
148     uint8_t boot_config;
149 
150     const SDProto *proto;
151 
152     /* Runtime changeables */
153 
154     uint32_t mode;    /* current card mode, one of SDCardModes */
155     int32_t state;    /* current card state, one of SDCardStates */
156     uint32_t vhs;
157     bool wp_switch;
158     unsigned long *wp_group_bmap;
159     int32_t wp_group_bits;
160     uint64_t size;
161     uint32_t blk_len;
162     uint32_t multi_blk_cnt;
163     uint32_t erase_start;
164     uint32_t erase_end;
165     uint8_t pwd[16];
166     uint32_t pwd_len;
167     uint8_t function_group[6];
168     uint8_t current_cmd;
169     const char *last_cmd_name;
170     /* True if we will handle the next command as an ACMD. Note that this does
171      * *not* track the APP_CMD status bit!
172      */
173     bool expecting_acmd;
174     uint32_t blk_written;
175 
176     uint64_t data_start;
177     uint32_t data_offset;
178     size_t data_size;
179     uint8_t data[512];
180     qemu_irq readonly_cb;
181     qemu_irq inserted_cb;
182     QEMUTimer *ocr_power_timer;
183     bool enable;
184     uint8_t dat_lines;
185     bool cmd_line;
186 };
187 
188 static void sd_realize(DeviceState *dev, Error **errp);
189 
190 static const SDProto sd_proto_spi;
191 static const SDProto sd_proto_emmc;
192 
193 static bool sd_is_spi(SDState *sd)
194 {
195     return sd->proto == &sd_proto_spi;
196 }
197 
198 static bool sd_is_emmc(SDState *sd)
199 {
200     return sd->proto == &sd_proto_emmc;
201 }
202 
203 static const char *sd_version_str(enum SDPhySpecificationVersion version)
204 {
205     static const char *sdphy_version[] = {
206         [SD_PHY_SPECv1_10_VERS]     = "v1.10",
207         [SD_PHY_SPECv2_00_VERS]     = "v2.00",
208         [SD_PHY_SPECv3_01_VERS]     = "v3.01",
209     };
210     if (version >= ARRAY_SIZE(sdphy_version)) {
211         return "unsupported version";
212     }
213     return sdphy_version[version];
214 }
215 
216 static const char *sd_mode_name(enum SDCardModes mode)
217 {
218     static const char *mode_name[] = {
219         [sd_inactive]                   = "inactive",
220         [sd_card_identification_mode]   = "identification",
221         [sd_data_transfer_mode]         = "transfer",
222     };
223     assert(mode < ARRAY_SIZE(mode_name));
224     return mode_name[mode];
225 }
226 
227 static const char *sd_state_name(enum SDCardStates state)
228 {
229     static const char *state_name[] = {
230         [sd_idle_state]             = "idle",
231         [sd_ready_state]            = "ready",
232         [sd_identification_state]   = "identification",
233         [sd_standby_state]          = "standby",
234         [sd_transfer_state]         = "transfer",
235         [sd_sendingdata_state]      = "sendingdata",
236         [sd_bus_test_state]         = "bus-test",
237         [sd_receivingdata_state]    = "receivingdata",
238         [sd_programming_state]      = "programming",
239         [sd_disconnect_state]       = "disconnect",
240         [sd_sleep_state]            = "sleep",
241         [sd_io_state]               = "i/o"
242     };
243     if (state == sd_inactive_state) {
244         return "inactive";
245     }
246     if (state == sd_waitirq_state) {
247         return "wait-irq";
248     }
249     assert(state < ARRAY_SIZE(state_name));
250     return state_name[state];
251 }
252 
253 static const char *sd_response_name(sd_rsp_type_t rsp)
254 {
255     static const char *response_name[] = {
256         [sd_r0]     = "RESP#0 (no response)",
257         [sd_r1]     = "RESP#1 (normal cmd)",
258         [sd_r2_i]   = "RESP#2 (CID reg)",
259         [sd_r2_s]   = "RESP#2 (CSD reg)",
260         [sd_r3]     = "RESP#3 (OCR reg)",
261         [sd_r6]     = "RESP#6 (RCA)",
262         [sd_r7]     = "RESP#7 (operating voltage)",
263     };
264     if (rsp == sd_illegal) {
265         return "ILLEGAL RESP";
266     }
267     if (rsp == sd_r1b) {
268         rsp = sd_r1;
269     }
270     assert(rsp < ARRAY_SIZE(response_name));
271     return response_name[rsp];
272 }
273 
274 static const char *sd_cmd_name(SDState *sd, uint8_t cmd)
275 {
276     static const char *cmd_abbrev[SDMMC_CMD_MAX] = {
277         [18]    = "READ_MULTIPLE_BLOCK",
278                                             [25]    = "WRITE_MULTIPLE_BLOCK",
279     };
280     const SDProto *sdp = sd->proto;
281 
282     if (sdp->cmd[cmd].handler) {
283         assert(!cmd_abbrev[cmd]);
284         return sdp->cmd[cmd].name;
285     }
286     return cmd_abbrev[cmd] ? cmd_abbrev[cmd] : "UNKNOWN_CMD";
287 }
288 
289 static const char *sd_acmd_name(SDState *sd, uint8_t cmd)
290 {
291     const SDProto *sdp = sd->proto;
292 
293     if (sdp->acmd[cmd].handler) {
294         return sdp->acmd[cmd].name;
295     }
296 
297     return "UNKNOWN_ACMD";
298 }
299 
300 static uint8_t sd_get_dat_lines(SDState *sd)
301 {
302     return sd->enable ? sd->dat_lines : 0;
303 }
304 
305 static bool sd_get_cmd_line(SDState *sd)
306 {
307     return sd->enable ? sd->cmd_line : false;
308 }
309 
310 static void sd_set_voltage(SDState *sd, uint16_t millivolts)
311 {
312     trace_sdcard_set_voltage(millivolts);
313 
314     switch (millivolts) {
315     case 3001 ... 3600: /* SD_VOLTAGE_3_3V */
316     case 2001 ... 3000: /* SD_VOLTAGE_3_0V */
317         break;
318     default:
319         qemu_log_mask(LOG_GUEST_ERROR, "SD card voltage not supported: %.3fV",
320                       millivolts / 1000.f);
321     }
322 }
323 
324 static void sd_set_mode(SDState *sd)
325 {
326     switch (sd->state) {
327     case sd_inactive_state:
328         sd->mode = sd_inactive;
329         break;
330 
331     case sd_idle_state:
332     case sd_ready_state:
333     case sd_identification_state:
334         sd->mode = sd_card_identification_mode;
335         break;
336 
337     case sd_standby_state:
338     case sd_transfer_state:
339     case sd_sendingdata_state:
340     case sd_receivingdata_state:
341     case sd_programming_state:
342     case sd_disconnect_state:
343         sd->mode = sd_data_transfer_mode;
344         break;
345     }
346 }
347 
348 static uint8_t sd_crc7(const void *message, size_t width)
349 {
350     int i, bit;
351     uint8_t shift_reg = 0x00;
352     const uint8_t *msg = (const uint8_t *)message;
353 
354     for (i = 0; i < width; i ++, msg ++)
355         for (bit = 7; bit >= 0; bit --) {
356             shift_reg <<= 1;
357             if ((shift_reg >> 7) ^ ((*msg >> bit) & 1))
358                 shift_reg ^= 0x89;
359         }
360 
361     return shift_reg;
362 }
363 
364 /* Operation Conditions register */
365 
366 #define OCR_POWER_DELAY_NS      500000 /* 0.5ms */
367 
368 FIELD(OCR, VDD_VOLTAGE_WINDOW,          0, 24)
369 FIELD(OCR, VDD_VOLTAGE_WIN_LO,          0,  8)
370 FIELD(OCR, DUAL_VOLTAGE_CARD,           7,  1)
371 FIELD(OCR, VDD_VOLTAGE_WIN_HI,          8, 16)
372 FIELD(OCR, ACCEPT_SWITCH_1V8,          24,  1) /* Only UHS-I */
373 FIELD(OCR, UHS_II_CARD,                29,  1) /* Only UHS-II */
374 FIELD(OCR, CARD_CAPACITY,              30,  1) /* 0:SDSC, 1:SDHC/SDXC */
375 FIELD(OCR, CARD_POWER_UP,              31,  1)
376 
377 #define ACMD41_ENQUIRY_MASK     0x00ffffff
378 #define ACMD41_R3_MASK          (R_OCR_VDD_VOLTAGE_WIN_HI_MASK \
379                                | R_OCR_ACCEPT_SWITCH_1V8_MASK \
380                                | R_OCR_UHS_II_CARD_MASK \
381                                | R_OCR_CARD_CAPACITY_MASK \
382                                | R_OCR_CARD_POWER_UP_MASK)
383 
384 static void sd_ocr_powerup(void *opaque)
385 {
386     SDState *sd = opaque;
387 
388     trace_sdcard_powerup();
389     assert(!FIELD_EX32(sd->ocr, OCR, CARD_POWER_UP));
390 
391     /* card power-up OK */
392     sd->ocr = FIELD_DP32(sd->ocr, OCR, CARD_POWER_UP, 1);
393 
394     if (sd->size > SDSC_MAX_CAPACITY) {
395         sd->ocr = FIELD_DP32(sd->ocr, OCR, CARD_CAPACITY, 1);
396     }
397 }
398 
399 static void sd_set_ocr(SDState *sd)
400 {
401     /* All voltages OK */
402     sd->ocr = R_OCR_VDD_VOLTAGE_WIN_HI_MASK;
403 
404     if (sd_is_spi(sd)) {
405         /*
406          * We don't need to emulate power up sequence in SPI-mode.
407          * Thus, the card's power up status bit should be set to 1 when reset.
408          * The card's capacity status bit should also be set if SD card size
409          * is larger than 2GB for SDHC support.
410          */
411         sd_ocr_powerup(sd);
412     }
413 }
414 
415 /* SD Configuration register */
416 
417 static void sd_set_scr(SDState *sd)
418 {
419     sd->scr[0] = 0 << 4;        /* SCR structure version 1.0 */
420     if (sd->spec_version == SD_PHY_SPECv1_10_VERS) {
421         sd->scr[0] |= 1;        /* Spec Version 1.10 */
422     } else {
423         sd->scr[0] |= 2;        /* Spec Version 2.00 or Version 3.0X */
424     }
425     sd->scr[1] = (2 << 4)       /* SDSC Card (Security Version 1.01) */
426                  | 0b0101;      /* 1-bit or 4-bit width bus modes */
427     sd->scr[2] = 0x00;          /* Extended Security is not supported. */
428     if (sd->spec_version >= SD_PHY_SPECv3_01_VERS) {
429         sd->scr[2] |= 1 << 7;   /* Spec Version 3.0X */
430     }
431     sd->scr[3] = 0x00;
432     /* reserved for manufacturer usage */
433     sd->scr[4] = 0x00;
434     sd->scr[5] = 0x00;
435     sd->scr[6] = 0x00;
436     sd->scr[7] = 0x00;
437 }
438 
439 /* Card IDentification register */
440 
441 #define MID     0xaa
442 #define OID     "XY"
443 #define PNM     "QEMU!"
444 #define PRV     0x01
445 #define MDT_YR  2006
446 #define MDT_MON 2
447 
448 static void sd_set_cid(SDState *sd)
449 {
450     sd->cid[0] = MID;       /* Fake card manufacturer ID (MID) */
451     sd->cid[1] = OID[0];    /* OEM/Application ID (OID) */
452     sd->cid[2] = OID[1];
453     sd->cid[3] = PNM[0];    /* Fake product name (PNM) */
454     sd->cid[4] = PNM[1];
455     sd->cid[5] = PNM[2];
456     sd->cid[6] = PNM[3];
457     sd->cid[7] = PNM[4];
458     sd->cid[8] = PRV;       /* Fake product revision (PRV) */
459     stl_be_p(&sd->cid[9], 0xdeadbeef); /* Fake serial number (PSN) */
460     sd->cid[13] = 0x00 |    /* Manufacture date (MDT) */
461         ((MDT_YR - 2000) / 10);
462     sd->cid[14] = ((MDT_YR % 10) << 4) | MDT_MON;
463     sd->cid[15] = (sd_crc7(sd->cid, 15) << 1) | 1;
464 }
465 
466 static void emmc_set_cid(SDState *sd)
467 {
468     sd->cid[0] = MID;       /* Fake card manufacturer ID (MID) */
469     sd->cid[1] = 0b01;      /* CBX: soldered BGA */
470     sd->cid[2] = OID[0];    /* OEM/Application ID (OID) */
471     sd->cid[3] = PNM[0];    /* Fake product name (PNM) */
472     sd->cid[4] = PNM[1];
473     sd->cid[5] = PNM[2];
474     sd->cid[6] = PNM[3];
475     sd->cid[7] = PNM[4];
476     sd->cid[8] = PNM[4];
477     sd->cid[9] = PRV;       /* Fake product revision (PRV) */
478     stl_be_p(&sd->cid[10], 0xdeadbeef); /* Fake serial number (PSN) */
479     sd->cid[14] = (MDT_MON << 4) | (MDT_YR - 1997); /* Manufacture date (MDT) */
480     sd->cid[15] = (sd_crc7(sd->cid, 15) << 1) | 1;
481 }
482 
483 /* Card-Specific Data register */
484 
485 #define HWBLOCK_SHIFT   9        /* 512 bytes */
486 #define SECTOR_SHIFT    5        /* 16 kilobytes */
487 #define WPGROUP_SHIFT   7        /* 2 megs */
488 #define CMULT_SHIFT     9        /* 512 times HWBLOCK_SIZE */
489 #define WPGROUP_SIZE    (1 << (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT))
490 
491 static const uint8_t sd_csd_rw_mask[16] = {
492     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
493     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xfe,
494 };
495 
496 static void emmc_set_ext_csd(SDState *sd, uint64_t size)
497 {
498     uint32_t sectcount = size >> HWBLOCK_SHIFT;
499 
500     memset(sd->ext_csd, 0, sizeof(sd->ext_csd)); /* FIXME only RW at reset */
501 
502     /* Properties segment (RO) */
503     sd->ext_csd[EXT_CSD_S_CMD_SET] = 0b1; /* supported command sets */
504     sd->ext_csd[EXT_CSD_BOOT_INFO] = 0x0; /* Boot information */
505                                      /* Boot partition size. 128KB unit */
506     sd->ext_csd[EXT_CSD_BOOT_MULT] = sd->boot_part_size / (128 * KiB);
507     sd->ext_csd[EXT_CSD_ACC_SIZE] = 0x1; /* Access size */
508     sd->ext_csd[EXT_CSD_HC_ERASE_GRP_SIZE] = 0x01; /* HC Erase unit size */
509     sd->ext_csd[EXT_CSD_ERASE_TIMEOUT_MULT] = 0x01; /* HC erase timeout */
510     sd->ext_csd[EXT_CSD_REL_WR_SEC_C] = 0x1; /* Reliable write sector count */
511     sd->ext_csd[EXT_CSD_HC_WP_GRP_SIZE] = 0x01; /* HC write protect group size */
512     sd->ext_csd[EXT_CSD_S_C_VCC] = 0x01; /* Sleep current VCC  */
513     sd->ext_csd[EXT_CSD_S_C_VCCQ] = 0x01; /* Sleep current VCCQ */
514     sd->ext_csd[EXT_CSD_S_A_TIMEOUT] = 0x01; /* Sleep/Awake timeout */
515     stl_le_p(&sd->ext_csd[EXT_CSD_SEC_CNT], sectcount); /* Sector count */
516     sd->ext_csd[210] = 0x46; /* Min write perf for 8bit@52Mhz */
517     sd->ext_csd[209] = 0x46; /* Min read perf for 8bit@52Mhz  */
518     sd->ext_csd[208] = 0x46; /* Min write perf for 4bit@52Mhz */
519     sd->ext_csd[207] = 0x46; /* Min read perf for 4bit@52Mhz */
520     sd->ext_csd[206] = 0x46; /* Min write perf for 4bit@26Mhz */
521     sd->ext_csd[205] = 0x46; /* Min read perf for 4bit@26Mhz */
522     sd->ext_csd[EXT_CSD_CARD_TYPE] = 0b11;
523     sd->ext_csd[EXT_CSD_STRUCTURE] = 2;
524     sd->ext_csd[EXT_CSD_REV] = 3;
525 
526     /* Mode segment (RW) */
527     sd->ext_csd[EXT_CSD_PART_CONFIG] = sd->boot_config;
528 }
529 
530 static void emmc_set_csd(SDState *sd, uint64_t size)
531 {
532     int hwblock_shift = HWBLOCK_SHIFT;
533     uint32_t sectsize = (1 << (SECTOR_SHIFT + 1)) - 1;
534     uint32_t wpsize = (1 << (WPGROUP_SHIFT + 1)) - 1;
535 
536     sd->csd[0] = (3 << 6) | (4 << 2); /* Spec v4.3 with EXT_CSD */
537     sd->csd[1] = (1 << 3) | 6; /* Asynchronous data access time: 1ms */
538     sd->csd[2] = 0x00;
539     sd->csd[3] = (1 << 3) | 3;; /* Maximum bus clock frequency: 100MHz */
540     sd->csd[4] = 0x0f;
541     if (size <= 2 * GiB) {
542         /* use 1k blocks */
543         uint32_t csize1k = (size >> (CMULT_SHIFT + 10)) - 1;
544         sd->csd[5] = 0x5a;
545         sd->csd[6] = 0x80 | ((csize1k >> 10) & 0xf);
546         sd->csd[7] = (csize1k >> 2) & 0xff;
547     } else { /* >= 2GB : size stored in ext CSD, block addressing */
548         sd->csd[5] = 0x59;
549         sd->csd[6] = 0x8f;
550         sd->csd[7] = 0xff;
551         sd->ocr = FIELD_DP32(sd->ocr, OCR, CARD_CAPACITY, 1);
552     }
553     sd->csd[8] = 0xff;
554     sd->csd[9] = 0xfc |     /* Max. write current */
555         ((CMULT_SHIFT - 2) >> 1);
556     sd->csd[10] = 0x40 |    /* Erase sector size */
557         (((CMULT_SHIFT - 2) << 7) & 0x80) | (sectsize >> 1);
558     sd->csd[11] = 0x00 |    /* Write protect group size */
559         ((sectsize << 7) & 0x80) | wpsize;
560     sd->csd[12] = 0x90 |    /* Write speed factor */
561         (hwblock_shift >> 2);
562     sd->csd[13] = 0x20 |    /* Max. write data block length */
563         ((hwblock_shift << 6) & 0xc0);
564     sd->csd[14] = 0x00;
565     sd->csd[15] = (sd_crc7(sd->csd, 15) << 1) | 1;
566     emmc_set_ext_csd(sd, size);
567 }
568 
569 static void sd_set_csd(SDState *sd, uint64_t size)
570 {
571     int hwblock_shift = HWBLOCK_SHIFT;
572     uint32_t csize;
573     uint32_t sectsize = (1 << (SECTOR_SHIFT + 1)) - 1;
574     uint32_t wpsize = (1 << (WPGROUP_SHIFT + 1)) - 1;
575 
576     /* To indicate 2 GiB card, BLOCK_LEN shall be 1024 bytes */
577     if (size == SDSC_MAX_CAPACITY) {
578         hwblock_shift += 1;
579     }
580     csize = (size >> (CMULT_SHIFT + hwblock_shift)) - 1;
581 
582     if (size <= SDSC_MAX_CAPACITY) { /* Standard Capacity SD */
583         sd->csd[0] = 0x00;      /* CSD structure */
584         sd->csd[1] = 0x26;      /* Data read access-time-1 */
585         sd->csd[2] = 0x00;      /* Data read access-time-2 */
586         sd->csd[3] = 0x32;      /* Max. data transfer rate: 25 MHz */
587         sd->csd[4] = 0x5f;      /* Card Command Classes */
588         sd->csd[5] = 0x50 |     /* Max. read data block length */
589             hwblock_shift;
590         sd->csd[6] = 0xe0 |     /* Partial block for read allowed */
591             ((csize >> 10) & 0x03);
592         sd->csd[7] = 0x00 |     /* Device size */
593             ((csize >> 2) & 0xff);
594         sd->csd[8] = 0x3f |     /* Max. read current */
595             ((csize << 6) & 0xc0);
596         sd->csd[9] = 0xfc |     /* Max. write current */
597             ((CMULT_SHIFT - 2) >> 1);
598         sd->csd[10] = 0x40 |    /* Erase sector size */
599             (((CMULT_SHIFT - 2) << 7) & 0x80) | (sectsize >> 1);
600         sd->csd[11] = 0x00 |    /* Write protect group size */
601             ((sectsize << 7) & 0x80) | wpsize;
602         sd->csd[12] = 0x90 |    /* Write speed factor */
603             (hwblock_shift >> 2);
604         sd->csd[13] = 0x20 |    /* Max. write data block length */
605             ((hwblock_shift << 6) & 0xc0);
606         sd->csd[14] = 0x00;     /* File format group */
607     } else {                    /* SDHC */
608         size /= 512 * KiB;
609         size -= 1;
610         sd->csd[0] = 0x40;
611         sd->csd[1] = 0x0e;
612         sd->csd[2] = 0x00;
613         sd->csd[3] = 0x32;
614         sd->csd[4] = 0x5b;
615         sd->csd[5] = 0x59;
616         sd->csd[6] = 0x00;
617         st24_be_p(&sd->csd[7], size);
618         sd->csd[10] = 0x7f;
619         sd->csd[11] = 0x80;
620         sd->csd[12] = 0x0a;
621         sd->csd[13] = 0x40;
622         sd->csd[14] = 0x00;
623     }
624     sd->csd[15] = (sd_crc7(sd->csd, 15) << 1) | 1;
625 }
626 
627 /* Relative Card Address register */
628 
629 static void sd_set_rca(SDState *sd, uint16_t value)
630 {
631     trace_sdcard_set_rca(value);
632     sd->rca = value;
633 }
634 
635 static uint16_t sd_req_get_rca(SDState *s, SDRequest req)
636 {
637     switch (s->proto->cmd[req.cmd].type) {
638     case sd_ac:
639     case sd_adtc:
640         return req.arg >> 16;
641     case sd_spi:
642     default:
643         g_assert_not_reached();
644     }
645 }
646 
647 static bool sd_req_rca_same(SDState *s, SDRequest req)
648 {
649     return sd_req_get_rca(s, req) == s->rca;
650 }
651 
652 /* Card Status register */
653 
654 FIELD(CSR, AKE_SEQ_ERROR,               3,  1)
655 FIELD(CSR, APP_CMD,                     5,  1)
656 FIELD(CSR, FX_EVENT,                    6,  1)
657 FIELD(CSR, SWITCH_ERROR,                7,  1)
658 FIELD(CSR, READY_FOR_DATA,              8,  1)
659 FIELD(CSR, CURRENT_STATE,               9,  4)
660 FIELD(CSR, ERASE_RESET,                13,  1)
661 FIELD(CSR, CARD_ECC_DISABLED,          14,  1)
662 FIELD(CSR, WP_ERASE_SKIP,              15,  1)
663 FIELD(CSR, CSD_OVERWRITE,              16,  1)
664 FIELD(CSR, DEFERRED_RESPONSE,          17,  1)
665 FIELD(CSR, ERROR,                      19,  1)
666 FIELD(CSR, CC_ERROR,                   20,  1)
667 FIELD(CSR, CARD_ECC_FAILED,            21,  1)
668 FIELD(CSR, ILLEGAL_COMMAND,            22,  1)
669 FIELD(CSR, COM_CRC_ERROR,              23,  1)
670 FIELD(CSR, LOCK_UNLOCK_FAILED,         24,  1)
671 FIELD(CSR, CARD_IS_LOCKED,             25,  1)
672 FIELD(CSR, WP_VIOLATION,               26,  1)
673 FIELD(CSR, ERASE_PARAM,                27,  1)
674 FIELD(CSR, ERASE_SEQ_ERROR,            28,  1)
675 FIELD(CSR, BLOCK_LEN_ERROR,            29,  1)
676 FIELD(CSR, ADDRESS_ERROR,              30,  1)
677 FIELD(CSR, OUT_OF_RANGE,               31,  1)
678 
679 /* Card status bits, split by clear condition:
680  * A : According to the card current state
681  * B : Always related to the previous command
682  * C : Cleared by read
683  */
684 #define CARD_STATUS_A           (R_CSR_READY_FOR_DATA_MASK \
685                                | R_CSR_CARD_ECC_DISABLED_MASK \
686                                | R_CSR_CARD_IS_LOCKED_MASK)
687 #define CARD_STATUS_B           (R_CSR_CURRENT_STATE_MASK \
688                                | R_CSR_ILLEGAL_COMMAND_MASK \
689                                | R_CSR_COM_CRC_ERROR_MASK)
690 #define CARD_STATUS_C           (R_CSR_AKE_SEQ_ERROR_MASK \
691                                | R_CSR_APP_CMD_MASK \
692                                | R_CSR_ERASE_RESET_MASK \
693                                | R_CSR_WP_ERASE_SKIP_MASK \
694                                | R_CSR_CSD_OVERWRITE_MASK \
695                                | R_CSR_ERROR_MASK \
696                                | R_CSR_CC_ERROR_MASK \
697                                | R_CSR_CARD_ECC_FAILED_MASK \
698                                | R_CSR_LOCK_UNLOCK_FAILED_MASK \
699                                | R_CSR_WP_VIOLATION_MASK \
700                                | R_CSR_ERASE_PARAM_MASK \
701                                | R_CSR_ERASE_SEQ_ERROR_MASK \
702                                | R_CSR_BLOCK_LEN_ERROR_MASK \
703                                | R_CSR_ADDRESS_ERROR_MASK \
704                                | R_CSR_OUT_OF_RANGE_MASK)
705 
706 static void sd_set_cardstatus(SDState *sd)
707 {
708     sd->card_status = READY_FOR_DATA;
709 }
710 
711 static void sd_set_sdstatus(SDState *sd)
712 {
713     memset(sd->sd_status, 0, 64);
714 }
715 
716 static const uint8_t sd_tuning_block_pattern4[64] = {
717     /*
718      * See: Physical Layer Simplified Specification Version 3.01,
719      * Table 4-2.
720      */
721     0xff, 0x0f, 0xff, 0x00,     0x0f, 0xfc, 0xc3, 0xcc,
722     0xc3, 0x3c, 0xcc, 0xff,     0xfe, 0xff, 0xfe, 0xef,
723     0xff, 0xdf, 0xff, 0xdd,     0xff, 0xfb, 0xff, 0xfb,
724     0xbf, 0xff, 0x7f, 0xff,     0x77, 0xf7, 0xbd, 0xef,
725     0xff, 0xf0, 0xff, 0xf0,     0x0f, 0xfc, 0xcc, 0x3c,
726     0xcc, 0x33, 0xcc, 0xcf,     0xff, 0xef, 0xff, 0xee,
727     0xff, 0xfd, 0xff, 0xfd,     0xdf, 0xff, 0xbf, 0xff,
728     0xbb, 0xff, 0xf7, 0xff,     0xf7, 0x7f, 0x7b, 0xde
729 };
730 
731 static int sd_req_crc_validate(SDRequest *req)
732 {
733     uint8_t buffer[5];
734     buffer[0] = 0x40 | req->cmd;
735     stl_be_p(&buffer[1], req->arg);
736     return 0;
737     return sd_crc7(buffer, 5) != req->crc;  /* TODO */
738 }
739 
740 static void sd_response_r1_make(SDState *sd, uint8_t *response)
741 {
742     stl_be_p(response, sd->card_status);
743 
744     /* Clear the "clear on read" status bits */
745     sd->card_status &= ~CARD_STATUS_C;
746 }
747 
748 static void sd_response_r3_make(SDState *sd, uint8_t *response)
749 {
750     stl_be_p(response, sd->ocr & ACMD41_R3_MASK);
751 }
752 
753 static void sd_response_r6_make(SDState *sd, uint8_t *response)
754 {
755     uint16_t status;
756 
757     status = ((sd->card_status >> 8) & 0xc000) |
758              ((sd->card_status >> 6) & 0x2000) |
759               (sd->card_status & 0x1fff);
760     sd->card_status &= ~(CARD_STATUS_C & 0xc81fff);
761     stw_be_p(response + 0, sd->rca);
762     stw_be_p(response + 2, status);
763 }
764 
765 static void sd_response_r7_make(SDState *sd, uint8_t *response)
766 {
767     stl_be_p(response, sd->vhs);
768 }
769 
770 static uint32_t sd_blk_len(SDState *sd)
771 {
772     if (FIELD_EX32(sd->ocr, OCR, CARD_CAPACITY)) {
773         return 1 << HWBLOCK_SHIFT;
774     }
775     return sd->blk_len;
776 }
777 
778 /*
779  * This requires a disk image that has two boot partitions inserted at the
780  * beginning of it. The size of the boot partitions is the "boot-size"
781  * property.
782  */
783 static uint32_t sd_bootpart_offset(SDState *sd)
784 {
785     unsigned partition_access;
786 
787     if (!sd->boot_part_size || !sd_is_emmc(sd)) {
788         return 0;
789     }
790 
791     partition_access = sd->ext_csd[EXT_CSD_PART_CONFIG]
792                                  & EXT_CSD_PART_CONFIG_ACC_MASK;
793     switch (partition_access) {
794     case EXT_CSD_PART_CONFIG_ACC_DEFAULT:
795         return sd->boot_part_size * 2;
796     case EXT_CSD_PART_CONFIG_ACC_BOOT0:
797         return 0;
798     case EXT_CSD_PART_CONFIG_ACC_BOOT0 + 1:
799         return sd->boot_part_size * 1;
800     default:
801          g_assert_not_reached();
802     }
803 }
804 
805 static uint64_t sd_req_get_address(SDState *sd, SDRequest req)
806 {
807     uint64_t addr;
808 
809     if (FIELD_EX32(sd->ocr, OCR, CARD_CAPACITY)) {
810         addr = (uint64_t) req.arg << HWBLOCK_SHIFT;
811     } else {
812         addr = req.arg;
813     }
814     trace_sdcard_req_addr(req.arg, addr);
815     return addr;
816 }
817 
818 static inline uint64_t sd_addr_to_wpnum(uint64_t addr)
819 {
820     return addr >> (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT);
821 }
822 
823 static void sd_reset(DeviceState *dev)
824 {
825     SDState *sd = SDMMC_COMMON(dev);
826     SDCardClass *sc = SDMMC_COMMON_GET_CLASS(sd);
827     uint64_t size;
828     uint64_t sect;
829 
830     trace_sdcard_reset();
831     if (sd->blk) {
832         blk_get_geometry(sd->blk, &sect);
833     } else {
834         sect = 0;
835     }
836     size = sect << HWBLOCK_SHIFT;
837     size -= sd_bootpart_offset(sd);
838 
839     sect = sd_addr_to_wpnum(size) + 1;
840 
841     sd->state = sd_idle_state;
842 
843     /* card registers */
844     sd->rca = sd_is_emmc(sd) ? 0x0001 : 0x0000;
845     sd->size = size;
846     sd_set_ocr(sd);
847     sd_set_scr(sd);
848     sc->set_cid(sd);
849     sc->set_csd(sd, size);
850     sd_set_cardstatus(sd);
851     sd_set_sdstatus(sd);
852 
853     g_free(sd->wp_group_bmap);
854     sd->wp_switch = sd->blk ? !blk_is_writable(sd->blk) : false;
855     sd->wp_group_bits = sect;
856     sd->wp_group_bmap = bitmap_new(sd->wp_group_bits);
857     memset(sd->function_group, 0, sizeof(sd->function_group));
858     sd->erase_start = INVALID_ADDRESS;
859     sd->erase_end = INVALID_ADDRESS;
860     sd->blk_len = 0x200;
861     sd->pwd_len = 0;
862     sd->expecting_acmd = false;
863     sd->dat_lines = 0xf;
864     sd->cmd_line = true;
865     sd->multi_blk_cnt = 0;
866 }
867 
868 static bool sd_get_inserted(SDState *sd)
869 {
870     return sd->blk && blk_is_inserted(sd->blk);
871 }
872 
873 static bool sd_get_readonly(SDState *sd)
874 {
875     return sd->wp_switch;
876 }
877 
878 static void sd_cardchange(void *opaque, bool load, Error **errp)
879 {
880     SDState *sd = opaque;
881     DeviceState *dev = DEVICE(sd);
882     SDBus *sdbus;
883     bool inserted = sd_get_inserted(sd);
884     bool readonly = sd_get_readonly(sd);
885 
886     if (inserted) {
887         trace_sdcard_inserted(readonly);
888         sd_reset(dev);
889     } else {
890         trace_sdcard_ejected();
891     }
892 
893     if (sd->me_no_qdev_me_kill_mammoth_with_rocks) {
894         qemu_set_irq(sd->inserted_cb, inserted);
895         if (inserted) {
896             qemu_set_irq(sd->readonly_cb, readonly);
897         }
898     } else {
899         sdbus = SD_BUS(qdev_get_parent_bus(dev));
900         sdbus_set_inserted(sdbus, inserted);
901         if (inserted) {
902             sdbus_set_readonly(sdbus, readonly);
903         }
904     }
905 }
906 
907 static const BlockDevOps sd_block_ops = {
908     .change_media_cb = sd_cardchange,
909 };
910 
911 static bool sd_ocr_vmstate_needed(void *opaque)
912 {
913     SDState *sd = opaque;
914 
915     /* Include the OCR state (and timer) if it is not yet powered up */
916     return !FIELD_EX32(sd->ocr, OCR, CARD_POWER_UP);
917 }
918 
919 static const VMStateDescription sd_ocr_vmstate = {
920     .name = "sd-card/ocr-state",
921     .version_id = 1,
922     .minimum_version_id = 1,
923     .needed = sd_ocr_vmstate_needed,
924     .fields = (const VMStateField[]) {
925         VMSTATE_UINT32(ocr, SDState),
926         VMSTATE_TIMER_PTR(ocr_power_timer, SDState),
927         VMSTATE_END_OF_LIST()
928     },
929 };
930 
931 static bool vmstate_needed_for_emmc(void *opaque)
932 {
933     SDState *sd = opaque;
934 
935     return sd_is_emmc(sd);
936 }
937 
938 static const VMStateDescription emmc_extcsd_vmstate = {
939     .name = "sd-card/ext_csd_modes-state",
940     .version_id = 1,
941     .minimum_version_id = 1,
942     .needed = vmstate_needed_for_emmc,
943     .fields = (const VMStateField[]) {
944         VMSTATE_UINT8_ARRAY(ext_csd_rw, SDState, 192),
945         VMSTATE_END_OF_LIST()
946     },
947 };
948 
949 static int sd_vmstate_pre_load(void *opaque)
950 {
951     SDState *sd = opaque;
952 
953     /* If the OCR state is not included (prior versions, or not
954      * needed), then the OCR must be set as powered up. If the OCR state
955      * is included, this will be replaced by the state restore.
956      */
957     sd_ocr_powerup(sd);
958 
959     return 0;
960 }
961 
962 static const VMStateDescription sd_vmstate = {
963     .name = "sd-card",
964     .version_id = 2,
965     .minimum_version_id = 2,
966     .pre_load = sd_vmstate_pre_load,
967     .fields = (const VMStateField[]) {
968         VMSTATE_UINT32(mode, SDState),
969         VMSTATE_INT32(state, SDState),
970         VMSTATE_UINT8_ARRAY(cid, SDState, 16),
971         VMSTATE_UINT8_ARRAY(csd, SDState, 16),
972         VMSTATE_UINT16(rca, SDState),
973         VMSTATE_UINT32(card_status, SDState),
974         VMSTATE_PARTIAL_BUFFER(sd_status, SDState, 1),
975         VMSTATE_UINT32(vhs, SDState),
976         VMSTATE_BITMAP(wp_group_bmap, SDState, 0, wp_group_bits),
977         VMSTATE_UINT32(blk_len, SDState),
978         VMSTATE_UINT32(multi_blk_cnt, SDState),
979         VMSTATE_UINT32(erase_start, SDState),
980         VMSTATE_UINT32(erase_end, SDState),
981         VMSTATE_UINT8_ARRAY(pwd, SDState, 16),
982         VMSTATE_UINT32(pwd_len, SDState),
983         VMSTATE_UINT8_ARRAY(function_group, SDState, 6),
984         VMSTATE_UINT8(current_cmd, SDState),
985         VMSTATE_BOOL(expecting_acmd, SDState),
986         VMSTATE_UINT32(blk_written, SDState),
987         VMSTATE_UINT64(data_start, SDState),
988         VMSTATE_UINT32(data_offset, SDState),
989         VMSTATE_UINT8_ARRAY(data, SDState, 512),
990         VMSTATE_UNUSED_V(1, 512),
991         VMSTATE_BOOL(enable, SDState),
992         VMSTATE_END_OF_LIST()
993     },
994     .subsections = (const VMStateDescription * const []) {
995         &sd_ocr_vmstate,
996         &emmc_extcsd_vmstate,
997         NULL
998     },
999 };
1000 
1001 /* Legacy initialization function for use by non-qdevified callers */
1002 SDState *sd_init(BlockBackend *blk, bool is_spi)
1003 {
1004     Object *obj;
1005     DeviceState *dev;
1006     SDState *sd;
1007     Error *err = NULL;
1008 
1009     obj = object_new(is_spi ? TYPE_SD_CARD_SPI : TYPE_SD_CARD);
1010     dev = DEVICE(obj);
1011     if (!qdev_prop_set_drive_err(dev, "drive", blk, &err)) {
1012         error_reportf_err(err, "sd_init failed: ");
1013         return NULL;
1014     }
1015 
1016     /*
1017      * Realizing the device properly would put it into the QOM
1018      * composition tree even though it is not plugged into an
1019      * appropriate bus.  That's a no-no.  Hide the device from
1020      * QOM/qdev, and call its qdev realize callback directly.
1021      */
1022     object_ref(obj);
1023     object_unparent(obj);
1024     sd_realize(dev, &err);
1025     if (err) {
1026         error_reportf_err(err, "sd_init failed: ");
1027         return NULL;
1028     }
1029 
1030     sd = SD_CARD(dev);
1031     sd->me_no_qdev_me_kill_mammoth_with_rocks = true;
1032     return sd;
1033 }
1034 
1035 void sd_set_cb(SDState *sd, qemu_irq readonly, qemu_irq insert)
1036 {
1037     sd->readonly_cb = readonly;
1038     sd->inserted_cb = insert;
1039     qemu_set_irq(readonly, sd->blk ? !blk_is_writable(sd->blk) : 0);
1040     qemu_set_irq(insert, sd->blk ? blk_is_inserted(sd->blk) : 0);
1041 }
1042 
1043 static void sd_blk_read(SDState *sd, uint64_t addr, uint32_t len)
1044 {
1045     trace_sdcard_read_block(addr, len);
1046     addr += sd_bootpart_offset(sd);
1047     if (!sd->blk || blk_pread(sd->blk, addr, len, sd->data, 0) < 0) {
1048         fprintf(stderr, "sd_blk_read: read error on host side\n");
1049     }
1050 }
1051 
1052 static void sd_blk_write(SDState *sd, uint64_t addr, uint32_t len)
1053 {
1054     trace_sdcard_write_block(addr, len);
1055     addr += sd_bootpart_offset(sd);
1056     if (!sd->blk || blk_pwrite(sd->blk, addr, len, sd->data, 0) < 0) {
1057         fprintf(stderr, "sd_blk_write: write error on host side\n");
1058     }
1059 }
1060 
1061 static void sd_erase(SDState *sd)
1062 {
1063     uint64_t erase_start = sd->erase_start;
1064     uint64_t erase_end = sd->erase_end;
1065     bool sdsc = true;
1066     uint64_t wpnum;
1067     uint64_t erase_addr;
1068     int erase_len = 1 << HWBLOCK_SHIFT;
1069 
1070     trace_sdcard_erase(sd->erase_start, sd->erase_end);
1071     if (sd->erase_start == INVALID_ADDRESS
1072             || sd->erase_end == INVALID_ADDRESS) {
1073         sd->card_status |= ERASE_SEQ_ERROR;
1074         sd->erase_start = INVALID_ADDRESS;
1075         sd->erase_end = INVALID_ADDRESS;
1076         return;
1077     }
1078 
1079     if (FIELD_EX32(sd->ocr, OCR, CARD_CAPACITY)) {
1080         /* High capacity memory card: erase units are 512 byte blocks */
1081         erase_start <<= HWBLOCK_SHIFT;
1082         erase_end <<= HWBLOCK_SHIFT;
1083         sdsc = false;
1084     }
1085 
1086     if (erase_start > sd->size || erase_end > sd->size) {
1087         sd->card_status |= OUT_OF_RANGE;
1088         sd->erase_start = INVALID_ADDRESS;
1089         sd->erase_end = INVALID_ADDRESS;
1090         return;
1091     }
1092 
1093     sd->erase_start = INVALID_ADDRESS;
1094     sd->erase_end = INVALID_ADDRESS;
1095     sd->csd[14] |= 0x40;
1096 
1097     memset(sd->data, 0xff, erase_len);
1098     for (erase_addr = erase_start; erase_addr <= erase_end;
1099          erase_addr += erase_len) {
1100         if (sdsc) {
1101             /* Only SDSC cards support write protect groups */
1102             wpnum = sd_addr_to_wpnum(erase_addr);
1103             assert(wpnum < sd->wp_group_bits);
1104             if (test_bit(wpnum, sd->wp_group_bmap)) {
1105                 sd->card_status |= WP_ERASE_SKIP;
1106                 continue;
1107             }
1108         }
1109         sd_blk_write(sd, erase_addr, erase_len);
1110     }
1111 }
1112 
1113 static uint32_t sd_wpbits(SDState *sd, uint64_t addr)
1114 {
1115     uint32_t i, wpnum;
1116     uint32_t ret = 0;
1117 
1118     wpnum = sd_addr_to_wpnum(addr);
1119 
1120     for (i = 0; i < 32; i++, wpnum++, addr += WPGROUP_SIZE) {
1121         if (addr >= sd->size) {
1122             /*
1123              * If the addresses of the last groups are outside the valid range,
1124              * then the corresponding write protection bits shall be set to 0.
1125              */
1126             continue;
1127         }
1128         assert(wpnum < sd->wp_group_bits);
1129         if (test_bit(wpnum, sd->wp_group_bmap)) {
1130             ret |= (1 << i);
1131         }
1132     }
1133 
1134     return ret;
1135 }
1136 
1137 enum ExtCsdAccessMode {
1138     EXT_CSD_ACCESS_MODE_COMMAND_SET = 0,
1139     EXT_CSD_ACCESS_MODE_SET_BITS    = 1,
1140     EXT_CSD_ACCESS_MODE_CLEAR_BITS  = 2,
1141     EXT_CSD_ACCESS_MODE_WRITE_BYTE  = 3
1142 };
1143 
1144 static void emmc_function_switch(SDState *sd, uint32_t arg)
1145 {
1146     uint8_t access = extract32(arg, 24, 2);
1147     uint8_t index = extract32(arg, 16, 8);
1148     uint8_t value = extract32(arg, 8, 8);
1149     uint8_t b = sd->ext_csd[index];
1150 
1151     trace_sdcard_switch(access, index, value, extract32(arg, 0, 2));
1152 
1153     if (index >= 192) {
1154         qemu_log_mask(LOG_GUEST_ERROR, "MMC switching illegal offset\n");
1155         sd->card_status |= R_CSR_SWITCH_ERROR_MASK;
1156         return;
1157     }
1158 
1159     switch (access) {
1160     case EXT_CSD_ACCESS_MODE_COMMAND_SET:
1161         qemu_log_mask(LOG_UNIMP, "MMC Command set switching not supported\n");
1162         return;
1163     case EXT_CSD_ACCESS_MODE_SET_BITS:
1164         b |= value;
1165         break;
1166     case EXT_CSD_ACCESS_MODE_CLEAR_BITS:
1167         b &= ~value;
1168         break;
1169     case EXT_CSD_ACCESS_MODE_WRITE_BYTE:
1170         b = value;
1171         break;
1172     }
1173 
1174     trace_sdcard_ext_csd_update(index, sd->ext_csd[index], b);
1175     sd->ext_csd[index] = b;
1176 }
1177 
1178 static void sd_function_switch(SDState *sd, uint32_t arg)
1179 {
1180     int i, mode, new_func;
1181     mode = !!(arg & 0x80000000);
1182 
1183     sd->data[0] = 0x00;     /* Maximum current consumption */
1184     sd->data[1] = 0x01;
1185     sd->data[2] = 0x80;     /* Supported group 6 functions */
1186     sd->data[3] = 0x01;
1187     sd->data[4] = 0x80;     /* Supported group 5 functions */
1188     sd->data[5] = 0x01;
1189     sd->data[6] = 0x80;     /* Supported group 4 functions */
1190     sd->data[7] = 0x01;
1191     sd->data[8] = 0x80;     /* Supported group 3 functions */
1192     sd->data[9] = 0x01;
1193     sd->data[10] = 0x80;    /* Supported group 2 functions */
1194     sd->data[11] = 0x43;
1195     sd->data[12] = 0x80;    /* Supported group 1 functions */
1196     sd->data[13] = 0x03;
1197 
1198     memset(&sd->data[14], 0, 3);
1199     for (i = 0; i < 6; i ++) {
1200         new_func = (arg >> (i * 4)) & 0x0f;
1201         if (mode && new_func != 0x0f)
1202             sd->function_group[i] = new_func;
1203         sd->data[16 - (i >> 1)] |= new_func << ((i % 2) * 4);
1204     }
1205     memset(&sd->data[17], 0, 47);
1206 }
1207 
1208 static inline bool sd_wp_addr(SDState *sd, uint64_t addr)
1209 {
1210     return test_bit(sd_addr_to_wpnum(addr), sd->wp_group_bmap);
1211 }
1212 
1213 static void sd_lock_command(SDState *sd)
1214 {
1215     int erase, lock, clr_pwd, set_pwd, pwd_len;
1216     erase = !!(sd->data[0] & 0x08);
1217     lock = sd->data[0] & 0x04;
1218     clr_pwd = sd->data[0] & 0x02;
1219     set_pwd = sd->data[0] & 0x01;
1220 
1221     if (sd->blk_len > 1)
1222         pwd_len = sd->data[1];
1223     else
1224         pwd_len = 0;
1225 
1226     if (lock) {
1227         trace_sdcard_lock();
1228     } else {
1229         trace_sdcard_unlock();
1230     }
1231     if (erase) {
1232         if (!(sd->card_status & CARD_IS_LOCKED) || sd->blk_len > 1 ||
1233                         set_pwd || clr_pwd || lock || sd->wp_switch ||
1234                         (sd->csd[14] & 0x20)) {
1235             sd->card_status |= LOCK_UNLOCK_FAILED;
1236             return;
1237         }
1238         bitmap_zero(sd->wp_group_bmap, sd->wp_group_bits);
1239         sd->csd[14] &= ~0x10;
1240         sd->card_status &= ~CARD_IS_LOCKED;
1241         sd->pwd_len = 0;
1242         /* Erasing the entire card here! */
1243         fprintf(stderr, "SD: Card force-erased by CMD42\n");
1244         return;
1245     }
1246 
1247     if (sd->blk_len < 2 + pwd_len ||
1248                     pwd_len <= sd->pwd_len ||
1249                     pwd_len > sd->pwd_len + 16) {
1250         sd->card_status |= LOCK_UNLOCK_FAILED;
1251         return;
1252     }
1253 
1254     if (sd->pwd_len && memcmp(sd->pwd, sd->data + 2, sd->pwd_len)) {
1255         sd->card_status |= LOCK_UNLOCK_FAILED;
1256         return;
1257     }
1258 
1259     pwd_len -= sd->pwd_len;
1260     if ((pwd_len && !set_pwd) ||
1261                     (clr_pwd && (set_pwd || lock)) ||
1262                     (lock && !sd->pwd_len && !set_pwd) ||
1263                     (!set_pwd && !clr_pwd &&
1264                      (((sd->card_status & CARD_IS_LOCKED) && lock) ||
1265                       (!(sd->card_status & CARD_IS_LOCKED) && !lock)))) {
1266         sd->card_status |= LOCK_UNLOCK_FAILED;
1267         return;
1268     }
1269 
1270     if (set_pwd) {
1271         memcpy(sd->pwd, sd->data + 2 + sd->pwd_len, pwd_len);
1272         sd->pwd_len = pwd_len;
1273     }
1274 
1275     if (clr_pwd) {
1276         sd->pwd_len = 0;
1277     }
1278 
1279     if (lock)
1280         sd->card_status |= CARD_IS_LOCKED;
1281     else
1282         sd->card_status &= ~CARD_IS_LOCKED;
1283 }
1284 
1285 static bool address_in_range(SDState *sd, const char *desc,
1286                              uint64_t addr, uint32_t length)
1287 {
1288     if (addr + length > sd->size) {
1289         qemu_log_mask(LOG_GUEST_ERROR,
1290                       "%s offset %"PRIu64" > card %"PRIu64" [%%%u]\n",
1291                       desc, addr, sd->size, length);
1292         sd->card_status |= ADDRESS_ERROR;
1293         return false;
1294     }
1295     return true;
1296 }
1297 
1298 static sd_rsp_type_t sd_invalid_state_for_cmd(SDState *sd, SDRequest req)
1299 {
1300     qemu_log_mask(LOG_GUEST_ERROR, "%s: CMD%i in a wrong state: %s (spec %s)\n",
1301                   sd->proto->name, req.cmd, sd_state_name(sd->state),
1302                   sd_version_str(sd->spec_version));
1303 
1304     return sd_illegal;
1305 }
1306 
1307 static sd_rsp_type_t sd_invalid_mode_for_cmd(SDState *sd, SDRequest req)
1308 {
1309     qemu_log_mask(LOG_GUEST_ERROR, "%s: CMD%i in a wrong mode: %s (spec %s)\n",
1310                   sd->proto->name, req.cmd, sd_mode_name(sd->mode),
1311                   sd_version_str(sd->spec_version));
1312 
1313     return sd_illegal;
1314 }
1315 
1316 static sd_rsp_type_t sd_cmd_illegal(SDState *sd, SDRequest req)
1317 {
1318     qemu_log_mask(LOG_GUEST_ERROR, "%s: Unknown CMD%i for spec %s\n",
1319                   sd->proto->name, req.cmd,
1320                   sd_version_str(sd->spec_version));
1321 
1322     return sd_illegal;
1323 }
1324 
1325 /* Commands that are recognised but not yet implemented. */
1326 static sd_rsp_type_t sd_cmd_unimplemented(SDState *sd, SDRequest req)
1327 {
1328     qemu_log_mask(LOG_UNIMP, "%s: CMD%i not implemented\n",
1329                   sd->proto->name, req.cmd);
1330 
1331     return sd_illegal;
1332 }
1333 
1334 static sd_rsp_type_t sd_cmd_optional(SDState *sd, SDRequest req)
1335 {
1336     qemu_log_mask(LOG_UNIMP, "%s: Optional CMD%i not implemented\n",
1337                   sd->proto->name, req.cmd);
1338 
1339     return sd_illegal;
1340 }
1341 
1342 /* Configure fields for following sd_generic_write_byte() calls */
1343 static sd_rsp_type_t sd_cmd_to_receivingdata(SDState *sd, SDRequest req,
1344                                              uint64_t start, size_t size)
1345 {
1346     if (sd->state != sd_transfer_state) {
1347         return sd_invalid_state_for_cmd(sd, req);
1348     }
1349     sd->state = sd_receivingdata_state;
1350     sd->data_start = start;
1351     sd->data_offset = 0;
1352     /* sd->data[] used as receive buffer */
1353     sd->data_size = size ?: sizeof(sd->data);
1354     return sd_r1;
1355 }
1356 
1357 /* Configure fields for following sd_generic_read_byte() calls */
1358 static sd_rsp_type_t sd_cmd_to_sendingdata(SDState *sd, SDRequest req,
1359                                            uint64_t start,
1360                                            const void *data, size_t size)
1361 {
1362     if (sd->state != sd_transfer_state) {
1363         sd_invalid_state_for_cmd(sd, req);
1364     }
1365 
1366     sd->state = sd_sendingdata_state;
1367     sd->data_start = start;
1368     sd->data_offset = 0;
1369     if (data) {
1370         assert(size > 0 && size <= sizeof(sd->data));
1371         memcpy(sd->data, data, size);
1372     }
1373     if (size) {
1374         sd->data_size = size;
1375     }
1376     return sd_r1;
1377 }
1378 
1379 /* CMD0 */
1380 static sd_rsp_type_t sd_cmd_GO_IDLE_STATE(SDState *sd, SDRequest req)
1381 {
1382     if (sd->state == sd_sleep_state) {
1383         switch (req.arg) {
1384         case 0x00000000:
1385         case 0xf0f0f0f0:
1386             break;
1387         default:
1388             return sd_r0;
1389         }
1390     }
1391     if (sd->state != sd_inactive_state) {
1392         sd->state = sd_idle_state;
1393         sd_reset(DEVICE(sd));
1394     }
1395 
1396     return sd_is_spi(sd) ? sd_r1 : sd_r0;
1397 }
1398 
1399 /* CMD1 */
1400 static sd_rsp_type_t spi_cmd_SEND_OP_COND(SDState *sd, SDRequest req)
1401 {
1402     sd->state = sd_transfer_state;
1403 
1404     return sd_r1;
1405 }
1406 
1407 /* CMD2 */
1408 static sd_rsp_type_t sd_cmd_ALL_SEND_CID(SDState *sd, SDRequest req)
1409 {
1410     switch (sd->state) {
1411     case sd_ready_state:
1412         sd->state = sd_identification_state;
1413         return sd_r2_i;
1414     default:
1415         return sd_invalid_state_for_cmd(sd, req);
1416     }
1417 }
1418 
1419 /* CMD3 */
1420 static sd_rsp_type_t sd_cmd_SEND_RELATIVE_ADDR(SDState *sd, SDRequest req)
1421 {
1422     uint16_t random_rca;
1423 
1424     switch (sd->state) {
1425     case sd_identification_state:
1426     case sd_standby_state:
1427         sd->state = sd_standby_state;
1428         qemu_guest_getrandom_nofail(&random_rca, sizeof(random_rca));
1429         sd_set_rca(sd, random_rca);
1430         return sd_r6;
1431 
1432     default:
1433         return sd_invalid_state_for_cmd(sd, req);
1434     }
1435 }
1436 
1437 static sd_rsp_type_t emmc_cmd_SET_RELATIVE_ADDR(SDState *sd, SDRequest req)
1438 {
1439     switch (sd->state) {
1440     case sd_identification_state:
1441     case sd_standby_state:
1442         sd->state = sd_standby_state;
1443         sd_set_rca(sd, req.arg >> 16);
1444         return sd_r1;
1445 
1446     default:
1447         return sd_invalid_state_for_cmd(sd, req);
1448     }
1449 }
1450 
1451 /* CMD5 */
1452 static sd_rsp_type_t emmc_cmd_sleep_awake(SDState *sd, SDRequest req)
1453 {
1454     bool do_sleep = extract32(req.arg, 15, 1);
1455 
1456     switch (sd->state) {
1457     case sd_sleep_state:
1458         if (!do_sleep) {
1459             /* Awake */
1460             sd->state = sd_standby_state;
1461         }
1462         return sd_r1b;
1463 
1464     case sd_standby_state:
1465         if (do_sleep) {
1466             sd->state = sd_sleep_state;
1467         }
1468         return sd_r1b;
1469 
1470     default:
1471         return sd_invalid_state_for_cmd(sd, req);
1472     }
1473 }
1474 
1475 /* CMD6 */
1476 static sd_rsp_type_t sd_cmd_SWITCH_FUNCTION(SDState *sd, SDRequest req)
1477 {
1478     if (sd->mode != sd_data_transfer_mode) {
1479         return sd_invalid_mode_for_cmd(sd, req);
1480     }
1481     if (sd->state != sd_transfer_state) {
1482         return sd_invalid_state_for_cmd(sd, req);
1483     }
1484 
1485     sd_function_switch(sd, req.arg);
1486     return sd_cmd_to_sendingdata(sd, req, 0, NULL, 64);
1487 }
1488 
1489 static sd_rsp_type_t emmc_cmd_SWITCH(SDState *sd, SDRequest req)
1490 {
1491     switch (sd->state) {
1492     case sd_transfer_state:
1493         sd->state = sd_programming_state;
1494         emmc_function_switch(sd, req.arg);
1495         sd->state = sd_transfer_state;
1496         return sd_r1b;
1497     default:
1498         return sd_invalid_state_for_cmd(sd, req);
1499     }
1500 }
1501 
1502 /* CMD7 */
1503 static sd_rsp_type_t sd_cmd_DE_SELECT_CARD(SDState *sd, SDRequest req)
1504 {
1505     bool same_rca = sd_req_rca_same(sd, req);
1506 
1507     switch (sd->state) {
1508     case sd_standby_state:
1509         if (!same_rca) {
1510             return sd_r0;
1511         }
1512         sd->state = sd_transfer_state;
1513         return sd_r1b;
1514 
1515     case sd_transfer_state:
1516     case sd_sendingdata_state:
1517         if (same_rca) {
1518             break;
1519         }
1520         sd->state = sd_standby_state;
1521         return sd_r1b;
1522 
1523     case sd_disconnect_state:
1524         if (!same_rca) {
1525             return sd_r0;
1526         }
1527         sd->state = sd_programming_state;
1528         return sd_r1b;
1529 
1530     case sd_programming_state:
1531         if (same_rca) {
1532             break;
1533         }
1534         sd->state = sd_disconnect_state;
1535         return sd_r1b;
1536 
1537     default:
1538         break;
1539     }
1540     return sd_invalid_state_for_cmd(sd, req);
1541 }
1542 
1543 /* CMD8 */
1544 static sd_rsp_type_t sd_cmd_SEND_IF_COND(SDState *sd, SDRequest req)
1545 {
1546     if (sd->spec_version < SD_PHY_SPECv2_00_VERS) {
1547         return sd_cmd_illegal(sd, req);
1548     }
1549     if (sd->state != sd_idle_state) {
1550         return sd_invalid_state_for_cmd(sd, req);
1551     }
1552     sd->vhs = 0;
1553 
1554     /* No response if not exactly one VHS bit is set.  */
1555     if (!(req.arg >> 8) || (req.arg >> (ctz32(req.arg & ~0xff) + 1))) {
1556         return sd_is_spi(sd) ? sd_r7 : sd_r0;
1557     }
1558 
1559     /* Accept.  */
1560     sd->vhs = req.arg;
1561     return sd_r7;
1562 }
1563 
1564 /* CMD8 */
1565 static sd_rsp_type_t emmc_cmd_SEND_EXT_CSD(SDState *sd, SDRequest req)
1566 {
1567     if (sd->state != sd_transfer_state) {
1568         return sd_invalid_state_for_cmd(sd, req);
1569     }
1570 
1571     return sd_cmd_to_sendingdata(sd, req, sd_req_get_address(sd, req),
1572                                  sd->ext_csd, sizeof(sd->ext_csd));
1573 }
1574 
1575 /* CMD9 */
1576 static sd_rsp_type_t spi_cmd_SEND_CSD(SDState *sd, SDRequest req)
1577 {
1578     if (sd->state != sd_standby_state) {
1579         return sd_invalid_state_for_cmd(sd, req);
1580     }
1581     return sd_cmd_to_sendingdata(sd, req, sd_req_get_address(sd, req),
1582                                  sd->csd, 16);
1583 }
1584 
1585 static sd_rsp_type_t sd_cmd_SEND_CSD(SDState *sd, SDRequest req)
1586 {
1587     if (sd->state != sd_standby_state) {
1588         return sd_invalid_state_for_cmd(sd, req);
1589     }
1590 
1591     return sd_req_rca_same(sd, req) ? sd_r2_s : sd_r0;
1592 }
1593 
1594 /* CMD10 */
1595 static sd_rsp_type_t spi_cmd_SEND_CID(SDState *sd, SDRequest req)
1596 {
1597     if (sd->state != sd_standby_state) {
1598         return sd_invalid_state_for_cmd(sd, req);
1599     }
1600     return sd_cmd_to_sendingdata(sd, req, sd_req_get_address(sd, req),
1601                                  sd->cid, 16);
1602 }
1603 
1604 static sd_rsp_type_t sd_cmd_SEND_CID(SDState *sd, SDRequest req)
1605 {
1606     if (sd->state != sd_standby_state) {
1607         return sd_invalid_state_for_cmd(sd, req);
1608     }
1609 
1610     return sd_req_rca_same(sd, req) ? sd_r2_i : sd_r0;
1611 }
1612 
1613 /* CMD12 */
1614 static sd_rsp_type_t sd_cmd_STOP_TRANSMISSION(SDState *sd, SDRequest req)
1615 {
1616     switch (sd->state) {
1617     case sd_sendingdata_state:
1618         sd->state = sd_transfer_state;
1619         return sd_r1b;
1620     case sd_receivingdata_state:
1621         sd->state = sd_programming_state;
1622         /* Bzzzzzzztt .... Operation complete.  */
1623         sd->state = sd_transfer_state;
1624         return sd_r1;
1625     default:
1626         return sd_invalid_state_for_cmd(sd, req);
1627     }
1628 }
1629 
1630 /* CMD13 */
1631 static sd_rsp_type_t sd_cmd_SEND_STATUS(SDState *sd, SDRequest req)
1632 {
1633     if (sd->mode != sd_data_transfer_mode) {
1634         return sd_invalid_mode_for_cmd(sd, req);
1635     }
1636 
1637     switch (sd->state) {
1638     case sd_standby_state:
1639     case sd_transfer_state:
1640     case sd_sendingdata_state:
1641     case sd_receivingdata_state:
1642     case sd_programming_state:
1643     case sd_disconnect_state:
1644         break;
1645     default:
1646         return sd_invalid_state_for_cmd(sd, req);
1647     }
1648 
1649     if (sd_is_spi(sd)) {
1650         return sd_r2_s;
1651     }
1652 
1653     return sd_req_rca_same(sd, req) ? sd_r1 : sd_r0;
1654 }
1655 
1656 /* CMD15 */
1657 static sd_rsp_type_t sd_cmd_GO_INACTIVE_STATE(SDState *sd, SDRequest req)
1658 {
1659     if (sd->mode != sd_data_transfer_mode) {
1660         return sd_invalid_mode_for_cmd(sd, req);
1661     }
1662     switch (sd->state) {
1663     case sd_standby_state:
1664     case sd_transfer_state:
1665     case sd_sendingdata_state:
1666     case sd_receivingdata_state:
1667     case sd_programming_state:
1668     case sd_disconnect_state:
1669         break;
1670     default:
1671         return sd_invalid_state_for_cmd(sd, req);
1672     }
1673     if (sd_req_rca_same(sd, req)) {
1674         sd->state = sd_inactive_state;
1675     }
1676 
1677     return sd_r0;
1678 }
1679 
1680 /* CMD16 */
1681 static sd_rsp_type_t sd_cmd_SET_BLOCKLEN(SDState *sd, SDRequest req)
1682 {
1683     if (sd->state != sd_transfer_state) {
1684         return sd_invalid_state_for_cmd(sd, req);
1685     }
1686     if (req.arg > (1 << HWBLOCK_SHIFT)) {
1687         sd->card_status |= BLOCK_LEN_ERROR;
1688     } else {
1689         trace_sdcard_set_blocklen(req.arg);
1690         sd->blk_len = req.arg;
1691     }
1692 
1693     return sd_r1;
1694 }
1695 
1696 /* CMD17 */
1697 static sd_rsp_type_t sd_cmd_READ_SINGLE_BLOCK(SDState *sd, SDRequest req)
1698 {
1699     uint64_t addr;
1700 
1701     if (sd->state != sd_transfer_state) {
1702         return sd_invalid_state_for_cmd(sd, req);
1703     }
1704 
1705     addr = sd_req_get_address(sd, req);
1706     if (!address_in_range(sd, "READ_SINGLE_BLOCK", addr, sd->blk_len)) {
1707         return sd_r1;
1708     }
1709 
1710     sd_blk_read(sd, addr, sd->blk_len);
1711     return sd_cmd_to_sendingdata(sd, req, addr, NULL, sd->blk_len);
1712 }
1713 
1714 /* CMD19 */
1715 static sd_rsp_type_t sd_cmd_SEND_TUNING_BLOCK(SDState *sd, SDRequest req)
1716 {
1717     if (sd->spec_version < SD_PHY_SPECv3_01_VERS) {
1718         return sd_cmd_illegal(sd, req);
1719     }
1720 
1721     return sd_cmd_to_sendingdata(sd, req, 0,
1722                                  sd_tuning_block_pattern4,
1723                                  sizeof(sd_tuning_block_pattern4));
1724 }
1725 
1726 /* CMD23 */
1727 static sd_rsp_type_t sd_cmd_SET_BLOCK_COUNT(SDState *sd, SDRequest req)
1728 {
1729     if (sd->spec_version < SD_PHY_SPECv3_01_VERS) {
1730         return sd_cmd_illegal(sd, req);
1731     }
1732 
1733     if (sd->state != sd_transfer_state) {
1734         return sd_invalid_state_for_cmd(sd, req);
1735     }
1736 
1737     sd->multi_blk_cnt = req.arg;
1738     if (sd_is_emmc(sd)) {
1739         sd->multi_blk_cnt &= 0xffff;
1740     }
1741     trace_sdcard_set_block_count(sd->multi_blk_cnt);
1742 
1743     return sd_r1;
1744 }
1745 
1746 /* CMD24 */
1747 static sd_rsp_type_t sd_cmd_WRITE_SINGLE_BLOCK(SDState *sd, SDRequest req)
1748 {
1749     uint64_t addr;
1750 
1751     if (sd->state != sd_transfer_state) {
1752         return sd_invalid_state_for_cmd(sd, req);
1753     }
1754 
1755     addr = sd_req_get_address(sd, req);
1756     if (!address_in_range(sd, "WRITE_SINGLE_BLOCK", addr, sd->blk_len)) {
1757         return sd_r1;
1758     }
1759 
1760     if (sd->size <= SDSC_MAX_CAPACITY) {
1761         if (sd_wp_addr(sd, addr)) {
1762             sd->card_status |= WP_VIOLATION;
1763         }
1764     }
1765     if (sd->csd[14] & 0x30) {
1766         sd->card_status |= WP_VIOLATION;
1767     }
1768 
1769     sd->blk_written = 0;
1770     return sd_cmd_to_receivingdata(sd, req, addr, sd->blk_len);
1771 }
1772 
1773 /* CMD26 */
1774 static sd_rsp_type_t emmc_cmd_PROGRAM_CID(SDState *sd, SDRequest req)
1775 {
1776     return sd_cmd_to_receivingdata(sd, req, 0, sizeof(sd->cid));
1777 }
1778 
1779 /* CMD27 */
1780 static sd_rsp_type_t sd_cmd_PROGRAM_CSD(SDState *sd, SDRequest req)
1781 {
1782     return sd_cmd_to_receivingdata(sd, req, 0, sizeof(sd->csd));
1783 }
1784 
1785 static sd_rsp_type_t sd_cmd_SET_CLR_WRITE_PROT(SDState *sd, SDRequest req,
1786                                                bool is_write)
1787 {
1788     uint64_t addr;
1789 
1790     if (sd->size > SDSC_MAX_CAPACITY) {
1791         return sd_illegal;
1792     }
1793 
1794     if (sd->state != sd_transfer_state) {
1795         return sd_invalid_state_for_cmd(sd, req);
1796     }
1797 
1798     addr = sd_req_get_address(sd, req);
1799     if (!address_in_range(sd, is_write ? "SET_WRITE_PROT" : "CLR_WRITE_PROT",
1800                           addr, 1)) {
1801         return sd_r1b;
1802     }
1803 
1804     sd->state = sd_programming_state;
1805     if (is_write) {
1806         set_bit(sd_addr_to_wpnum(addr), sd->wp_group_bmap);
1807     } else {
1808         clear_bit(sd_addr_to_wpnum(addr), sd->wp_group_bmap);
1809     }
1810     /* Bzzzzzzztt .... Operation complete.  */
1811     sd->state = sd_transfer_state;
1812     return sd_r1;
1813 }
1814 
1815 /* CMD28 */
1816 static sd_rsp_type_t sd_cmd_SET_WRITE_PROT(SDState *sd, SDRequest req)
1817 {
1818     return sd_cmd_SET_CLR_WRITE_PROT(sd, req, true);
1819 }
1820 
1821 /* CMD29 */
1822 static sd_rsp_type_t sd_cmd_CLR_WRITE_PROT(SDState *sd, SDRequest req)
1823 {
1824     return sd_cmd_SET_CLR_WRITE_PROT(sd, req, false);
1825 }
1826 
1827 /* CMD30 */
1828 static sd_rsp_type_t sd_cmd_SEND_WRITE_PROT(SDState *sd, SDRequest req)
1829 {
1830     uint64_t addr;
1831     uint32_t data;
1832 
1833     if (sd->size > SDSC_MAX_CAPACITY) {
1834         return sd_illegal;
1835     }
1836 
1837     if (sd->state != sd_transfer_state) {
1838         return sd_invalid_state_for_cmd(sd, req);
1839     }
1840 
1841     addr = sd_req_get_address(sd, req);
1842     if (!address_in_range(sd, "SEND_WRITE_PROT", addr, sd->blk_len)) {
1843         return sd_r1;
1844     }
1845 
1846     data = sd_wpbits(sd, req.arg);
1847     return sd_cmd_to_sendingdata(sd, req, addr, &data, sizeof(data));
1848 }
1849 
1850 /* CMD32 */
1851 static sd_rsp_type_t sd_cmd_ERASE_WR_BLK_START(SDState *sd, SDRequest req)
1852 {
1853     if (sd->state != sd_transfer_state) {
1854         return sd_invalid_state_for_cmd(sd, req);
1855     }
1856     sd->erase_start = req.arg;
1857     return sd_r1;
1858 }
1859 
1860 /* CMD33 */
1861 static sd_rsp_type_t sd_cmd_ERASE_WR_BLK_END(SDState *sd, SDRequest req)
1862 {
1863     if (sd->state != sd_transfer_state) {
1864         return sd_invalid_state_for_cmd(sd, req);
1865     }
1866     sd->erase_end = req.arg;
1867     return sd_r1;
1868 }
1869 
1870 /* CMD38 */
1871 static sd_rsp_type_t sd_cmd_ERASE(SDState *sd, SDRequest req)
1872 {
1873     if (sd->state != sd_transfer_state) {
1874         return sd_invalid_state_for_cmd(sd, req);
1875     }
1876     if (sd->csd[14] & 0x30) {
1877         sd->card_status |= WP_VIOLATION;
1878         return sd_r1b;
1879     }
1880 
1881     sd->state = sd_programming_state;
1882     sd_erase(sd);
1883     /* Bzzzzzzztt .... Operation complete.  */
1884     sd->state = sd_transfer_state;
1885     return sd_r1b;
1886 }
1887 
1888 /* CMD42 */
1889 static sd_rsp_type_t sd_cmd_LOCK_UNLOCK(SDState *sd, SDRequest req)
1890 {
1891     return sd_cmd_to_receivingdata(sd, req, 0, 0);
1892 }
1893 
1894 /* CMD55 */
1895 static sd_rsp_type_t sd_cmd_APP_CMD(SDState *sd, SDRequest req)
1896 {
1897     switch (sd->state) {
1898     case sd_ready_state:
1899     case sd_identification_state:
1900     case sd_inactive_state:
1901     case sd_sleep_state:
1902         return sd_invalid_state_for_cmd(sd, req);
1903     case sd_idle_state:
1904         if (!sd_is_spi(sd) && sd_req_get_rca(sd, req) != 0x0000) {
1905             qemu_log_mask(LOG_GUEST_ERROR,
1906                           "SD: illegal RCA 0x%04x for APP_CMD\n", req.cmd);
1907         }
1908         /* fall-through */
1909     default:
1910         break;
1911     }
1912     if (!sd_is_spi(sd) && !sd_req_rca_same(sd, req)) {
1913         return sd_r0;
1914     }
1915     sd->expecting_acmd = true;
1916     sd->card_status |= APP_CMD;
1917 
1918     return sd_r1;
1919 }
1920 
1921 /* CMD56 */
1922 static sd_rsp_type_t sd_cmd_GEN_CMD(SDState *sd, SDRequest req)
1923 {
1924     if (sd->state != sd_transfer_state) {
1925         return sd_invalid_state_for_cmd(sd, req);
1926     }
1927 
1928     /* Vendor specific command: our model is RAZ/WI */
1929     if (req.arg & 1) {
1930         memset(sd->data, 0, sizeof(sd->data));
1931         return sd_cmd_to_sendingdata(sd, req, 0, NULL, 0);
1932     } else {
1933         return sd_cmd_to_receivingdata(sd, req, 0, 0);
1934     }
1935 }
1936 
1937 /* CMD58 */
1938 static sd_rsp_type_t spi_cmd_READ_OCR(SDState *sd, SDRequest req)
1939 {
1940     return sd_r3;
1941 }
1942 
1943 /* CMD59 */
1944 static sd_rsp_type_t spi_cmd_CRC_ON_OFF(SDState *sd, SDRequest req)
1945 {
1946     return sd_r1;
1947 }
1948 
1949 /* ACMD6 */
1950 static sd_rsp_type_t sd_acmd_SET_BUS_WIDTH(SDState *sd, SDRequest req)
1951 {
1952     if (sd->state != sd_transfer_state) {
1953         return sd_invalid_state_for_cmd(sd, req);
1954     }
1955 
1956     sd->sd_status[0] &= 0x3f;
1957     sd->sd_status[0] |= (req.arg & 0x03) << 6;
1958     return sd_r1;
1959 }
1960 
1961 /* ACMD13 */
1962 static sd_rsp_type_t sd_acmd_SD_STATUS(SDState *sd, SDRequest req)
1963 {
1964     return sd_cmd_to_sendingdata(sd, req, 0,
1965                                  sd->sd_status, sizeof(sd->sd_status));
1966 }
1967 
1968 /* ACMD22 */
1969 static sd_rsp_type_t sd_acmd_SEND_NUM_WR_BLOCKS(SDState *sd, SDRequest req)
1970 {
1971     return sd_cmd_to_sendingdata(sd, req, 0,
1972                                  &sd->blk_written, sizeof(sd->blk_written));
1973 }
1974 
1975 /* ACMD23 */
1976 static sd_rsp_type_t sd_acmd_SET_WR_BLK_ERASE_COUNT(SDState *sd, SDRequest req)
1977 {
1978     if (sd->state != sd_transfer_state) {
1979         return sd_invalid_state_for_cmd(sd, req);
1980     }
1981     return sd_r1;
1982 }
1983 
1984 /* ACMD41 */
1985 static sd_rsp_type_t sd_cmd_SEND_OP_COND(SDState *sd, SDRequest req)
1986 {
1987     if (sd->state != sd_idle_state) {
1988         return sd_invalid_state_for_cmd(sd, req);
1989     }
1990 
1991     /*
1992      * If it's the first ACMD41 since reset, we need to decide
1993      * whether to power up. If this is not an enquiry ACMD41,
1994      * we immediately report power on and proceed below to the
1995      * ready state, but if it is, we set a timer to model a
1996      * delay for power up. This works around a bug in EDK2
1997      * UEFI, which sends an initial enquiry ACMD41, but
1998      * assumes that the card is in ready state as soon as it
1999      * sees the power up bit set.
2000      */
2001     if (!FIELD_EX32(sd->ocr, OCR, CARD_POWER_UP)) {
2002         if ((req.arg & ACMD41_ENQUIRY_MASK) != 0) {
2003             timer_del(sd->ocr_power_timer);
2004             sd_ocr_powerup(sd);
2005         } else {
2006             trace_sdcard_inquiry_cmd41();
2007             if (!timer_pending(sd->ocr_power_timer)) {
2008                 timer_mod_ns(sd->ocr_power_timer,
2009                              (qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL)
2010                               + OCR_POWER_DELAY_NS));
2011             }
2012         }
2013     }
2014 
2015     if (FIELD_EX32(sd->ocr & req.arg, OCR, VDD_VOLTAGE_WINDOW)) {
2016         /*
2017          * We accept any voltage.  10000 V is nothing.
2018          *
2019          * Once we're powered up, we advance straight to ready state
2020          * unless it's an enquiry ACMD41 (bits 23:0 == 0).
2021          */
2022         sd->state = sd_ready_state;
2023     }
2024 
2025     return sd_r3;
2026 }
2027 
2028 /* ACMD42 */
2029 static sd_rsp_type_t sd_acmd_SET_CLR_CARD_DETECT(SDState *sd, SDRequest req)
2030 {
2031     if (sd->state != sd_transfer_state) {
2032         return sd_invalid_state_for_cmd(sd, req);
2033     }
2034 
2035     /* Bringing in the 50KOhm pull-up resistor... Done.  */
2036     return sd_r1;
2037 }
2038 
2039 /* ACMD51 */
2040 static sd_rsp_type_t sd_acmd_SEND_SCR(SDState *sd, SDRequest req)
2041 {
2042     return sd_cmd_to_sendingdata(sd, req, 0, sd->scr, sizeof(sd->scr));
2043 }
2044 
2045 static sd_rsp_type_t sd_normal_command(SDState *sd, SDRequest req)
2046 {
2047     uint64_t addr;
2048 
2049     sd->last_cmd_name = sd_cmd_name(sd, req.cmd);
2050     /* CMD55 precedes an ACMD, so we are not interested in tracing it.
2051      * However there is no ACMD55, so we want to trace this particular case.
2052      */
2053     if (req.cmd != 55 || sd->expecting_acmd) {
2054         trace_sdcard_normal_command(sd->proto->name,
2055                                     sd->last_cmd_name, req.cmd,
2056                                     req.arg, sd_state_name(sd->state));
2057     }
2058 
2059     /* Not interpreting this as an app command */
2060     sd->card_status &= ~APP_CMD;
2061 
2062     /* CMD23 (set block count) must be immediately followed by CMD18 or CMD25
2063      * if not, its effects are cancelled */
2064     if (sd->multi_blk_cnt != 0 && !(req.cmd == 18 || req.cmd == 25)) {
2065         sd->multi_blk_cnt = 0;
2066     }
2067 
2068     if (sd->proto->cmd[req.cmd].class == 6 && FIELD_EX32(sd->ocr, OCR,
2069                                                          CARD_CAPACITY)) {
2070         /* Only Standard Capacity cards support class 6 commands */
2071         return sd_illegal;
2072     }
2073 
2074     if (sd->proto->cmd[req.cmd].handler) {
2075         return sd->proto->cmd[req.cmd].handler(sd, req);
2076     }
2077 
2078     switch (req.cmd) {
2079     /* Block read commands (Class 2) */
2080     case 18:  /* CMD18:  READ_MULTIPLE_BLOCK */
2081         addr = sd_req_get_address(sd, req);
2082         switch (sd->state) {
2083         case sd_transfer_state:
2084 
2085             if (!address_in_range(sd, "READ_BLOCK", addr, sd->blk_len)) {
2086                 return sd_r1;
2087             }
2088 
2089             sd->state = sd_sendingdata_state;
2090             sd->data_start = addr;
2091             sd->data_offset = 0;
2092             return sd_r1;
2093 
2094         default:
2095             break;
2096         }
2097         break;
2098 
2099     /* Block write commands (Class 4) */
2100     case 25:  /* CMD25:  WRITE_MULTIPLE_BLOCK */
2101         addr = sd_req_get_address(sd, req);
2102         switch (sd->state) {
2103         case sd_transfer_state:
2104 
2105             if (!address_in_range(sd, "WRITE_BLOCK", addr, sd->blk_len)) {
2106                 return sd_r1;
2107             }
2108 
2109             sd->state = sd_receivingdata_state;
2110             sd->data_start = addr;
2111             sd->data_offset = 0;
2112             sd->blk_written = 0;
2113 
2114             if (sd->size <= SDSC_MAX_CAPACITY) {
2115                 if (sd_wp_addr(sd, sd->data_start)) {
2116                     sd->card_status |= WP_VIOLATION;
2117                 }
2118             }
2119             if (sd->csd[14] & 0x30) {
2120                 sd->card_status |= WP_VIOLATION;
2121             }
2122             return sd_r1;
2123 
2124         default:
2125             break;
2126         }
2127         break;
2128 
2129     default:
2130         qemu_log_mask(LOG_GUEST_ERROR, "SD: Unknown CMD%i\n", req.cmd);
2131         return sd_illegal;
2132     }
2133 
2134     return sd_invalid_state_for_cmd(sd, req);
2135 }
2136 
2137 static sd_rsp_type_t sd_app_command(SDState *sd,
2138                                     SDRequest req)
2139 {
2140     sd->last_cmd_name = sd_acmd_name(sd, req.cmd);
2141     trace_sdcard_app_command(sd->proto->name, sd->last_cmd_name,
2142                              req.cmd, req.arg, sd_state_name(sd->state));
2143     sd->card_status |= APP_CMD;
2144 
2145     if (sd->proto->acmd[req.cmd].handler) {
2146         return sd->proto->acmd[req.cmd].handler(sd, req);
2147     }
2148 
2149     switch (req.cmd) {
2150     case 18:    /* Reserved for SD security applications */
2151     case 25:
2152     case 26:
2153     case 38:
2154     case 43 ... 49:
2155         /* Refer to the "SD Specifications Part3 Security Specification" for
2156          * information about the SD Security Features.
2157          */
2158         qemu_log_mask(LOG_UNIMP, "SD: CMD%i Security not implemented\n",
2159                       req.cmd);
2160         return sd_illegal;
2161 
2162     default:
2163         /* Fall back to standard commands.  */
2164         return sd_normal_command(sd, req);
2165     }
2166 
2167     qemu_log_mask(LOG_GUEST_ERROR, "SD: ACMD%i in a wrong state\n", req.cmd);
2168     return sd_illegal;
2169 }
2170 
2171 static bool cmd_valid_while_locked(SDState *sd, unsigned cmd)
2172 {
2173     unsigned cmd_class;
2174 
2175     /* Valid commands in locked state:
2176      * basic class (0)
2177      * lock card class (7)
2178      * CMD16
2179      * implicitly, the ACMD prefix CMD55
2180      * ACMD41 and ACMD42
2181      * Anything else provokes an "illegal command" response.
2182      */
2183     if (sd->expecting_acmd) {
2184         return cmd == 41 || cmd == 42;
2185     }
2186     if (cmd == 16 || cmd == 55) {
2187         return true;
2188     }
2189     if (!sd->proto->cmd[cmd].handler) {
2190         return false;
2191     }
2192     cmd_class = sd->proto->cmd[cmd].class;
2193 
2194     return cmd_class == 0 || cmd_class == 7;
2195 }
2196 
2197 int sd_do_command(SDState *sd, SDRequest *req,
2198                   uint8_t *response) {
2199     int last_state;
2200     sd_rsp_type_t rtype;
2201     int rsplen;
2202 
2203     if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable) {
2204         return 0;
2205     }
2206 
2207     if (sd->state == sd_inactive_state) {
2208         rtype = sd_illegal;
2209         goto send_response;
2210     }
2211 
2212     if (sd_req_crc_validate(req)) {
2213         sd->card_status |= COM_CRC_ERROR;
2214         rtype = sd_illegal;
2215         goto send_response;
2216     }
2217 
2218     if (req->cmd >= SDMMC_CMD_MAX) {
2219         qemu_log_mask(LOG_GUEST_ERROR, "SD: incorrect command 0x%02x\n",
2220                       req->cmd);
2221         req->cmd &= 0x3f;
2222     }
2223 
2224     if (sd->state == sd_sleep_state && req->cmd) {
2225         qemu_log_mask(LOG_GUEST_ERROR, "SD: Card is sleeping\n");
2226         rtype = sd_r0;
2227         goto send_response;
2228     }
2229 
2230     if (sd->card_status & CARD_IS_LOCKED) {
2231         if (!cmd_valid_while_locked(sd, req->cmd)) {
2232             sd->card_status |= ILLEGAL_COMMAND;
2233             sd->expecting_acmd = false;
2234             qemu_log_mask(LOG_GUEST_ERROR, "SD: Card is locked\n");
2235             rtype = sd_illegal;
2236             goto send_response;
2237         }
2238     }
2239 
2240     last_state = sd->state;
2241     sd_set_mode(sd);
2242 
2243     if (sd->expecting_acmd) {
2244         sd->expecting_acmd = false;
2245         rtype = sd_app_command(sd, *req);
2246     } else {
2247         rtype = sd_normal_command(sd, *req);
2248     }
2249 
2250     if (rtype == sd_illegal) {
2251         sd->card_status |= ILLEGAL_COMMAND;
2252     } else {
2253         /* Valid command, we can update the 'state before command' bits.
2254          * (Do this now so they appear in r1 responses.)
2255          */
2256         sd->card_status = FIELD_DP32(sd->card_status, CSR,
2257                                      CURRENT_STATE, last_state);
2258     }
2259 
2260 send_response:
2261     switch (rtype) {
2262     case sd_r1:
2263     case sd_r1b:
2264         sd_response_r1_make(sd, response);
2265         rsplen = 4;
2266         break;
2267 
2268     case sd_r2_i:
2269         memcpy(response, sd->cid, sizeof(sd->cid));
2270         rsplen = 16;
2271         break;
2272 
2273     case sd_r2_s:
2274         memcpy(response, sd->csd, sizeof(sd->csd));
2275         rsplen = 16;
2276         break;
2277 
2278     case sd_r3:
2279         sd_response_r3_make(sd, response);
2280         rsplen = 4;
2281         break;
2282 
2283     case sd_r6:
2284         sd_response_r6_make(sd, response);
2285         rsplen = 4;
2286         break;
2287 
2288     case sd_r7:
2289         sd_response_r7_make(sd, response);
2290         rsplen = 4;
2291         break;
2292 
2293     case sd_r0:
2294         /*
2295          * Invalid state transition, reset implementation
2296          * fields to avoid OOB abuse.
2297          */
2298         sd->data_start = 0;
2299         sd->data_offset = 0;
2300         /* fall-through */
2301     case sd_illegal:
2302         rsplen = 0;
2303         break;
2304     default:
2305         g_assert_not_reached();
2306     }
2307     trace_sdcard_response(sd_response_name(rtype), rsplen);
2308 
2309     if (rtype != sd_illegal) {
2310         /* Clear the "clear on valid command" status bits now we've
2311          * sent any response
2312          */
2313         sd->card_status &= ~CARD_STATUS_B;
2314     }
2315 
2316 #ifdef DEBUG_SD
2317     qemu_hexdump(stderr, "Response", response, rsplen);
2318 #endif
2319 
2320     sd->current_cmd = rtype == sd_illegal ? 0 : req->cmd;
2321 
2322     return rsplen;
2323 }
2324 
2325 /* Return true if buffer is consumed. Configured by sd_cmd_to_receivingdata() */
2326 static bool sd_generic_write_byte(SDState *sd, uint8_t value)
2327 {
2328     sd->data[sd->data_offset] = value;
2329 
2330     if (++sd->data_offset >= sd->data_size) {
2331         sd->state = sd_transfer_state;
2332         return true;
2333     }
2334     return false;
2335 }
2336 
2337 /* Return true when buffer is consumed. Configured by sd_cmd_to_sendingdata() */
2338 static bool sd_generic_read_byte(SDState *sd, uint8_t *value)
2339 {
2340     *value = sd->data[sd->data_offset];
2341 
2342     if (++sd->data_offset >= sd->data_size) {
2343         sd->state = sd_transfer_state;
2344         return true;
2345     }
2346 
2347     return false;
2348 }
2349 
2350 void sd_write_byte(SDState *sd, uint8_t value)
2351 {
2352     int i;
2353 
2354     if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable)
2355         return;
2356 
2357     if (sd->state != sd_receivingdata_state) {
2358         qemu_log_mask(LOG_GUEST_ERROR,
2359                       "%s: not in Receiving-Data state\n", __func__);
2360         return;
2361     }
2362 
2363     if (sd->card_status & (ADDRESS_ERROR | WP_VIOLATION))
2364         return;
2365 
2366     trace_sdcard_write_data(sd->proto->name,
2367                             sd->last_cmd_name,
2368                             sd->current_cmd, sd->data_offset, value);
2369     switch (sd->current_cmd) {
2370     case 24:  /* CMD24:  WRITE_SINGLE_BLOCK */
2371         if (sd_generic_write_byte(sd, value)) {
2372             /* TODO: Check CRC before committing */
2373             sd->state = sd_programming_state;
2374             sd_blk_write(sd, sd->data_start, sd->data_offset);
2375             sd->blk_written ++;
2376             sd->csd[14] |= 0x40;
2377             /* Bzzzzzzztt .... Operation complete.  */
2378             sd->state = sd_transfer_state;
2379         }
2380         break;
2381 
2382     case 25:  /* CMD25:  WRITE_MULTIPLE_BLOCK */
2383         if (sd->data_offset == 0) {
2384             /* Start of the block - let's check the address is valid */
2385             if (!address_in_range(sd, "WRITE_MULTIPLE_BLOCK",
2386                                   sd->data_start, sd->blk_len)) {
2387                 break;
2388             }
2389             if (sd->size <= SDSC_MAX_CAPACITY) {
2390                 if (sd_wp_addr(sd, sd->data_start)) {
2391                     sd->card_status |= WP_VIOLATION;
2392                     break;
2393                 }
2394             }
2395         }
2396         sd->data[sd->data_offset++] = value;
2397         if (sd->data_offset >= sd->blk_len) {
2398             /* TODO: Check CRC before committing */
2399             sd->state = sd_programming_state;
2400             sd_blk_write(sd, sd->data_start, sd->data_offset);
2401             sd->blk_written++;
2402             sd->data_start += sd->blk_len;
2403             sd->data_offset = 0;
2404             sd->csd[14] |= 0x40;
2405 
2406             /* Bzzzzzzztt .... Operation complete.  */
2407             if (sd->multi_blk_cnt != 0) {
2408                 if (--sd->multi_blk_cnt == 0) {
2409                     /* Stop! */
2410                     sd->state = sd_transfer_state;
2411                     break;
2412                 }
2413             }
2414 
2415             sd->state = sd_receivingdata_state;
2416         }
2417         break;
2418 
2419     case 26:  /* CMD26:  PROGRAM_CID */
2420         if (sd_generic_write_byte(sd, value)) {
2421             /* TODO: Check CRC before committing */
2422             sd->state = sd_programming_state;
2423             for (i = 0; i < sizeof(sd->cid); i ++)
2424                 if ((sd->cid[i] | 0x00) != sd->data[i])
2425                     sd->card_status |= CID_CSD_OVERWRITE;
2426 
2427             if (!(sd->card_status & CID_CSD_OVERWRITE))
2428                 for (i = 0; i < sizeof(sd->cid); i ++) {
2429                     sd->cid[i] |= 0x00;
2430                     sd->cid[i] &= sd->data[i];
2431                 }
2432             /* Bzzzzzzztt .... Operation complete.  */
2433             sd->state = sd_transfer_state;
2434         }
2435         break;
2436 
2437     case 27:  /* CMD27:  PROGRAM_CSD */
2438         if (sd_generic_write_byte(sd, value)) {
2439             /* TODO: Check CRC before committing */
2440             sd->state = sd_programming_state;
2441             for (i = 0; i < sizeof(sd->csd); i ++)
2442                 if ((sd->csd[i] | sd_csd_rw_mask[i]) !=
2443                     (sd->data[i] | sd_csd_rw_mask[i]))
2444                     sd->card_status |= CID_CSD_OVERWRITE;
2445 
2446             /* Copy flag (OTP) & Permanent write protect */
2447             if (sd->csd[14] & ~sd->data[14] & 0x60)
2448                 sd->card_status |= CID_CSD_OVERWRITE;
2449 
2450             if (!(sd->card_status & CID_CSD_OVERWRITE))
2451                 for (i = 0; i < sizeof(sd->csd); i ++) {
2452                     sd->csd[i] |= sd_csd_rw_mask[i];
2453                     sd->csd[i] &= sd->data[i];
2454                 }
2455             /* Bzzzzzzztt .... Operation complete.  */
2456             sd->state = sd_transfer_state;
2457         }
2458         break;
2459 
2460     case 42:  /* CMD42:  LOCK_UNLOCK */
2461         if (sd_generic_write_byte(sd, value)) {
2462             /* TODO: Check CRC before committing */
2463             sd->state = sd_programming_state;
2464             sd_lock_command(sd);
2465             /* Bzzzzzzztt .... Operation complete.  */
2466             sd->state = sd_transfer_state;
2467         }
2468         break;
2469 
2470     case 56:  /* CMD56:  GEN_CMD */
2471         sd_generic_write_byte(sd, value);
2472         break;
2473 
2474     default:
2475         g_assert_not_reached();
2476     }
2477 }
2478 
2479 uint8_t sd_read_byte(SDState *sd)
2480 {
2481     /* TODO: Append CRCs */
2482     const uint8_t dummy_byte = 0x00;
2483     uint8_t ret;
2484     uint32_t io_len;
2485 
2486     if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable)
2487         return dummy_byte;
2488 
2489     if (sd->state != sd_sendingdata_state) {
2490         qemu_log_mask(LOG_GUEST_ERROR,
2491                       "%s: not in Sending-Data state\n", __func__);
2492         return dummy_byte;
2493     }
2494 
2495     if (sd->card_status & (ADDRESS_ERROR | WP_VIOLATION)) {
2496         return dummy_byte;
2497     }
2498 
2499     io_len = sd_blk_len(sd);
2500 
2501     trace_sdcard_read_data(sd->proto->name,
2502                            sd->last_cmd_name, sd->current_cmd,
2503                            sd->data_offset, sd->data_size, io_len);
2504     switch (sd->current_cmd) {
2505     case 6:  /* CMD6:   SWITCH_FUNCTION */
2506     case 8:  /* CMD8:   SEND_EXT_CSD */
2507     case 9:  /* CMD9:   SEND_CSD */
2508     case 10: /* CMD10:  SEND_CID */
2509     case 13: /* ACMD13: SD_STATUS */
2510     case 17: /* CMD17:  READ_SINGLE_BLOCK */
2511     case 19: /* CMD19:  SEND_TUNING_BLOCK (SD) */
2512     case 22: /* ACMD22: SEND_NUM_WR_BLOCKS */
2513     case 30: /* CMD30:  SEND_WRITE_PROT */
2514     case 51: /* ACMD51: SEND_SCR */
2515     case 56: /* CMD56:  GEN_CMD */
2516         sd_generic_read_byte(sd, &ret);
2517         break;
2518 
2519     case 18:  /* CMD18:  READ_MULTIPLE_BLOCK */
2520         if (sd->data_offset == 0) {
2521             if (!address_in_range(sd, "READ_MULTIPLE_BLOCK",
2522                                   sd->data_start, io_len)) {
2523                 return dummy_byte;
2524             }
2525             sd_blk_read(sd, sd->data_start, io_len);
2526         }
2527         ret = sd->data[sd->data_offset ++];
2528 
2529         if (sd->data_offset >= io_len) {
2530             sd->data_start += io_len;
2531             sd->data_offset = 0;
2532 
2533             if (sd->multi_blk_cnt != 0) {
2534                 if (--sd->multi_blk_cnt == 0) {
2535                     /* Stop! */
2536                     sd->state = sd_transfer_state;
2537                     break;
2538                 }
2539             }
2540         }
2541         break;
2542 
2543     default:
2544         qemu_log_mask(LOG_GUEST_ERROR, "%s: DAT read illegal for command %s\n",
2545                                        __func__, sd->last_cmd_name);
2546         return dummy_byte;
2547     }
2548 
2549     return ret;
2550 }
2551 
2552 static bool sd_receive_ready(SDState *sd)
2553 {
2554     return sd->state == sd_receivingdata_state;
2555 }
2556 
2557 static bool sd_data_ready(SDState *sd)
2558 {
2559     return sd->state == sd_sendingdata_state;
2560 }
2561 
2562 void sd_enable(SDState *sd, bool enable)
2563 {
2564     sd->enable = enable;
2565 }
2566 
2567 static const SDProto sd_proto_spi = {
2568     .name = "SPI",
2569     .cmd = {
2570         [0]  = {0,  sd_spi, "GO_IDLE_STATE", sd_cmd_GO_IDLE_STATE},
2571         [1]  = {0,  sd_spi, "SEND_OP_COND", spi_cmd_SEND_OP_COND},
2572         [5]  = {9,  sd_spi, "IO_SEND_OP_COND", sd_cmd_optional},
2573         [6]  = {10, sd_spi, "SWITCH_FUNCTION", sd_cmd_SWITCH_FUNCTION},
2574         [8]  = {0,  sd_spi, "SEND_IF_COND", sd_cmd_SEND_IF_COND},
2575         [9]  = {0,  sd_spi, "SEND_CSD", spi_cmd_SEND_CSD},
2576         [10] = {0,  sd_spi, "SEND_CID", spi_cmd_SEND_CID},
2577         [12] = {0,  sd_spi, "STOP_TRANSMISSION", sd_cmd_STOP_TRANSMISSION},
2578         [13] = {0,  sd_spi, "SEND_STATUS", sd_cmd_SEND_STATUS},
2579         [16] = {2,  sd_spi, "SET_BLOCKLEN", sd_cmd_SET_BLOCKLEN},
2580         [17] = {2,  sd_spi, "READ_SINGLE_BLOCK", sd_cmd_READ_SINGLE_BLOCK},
2581         [24] = {4,  sd_spi, "WRITE_SINGLE_BLOCK", sd_cmd_WRITE_SINGLE_BLOCK},
2582         [27] = {4,  sd_spi, "PROGRAM_CSD", sd_cmd_PROGRAM_CSD},
2583         [28] = {6,  sd_spi, "SET_WRITE_PROT", sd_cmd_SET_WRITE_PROT},
2584         [29] = {6,  sd_spi, "CLR_WRITE_PROT", sd_cmd_CLR_WRITE_PROT},
2585         [30] = {6,  sd_spi, "SEND_WRITE_PROT", sd_cmd_SEND_WRITE_PROT},
2586         [32] = {5,  sd_spi, "ERASE_WR_BLK_START", sd_cmd_ERASE_WR_BLK_START},
2587         [33] = {5,  sd_spi, "ERASE_WR_BLK_END", sd_cmd_ERASE_WR_BLK_END},
2588         [34] = {10, sd_spi, "READ_SEC_CMD", sd_cmd_optional},
2589         [35] = {10, sd_spi, "WRITE_SEC_CMD", sd_cmd_optional},
2590         [36] = {10, sd_spi, "SEND_PSI", sd_cmd_optional},
2591         [37] = {10, sd_spi, "CONTROL_ASSD_SYSTEM", sd_cmd_optional},
2592         [38] = {5,  sd_spi, "ERASE", sd_cmd_ERASE},
2593         [42] = {7,  sd_spi, "LOCK_UNLOCK", sd_cmd_LOCK_UNLOCK},
2594         [50] = {10, sd_spi, "DIRECT_SECURE_READ", sd_cmd_optional},
2595         [52] = {9,  sd_spi, "IO_RW_DIRECT", sd_cmd_optional},
2596         [53] = {9,  sd_spi, "IO_RW_EXTENDED", sd_cmd_optional},
2597         [55] = {8,  sd_spi, "APP_CMD", sd_cmd_APP_CMD},
2598         [56] = {8,  sd_spi, "GEN_CMD", sd_cmd_GEN_CMD},
2599         [57] = {10, sd_spi, "DIRECT_SECURE_WRITE", sd_cmd_optional},
2600         [58] = {0,  sd_spi, "READ_OCR", spi_cmd_READ_OCR},
2601         [59] = {0,  sd_spi, "CRC_ON_OFF", spi_cmd_CRC_ON_OFF},
2602     },
2603     .acmd = {
2604         [13] = {8,  sd_spi, "SD_STATUS", sd_acmd_SD_STATUS},
2605         [22] = {8,  sd_spi, "SEND_NUM_WR_BLOCKS", sd_acmd_SEND_NUM_WR_BLOCKS},
2606         [23] = {8,  sd_spi, "SET_WR_BLK_ERASE_COUNT", sd_acmd_SET_WR_BLK_ERASE_COUNT},
2607         [41] = {8,  sd_spi, "SEND_OP_COND", spi_cmd_SEND_OP_COND},
2608         [42] = {8,  sd_spi, "SET_CLR_CARD_DETECT", sd_acmd_SET_CLR_CARD_DETECT},
2609         [51] = {8,  sd_spi, "SEND_SCR", sd_acmd_SEND_SCR},
2610     },
2611 };
2612 
2613 static const SDProto sd_proto_sd = {
2614     .name = "SD",
2615     .cmd = {
2616         [0]  = {0,  sd_bc,   "GO_IDLE_STATE", sd_cmd_GO_IDLE_STATE},
2617         [2]  = {0,  sd_bcr,  "ALL_SEND_CID", sd_cmd_ALL_SEND_CID},
2618         [3]  = {0,  sd_bcr,  "SEND_RELATIVE_ADDR", sd_cmd_SEND_RELATIVE_ADDR},
2619         [4]  = {0,  sd_bc,   "SEND_DSR", sd_cmd_unimplemented},
2620         [5]  = {9,  sd_bc,   "IO_SEND_OP_COND", sd_cmd_optional},
2621         [6]  = {10, sd_adtc, "SWITCH_FUNCTION", sd_cmd_SWITCH_FUNCTION},
2622         [7]  = {0,  sd_ac,   "(DE)SELECT_CARD", sd_cmd_DE_SELECT_CARD},
2623         [8]  = {0,  sd_bcr,  "SEND_IF_COND", sd_cmd_SEND_IF_COND},
2624         [9]  = {0,  sd_ac,   "SEND_CSD", sd_cmd_SEND_CSD},
2625         [10] = {0,  sd_ac,   "SEND_CID", sd_cmd_SEND_CID},
2626         [11] = {0,  sd_ac,   "VOLTAGE_SWITCH", sd_cmd_optional},
2627         [12] = {0,  sd_ac,   "STOP_TRANSMISSION", sd_cmd_STOP_TRANSMISSION},
2628         [13] = {0,  sd_ac,   "SEND_STATUS", sd_cmd_SEND_STATUS},
2629         [15] = {0,  sd_ac,   "GO_INACTIVE_STATE", sd_cmd_GO_INACTIVE_STATE},
2630         [16] = {2,  sd_ac,   "SET_BLOCKLEN", sd_cmd_SET_BLOCKLEN},
2631         [17] = {2,  sd_adtc, "READ_SINGLE_BLOCK", sd_cmd_READ_SINGLE_BLOCK},
2632         [19] = {2,  sd_adtc, "SEND_TUNING_BLOCK", sd_cmd_SEND_TUNING_BLOCK},
2633         [20] = {2,  sd_ac,   "SPEED_CLASS_CONTROL", sd_cmd_optional},
2634         [23] = {2,  sd_ac,   "SET_BLOCK_COUNT", sd_cmd_SET_BLOCK_COUNT},
2635         [24] = {4,  sd_adtc, "WRITE_SINGLE_BLOCK", sd_cmd_WRITE_SINGLE_BLOCK},
2636         [27] = {4,  sd_adtc, "PROGRAM_CSD", sd_cmd_PROGRAM_CSD},
2637         [28] = {6,  sd_ac,   "SET_WRITE_PROT", sd_cmd_SET_WRITE_PROT},
2638         [29] = {6,  sd_ac,   "CLR_WRITE_PROT", sd_cmd_CLR_WRITE_PROT},
2639         [30] = {6,  sd_adtc, "SEND_WRITE_PROT", sd_cmd_SEND_WRITE_PROT},
2640         [32] = {5,  sd_ac,   "ERASE_WR_BLK_START", sd_cmd_ERASE_WR_BLK_START},
2641         [33] = {5,  sd_ac,   "ERASE_WR_BLK_END", sd_cmd_ERASE_WR_BLK_END},
2642         [34] = {10, sd_adtc, "READ_SEC_CMD", sd_cmd_optional},
2643         [35] = {10, sd_adtc, "WRITE_SEC_CMD", sd_cmd_optional},
2644         [36] = {10, sd_adtc, "SEND_PSI", sd_cmd_optional},
2645         [37] = {10, sd_ac,   "CONTROL_ASSD_SYSTEM", sd_cmd_optional},
2646         [38] = {5,  sd_ac,   "ERASE", sd_cmd_ERASE},
2647         [42] = {7,  sd_adtc, "LOCK_UNLOCK", sd_cmd_LOCK_UNLOCK},
2648         [43] = {1,  sd_ac,   "Q_MANAGEMENT", sd_cmd_optional},
2649         [44] = {1,  sd_ac,   "Q_TASK_INFO_A", sd_cmd_optional},
2650         [45] = {1,  sd_ac,   "Q_TASK_INFO_B", sd_cmd_optional},
2651         [46] = {1,  sd_adtc, "Q_RD_TASK", sd_cmd_optional},
2652         [47] = {1,  sd_adtc, "Q_WR_TASK", sd_cmd_optional},
2653         [48] = {1,  sd_adtc, "READ_EXTR_SINGLE", sd_cmd_optional},
2654         [49] = {1,  sd_adtc, "WRITE_EXTR_SINGLE", sd_cmd_optional},
2655         [50] = {10, sd_adtc, "DIRECT_SECURE_READ", sd_cmd_optional},
2656         [52] = {9,  sd_bc,   "IO_RW_DIRECT", sd_cmd_optional},
2657         [53] = {9,  sd_bc,   "IO_RW_EXTENDED", sd_cmd_optional},
2658         [55] = {8,  sd_ac,   "APP_CMD", sd_cmd_APP_CMD},
2659         [56] = {8,  sd_adtc, "GEN_CMD", sd_cmd_GEN_CMD},
2660         [57] = {10, sd_adtc, "DIRECT_SECURE_WRITE", sd_cmd_optional},
2661         [58] = {11, sd_adtc, "READ_EXTR_MULTI", sd_cmd_optional},
2662         [59] = {11, sd_adtc, "WRITE_EXTR_MULTI", sd_cmd_optional},
2663     },
2664     .acmd = {
2665         [6]  = {8,  sd_ac,   "SET_BUS_WIDTH", sd_acmd_SET_BUS_WIDTH},
2666         [13] = {8,  sd_adtc, "SD_STATUS", sd_acmd_SD_STATUS},
2667         [22] = {8,  sd_adtc, "SEND_NUM_WR_BLOCKS", sd_acmd_SEND_NUM_WR_BLOCKS},
2668         [23] = {8,  sd_ac,   "SET_WR_BLK_ERASE_COUNT", sd_acmd_SET_WR_BLK_ERASE_COUNT},
2669         [41] = {8,  sd_bcr,  "SEND_OP_COND", sd_cmd_SEND_OP_COND},
2670         [42] = {8,  sd_ac,   "SET_CLR_CARD_DETECT", sd_acmd_SET_CLR_CARD_DETECT},
2671         [51] = {8,  sd_adtc, "SEND_SCR", sd_acmd_SEND_SCR},
2672     },
2673 };
2674 
2675 static const SDProto sd_proto_emmc = {
2676     /* Only v4.3 is supported */
2677     .name = "eMMC",
2678     .cmd = {
2679         [0]  = {0,  sd_bc,   "GO_IDLE_STATE", sd_cmd_GO_IDLE_STATE},
2680         [1]  = {0,  sd_bcr,  "SEND_OP_COND", sd_cmd_SEND_OP_COND},
2681         [2]  = {0,  sd_bcr,  "ALL_SEND_CID", sd_cmd_ALL_SEND_CID},
2682         [3]  = {0,  sd_ac,   "SET_RELATIVE_ADDR", emmc_cmd_SET_RELATIVE_ADDR},
2683         [4]  = {0,  sd_bc,   "SEND_DSR", sd_cmd_unimplemented},
2684         [5]  = {0,  sd_ac,   "SLEEP/AWAKE", emmc_cmd_sleep_awake},
2685         [6]  = {10, sd_adtc, "SWITCH", emmc_cmd_SWITCH},
2686         [7]  = {0,  sd_ac,   "(DE)SELECT_CARD", sd_cmd_DE_SELECT_CARD},
2687         [8]  = {0,  sd_adtc, "SEND_EXT_CSD", emmc_cmd_SEND_EXT_CSD},
2688         [9]  = {0,  sd_ac,   "SEND_CSD", sd_cmd_SEND_CSD},
2689         [10] = {0,  sd_ac,   "SEND_CID", sd_cmd_SEND_CID},
2690         [11] = {1,  sd_adtc, "READ_DAT_UNTIL_STOP", sd_cmd_unimplemented},
2691         [12] = {0,  sd_ac,   "STOP_TRANSMISSION", sd_cmd_STOP_TRANSMISSION},
2692         [13] = {0,  sd_ac,   "SEND_STATUS", sd_cmd_SEND_STATUS},
2693         [14] = {0,  sd_adtc, "BUSTEST_R", sd_cmd_unimplemented},
2694         [15] = {0,  sd_ac,   "GO_INACTIVE_STATE", sd_cmd_GO_INACTIVE_STATE},
2695         [16] = {2,  sd_ac,   "SET_BLOCKLEN", sd_cmd_SET_BLOCKLEN},
2696         [17] = {2,  sd_adtc, "READ_SINGLE_BLOCK", sd_cmd_READ_SINGLE_BLOCK},
2697         [19] = {0,  sd_adtc, "BUSTEST_W", sd_cmd_unimplemented},
2698         [20] = {3,  sd_adtc, "WRITE_DAT_UNTIL_STOP", sd_cmd_unimplemented},
2699         [23] = {2,  sd_ac,   "SET_BLOCK_COUNT", sd_cmd_SET_BLOCK_COUNT},
2700         [24] = {4,  sd_adtc, "WRITE_SINGLE_BLOCK", sd_cmd_WRITE_SINGLE_BLOCK},
2701         [26] = {4,  sd_adtc, "PROGRAM_CID", emmc_cmd_PROGRAM_CID},
2702         [27] = {4,  sd_adtc, "PROGRAM_CSD", sd_cmd_PROGRAM_CSD},
2703         [28] = {6,  sd_ac,   "SET_WRITE_PROT", sd_cmd_SET_WRITE_PROT},
2704         [29] = {6,  sd_ac,   "CLR_WRITE_PROT", sd_cmd_CLR_WRITE_PROT},
2705         [30] = {6,  sd_adtc, "SEND_WRITE_PROT", sd_cmd_SEND_WRITE_PROT},
2706         [31] = {6,  sd_adtc, "SEND_WRITE_PROT_TYPE", sd_cmd_unimplemented},
2707         [35] = {5,  sd_ac,   "ERASE_WR_BLK_START", sd_cmd_ERASE_WR_BLK_START},
2708         [36] = {5,  sd_ac,   "ERASE_WR_BLK_END", sd_cmd_ERASE_WR_BLK_END},
2709         [38] = {5,  sd_ac,   "ERASE", sd_cmd_ERASE},
2710         [39] = {9,  sd_ac,   "FAST_IO", sd_cmd_unimplemented},
2711         [40] = {9,  sd_bcr,  "GO_IRQ_STATE", sd_cmd_unimplemented},
2712         [42] = {7,  sd_adtc, "LOCK_UNLOCK", sd_cmd_LOCK_UNLOCK},
2713         [49] = {0,  sd_adtc, "SET_TIME", sd_cmd_unimplemented},
2714         [55] = {8,  sd_ac,   "APP_CMD", sd_cmd_APP_CMD},
2715         [56] = {8,  sd_adtc, "GEN_CMD", sd_cmd_GEN_CMD},
2716     },
2717 };
2718 
2719 static void sd_instance_init(Object *obj)
2720 {
2721     SDState *sd = SDMMC_COMMON(obj);
2722     SDCardClass *sc = SDMMC_COMMON_GET_CLASS(sd);
2723 
2724     sd->proto = sc->proto;
2725     sd->last_cmd_name = "UNSET";
2726     sd->enable = true;
2727     sd->ocr_power_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, sd_ocr_powerup, sd);
2728 }
2729 
2730 static void sd_instance_finalize(Object *obj)
2731 {
2732     SDState *sd = SDMMC_COMMON(obj);
2733 
2734     timer_free(sd->ocr_power_timer);
2735 }
2736 
2737 static void sd_realize(DeviceState *dev, Error **errp)
2738 {
2739     SDState *sd = SDMMC_COMMON(dev);
2740     int ret;
2741 
2742     switch (sd->spec_version) {
2743     case SD_PHY_SPECv1_10_VERS
2744      ... SD_PHY_SPECv3_01_VERS:
2745         break;
2746     default:
2747         error_setg(errp, "Invalid SD card Spec version: %u", sd->spec_version);
2748         return;
2749     }
2750 
2751     if (sd->blk) {
2752         int64_t blk_size;
2753 
2754         if (!blk_supports_write_perm(sd->blk)) {
2755             error_setg(errp, "Cannot use read-only drive as SD card");
2756             return;
2757         }
2758 
2759         blk_size = blk_getlength(sd->blk);
2760         if (blk_size > 0 && !is_power_of_2(blk_size)) {
2761             int64_t blk_size_aligned = pow2ceil(blk_size);
2762             char *blk_size_str;
2763 
2764             blk_size_str = size_to_str(blk_size);
2765             error_setg(errp, "Invalid SD card size: %s", blk_size_str);
2766             g_free(blk_size_str);
2767 
2768             blk_size_str = size_to_str(blk_size_aligned);
2769             error_append_hint(errp,
2770                               "SD card size has to be a power of 2, e.g. %s.\n"
2771                               "You can resize disk images with"
2772                               " 'qemu-img resize <imagefile> <new-size>'\n"
2773                               "(note that this will lose data if you make the"
2774                               " image smaller than it currently is).\n",
2775                               blk_size_str);
2776             g_free(blk_size_str);
2777 
2778             return;
2779         }
2780 
2781         ret = blk_set_perm(sd->blk, BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE,
2782                            BLK_PERM_ALL, errp);
2783         if (ret < 0) {
2784             return;
2785         }
2786         blk_set_dev_ops(sd->blk, &sd_block_ops, sd);
2787     }
2788 }
2789 
2790 static void emmc_realize(DeviceState *dev, Error **errp)
2791 {
2792     SDState *sd = SDMMC_COMMON(dev);
2793 
2794     sd->spec_version = SD_PHY_SPECv3_01_VERS; /* Actually v4.3 */
2795 
2796     sd_realize(dev, errp);
2797 }
2798 
2799 static Property sdmmc_common_properties[] = {
2800     DEFINE_PROP_DRIVE("drive", SDState, blk),
2801     DEFINE_PROP_END_OF_LIST()
2802 };
2803 
2804 static Property sd_properties[] = {
2805     DEFINE_PROP_UINT8("spec_version", SDState,
2806                       spec_version, SD_PHY_SPECv3_01_VERS),
2807     DEFINE_PROP_END_OF_LIST()
2808 };
2809 
2810 static Property emmc_properties[] = {
2811     DEFINE_PROP_UINT64("boot-partition-size", SDState, boot_part_size, 0),
2812     DEFINE_PROP_UINT8("boot-config", SDState, boot_config, 0x0),
2813     DEFINE_PROP_END_OF_LIST()
2814 };
2815 
2816 static void sdmmc_common_class_init(ObjectClass *klass, void *data)
2817 {
2818     DeviceClass *dc = DEVICE_CLASS(klass);
2819     SDCardClass *sc = SDMMC_COMMON_CLASS(klass);
2820 
2821     device_class_set_props(dc, sdmmc_common_properties);
2822     dc->vmsd = &sd_vmstate;
2823     device_class_set_legacy_reset(dc, sd_reset);
2824     dc->bus_type = TYPE_SD_BUS;
2825     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
2826 
2827     sc->set_voltage = sd_set_voltage;
2828     sc->get_dat_lines = sd_get_dat_lines;
2829     sc->get_cmd_line = sd_get_cmd_line;
2830     sc->do_command = sd_do_command;
2831     sc->write_byte = sd_write_byte;
2832     sc->read_byte = sd_read_byte;
2833     sc->receive_ready = sd_receive_ready;
2834     sc->data_ready = sd_data_ready;
2835     sc->enable = sd_enable;
2836     sc->get_inserted = sd_get_inserted;
2837     sc->get_readonly = sd_get_readonly;
2838 }
2839 
2840 static void sd_class_init(ObjectClass *klass, void *data)
2841 {
2842     DeviceClass *dc = DEVICE_CLASS(klass);
2843     SDCardClass *sc = SDMMC_COMMON_CLASS(klass);
2844 
2845     dc->realize = sd_realize;
2846     device_class_set_props(dc, sd_properties);
2847 
2848     sc->set_cid = sd_set_cid;
2849     sc->set_csd = sd_set_csd;
2850     sc->proto = &sd_proto_sd;
2851 }
2852 
2853 /*
2854  * We do not model the chip select pin, so allow the board to select
2855  * whether card should be in SSI or MMC/SD mode.  It is also up to the
2856  * board to ensure that ssi transfers only occur when the chip select
2857  * is asserted.
2858  */
2859 static void sd_spi_class_init(ObjectClass *klass, void *data)
2860 {
2861     DeviceClass *dc = DEVICE_CLASS(klass);
2862     SDCardClass *sc = SDMMC_COMMON_CLASS(klass);
2863 
2864     dc->desc = "SD SPI";
2865     sc->proto = &sd_proto_spi;
2866 }
2867 
2868 static void emmc_class_init(ObjectClass *klass, void *data)
2869 {
2870     DeviceClass *dc = DEVICE_CLASS(klass);
2871     SDCardClass *sc = SDMMC_COMMON_CLASS(klass);
2872 
2873     dc->desc = "eMMC";
2874     dc->realize = emmc_realize;
2875     device_class_set_props(dc, emmc_properties);
2876     /* Reason: Soldered on board */
2877     dc->user_creatable = false;
2878 
2879     sc->proto = &sd_proto_emmc;
2880 
2881     sc->set_cid = emmc_set_cid;
2882     sc->set_csd = emmc_set_csd;
2883 }
2884 
2885 static const TypeInfo sd_types[] = {
2886     {
2887         .name           = TYPE_SDMMC_COMMON,
2888         .parent         = TYPE_DEVICE,
2889         .abstract       = true,
2890         .instance_size  = sizeof(SDState),
2891         .class_size     = sizeof(SDCardClass),
2892         .class_init     = sdmmc_common_class_init,
2893         .instance_init  = sd_instance_init,
2894         .instance_finalize = sd_instance_finalize,
2895     },
2896     {
2897         .name           = TYPE_SD_CARD,
2898         .parent         = TYPE_SDMMC_COMMON,
2899         .class_init     = sd_class_init,
2900     },
2901     {
2902         .name           = TYPE_SD_CARD_SPI,
2903         .parent         = TYPE_SD_CARD,
2904         .class_init     = sd_spi_class_init,
2905     },
2906     {
2907         .name           = TYPE_EMMC,
2908         .parent         = TYPE_SDMMC_COMMON,
2909         .class_init     = emmc_class_init,
2910     },
2911 };
2912 
2913 DEFINE_TYPES(sd_types)
2914