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