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