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