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