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