hw/sd/sdcard: Restrict SWITCH_FUNCTION to sd_transfer_state (CMD6)
[qemu/armbru.git] / hw / sd / sd.c
blobb5d002e6d712aa303b325c515a8f796620ccff0d
1 /*
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
11 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
18 * distribution.
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"
36 #include "hw/irq.h"
37 #include "hw/registerfields.h"
38 #include "sysemu/block-backend.h"
39 #include "hw/sd/sd.h"
40 #include "hw/sd/sdcard_legacy.h"
41 #include "migration/vmstate.h"
42 #include "qapi/error.h"
43 #include "qemu/bitmap.h"
44 #include "hw/qdev-properties.h"
45 #include "hw/qdev-properties-system.h"
46 #include "qemu/error-report.h"
47 #include "qemu/timer.h"
48 #include "qemu/log.h"
49 #include "qemu/module.h"
50 #include "sdmmc-internal.h"
51 #include "trace.h"
53 //#define DEBUG_SD 1
55 #define SDSC_MAX_CAPACITY (2 * GiB)
57 #define INVALID_ADDRESS UINT32_MAX
59 typedef enum {
60 sd_r0 = 0, /* no response */
61 sd_r1, /* normal response command */
62 sd_r2_i, /* CID register */
63 sd_r2_s, /* CSD register */
64 sd_r3, /* OCR register */
65 sd_r6 = 6, /* Published RCA response */
66 sd_r7, /* Operating voltage */
67 sd_r1b = -1,
68 sd_illegal = -2,
69 } sd_rsp_type_t;
71 enum SDCardModes {
72 sd_inactive,
73 sd_card_identification_mode,
74 sd_data_transfer_mode,
77 enum SDCardStates {
78 sd_inactive_state = -1,
79 sd_idle_state = 0,
80 sd_ready_state,
81 sd_identification_state,
82 sd_standby_state,
83 sd_transfer_state,
84 sd_sendingdata_state,
85 sd_receivingdata_state,
86 sd_programming_state,
87 sd_disconnect_state,
90 typedef sd_rsp_type_t (*sd_cmd_handler)(SDState *sd, SDRequest req);
92 typedef struct SDProto {
93 const char *name;
94 sd_cmd_handler cmd[SDMMC_CMD_MAX];
95 sd_cmd_handler acmd[SDMMC_CMD_MAX];
96 } SDProto;
98 struct SDState {
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 */
106 uint32_t ocr;
107 uint8_t scr[8];
108 uint8_t cid[16];
109 uint8_t csd[16];
110 uint16_t rca;
111 uint32_t card_status;
112 uint8_t sd_status[64];
114 /* Static properties */
116 uint8_t spec_version;
117 BlockBackend *blk;
119 /* Runtime changeables */
121 uint32_t mode; /* current card mode, one of SDCardModes */
122 int32_t state; /* current card state, one of SDCardStates */
123 uint32_t vhs;
124 bool wp_switch;
125 unsigned long *wp_group_bmap;
126 int32_t wp_group_bits;
127 uint64_t size;
128 uint32_t blk_len;
129 uint32_t multi_blk_cnt;
130 uint32_t erase_start;
131 uint32_t erase_end;
132 uint8_t pwd[16];
133 uint32_t pwd_len;
134 uint8_t function_group[6];
135 uint8_t current_cmd;
136 const char *last_cmd_name;
137 /* True if we will handle the next command as an ACMD. Note that this does
138 * *not* track the APP_CMD status bit!
140 bool expecting_acmd;
141 uint32_t blk_written;
142 uint64_t data_start;
143 uint32_t data_offset;
144 uint8_t data[512];
145 qemu_irq readonly_cb;
146 qemu_irq inserted_cb;
147 QEMUTimer *ocr_power_timer;
148 bool enable;
149 uint8_t dat_lines;
150 bool cmd_line;
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);
159 return sc->proto;
162 static const SDProto sd_proto_spi;
164 static bool sd_is_spi(SDState *sd)
166 return sd_proto(sd) == &sd_proto_spi;
169 static const char *sd_version_str(enum SDPhySpecificationVersion version)
171 static const char *sdphy_version[] = {
172 [SD_PHY_SPECv1_10_VERS] = "v1.10",
173 [SD_PHY_SPECv2_00_VERS] = "v2.00",
174 [SD_PHY_SPECv3_01_VERS] = "v3.01",
176 if (version >= ARRAY_SIZE(sdphy_version)) {
177 return "unsupported version";
179 return sdphy_version[version];
182 static const char *sd_mode_name(enum SDCardModes mode)
184 static const char *mode_name[] = {
185 [sd_inactive] = "inactive",
186 [sd_card_identification_mode] = "identification",
187 [sd_data_transfer_mode] = "transfer",
189 assert(mode < ARRAY_SIZE(mode_name));
190 return mode_name[mode];
193 static const char *sd_state_name(enum SDCardStates state)
195 static const char *state_name[] = {
196 [sd_idle_state] = "idle",
197 [sd_ready_state] = "ready",
198 [sd_identification_state] = "identification",
199 [sd_standby_state] = "standby",
200 [sd_transfer_state] = "transfer",
201 [sd_sendingdata_state] = "sendingdata",
202 [sd_receivingdata_state] = "receivingdata",
203 [sd_programming_state] = "programming",
204 [sd_disconnect_state] = "disconnect",
206 if (state == sd_inactive_state) {
207 return "inactive";
209 assert(state < ARRAY_SIZE(state_name));
210 return state_name[state];
213 static const char *sd_response_name(sd_rsp_type_t rsp)
215 static const char *response_name[] = {
216 [sd_r0] = "RESP#0 (no response)",
217 [sd_r1] = "RESP#1 (normal cmd)",
218 [sd_r2_i] = "RESP#2 (CID reg)",
219 [sd_r2_s] = "RESP#2 (CSD reg)",
220 [sd_r3] = "RESP#3 (OCR reg)",
221 [sd_r6] = "RESP#6 (RCA)",
222 [sd_r7] = "RESP#7 (operating voltage)",
224 if (rsp == sd_illegal) {
225 return "ILLEGAL RESP";
227 if (rsp == sd_r1b) {
228 rsp = sd_r1;
230 assert(rsp < ARRAY_SIZE(response_name));
231 return response_name[rsp];
234 static uint8_t sd_get_dat_lines(SDState *sd)
236 return sd->enable ? sd->dat_lines : 0;
239 static bool sd_get_cmd_line(SDState *sd)
241 return sd->enable ? sd->cmd_line : false;
244 static void sd_set_voltage(SDState *sd, uint16_t millivolts)
246 trace_sdcard_set_voltage(millivolts);
248 switch (millivolts) {
249 case 3001 ... 3600: /* SD_VOLTAGE_3_3V */
250 case 2001 ... 3000: /* SD_VOLTAGE_3_0V */
251 break;
252 default:
253 qemu_log_mask(LOG_GUEST_ERROR, "SD card voltage not supported: %.3fV",
254 millivolts / 1000.f);
258 static void sd_set_mode(SDState *sd)
260 switch (sd->state) {
261 case sd_inactive_state:
262 sd->mode = sd_inactive;
263 break;
265 case sd_idle_state:
266 case sd_ready_state:
267 case sd_identification_state:
268 sd->mode = sd_card_identification_mode;
269 break;
271 case sd_standby_state:
272 case sd_transfer_state:
273 case sd_sendingdata_state:
274 case sd_receivingdata_state:
275 case sd_programming_state:
276 case sd_disconnect_state:
277 sd->mode = sd_data_transfer_mode;
278 break;
282 static const sd_cmd_type_t sd_cmd_type[SDMMC_CMD_MAX] = {
283 sd_bc, sd_none, sd_bcr, sd_bcr, sd_none, sd_none, sd_none, sd_ac,
284 sd_bcr, sd_ac, sd_ac, sd_adtc, sd_ac, sd_ac, sd_none, sd_ac,
285 /* 16 */
286 sd_ac, sd_adtc, sd_adtc, sd_none, sd_none, sd_none, sd_none, sd_none,
287 sd_adtc, sd_adtc, sd_adtc, sd_adtc, sd_ac, sd_ac, sd_adtc, sd_none,
288 /* 32 */
289 sd_ac, sd_ac, sd_none, sd_none, sd_none, sd_none, sd_ac, sd_none,
290 sd_none, sd_none, sd_bc, sd_none, sd_none, sd_none, sd_none, sd_none,
291 /* 48 */
292 sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, sd_ac,
293 sd_adtc, sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, sd_none,
296 static const int sd_cmd_class[SDMMC_CMD_MAX] = {
297 0, 0, 0, 0, 0, 9, 10, 0, 0, 0, 0, 1, 0, 0, 0, 0,
298 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 6, 6, 6, 6,
299 5, 5, 10, 10, 10, 10, 5, 9, 9, 9, 7, 7, 7, 7, 7, 7,
300 7, 7, 10, 7, 9, 9, 9, 8, 8, 10, 8, 8, 8, 8, 8, 8,
303 static uint8_t sd_crc7(const void *message, size_t width)
305 int i, bit;
306 uint8_t shift_reg = 0x00;
307 const uint8_t *msg = (const uint8_t *)message;
309 for (i = 0; i < width; i ++, msg ++)
310 for (bit = 7; bit >= 0; bit --) {
311 shift_reg <<= 1;
312 if ((shift_reg >> 7) ^ ((*msg >> bit) & 1))
313 shift_reg ^= 0x89;
316 return shift_reg;
319 /* Operation Conditions register */
321 #define OCR_POWER_DELAY_NS 500000 /* 0.5ms */
323 FIELD(OCR, VDD_VOLTAGE_WINDOW, 0, 24)
324 FIELD(OCR, VDD_VOLTAGE_WIN_LO, 0, 8)
325 FIELD(OCR, DUAL_VOLTAGE_CARD, 7, 1)
326 FIELD(OCR, VDD_VOLTAGE_WIN_HI, 8, 16)
327 FIELD(OCR, ACCEPT_SWITCH_1V8, 24, 1) /* Only UHS-I */
328 FIELD(OCR, UHS_II_CARD, 29, 1) /* Only UHS-II */
329 FIELD(OCR, CARD_CAPACITY, 30, 1) /* 0:SDSC, 1:SDHC/SDXC */
330 FIELD(OCR, CARD_POWER_UP, 31, 1)
332 #define ACMD41_ENQUIRY_MASK 0x00ffffff
333 #define ACMD41_R3_MASK (R_OCR_VDD_VOLTAGE_WIN_HI_MASK \
334 | R_OCR_ACCEPT_SWITCH_1V8_MASK \
335 | R_OCR_UHS_II_CARD_MASK \
336 | R_OCR_CARD_CAPACITY_MASK \
337 | R_OCR_CARD_POWER_UP_MASK)
339 static void sd_ocr_powerup(void *opaque)
341 SDState *sd = opaque;
343 trace_sdcard_powerup();
344 assert(!FIELD_EX32(sd->ocr, OCR, CARD_POWER_UP));
346 /* card power-up OK */
347 sd->ocr = FIELD_DP32(sd->ocr, OCR, CARD_POWER_UP, 1);
349 if (sd->size > SDSC_MAX_CAPACITY) {
350 sd->ocr = FIELD_DP32(sd->ocr, OCR, CARD_CAPACITY, 1);
354 static void sd_set_ocr(SDState *sd)
356 /* All voltages OK */
357 sd->ocr = R_OCR_VDD_VOLTAGE_WIN_HI_MASK;
359 if (sd_is_spi(sd)) {
361 * We don't need to emulate power up sequence in SPI-mode.
362 * Thus, the card's power up status bit should be set to 1 when reset.
363 * The card's capacity status bit should also be set if SD card size
364 * is larger than 2GB for SDHC support.
366 sd_ocr_powerup(sd);
370 /* SD Configuration register */
372 static void sd_set_scr(SDState *sd)
374 sd->scr[0] = 0 << 4; /* SCR structure version 1.0 */
375 if (sd->spec_version == SD_PHY_SPECv1_10_VERS) {
376 sd->scr[0] |= 1; /* Spec Version 1.10 */
377 } else {
378 sd->scr[0] |= 2; /* Spec Version 2.00 or Version 3.0X */
380 sd->scr[1] = (2 << 4) /* SDSC Card (Security Version 1.01) */
381 | 0b0101; /* 1-bit or 4-bit width bus modes */
382 sd->scr[2] = 0x00; /* Extended Security is not supported. */
383 if (sd->spec_version >= SD_PHY_SPECv3_01_VERS) {
384 sd->scr[2] |= 1 << 7; /* Spec Version 3.0X */
386 sd->scr[3] = 0x00;
387 /* reserved for manufacturer usage */
388 sd->scr[4] = 0x00;
389 sd->scr[5] = 0x00;
390 sd->scr[6] = 0x00;
391 sd->scr[7] = 0x00;
394 /* Card IDentification register */
396 #define MID 0xaa
397 #define OID "XY"
398 #define PNM "QEMU!"
399 #define PRV 0x01
400 #define MDT_YR 2006
401 #define MDT_MON 2
403 static void sd_set_cid(SDState *sd)
405 sd->cid[0] = MID; /* Fake card manufacturer ID (MID) */
406 sd->cid[1] = OID[0]; /* OEM/Application ID (OID) */
407 sd->cid[2] = OID[1];
408 sd->cid[3] = PNM[0]; /* Fake product name (PNM) */
409 sd->cid[4] = PNM[1];
410 sd->cid[5] = PNM[2];
411 sd->cid[6] = PNM[3];
412 sd->cid[7] = PNM[4];
413 sd->cid[8] = PRV; /* Fake product revision (PRV) */
414 stl_be_p(&sd->cid[9], 0xdeadbeef); /* Fake serial number (PSN) */
415 sd->cid[13] = 0x00 | /* Manufacture date (MDT) */
416 ((MDT_YR - 2000) / 10);
417 sd->cid[14] = ((MDT_YR % 10) << 4) | MDT_MON;
418 sd->cid[15] = (sd_crc7(sd->cid, 15) << 1) | 1;
421 /* Card-Specific Data register */
423 #define HWBLOCK_SHIFT 9 /* 512 bytes */
424 #define SECTOR_SHIFT 5 /* 16 kilobytes */
425 #define WPGROUP_SHIFT 7 /* 2 megs */
426 #define CMULT_SHIFT 9 /* 512 times HWBLOCK_SIZE */
427 #define WPGROUP_SIZE (1 << (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT))
429 static const uint8_t sd_csd_rw_mask[16] = {
430 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
431 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xfe,
434 static void sd_set_csd(SDState *sd, uint64_t size)
436 int hwblock_shift = HWBLOCK_SHIFT;
437 uint32_t csize;
438 uint32_t sectsize = (1 << (SECTOR_SHIFT + 1)) - 1;
439 uint32_t wpsize = (1 << (WPGROUP_SHIFT + 1)) - 1;
441 /* To indicate 2 GiB card, BLOCK_LEN shall be 1024 bytes */
442 if (size == SDSC_MAX_CAPACITY) {
443 hwblock_shift += 1;
445 csize = (size >> (CMULT_SHIFT + hwblock_shift)) - 1;
447 if (size <= SDSC_MAX_CAPACITY) { /* Standard Capacity SD */
448 sd->csd[0] = 0x00; /* CSD structure */
449 sd->csd[1] = 0x26; /* Data read access-time-1 */
450 sd->csd[2] = 0x00; /* Data read access-time-2 */
451 sd->csd[3] = 0x32; /* Max. data transfer rate: 25 MHz */
452 sd->csd[4] = 0x5f; /* Card Command Classes */
453 sd->csd[5] = 0x50 | /* Max. read data block length */
454 hwblock_shift;
455 sd->csd[6] = 0xe0 | /* Partial block for read allowed */
456 ((csize >> 10) & 0x03);
457 sd->csd[7] = 0x00 | /* Device size */
458 ((csize >> 2) & 0xff);
459 sd->csd[8] = 0x3f | /* Max. read current */
460 ((csize << 6) & 0xc0);
461 sd->csd[9] = 0xfc | /* Max. write current */
462 ((CMULT_SHIFT - 2) >> 1);
463 sd->csd[10] = 0x40 | /* Erase sector size */
464 (((CMULT_SHIFT - 2) << 7) & 0x80) | (sectsize >> 1);
465 sd->csd[11] = 0x00 | /* Write protect group size */
466 ((sectsize << 7) & 0x80) | wpsize;
467 sd->csd[12] = 0x90 | /* Write speed factor */
468 (hwblock_shift >> 2);
469 sd->csd[13] = 0x20 | /* Max. write data block length */
470 ((hwblock_shift << 6) & 0xc0);
471 sd->csd[14] = 0x00; /* File format group */
472 } else { /* SDHC */
473 size /= 512 * KiB;
474 size -= 1;
475 sd->csd[0] = 0x40;
476 sd->csd[1] = 0x0e;
477 sd->csd[2] = 0x00;
478 sd->csd[3] = 0x32;
479 sd->csd[4] = 0x5b;
480 sd->csd[5] = 0x59;
481 sd->csd[6] = 0x00;
482 st24_be_p(&sd->csd[7], size);
483 sd->csd[10] = 0x7f;
484 sd->csd[11] = 0x80;
485 sd->csd[12] = 0x0a;
486 sd->csd[13] = 0x40;
487 sd->csd[14] = 0x00;
489 sd->csd[15] = (sd_crc7(sd->csd, 15) << 1) | 1;
492 /* Relative Card Address register */
494 static void sd_set_rca(SDState *sd)
496 sd->rca += 0x4567;
499 static uint16_t sd_req_get_rca(SDState *s, SDRequest req)
501 if (sd_cmd_type[req.cmd] == sd_ac || sd_cmd_type[req.cmd] == sd_adtc) {
502 return req.arg >> 16;
504 return 0;
507 /* Card Status register */
509 FIELD(CSR, AKE_SEQ_ERROR, 3, 1)
510 FIELD(CSR, APP_CMD, 5, 1)
511 FIELD(CSR, FX_EVENT, 6, 1)
512 FIELD(CSR, READY_FOR_DATA, 8, 1)
513 FIELD(CSR, CURRENT_STATE, 9, 4)
514 FIELD(CSR, ERASE_RESET, 13, 1)
515 FIELD(CSR, CARD_ECC_DISABLED, 14, 1)
516 FIELD(CSR, WP_ERASE_SKIP, 15, 1)
517 FIELD(CSR, CSD_OVERWRITE, 16, 1)
518 FIELD(CSR, DEFERRED_RESPONSE, 17, 1)
519 FIELD(CSR, ERROR, 19, 1)
520 FIELD(CSR, CC_ERROR, 20, 1)
521 FIELD(CSR, CARD_ECC_FAILED, 21, 1)
522 FIELD(CSR, ILLEGAL_COMMAND, 22, 1)
523 FIELD(CSR, COM_CRC_ERROR, 23, 1)
524 FIELD(CSR, LOCK_UNLOCK_FAILED, 24, 1)
525 FIELD(CSR, CARD_IS_LOCKED, 25, 1)
526 FIELD(CSR, WP_VIOLATION, 26, 1)
527 FIELD(CSR, ERASE_PARAM, 27, 1)
528 FIELD(CSR, ERASE_SEQ_ERROR, 28, 1)
529 FIELD(CSR, BLOCK_LEN_ERROR, 29, 1)
530 FIELD(CSR, ADDRESS_ERROR, 30, 1)
531 FIELD(CSR, OUT_OF_RANGE, 31, 1)
533 /* Card status bits, split by clear condition:
534 * A : According to the card current state
535 * B : Always related to the previous command
536 * C : Cleared by read
538 #define CARD_STATUS_A (R_CSR_READY_FOR_DATA_MASK \
539 | R_CSR_CARD_ECC_DISABLED_MASK \
540 | R_CSR_CARD_IS_LOCKED_MASK)
541 #define CARD_STATUS_B (R_CSR_CURRENT_STATE_MASK \
542 | R_CSR_ILLEGAL_COMMAND_MASK \
543 | R_CSR_COM_CRC_ERROR_MASK)
544 #define CARD_STATUS_C (R_CSR_AKE_SEQ_ERROR_MASK \
545 | R_CSR_APP_CMD_MASK \
546 | R_CSR_ERASE_RESET_MASK \
547 | R_CSR_WP_ERASE_SKIP_MASK \
548 | R_CSR_CSD_OVERWRITE_MASK \
549 | R_CSR_ERROR_MASK \
550 | R_CSR_CC_ERROR_MASK \
551 | R_CSR_CARD_ECC_FAILED_MASK \
552 | R_CSR_LOCK_UNLOCK_FAILED_MASK \
553 | R_CSR_WP_VIOLATION_MASK \
554 | R_CSR_ERASE_PARAM_MASK \
555 | R_CSR_ERASE_SEQ_ERROR_MASK \
556 | R_CSR_BLOCK_LEN_ERROR_MASK \
557 | R_CSR_ADDRESS_ERROR_MASK \
558 | R_CSR_OUT_OF_RANGE_MASK)
560 static void sd_set_cardstatus(SDState *sd)
562 sd->card_status = 0x00000100;
565 static void sd_set_sdstatus(SDState *sd)
567 memset(sd->sd_status, 0, 64);
570 static int sd_req_crc_validate(SDRequest *req)
572 uint8_t buffer[5];
573 buffer[0] = 0x40 | req->cmd;
574 stl_be_p(&buffer[1], req->arg);
575 return 0;
576 return sd_crc7(buffer, 5) != req->crc; /* TODO */
579 static void sd_response_r1_make(SDState *sd, uint8_t *response)
581 stl_be_p(response, sd->card_status);
583 /* Clear the "clear on read" status bits */
584 sd->card_status &= ~CARD_STATUS_C;
587 static void sd_response_r3_make(SDState *sd, uint8_t *response)
589 stl_be_p(response, sd->ocr & ACMD41_R3_MASK);
592 static void sd_response_r6_make(SDState *sd, uint8_t *response)
594 uint16_t status;
596 status = ((sd->card_status >> 8) & 0xc000) |
597 ((sd->card_status >> 6) & 0x2000) |
598 (sd->card_status & 0x1fff);
599 sd->card_status &= ~(CARD_STATUS_C & 0xc81fff);
600 stw_be_p(response + 0, sd->rca);
601 stw_be_p(response + 2, status);
604 static void sd_response_r7_make(SDState *sd, uint8_t *response)
606 stl_be_p(response, sd->vhs);
609 static uint64_t sd_req_get_address(SDState *sd, SDRequest req)
611 uint64_t addr;
613 if (FIELD_EX32(sd->ocr, OCR, CARD_CAPACITY)) {
614 addr = (uint64_t) req.arg << HWBLOCK_SHIFT;
615 } else {
616 addr = req.arg;
618 trace_sdcard_req_addr(req.arg, addr);
619 return addr;
622 static inline uint64_t sd_addr_to_wpnum(uint64_t addr)
624 return addr >> (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT);
627 static void sd_reset(DeviceState *dev)
629 SDState *sd = SD_CARD(dev);
630 uint64_t size;
631 uint64_t sect;
633 trace_sdcard_reset();
634 if (sd->blk) {
635 blk_get_geometry(sd->blk, &sect);
636 } else {
637 sect = 0;
639 size = sect << HWBLOCK_SHIFT;
641 sect = sd_addr_to_wpnum(size) + 1;
643 sd->state = sd_idle_state;
645 /* card registers */
646 sd->rca = 0x0000;
647 sd->size = size;
648 sd_set_ocr(sd);
649 sd_set_scr(sd);
650 sd_set_cid(sd);
651 sd_set_csd(sd, size);
652 sd_set_cardstatus(sd);
653 sd_set_sdstatus(sd);
655 g_free(sd->wp_group_bmap);
656 sd->wp_switch = sd->blk ? !blk_is_writable(sd->blk) : false;
657 sd->wp_group_bits = sect;
658 sd->wp_group_bmap = bitmap_new(sd->wp_group_bits);
659 memset(sd->function_group, 0, sizeof(sd->function_group));
660 sd->erase_start = INVALID_ADDRESS;
661 sd->erase_end = INVALID_ADDRESS;
662 sd->blk_len = 0x200;
663 sd->pwd_len = 0;
664 sd->expecting_acmd = false;
665 sd->dat_lines = 0xf;
666 sd->cmd_line = true;
667 sd->multi_blk_cnt = 0;
670 static bool sd_get_inserted(SDState *sd)
672 return sd->blk && blk_is_inserted(sd->blk);
675 static bool sd_get_readonly(SDState *sd)
677 return sd->wp_switch;
680 static void sd_cardchange(void *opaque, bool load, Error **errp)
682 SDState *sd = opaque;
683 DeviceState *dev = DEVICE(sd);
684 SDBus *sdbus;
685 bool inserted = sd_get_inserted(sd);
686 bool readonly = sd_get_readonly(sd);
688 if (inserted) {
689 trace_sdcard_inserted(readonly);
690 sd_reset(dev);
691 } else {
692 trace_sdcard_ejected();
695 if (sd->me_no_qdev_me_kill_mammoth_with_rocks) {
696 qemu_set_irq(sd->inserted_cb, inserted);
697 if (inserted) {
698 qemu_set_irq(sd->readonly_cb, readonly);
700 } else {
701 sdbus = SD_BUS(qdev_get_parent_bus(dev));
702 sdbus_set_inserted(sdbus, inserted);
703 if (inserted) {
704 sdbus_set_readonly(sdbus, readonly);
709 static const BlockDevOps sd_block_ops = {
710 .change_media_cb = sd_cardchange,
713 static bool sd_ocr_vmstate_needed(void *opaque)
715 SDState *sd = opaque;
717 /* Include the OCR state (and timer) if it is not yet powered up */
718 return !FIELD_EX32(sd->ocr, OCR, CARD_POWER_UP);
721 static const VMStateDescription sd_ocr_vmstate = {
722 .name = "sd-card/ocr-state",
723 .version_id = 1,
724 .minimum_version_id = 1,
725 .needed = sd_ocr_vmstate_needed,
726 .fields = (const VMStateField[]) {
727 VMSTATE_UINT32(ocr, SDState),
728 VMSTATE_TIMER_PTR(ocr_power_timer, SDState),
729 VMSTATE_END_OF_LIST()
733 static int sd_vmstate_pre_load(void *opaque)
735 SDState *sd = opaque;
737 /* If the OCR state is not included (prior versions, or not
738 * needed), then the OCR must be set as powered up. If the OCR state
739 * is included, this will be replaced by the state restore.
741 sd_ocr_powerup(sd);
743 return 0;
746 static const VMStateDescription sd_vmstate = {
747 .name = "sd-card",
748 .version_id = 2,
749 .minimum_version_id = 2,
750 .pre_load = sd_vmstate_pre_load,
751 .fields = (const VMStateField[]) {
752 VMSTATE_UINT32(mode, SDState),
753 VMSTATE_INT32(state, SDState),
754 VMSTATE_UINT8_ARRAY(cid, SDState, 16),
755 VMSTATE_UINT8_ARRAY(csd, SDState, 16),
756 VMSTATE_UINT16(rca, SDState),
757 VMSTATE_UINT32(card_status, SDState),
758 VMSTATE_PARTIAL_BUFFER(sd_status, SDState, 1),
759 VMSTATE_UINT32(vhs, SDState),
760 VMSTATE_BITMAP(wp_group_bmap, SDState, 0, wp_group_bits),
761 VMSTATE_UINT32(blk_len, SDState),
762 VMSTATE_UINT32(multi_blk_cnt, SDState),
763 VMSTATE_UINT32(erase_start, SDState),
764 VMSTATE_UINT32(erase_end, SDState),
765 VMSTATE_UINT8_ARRAY(pwd, SDState, 16),
766 VMSTATE_UINT32(pwd_len, SDState),
767 VMSTATE_UINT8_ARRAY(function_group, SDState, 6),
768 VMSTATE_UINT8(current_cmd, SDState),
769 VMSTATE_BOOL(expecting_acmd, SDState),
770 VMSTATE_UINT32(blk_written, SDState),
771 VMSTATE_UINT64(data_start, SDState),
772 VMSTATE_UINT32(data_offset, SDState),
773 VMSTATE_UINT8_ARRAY(data, SDState, 512),
774 VMSTATE_UNUSED_V(1, 512),
775 VMSTATE_BOOL(enable, SDState),
776 VMSTATE_END_OF_LIST()
778 .subsections = (const VMStateDescription * const []) {
779 &sd_ocr_vmstate,
780 NULL
784 /* Legacy initialization function for use by non-qdevified callers */
785 SDState *sd_init(BlockBackend *blk, bool is_spi)
787 Object *obj;
788 DeviceState *dev;
789 SDState *sd;
790 Error *err = NULL;
792 obj = object_new(is_spi ? TYPE_SD_CARD_SPI : TYPE_SD_CARD);
793 dev = DEVICE(obj);
794 if (!qdev_prop_set_drive_err(dev, "drive", blk, &err)) {
795 error_reportf_err(err, "sd_init failed: ");
796 return NULL;
800 * Realizing the device properly would put it into the QOM
801 * composition tree even though it is not plugged into an
802 * appropriate bus. That's a no-no. Hide the device from
803 * QOM/qdev, and call its qdev realize callback directly.
805 object_ref(obj);
806 object_unparent(obj);
807 sd_realize(dev, &err);
808 if (err) {
809 error_reportf_err(err, "sd_init failed: ");
810 return NULL;
813 sd = SD_CARD(dev);
814 sd->me_no_qdev_me_kill_mammoth_with_rocks = true;
815 return sd;
818 void sd_set_cb(SDState *sd, qemu_irq readonly, qemu_irq insert)
820 sd->readonly_cb = readonly;
821 sd->inserted_cb = insert;
822 qemu_set_irq(readonly, sd->blk ? !blk_is_writable(sd->blk) : 0);
823 qemu_set_irq(insert, sd->blk ? blk_is_inserted(sd->blk) : 0);
826 static void sd_blk_read(SDState *sd, uint64_t addr, uint32_t len)
828 trace_sdcard_read_block(addr, len);
829 if (!sd->blk || blk_pread(sd->blk, addr, len, sd->data, 0) < 0) {
830 fprintf(stderr, "sd_blk_read: read error on host side\n");
834 static void sd_blk_write(SDState *sd, uint64_t addr, uint32_t len)
836 trace_sdcard_write_block(addr, len);
837 if (!sd->blk || blk_pwrite(sd->blk, addr, len, sd->data, 0) < 0) {
838 fprintf(stderr, "sd_blk_write: write error on host side\n");
842 #define APP_READ_BLOCK(a, len) memset(sd->data, 0xec, len)
843 #define APP_WRITE_BLOCK(a, len)
845 static void sd_erase(SDState *sd)
847 uint64_t erase_start = sd->erase_start;
848 uint64_t erase_end = sd->erase_end;
849 bool sdsc = true;
850 uint64_t wpnum;
851 uint64_t erase_addr;
852 int erase_len = 1 << HWBLOCK_SHIFT;
854 trace_sdcard_erase(sd->erase_start, sd->erase_end);
855 if (sd->erase_start == INVALID_ADDRESS
856 || sd->erase_end == INVALID_ADDRESS) {
857 sd->card_status |= ERASE_SEQ_ERROR;
858 sd->erase_start = INVALID_ADDRESS;
859 sd->erase_end = INVALID_ADDRESS;
860 return;
863 if (FIELD_EX32(sd->ocr, OCR, CARD_CAPACITY)) {
864 /* High capacity memory card: erase units are 512 byte blocks */
865 erase_start <<= HWBLOCK_SHIFT;
866 erase_end <<= HWBLOCK_SHIFT;
867 sdsc = false;
870 if (erase_start > sd->size || erase_end > sd->size) {
871 sd->card_status |= OUT_OF_RANGE;
872 sd->erase_start = INVALID_ADDRESS;
873 sd->erase_end = INVALID_ADDRESS;
874 return;
877 sd->erase_start = INVALID_ADDRESS;
878 sd->erase_end = INVALID_ADDRESS;
879 sd->csd[14] |= 0x40;
881 memset(sd->data, 0xff, erase_len);
882 for (erase_addr = erase_start; erase_addr <= erase_end;
883 erase_addr += erase_len) {
884 if (sdsc) {
885 /* Only SDSC cards support write protect groups */
886 wpnum = sd_addr_to_wpnum(erase_addr);
887 assert(wpnum < sd->wp_group_bits);
888 if (test_bit(wpnum, sd->wp_group_bmap)) {
889 sd->card_status |= WP_ERASE_SKIP;
890 continue;
893 sd_blk_write(sd, erase_addr, erase_len);
897 static uint32_t sd_wpbits(SDState *sd, uint64_t addr)
899 uint32_t i, wpnum;
900 uint32_t ret = 0;
902 wpnum = sd_addr_to_wpnum(addr);
904 for (i = 0; i < 32; i++, wpnum++, addr += WPGROUP_SIZE) {
905 if (addr >= sd->size) {
907 * If the addresses of the last groups are outside the valid range,
908 * then the corresponding write protection bits shall be set to 0.
910 continue;
912 assert(wpnum < sd->wp_group_bits);
913 if (test_bit(wpnum, sd->wp_group_bmap)) {
914 ret |= (1 << i);
918 return ret;
921 static void sd_function_switch(SDState *sd, uint32_t arg)
923 int i, mode, new_func;
924 mode = !!(arg & 0x80000000);
926 sd->data[0] = 0x00; /* Maximum current consumption */
927 sd->data[1] = 0x01;
928 sd->data[2] = 0x80; /* Supported group 6 functions */
929 sd->data[3] = 0x01;
930 sd->data[4] = 0x80; /* Supported group 5 functions */
931 sd->data[5] = 0x01;
932 sd->data[6] = 0x80; /* Supported group 4 functions */
933 sd->data[7] = 0x01;
934 sd->data[8] = 0x80; /* Supported group 3 functions */
935 sd->data[9] = 0x01;
936 sd->data[10] = 0x80; /* Supported group 2 functions */
937 sd->data[11] = 0x43;
938 sd->data[12] = 0x80; /* Supported group 1 functions */
939 sd->data[13] = 0x03;
941 memset(&sd->data[14], 0, 3);
942 for (i = 0; i < 6; i ++) {
943 new_func = (arg >> (i * 4)) & 0x0f;
944 if (mode && new_func != 0x0f)
945 sd->function_group[i] = new_func;
946 sd->data[16 - (i >> 1)] |= new_func << ((i % 2) * 4);
948 memset(&sd->data[17], 0, 47);
951 static inline bool sd_wp_addr(SDState *sd, uint64_t addr)
953 return test_bit(sd_addr_to_wpnum(addr), sd->wp_group_bmap);
956 static void sd_lock_command(SDState *sd)
958 int erase, lock, clr_pwd, set_pwd, pwd_len;
959 erase = !!(sd->data[0] & 0x08);
960 lock = sd->data[0] & 0x04;
961 clr_pwd = sd->data[0] & 0x02;
962 set_pwd = sd->data[0] & 0x01;
964 if (sd->blk_len > 1)
965 pwd_len = sd->data[1];
966 else
967 pwd_len = 0;
969 if (lock) {
970 trace_sdcard_lock();
971 } else {
972 trace_sdcard_unlock();
974 if (erase) {
975 if (!(sd->card_status & CARD_IS_LOCKED) || sd->blk_len > 1 ||
976 set_pwd || clr_pwd || lock || sd->wp_switch ||
977 (sd->csd[14] & 0x20)) {
978 sd->card_status |= LOCK_UNLOCK_FAILED;
979 return;
981 bitmap_zero(sd->wp_group_bmap, sd->wp_group_bits);
982 sd->csd[14] &= ~0x10;
983 sd->card_status &= ~CARD_IS_LOCKED;
984 sd->pwd_len = 0;
985 /* Erasing the entire card here! */
986 fprintf(stderr, "SD: Card force-erased by CMD42\n");
987 return;
990 if (sd->blk_len < 2 + pwd_len ||
991 pwd_len <= sd->pwd_len ||
992 pwd_len > sd->pwd_len + 16) {
993 sd->card_status |= LOCK_UNLOCK_FAILED;
994 return;
997 if (sd->pwd_len && memcmp(sd->pwd, sd->data + 2, sd->pwd_len)) {
998 sd->card_status |= LOCK_UNLOCK_FAILED;
999 return;
1002 pwd_len -= sd->pwd_len;
1003 if ((pwd_len && !set_pwd) ||
1004 (clr_pwd && (set_pwd || lock)) ||
1005 (lock && !sd->pwd_len && !set_pwd) ||
1006 (!set_pwd && !clr_pwd &&
1007 (((sd->card_status & CARD_IS_LOCKED) && lock) ||
1008 (!(sd->card_status & CARD_IS_LOCKED) && !lock)))) {
1009 sd->card_status |= LOCK_UNLOCK_FAILED;
1010 return;
1013 if (set_pwd) {
1014 memcpy(sd->pwd, sd->data + 2 + sd->pwd_len, pwd_len);
1015 sd->pwd_len = pwd_len;
1018 if (clr_pwd) {
1019 sd->pwd_len = 0;
1022 if (lock)
1023 sd->card_status |= CARD_IS_LOCKED;
1024 else
1025 sd->card_status &= ~CARD_IS_LOCKED;
1028 static bool address_in_range(SDState *sd, const char *desc,
1029 uint64_t addr, uint32_t length)
1031 if (addr + length > sd->size) {
1032 qemu_log_mask(LOG_GUEST_ERROR,
1033 "%s offset %"PRIu64" > card %"PRIu64" [%%%u]\n",
1034 desc, addr, sd->size, length);
1035 sd->card_status |= ADDRESS_ERROR;
1036 return false;
1038 return true;
1041 static sd_rsp_type_t sd_invalid_state_for_cmd(SDState *sd, SDRequest req)
1043 qemu_log_mask(LOG_GUEST_ERROR, "%s: CMD%i in a wrong state: %s (spec %s)\n",
1044 sd_proto(sd)->name, req.cmd, sd_state_name(sd->state),
1045 sd_version_str(sd->spec_version));
1047 return sd_illegal;
1050 static sd_rsp_type_t sd_invalid_mode_for_cmd(SDState *sd, SDRequest req)
1052 qemu_log_mask(LOG_GUEST_ERROR, "%s: CMD%i in a wrong mode: %s (spec %s)\n",
1053 sd_proto(sd)->name, req.cmd, sd_mode_name(sd->mode),
1054 sd_version_str(sd->spec_version));
1056 return sd_illegal;
1059 static sd_rsp_type_t sd_cmd_illegal(SDState *sd, SDRequest req)
1061 qemu_log_mask(LOG_GUEST_ERROR, "%s: Unknown CMD%i for spec %s\n",
1062 sd_proto(sd)->name, req.cmd,
1063 sd_version_str(sd->spec_version));
1065 return sd_illegal;
1068 /* Commands that are recognised but not yet implemented. */
1069 __attribute__((unused))
1070 static sd_rsp_type_t sd_cmd_unimplemented(SDState *sd, SDRequest req)
1072 qemu_log_mask(LOG_UNIMP, "%s: CMD%i not implemented\n",
1073 sd_proto(sd)->name, req.cmd);
1075 return sd_illegal;
1078 /* CMD0 */
1079 static sd_rsp_type_t sd_cmd_GO_IDLE_STATE(SDState *sd, SDRequest req)
1081 if (sd->state != sd_inactive_state) {
1082 sd->state = sd_idle_state;
1083 sd_reset(DEVICE(sd));
1086 return sd_is_spi(sd) ? sd_r1 : sd_r0;
1089 /* CMD1 */
1090 static sd_rsp_type_t spi_cmd_SEND_OP_COND(SDState *sd, SDRequest req)
1092 sd->state = sd_transfer_state;
1094 return sd_r1;
1097 /* CMD2 */
1098 static sd_rsp_type_t sd_cmd_ALL_SEND_CID(SDState *sd, SDRequest req)
1100 switch (sd->state) {
1101 case sd_ready_state:
1102 sd->state = sd_identification_state;
1103 return sd_r2_i;
1104 default:
1105 return sd_invalid_state_for_cmd(sd, req);
1109 /* CMD3 */
1110 static sd_rsp_type_t sd_cmd_SEND_RELATIVE_ADDR(SDState *sd, SDRequest req)
1112 switch (sd->state) {
1113 case sd_identification_state:
1114 case sd_standby_state:
1115 sd->state = sd_standby_state;
1116 sd_set_rca(sd);
1117 return sd_r6;
1119 default:
1120 return sd_invalid_state_for_cmd(sd, req);
1124 /* CMD19 */
1125 static sd_rsp_type_t sd_cmd_SEND_TUNING_BLOCK(SDState *sd, SDRequest req)
1127 if (sd->spec_version < SD_PHY_SPECv3_01_VERS) {
1128 return sd_cmd_illegal(sd, req);
1131 if (sd->state != sd_transfer_state) {
1132 return sd_invalid_state_for_cmd(sd, req);
1135 sd->state = sd_sendingdata_state;
1136 sd->data_offset = 0;
1138 return sd_r1;
1141 /* CMD23 */
1142 static sd_rsp_type_t sd_cmd_SET_BLOCK_COUNT(SDState *sd, SDRequest req)
1144 if (sd->spec_version < SD_PHY_SPECv3_01_VERS) {
1145 return sd_cmd_illegal(sd, req);
1148 if (sd->state != sd_transfer_state) {
1149 return sd_invalid_state_for_cmd(sd, req);
1152 sd->multi_blk_cnt = req.arg;
1153 trace_sdcard_set_block_count(sd->multi_blk_cnt);
1155 return sd_r1;
1158 static sd_rsp_type_t sd_normal_command(SDState *sd, SDRequest req)
1160 uint16_t rca;
1161 uint64_t addr;
1163 sd->last_cmd_name = sd_cmd_name(req.cmd);
1164 /* CMD55 precedes an ACMD, so we are not interested in tracing it.
1165 * However there is no ACMD55, so we want to trace this particular case.
1167 if (req.cmd != 55 || sd->expecting_acmd) {
1168 trace_sdcard_normal_command(sd_proto(sd)->name,
1169 sd->last_cmd_name, req.cmd,
1170 req.arg, sd_state_name(sd->state));
1173 /* Not interpreting this as an app command */
1174 sd->card_status &= ~APP_CMD;
1176 /* CMD23 (set block count) must be immediately followed by CMD18 or CMD25
1177 * if not, its effects are cancelled */
1178 if (sd->multi_blk_cnt != 0 && !(req.cmd == 18 || req.cmd == 25)) {
1179 sd->multi_blk_cnt = 0;
1182 if (sd_cmd_class[req.cmd] == 6 && FIELD_EX32(sd->ocr, OCR, CARD_CAPACITY)) {
1183 /* Only Standard Capacity cards support class 6 commands */
1184 return sd_illegal;
1187 if (sd_proto(sd)->cmd[req.cmd]) {
1188 return sd_proto(sd)->cmd[req.cmd](sd, req);
1191 switch (req.cmd) {
1192 /* Basic commands (Class 0 and Class 1) */
1193 case 4: /* CMD4: SEND_DSR */
1194 switch (sd->state) {
1195 case sd_standby_state:
1196 break;
1198 default:
1199 break;
1201 break;
1203 case 6: /* CMD6: SWITCH_FUNCTION */
1204 if (sd->mode != sd_data_transfer_mode) {
1205 return sd_invalid_mode_for_cmd(sd, req);
1207 if (sd->state != sd_transfer_state) {
1208 return sd_invalid_state_for_cmd(sd, req);
1211 sd_function_switch(sd, req.arg);
1212 sd->state = sd_sendingdata_state;
1213 sd->data_start = 0;
1214 sd->data_offset = 0;
1215 return sd_r1;
1217 case 7: /* CMD7: SELECT/DESELECT_CARD */
1218 rca = sd_req_get_rca(sd, req);
1219 switch (sd->state) {
1220 case sd_standby_state:
1221 if (sd->rca != rca)
1222 return sd_r0;
1224 sd->state = sd_transfer_state;
1225 return sd_r1b;
1227 case sd_transfer_state:
1228 case sd_sendingdata_state:
1229 if (sd->rca == rca)
1230 break;
1232 sd->state = sd_standby_state;
1233 return sd_r1b;
1235 case sd_disconnect_state:
1236 if (sd->rca != rca)
1237 return sd_r0;
1239 sd->state = sd_programming_state;
1240 return sd_r1b;
1242 case sd_programming_state:
1243 if (sd->rca == rca)
1244 break;
1246 sd->state = sd_disconnect_state;
1247 return sd_r1b;
1249 default:
1250 break;
1252 break;
1254 case 8: /* CMD8: SEND_IF_COND */
1255 if (sd->spec_version < SD_PHY_SPECv2_00_VERS) {
1256 break;
1258 if (sd->state != sd_idle_state) {
1259 break;
1261 sd->vhs = 0;
1263 /* No response if not exactly one VHS bit is set. */
1264 if (!(req.arg >> 8) || (req.arg >> (ctz32(req.arg & ~0xff) + 1))) {
1265 return sd_is_spi(sd) ? sd_r7 : sd_r0;
1268 /* Accept. */
1269 sd->vhs = req.arg;
1270 return sd_r7;
1272 case 9: /* CMD9: SEND_CSD */
1273 rca = sd_req_get_rca(sd, req);
1274 switch (sd->state) {
1275 case sd_standby_state:
1276 if (sd->rca != rca)
1277 return sd_r0;
1279 return sd_r2_s;
1281 case sd_transfer_state:
1282 if (!sd_is_spi(sd)) {
1283 break;
1285 sd->state = sd_sendingdata_state;
1286 memcpy(sd->data, sd->csd, 16);
1287 sd->data_start = sd_req_get_address(sd, req);
1288 sd->data_offset = 0;
1289 return sd_r1;
1291 default:
1292 break;
1294 break;
1296 case 10: /* CMD10: SEND_CID */
1297 rca = sd_req_get_rca(sd, req);
1298 switch (sd->state) {
1299 case sd_standby_state:
1300 if (sd->rca != rca)
1301 return sd_r0;
1303 return sd_r2_i;
1305 case sd_transfer_state:
1306 if (!sd_is_spi(sd)) {
1307 break;
1309 sd->state = sd_sendingdata_state;
1310 memcpy(sd->data, sd->cid, 16);
1311 sd->data_start = sd_req_get_address(sd, req);
1312 sd->data_offset = 0;
1313 return sd_r1;
1315 default:
1316 break;
1318 break;
1320 case 12: /* CMD12: STOP_TRANSMISSION */
1321 switch (sd->state) {
1322 case sd_sendingdata_state:
1323 sd->state = sd_transfer_state;
1324 return sd_r1b;
1326 case sd_receivingdata_state:
1327 sd->state = sd_programming_state;
1328 /* Bzzzzzzztt .... Operation complete. */
1329 sd->state = sd_transfer_state;
1330 return sd_r1b;
1332 default:
1333 break;
1335 break;
1337 case 13: /* CMD13: SEND_STATUS */
1338 rca = sd_req_get_rca(sd, req);
1339 if (sd->mode != sd_data_transfer_mode) {
1340 return sd_invalid_mode_for_cmd(sd, req);
1342 if (!sd_is_spi(sd) && sd->rca != rca) {
1343 return sd_r0;
1346 return sd_r1;
1348 case 15: /* CMD15: GO_INACTIVE_STATE */
1349 if (sd->mode != sd_data_transfer_mode) {
1350 return sd_invalid_mode_for_cmd(sd, req);
1352 rca = sd_req_get_rca(sd, req);
1353 if (sd->rca == rca) {
1354 sd->state = sd_inactive_state;
1356 return sd_r0;
1358 /* Block read commands (Class 2) */
1359 case 16: /* CMD16: SET_BLOCKLEN */
1360 switch (sd->state) {
1361 case sd_transfer_state:
1362 if (req.arg > (1 << HWBLOCK_SHIFT)) {
1363 sd->card_status |= BLOCK_LEN_ERROR;
1364 } else {
1365 trace_sdcard_set_blocklen(req.arg);
1366 sd->blk_len = req.arg;
1369 return sd_r1;
1371 default:
1372 break;
1374 break;
1376 case 17: /* CMD17: READ_SINGLE_BLOCK */
1377 case 18: /* CMD18: READ_MULTIPLE_BLOCK */
1378 addr = sd_req_get_address(sd, req);
1379 switch (sd->state) {
1380 case sd_transfer_state:
1382 if (!address_in_range(sd, "READ_BLOCK", addr, sd->blk_len)) {
1383 return sd_r1;
1386 sd->state = sd_sendingdata_state;
1387 sd->data_start = addr;
1388 sd->data_offset = 0;
1389 return sd_r1;
1391 default:
1392 break;
1394 break;
1396 /* Block write commands (Class 4) */
1397 case 24: /* CMD24: WRITE_SINGLE_BLOCK */
1398 case 25: /* CMD25: WRITE_MULTIPLE_BLOCK */
1399 addr = sd_req_get_address(sd, req);
1400 switch (sd->state) {
1401 case sd_transfer_state:
1403 if (!address_in_range(sd, "WRITE_BLOCK", addr, sd->blk_len)) {
1404 return sd_r1;
1407 sd->state = sd_receivingdata_state;
1408 sd->data_start = addr;
1409 sd->data_offset = 0;
1410 sd->blk_written = 0;
1412 if (sd->size <= SDSC_MAX_CAPACITY) {
1413 if (sd_wp_addr(sd, sd->data_start)) {
1414 sd->card_status |= WP_VIOLATION;
1417 if (sd->csd[14] & 0x30) {
1418 sd->card_status |= WP_VIOLATION;
1420 return sd_r1;
1422 default:
1423 break;
1425 break;
1427 case 26: /* CMD26: PROGRAM_CID */
1428 switch (sd->state) {
1429 case sd_transfer_state:
1430 sd->state = sd_receivingdata_state;
1431 sd->data_start = 0;
1432 sd->data_offset = 0;
1433 return sd_r1;
1435 default:
1436 break;
1438 break;
1440 case 27: /* CMD27: PROGRAM_CSD */
1441 switch (sd->state) {
1442 case sd_transfer_state:
1443 sd->state = sd_receivingdata_state;
1444 sd->data_start = 0;
1445 sd->data_offset = 0;
1446 return sd_r1;
1448 default:
1449 break;
1451 break;
1453 /* Write protection (Class 6) */
1454 case 28: /* CMD28: SET_WRITE_PROT */
1455 if (sd->size > SDSC_MAX_CAPACITY) {
1456 return sd_illegal;
1458 addr = sd_req_get_address(sd, req);
1459 switch (sd->state) {
1460 case sd_transfer_state:
1461 if (!address_in_range(sd, "SET_WRITE_PROT", addr, 1)) {
1462 return sd_r1b;
1465 sd->state = sd_programming_state;
1466 set_bit(sd_addr_to_wpnum(addr), sd->wp_group_bmap);
1467 /* Bzzzzzzztt .... Operation complete. */
1468 sd->state = sd_transfer_state;
1469 return sd_r1b;
1471 default:
1472 break;
1474 break;
1476 case 29: /* CMD29: CLR_WRITE_PROT */
1477 if (sd->size > SDSC_MAX_CAPACITY) {
1478 return sd_illegal;
1480 addr = sd_req_get_address(sd, req);
1481 switch (sd->state) {
1482 case sd_transfer_state:
1483 if (!address_in_range(sd, "CLR_WRITE_PROT", addr, 1)) {
1484 return sd_r1b;
1487 sd->state = sd_programming_state;
1488 clear_bit(sd_addr_to_wpnum(addr), sd->wp_group_bmap);
1489 /* Bzzzzzzztt .... Operation complete. */
1490 sd->state = sd_transfer_state;
1491 return sd_r1b;
1493 default:
1494 break;
1496 break;
1498 case 30: /* CMD30: SEND_WRITE_PROT */
1499 if (sd->size > SDSC_MAX_CAPACITY) {
1500 return sd_illegal;
1502 addr = sd_req_get_address(sd, req);
1503 switch (sd->state) {
1504 case sd_transfer_state:
1505 if (!address_in_range(sd, "SEND_WRITE_PROT",
1506 req.arg, sd->blk_len)) {
1507 return sd_r1;
1510 sd->state = sd_sendingdata_state;
1511 *(uint32_t *) sd->data = sd_wpbits(sd, req.arg);
1512 sd->data_start = addr;
1513 sd->data_offset = 0;
1514 return sd_r1;
1516 default:
1517 break;
1519 break;
1521 /* Erase commands (Class 5) */
1522 case 32: /* CMD32: ERASE_WR_BLK_START */
1523 switch (sd->state) {
1524 case sd_transfer_state:
1525 sd->erase_start = req.arg;
1526 return sd_r1;
1528 default:
1529 break;
1531 break;
1533 case 33: /* CMD33: ERASE_WR_BLK_END */
1534 switch (sd->state) {
1535 case sd_transfer_state:
1536 sd->erase_end = req.arg;
1537 return sd_r1;
1539 default:
1540 break;
1542 break;
1544 case 38: /* CMD38: ERASE */
1545 switch (sd->state) {
1546 case sd_transfer_state:
1547 if (sd->csd[14] & 0x30) {
1548 sd->card_status |= WP_VIOLATION;
1549 return sd_r1b;
1552 sd->state = sd_programming_state;
1553 sd_erase(sd);
1554 /* Bzzzzzzztt .... Operation complete. */
1555 sd->state = sd_transfer_state;
1556 return sd_r1b;
1558 default:
1559 break;
1561 break;
1563 /* Lock card commands (Class 7) */
1564 case 42: /* CMD42: LOCK_UNLOCK */
1565 switch (sd->state) {
1566 case sd_transfer_state:
1567 sd->state = sd_receivingdata_state;
1568 sd->data_start = 0;
1569 sd->data_offset = 0;
1570 return sd_r1;
1572 default:
1573 break;
1575 break;
1577 /* Application specific commands (Class 8) */
1578 case 55: /* CMD55: APP_CMD */
1579 rca = sd_req_get_rca(sd, req);
1580 switch (sd->state) {
1581 case sd_ready_state:
1582 case sd_identification_state:
1583 case sd_inactive_state:
1584 return sd_illegal;
1585 case sd_idle_state:
1586 if (rca) {
1587 qemu_log_mask(LOG_GUEST_ERROR,
1588 "SD: illegal RCA 0x%04x for APP_CMD\n", req.cmd);
1590 default:
1591 break;
1593 if (!sd_is_spi(sd)) {
1594 if (sd->rca != rca) {
1595 return sd_r0;
1598 sd->expecting_acmd = true;
1599 sd->card_status |= APP_CMD;
1600 return sd_r1;
1602 case 56: /* CMD56: GEN_CMD */
1603 switch (sd->state) {
1604 case sd_transfer_state:
1605 sd->data_offset = 0;
1606 if (req.arg & 1)
1607 sd->state = sd_sendingdata_state;
1608 else
1609 sd->state = sd_receivingdata_state;
1610 return sd_r1;
1612 default:
1613 break;
1615 break;
1617 case 58: /* CMD58: READ_OCR (SPI) */
1618 return sd_r3;
1620 case 59: /* CMD59: CRC_ON_OFF (SPI) */
1621 return sd_r1;
1623 default:
1624 qemu_log_mask(LOG_GUEST_ERROR, "SD: Unknown CMD%i\n", req.cmd);
1625 return sd_illegal;
1628 return sd_invalid_state_for_cmd(sd, req);
1631 static sd_rsp_type_t sd_app_command(SDState *sd,
1632 SDRequest req)
1634 sd->last_cmd_name = sd_acmd_name(req.cmd);
1635 trace_sdcard_app_command(sd_proto(sd)->name, sd->last_cmd_name,
1636 req.cmd, req.arg, sd_state_name(sd->state));
1637 sd->card_status |= APP_CMD;
1639 if (sd_proto(sd)->acmd[req.cmd]) {
1640 return sd_proto(sd)->acmd[req.cmd](sd, req);
1643 switch (req.cmd) {
1644 case 6: /* ACMD6: SET_BUS_WIDTH */
1645 switch (sd->state) {
1646 case sd_transfer_state:
1647 sd->sd_status[0] &= 0x3f;
1648 sd->sd_status[0] |= (req.arg & 0x03) << 6;
1649 return sd_r1;
1651 default:
1652 break;
1654 break;
1656 case 13: /* ACMD13: SD_STATUS */
1657 switch (sd->state) {
1658 case sd_transfer_state:
1659 sd->state = sd_sendingdata_state;
1660 sd->data_start = 0;
1661 sd->data_offset = 0;
1662 return sd_r1;
1664 default:
1665 break;
1667 break;
1669 case 22: /* ACMD22: SEND_NUM_WR_BLOCKS */
1670 switch (sd->state) {
1671 case sd_transfer_state:
1672 *(uint32_t *) sd->data = sd->blk_written;
1674 sd->state = sd_sendingdata_state;
1675 sd->data_start = 0;
1676 sd->data_offset = 0;
1677 return sd_r1;
1679 default:
1680 break;
1682 break;
1684 case 23: /* ACMD23: SET_WR_BLK_ERASE_COUNT */
1685 switch (sd->state) {
1686 case sd_transfer_state:
1687 return sd_r1;
1689 default:
1690 break;
1692 break;
1694 case 41: /* ACMD41: SD_APP_OP_COND */
1695 if (sd->state != sd_idle_state) {
1696 break;
1698 /* If it's the first ACMD41 since reset, we need to decide
1699 * whether to power up. If this is not an enquiry ACMD41,
1700 * we immediately report power on and proceed below to the
1701 * ready state, but if it is, we set a timer to model a
1702 * delay for power up. This works around a bug in EDK2
1703 * UEFI, which sends an initial enquiry ACMD41, but
1704 * assumes that the card is in ready state as soon as it
1705 * sees the power up bit set. */
1706 if (!FIELD_EX32(sd->ocr, OCR, CARD_POWER_UP)) {
1707 if ((req.arg & ACMD41_ENQUIRY_MASK) != 0) {
1708 timer_del(sd->ocr_power_timer);
1709 sd_ocr_powerup(sd);
1710 } else {
1711 trace_sdcard_inquiry_cmd41();
1712 if (!timer_pending(sd->ocr_power_timer)) {
1713 timer_mod_ns(sd->ocr_power_timer,
1714 (qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL)
1715 + OCR_POWER_DELAY_NS));
1720 if (FIELD_EX32(sd->ocr & req.arg, OCR, VDD_VOLTAGE_WINDOW)) {
1721 /* We accept any voltage. 10000 V is nothing.
1723 * Once we're powered up, we advance straight to ready state
1724 * unless it's an enquiry ACMD41 (bits 23:0 == 0).
1726 sd->state = sd_ready_state;
1729 return sd_r3;
1731 case 42: /* ACMD42: SET_CLR_CARD_DETECT */
1732 switch (sd->state) {
1733 case sd_transfer_state:
1734 /* Bringing in the 50KOhm pull-up resistor... Done. */
1735 return sd_r1;
1737 default:
1738 break;
1740 break;
1742 case 51: /* ACMD51: SEND_SCR */
1743 switch (sd->state) {
1744 case sd_transfer_state:
1745 sd->state = sd_sendingdata_state;
1746 sd->data_start = 0;
1747 sd->data_offset = 0;
1748 return sd_r1;
1750 default:
1751 break;
1753 break;
1755 case 18: /* Reserved for SD security applications */
1756 case 25:
1757 case 26:
1758 case 38:
1759 case 43 ... 49:
1760 /* Refer to the "SD Specifications Part3 Security Specification" for
1761 * information about the SD Security Features.
1763 qemu_log_mask(LOG_UNIMP, "SD: CMD%i Security not implemented\n",
1764 req.cmd);
1765 return sd_illegal;
1767 default:
1768 /* Fall back to standard commands. */
1769 return sd_normal_command(sd, req);
1772 qemu_log_mask(LOG_GUEST_ERROR, "SD: ACMD%i in a wrong state\n", req.cmd);
1773 return sd_illegal;
1776 static bool cmd_valid_while_locked(SDState *sd, unsigned cmd)
1778 /* Valid commands in locked state:
1779 * basic class (0)
1780 * lock card class (7)
1781 * CMD16
1782 * implicitly, the ACMD prefix CMD55
1783 * ACMD41 and ACMD42
1784 * Anything else provokes an "illegal command" response.
1786 if (sd->expecting_acmd) {
1787 return cmd == 41 || cmd == 42;
1789 if (cmd == 16 || cmd == 55) {
1790 return true;
1792 return sd_cmd_class[cmd] == 0 || sd_cmd_class[cmd] == 7;
1795 int sd_do_command(SDState *sd, SDRequest *req,
1796 uint8_t *response) {
1797 int last_state;
1798 sd_rsp_type_t rtype;
1799 int rsplen;
1801 if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable) {
1802 return 0;
1805 if (sd_req_crc_validate(req)) {
1806 sd->card_status |= COM_CRC_ERROR;
1807 rtype = sd_illegal;
1808 goto send_response;
1811 if (req->cmd >= SDMMC_CMD_MAX) {
1812 qemu_log_mask(LOG_GUEST_ERROR, "SD: incorrect command 0x%02x\n",
1813 req->cmd);
1814 req->cmd &= 0x3f;
1817 if (sd->card_status & CARD_IS_LOCKED) {
1818 if (!cmd_valid_while_locked(sd, req->cmd)) {
1819 sd->card_status |= ILLEGAL_COMMAND;
1820 sd->expecting_acmd = false;
1821 qemu_log_mask(LOG_GUEST_ERROR, "SD: Card is locked\n");
1822 rtype = sd_illegal;
1823 goto send_response;
1827 last_state = sd->state;
1828 sd_set_mode(sd);
1830 if (sd->expecting_acmd) {
1831 sd->expecting_acmd = false;
1832 rtype = sd_app_command(sd, *req);
1833 } else {
1834 rtype = sd_normal_command(sd, *req);
1837 if (rtype == sd_illegal) {
1838 sd->card_status |= ILLEGAL_COMMAND;
1839 } else {
1840 /* Valid command, we can update the 'state before command' bits.
1841 * (Do this now so they appear in r1 responses.)
1843 sd->current_cmd = req->cmd;
1844 sd->card_status = FIELD_DP32(sd->card_status, CSR,
1845 CURRENT_STATE, last_state);
1848 send_response:
1849 switch (rtype) {
1850 case sd_r1:
1851 case sd_r1b:
1852 sd_response_r1_make(sd, response);
1853 rsplen = 4;
1854 break;
1856 case sd_r2_i:
1857 memcpy(response, sd->cid, sizeof(sd->cid));
1858 rsplen = 16;
1859 break;
1861 case sd_r2_s:
1862 memcpy(response, sd->csd, sizeof(sd->csd));
1863 rsplen = 16;
1864 break;
1866 case sd_r3:
1867 sd_response_r3_make(sd, response);
1868 rsplen = 4;
1869 break;
1871 case sd_r6:
1872 sd_response_r6_make(sd, response);
1873 rsplen = 4;
1874 break;
1876 case sd_r7:
1877 sd_response_r7_make(sd, response);
1878 rsplen = 4;
1879 break;
1881 case sd_r0:
1883 * Invalid state transition, reset implementation
1884 * fields to avoid OOB abuse.
1886 sd->data_start = 0;
1887 sd->data_offset = 0;
1888 /* fall-through */
1889 case sd_illegal:
1890 rsplen = 0;
1891 break;
1892 default:
1893 g_assert_not_reached();
1895 trace_sdcard_response(sd_response_name(rtype), rsplen);
1897 if (rtype != sd_illegal) {
1898 /* Clear the "clear on valid command" status bits now we've
1899 * sent any response
1901 sd->card_status &= ~CARD_STATUS_B;
1904 #ifdef DEBUG_SD
1905 qemu_hexdump(stderr, "Response", response, rsplen);
1906 #endif
1908 return rsplen;
1911 void sd_write_byte(SDState *sd, uint8_t value)
1913 int i;
1915 if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable)
1916 return;
1918 if (sd->state != sd_receivingdata_state) {
1919 qemu_log_mask(LOG_GUEST_ERROR,
1920 "%s: not in Receiving-Data state\n", __func__);
1921 return;
1924 if (sd->card_status & (ADDRESS_ERROR | WP_VIOLATION))
1925 return;
1927 trace_sdcard_write_data(sd_proto(sd)->name,
1928 sd->last_cmd_name,
1929 sd->current_cmd, sd->data_offset, value);
1930 switch (sd->current_cmd) {
1931 case 24: /* CMD24: WRITE_SINGLE_BLOCK */
1932 sd->data[sd->data_offset ++] = value;
1933 if (sd->data_offset >= sd->blk_len) {
1934 /* TODO: Check CRC before committing */
1935 sd->state = sd_programming_state;
1936 sd_blk_write(sd, sd->data_start, sd->data_offset);
1937 sd->blk_written ++;
1938 sd->csd[14] |= 0x40;
1939 /* Bzzzzzzztt .... Operation complete. */
1940 sd->state = sd_transfer_state;
1942 break;
1944 case 25: /* CMD25: WRITE_MULTIPLE_BLOCK */
1945 if (sd->data_offset == 0) {
1946 /* Start of the block - let's check the address is valid */
1947 if (!address_in_range(sd, "WRITE_MULTIPLE_BLOCK",
1948 sd->data_start, sd->blk_len)) {
1949 break;
1951 if (sd->size <= SDSC_MAX_CAPACITY) {
1952 if (sd_wp_addr(sd, sd->data_start)) {
1953 sd->card_status |= WP_VIOLATION;
1954 break;
1958 sd->data[sd->data_offset++] = value;
1959 if (sd->data_offset >= sd->blk_len) {
1960 /* TODO: Check CRC before committing */
1961 sd->state = sd_programming_state;
1962 sd_blk_write(sd, sd->data_start, sd->data_offset);
1963 sd->blk_written++;
1964 sd->data_start += sd->blk_len;
1965 sd->data_offset = 0;
1966 sd->csd[14] |= 0x40;
1968 /* Bzzzzzzztt .... Operation complete. */
1969 if (sd->multi_blk_cnt != 0) {
1970 if (--sd->multi_blk_cnt == 0) {
1971 /* Stop! */
1972 sd->state = sd_transfer_state;
1973 break;
1977 sd->state = sd_receivingdata_state;
1979 break;
1981 case 26: /* CMD26: PROGRAM_CID */
1982 sd->data[sd->data_offset ++] = value;
1983 if (sd->data_offset >= sizeof(sd->cid)) {
1984 /* TODO: Check CRC before committing */
1985 sd->state = sd_programming_state;
1986 for (i = 0; i < sizeof(sd->cid); i ++)
1987 if ((sd->cid[i] | 0x00) != sd->data[i])
1988 sd->card_status |= CID_CSD_OVERWRITE;
1990 if (!(sd->card_status & CID_CSD_OVERWRITE))
1991 for (i = 0; i < sizeof(sd->cid); i ++) {
1992 sd->cid[i] |= 0x00;
1993 sd->cid[i] &= sd->data[i];
1995 /* Bzzzzzzztt .... Operation complete. */
1996 sd->state = sd_transfer_state;
1998 break;
2000 case 27: /* CMD27: PROGRAM_CSD */
2001 sd->data[sd->data_offset ++] = value;
2002 if (sd->data_offset >= sizeof(sd->csd)) {
2003 /* TODO: Check CRC before committing */
2004 sd->state = sd_programming_state;
2005 for (i = 0; i < sizeof(sd->csd); i ++)
2006 if ((sd->csd[i] | sd_csd_rw_mask[i]) !=
2007 (sd->data[i] | sd_csd_rw_mask[i]))
2008 sd->card_status |= CID_CSD_OVERWRITE;
2010 /* Copy flag (OTP) & Permanent write protect */
2011 if (sd->csd[14] & ~sd->data[14] & 0x60)
2012 sd->card_status |= CID_CSD_OVERWRITE;
2014 if (!(sd->card_status & CID_CSD_OVERWRITE))
2015 for (i = 0; i < sizeof(sd->csd); i ++) {
2016 sd->csd[i] |= sd_csd_rw_mask[i];
2017 sd->csd[i] &= sd->data[i];
2019 /* Bzzzzzzztt .... Operation complete. */
2020 sd->state = sd_transfer_state;
2022 break;
2024 case 42: /* CMD42: LOCK_UNLOCK */
2025 sd->data[sd->data_offset ++] = value;
2026 if (sd->data_offset >= sd->blk_len) {
2027 /* TODO: Check CRC before committing */
2028 sd->state = sd_programming_state;
2029 sd_lock_command(sd);
2030 /* Bzzzzzzztt .... Operation complete. */
2031 sd->state = sd_transfer_state;
2033 break;
2035 case 56: /* CMD56: GEN_CMD */
2036 sd->data[sd->data_offset ++] = value;
2037 if (sd->data_offset >= sd->blk_len) {
2038 APP_WRITE_BLOCK(sd->data_start, sd->data_offset);
2039 sd->state = sd_transfer_state;
2041 break;
2043 default:
2044 qemu_log_mask(LOG_GUEST_ERROR, "%s: unknown command\n", __func__);
2045 break;
2049 #define SD_TUNING_BLOCK_SIZE 64
2051 static const uint8_t sd_tuning_block_pattern[SD_TUNING_BLOCK_SIZE] = {
2052 /* See: Physical Layer Simplified Specification Version 3.01, Table 4-2 */
2053 0xff, 0x0f, 0xff, 0x00, 0x0f, 0xfc, 0xc3, 0xcc,
2054 0xc3, 0x3c, 0xcc, 0xff, 0xfe, 0xff, 0xfe, 0xef,
2055 0xff, 0xdf, 0xff, 0xdd, 0xff, 0xfb, 0xff, 0xfb,
2056 0xbf, 0xff, 0x7f, 0xff, 0x77, 0xf7, 0xbd, 0xef,
2057 0xff, 0xf0, 0xff, 0xf0, 0x0f, 0xfc, 0xcc, 0x3c,
2058 0xcc, 0x33, 0xcc, 0xcf, 0xff, 0xef, 0xff, 0xee,
2059 0xff, 0xfd, 0xff, 0xfd, 0xdf, 0xff, 0xbf, 0xff,
2060 0xbb, 0xff, 0xf7, 0xff, 0xf7, 0x7f, 0x7b, 0xde,
2063 uint8_t sd_read_byte(SDState *sd)
2065 /* TODO: Append CRCs */
2066 uint8_t ret;
2067 uint32_t io_len;
2069 if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable)
2070 return 0x00;
2072 if (sd->state != sd_sendingdata_state) {
2073 qemu_log_mask(LOG_GUEST_ERROR,
2074 "%s: not in Sending-Data state\n", __func__);
2075 return 0x00;
2078 if (sd->card_status & (ADDRESS_ERROR | WP_VIOLATION))
2079 return 0x00;
2081 io_len = (sd->ocr & (1 << 30)) ? 512 : sd->blk_len;
2083 trace_sdcard_read_data(sd_proto(sd)->name,
2084 sd->last_cmd_name,
2085 sd->current_cmd, sd->data_offset, io_len);
2086 switch (sd->current_cmd) {
2087 case 6: /* CMD6: SWITCH_FUNCTION */
2088 ret = sd->data[sd->data_offset ++];
2090 if (sd->data_offset >= 64)
2091 sd->state = sd_transfer_state;
2092 break;
2094 case 9: /* CMD9: SEND_CSD */
2095 case 10: /* CMD10: SEND_CID */
2096 ret = sd->data[sd->data_offset ++];
2098 if (sd->data_offset >= 16)
2099 sd->state = sd_transfer_state;
2100 break;
2102 case 13: /* ACMD13: SD_STATUS */
2103 ret = sd->sd_status[sd->data_offset ++];
2105 if (sd->data_offset >= sizeof(sd->sd_status))
2106 sd->state = sd_transfer_state;
2107 break;
2109 case 17: /* CMD17: READ_SINGLE_BLOCK */
2110 if (sd->data_offset == 0) {
2111 sd_blk_read(sd, sd->data_start, io_len);
2113 ret = sd->data[sd->data_offset ++];
2115 if (sd->data_offset >= io_len)
2116 sd->state = sd_transfer_state;
2117 break;
2119 case 18: /* CMD18: READ_MULTIPLE_BLOCK */
2120 if (sd->data_offset == 0) {
2121 if (!address_in_range(sd, "READ_MULTIPLE_BLOCK",
2122 sd->data_start, io_len)) {
2123 return 0x00;
2125 sd_blk_read(sd, sd->data_start, io_len);
2127 ret = sd->data[sd->data_offset ++];
2129 if (sd->data_offset >= io_len) {
2130 sd->data_start += io_len;
2131 sd->data_offset = 0;
2133 if (sd->multi_blk_cnt != 0) {
2134 if (--sd->multi_blk_cnt == 0) {
2135 /* Stop! */
2136 sd->state = sd_transfer_state;
2137 break;
2141 break;
2143 case 19: /* CMD19: SEND_TUNING_BLOCK (SD) */
2144 if (sd->data_offset >= SD_TUNING_BLOCK_SIZE - 1) {
2145 sd->state = sd_transfer_state;
2147 ret = sd_tuning_block_pattern[sd->data_offset++];
2148 break;
2150 case 22: /* ACMD22: SEND_NUM_WR_BLOCKS */
2151 ret = sd->data[sd->data_offset ++];
2153 if (sd->data_offset >= 4)
2154 sd->state = sd_transfer_state;
2155 break;
2157 case 30: /* CMD30: SEND_WRITE_PROT */
2158 ret = sd->data[sd->data_offset ++];
2160 if (sd->data_offset >= 4)
2161 sd->state = sd_transfer_state;
2162 break;
2164 case 51: /* ACMD51: SEND_SCR */
2165 ret = sd->scr[sd->data_offset ++];
2167 if (sd->data_offset >= sizeof(sd->scr))
2168 sd->state = sd_transfer_state;
2169 break;
2171 case 56: /* CMD56: GEN_CMD */
2172 if (sd->data_offset == 0)
2173 APP_READ_BLOCK(sd->data_start, sd->blk_len);
2174 ret = sd->data[sd->data_offset ++];
2176 if (sd->data_offset >= sd->blk_len)
2177 sd->state = sd_transfer_state;
2178 break;
2180 default:
2181 qemu_log_mask(LOG_GUEST_ERROR, "%s: unknown command\n", __func__);
2182 return 0x00;
2185 return ret;
2188 static bool sd_receive_ready(SDState *sd)
2190 return sd->state == sd_receivingdata_state;
2193 static bool sd_data_ready(SDState *sd)
2195 return sd->state == sd_sendingdata_state;
2198 void sd_enable(SDState *sd, bool enable)
2200 sd->enable = enable;
2203 static const SDProto sd_proto_spi = {
2204 .name = "SPI",
2205 .cmd = {
2206 [0] = sd_cmd_GO_IDLE_STATE,
2207 [1] = spi_cmd_SEND_OP_COND,
2209 .acmd = {
2210 [41] = spi_cmd_SEND_OP_COND,
2214 static const SDProto sd_proto_sd = {
2215 .name = "SD",
2216 .cmd = {
2217 [0] = sd_cmd_GO_IDLE_STATE,
2218 [2] = sd_cmd_ALL_SEND_CID,
2219 [3] = sd_cmd_SEND_RELATIVE_ADDR,
2220 [19] = sd_cmd_SEND_TUNING_BLOCK,
2221 [23] = sd_cmd_SET_BLOCK_COUNT,
2225 static void sd_instance_init(Object *obj)
2227 SDState *sd = SD_CARD(obj);
2229 sd->last_cmd_name = "UNSET";
2230 sd->enable = true;
2231 sd->ocr_power_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, sd_ocr_powerup, sd);
2234 static void sd_instance_finalize(Object *obj)
2236 SDState *sd = SD_CARD(obj);
2238 timer_free(sd->ocr_power_timer);
2241 static void sd_realize(DeviceState *dev, Error **errp)
2243 SDState *sd = SD_CARD(dev);
2244 int ret;
2246 switch (sd->spec_version) {
2247 case SD_PHY_SPECv1_10_VERS
2248 ... SD_PHY_SPECv3_01_VERS:
2249 break;
2250 default:
2251 error_setg(errp, "Invalid SD card Spec version: %u", sd->spec_version);
2252 return;
2255 if (sd->blk) {
2256 int64_t blk_size;
2258 if (!blk_supports_write_perm(sd->blk)) {
2259 error_setg(errp, "Cannot use read-only drive as SD card");
2260 return;
2263 blk_size = blk_getlength(sd->blk);
2264 if (blk_size > 0 && !is_power_of_2(blk_size)) {
2265 int64_t blk_size_aligned = pow2ceil(blk_size);
2266 char *blk_size_str;
2268 blk_size_str = size_to_str(blk_size);
2269 error_setg(errp, "Invalid SD card size: %s", blk_size_str);
2270 g_free(blk_size_str);
2272 blk_size_str = size_to_str(blk_size_aligned);
2273 error_append_hint(errp,
2274 "SD card size has to be a power of 2, e.g. %s.\n"
2275 "You can resize disk images with"
2276 " 'qemu-img resize <imagefile> <new-size>'\n"
2277 "(note that this will lose data if you make the"
2278 " image smaller than it currently is).\n",
2279 blk_size_str);
2280 g_free(blk_size_str);
2282 return;
2285 ret = blk_set_perm(sd->blk, BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE,
2286 BLK_PERM_ALL, errp);
2287 if (ret < 0) {
2288 return;
2290 blk_set_dev_ops(sd->blk, &sd_block_ops, sd);
2294 static Property sd_properties[] = {
2295 DEFINE_PROP_UINT8("spec_version", SDState,
2296 spec_version, SD_PHY_SPECv2_00_VERS),
2297 DEFINE_PROP_DRIVE("drive", SDState, blk),
2298 /* We do not model the chip select pin, so allow the board to select
2299 * whether card should be in SSI or MMC/SD mode. It is also up to the
2300 * board to ensure that ssi transfers only occur when the chip select
2301 * is asserted. */
2302 DEFINE_PROP_END_OF_LIST()
2305 static void sd_class_init(ObjectClass *klass, void *data)
2307 DeviceClass *dc = DEVICE_CLASS(klass);
2308 SDCardClass *sc = SD_CARD_CLASS(klass);
2310 dc->realize = sd_realize;
2311 device_class_set_props(dc, sd_properties);
2312 dc->vmsd = &sd_vmstate;
2313 dc->reset = sd_reset;
2314 dc->bus_type = TYPE_SD_BUS;
2315 set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
2317 sc->set_voltage = sd_set_voltage;
2318 sc->get_dat_lines = sd_get_dat_lines;
2319 sc->get_cmd_line = sd_get_cmd_line;
2320 sc->do_command = sd_do_command;
2321 sc->write_byte = sd_write_byte;
2322 sc->read_byte = sd_read_byte;
2323 sc->receive_ready = sd_receive_ready;
2324 sc->data_ready = sd_data_ready;
2325 sc->enable = sd_enable;
2326 sc->get_inserted = sd_get_inserted;
2327 sc->get_readonly = sd_get_readonly;
2328 sc->proto = &sd_proto_sd;
2332 * We do not model the chip select pin, so allow the board to select
2333 * whether card should be in SSI or MMC/SD mode. It is also up to the
2334 * board to ensure that ssi transfers only occur when the chip select
2335 * is asserted.
2337 static void sd_spi_class_init(ObjectClass *klass, void *data)
2339 DeviceClass *dc = DEVICE_CLASS(klass);
2340 SDCardClass *sc = SD_CARD_CLASS(klass);
2342 dc->desc = "SD SPI";
2343 sc->proto = &sd_proto_spi;
2346 static const TypeInfo sd_types[] = {
2348 .name = TYPE_SD_CARD,
2349 .parent = TYPE_DEVICE,
2350 .instance_size = sizeof(SDState),
2351 .class_size = sizeof(SDCardClass),
2352 .class_init = sd_class_init,
2353 .instance_init = sd_instance_init,
2354 .instance_finalize = sd_instance_finalize,
2357 .name = TYPE_SD_CARD_SPI,
2358 .parent = TYPE_SD_CARD,
2359 .class_init = sd_spi_class_init,
2363 DEFINE_TYPES(sd_types)