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