2 * SD Memory Card emulation as defined in the "SD Memory Card Physical
3 * layer specification, Version 2.00."
5 * Copyright (c) 2006 Andrzej Zaborowski <balrog@zabor.org>
6 * Copyright (c) 2007 CodeSourcery
7 * Copyright (c) 2018 Philippe Mathieu-Daudé <f4bug@amsat.org>
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
21 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
22 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
23 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
24 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
25 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
26 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
27 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
28 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 #include "qemu/osdep.h"
34 #include "qemu/units.h"
35 #include "qemu/cutils.h"
37 #include "hw/registerfields.h"
38 #include "sysemu/block-backend.h"
40 #include "hw/sd/sdcard_legacy.h"
41 #include "migration/vmstate.h"
42 #include "qapi/error.h"
43 #include "qemu/bitmap.h"
44 #include "hw/qdev-properties.h"
45 #include "hw/qdev-properties-system.h"
46 #include "qemu/error-report.h"
47 #include "qemu/timer.h"
49 #include "qemu/module.h"
50 #include "sdmmc-internal.h"
55 #define SDSC_MAX_CAPACITY (2 * GiB)
57 #define INVALID_ADDRESS UINT32_MAX
60 sd_r0 = 0, /* no response */
61 sd_r1, /* normal response command */
62 sd_r2_i, /* CID register */
63 sd_r2_s, /* CSD register */
64 sd_r3, /* OCR register */
65 sd_r6 = 6, /* Published RCA response */
66 sd_r7, /* Operating voltage */
73 sd_card_identification_mode,
74 sd_data_transfer_mode,
78 sd_inactive_state = -1,
81 sd_identification_state,
85 sd_receivingdata_state,
90 typedef sd_rsp_type_t (*sd_cmd_handler)(SDState *sd, SDRequest req);
92 typedef struct SDProto {
94 sd_cmd_handler cmd[SDMMC_CMD_MAX];
95 sd_cmd_handler acmd[SDMMC_CMD_MAX];
99 DeviceState parent_obj;
101 /* If true, created by sd_init() for a non-qdevified caller */
102 /* TODO purge them with fire */
103 bool me_no_qdev_me_kill_mammoth_with_rocks;
105 /* SD Memory Card Registers */
111 uint32_t card_status;
112 uint8_t sd_status[64];
114 /* Static properties */
116 uint8_t spec_version;
120 /* Runtime changeables */
122 uint32_t mode; /* current card mode, one of SDCardModes */
123 int32_t state; /* current card state, one of SDCardStates */
126 unsigned long *wp_group_bmap;
127 int32_t wp_group_bits;
130 uint32_t multi_blk_cnt;
131 uint32_t erase_start;
135 uint8_t function_group[6];
137 /* True if we will handle the next command as an ACMD. Note that this does
138 * *not* track the APP_CMD status bit!
141 uint32_t blk_written;
143 uint32_t data_offset;
145 qemu_irq readonly_cb;
146 qemu_irq inserted_cb;
147 QEMUTimer *ocr_power_timer;
153 static void sd_realize(DeviceState *dev, Error **errp);
155 static const struct SDProto *sd_proto(SDState *sd)
157 SDCardClass *sc = SD_CARD_GET_CLASS(sd);
162 static const char *sd_version_str(enum SDPhySpecificationVersion version)
164 static const char *sdphy_version[] = {
165 [SD_PHY_SPECv1_10_VERS] = "v1.10",
166 [SD_PHY_SPECv2_00_VERS] = "v2.00",
167 [SD_PHY_SPECv3_01_VERS] = "v3.01",
169 if (version >= ARRAY_SIZE(sdphy_version)) {
170 return "unsupported version";
172 return sdphy_version[version];
175 static const char *sd_state_name(enum SDCardStates state)
177 static const char *state_name[] = {
178 [sd_idle_state] = "idle",
179 [sd_ready_state] = "ready",
180 [sd_identification_state] = "identification",
181 [sd_standby_state] = "standby",
182 [sd_transfer_state] = "transfer",
183 [sd_sendingdata_state] = "sendingdata",
184 [sd_receivingdata_state] = "receivingdata",
185 [sd_programming_state] = "programming",
186 [sd_disconnect_state] = "disconnect",
188 if (state == sd_inactive_state) {
191 assert(state < ARRAY_SIZE(state_name));
192 return state_name[state];
195 static const char *sd_response_name(sd_rsp_type_t rsp)
197 static const char *response_name[] = {
198 [sd_r0] = "RESP#0 (no response)",
199 [sd_r1] = "RESP#1 (normal cmd)",
200 [sd_r2_i] = "RESP#2 (CID reg)",
201 [sd_r2_s] = "RESP#2 (CSD reg)",
202 [sd_r3] = "RESP#3 (OCR reg)",
203 [sd_r6] = "RESP#6 (RCA)",
204 [sd_r7] = "RESP#7 (operating voltage)",
206 if (rsp == sd_illegal) {
207 return "ILLEGAL RESP";
212 assert(rsp < ARRAY_SIZE(response_name));
213 return response_name[rsp];
216 static uint8_t sd_get_dat_lines(SDState *sd)
218 return sd->enable ? sd->dat_lines : 0;
221 static bool sd_get_cmd_line(SDState *sd)
223 return sd->enable ? sd->cmd_line : false;
226 static void sd_set_voltage(SDState *sd, uint16_t millivolts)
228 trace_sdcard_set_voltage(millivolts);
230 switch (millivolts) {
231 case 3001 ... 3600: /* SD_VOLTAGE_3_3V */
232 case 2001 ... 3000: /* SD_VOLTAGE_3_0V */
235 qemu_log_mask(LOG_GUEST_ERROR, "SD card voltage not supported: %.3fV",
236 millivolts / 1000.f);
240 static void sd_set_mode(SDState *sd)
243 case sd_inactive_state:
244 sd->mode = sd_inactive;
249 case sd_identification_state:
250 sd->mode = sd_card_identification_mode;
253 case sd_standby_state:
254 case sd_transfer_state:
255 case sd_sendingdata_state:
256 case sd_receivingdata_state:
257 case sd_programming_state:
258 case sd_disconnect_state:
259 sd->mode = sd_data_transfer_mode;
264 static const sd_cmd_type_t sd_cmd_type[SDMMC_CMD_MAX] = {
265 sd_bc, sd_none, sd_bcr, sd_bcr, sd_none, sd_none, sd_none, sd_ac,
266 sd_bcr, sd_ac, sd_ac, sd_adtc, sd_ac, sd_ac, sd_none, sd_ac,
268 sd_ac, sd_adtc, sd_adtc, sd_none, sd_none, sd_none, sd_none, sd_none,
269 sd_adtc, sd_adtc, sd_adtc, sd_adtc, sd_ac, sd_ac, sd_adtc, sd_none,
271 sd_ac, sd_ac, sd_none, sd_none, sd_none, sd_none, sd_ac, sd_none,
272 sd_none, sd_none, sd_bc, sd_none, sd_none, sd_none, sd_none, sd_none,
274 sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, sd_ac,
275 sd_adtc, sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, sd_none,
278 static const int sd_cmd_class[SDMMC_CMD_MAX] = {
279 0, 0, 0, 0, 0, 9, 10, 0, 0, 0, 0, 1, 0, 0, 0, 0,
280 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 6, 6, 6, 6,
281 5, 5, 10, 10, 10, 10, 5, 9, 9, 9, 7, 7, 7, 7, 7, 7,
282 7, 7, 10, 7, 9, 9, 9, 8, 8, 10, 8, 8, 8, 8, 8, 8,
285 static uint8_t sd_crc7(const void *message, size_t width)
288 uint8_t shift_reg = 0x00;
289 const uint8_t *msg = (const uint8_t *)message;
291 for (i = 0; i < width; i ++, msg ++)
292 for (bit = 7; bit >= 0; bit --) {
294 if ((shift_reg >> 7) ^ ((*msg >> bit) & 1))
301 #define OCR_POWER_DELAY_NS 500000 /* 0.5ms */
303 FIELD(OCR, VDD_VOLTAGE_WINDOW, 0, 24)
304 FIELD(OCR, VDD_VOLTAGE_WIN_LO, 0, 8)
305 FIELD(OCR, DUAL_VOLTAGE_CARD, 7, 1)
306 FIELD(OCR, VDD_VOLTAGE_WIN_HI, 8, 16)
307 FIELD(OCR, ACCEPT_SWITCH_1V8, 24, 1) /* Only UHS-I */
308 FIELD(OCR, UHS_II_CARD, 29, 1) /* Only UHS-II */
309 FIELD(OCR, CARD_CAPACITY, 30, 1) /* 0:SDSC, 1:SDHC/SDXC */
310 FIELD(OCR, CARD_POWER_UP, 31, 1)
312 #define ACMD41_ENQUIRY_MASK 0x00ffffff
313 #define ACMD41_R3_MASK (R_OCR_VDD_VOLTAGE_WIN_HI_MASK \
314 | R_OCR_ACCEPT_SWITCH_1V8_MASK \
315 | R_OCR_UHS_II_CARD_MASK \
316 | R_OCR_CARD_CAPACITY_MASK \
317 | R_OCR_CARD_POWER_UP_MASK)
319 static void sd_ocr_powerup(void *opaque)
321 SDState *sd = opaque;
323 trace_sdcard_powerup();
324 assert(!FIELD_EX32(sd->ocr, OCR, CARD_POWER_UP));
326 /* card power-up OK */
327 sd->ocr = FIELD_DP32(sd->ocr, OCR, CARD_POWER_UP, 1);
329 if (sd->size > SDSC_MAX_CAPACITY) {
330 sd->ocr = FIELD_DP32(sd->ocr, OCR, CARD_CAPACITY, 1);
334 static void sd_set_ocr(SDState *sd)
336 /* All voltages OK */
337 sd->ocr = R_OCR_VDD_VOLTAGE_WIN_HI_MASK;
341 * We don't need to emulate power up sequence in SPI-mode.
342 * Thus, the card's power up status bit should be set to 1 when reset.
343 * The card's capacity status bit should also be set if SD card size
344 * is larger than 2GB for SDHC support.
350 static void sd_set_scr(SDState *sd)
352 sd->scr[0] = 0 << 4; /* SCR structure version 1.0 */
353 if (sd->spec_version == SD_PHY_SPECv1_10_VERS) {
354 sd->scr[0] |= 1; /* Spec Version 1.10 */
356 sd->scr[0] |= 2; /* Spec Version 2.00 or Version 3.0X */
358 sd->scr[1] = (2 << 4) /* SDSC Card (Security Version 1.01) */
359 | 0b0101; /* 1-bit or 4-bit width bus modes */
360 sd->scr[2] = 0x00; /* Extended Security is not supported. */
361 if (sd->spec_version >= SD_PHY_SPECv3_01_VERS) {
362 sd->scr[2] |= 1 << 7; /* Spec Version 3.0X */
365 /* reserved for manufacturer usage */
379 static void sd_set_cid(SDState *sd)
381 sd->cid[0] = MID; /* Fake card manufacturer ID (MID) */
382 sd->cid[1] = OID[0]; /* OEM/Application ID (OID) */
384 sd->cid[3] = PNM[0]; /* Fake product name (PNM) */
389 sd->cid[8] = PRV; /* Fake product revision (PRV) */
390 sd->cid[9] = 0xde; /* Fake serial number (PSN) */
394 sd->cid[13] = 0x00 | /* Manufacture date (MDT) */
395 ((MDT_YR - 2000) / 10);
396 sd->cid[14] = ((MDT_YR % 10) << 4) | MDT_MON;
397 sd->cid[15] = (sd_crc7(sd->cid, 15) << 1) | 1;
400 #define HWBLOCK_SHIFT 9 /* 512 bytes */
401 #define SECTOR_SHIFT 5 /* 16 kilobytes */
402 #define WPGROUP_SHIFT 7 /* 2 megs */
403 #define CMULT_SHIFT 9 /* 512 times HWBLOCK_SIZE */
404 #define WPGROUP_SIZE (1 << (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT))
406 static const uint8_t sd_csd_rw_mask[16] = {
407 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
408 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xfe,
411 static void sd_set_csd(SDState *sd, uint64_t size)
413 int hwblock_shift = HWBLOCK_SHIFT;
415 uint32_t sectsize = (1 << (SECTOR_SHIFT + 1)) - 1;
416 uint32_t wpsize = (1 << (WPGROUP_SHIFT + 1)) - 1;
418 /* To indicate 2 GiB card, BLOCK_LEN shall be 1024 bytes */
419 if (size == SDSC_MAX_CAPACITY) {
422 csize = (size >> (CMULT_SHIFT + hwblock_shift)) - 1;
424 if (size <= SDSC_MAX_CAPACITY) { /* Standard Capacity SD */
425 sd->csd[0] = 0x00; /* CSD structure */
426 sd->csd[1] = 0x26; /* Data read access-time-1 */
427 sd->csd[2] = 0x00; /* Data read access-time-2 */
428 sd->csd[3] = 0x32; /* Max. data transfer rate: 25 MHz */
429 sd->csd[4] = 0x5f; /* Card Command Classes */
430 sd->csd[5] = 0x50 | /* Max. read data block length */
432 sd->csd[6] = 0xe0 | /* Partial block for read allowed */
433 ((csize >> 10) & 0x03);
434 sd->csd[7] = 0x00 | /* Device size */
435 ((csize >> 2) & 0xff);
436 sd->csd[8] = 0x3f | /* Max. read current */
437 ((csize << 6) & 0xc0);
438 sd->csd[9] = 0xfc | /* Max. write current */
439 ((CMULT_SHIFT - 2) >> 1);
440 sd->csd[10] = 0x40 | /* Erase sector size */
441 (((CMULT_SHIFT - 2) << 7) & 0x80) | (sectsize >> 1);
442 sd->csd[11] = 0x00 | /* Write protect group size */
443 ((sectsize << 7) & 0x80) | wpsize;
444 sd->csd[12] = 0x90 | /* Write speed factor */
445 (hwblock_shift >> 2);
446 sd->csd[13] = 0x20 | /* Max. write data block length */
447 ((hwblock_shift << 6) & 0xc0);
448 sd->csd[14] = 0x00; /* File format group */
459 sd->csd[7] = (size >> 16) & 0xff;
460 sd->csd[8] = (size >> 8) & 0xff;
461 sd->csd[9] = (size & 0xff);
468 sd->csd[15] = (sd_crc7(sd->csd, 15) << 1) | 1;
471 static void sd_set_rca(SDState *sd)
476 FIELD(CSR, AKE_SEQ_ERROR, 3, 1)
477 FIELD(CSR, APP_CMD, 5, 1)
478 FIELD(CSR, FX_EVENT, 6, 1)
479 FIELD(CSR, READY_FOR_DATA, 8, 1)
480 FIELD(CSR, CURRENT_STATE, 9, 4)
481 FIELD(CSR, ERASE_RESET, 13, 1)
482 FIELD(CSR, CARD_ECC_DISABLED, 14, 1)
483 FIELD(CSR, WP_ERASE_SKIP, 15, 1)
484 FIELD(CSR, CSD_OVERWRITE, 16, 1)
485 FIELD(CSR, DEFERRED_RESPONSE, 17, 1)
486 FIELD(CSR, ERROR, 19, 1)
487 FIELD(CSR, CC_ERROR, 20, 1)
488 FIELD(CSR, CARD_ECC_FAILED, 21, 1)
489 FIELD(CSR, ILLEGAL_COMMAND, 22, 1)
490 FIELD(CSR, COM_CRC_ERROR, 23, 1)
491 FIELD(CSR, LOCK_UNLOCK_FAILED, 24, 1)
492 FIELD(CSR, CARD_IS_LOCKED, 25, 1)
493 FIELD(CSR, WP_VIOLATION, 26, 1)
494 FIELD(CSR, ERASE_PARAM, 27, 1)
495 FIELD(CSR, ERASE_SEQ_ERROR, 28, 1)
496 FIELD(CSR, BLOCK_LEN_ERROR, 29, 1)
497 FIELD(CSR, ADDRESS_ERROR, 30, 1)
498 FIELD(CSR, OUT_OF_RANGE, 31, 1)
500 /* Card status bits, split by clear condition:
501 * A : According to the card current state
502 * B : Always related to the previous command
503 * C : Cleared by read
505 #define CARD_STATUS_A (R_CSR_READY_FOR_DATA_MASK \
506 | R_CSR_CARD_ECC_DISABLED_MASK \
507 | R_CSR_CARD_IS_LOCKED_MASK)
508 #define CARD_STATUS_B (R_CSR_CURRENT_STATE_MASK \
509 | R_CSR_ILLEGAL_COMMAND_MASK \
510 | R_CSR_COM_CRC_ERROR_MASK)
511 #define CARD_STATUS_C (R_CSR_AKE_SEQ_ERROR_MASK \
512 | R_CSR_APP_CMD_MASK \
513 | R_CSR_ERASE_RESET_MASK \
514 | R_CSR_WP_ERASE_SKIP_MASK \
515 | R_CSR_CSD_OVERWRITE_MASK \
517 | R_CSR_CC_ERROR_MASK \
518 | R_CSR_CARD_ECC_FAILED_MASK \
519 | R_CSR_LOCK_UNLOCK_FAILED_MASK \
520 | R_CSR_WP_VIOLATION_MASK \
521 | R_CSR_ERASE_PARAM_MASK \
522 | R_CSR_ERASE_SEQ_ERROR_MASK \
523 | R_CSR_BLOCK_LEN_ERROR_MASK \
524 | R_CSR_ADDRESS_ERROR_MASK \
525 | R_CSR_OUT_OF_RANGE_MASK)
527 static void sd_set_cardstatus(SDState *sd)
529 sd->card_status = 0x00000100;
532 static void sd_set_sdstatus(SDState *sd)
534 memset(sd->sd_status, 0, 64);
537 static int sd_req_crc_validate(SDRequest *req)
540 buffer[0] = 0x40 | req->cmd;
541 stl_be_p(&buffer[1], req->arg);
543 return sd_crc7(buffer, 5) != req->crc; /* TODO */
546 static void sd_response_r1_make(SDState *sd, uint8_t *response)
548 stl_be_p(response, sd->card_status);
550 /* Clear the "clear on read" status bits */
551 sd->card_status &= ~CARD_STATUS_C;
554 static void sd_response_r3_make(SDState *sd, uint8_t *response)
556 stl_be_p(response, sd->ocr & ACMD41_R3_MASK);
559 static void sd_response_r6_make(SDState *sd, uint8_t *response)
563 status = ((sd->card_status >> 8) & 0xc000) |
564 ((sd->card_status >> 6) & 0x2000) |
565 (sd->card_status & 0x1fff);
566 sd->card_status &= ~(CARD_STATUS_C & 0xc81fff);
567 stw_be_p(response + 0, sd->rca);
568 stw_be_p(response + 2, status);
571 static void sd_response_r7_make(SDState *sd, uint8_t *response)
573 stl_be_p(response, sd->vhs);
576 static inline uint64_t sd_addr_to_wpnum(uint64_t addr)
578 return addr >> (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT);
581 static void sd_reset(DeviceState *dev)
583 SDState *sd = SD_CARD(dev);
587 trace_sdcard_reset();
589 blk_get_geometry(sd->blk, §);
595 sect = sd_addr_to_wpnum(size) + 1;
597 sd->state = sd_idle_state;
603 sd_set_csd(sd, size);
604 sd_set_cardstatus(sd);
607 g_free(sd->wp_group_bmap);
608 sd->wp_switch = sd->blk ? !blk_is_writable(sd->blk) : false;
609 sd->wp_group_bits = sect;
610 sd->wp_group_bmap = bitmap_new(sd->wp_group_bits);
611 memset(sd->function_group, 0, sizeof(sd->function_group));
612 sd->erase_start = INVALID_ADDRESS;
613 sd->erase_end = INVALID_ADDRESS;
616 sd->expecting_acmd = false;
619 sd->multi_blk_cnt = 0;
622 static bool sd_get_inserted(SDState *sd)
624 return sd->blk && blk_is_inserted(sd->blk);
627 static bool sd_get_readonly(SDState *sd)
629 return sd->wp_switch;
632 static void sd_cardchange(void *opaque, bool load, Error **errp)
634 SDState *sd = opaque;
635 DeviceState *dev = DEVICE(sd);
637 bool inserted = sd_get_inserted(sd);
638 bool readonly = sd_get_readonly(sd);
641 trace_sdcard_inserted(readonly);
644 trace_sdcard_ejected();
647 if (sd->me_no_qdev_me_kill_mammoth_with_rocks) {
648 qemu_set_irq(sd->inserted_cb, inserted);
650 qemu_set_irq(sd->readonly_cb, readonly);
653 sdbus = SD_BUS(qdev_get_parent_bus(dev));
654 sdbus_set_inserted(sdbus, inserted);
656 sdbus_set_readonly(sdbus, readonly);
661 static const BlockDevOps sd_block_ops = {
662 .change_media_cb = sd_cardchange,
665 static bool sd_ocr_vmstate_needed(void *opaque)
667 SDState *sd = opaque;
669 /* Include the OCR state (and timer) if it is not yet powered up */
670 return !FIELD_EX32(sd->ocr, OCR, CARD_POWER_UP);
673 static const VMStateDescription sd_ocr_vmstate = {
674 .name = "sd-card/ocr-state",
676 .minimum_version_id = 1,
677 .needed = sd_ocr_vmstate_needed,
678 .fields = (VMStateField[]) {
679 VMSTATE_UINT32(ocr, SDState),
680 VMSTATE_TIMER_PTR(ocr_power_timer, SDState),
681 VMSTATE_END_OF_LIST()
685 static int sd_vmstate_pre_load(void *opaque)
687 SDState *sd = opaque;
689 /* If the OCR state is not included (prior versions, or not
690 * needed), then the OCR must be set as powered up. If the OCR state
691 * is included, this will be replaced by the state restore.
698 static const VMStateDescription sd_vmstate = {
701 .minimum_version_id = 2,
702 .pre_load = sd_vmstate_pre_load,
703 .fields = (VMStateField[]) {
704 VMSTATE_UINT32(mode, SDState),
705 VMSTATE_INT32(state, SDState),
706 VMSTATE_UINT8_ARRAY(cid, SDState, 16),
707 VMSTATE_UINT8_ARRAY(csd, SDState, 16),
708 VMSTATE_UINT16(rca, SDState),
709 VMSTATE_UINT32(card_status, SDState),
710 VMSTATE_PARTIAL_BUFFER(sd_status, SDState, 1),
711 VMSTATE_UINT32(vhs, SDState),
712 VMSTATE_BITMAP(wp_group_bmap, SDState, 0, wp_group_bits),
713 VMSTATE_UINT32(blk_len, SDState),
714 VMSTATE_UINT32(multi_blk_cnt, SDState),
715 VMSTATE_UINT32(erase_start, SDState),
716 VMSTATE_UINT32(erase_end, SDState),
717 VMSTATE_UINT8_ARRAY(pwd, SDState, 16),
718 VMSTATE_UINT32(pwd_len, SDState),
719 VMSTATE_UINT8_ARRAY(function_group, SDState, 6),
720 VMSTATE_UINT8(current_cmd, SDState),
721 VMSTATE_BOOL(expecting_acmd, SDState),
722 VMSTATE_UINT32(blk_written, SDState),
723 VMSTATE_UINT64(data_start, SDState),
724 VMSTATE_UINT32(data_offset, SDState),
725 VMSTATE_UINT8_ARRAY(data, SDState, 512),
726 VMSTATE_UNUSED_V(1, 512),
727 VMSTATE_BOOL(enable, SDState),
728 VMSTATE_END_OF_LIST()
730 .subsections = (const VMStateDescription*[]) {
736 /* Legacy initialization function for use by non-qdevified callers */
737 SDState *sd_init(BlockBackend *blk, bool is_spi)
744 obj = object_new(TYPE_SD_CARD);
746 if (!qdev_prop_set_drive_err(dev, "drive", blk, &err)) {
747 error_reportf_err(err, "sd_init failed: ");
750 qdev_prop_set_bit(dev, "spi", is_spi);
753 * Realizing the device properly would put it into the QOM
754 * composition tree even though it is not plugged into an
755 * appropriate bus. That's a no-no. Hide the device from
756 * QOM/qdev, and call its qdev realize callback directly.
759 object_unparent(obj);
760 sd_realize(dev, &err);
762 error_reportf_err(err, "sd_init failed: ");
767 sd->me_no_qdev_me_kill_mammoth_with_rocks = true;
771 void sd_set_cb(SDState *sd, qemu_irq readonly, qemu_irq insert)
773 sd->readonly_cb = readonly;
774 sd->inserted_cb = insert;
775 qemu_set_irq(readonly, sd->blk ? !blk_is_writable(sd->blk) : 0);
776 qemu_set_irq(insert, sd->blk ? blk_is_inserted(sd->blk) : 0);
779 static void sd_blk_read(SDState *sd, uint64_t addr, uint32_t len)
781 trace_sdcard_read_block(addr, len);
782 if (!sd->blk || blk_pread(sd->blk, addr, len, sd->data, 0) < 0) {
783 fprintf(stderr, "sd_blk_read: read error on host side\n");
787 static void sd_blk_write(SDState *sd, uint64_t addr, uint32_t len)
789 trace_sdcard_write_block(addr, len);
790 if (!sd->blk || blk_pwrite(sd->blk, addr, len, sd->data, 0) < 0) {
791 fprintf(stderr, "sd_blk_write: write error on host side\n");
795 #define BLK_READ_BLOCK(a, len) sd_blk_read(sd, a, len)
796 #define BLK_WRITE_BLOCK(a, len) sd_blk_write(sd, a, len)
797 #define APP_READ_BLOCK(a, len) memset(sd->data, 0xec, len)
798 #define APP_WRITE_BLOCK(a, len)
800 static void sd_erase(SDState *sd)
802 uint64_t erase_start = sd->erase_start;
803 uint64_t erase_end = sd->erase_end;
807 int erase_len = 1 << HWBLOCK_SHIFT;
809 trace_sdcard_erase(sd->erase_start, sd->erase_end);
810 if (sd->erase_start == INVALID_ADDRESS
811 || sd->erase_end == INVALID_ADDRESS) {
812 sd->card_status |= ERASE_SEQ_ERROR;
813 sd->erase_start = INVALID_ADDRESS;
814 sd->erase_end = INVALID_ADDRESS;
818 if (FIELD_EX32(sd->ocr, OCR, CARD_CAPACITY)) {
819 /* High capacity memory card: erase units are 512 byte blocks */
825 if (erase_start > sd->size || erase_end > sd->size) {
826 sd->card_status |= OUT_OF_RANGE;
827 sd->erase_start = INVALID_ADDRESS;
828 sd->erase_end = INVALID_ADDRESS;
832 sd->erase_start = INVALID_ADDRESS;
833 sd->erase_end = INVALID_ADDRESS;
836 memset(sd->data, 0xff, erase_len);
837 for (erase_addr = erase_start; erase_addr <= erase_end;
838 erase_addr += erase_len) {
840 /* Only SDSC cards support write protect groups */
841 wpnum = sd_addr_to_wpnum(erase_addr);
842 assert(wpnum < sd->wp_group_bits);
843 if (test_bit(wpnum, sd->wp_group_bmap)) {
844 sd->card_status |= WP_ERASE_SKIP;
848 BLK_WRITE_BLOCK(erase_addr, erase_len);
852 static uint32_t sd_wpbits(SDState *sd, uint64_t addr)
857 wpnum = sd_addr_to_wpnum(addr);
859 for (i = 0; i < 32; i++, wpnum++, addr += WPGROUP_SIZE) {
860 if (addr >= sd->size) {
862 * If the addresses of the last groups are outside the valid range,
863 * then the corresponding write protection bits shall be set to 0.
867 assert(wpnum < sd->wp_group_bits);
868 if (test_bit(wpnum, sd->wp_group_bmap)) {
876 static void sd_function_switch(SDState *sd, uint32_t arg)
878 int i, mode, new_func;
879 mode = !!(arg & 0x80000000);
881 sd->data[0] = 0x00; /* Maximum current consumption */
883 sd->data[2] = 0x80; /* Supported group 6 functions */
885 sd->data[4] = 0x80; /* Supported group 5 functions */
887 sd->data[6] = 0x80; /* Supported group 4 functions */
889 sd->data[8] = 0x80; /* Supported group 3 functions */
891 sd->data[10] = 0x80; /* Supported group 2 functions */
893 sd->data[12] = 0x80; /* Supported group 1 functions */
896 memset(&sd->data[14], 0, 3);
897 for (i = 0; i < 6; i ++) {
898 new_func = (arg >> (i * 4)) & 0x0f;
899 if (mode && new_func != 0x0f)
900 sd->function_group[i] = new_func;
901 sd->data[16 - (i >> 1)] |= new_func << ((i % 2) * 4);
903 memset(&sd->data[17], 0, 47);
906 static inline bool sd_wp_addr(SDState *sd, uint64_t addr)
908 return test_bit(sd_addr_to_wpnum(addr), sd->wp_group_bmap);
911 static void sd_lock_command(SDState *sd)
913 int erase, lock, clr_pwd, set_pwd, pwd_len;
914 erase = !!(sd->data[0] & 0x08);
915 lock = sd->data[0] & 0x04;
916 clr_pwd = sd->data[0] & 0x02;
917 set_pwd = sd->data[0] & 0x01;
920 pwd_len = sd->data[1];
927 trace_sdcard_unlock();
930 if (!(sd->card_status & CARD_IS_LOCKED) || sd->blk_len > 1 ||
931 set_pwd || clr_pwd || lock || sd->wp_switch ||
932 (sd->csd[14] & 0x20)) {
933 sd->card_status |= LOCK_UNLOCK_FAILED;
936 bitmap_zero(sd->wp_group_bmap, sd->wp_group_bits);
937 sd->csd[14] &= ~0x10;
938 sd->card_status &= ~CARD_IS_LOCKED;
940 /* Erasing the entire card here! */
941 fprintf(stderr, "SD: Card force-erased by CMD42\n");
945 if (sd->blk_len < 2 + pwd_len ||
946 pwd_len <= sd->pwd_len ||
947 pwd_len > sd->pwd_len + 16) {
948 sd->card_status |= LOCK_UNLOCK_FAILED;
952 if (sd->pwd_len && memcmp(sd->pwd, sd->data + 2, sd->pwd_len)) {
953 sd->card_status |= LOCK_UNLOCK_FAILED;
957 pwd_len -= sd->pwd_len;
958 if ((pwd_len && !set_pwd) ||
959 (clr_pwd && (set_pwd || lock)) ||
960 (lock && !sd->pwd_len && !set_pwd) ||
961 (!set_pwd && !clr_pwd &&
962 (((sd->card_status & CARD_IS_LOCKED) && lock) ||
963 (!(sd->card_status & CARD_IS_LOCKED) && !lock)))) {
964 sd->card_status |= LOCK_UNLOCK_FAILED;
969 memcpy(sd->pwd, sd->data + 2 + sd->pwd_len, pwd_len);
970 sd->pwd_len = pwd_len;
978 sd->card_status |= CARD_IS_LOCKED;
980 sd->card_status &= ~CARD_IS_LOCKED;
983 static bool address_in_range(SDState *sd, const char *desc,
984 uint64_t addr, uint32_t length)
986 if (addr + length > sd->size) {
987 qemu_log_mask(LOG_GUEST_ERROR,
988 "%s offset %"PRIu64" > card %"PRIu64" [%%%u]\n",
989 desc, addr, sd->size, length);
990 sd->card_status |= ADDRESS_ERROR;
996 static sd_rsp_type_t sd_invalid_state_for_cmd(SDState *sd, SDRequest req)
998 qemu_log_mask(LOG_GUEST_ERROR, "%s: CMD%i in a wrong state: %s (spec %s)\n",
999 sd_proto(sd)->name, req.cmd, sd_state_name(sd->state),
1000 sd_version_str(sd->spec_version));
1005 static sd_rsp_type_t sd_cmd_illegal(SDState *sd, SDRequest req)
1007 qemu_log_mask(LOG_GUEST_ERROR, "%s: Unknown CMD%i for spec %s\n",
1008 sd_proto(sd)->name, req.cmd,
1009 sd_version_str(sd->spec_version));
1014 static sd_rsp_type_t sd_normal_command(SDState *sd, SDRequest req)
1016 uint32_t rca = 0x0000;
1017 uint64_t addr = (sd->ocr & (1 << 30)) ? (uint64_t) req.arg << 9 : req.arg;
1019 /* CMD55 precedes an ACMD, so we are not interested in tracing it.
1020 * However there is no ACMD55, so we want to trace this particular case.
1022 if (req.cmd != 55 || sd->expecting_acmd) {
1023 trace_sdcard_normal_command(sd_proto(sd)->name,
1024 sd_cmd_name(req.cmd), req.cmd,
1025 req.arg, sd_state_name(sd->state));
1028 /* Not interpreting this as an app command */
1029 sd->card_status &= ~APP_CMD;
1031 if (sd_cmd_type[req.cmd] == sd_ac
1032 || sd_cmd_type[req.cmd] == sd_adtc) {
1033 rca = req.arg >> 16;
1036 /* CMD23 (set block count) must be immediately followed by CMD18 or CMD25
1037 * if not, its effects are cancelled */
1038 if (sd->multi_blk_cnt != 0 && !(req.cmd == 18 || req.cmd == 25)) {
1039 sd->multi_blk_cnt = 0;
1042 if (sd_cmd_class[req.cmd] == 6 && FIELD_EX32(sd->ocr, OCR, CARD_CAPACITY)) {
1043 /* Only Standard Capacity cards support class 6 commands */
1047 if (sd_proto(sd)->cmd[req.cmd]) {
1048 return sd_proto(sd)->cmd[req.cmd](sd, req);
1052 /* Basic commands (Class 0 and Class 1) */
1053 case 0: /* CMD0: GO_IDLE_STATE */
1054 switch (sd->state) {
1055 case sd_inactive_state:
1056 return sd->spi ? sd_r1 : sd_r0;
1059 sd->state = sd_idle_state;
1060 sd_reset(DEVICE(sd));
1061 return sd->spi ? sd_r1 : sd_r0;
1065 case 1: /* CMD1: SEND_OP_CMD */
1066 sd->state = sd_transfer_state;
1069 case 2: /* CMD2: ALL_SEND_CID */
1070 switch (sd->state) {
1071 case sd_ready_state:
1072 sd->state = sd_identification_state;
1080 case 3: /* CMD3: SEND_RELATIVE_ADDR */
1081 switch (sd->state) {
1082 case sd_identification_state:
1083 case sd_standby_state:
1084 sd->state = sd_standby_state;
1093 case 4: /* CMD4: SEND_DSR */
1094 switch (sd->state) {
1095 case sd_standby_state:
1103 case 6: /* CMD6: SWITCH_FUNCTION */
1105 case sd_data_transfer_mode:
1106 sd_function_switch(sd, req.arg);
1107 sd->state = sd_sendingdata_state;
1109 sd->data_offset = 0;
1117 case 7: /* CMD7: SELECT/DESELECT_CARD */
1118 switch (sd->state) {
1119 case sd_standby_state:
1123 sd->state = sd_transfer_state;
1126 case sd_transfer_state:
1127 case sd_sendingdata_state:
1131 sd->state = sd_standby_state;
1134 case sd_disconnect_state:
1138 sd->state = sd_programming_state;
1141 case sd_programming_state:
1145 sd->state = sd_disconnect_state;
1153 case 8: /* CMD8: SEND_IF_COND */
1154 if (sd->spec_version < SD_PHY_SPECv2_00_VERS) {
1157 if (sd->state != sd_idle_state) {
1162 /* No response if not exactly one VHS bit is set. */
1163 if (!(req.arg >> 8) || (req.arg >> (ctz32(req.arg & ~0xff) + 1))) {
1164 return sd->spi ? sd_r7 : sd_r0;
1171 case 9: /* CMD9: SEND_CSD */
1172 switch (sd->state) {
1173 case sd_standby_state:
1179 case sd_transfer_state:
1182 sd->state = sd_sendingdata_state;
1183 memcpy(sd->data, sd->csd, 16);
1184 sd->data_start = addr;
1185 sd->data_offset = 0;
1193 case 10: /* CMD10: SEND_CID */
1194 switch (sd->state) {
1195 case sd_standby_state:
1201 case sd_transfer_state:
1204 sd->state = sd_sendingdata_state;
1205 memcpy(sd->data, sd->cid, 16);
1206 sd->data_start = addr;
1207 sd->data_offset = 0;
1215 case 12: /* CMD12: STOP_TRANSMISSION */
1216 switch (sd->state) {
1217 case sd_sendingdata_state:
1218 sd->state = sd_transfer_state;
1221 case sd_receivingdata_state:
1222 sd->state = sd_programming_state;
1223 /* Bzzzzzzztt .... Operation complete. */
1224 sd->state = sd_transfer_state;
1232 case 13: /* CMD13: SEND_STATUS */
1234 case sd_data_transfer_mode:
1235 if (!sd->spi && sd->rca != rca) {
1246 case 15: /* CMD15: GO_INACTIVE_STATE */
1248 case sd_data_transfer_mode:
1252 sd->state = sd_inactive_state;
1260 /* Block read commands (Classs 2) */
1261 case 16: /* CMD16: SET_BLOCKLEN */
1262 switch (sd->state) {
1263 case sd_transfer_state:
1264 if (req.arg > (1 << HWBLOCK_SHIFT)) {
1265 sd->card_status |= BLOCK_LEN_ERROR;
1267 trace_sdcard_set_blocklen(req.arg);
1268 sd->blk_len = req.arg;
1278 case 17: /* CMD17: READ_SINGLE_BLOCK */
1279 case 18: /* CMD18: READ_MULTIPLE_BLOCK */
1280 switch (sd->state) {
1281 case sd_transfer_state:
1283 if (!address_in_range(sd, "READ_BLOCK", addr, sd->blk_len)) {
1287 sd->state = sd_sendingdata_state;
1288 sd->data_start = addr;
1289 sd->data_offset = 0;
1297 case 19: /* CMD19: SEND_TUNING_BLOCK (SD) */
1298 if (sd->spec_version < SD_PHY_SPECv3_01_VERS) {
1299 return sd_invalid_state_for_cmd(sd, req);
1301 if (sd->state == sd_transfer_state) {
1302 sd->state = sd_sendingdata_state;
1303 sd->data_offset = 0;
1308 case 23: /* CMD23: SET_BLOCK_COUNT */
1309 if (sd->spec_version < SD_PHY_SPECv3_01_VERS) {
1310 return sd_invalid_state_for_cmd(sd, req);
1312 switch (sd->state) {
1313 case sd_transfer_state:
1314 sd->multi_blk_cnt = req.arg;
1322 /* Block write commands (Class 4) */
1323 case 24: /* CMD24: WRITE_SINGLE_BLOCK */
1324 case 25: /* CMD25: WRITE_MULTIPLE_BLOCK */
1325 switch (sd->state) {
1326 case sd_transfer_state:
1328 if (!address_in_range(sd, "WRITE_BLOCK", addr, sd->blk_len)) {
1332 sd->state = sd_receivingdata_state;
1333 sd->data_start = addr;
1334 sd->data_offset = 0;
1335 sd->blk_written = 0;
1337 if (sd->size <= SDSC_MAX_CAPACITY) {
1338 if (sd_wp_addr(sd, sd->data_start)) {
1339 sd->card_status |= WP_VIOLATION;
1342 if (sd->csd[14] & 0x30) {
1343 sd->card_status |= WP_VIOLATION;
1352 case 26: /* CMD26: PROGRAM_CID */
1353 switch (sd->state) {
1354 case sd_transfer_state:
1355 sd->state = sd_receivingdata_state;
1357 sd->data_offset = 0;
1365 case 27: /* CMD27: PROGRAM_CSD */
1366 switch (sd->state) {
1367 case sd_transfer_state:
1368 sd->state = sd_receivingdata_state;
1370 sd->data_offset = 0;
1378 /* Write protection (Class 6) */
1379 case 28: /* CMD28: SET_WRITE_PROT */
1380 if (sd->size > SDSC_MAX_CAPACITY) {
1384 switch (sd->state) {
1385 case sd_transfer_state:
1386 if (!address_in_range(sd, "SET_WRITE_PROT", addr, 1)) {
1390 sd->state = sd_programming_state;
1391 set_bit(sd_addr_to_wpnum(addr), sd->wp_group_bmap);
1392 /* Bzzzzzzztt .... Operation complete. */
1393 sd->state = sd_transfer_state;
1401 case 29: /* CMD29: CLR_WRITE_PROT */
1402 if (sd->size > SDSC_MAX_CAPACITY) {
1406 switch (sd->state) {
1407 case sd_transfer_state:
1408 if (!address_in_range(sd, "CLR_WRITE_PROT", addr, 1)) {
1412 sd->state = sd_programming_state;
1413 clear_bit(sd_addr_to_wpnum(addr), sd->wp_group_bmap);
1414 /* Bzzzzzzztt .... Operation complete. */
1415 sd->state = sd_transfer_state;
1423 case 30: /* CMD30: SEND_WRITE_PROT */
1424 if (sd->size > SDSC_MAX_CAPACITY) {
1428 switch (sd->state) {
1429 case sd_transfer_state:
1430 if (!address_in_range(sd, "SEND_WRITE_PROT",
1431 req.arg, sd->blk_len)) {
1435 sd->state = sd_sendingdata_state;
1436 *(uint32_t *) sd->data = sd_wpbits(sd, req.arg);
1437 sd->data_start = addr;
1438 sd->data_offset = 0;
1446 /* Erase commands (Class 5) */
1447 case 32: /* CMD32: ERASE_WR_BLK_START */
1448 switch (sd->state) {
1449 case sd_transfer_state:
1450 sd->erase_start = req.arg;
1458 case 33: /* CMD33: ERASE_WR_BLK_END */
1459 switch (sd->state) {
1460 case sd_transfer_state:
1461 sd->erase_end = req.arg;
1469 case 38: /* CMD38: ERASE */
1470 switch (sd->state) {
1471 case sd_transfer_state:
1472 if (sd->csd[14] & 0x30) {
1473 sd->card_status |= WP_VIOLATION;
1477 sd->state = sd_programming_state;
1479 /* Bzzzzzzztt .... Operation complete. */
1480 sd->state = sd_transfer_state;
1488 /* Lock card commands (Class 7) */
1489 case 42: /* CMD42: LOCK_UNLOCK */
1490 switch (sd->state) {
1491 case sd_transfer_state:
1492 sd->state = sd_receivingdata_state;
1494 sd->data_offset = 0;
1502 /* Application specific commands (Class 8) */
1503 case 55: /* CMD55: APP_CMD */
1504 switch (sd->state) {
1505 case sd_ready_state:
1506 case sd_identification_state:
1507 case sd_inactive_state:
1511 qemu_log_mask(LOG_GUEST_ERROR,
1512 "SD: illegal RCA 0x%04x for APP_CMD\n", req.cmd);
1518 if (sd->rca != rca) {
1522 sd->expecting_acmd = true;
1523 sd->card_status |= APP_CMD;
1526 case 56: /* CMD56: GEN_CMD */
1527 switch (sd->state) {
1528 case sd_transfer_state:
1529 sd->data_offset = 0;
1531 sd->state = sd_sendingdata_state;
1533 sd->state = sd_receivingdata_state;
1541 case 58: /* CMD58: READ_OCR (SPI) */
1544 case 59: /* CMD59: CRC_ON_OFF (SPI) */
1548 qemu_log_mask(LOG_GUEST_ERROR, "SD: Unknown CMD%i\n", req.cmd);
1552 return sd_invalid_state_for_cmd(sd, req);
1555 static sd_rsp_type_t sd_app_command(SDState *sd,
1558 trace_sdcard_app_command(sd_proto(sd)->name, sd_acmd_name(req.cmd),
1559 req.cmd, req.arg, sd_state_name(sd->state));
1560 sd->card_status |= APP_CMD;
1562 if (sd_proto(sd)->acmd[req.cmd]) {
1563 return sd_proto(sd)->acmd[req.cmd](sd, req);
1567 case 6: /* ACMD6: SET_BUS_WIDTH */
1569 goto unimplemented_spi_cmd;
1571 switch (sd->state) {
1572 case sd_transfer_state:
1573 sd->sd_status[0] &= 0x3f;
1574 sd->sd_status[0] |= (req.arg & 0x03) << 6;
1582 case 13: /* ACMD13: SD_STATUS */
1583 switch (sd->state) {
1584 case sd_transfer_state:
1585 sd->state = sd_sendingdata_state;
1587 sd->data_offset = 0;
1595 case 22: /* ACMD22: SEND_NUM_WR_BLOCKS */
1596 switch (sd->state) {
1597 case sd_transfer_state:
1598 *(uint32_t *) sd->data = sd->blk_written;
1600 sd->state = sd_sendingdata_state;
1602 sd->data_offset = 0;
1610 case 23: /* ACMD23: SET_WR_BLK_ERASE_COUNT */
1611 switch (sd->state) {
1612 case sd_transfer_state:
1620 case 41: /* ACMD41: SD_APP_OP_COND */
1623 sd->state = sd_transfer_state;
1626 if (sd->state != sd_idle_state) {
1629 /* If it's the first ACMD41 since reset, we need to decide
1630 * whether to power up. If this is not an enquiry ACMD41,
1631 * we immediately report power on and proceed below to the
1632 * ready state, but if it is, we set a timer to model a
1633 * delay for power up. This works around a bug in EDK2
1634 * UEFI, which sends an initial enquiry ACMD41, but
1635 * assumes that the card is in ready state as soon as it
1636 * sees the power up bit set. */
1637 if (!FIELD_EX32(sd->ocr, OCR, CARD_POWER_UP)) {
1638 if ((req.arg & ACMD41_ENQUIRY_MASK) != 0) {
1639 timer_del(sd->ocr_power_timer);
1642 trace_sdcard_inquiry_cmd41();
1643 if (!timer_pending(sd->ocr_power_timer)) {
1644 timer_mod_ns(sd->ocr_power_timer,
1645 (qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL)
1646 + OCR_POWER_DELAY_NS));
1651 if (FIELD_EX32(sd->ocr & req.arg, OCR, VDD_VOLTAGE_WINDOW)) {
1652 /* We accept any voltage. 10000 V is nothing.
1654 * Once we're powered up, we advance straight to ready state
1655 * unless it's an enquiry ACMD41 (bits 23:0 == 0).
1657 sd->state = sd_ready_state;
1662 case 42: /* ACMD42: SET_CLR_CARD_DETECT */
1663 switch (sd->state) {
1664 case sd_transfer_state:
1665 /* Bringing in the 50KOhm pull-up resistor... Done. */
1673 case 51: /* ACMD51: SEND_SCR */
1674 switch (sd->state) {
1675 case sd_transfer_state:
1676 sd->state = sd_sendingdata_state;
1678 sd->data_offset = 0;
1686 case 18: /* Reserved for SD security applications */
1691 /* Refer to the "SD Specifications Part3 Security Specification" for
1692 * information about the SD Security Features.
1694 qemu_log_mask(LOG_UNIMP, "SD: CMD%i Security not implemented\n",
1699 /* Fall back to standard commands. */
1700 return sd_normal_command(sd, req);
1702 unimplemented_spi_cmd:
1703 /* Commands that are recognised but not yet implemented in SPI mode. */
1704 qemu_log_mask(LOG_UNIMP, "SD: CMD%i not implemented in SPI mode\n",
1709 qemu_log_mask(LOG_GUEST_ERROR, "SD: ACMD%i in a wrong state\n", req.cmd);
1713 static int cmd_valid_while_locked(SDState *sd, const uint8_t cmd)
1715 /* Valid commands in locked state:
1717 * lock card class (7)
1719 * implicitly, the ACMD prefix CMD55
1721 * Anything else provokes an "illegal command" response.
1723 if (sd->expecting_acmd) {
1724 return cmd == 41 || cmd == 42;
1726 if (cmd == 16 || cmd == 55) {
1729 return sd_cmd_class[cmd] == 0 || sd_cmd_class[cmd] == 7;
1732 int sd_do_command(SDState *sd, SDRequest *req,
1733 uint8_t *response) {
1735 sd_rsp_type_t rtype;
1738 if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable) {
1742 if (sd_req_crc_validate(req)) {
1743 sd->card_status |= COM_CRC_ERROR;
1748 if (req->cmd >= SDMMC_CMD_MAX) {
1749 qemu_log_mask(LOG_GUEST_ERROR, "SD: incorrect command 0x%02x\n",
1754 if (sd->card_status & CARD_IS_LOCKED) {
1755 if (!cmd_valid_while_locked(sd, req->cmd)) {
1756 sd->card_status |= ILLEGAL_COMMAND;
1757 sd->expecting_acmd = false;
1758 qemu_log_mask(LOG_GUEST_ERROR, "SD: Card is locked\n");
1764 last_state = sd->state;
1767 if (sd->expecting_acmd) {
1768 sd->expecting_acmd = false;
1769 rtype = sd_app_command(sd, *req);
1771 rtype = sd_normal_command(sd, *req);
1774 if (rtype == sd_illegal) {
1775 sd->card_status |= ILLEGAL_COMMAND;
1777 /* Valid command, we can update the 'state before command' bits.
1778 * (Do this now so they appear in r1 responses.)
1780 sd->current_cmd = req->cmd;
1781 sd->card_status &= ~CURRENT_STATE;
1782 sd->card_status |= (last_state << 9);
1789 sd_response_r1_make(sd, response);
1794 memcpy(response, sd->cid, sizeof(sd->cid));
1799 memcpy(response, sd->csd, sizeof(sd->csd));
1804 sd_response_r3_make(sd, response);
1809 sd_response_r6_make(sd, response);
1814 sd_response_r7_make(sd, response);
1823 g_assert_not_reached();
1825 trace_sdcard_response(sd_response_name(rtype), rsplen);
1827 if (rtype != sd_illegal) {
1828 /* Clear the "clear on valid command" status bits now we've
1831 sd->card_status &= ~CARD_STATUS_B;
1835 qemu_hexdump(stderr, "Response", response, rsplen);
1841 void sd_write_byte(SDState *sd, uint8_t value)
1845 if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable)
1848 if (sd->state != sd_receivingdata_state) {
1849 qemu_log_mask(LOG_GUEST_ERROR,
1850 "%s: not in Receiving-Data state\n", __func__);
1854 if (sd->card_status & (ADDRESS_ERROR | WP_VIOLATION))
1857 trace_sdcard_write_data(sd_proto(sd)->name,
1858 sd_acmd_name(sd->current_cmd),
1859 sd->current_cmd, value);
1860 switch (sd->current_cmd) {
1861 case 24: /* CMD24: WRITE_SINGLE_BLOCK */
1862 sd->data[sd->data_offset ++] = value;
1863 if (sd->data_offset >= sd->blk_len) {
1864 /* TODO: Check CRC before committing */
1865 sd->state = sd_programming_state;
1866 BLK_WRITE_BLOCK(sd->data_start, sd->data_offset);
1868 sd->csd[14] |= 0x40;
1869 /* Bzzzzzzztt .... Operation complete. */
1870 sd->state = sd_transfer_state;
1874 case 25: /* CMD25: WRITE_MULTIPLE_BLOCK */
1875 if (sd->data_offset == 0) {
1876 /* Start of the block - let's check the address is valid */
1877 if (!address_in_range(sd, "WRITE_MULTIPLE_BLOCK",
1878 sd->data_start, sd->blk_len)) {
1881 if (sd->size <= SDSC_MAX_CAPACITY) {
1882 if (sd_wp_addr(sd, sd->data_start)) {
1883 sd->card_status |= WP_VIOLATION;
1888 sd->data[sd->data_offset++] = value;
1889 if (sd->data_offset >= sd->blk_len) {
1890 /* TODO: Check CRC before committing */
1891 sd->state = sd_programming_state;
1892 BLK_WRITE_BLOCK(sd->data_start, sd->data_offset);
1894 sd->data_start += sd->blk_len;
1895 sd->data_offset = 0;
1896 sd->csd[14] |= 0x40;
1898 /* Bzzzzzzztt .... Operation complete. */
1899 if (sd->multi_blk_cnt != 0) {
1900 if (--sd->multi_blk_cnt == 0) {
1902 sd->state = sd_transfer_state;
1907 sd->state = sd_receivingdata_state;
1911 case 26: /* CMD26: PROGRAM_CID */
1912 sd->data[sd->data_offset ++] = value;
1913 if (sd->data_offset >= sizeof(sd->cid)) {
1914 /* TODO: Check CRC before committing */
1915 sd->state = sd_programming_state;
1916 for (i = 0; i < sizeof(sd->cid); i ++)
1917 if ((sd->cid[i] | 0x00) != sd->data[i])
1918 sd->card_status |= CID_CSD_OVERWRITE;
1920 if (!(sd->card_status & CID_CSD_OVERWRITE))
1921 for (i = 0; i < sizeof(sd->cid); i ++) {
1923 sd->cid[i] &= sd->data[i];
1925 /* Bzzzzzzztt .... Operation complete. */
1926 sd->state = sd_transfer_state;
1930 case 27: /* CMD27: PROGRAM_CSD */
1931 sd->data[sd->data_offset ++] = value;
1932 if (sd->data_offset >= sizeof(sd->csd)) {
1933 /* TODO: Check CRC before committing */
1934 sd->state = sd_programming_state;
1935 for (i = 0; i < sizeof(sd->csd); i ++)
1936 if ((sd->csd[i] | sd_csd_rw_mask[i]) !=
1937 (sd->data[i] | sd_csd_rw_mask[i]))
1938 sd->card_status |= CID_CSD_OVERWRITE;
1940 /* Copy flag (OTP) & Permanent write protect */
1941 if (sd->csd[14] & ~sd->data[14] & 0x60)
1942 sd->card_status |= CID_CSD_OVERWRITE;
1944 if (!(sd->card_status & CID_CSD_OVERWRITE))
1945 for (i = 0; i < sizeof(sd->csd); i ++) {
1946 sd->csd[i] |= sd_csd_rw_mask[i];
1947 sd->csd[i] &= sd->data[i];
1949 /* Bzzzzzzztt .... Operation complete. */
1950 sd->state = sd_transfer_state;
1954 case 42: /* CMD42: LOCK_UNLOCK */
1955 sd->data[sd->data_offset ++] = value;
1956 if (sd->data_offset >= sd->blk_len) {
1957 /* TODO: Check CRC before committing */
1958 sd->state = sd_programming_state;
1959 sd_lock_command(sd);
1960 /* Bzzzzzzztt .... Operation complete. */
1961 sd->state = sd_transfer_state;
1965 case 56: /* CMD56: GEN_CMD */
1966 sd->data[sd->data_offset ++] = value;
1967 if (sd->data_offset >= sd->blk_len) {
1968 APP_WRITE_BLOCK(sd->data_start, sd->data_offset);
1969 sd->state = sd_transfer_state;
1974 qemu_log_mask(LOG_GUEST_ERROR, "%s: unknown command\n", __func__);
1979 #define SD_TUNING_BLOCK_SIZE 64
1981 static const uint8_t sd_tuning_block_pattern[SD_TUNING_BLOCK_SIZE] = {
1982 /* See: Physical Layer Simplified Specification Version 3.01, Table 4-2 */
1983 0xff, 0x0f, 0xff, 0x00, 0x0f, 0xfc, 0xc3, 0xcc,
1984 0xc3, 0x3c, 0xcc, 0xff, 0xfe, 0xff, 0xfe, 0xef,
1985 0xff, 0xdf, 0xff, 0xdd, 0xff, 0xfb, 0xff, 0xfb,
1986 0xbf, 0xff, 0x7f, 0xff, 0x77, 0xf7, 0xbd, 0xef,
1987 0xff, 0xf0, 0xff, 0xf0, 0x0f, 0xfc, 0xcc, 0x3c,
1988 0xcc, 0x33, 0xcc, 0xcf, 0xff, 0xef, 0xff, 0xee,
1989 0xff, 0xfd, 0xff, 0xfd, 0xdf, 0xff, 0xbf, 0xff,
1990 0xbb, 0xff, 0xf7, 0xff, 0xf7, 0x7f, 0x7b, 0xde,
1993 uint8_t sd_read_byte(SDState *sd)
1995 /* TODO: Append CRCs */
1999 if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable)
2002 if (sd->state != sd_sendingdata_state) {
2003 qemu_log_mask(LOG_GUEST_ERROR,
2004 "%s: not in Sending-Data state\n", __func__);
2008 if (sd->card_status & (ADDRESS_ERROR | WP_VIOLATION))
2011 io_len = (sd->ocr & (1 << 30)) ? 512 : sd->blk_len;
2013 trace_sdcard_read_data(sd_proto(sd)->name,
2014 sd_acmd_name(sd->current_cmd),
2015 sd->current_cmd, io_len);
2016 switch (sd->current_cmd) {
2017 case 6: /* CMD6: SWITCH_FUNCTION */
2018 ret = sd->data[sd->data_offset ++];
2020 if (sd->data_offset >= 64)
2021 sd->state = sd_transfer_state;
2024 case 9: /* CMD9: SEND_CSD */
2025 case 10: /* CMD10: SEND_CID */
2026 ret = sd->data[sd->data_offset ++];
2028 if (sd->data_offset >= 16)
2029 sd->state = sd_transfer_state;
2032 case 13: /* ACMD13: SD_STATUS */
2033 ret = sd->sd_status[sd->data_offset ++];
2035 if (sd->data_offset >= sizeof(sd->sd_status))
2036 sd->state = sd_transfer_state;
2039 case 17: /* CMD17: READ_SINGLE_BLOCK */
2040 if (sd->data_offset == 0)
2041 BLK_READ_BLOCK(sd->data_start, io_len);
2042 ret = sd->data[sd->data_offset ++];
2044 if (sd->data_offset >= io_len)
2045 sd->state = sd_transfer_state;
2048 case 18: /* CMD18: READ_MULTIPLE_BLOCK */
2049 if (sd->data_offset == 0) {
2050 if (!address_in_range(sd, "READ_MULTIPLE_BLOCK",
2051 sd->data_start, io_len)) {
2054 BLK_READ_BLOCK(sd->data_start, io_len);
2056 ret = sd->data[sd->data_offset ++];
2058 if (sd->data_offset >= io_len) {
2059 sd->data_start += io_len;
2060 sd->data_offset = 0;
2062 if (sd->multi_blk_cnt != 0) {
2063 if (--sd->multi_blk_cnt == 0) {
2065 sd->state = sd_transfer_state;
2072 case 19: /* CMD19: SEND_TUNING_BLOCK (SD) */
2073 if (sd->data_offset >= SD_TUNING_BLOCK_SIZE - 1) {
2074 sd->state = sd_transfer_state;
2076 ret = sd_tuning_block_pattern[sd->data_offset++];
2079 case 22: /* ACMD22: SEND_NUM_WR_BLOCKS */
2080 ret = sd->data[sd->data_offset ++];
2082 if (sd->data_offset >= 4)
2083 sd->state = sd_transfer_state;
2086 case 30: /* CMD30: SEND_WRITE_PROT */
2087 ret = sd->data[sd->data_offset ++];
2089 if (sd->data_offset >= 4)
2090 sd->state = sd_transfer_state;
2093 case 51: /* ACMD51: SEND_SCR */
2094 ret = sd->scr[sd->data_offset ++];
2096 if (sd->data_offset >= sizeof(sd->scr))
2097 sd->state = sd_transfer_state;
2100 case 56: /* CMD56: GEN_CMD */
2101 if (sd->data_offset == 0)
2102 APP_READ_BLOCK(sd->data_start, sd->blk_len);
2103 ret = sd->data[sd->data_offset ++];
2105 if (sd->data_offset >= sd->blk_len)
2106 sd->state = sd_transfer_state;
2110 qemu_log_mask(LOG_GUEST_ERROR, "%s: unknown command\n", __func__);
2117 static bool sd_receive_ready(SDState *sd)
2119 return sd->state == sd_receivingdata_state;
2122 static bool sd_data_ready(SDState *sd)
2124 return sd->state == sd_sendingdata_state;
2127 void sd_enable(SDState *sd, bool enable)
2129 sd->enable = enable;
2132 static const SDProto sd_proto_spi = {
2135 [2 ... 4] = sd_cmd_illegal,
2136 [5] = sd_cmd_illegal,
2137 [7] = sd_cmd_illegal,
2138 [15] = sd_cmd_illegal,
2139 [26] = sd_cmd_illegal,
2140 [52 ... 54] = sd_cmd_illegal,
2144 static const SDProto sd_proto_sd = {
2147 [1] = sd_cmd_illegal,
2148 [5] = sd_cmd_illegal,
2149 [52 ... 54] = sd_cmd_illegal,
2150 [58] = sd_cmd_illegal,
2151 [59] = sd_cmd_illegal,
2155 static void sd_instance_init(Object *obj)
2157 SDState *sd = SD_CARD(obj);
2160 sd->ocr_power_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, sd_ocr_powerup, sd);
2163 static void sd_instance_finalize(Object *obj)
2165 SDState *sd = SD_CARD(obj);
2167 timer_free(sd->ocr_power_timer);
2170 static void sd_realize(DeviceState *dev, Error **errp)
2172 SDState *sd = SD_CARD(dev);
2173 SDCardClass *sc = SD_CARD_GET_CLASS(sd);
2176 sc->proto = sd->spi ? &sd_proto_spi : &sd_proto_sd;
2178 switch (sd->spec_version) {
2179 case SD_PHY_SPECv1_10_VERS
2180 ... SD_PHY_SPECv3_01_VERS:
2183 error_setg(errp, "Invalid SD card Spec version: %u", sd->spec_version);
2190 if (!blk_supports_write_perm(sd->blk)) {
2191 error_setg(errp, "Cannot use read-only drive as SD card");
2195 blk_size = blk_getlength(sd->blk);
2196 if (blk_size > 0 && !is_power_of_2(blk_size)) {
2197 int64_t blk_size_aligned = pow2ceil(blk_size);
2200 blk_size_str = size_to_str(blk_size);
2201 error_setg(errp, "Invalid SD card size: %s", blk_size_str);
2202 g_free(blk_size_str);
2204 blk_size_str = size_to_str(blk_size_aligned);
2205 error_append_hint(errp,
2206 "SD card size has to be a power of 2, e.g. %s.\n"
2207 "You can resize disk images with"
2208 " 'qemu-img resize <imagefile> <new-size>'\n"
2209 "(note that this will lose data if you make the"
2210 " image smaller than it currently is).\n",
2212 g_free(blk_size_str);
2217 ret = blk_set_perm(sd->blk, BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE,
2218 BLK_PERM_ALL, errp);
2222 blk_set_dev_ops(sd->blk, &sd_block_ops, sd);
2226 static Property sd_properties[] = {
2227 DEFINE_PROP_UINT8("spec_version", SDState,
2228 spec_version, SD_PHY_SPECv2_00_VERS),
2229 DEFINE_PROP_DRIVE("drive", SDState, blk),
2230 /* We do not model the chip select pin, so allow the board to select
2231 * whether card should be in SSI or MMC/SD mode. It is also up to the
2232 * board to ensure that ssi transfers only occur when the chip select
2234 DEFINE_PROP_BOOL("spi", SDState, spi, false),
2235 DEFINE_PROP_END_OF_LIST()
2238 static void sd_class_init(ObjectClass *klass, void *data)
2240 DeviceClass *dc = DEVICE_CLASS(klass);
2241 SDCardClass *sc = SD_CARD_CLASS(klass);
2243 dc->realize = sd_realize;
2244 device_class_set_props(dc, sd_properties);
2245 dc->vmsd = &sd_vmstate;
2246 dc->reset = sd_reset;
2247 dc->bus_type = TYPE_SD_BUS;
2248 set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
2250 sc->set_voltage = sd_set_voltage;
2251 sc->get_dat_lines = sd_get_dat_lines;
2252 sc->get_cmd_line = sd_get_cmd_line;
2253 sc->do_command = sd_do_command;
2254 sc->write_byte = sd_write_byte;
2255 sc->read_byte = sd_read_byte;
2256 sc->receive_ready = sd_receive_ready;
2257 sc->data_ready = sd_data_ready;
2258 sc->enable = sd_enable;
2259 sc->get_inserted = sd_get_inserted;
2260 sc->get_readonly = sd_get_readonly;
2263 static const TypeInfo sd_info = {
2264 .name = TYPE_SD_CARD,
2265 .parent = TYPE_DEVICE,
2266 .instance_size = sizeof(SDState),
2267 .class_size = sizeof(SDCardClass),
2268 .class_init = sd_class_init,
2269 .instance_init = sd_instance_init,
2270 .instance_finalize = sd_instance_finalize,
2273 static void sd_register_types(void)
2275 type_register_static(&sd_info);
2278 type_init(sd_register_types)