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