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