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