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