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