xref: /openbmc/qemu/hw/sd/sd.c (revision 7acafcfa)
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     if (!qdev_prop_set_drive_err(dev, "drive", blk, &err)) {
710         error_reportf_err(err, "sd_init failed: ");
711         return NULL;
712     }
713     qdev_prop_set_bit(dev, "spi", is_spi);
714 
715     /*
716      * Realizing the device properly would put it into the QOM
717      * composition tree even though it is not plugged into an
718      * appropriate bus.  That's a no-no.  Hide the device from
719      * QOM/qdev, and call its qdev realize callback directly.
720      */
721     object_ref(obj);
722     object_unparent(obj);
723     sd_realize(dev, &err);
724     if (err) {
725         error_reportf_err(err, "sd_init failed: ");
726         return NULL;
727     }
728 
729     sd = SD_CARD(dev);
730     sd->me_no_qdev_me_kill_mammoth_with_rocks = true;
731     return sd;
732 }
733 
734 void sd_set_cb(SDState *sd, qemu_irq readonly, qemu_irq insert)
735 {
736     sd->readonly_cb = readonly;
737     sd->inserted_cb = insert;
738     qemu_set_irq(readonly, sd->blk ? blk_is_read_only(sd->blk) : 0);
739     qemu_set_irq(insert, sd->blk ? blk_is_inserted(sd->blk) : 0);
740 }
741 
742 static void sd_erase(SDState *sd)
743 {
744     int i;
745     uint64_t erase_start = sd->erase_start;
746     uint64_t erase_end = sd->erase_end;
747 
748     trace_sdcard_erase();
749     if (!sd->erase_start || !sd->erase_end) {
750         sd->card_status |= ERASE_SEQ_ERROR;
751         return;
752     }
753 
754     if (FIELD_EX32(sd->ocr, OCR, CARD_CAPACITY)) {
755         /* High capacity memory card: erase units are 512 byte blocks */
756         erase_start *= 512;
757         erase_end *= 512;
758     }
759 
760     erase_start = sd_addr_to_wpnum(erase_start);
761     erase_end = sd_addr_to_wpnum(erase_end);
762     sd->erase_start = 0;
763     sd->erase_end = 0;
764     sd->csd[14] |= 0x40;
765 
766     for (i = erase_start; i <= erase_end; i++) {
767         if (test_bit(i, sd->wp_groups)) {
768             sd->card_status |= WP_ERASE_SKIP;
769         }
770     }
771 }
772 
773 static uint32_t sd_wpbits(SDState *sd, uint64_t addr)
774 {
775     uint32_t i, wpnum;
776     uint32_t ret = 0;
777 
778     wpnum = sd_addr_to_wpnum(addr);
779 
780     for (i = 0; i < 32; i++, wpnum++, addr += WPGROUP_SIZE) {
781         if (addr < sd->size && test_bit(wpnum, sd->wp_groups)) {
782             ret |= (1 << i);
783         }
784     }
785 
786     return ret;
787 }
788 
789 static void sd_function_switch(SDState *sd, uint32_t arg)
790 {
791     int i, mode, new_func;
792     mode = !!(arg & 0x80000000);
793 
794     sd->data[0] = 0x00;		/* Maximum current consumption */
795     sd->data[1] = 0x01;
796     sd->data[2] = 0x80;		/* Supported group 6 functions */
797     sd->data[3] = 0x01;
798     sd->data[4] = 0x80;		/* Supported group 5 functions */
799     sd->data[5] = 0x01;
800     sd->data[6] = 0x80;		/* Supported group 4 functions */
801     sd->data[7] = 0x01;
802     sd->data[8] = 0x80;		/* Supported group 3 functions */
803     sd->data[9] = 0x01;
804     sd->data[10] = 0x80;	/* Supported group 2 functions */
805     sd->data[11] = 0x43;
806     sd->data[12] = 0x80;	/* Supported group 1 functions */
807     sd->data[13] = 0x03;
808     for (i = 0; i < 6; i ++) {
809         new_func = (arg >> (i * 4)) & 0x0f;
810         if (mode && new_func != 0x0f)
811             sd->function_group[i] = new_func;
812         sd->data[14 + (i >> 1)] = new_func << ((i * 4) & 4);
813     }
814     memset(&sd->data[17], 0, 47);
815     stw_be_p(sd->data + 64, sd_crc16(sd->data, 64));
816 }
817 
818 static inline bool sd_wp_addr(SDState *sd, uint64_t addr)
819 {
820     return test_bit(sd_addr_to_wpnum(addr), sd->wp_groups);
821 }
822 
823 static void sd_lock_command(SDState *sd)
824 {
825     int erase, lock, clr_pwd, set_pwd, pwd_len;
826     erase = !!(sd->data[0] & 0x08);
827     lock = sd->data[0] & 0x04;
828     clr_pwd = sd->data[0] & 0x02;
829     set_pwd = sd->data[0] & 0x01;
830 
831     if (sd->blk_len > 1)
832         pwd_len = sd->data[1];
833     else
834         pwd_len = 0;
835 
836     if (lock) {
837         trace_sdcard_lock();
838     } else {
839         trace_sdcard_unlock();
840     }
841     if (erase) {
842         if (!(sd->card_status & CARD_IS_LOCKED) || sd->blk_len > 1 ||
843                         set_pwd || clr_pwd || lock || sd->wp_switch ||
844                         (sd->csd[14] & 0x20)) {
845             sd->card_status |= LOCK_UNLOCK_FAILED;
846             return;
847         }
848         bitmap_zero(sd->wp_groups, sd->wpgrps_size);
849         sd->csd[14] &= ~0x10;
850         sd->card_status &= ~CARD_IS_LOCKED;
851         sd->pwd_len = 0;
852         /* Erasing the entire card here! */
853         fprintf(stderr, "SD: Card force-erased by CMD42\n");
854         return;
855     }
856 
857     if (sd->blk_len < 2 + pwd_len ||
858                     pwd_len <= sd->pwd_len ||
859                     pwd_len > sd->pwd_len + 16) {
860         sd->card_status |= LOCK_UNLOCK_FAILED;
861         return;
862     }
863 
864     if (sd->pwd_len && memcmp(sd->pwd, sd->data + 2, sd->pwd_len)) {
865         sd->card_status |= LOCK_UNLOCK_FAILED;
866         return;
867     }
868 
869     pwd_len -= sd->pwd_len;
870     if ((pwd_len && !set_pwd) ||
871                     (clr_pwd && (set_pwd || lock)) ||
872                     (lock && !sd->pwd_len && !set_pwd) ||
873                     (!set_pwd && !clr_pwd &&
874                      (((sd->card_status & CARD_IS_LOCKED) && lock) ||
875                       (!(sd->card_status & CARD_IS_LOCKED) && !lock)))) {
876         sd->card_status |= LOCK_UNLOCK_FAILED;
877         return;
878     }
879 
880     if (set_pwd) {
881         memcpy(sd->pwd, sd->data + 2 + sd->pwd_len, pwd_len);
882         sd->pwd_len = pwd_len;
883     }
884 
885     if (clr_pwd) {
886         sd->pwd_len = 0;
887     }
888 
889     if (lock)
890         sd->card_status |= CARD_IS_LOCKED;
891     else
892         sd->card_status &= ~CARD_IS_LOCKED;
893 }
894 
895 static sd_rsp_type_t sd_normal_command(SDState *sd, SDRequest req)
896 {
897     uint32_t rca = 0x0000;
898     uint64_t addr = (sd->ocr & (1 << 30)) ? (uint64_t) req.arg << 9 : req.arg;
899 
900     /* CMD55 precedes an ACMD, so we are not interested in tracing it.
901      * However there is no ACMD55, so we want to trace this particular case.
902      */
903     if (req.cmd != 55 || sd->expecting_acmd) {
904         trace_sdcard_normal_command(sd->proto_name,
905                                     sd_cmd_name(req.cmd), req.cmd,
906                                     req.arg, sd_state_name(sd->state));
907     }
908 
909     /* Not interpreting this as an app command */
910     sd->card_status &= ~APP_CMD;
911 
912     if (sd_cmd_type[req.cmd] == sd_ac
913         || sd_cmd_type[req.cmd] == sd_adtc) {
914         rca = req.arg >> 16;
915     }
916 
917     /* CMD23 (set block count) must be immediately followed by CMD18 or CMD25
918      * if not, its effects are cancelled */
919     if (sd->multi_blk_cnt != 0 && !(req.cmd == 18 || req.cmd == 25)) {
920         sd->multi_blk_cnt = 0;
921     }
922 
923     switch (req.cmd) {
924     /* Basic commands (Class 0 and Class 1) */
925     case 0:	/* CMD0:   GO_IDLE_STATE */
926         switch (sd->state) {
927         case sd_inactive_state:
928             return sd->spi ? sd_r1 : sd_r0;
929 
930         default:
931             sd->state = sd_idle_state;
932             sd_reset(DEVICE(sd));
933             return sd->spi ? sd_r1 : sd_r0;
934         }
935         break;
936 
937     case 1:	/* CMD1:   SEND_OP_CMD */
938         if (!sd->spi)
939             goto bad_cmd;
940 
941         sd->state = sd_transfer_state;
942         return sd_r1;
943 
944     case 2:	/* CMD2:   ALL_SEND_CID */
945         if (sd->spi)
946             goto bad_cmd;
947         switch (sd->state) {
948         case sd_ready_state:
949             sd->state = sd_identification_state;
950             return sd_r2_i;
951 
952         default:
953             break;
954         }
955         break;
956 
957     case 3:	/* CMD3:   SEND_RELATIVE_ADDR */
958         if (sd->spi)
959             goto bad_cmd;
960         switch (sd->state) {
961         case sd_identification_state:
962         case sd_standby_state:
963             sd->state = sd_standby_state;
964             sd_set_rca(sd);
965             return sd_r6;
966 
967         default:
968             break;
969         }
970         break;
971 
972     case 4:	/* CMD4:   SEND_DSR */
973         if (sd->spi)
974             goto bad_cmd;
975         switch (sd->state) {
976         case sd_standby_state:
977             break;
978 
979         default:
980             break;
981         }
982         break;
983 
984     case 5: /* CMD5: reserved for SDIO cards */
985         return sd_illegal;
986 
987     case 6:	/* CMD6:   SWITCH_FUNCTION */
988         switch (sd->mode) {
989         case sd_data_transfer_mode:
990             sd_function_switch(sd, req.arg);
991             sd->state = sd_sendingdata_state;
992             sd->data_start = 0;
993             sd->data_offset = 0;
994             return sd_r1;
995 
996         default:
997             break;
998         }
999         break;
1000 
1001     case 7:	/* CMD7:   SELECT/DESELECT_CARD */
1002         if (sd->spi)
1003             goto bad_cmd;
1004         switch (sd->state) {
1005         case sd_standby_state:
1006             if (sd->rca != rca)
1007                 return sd_r0;
1008 
1009             sd->state = sd_transfer_state;
1010             return sd_r1b;
1011 
1012         case sd_transfer_state:
1013         case sd_sendingdata_state:
1014             if (sd->rca == rca)
1015                 break;
1016 
1017             sd->state = sd_standby_state;
1018             return sd_r1b;
1019 
1020         case sd_disconnect_state:
1021             if (sd->rca != rca)
1022                 return sd_r0;
1023 
1024             sd->state = sd_programming_state;
1025             return sd_r1b;
1026 
1027         case sd_programming_state:
1028             if (sd->rca == rca)
1029                 break;
1030 
1031             sd->state = sd_disconnect_state;
1032             return sd_r1b;
1033 
1034         default:
1035             break;
1036         }
1037         break;
1038 
1039     case 8:	/* CMD8:   SEND_IF_COND */
1040         if (sd->spec_version < SD_PHY_SPECv2_00_VERS) {
1041             break;
1042         }
1043         if (sd->state != sd_idle_state) {
1044             break;
1045         }
1046         sd->vhs = 0;
1047 
1048         /* No response if not exactly one VHS bit is set.  */
1049         if (!(req.arg >> 8) || (req.arg >> (ctz32(req.arg & ~0xff) + 1))) {
1050             return sd->spi ? sd_r7 : sd_r0;
1051         }
1052 
1053         /* Accept.  */
1054         sd->vhs = req.arg;
1055         return sd_r7;
1056 
1057     case 9:	/* CMD9:   SEND_CSD */
1058         switch (sd->state) {
1059         case sd_standby_state:
1060             if (sd->rca != rca)
1061                 return sd_r0;
1062 
1063             return sd_r2_s;
1064 
1065         case sd_transfer_state:
1066             if (!sd->spi)
1067                 break;
1068             sd->state = sd_sendingdata_state;
1069             memcpy(sd->data, sd->csd, 16);
1070             sd->data_start = addr;
1071             sd->data_offset = 0;
1072             return sd_r1;
1073 
1074         default:
1075             break;
1076         }
1077         break;
1078 
1079     case 10:	/* CMD10:  SEND_CID */
1080         switch (sd->state) {
1081         case sd_standby_state:
1082             if (sd->rca != rca)
1083                 return sd_r0;
1084 
1085             return sd_r2_i;
1086 
1087         case sd_transfer_state:
1088             if (!sd->spi)
1089                 break;
1090             sd->state = sd_sendingdata_state;
1091             memcpy(sd->data, sd->cid, 16);
1092             sd->data_start = addr;
1093             sd->data_offset = 0;
1094             return sd_r1;
1095 
1096         default:
1097             break;
1098         }
1099         break;
1100 
1101     case 12:	/* CMD12:  STOP_TRANSMISSION */
1102         switch (sd->state) {
1103         case sd_sendingdata_state:
1104             sd->state = sd_transfer_state;
1105             return sd_r1b;
1106 
1107         case sd_receivingdata_state:
1108             sd->state = sd_programming_state;
1109             /* Bzzzzzzztt .... Operation complete.  */
1110             sd->state = sd_transfer_state;
1111             return sd_r1b;
1112 
1113         default:
1114             break;
1115         }
1116         break;
1117 
1118     case 13:	/* CMD13:  SEND_STATUS */
1119         switch (sd->mode) {
1120         case sd_data_transfer_mode:
1121             if (sd->rca != rca)
1122                 return sd_r0;
1123 
1124             return sd_r1;
1125 
1126         default:
1127             break;
1128         }
1129         break;
1130 
1131     case 15:	/* CMD15:  GO_INACTIVE_STATE */
1132         if (sd->spi)
1133             goto bad_cmd;
1134         switch (sd->mode) {
1135         case sd_data_transfer_mode:
1136             if (sd->rca != rca)
1137                 return sd_r0;
1138 
1139             sd->state = sd_inactive_state;
1140             return sd_r0;
1141 
1142         default:
1143             break;
1144         }
1145         break;
1146 
1147     /* Block read commands (Classs 2) */
1148     case 16:	/* CMD16:  SET_BLOCKLEN */
1149         switch (sd->state) {
1150         case sd_transfer_state:
1151             if (req.arg > (1 << HWBLOCK_SHIFT)) {
1152                 sd->card_status |= BLOCK_LEN_ERROR;
1153             } else {
1154                 trace_sdcard_set_blocklen(req.arg);
1155                 sd->blk_len = req.arg;
1156             }
1157 
1158             return sd_r1;
1159 
1160         default:
1161             break;
1162         }
1163         break;
1164 
1165     case 17:	/* CMD17:  READ_SINGLE_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 18:	/* CMD18:  READ_MULTIPLE_BLOCK */
1182         switch (sd->state) {
1183         case sd_transfer_state:
1184             sd->state = sd_sendingdata_state;
1185             sd->data_start = addr;
1186             sd->data_offset = 0;
1187 
1188             if (sd->data_start + sd->blk_len > sd->size)
1189                 sd->card_status |= ADDRESS_ERROR;
1190             return sd_r1;
1191 
1192         default:
1193             break;
1194         }
1195         break;
1196 
1197     case 19:    /* CMD19: SEND_TUNING_BLOCK (SD) */
1198         if (sd->spec_version < SD_PHY_SPECv3_01_VERS) {
1199             break;
1200         }
1201         if (sd->state == sd_transfer_state) {
1202             sd->state = sd_sendingdata_state;
1203             sd->data_offset = 0;
1204             return sd_r1;
1205         }
1206         break;
1207 
1208     case 23:    /* CMD23: SET_BLOCK_COUNT */
1209         if (sd->spec_version < SD_PHY_SPECv3_01_VERS) {
1210             break;
1211         }
1212         switch (sd->state) {
1213         case sd_transfer_state:
1214             sd->multi_blk_cnt = req.arg;
1215             return sd_r1;
1216 
1217         default:
1218             break;
1219         }
1220         break;
1221 
1222     /* Block write commands (Class 4) */
1223     case 24:	/* CMD24:  WRITE_SINGLE_BLOCK */
1224         switch (sd->state) {
1225         case sd_transfer_state:
1226             /* Writing in SPI mode not implemented.  */
1227             if (sd->spi)
1228                 break;
1229             sd->state = sd_receivingdata_state;
1230             sd->data_start = addr;
1231             sd->data_offset = 0;
1232             sd->blk_written = 0;
1233 
1234             if (sd->data_start + sd->blk_len > sd->size)
1235                 sd->card_status |= ADDRESS_ERROR;
1236             if (sd_wp_addr(sd, sd->data_start))
1237                 sd->card_status |= WP_VIOLATION;
1238             if (sd->csd[14] & 0x30)
1239                 sd->card_status |= WP_VIOLATION;
1240             return sd_r1;
1241 
1242         default:
1243             break;
1244         }
1245         break;
1246 
1247     case 25:	/* CMD25:  WRITE_MULTIPLE_BLOCK */
1248         switch (sd->state) {
1249         case sd_transfer_state:
1250             /* Writing in SPI mode not implemented.  */
1251             if (sd->spi)
1252                 break;
1253             sd->state = sd_receivingdata_state;
1254             sd->data_start = addr;
1255             sd->data_offset = 0;
1256             sd->blk_written = 0;
1257 
1258             if (sd->data_start + sd->blk_len > sd->size)
1259                 sd->card_status |= ADDRESS_ERROR;
1260             if (sd_wp_addr(sd, sd->data_start))
1261                 sd->card_status |= WP_VIOLATION;
1262             if (sd->csd[14] & 0x30)
1263                 sd->card_status |= WP_VIOLATION;
1264             return sd_r1;
1265 
1266         default:
1267             break;
1268         }
1269         break;
1270 
1271     case 26:	/* CMD26:  PROGRAM_CID */
1272         if (sd->spi)
1273             goto bad_cmd;
1274         switch (sd->state) {
1275         case sd_transfer_state:
1276             sd->state = sd_receivingdata_state;
1277             sd->data_start = 0;
1278             sd->data_offset = 0;
1279             return sd_r1;
1280 
1281         default:
1282             break;
1283         }
1284         break;
1285 
1286     case 27:	/* CMD27:  PROGRAM_CSD */
1287         switch (sd->state) {
1288         case sd_transfer_state:
1289             sd->state = sd_receivingdata_state;
1290             sd->data_start = 0;
1291             sd->data_offset = 0;
1292             return sd_r1;
1293 
1294         default:
1295             break;
1296         }
1297         break;
1298 
1299     /* Write protection (Class 6) */
1300     case 28:	/* CMD28:  SET_WRITE_PROT */
1301         switch (sd->state) {
1302         case sd_transfer_state:
1303             if (addr >= sd->size) {
1304                 sd->card_status |= ADDRESS_ERROR;
1305                 return sd_r1b;
1306             }
1307 
1308             sd->state = sd_programming_state;
1309             set_bit(sd_addr_to_wpnum(addr), sd->wp_groups);
1310             /* Bzzzzzzztt .... Operation complete.  */
1311             sd->state = sd_transfer_state;
1312             return sd_r1b;
1313 
1314         default:
1315             break;
1316         }
1317         break;
1318 
1319     case 29:	/* CMD29:  CLR_WRITE_PROT */
1320         switch (sd->state) {
1321         case sd_transfer_state:
1322             if (addr >= sd->size) {
1323                 sd->card_status |= ADDRESS_ERROR;
1324                 return sd_r1b;
1325             }
1326 
1327             sd->state = sd_programming_state;
1328             clear_bit(sd_addr_to_wpnum(addr), sd->wp_groups);
1329             /* Bzzzzzzztt .... Operation complete.  */
1330             sd->state = sd_transfer_state;
1331             return sd_r1b;
1332 
1333         default:
1334             break;
1335         }
1336         break;
1337 
1338     case 30:	/* CMD30:  SEND_WRITE_PROT */
1339         switch (sd->state) {
1340         case sd_transfer_state:
1341             sd->state = sd_sendingdata_state;
1342             *(uint32_t *) sd->data = sd_wpbits(sd, req.arg);
1343             sd->data_start = addr;
1344             sd->data_offset = 0;
1345             return sd_r1b;
1346 
1347         default:
1348             break;
1349         }
1350         break;
1351 
1352     /* Erase commands (Class 5) */
1353     case 32:	/* CMD32:  ERASE_WR_BLK_START */
1354         switch (sd->state) {
1355         case sd_transfer_state:
1356             sd->erase_start = req.arg;
1357             return sd_r1;
1358 
1359         default:
1360             break;
1361         }
1362         break;
1363 
1364     case 33:	/* CMD33:  ERASE_WR_BLK_END */
1365         switch (sd->state) {
1366         case sd_transfer_state:
1367             sd->erase_end = req.arg;
1368             return sd_r1;
1369 
1370         default:
1371             break;
1372         }
1373         break;
1374 
1375     case 38:	/* CMD38:  ERASE */
1376         switch (sd->state) {
1377         case sd_transfer_state:
1378             if (sd->csd[14] & 0x30) {
1379                 sd->card_status |= WP_VIOLATION;
1380                 return sd_r1b;
1381             }
1382 
1383             sd->state = sd_programming_state;
1384             sd_erase(sd);
1385             /* Bzzzzzzztt .... Operation complete.  */
1386             sd->state = sd_transfer_state;
1387             return sd_r1b;
1388 
1389         default:
1390             break;
1391         }
1392         break;
1393 
1394     /* Lock card commands (Class 7) */
1395     case 42:	/* CMD42:  LOCK_UNLOCK */
1396         switch (sd->state) {
1397         case sd_transfer_state:
1398             sd->state = sd_receivingdata_state;
1399             sd->data_start = 0;
1400             sd->data_offset = 0;
1401             return sd_r1;
1402 
1403         default:
1404             break;
1405         }
1406         break;
1407 
1408     case 52 ... 54:
1409         /* CMD52, CMD53, CMD54: reserved for SDIO cards
1410          * (see the SDIO Simplified Specification V2.0)
1411          * Handle as illegal command but do not complain
1412          * on stderr, as some OSes may use these in their
1413          * probing for presence of an SDIO card.
1414          */
1415         return sd_illegal;
1416 
1417     /* Application specific commands (Class 8) */
1418     case 55:	/* CMD55:  APP_CMD */
1419         switch (sd->state) {
1420         case sd_ready_state:
1421         case sd_identification_state:
1422         case sd_inactive_state:
1423             return sd_illegal;
1424         case sd_idle_state:
1425             if (rca) {
1426                 qemu_log_mask(LOG_GUEST_ERROR,
1427                               "SD: illegal RCA 0x%04x for APP_CMD\n", req.cmd);
1428             }
1429         default:
1430             break;
1431         }
1432         if (!sd->spi) {
1433             if (sd->rca != rca) {
1434                 return sd_r0;
1435             }
1436         }
1437         sd->expecting_acmd = true;
1438         sd->card_status |= APP_CMD;
1439         return sd_r1;
1440 
1441     case 56:	/* CMD56:  GEN_CMD */
1442         switch (sd->state) {
1443         case sd_transfer_state:
1444             sd->data_offset = 0;
1445             if (req.arg & 1)
1446                 sd->state = sd_sendingdata_state;
1447             else
1448                 sd->state = sd_receivingdata_state;
1449             return sd_r1;
1450 
1451         default:
1452             break;
1453         }
1454         break;
1455 
1456     case 58:    /* CMD58:   READ_OCR (SPI) */
1457         if (!sd->spi) {
1458             goto bad_cmd;
1459         }
1460         return sd_r3;
1461 
1462     case 59:    /* CMD59:   CRC_ON_OFF (SPI) */
1463         if (!sd->spi) {
1464             goto bad_cmd;
1465         }
1466         goto unimplemented_spi_cmd;
1467 
1468     default:
1469     bad_cmd:
1470         qemu_log_mask(LOG_GUEST_ERROR, "SD: Unknown CMD%i\n", req.cmd);
1471         return sd_illegal;
1472 
1473     unimplemented_spi_cmd:
1474         /* Commands that are recognised but not yet implemented in SPI mode.  */
1475         qemu_log_mask(LOG_UNIMP, "SD: CMD%i not implemented in SPI mode\n",
1476                       req.cmd);
1477         return sd_illegal;
1478     }
1479 
1480     qemu_log_mask(LOG_GUEST_ERROR, "SD: CMD%i in a wrong state\n", req.cmd);
1481     return sd_illegal;
1482 }
1483 
1484 static sd_rsp_type_t sd_app_command(SDState *sd,
1485                                     SDRequest req)
1486 {
1487     trace_sdcard_app_command(sd->proto_name, sd_acmd_name(req.cmd),
1488                              req.cmd, req.arg, sd_state_name(sd->state));
1489     sd->card_status |= APP_CMD;
1490     switch (req.cmd) {
1491     case 6:	/* ACMD6:  SET_BUS_WIDTH */
1492         if (sd->spi) {
1493             goto unimplemented_spi_cmd;
1494         }
1495         switch (sd->state) {
1496         case sd_transfer_state:
1497             sd->sd_status[0] &= 0x3f;
1498             sd->sd_status[0] |= (req.arg & 0x03) << 6;
1499             return sd_r1;
1500 
1501         default:
1502             break;
1503         }
1504         break;
1505 
1506     case 13:	/* ACMD13: SD_STATUS */
1507         switch (sd->state) {
1508         case sd_transfer_state:
1509             sd->state = sd_sendingdata_state;
1510             sd->data_start = 0;
1511             sd->data_offset = 0;
1512             return sd_r1;
1513 
1514         default:
1515             break;
1516         }
1517         break;
1518 
1519     case 22:	/* ACMD22: SEND_NUM_WR_BLOCKS */
1520         switch (sd->state) {
1521         case sd_transfer_state:
1522             *(uint32_t *) sd->data = sd->blk_written;
1523 
1524             sd->state = sd_sendingdata_state;
1525             sd->data_start = 0;
1526             sd->data_offset = 0;
1527             return sd_r1;
1528 
1529         default:
1530             break;
1531         }
1532         break;
1533 
1534     case 23:	/* ACMD23: SET_WR_BLK_ERASE_COUNT */
1535         switch (sd->state) {
1536         case sd_transfer_state:
1537             return sd_r1;
1538 
1539         default:
1540             break;
1541         }
1542         break;
1543 
1544     case 41:	/* ACMD41: SD_APP_OP_COND */
1545         if (sd->spi) {
1546             /* SEND_OP_CMD */
1547             sd->state = sd_transfer_state;
1548             return sd_r1;
1549         }
1550         if (sd->state != sd_idle_state) {
1551             break;
1552         }
1553         /* If it's the first ACMD41 since reset, we need to decide
1554          * whether to power up. If this is not an enquiry ACMD41,
1555          * we immediately report power on and proceed below to the
1556          * ready state, but if it is, we set a timer to model a
1557          * delay for power up. This works around a bug in EDK2
1558          * UEFI, which sends an initial enquiry ACMD41, but
1559          * assumes that the card is in ready state as soon as it
1560          * sees the power up bit set. */
1561         if (!FIELD_EX32(sd->ocr, OCR, CARD_POWER_UP)) {
1562             if ((req.arg & ACMD41_ENQUIRY_MASK) != 0) {
1563                 timer_del(sd->ocr_power_timer);
1564                 sd_ocr_powerup(sd);
1565             } else {
1566                 trace_sdcard_inquiry_cmd41();
1567                 if (!timer_pending(sd->ocr_power_timer)) {
1568                     timer_mod_ns(sd->ocr_power_timer,
1569                                  (qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL)
1570                                   + OCR_POWER_DELAY_NS));
1571                 }
1572             }
1573         }
1574 
1575         if (FIELD_EX32(sd->ocr & req.arg, OCR, VDD_VOLTAGE_WINDOW)) {
1576             /* We accept any voltage.  10000 V is nothing.
1577              *
1578              * Once we're powered up, we advance straight to ready state
1579              * unless it's an enquiry ACMD41 (bits 23:0 == 0).
1580              */
1581             sd->state = sd_ready_state;
1582         }
1583 
1584         return sd_r3;
1585 
1586     case 42:	/* ACMD42: SET_CLR_CARD_DETECT */
1587         switch (sd->state) {
1588         case sd_transfer_state:
1589             /* Bringing in the 50KOhm pull-up resistor... Done.  */
1590             return sd_r1;
1591 
1592         default:
1593             break;
1594         }
1595         break;
1596 
1597     case 51:	/* ACMD51: SEND_SCR */
1598         switch (sd->state) {
1599         case sd_transfer_state:
1600             sd->state = sd_sendingdata_state;
1601             sd->data_start = 0;
1602             sd->data_offset = 0;
1603             return sd_r1;
1604 
1605         default:
1606             break;
1607         }
1608         break;
1609 
1610     case 18:    /* Reserved for SD security applications */
1611     case 25:
1612     case 26:
1613     case 38:
1614     case 43 ... 49:
1615         /* Refer to the "SD Specifications Part3 Security Specification" for
1616          * information about the SD Security Features.
1617          */
1618         qemu_log_mask(LOG_UNIMP, "SD: CMD%i Security not implemented\n",
1619                       req.cmd);
1620         return sd_illegal;
1621 
1622     default:
1623         /* Fall back to standard commands.  */
1624         return sd_normal_command(sd, req);
1625 
1626     unimplemented_spi_cmd:
1627         /* Commands that are recognised but not yet implemented in SPI mode.  */
1628         qemu_log_mask(LOG_UNIMP, "SD: CMD%i not implemented in SPI mode\n",
1629                       req.cmd);
1630         return sd_illegal;
1631     }
1632 
1633     qemu_log_mask(LOG_GUEST_ERROR, "SD: ACMD%i in a wrong state\n", req.cmd);
1634     return sd_illegal;
1635 }
1636 
1637 static int cmd_valid_while_locked(SDState *sd, SDRequest *req)
1638 {
1639     /* Valid commands in locked state:
1640      * basic class (0)
1641      * lock card class (7)
1642      * CMD16
1643      * implicitly, the ACMD prefix CMD55
1644      * ACMD41 and ACMD42
1645      * Anything else provokes an "illegal command" response.
1646      */
1647     if (sd->expecting_acmd) {
1648         return req->cmd == 41 || req->cmd == 42;
1649     }
1650     if (req->cmd == 16 || req->cmd == 55) {
1651         return 1;
1652     }
1653     return sd_cmd_class[req->cmd] == 0
1654             || sd_cmd_class[req->cmd] == 7;
1655 }
1656 
1657 int sd_do_command(SDState *sd, SDRequest *req,
1658                   uint8_t *response) {
1659     int last_state;
1660     sd_rsp_type_t rtype;
1661     int rsplen;
1662 
1663     if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable) {
1664         return 0;
1665     }
1666 
1667     if (sd_req_crc_validate(req)) {
1668         sd->card_status |= COM_CRC_ERROR;
1669         rtype = sd_illegal;
1670         goto send_response;
1671     }
1672 
1673     if (req->cmd >= SDMMC_CMD_MAX) {
1674         qemu_log_mask(LOG_GUEST_ERROR, "SD: incorrect command 0x%02x\n",
1675                       req->cmd);
1676         req->cmd &= 0x3f;
1677     }
1678 
1679     if (sd->card_status & CARD_IS_LOCKED) {
1680         if (!cmd_valid_while_locked(sd, req)) {
1681             sd->card_status |= ILLEGAL_COMMAND;
1682             sd->expecting_acmd = false;
1683             qemu_log_mask(LOG_GUEST_ERROR, "SD: Card is locked\n");
1684             rtype = sd_illegal;
1685             goto send_response;
1686         }
1687     }
1688 
1689     last_state = sd->state;
1690     sd_set_mode(sd);
1691 
1692     if (sd->expecting_acmd) {
1693         sd->expecting_acmd = false;
1694         rtype = sd_app_command(sd, *req);
1695     } else {
1696         rtype = sd_normal_command(sd, *req);
1697     }
1698 
1699     if (rtype == sd_illegal) {
1700         sd->card_status |= ILLEGAL_COMMAND;
1701     } else {
1702         /* Valid command, we can update the 'state before command' bits.
1703          * (Do this now so they appear in r1 responses.)
1704          */
1705         sd->current_cmd = req->cmd;
1706         sd->card_status &= ~CURRENT_STATE;
1707         sd->card_status |= (last_state << 9);
1708     }
1709 
1710 send_response:
1711     switch (rtype) {
1712     case sd_r1:
1713     case sd_r1b:
1714         sd_response_r1_make(sd, response);
1715         rsplen = 4;
1716         break;
1717 
1718     case sd_r2_i:
1719         memcpy(response, sd->cid, sizeof(sd->cid));
1720         rsplen = 16;
1721         break;
1722 
1723     case sd_r2_s:
1724         memcpy(response, sd->csd, sizeof(sd->csd));
1725         rsplen = 16;
1726         break;
1727 
1728     case sd_r3:
1729         sd_response_r3_make(sd, response);
1730         rsplen = 4;
1731         break;
1732 
1733     case sd_r6:
1734         sd_response_r6_make(sd, response);
1735         rsplen = 4;
1736         break;
1737 
1738     case sd_r7:
1739         sd_response_r7_make(sd, response);
1740         rsplen = 4;
1741         break;
1742 
1743     case sd_r0:
1744     case sd_illegal:
1745         rsplen = 0;
1746         break;
1747     default:
1748         g_assert_not_reached();
1749     }
1750     trace_sdcard_response(sd_response_name(rtype), rsplen);
1751 
1752     if (rtype != sd_illegal) {
1753         /* Clear the "clear on valid command" status bits now we've
1754          * sent any response
1755          */
1756         sd->card_status &= ~CARD_STATUS_B;
1757     }
1758 
1759 #ifdef DEBUG_SD
1760     qemu_hexdump((const char *)response, stderr, "Response", rsplen);
1761 #endif
1762 
1763     return rsplen;
1764 }
1765 
1766 static void sd_blk_read(SDState *sd, uint64_t addr, uint32_t len)
1767 {
1768     trace_sdcard_read_block(addr, len);
1769     if (!sd->blk || blk_pread(sd->blk, addr, sd->data, len) < 0) {
1770         fprintf(stderr, "sd_blk_read: read error on host side\n");
1771     }
1772 }
1773 
1774 static void sd_blk_write(SDState *sd, uint64_t addr, uint32_t len)
1775 {
1776     trace_sdcard_write_block(addr, len);
1777     if (!sd->blk || blk_pwrite(sd->blk, addr, sd->data, len, 0) < 0) {
1778         fprintf(stderr, "sd_blk_write: write error on host side\n");
1779     }
1780 }
1781 
1782 #define BLK_READ_BLOCK(a, len)	sd_blk_read(sd, a, len)
1783 #define BLK_WRITE_BLOCK(a, len)	sd_blk_write(sd, a, len)
1784 #define APP_READ_BLOCK(a, len)	memset(sd->data, 0xec, len)
1785 #define APP_WRITE_BLOCK(a, len)
1786 
1787 void sd_write_data(SDState *sd, uint8_t value)
1788 {
1789     int i;
1790 
1791     if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable)
1792         return;
1793 
1794     if (sd->state != sd_receivingdata_state) {
1795         qemu_log_mask(LOG_GUEST_ERROR,
1796                       "sd_write_data: not in Receiving-Data state\n");
1797         return;
1798     }
1799 
1800     if (sd->card_status & (ADDRESS_ERROR | WP_VIOLATION))
1801         return;
1802 
1803     trace_sdcard_write_data(sd->proto_name,
1804                             sd_acmd_name(sd->current_cmd),
1805                             sd->current_cmd, value);
1806     switch (sd->current_cmd) {
1807     case 24:	/* CMD24:  WRITE_SINGLE_BLOCK */
1808         sd->data[sd->data_offset ++] = value;
1809         if (sd->data_offset >= sd->blk_len) {
1810             /* TODO: Check CRC before committing */
1811             sd->state = sd_programming_state;
1812             BLK_WRITE_BLOCK(sd->data_start, sd->data_offset);
1813             sd->blk_written ++;
1814             sd->csd[14] |= 0x40;
1815             /* Bzzzzzzztt .... Operation complete.  */
1816             sd->state = sd_transfer_state;
1817         }
1818         break;
1819 
1820     case 25:	/* CMD25:  WRITE_MULTIPLE_BLOCK */
1821         if (sd->data_offset == 0) {
1822             /* Start of the block - let's check the address is valid */
1823             if (sd->data_start + sd->blk_len > sd->size) {
1824                 sd->card_status |= ADDRESS_ERROR;
1825                 break;
1826             }
1827             if (sd_wp_addr(sd, sd->data_start)) {
1828                 sd->card_status |= WP_VIOLATION;
1829                 break;
1830             }
1831         }
1832         sd->data[sd->data_offset++] = value;
1833         if (sd->data_offset >= sd->blk_len) {
1834             /* TODO: Check CRC before committing */
1835             sd->state = sd_programming_state;
1836             BLK_WRITE_BLOCK(sd->data_start, sd->data_offset);
1837             sd->blk_written++;
1838             sd->data_start += sd->blk_len;
1839             sd->data_offset = 0;
1840             sd->csd[14] |= 0x40;
1841 
1842             /* Bzzzzzzztt .... Operation complete.  */
1843             if (sd->multi_blk_cnt != 0) {
1844                 if (--sd->multi_blk_cnt == 0) {
1845                     /* Stop! */
1846                     sd->state = sd_transfer_state;
1847                     break;
1848                 }
1849             }
1850 
1851             sd->state = sd_receivingdata_state;
1852         }
1853         break;
1854 
1855     case 26:	/* CMD26:  PROGRAM_CID */
1856         sd->data[sd->data_offset ++] = value;
1857         if (sd->data_offset >= sizeof(sd->cid)) {
1858             /* TODO: Check CRC before committing */
1859             sd->state = sd_programming_state;
1860             for (i = 0; i < sizeof(sd->cid); i ++)
1861                 if ((sd->cid[i] | 0x00) != sd->data[i])
1862                     sd->card_status |= CID_CSD_OVERWRITE;
1863 
1864             if (!(sd->card_status & CID_CSD_OVERWRITE))
1865                 for (i = 0; i < sizeof(sd->cid); i ++) {
1866                     sd->cid[i] |= 0x00;
1867                     sd->cid[i] &= sd->data[i];
1868                 }
1869             /* Bzzzzzzztt .... Operation complete.  */
1870             sd->state = sd_transfer_state;
1871         }
1872         break;
1873 
1874     case 27:	/* CMD27:  PROGRAM_CSD */
1875         sd->data[sd->data_offset ++] = value;
1876         if (sd->data_offset >= sizeof(sd->csd)) {
1877             /* TODO: Check CRC before committing */
1878             sd->state = sd_programming_state;
1879             for (i = 0; i < sizeof(sd->csd); i ++)
1880                 if ((sd->csd[i] | sd_csd_rw_mask[i]) !=
1881                     (sd->data[i] | sd_csd_rw_mask[i]))
1882                     sd->card_status |= CID_CSD_OVERWRITE;
1883 
1884             /* Copy flag (OTP) & Permanent write protect */
1885             if (sd->csd[14] & ~sd->data[14] & 0x60)
1886                 sd->card_status |= CID_CSD_OVERWRITE;
1887 
1888             if (!(sd->card_status & CID_CSD_OVERWRITE))
1889                 for (i = 0; i < sizeof(sd->csd); i ++) {
1890                     sd->csd[i] |= sd_csd_rw_mask[i];
1891                     sd->csd[i] &= sd->data[i];
1892                 }
1893             /* Bzzzzzzztt .... Operation complete.  */
1894             sd->state = sd_transfer_state;
1895         }
1896         break;
1897 
1898     case 42:	/* CMD42:  LOCK_UNLOCK */
1899         sd->data[sd->data_offset ++] = value;
1900         if (sd->data_offset >= sd->blk_len) {
1901             /* TODO: Check CRC before committing */
1902             sd->state = sd_programming_state;
1903             sd_lock_command(sd);
1904             /* Bzzzzzzztt .... Operation complete.  */
1905             sd->state = sd_transfer_state;
1906         }
1907         break;
1908 
1909     case 56:	/* CMD56:  GEN_CMD */
1910         sd->data[sd->data_offset ++] = value;
1911         if (sd->data_offset >= sd->blk_len) {
1912             APP_WRITE_BLOCK(sd->data_start, sd->data_offset);
1913             sd->state = sd_transfer_state;
1914         }
1915         break;
1916 
1917     default:
1918         qemu_log_mask(LOG_GUEST_ERROR, "sd_write_data: unknown command\n");
1919         break;
1920     }
1921 }
1922 
1923 #define SD_TUNING_BLOCK_SIZE    64
1924 
1925 static const uint8_t sd_tuning_block_pattern[SD_TUNING_BLOCK_SIZE] = {
1926     /* See: Physical Layer Simplified Specification Version 3.01, Table 4-2 */
1927     0xff, 0x0f, 0xff, 0x00,         0x0f, 0xfc, 0xc3, 0xcc,
1928     0xc3, 0x3c, 0xcc, 0xff,         0xfe, 0xff, 0xfe, 0xef,
1929     0xff, 0xdf, 0xff, 0xdd,         0xff, 0xfb, 0xff, 0xfb,
1930     0xbf, 0xff, 0x7f, 0xff,         0x77, 0xf7, 0xbd, 0xef,
1931     0xff, 0xf0, 0xff, 0xf0,         0x0f, 0xfc, 0xcc, 0x3c,
1932     0xcc, 0x33, 0xcc, 0xcf,         0xff, 0xef, 0xff, 0xee,
1933     0xff, 0xfd, 0xff, 0xfd,         0xdf, 0xff, 0xbf, 0xff,
1934     0xbb, 0xff, 0xf7, 0xff,         0xf7, 0x7f, 0x7b, 0xde,
1935 };
1936 
1937 uint8_t sd_read_data(SDState *sd)
1938 {
1939     /* TODO: Append CRCs */
1940     uint8_t ret;
1941     int io_len;
1942 
1943     if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable)
1944         return 0x00;
1945 
1946     if (sd->state != sd_sendingdata_state) {
1947         qemu_log_mask(LOG_GUEST_ERROR,
1948                       "sd_read_data: not in Sending-Data state\n");
1949         return 0x00;
1950     }
1951 
1952     if (sd->card_status & (ADDRESS_ERROR | WP_VIOLATION))
1953         return 0x00;
1954 
1955     io_len = (sd->ocr & (1 << 30)) ? 512 : sd->blk_len;
1956 
1957     trace_sdcard_read_data(sd->proto_name,
1958                            sd_acmd_name(sd->current_cmd),
1959                            sd->current_cmd, io_len);
1960     switch (sd->current_cmd) {
1961     case 6:	/* CMD6:   SWITCH_FUNCTION */
1962         ret = sd->data[sd->data_offset ++];
1963 
1964         if (sd->data_offset >= 64)
1965             sd->state = sd_transfer_state;
1966         break;
1967 
1968     case 9:	/* CMD9:   SEND_CSD */
1969     case 10:	/* CMD10:  SEND_CID */
1970         ret = sd->data[sd->data_offset ++];
1971 
1972         if (sd->data_offset >= 16)
1973             sd->state = sd_transfer_state;
1974         break;
1975 
1976     case 13:	/* ACMD13: SD_STATUS */
1977         ret = sd->sd_status[sd->data_offset ++];
1978 
1979         if (sd->data_offset >= sizeof(sd->sd_status))
1980             sd->state = sd_transfer_state;
1981         break;
1982 
1983     case 17:	/* CMD17:  READ_SINGLE_BLOCK */
1984         if (sd->data_offset == 0)
1985             BLK_READ_BLOCK(sd->data_start, io_len);
1986         ret = sd->data[sd->data_offset ++];
1987 
1988         if (sd->data_offset >= io_len)
1989             sd->state = sd_transfer_state;
1990         break;
1991 
1992     case 18:	/* CMD18:  READ_MULTIPLE_BLOCK */
1993         if (sd->data_offset == 0) {
1994             if (sd->data_start + io_len > sd->size) {
1995                 sd->card_status |= ADDRESS_ERROR;
1996                 return 0x00;
1997             }
1998             BLK_READ_BLOCK(sd->data_start, io_len);
1999         }
2000         ret = sd->data[sd->data_offset ++];
2001 
2002         if (sd->data_offset >= io_len) {
2003             sd->data_start += io_len;
2004             sd->data_offset = 0;
2005 
2006             if (sd->multi_blk_cnt != 0) {
2007                 if (--sd->multi_blk_cnt == 0) {
2008                     /* Stop! */
2009                     sd->state = sd_transfer_state;
2010                     break;
2011                 }
2012             }
2013         }
2014         break;
2015 
2016     case 19:    /* CMD19:  SEND_TUNING_BLOCK (SD) */
2017         if (sd->data_offset >= SD_TUNING_BLOCK_SIZE - 1) {
2018             sd->state = sd_transfer_state;
2019         }
2020         ret = sd_tuning_block_pattern[sd->data_offset++];
2021         break;
2022 
2023     case 22:	/* ACMD22: SEND_NUM_WR_BLOCKS */
2024         ret = sd->data[sd->data_offset ++];
2025 
2026         if (sd->data_offset >= 4)
2027             sd->state = sd_transfer_state;
2028         break;
2029 
2030     case 30:	/* CMD30:  SEND_WRITE_PROT */
2031         ret = sd->data[sd->data_offset ++];
2032 
2033         if (sd->data_offset >= 4)
2034             sd->state = sd_transfer_state;
2035         break;
2036 
2037     case 51:	/* ACMD51: SEND_SCR */
2038         ret = sd->scr[sd->data_offset ++];
2039 
2040         if (sd->data_offset >= sizeof(sd->scr))
2041             sd->state = sd_transfer_state;
2042         break;
2043 
2044     case 56:	/* CMD56:  GEN_CMD */
2045         if (sd->data_offset == 0)
2046             APP_READ_BLOCK(sd->data_start, sd->blk_len);
2047         ret = sd->data[sd->data_offset ++];
2048 
2049         if (sd->data_offset >= sd->blk_len)
2050             sd->state = sd_transfer_state;
2051         break;
2052 
2053     default:
2054         qemu_log_mask(LOG_GUEST_ERROR, "sd_read_data: unknown command\n");
2055         return 0x00;
2056     }
2057 
2058     return ret;
2059 }
2060 
2061 bool sd_data_ready(SDState *sd)
2062 {
2063     return sd->state == sd_sendingdata_state;
2064 }
2065 
2066 void sd_enable(SDState *sd, bool enable)
2067 {
2068     sd->enable = enable;
2069 }
2070 
2071 static void sd_instance_init(Object *obj)
2072 {
2073     SDState *sd = SD_CARD(obj);
2074 
2075     sd->enable = true;
2076     sd->ocr_power_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, sd_ocr_powerup, sd);
2077 }
2078 
2079 static void sd_instance_finalize(Object *obj)
2080 {
2081     SDState *sd = SD_CARD(obj);
2082 
2083     timer_del(sd->ocr_power_timer);
2084     timer_free(sd->ocr_power_timer);
2085 }
2086 
2087 static void sd_realize(DeviceState *dev, Error **errp)
2088 {
2089     SDState *sd = SD_CARD(dev);
2090     int ret;
2091 
2092     sd->proto_name = sd->spi ? "SPI" : "SD";
2093 
2094     switch (sd->spec_version) {
2095     case SD_PHY_SPECv1_10_VERS
2096      ... SD_PHY_SPECv3_01_VERS:
2097         break;
2098     default:
2099         error_setg(errp, "Invalid SD card Spec version: %u", sd->spec_version);
2100         return;
2101     }
2102 
2103     if (sd->blk && blk_is_read_only(sd->blk)) {
2104         error_setg(errp, "Cannot use read-only drive as SD card");
2105         return;
2106     }
2107 
2108     if (sd->blk) {
2109         ret = blk_set_perm(sd->blk, BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE,
2110                            BLK_PERM_ALL, errp);
2111         if (ret < 0) {
2112             return;
2113         }
2114         blk_set_dev_ops(sd->blk, &sd_block_ops, sd);
2115     }
2116 }
2117 
2118 static Property sd_properties[] = {
2119     DEFINE_PROP_UINT8("spec_version", SDState,
2120                       spec_version, SD_PHY_SPECv2_00_VERS),
2121     DEFINE_PROP_DRIVE("drive", SDState, blk),
2122     /* We do not model the chip select pin, so allow the board to select
2123      * whether card should be in SSI or MMC/SD mode.  It is also up to the
2124      * board to ensure that ssi transfers only occur when the chip select
2125      * is asserted.  */
2126     DEFINE_PROP_BOOL("spi", SDState, spi, false),
2127     DEFINE_PROP_END_OF_LIST()
2128 };
2129 
2130 static void sd_class_init(ObjectClass *klass, void *data)
2131 {
2132     DeviceClass *dc = DEVICE_CLASS(klass);
2133     SDCardClass *sc = SD_CARD_CLASS(klass);
2134 
2135     dc->realize = sd_realize;
2136     device_class_set_props(dc, sd_properties);
2137     dc->vmsd = &sd_vmstate;
2138     dc->reset = sd_reset;
2139     dc->bus_type = TYPE_SD_BUS;
2140     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
2141 
2142     sc->set_voltage = sd_set_voltage;
2143     sc->get_dat_lines = sd_get_dat_lines;
2144     sc->get_cmd_line = sd_get_cmd_line;
2145     sc->do_command = sd_do_command;
2146     sc->write_data = sd_write_data;
2147     sc->read_data = sd_read_data;
2148     sc->data_ready = sd_data_ready;
2149     sc->enable = sd_enable;
2150     sc->get_inserted = sd_get_inserted;
2151     sc->get_readonly = sd_get_readonly;
2152 }
2153 
2154 static const TypeInfo sd_info = {
2155     .name = TYPE_SD_CARD,
2156     .parent = TYPE_DEVICE,
2157     .instance_size = sizeof(SDState),
2158     .class_size = sizeof(SDCardClass),
2159     .class_init = sd_class_init,
2160     .instance_init = sd_instance_init,
2161     .instance_finalize = sd_instance_finalize,
2162 };
2163 
2164 static void sd_register_types(void)
2165 {
2166     type_register_static(&sd_info);
2167 }
2168 
2169 type_init(sd_register_types)
2170