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