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