xref: /openbmc/qemu/hw/sd/sd.c (revision 3cfafd31)
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 bool address_in_range(SDState *sd, const char *desc,
941                              uint64_t addr, uint32_t length)
942 {
943     if (addr + length > sd->size) {
944         qemu_log_mask(LOG_GUEST_ERROR,
945                       "%s offset %"PRIu64" > card %"PRIu64" [%%%u]\n",
946                       desc, addr, sd->size, length);
947         sd->card_status |= ADDRESS_ERROR;
948         return false;
949     }
950     return true;
951 }
952 
953 static sd_rsp_type_t sd_normal_command(SDState *sd, SDRequest req)
954 {
955     uint32_t rca = 0x0000;
956     uint64_t addr = (sd->ocr & (1 << 30)) ? (uint64_t) req.arg << 9 : req.arg;
957 
958     /* CMD55 precedes an ACMD, so we are not interested in tracing it.
959      * However there is no ACMD55, so we want to trace this particular case.
960      */
961     if (req.cmd != 55 || sd->expecting_acmd) {
962         trace_sdcard_normal_command(sd->proto_name,
963                                     sd_cmd_name(req.cmd), req.cmd,
964                                     req.arg, sd_state_name(sd->state));
965     }
966 
967     /* Not interpreting this as an app command */
968     sd->card_status &= ~APP_CMD;
969 
970     if (sd_cmd_type[req.cmd] == sd_ac
971         || sd_cmd_type[req.cmd] == sd_adtc) {
972         rca = req.arg >> 16;
973     }
974 
975     /* CMD23 (set block count) must be immediately followed by CMD18 or CMD25
976      * if not, its effects are cancelled */
977     if (sd->multi_blk_cnt != 0 && !(req.cmd == 18 || req.cmd == 25)) {
978         sd->multi_blk_cnt = 0;
979     }
980 
981     if (sd_cmd_class[req.cmd] == 6 && FIELD_EX32(sd->ocr, OCR, CARD_CAPACITY)) {
982         /* Only Standard Capacity cards support class 6 commands */
983         return sd_illegal;
984     }
985 
986     switch (req.cmd) {
987     /* Basic commands (Class 0 and Class 1) */
988     case 0:	/* CMD0:   GO_IDLE_STATE */
989         switch (sd->state) {
990         case sd_inactive_state:
991             return sd->spi ? sd_r1 : sd_r0;
992 
993         default:
994             sd->state = sd_idle_state;
995             sd_reset(DEVICE(sd));
996             return sd->spi ? sd_r1 : sd_r0;
997         }
998         break;
999 
1000     case 1:	/* CMD1:   SEND_OP_CMD */
1001         if (!sd->spi)
1002             goto bad_cmd;
1003 
1004         sd->state = sd_transfer_state;
1005         return sd_r1;
1006 
1007     case 2:	/* CMD2:   ALL_SEND_CID */
1008         if (sd->spi)
1009             goto bad_cmd;
1010         switch (sd->state) {
1011         case sd_ready_state:
1012             sd->state = sd_identification_state;
1013             return sd_r2_i;
1014 
1015         default:
1016             break;
1017         }
1018         break;
1019 
1020     case 3:	/* CMD3:   SEND_RELATIVE_ADDR */
1021         if (sd->spi)
1022             goto bad_cmd;
1023         switch (sd->state) {
1024         case sd_identification_state:
1025         case sd_standby_state:
1026             sd->state = sd_standby_state;
1027             sd_set_rca(sd);
1028             return sd_r6;
1029 
1030         default:
1031             break;
1032         }
1033         break;
1034 
1035     case 4:	/* CMD4:   SEND_DSR */
1036         if (sd->spi)
1037             goto bad_cmd;
1038         switch (sd->state) {
1039         case sd_standby_state:
1040             break;
1041 
1042         default:
1043             break;
1044         }
1045         break;
1046 
1047     case 5: /* CMD5: reserved for SDIO cards */
1048         return sd_illegal;
1049 
1050     case 6:	/* CMD6:   SWITCH_FUNCTION */
1051         switch (sd->mode) {
1052         case sd_data_transfer_mode:
1053             sd_function_switch(sd, req.arg);
1054             sd->state = sd_sendingdata_state;
1055             sd->data_start = 0;
1056             sd->data_offset = 0;
1057             return sd_r1;
1058 
1059         default:
1060             break;
1061         }
1062         break;
1063 
1064     case 7:	/* CMD7:   SELECT/DESELECT_CARD */
1065         if (sd->spi)
1066             goto bad_cmd;
1067         switch (sd->state) {
1068         case sd_standby_state:
1069             if (sd->rca != rca)
1070                 return sd_r0;
1071 
1072             sd->state = sd_transfer_state;
1073             return sd_r1b;
1074 
1075         case sd_transfer_state:
1076         case sd_sendingdata_state:
1077             if (sd->rca == rca)
1078                 break;
1079 
1080             sd->state = sd_standby_state;
1081             return sd_r1b;
1082 
1083         case sd_disconnect_state:
1084             if (sd->rca != rca)
1085                 return sd_r0;
1086 
1087             sd->state = sd_programming_state;
1088             return sd_r1b;
1089 
1090         case sd_programming_state:
1091             if (sd->rca == rca)
1092                 break;
1093 
1094             sd->state = sd_disconnect_state;
1095             return sd_r1b;
1096 
1097         default:
1098             break;
1099         }
1100         break;
1101 
1102     case 8:	/* CMD8:   SEND_IF_COND */
1103         if (sd->spec_version < SD_PHY_SPECv2_00_VERS) {
1104             break;
1105         }
1106         if (sd->state != sd_idle_state) {
1107             break;
1108         }
1109         sd->vhs = 0;
1110 
1111         /* No response if not exactly one VHS bit is set.  */
1112         if (!(req.arg >> 8) || (req.arg >> (ctz32(req.arg & ~0xff) + 1))) {
1113             return sd->spi ? sd_r7 : sd_r0;
1114         }
1115 
1116         /* Accept.  */
1117         sd->vhs = req.arg;
1118         return sd_r7;
1119 
1120     case 9:	/* CMD9:   SEND_CSD */
1121         switch (sd->state) {
1122         case sd_standby_state:
1123             if (sd->rca != rca)
1124                 return sd_r0;
1125 
1126             return sd_r2_s;
1127 
1128         case sd_transfer_state:
1129             if (!sd->spi)
1130                 break;
1131             sd->state = sd_sendingdata_state;
1132             memcpy(sd->data, sd->csd, 16);
1133             sd->data_start = addr;
1134             sd->data_offset = 0;
1135             return sd_r1;
1136 
1137         default:
1138             break;
1139         }
1140         break;
1141 
1142     case 10:	/* CMD10:  SEND_CID */
1143         switch (sd->state) {
1144         case sd_standby_state:
1145             if (sd->rca != rca)
1146                 return sd_r0;
1147 
1148             return sd_r2_i;
1149 
1150         case sd_transfer_state:
1151             if (!sd->spi)
1152                 break;
1153             sd->state = sd_sendingdata_state;
1154             memcpy(sd->data, sd->cid, 16);
1155             sd->data_start = addr;
1156             sd->data_offset = 0;
1157             return sd_r1;
1158 
1159         default:
1160             break;
1161         }
1162         break;
1163 
1164     case 12:	/* CMD12:  STOP_TRANSMISSION */
1165         switch (sd->state) {
1166         case sd_sendingdata_state:
1167             sd->state = sd_transfer_state;
1168             return sd_r1b;
1169 
1170         case sd_receivingdata_state:
1171             sd->state = sd_programming_state;
1172             /* Bzzzzzzztt .... Operation complete.  */
1173             sd->state = sd_transfer_state;
1174             return sd_r1b;
1175 
1176         default:
1177             break;
1178         }
1179         break;
1180 
1181     case 13:	/* CMD13:  SEND_STATUS */
1182         switch (sd->mode) {
1183         case sd_data_transfer_mode:
1184             if (!sd->spi && sd->rca != rca) {
1185                 return sd_r0;
1186             }
1187 
1188             return sd_r1;
1189 
1190         default:
1191             break;
1192         }
1193         break;
1194 
1195     case 15:	/* CMD15:  GO_INACTIVE_STATE */
1196         if (sd->spi)
1197             goto bad_cmd;
1198         switch (sd->mode) {
1199         case sd_data_transfer_mode:
1200             if (sd->rca != rca)
1201                 return sd_r0;
1202 
1203             sd->state = sd_inactive_state;
1204             return sd_r0;
1205 
1206         default:
1207             break;
1208         }
1209         break;
1210 
1211     /* Block read commands (Classs 2) */
1212     case 16:	/* CMD16:  SET_BLOCKLEN */
1213         switch (sd->state) {
1214         case sd_transfer_state:
1215             if (req.arg > (1 << HWBLOCK_SHIFT)) {
1216                 sd->card_status |= BLOCK_LEN_ERROR;
1217             } else {
1218                 trace_sdcard_set_blocklen(req.arg);
1219                 sd->blk_len = req.arg;
1220             }
1221 
1222             return sd_r1;
1223 
1224         default:
1225             break;
1226         }
1227         break;
1228 
1229     case 17:	/* CMD17:  READ_SINGLE_BLOCK */
1230     case 18:	/* CMD18:  READ_MULTIPLE_BLOCK */
1231         switch (sd->state) {
1232         case sd_transfer_state:
1233 
1234             if (!address_in_range(sd, "READ_BLOCK", addr, sd->blk_len)) {
1235                 return sd_r1;
1236             }
1237 
1238             sd->state = sd_sendingdata_state;
1239             sd->data_start = addr;
1240             sd->data_offset = 0;
1241             return sd_r1;
1242 
1243         default:
1244             break;
1245         }
1246         break;
1247 
1248     case 19:    /* CMD19: SEND_TUNING_BLOCK (SD) */
1249         if (sd->spec_version < SD_PHY_SPECv3_01_VERS) {
1250             break;
1251         }
1252         if (sd->state == sd_transfer_state) {
1253             sd->state = sd_sendingdata_state;
1254             sd->data_offset = 0;
1255             return sd_r1;
1256         }
1257         break;
1258 
1259     case 23:    /* CMD23: SET_BLOCK_COUNT */
1260         if (sd->spec_version < SD_PHY_SPECv3_01_VERS) {
1261             break;
1262         }
1263         switch (sd->state) {
1264         case sd_transfer_state:
1265             sd->multi_blk_cnt = req.arg;
1266             return sd_r1;
1267 
1268         default:
1269             break;
1270         }
1271         break;
1272 
1273     /* Block write commands (Class 4) */
1274     case 24:	/* CMD24:  WRITE_SINGLE_BLOCK */
1275     case 25:	/* CMD25:  WRITE_MULTIPLE_BLOCK */
1276         switch (sd->state) {
1277         case sd_transfer_state:
1278 
1279             if (!address_in_range(sd, "WRITE_BLOCK", addr, sd->blk_len)) {
1280                 return sd_r1;
1281             }
1282 
1283             sd->state = sd_receivingdata_state;
1284             sd->data_start = addr;
1285             sd->data_offset = 0;
1286             sd->blk_written = 0;
1287 
1288             if (sd->size <= SDSC_MAX_CAPACITY) {
1289                 if (sd_wp_addr(sd, sd->data_start)) {
1290                     sd->card_status |= WP_VIOLATION;
1291                 }
1292             }
1293             if (sd->csd[14] & 0x30) {
1294                 sd->card_status |= WP_VIOLATION;
1295             }
1296             return sd_r1;
1297 
1298         default:
1299             break;
1300         }
1301         break;
1302 
1303     case 26:	/* CMD26:  PROGRAM_CID */
1304         if (sd->spi)
1305             goto bad_cmd;
1306         switch (sd->state) {
1307         case sd_transfer_state:
1308             sd->state = sd_receivingdata_state;
1309             sd->data_start = 0;
1310             sd->data_offset = 0;
1311             return sd_r1;
1312 
1313         default:
1314             break;
1315         }
1316         break;
1317 
1318     case 27:	/* CMD27:  PROGRAM_CSD */
1319         switch (sd->state) {
1320         case sd_transfer_state:
1321             sd->state = sd_receivingdata_state;
1322             sd->data_start = 0;
1323             sd->data_offset = 0;
1324             return sd_r1;
1325 
1326         default:
1327             break;
1328         }
1329         break;
1330 
1331     /* Write protection (Class 6) */
1332     case 28:	/* CMD28:  SET_WRITE_PROT */
1333         if (sd->size > SDSC_MAX_CAPACITY) {
1334             return sd_illegal;
1335         }
1336 
1337         switch (sd->state) {
1338         case sd_transfer_state:
1339             if (!address_in_range(sd, "SET_WRITE_PROT", addr, 1)) {
1340                 return sd_r1b;
1341             }
1342 
1343             sd->state = sd_programming_state;
1344             set_bit(sd_addr_to_wpnum(addr), sd->wp_groups);
1345             /* Bzzzzzzztt .... Operation complete.  */
1346             sd->state = sd_transfer_state;
1347             return sd_r1b;
1348 
1349         default:
1350             break;
1351         }
1352         break;
1353 
1354     case 29:	/* CMD29:  CLR_WRITE_PROT */
1355         if (sd->size > SDSC_MAX_CAPACITY) {
1356             return sd_illegal;
1357         }
1358 
1359         switch (sd->state) {
1360         case sd_transfer_state:
1361             if (!address_in_range(sd, "CLR_WRITE_PROT", addr, 1)) {
1362                 return sd_r1b;
1363             }
1364 
1365             sd->state = sd_programming_state;
1366             clear_bit(sd_addr_to_wpnum(addr), sd->wp_groups);
1367             /* Bzzzzzzztt .... Operation complete.  */
1368             sd->state = sd_transfer_state;
1369             return sd_r1b;
1370 
1371         default:
1372             break;
1373         }
1374         break;
1375 
1376     case 30:	/* CMD30:  SEND_WRITE_PROT */
1377         if (sd->size > SDSC_MAX_CAPACITY) {
1378             return sd_illegal;
1379         }
1380 
1381         switch (sd->state) {
1382         case sd_transfer_state:
1383             if (!address_in_range(sd, "SEND_WRITE_PROT",
1384                                   req.arg, sd->blk_len)) {
1385                 return sd_r1;
1386             }
1387 
1388             sd->state = sd_sendingdata_state;
1389             *(uint32_t *) sd->data = sd_wpbits(sd, req.arg);
1390             sd->data_start = addr;
1391             sd->data_offset = 0;
1392             return sd_r1;
1393 
1394         default:
1395             break;
1396         }
1397         break;
1398 
1399     /* Erase commands (Class 5) */
1400     case 32:	/* CMD32:  ERASE_WR_BLK_START */
1401         switch (sd->state) {
1402         case sd_transfer_state:
1403             sd->erase_start = req.arg;
1404             return sd_r1;
1405 
1406         default:
1407             break;
1408         }
1409         break;
1410 
1411     case 33:	/* CMD33:  ERASE_WR_BLK_END */
1412         switch (sd->state) {
1413         case sd_transfer_state:
1414             sd->erase_end = req.arg;
1415             return sd_r1;
1416 
1417         default:
1418             break;
1419         }
1420         break;
1421 
1422     case 38:	/* CMD38:  ERASE */
1423         switch (sd->state) {
1424         case sd_transfer_state:
1425             if (sd->csd[14] & 0x30) {
1426                 sd->card_status |= WP_VIOLATION;
1427                 return sd_r1b;
1428             }
1429 
1430             sd->state = sd_programming_state;
1431             sd_erase(sd);
1432             /* Bzzzzzzztt .... Operation complete.  */
1433             sd->state = sd_transfer_state;
1434             return sd_r1b;
1435 
1436         default:
1437             break;
1438         }
1439         break;
1440 
1441     /* Lock card commands (Class 7) */
1442     case 42:	/* CMD42:  LOCK_UNLOCK */
1443         switch (sd->state) {
1444         case sd_transfer_state:
1445             sd->state = sd_receivingdata_state;
1446             sd->data_start = 0;
1447             sd->data_offset = 0;
1448             return sd_r1;
1449 
1450         default:
1451             break;
1452         }
1453         break;
1454 
1455     case 52 ... 54:
1456         /* CMD52, CMD53, CMD54: reserved for SDIO cards
1457          * (see the SDIO Simplified Specification V2.0)
1458          * Handle as illegal command but do not complain
1459          * on stderr, as some OSes may use these in their
1460          * probing for presence of an SDIO card.
1461          */
1462         return sd_illegal;
1463 
1464     /* Application specific commands (Class 8) */
1465     case 55:	/* CMD55:  APP_CMD */
1466         switch (sd->state) {
1467         case sd_ready_state:
1468         case sd_identification_state:
1469         case sd_inactive_state:
1470             return sd_illegal;
1471         case sd_idle_state:
1472             if (rca) {
1473                 qemu_log_mask(LOG_GUEST_ERROR,
1474                               "SD: illegal RCA 0x%04x for APP_CMD\n", req.cmd);
1475             }
1476         default:
1477             break;
1478         }
1479         if (!sd->spi) {
1480             if (sd->rca != rca) {
1481                 return sd_r0;
1482             }
1483         }
1484         sd->expecting_acmd = true;
1485         sd->card_status |= APP_CMD;
1486         return sd_r1;
1487 
1488     case 56:	/* CMD56:  GEN_CMD */
1489         switch (sd->state) {
1490         case sd_transfer_state:
1491             sd->data_offset = 0;
1492             if (req.arg & 1)
1493                 sd->state = sd_sendingdata_state;
1494             else
1495                 sd->state = sd_receivingdata_state;
1496             return sd_r1;
1497 
1498         default:
1499             break;
1500         }
1501         break;
1502 
1503     case 58:    /* CMD58:   READ_OCR (SPI) */
1504         if (!sd->spi) {
1505             goto bad_cmd;
1506         }
1507         return sd_r3;
1508 
1509     case 59:    /* CMD59:   CRC_ON_OFF (SPI) */
1510         if (!sd->spi) {
1511             goto bad_cmd;
1512         }
1513         return sd_r1;
1514 
1515     default:
1516     bad_cmd:
1517         qemu_log_mask(LOG_GUEST_ERROR, "SD: Unknown CMD%i\n", req.cmd);
1518         return sd_illegal;
1519     }
1520 
1521     qemu_log_mask(LOG_GUEST_ERROR, "SD: CMD%i in a wrong state: %s\n",
1522                   req.cmd, sd_state_name(sd->state));
1523     return sd_illegal;
1524 }
1525 
1526 static sd_rsp_type_t sd_app_command(SDState *sd,
1527                                     SDRequest req)
1528 {
1529     trace_sdcard_app_command(sd->proto_name, sd_acmd_name(req.cmd),
1530                              req.cmd, req.arg, sd_state_name(sd->state));
1531     sd->card_status |= APP_CMD;
1532     switch (req.cmd) {
1533     case 6:	/* ACMD6:  SET_BUS_WIDTH */
1534         if (sd->spi) {
1535             goto unimplemented_spi_cmd;
1536         }
1537         switch (sd->state) {
1538         case sd_transfer_state:
1539             sd->sd_status[0] &= 0x3f;
1540             sd->sd_status[0] |= (req.arg & 0x03) << 6;
1541             return sd_r1;
1542 
1543         default:
1544             break;
1545         }
1546         break;
1547 
1548     case 13:	/* ACMD13: SD_STATUS */
1549         switch (sd->state) {
1550         case sd_transfer_state:
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 22:	/* ACMD22: SEND_NUM_WR_BLOCKS */
1562         switch (sd->state) {
1563         case sd_transfer_state:
1564             *(uint32_t *) sd->data = sd->blk_written;
1565 
1566             sd->state = sd_sendingdata_state;
1567             sd->data_start = 0;
1568             sd->data_offset = 0;
1569             return sd_r1;
1570 
1571         default:
1572             break;
1573         }
1574         break;
1575 
1576     case 23:	/* ACMD23: SET_WR_BLK_ERASE_COUNT */
1577         switch (sd->state) {
1578         case sd_transfer_state:
1579             return sd_r1;
1580 
1581         default:
1582             break;
1583         }
1584         break;
1585 
1586     case 41:	/* ACMD41: SD_APP_OP_COND */
1587         if (sd->spi) {
1588             /* SEND_OP_CMD */
1589             sd->state = sd_transfer_state;
1590             return sd_r1;
1591         }
1592         if (sd->state != sd_idle_state) {
1593             break;
1594         }
1595         /* If it's the first ACMD41 since reset, we need to decide
1596          * whether to power up. If this is not an enquiry ACMD41,
1597          * we immediately report power on and proceed below to the
1598          * ready state, but if it is, we set a timer to model a
1599          * delay for power up. This works around a bug in EDK2
1600          * UEFI, which sends an initial enquiry ACMD41, but
1601          * assumes that the card is in ready state as soon as it
1602          * sees the power up bit set. */
1603         if (!FIELD_EX32(sd->ocr, OCR, CARD_POWER_UP)) {
1604             if ((req.arg & ACMD41_ENQUIRY_MASK) != 0) {
1605                 timer_del(sd->ocr_power_timer);
1606                 sd_ocr_powerup(sd);
1607             } else {
1608                 trace_sdcard_inquiry_cmd41();
1609                 if (!timer_pending(sd->ocr_power_timer)) {
1610                     timer_mod_ns(sd->ocr_power_timer,
1611                                  (qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL)
1612                                   + OCR_POWER_DELAY_NS));
1613                 }
1614             }
1615         }
1616 
1617         if (FIELD_EX32(sd->ocr & req.arg, OCR, VDD_VOLTAGE_WINDOW)) {
1618             /* We accept any voltage.  10000 V is nothing.
1619              *
1620              * Once we're powered up, we advance straight to ready state
1621              * unless it's an enquiry ACMD41 (bits 23:0 == 0).
1622              */
1623             sd->state = sd_ready_state;
1624         }
1625 
1626         return sd_r3;
1627 
1628     case 42:	/* ACMD42: SET_CLR_CARD_DETECT */
1629         switch (sd->state) {
1630         case sd_transfer_state:
1631             /* Bringing in the 50KOhm pull-up resistor... Done.  */
1632             return sd_r1;
1633 
1634         default:
1635             break;
1636         }
1637         break;
1638 
1639     case 51:	/* ACMD51: SEND_SCR */
1640         switch (sd->state) {
1641         case sd_transfer_state:
1642             sd->state = sd_sendingdata_state;
1643             sd->data_start = 0;
1644             sd->data_offset = 0;
1645             return sd_r1;
1646 
1647         default:
1648             break;
1649         }
1650         break;
1651 
1652     case 18:    /* Reserved for SD security applications */
1653     case 25:
1654     case 26:
1655     case 38:
1656     case 43 ... 49:
1657         /* Refer to the "SD Specifications Part3 Security Specification" for
1658          * information about the SD Security Features.
1659          */
1660         qemu_log_mask(LOG_UNIMP, "SD: CMD%i Security not implemented\n",
1661                       req.cmd);
1662         return sd_illegal;
1663 
1664     default:
1665         /* Fall back to standard commands.  */
1666         return sd_normal_command(sd, req);
1667 
1668     unimplemented_spi_cmd:
1669         /* Commands that are recognised but not yet implemented in SPI mode.  */
1670         qemu_log_mask(LOG_UNIMP, "SD: CMD%i not implemented in SPI mode\n",
1671                       req.cmd);
1672         return sd_illegal;
1673     }
1674 
1675     qemu_log_mask(LOG_GUEST_ERROR, "SD: ACMD%i in a wrong state\n", req.cmd);
1676     return sd_illegal;
1677 }
1678 
1679 static int cmd_valid_while_locked(SDState *sd, const uint8_t cmd)
1680 {
1681     /* Valid commands in locked state:
1682      * basic class (0)
1683      * lock card class (7)
1684      * CMD16
1685      * implicitly, the ACMD prefix CMD55
1686      * ACMD41 and ACMD42
1687      * Anything else provokes an "illegal command" response.
1688      */
1689     if (sd->expecting_acmd) {
1690         return cmd == 41 || cmd == 42;
1691     }
1692     if (cmd == 16 || cmd == 55) {
1693         return 1;
1694     }
1695     return sd_cmd_class[cmd] == 0 || sd_cmd_class[cmd] == 7;
1696 }
1697 
1698 int sd_do_command(SDState *sd, SDRequest *req,
1699                   uint8_t *response) {
1700     int last_state;
1701     sd_rsp_type_t rtype;
1702     int rsplen;
1703 
1704     if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable) {
1705         return 0;
1706     }
1707 
1708     if (sd_req_crc_validate(req)) {
1709         sd->card_status |= COM_CRC_ERROR;
1710         rtype = sd_illegal;
1711         goto send_response;
1712     }
1713 
1714     if (req->cmd >= SDMMC_CMD_MAX) {
1715         qemu_log_mask(LOG_GUEST_ERROR, "SD: incorrect command 0x%02x\n",
1716                       req->cmd);
1717         req->cmd &= 0x3f;
1718     }
1719 
1720     if (sd->card_status & CARD_IS_LOCKED) {
1721         if (!cmd_valid_while_locked(sd, req->cmd)) {
1722             sd->card_status |= ILLEGAL_COMMAND;
1723             sd->expecting_acmd = false;
1724             qemu_log_mask(LOG_GUEST_ERROR, "SD: Card is locked\n");
1725             rtype = sd_illegal;
1726             goto send_response;
1727         }
1728     }
1729 
1730     last_state = sd->state;
1731     sd_set_mode(sd);
1732 
1733     if (sd->expecting_acmd) {
1734         sd->expecting_acmd = false;
1735         rtype = sd_app_command(sd, *req);
1736     } else {
1737         rtype = sd_normal_command(sd, *req);
1738     }
1739 
1740     if (rtype == sd_illegal) {
1741         sd->card_status |= ILLEGAL_COMMAND;
1742     } else {
1743         /* Valid command, we can update the 'state before command' bits.
1744          * (Do this now so they appear in r1 responses.)
1745          */
1746         sd->current_cmd = req->cmd;
1747         sd->card_status &= ~CURRENT_STATE;
1748         sd->card_status |= (last_state << 9);
1749     }
1750 
1751 send_response:
1752     switch (rtype) {
1753     case sd_r1:
1754     case sd_r1b:
1755         sd_response_r1_make(sd, response);
1756         rsplen = 4;
1757         break;
1758 
1759     case sd_r2_i:
1760         memcpy(response, sd->cid, sizeof(sd->cid));
1761         rsplen = 16;
1762         break;
1763 
1764     case sd_r2_s:
1765         memcpy(response, sd->csd, sizeof(sd->csd));
1766         rsplen = 16;
1767         break;
1768 
1769     case sd_r3:
1770         sd_response_r3_make(sd, response);
1771         rsplen = 4;
1772         break;
1773 
1774     case sd_r6:
1775         sd_response_r6_make(sd, response);
1776         rsplen = 4;
1777         break;
1778 
1779     case sd_r7:
1780         sd_response_r7_make(sd, response);
1781         rsplen = 4;
1782         break;
1783 
1784     case sd_r0:
1785     case sd_illegal:
1786         rsplen = 0;
1787         break;
1788     default:
1789         g_assert_not_reached();
1790     }
1791     trace_sdcard_response(sd_response_name(rtype), rsplen);
1792 
1793     if (rtype != sd_illegal) {
1794         /* Clear the "clear on valid command" status bits now we've
1795          * sent any response
1796          */
1797         sd->card_status &= ~CARD_STATUS_B;
1798     }
1799 
1800 #ifdef DEBUG_SD
1801     qemu_hexdump(stderr, "Response", response, rsplen);
1802 #endif
1803 
1804     return rsplen;
1805 }
1806 
1807 void sd_write_byte(SDState *sd, uint8_t value)
1808 {
1809     int i;
1810 
1811     if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable)
1812         return;
1813 
1814     if (sd->state != sd_receivingdata_state) {
1815         qemu_log_mask(LOG_GUEST_ERROR,
1816                       "%s: not in Receiving-Data state\n", __func__);
1817         return;
1818     }
1819 
1820     if (sd->card_status & (ADDRESS_ERROR | WP_VIOLATION))
1821         return;
1822 
1823     trace_sdcard_write_data(sd->proto_name,
1824                             sd_acmd_name(sd->current_cmd),
1825                             sd->current_cmd, value);
1826     switch (sd->current_cmd) {
1827     case 24:	/* CMD24:  WRITE_SINGLE_BLOCK */
1828         sd->data[sd->data_offset ++] = value;
1829         if (sd->data_offset >= sd->blk_len) {
1830             /* TODO: Check CRC before committing */
1831             sd->state = sd_programming_state;
1832             BLK_WRITE_BLOCK(sd->data_start, sd->data_offset);
1833             sd->blk_written ++;
1834             sd->csd[14] |= 0x40;
1835             /* Bzzzzzzztt .... Operation complete.  */
1836             sd->state = sd_transfer_state;
1837         }
1838         break;
1839 
1840     case 25:	/* CMD25:  WRITE_MULTIPLE_BLOCK */
1841         if (sd->data_offset == 0) {
1842             /* Start of the block - let's check the address is valid */
1843             if (!address_in_range(sd, "WRITE_MULTIPLE_BLOCK",
1844                                   sd->data_start, sd->blk_len)) {
1845                 break;
1846             }
1847             if (sd->size <= SDSC_MAX_CAPACITY) {
1848                 if (sd_wp_addr(sd, sd->data_start)) {
1849                     sd->card_status |= WP_VIOLATION;
1850                     break;
1851                 }
1852             }
1853         }
1854         sd->data[sd->data_offset++] = value;
1855         if (sd->data_offset >= sd->blk_len) {
1856             /* TODO: Check CRC before committing */
1857             sd->state = sd_programming_state;
1858             BLK_WRITE_BLOCK(sd->data_start, sd->data_offset);
1859             sd->blk_written++;
1860             sd->data_start += sd->blk_len;
1861             sd->data_offset = 0;
1862             sd->csd[14] |= 0x40;
1863 
1864             /* Bzzzzzzztt .... Operation complete.  */
1865             if (sd->multi_blk_cnt != 0) {
1866                 if (--sd->multi_blk_cnt == 0) {
1867                     /* Stop! */
1868                     sd->state = sd_transfer_state;
1869                     break;
1870                 }
1871             }
1872 
1873             sd->state = sd_receivingdata_state;
1874         }
1875         break;
1876 
1877     case 26:	/* CMD26:  PROGRAM_CID */
1878         sd->data[sd->data_offset ++] = value;
1879         if (sd->data_offset >= sizeof(sd->cid)) {
1880             /* TODO: Check CRC before committing */
1881             sd->state = sd_programming_state;
1882             for (i = 0; i < sizeof(sd->cid); i ++)
1883                 if ((sd->cid[i] | 0x00) != sd->data[i])
1884                     sd->card_status |= CID_CSD_OVERWRITE;
1885 
1886             if (!(sd->card_status & CID_CSD_OVERWRITE))
1887                 for (i = 0; i < sizeof(sd->cid); i ++) {
1888                     sd->cid[i] |= 0x00;
1889                     sd->cid[i] &= sd->data[i];
1890                 }
1891             /* Bzzzzzzztt .... Operation complete.  */
1892             sd->state = sd_transfer_state;
1893         }
1894         break;
1895 
1896     case 27:	/* CMD27:  PROGRAM_CSD */
1897         sd->data[sd->data_offset ++] = value;
1898         if (sd->data_offset >= sizeof(sd->csd)) {
1899             /* TODO: Check CRC before committing */
1900             sd->state = sd_programming_state;
1901             for (i = 0; i < sizeof(sd->csd); i ++)
1902                 if ((sd->csd[i] | sd_csd_rw_mask[i]) !=
1903                     (sd->data[i] | sd_csd_rw_mask[i]))
1904                     sd->card_status |= CID_CSD_OVERWRITE;
1905 
1906             /* Copy flag (OTP) & Permanent write protect */
1907             if (sd->csd[14] & ~sd->data[14] & 0x60)
1908                 sd->card_status |= CID_CSD_OVERWRITE;
1909 
1910             if (!(sd->card_status & CID_CSD_OVERWRITE))
1911                 for (i = 0; i < sizeof(sd->csd); i ++) {
1912                     sd->csd[i] |= sd_csd_rw_mask[i];
1913                     sd->csd[i] &= sd->data[i];
1914                 }
1915             /* Bzzzzzzztt .... Operation complete.  */
1916             sd->state = sd_transfer_state;
1917         }
1918         break;
1919 
1920     case 42:	/* CMD42:  LOCK_UNLOCK */
1921         sd->data[sd->data_offset ++] = value;
1922         if (sd->data_offset >= sd->blk_len) {
1923             /* TODO: Check CRC before committing */
1924             sd->state = sd_programming_state;
1925             sd_lock_command(sd);
1926             /* Bzzzzzzztt .... Operation complete.  */
1927             sd->state = sd_transfer_state;
1928         }
1929         break;
1930 
1931     case 56:	/* CMD56:  GEN_CMD */
1932         sd->data[sd->data_offset ++] = value;
1933         if (sd->data_offset >= sd->blk_len) {
1934             APP_WRITE_BLOCK(sd->data_start, sd->data_offset);
1935             sd->state = sd_transfer_state;
1936         }
1937         break;
1938 
1939     default:
1940         qemu_log_mask(LOG_GUEST_ERROR, "%s: unknown command\n", __func__);
1941         break;
1942     }
1943 }
1944 
1945 #define SD_TUNING_BLOCK_SIZE    64
1946 
1947 static const uint8_t sd_tuning_block_pattern[SD_TUNING_BLOCK_SIZE] = {
1948     /* See: Physical Layer Simplified Specification Version 3.01, Table 4-2 */
1949     0xff, 0x0f, 0xff, 0x00,         0x0f, 0xfc, 0xc3, 0xcc,
1950     0xc3, 0x3c, 0xcc, 0xff,         0xfe, 0xff, 0xfe, 0xef,
1951     0xff, 0xdf, 0xff, 0xdd,         0xff, 0xfb, 0xff, 0xfb,
1952     0xbf, 0xff, 0x7f, 0xff,         0x77, 0xf7, 0xbd, 0xef,
1953     0xff, 0xf0, 0xff, 0xf0,         0x0f, 0xfc, 0xcc, 0x3c,
1954     0xcc, 0x33, 0xcc, 0xcf,         0xff, 0xef, 0xff, 0xee,
1955     0xff, 0xfd, 0xff, 0xfd,         0xdf, 0xff, 0xbf, 0xff,
1956     0xbb, 0xff, 0xf7, 0xff,         0xf7, 0x7f, 0x7b, 0xde,
1957 };
1958 
1959 uint8_t sd_read_byte(SDState *sd)
1960 {
1961     /* TODO: Append CRCs */
1962     uint8_t ret;
1963     uint32_t io_len;
1964 
1965     if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable)
1966         return 0x00;
1967 
1968     if (sd->state != sd_sendingdata_state) {
1969         qemu_log_mask(LOG_GUEST_ERROR,
1970                       "%s: not in Sending-Data state\n", __func__);
1971         return 0x00;
1972     }
1973 
1974     if (sd->card_status & (ADDRESS_ERROR | WP_VIOLATION))
1975         return 0x00;
1976 
1977     io_len = (sd->ocr & (1 << 30)) ? 512 : sd->blk_len;
1978 
1979     trace_sdcard_read_data(sd->proto_name,
1980                            sd_acmd_name(sd->current_cmd),
1981                            sd->current_cmd, io_len);
1982     switch (sd->current_cmd) {
1983     case 6:	/* CMD6:   SWITCH_FUNCTION */
1984         ret = sd->data[sd->data_offset ++];
1985 
1986         if (sd->data_offset >= 64)
1987             sd->state = sd_transfer_state;
1988         break;
1989 
1990     case 9:	/* CMD9:   SEND_CSD */
1991     case 10:	/* CMD10:  SEND_CID */
1992         ret = sd->data[sd->data_offset ++];
1993 
1994         if (sd->data_offset >= 16)
1995             sd->state = sd_transfer_state;
1996         break;
1997 
1998     case 13:	/* ACMD13: SD_STATUS */
1999         ret = sd->sd_status[sd->data_offset ++];
2000 
2001         if (sd->data_offset >= sizeof(sd->sd_status))
2002             sd->state = sd_transfer_state;
2003         break;
2004 
2005     case 17:	/* CMD17:  READ_SINGLE_BLOCK */
2006         if (sd->data_offset == 0)
2007             BLK_READ_BLOCK(sd->data_start, io_len);
2008         ret = sd->data[sd->data_offset ++];
2009 
2010         if (sd->data_offset >= io_len)
2011             sd->state = sd_transfer_state;
2012         break;
2013 
2014     case 18:	/* CMD18:  READ_MULTIPLE_BLOCK */
2015         if (sd->data_offset == 0) {
2016             if (!address_in_range(sd, "READ_MULTIPLE_BLOCK",
2017                                   sd->data_start, io_len)) {
2018                 return 0x00;
2019             }
2020             BLK_READ_BLOCK(sd->data_start, io_len);
2021         }
2022         ret = sd->data[sd->data_offset ++];
2023 
2024         if (sd->data_offset >= io_len) {
2025             sd->data_start += io_len;
2026             sd->data_offset = 0;
2027 
2028             if (sd->multi_blk_cnt != 0) {
2029                 if (--sd->multi_blk_cnt == 0) {
2030                     /* Stop! */
2031                     sd->state = sd_transfer_state;
2032                     break;
2033                 }
2034             }
2035         }
2036         break;
2037 
2038     case 19:    /* CMD19:  SEND_TUNING_BLOCK (SD) */
2039         if (sd->data_offset >= SD_TUNING_BLOCK_SIZE - 1) {
2040             sd->state = sd_transfer_state;
2041         }
2042         ret = sd_tuning_block_pattern[sd->data_offset++];
2043         break;
2044 
2045     case 22:	/* ACMD22: SEND_NUM_WR_BLOCKS */
2046         ret = sd->data[sd->data_offset ++];
2047 
2048         if (sd->data_offset >= 4)
2049             sd->state = sd_transfer_state;
2050         break;
2051 
2052     case 30:	/* CMD30:  SEND_WRITE_PROT */
2053         ret = sd->data[sd->data_offset ++];
2054 
2055         if (sd->data_offset >= 4)
2056             sd->state = sd_transfer_state;
2057         break;
2058 
2059     case 51:	/* ACMD51: SEND_SCR */
2060         ret = sd->scr[sd->data_offset ++];
2061 
2062         if (sd->data_offset >= sizeof(sd->scr))
2063             sd->state = sd_transfer_state;
2064         break;
2065 
2066     case 56:	/* CMD56:  GEN_CMD */
2067         if (sd->data_offset == 0)
2068             APP_READ_BLOCK(sd->data_start, sd->blk_len);
2069         ret = sd->data[sd->data_offset ++];
2070 
2071         if (sd->data_offset >= sd->blk_len)
2072             sd->state = sd_transfer_state;
2073         break;
2074 
2075     default:
2076         qemu_log_mask(LOG_GUEST_ERROR, "%s: unknown command\n", __func__);
2077         return 0x00;
2078     }
2079 
2080     return ret;
2081 }
2082 
2083 static bool sd_receive_ready(SDState *sd)
2084 {
2085     return sd->state == sd_receivingdata_state;
2086 }
2087 
2088 static bool sd_data_ready(SDState *sd)
2089 {
2090     return sd->state == sd_sendingdata_state;
2091 }
2092 
2093 void sd_enable(SDState *sd, bool enable)
2094 {
2095     sd->enable = enable;
2096 }
2097 
2098 static void sd_instance_init(Object *obj)
2099 {
2100     SDState *sd = SD_CARD(obj);
2101 
2102     sd->enable = true;
2103     sd->ocr_power_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, sd_ocr_powerup, sd);
2104 }
2105 
2106 static void sd_instance_finalize(Object *obj)
2107 {
2108     SDState *sd = SD_CARD(obj);
2109 
2110     timer_free(sd->ocr_power_timer);
2111 }
2112 
2113 static void sd_realize(DeviceState *dev, Error **errp)
2114 {
2115     SDState *sd = SD_CARD(dev);
2116     int ret;
2117 
2118     sd->proto_name = sd->spi ? "SPI" : "SD";
2119 
2120     switch (sd->spec_version) {
2121     case SD_PHY_SPECv1_10_VERS
2122      ... SD_PHY_SPECv3_01_VERS:
2123         break;
2124     default:
2125         error_setg(errp, "Invalid SD card Spec version: %u", sd->spec_version);
2126         return;
2127     }
2128 
2129     if (sd->blk) {
2130         int64_t blk_size;
2131 
2132         if (!blk_supports_write_perm(sd->blk)) {
2133             error_setg(errp, "Cannot use read-only drive as SD card");
2134             return;
2135         }
2136 
2137         blk_size = blk_getlength(sd->blk);
2138         if (blk_size > 0 && !is_power_of_2(blk_size)) {
2139             int64_t blk_size_aligned = pow2ceil(blk_size);
2140             char *blk_size_str;
2141 
2142             blk_size_str = size_to_str(blk_size);
2143             error_setg(errp, "Invalid SD card size: %s", blk_size_str);
2144             g_free(blk_size_str);
2145 
2146             blk_size_str = size_to_str(blk_size_aligned);
2147             error_append_hint(errp,
2148                               "SD card size has to be a power of 2, e.g. %s.\n"
2149                               "You can resize disk images with"
2150                               " 'qemu-img resize <imagefile> <new-size>'\n"
2151                               "(note that this will lose data if you make the"
2152                               " image smaller than it currently is).\n",
2153                               blk_size_str);
2154             g_free(blk_size_str);
2155 
2156             return;
2157         }
2158 
2159         ret = blk_set_perm(sd->blk, BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE,
2160                            BLK_PERM_ALL, errp);
2161         if (ret < 0) {
2162             return;
2163         }
2164         blk_set_dev_ops(sd->blk, &sd_block_ops, sd);
2165     }
2166 }
2167 
2168 static Property sd_properties[] = {
2169     DEFINE_PROP_UINT8("spec_version", SDState,
2170                       spec_version, SD_PHY_SPECv2_00_VERS),
2171     DEFINE_PROP_DRIVE("drive", SDState, blk),
2172     /* We do not model the chip select pin, so allow the board to select
2173      * whether card should be in SSI or MMC/SD mode.  It is also up to the
2174      * board to ensure that ssi transfers only occur when the chip select
2175      * is asserted.  */
2176     DEFINE_PROP_BOOL("spi", SDState, spi, false),
2177     DEFINE_PROP_END_OF_LIST()
2178 };
2179 
2180 static void sd_class_init(ObjectClass *klass, void *data)
2181 {
2182     DeviceClass *dc = DEVICE_CLASS(klass);
2183     SDCardClass *sc = SD_CARD_CLASS(klass);
2184 
2185     dc->realize = sd_realize;
2186     device_class_set_props(dc, sd_properties);
2187     dc->vmsd = &sd_vmstate;
2188     dc->reset = sd_reset;
2189     dc->bus_type = TYPE_SD_BUS;
2190     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
2191 
2192     sc->set_voltage = sd_set_voltage;
2193     sc->get_dat_lines = sd_get_dat_lines;
2194     sc->get_cmd_line = sd_get_cmd_line;
2195     sc->do_command = sd_do_command;
2196     sc->write_byte = sd_write_byte;
2197     sc->read_byte = sd_read_byte;
2198     sc->receive_ready = sd_receive_ready;
2199     sc->data_ready = sd_data_ready;
2200     sc->enable = sd_enable;
2201     sc->get_inserted = sd_get_inserted;
2202     sc->get_readonly = sd_get_readonly;
2203 }
2204 
2205 static const TypeInfo sd_info = {
2206     .name = TYPE_SD_CARD,
2207     .parent = TYPE_DEVICE,
2208     .instance_size = sizeof(SDState),
2209     .class_size = sizeof(SDCardClass),
2210     .class_init = sd_class_init,
2211     .instance_init = sd_instance_init,
2212     .instance_finalize = sd_instance_finalize,
2213 };
2214 
2215 static void sd_register_types(void)
2216 {
2217     type_register_static(&sd_info);
2218 }
2219 
2220 type_init(sd_register_types)
2221