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