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