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