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