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