xref: /openbmc/qemu/hw/sd/sd.c (revision 0ed93f4c)
1 /*
2  * SD Memory Card emulation as defined in the "SD Memory Card Physical
3  * layer specification, Version 2.00."
4  *
5  * Copyright (c) 2006 Andrzej Zaborowski  <balrog@zabor.org>
6  * Copyright (c) 2007 CodeSourcery
7  * Copyright (c) 2018 Philippe Mathieu-Daudé <f4bug@amsat.org>
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
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.
19  *
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.
31  */
32 
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 "qemu/error-report.h"
46 #include "qemu/timer.h"
47 #include "qemu/log.h"
48 #include "qemu/module.h"
49 #include "sdmmc-internal.h"
50 #include "trace.h"
51 
52 //#define DEBUG_SD 1
53 
54 #define SDSC_MAX_CAPACITY   (2 * GiB)
55 
56 typedef enum {
57     sd_r0 = 0,    /* no response */
58     sd_r1,        /* normal response command */
59     sd_r2_i,      /* CID register */
60     sd_r2_s,      /* CSD register */
61     sd_r3,        /* OCR register */
62     sd_r6 = 6,    /* Published RCA response */
63     sd_r7,        /* Operating voltage */
64     sd_r1b = -1,
65     sd_illegal = -2,
66 } sd_rsp_type_t;
67 
68 enum SDCardModes {
69     sd_inactive,
70     sd_card_identification_mode,
71     sd_data_transfer_mode,
72 };
73 
74 enum SDCardStates {
75     sd_inactive_state = -1,
76     sd_idle_state = 0,
77     sd_ready_state,
78     sd_identification_state,
79     sd_standby_state,
80     sd_transfer_state,
81     sd_sendingdata_state,
82     sd_receivingdata_state,
83     sd_programming_state,
84     sd_disconnect_state,
85 };
86 
87 struct SDState {
88     DeviceState parent_obj;
89 
90     /* If true, created by sd_init() for a non-qdevified caller */
91     /* TODO purge them with fire */
92     bool me_no_qdev_me_kill_mammoth_with_rocks;
93 
94     /* SD Memory Card Registers */
95     uint32_t ocr;
96     uint8_t scr[8];
97     uint8_t cid[16];
98     uint8_t csd[16];
99     uint16_t rca;
100     uint32_t card_status;
101     uint8_t sd_status[64];
102 
103     /* Configurable properties */
104     uint8_t spec_version;
105     BlockBackend *blk;
106     bool spi;
107 
108     uint32_t mode;    /* current card mode, one of SDCardModes */
109     int32_t state;    /* current card state, one of SDCardStates */
110     uint32_t vhs;
111     bool wp_switch;
112     unsigned long *wp_groups;
113     int32_t wpgrps_size;
114     uint64_t size;
115     uint32_t blk_len;
116     uint32_t multi_blk_cnt;
117     uint32_t erase_start;
118     uint32_t erase_end;
119     uint8_t pwd[16];
120     uint32_t pwd_len;
121     uint8_t function_group[6];
122     uint8_t current_cmd;
123     /* True if we will handle the next command as an ACMD. Note that this does
124      * *not* track the APP_CMD status bit!
125      */
126     bool expecting_acmd;
127     uint32_t blk_written;
128     uint64_t data_start;
129     uint32_t data_offset;
130     uint8_t data[512];
131     qemu_irq readonly_cb;
132     qemu_irq inserted_cb;
133     QEMUTimer *ocr_power_timer;
134     const char *proto_name;
135     bool enable;
136     uint8_t dat_lines;
137     bool cmd_line;
138 };
139 
140 static void sd_realize(DeviceState *dev, Error **errp);
141 
142 static const char *sd_state_name(enum SDCardStates state)
143 {
144     static const char *state_name[] = {
145         [sd_idle_state]             = "idle",
146         [sd_ready_state]            = "ready",
147         [sd_identification_state]   = "identification",
148         [sd_standby_state]          = "standby",
149         [sd_transfer_state]         = "transfer",
150         [sd_sendingdata_state]      = "sendingdata",
151         [sd_receivingdata_state]    = "receivingdata",
152         [sd_programming_state]      = "programming",
153         [sd_disconnect_state]       = "disconnect",
154     };
155     if (state == sd_inactive_state) {
156         return "inactive";
157     }
158     assert(state < ARRAY_SIZE(state_name));
159     return state_name[state];
160 }
161 
162 static const char *sd_response_name(sd_rsp_type_t rsp)
163 {
164     static const char *response_name[] = {
165         [sd_r0]     = "RESP#0 (no response)",
166         [sd_r1]     = "RESP#1 (normal cmd)",
167         [sd_r2_i]   = "RESP#2 (CID reg)",
168         [sd_r2_s]   = "RESP#2 (CSD reg)",
169         [sd_r3]     = "RESP#3 (OCR reg)",
170         [sd_r6]     = "RESP#6 (RCA)",
171         [sd_r7]     = "RESP#7 (operating voltage)",
172     };
173     if (rsp == sd_illegal) {
174         return "ILLEGAL RESP";
175     }
176     if (rsp == sd_r1b) {
177         rsp = sd_r1;
178     }
179     assert(rsp < ARRAY_SIZE(response_name));
180     return response_name[rsp];
181 }
182 
183 static uint8_t sd_get_dat_lines(SDState *sd)
184 {
185     return sd->enable ? sd->dat_lines : 0;
186 }
187 
188 static bool sd_get_cmd_line(SDState *sd)
189 {
190     return sd->enable ? sd->cmd_line : false;
191 }
192 
193 static void sd_set_voltage(SDState *sd, uint16_t millivolts)
194 {
195     trace_sdcard_set_voltage(millivolts);
196 
197     switch (millivolts) {
198     case 3001 ... 3600: /* SD_VOLTAGE_3_3V */
199     case 2001 ... 3000: /* SD_VOLTAGE_3_0V */
200         break;
201     default:
202         qemu_log_mask(LOG_GUEST_ERROR, "SD card voltage not supported: %.3fV",
203                       millivolts / 1000.f);
204     }
205 }
206 
207 static void sd_set_mode(SDState *sd)
208 {
209     switch (sd->state) {
210     case sd_inactive_state:
211         sd->mode = sd_inactive;
212         break;
213 
214     case sd_idle_state:
215     case sd_ready_state:
216     case sd_identification_state:
217         sd->mode = sd_card_identification_mode;
218         break;
219 
220     case sd_standby_state:
221     case sd_transfer_state:
222     case sd_sendingdata_state:
223     case sd_receivingdata_state:
224     case sd_programming_state:
225     case sd_disconnect_state:
226         sd->mode = sd_data_transfer_mode;
227         break;
228     }
229 }
230 
231 static const sd_cmd_type_t sd_cmd_type[SDMMC_CMD_MAX] = {
232     sd_bc,   sd_none, sd_bcr,  sd_bcr,  sd_none, sd_none, sd_none, sd_ac,
233     sd_bcr,  sd_ac,   sd_ac,   sd_adtc, sd_ac,   sd_ac,   sd_none, sd_ac,
234     /* 16 */
235     sd_ac,   sd_adtc, sd_adtc, sd_none, sd_none, sd_none, sd_none, sd_none,
236     sd_adtc, sd_adtc, sd_adtc, sd_adtc, sd_ac,   sd_ac,   sd_adtc, sd_none,
237     /* 32 */
238     sd_ac,   sd_ac,   sd_none, sd_none, sd_none, sd_none, sd_ac,   sd_none,
239     sd_none, sd_none, sd_bc,   sd_none, sd_none, sd_none, sd_none, sd_none,
240     /* 48 */
241     sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, sd_ac,
242     sd_adtc, sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, sd_none,
243 };
244 
245 static const int sd_cmd_class[SDMMC_CMD_MAX] = {
246     0,  0,  0,  0,  0,  9, 10,  0,  0,  0,  0,  1,  0,  0,  0,  0,
247     2,  2,  2,  2,  3,  3,  3,  3,  4,  4,  4,  4,  6,  6,  6,  6,
248     5,  5, 10, 10, 10, 10,  5,  9,  9,  9,  7,  7,  7,  7,  7,  7,
249     7,  7, 10,  7,  9,  9,  9,  8,  8, 10,  8,  8,  8,  8,  8,  8,
250 };
251 
252 static uint8_t sd_crc7(void *message, size_t width)
253 {
254     int i, bit;
255     uint8_t shift_reg = 0x00;
256     uint8_t *msg = (uint8_t *) message;
257 
258     for (i = 0; i < width; i ++, msg ++)
259         for (bit = 7; bit >= 0; bit --) {
260             shift_reg <<= 1;
261             if ((shift_reg >> 7) ^ ((*msg >> bit) & 1))
262                 shift_reg ^= 0x89;
263         }
264 
265     return shift_reg;
266 }
267 
268 static uint16_t sd_crc16(void *message, size_t width)
269 {
270     int i, bit;
271     uint16_t shift_reg = 0x0000;
272     uint16_t *msg = (uint16_t *) message;
273     width <<= 1;
274 
275     for (i = 0; i < width; i ++, msg ++)
276         for (bit = 15; bit >= 0; bit --) {
277             shift_reg <<= 1;
278             if ((shift_reg >> 15) ^ ((*msg >> bit) & 1))
279                 shift_reg ^= 0x1011;
280         }
281 
282     return shift_reg;
283 }
284 
285 #define OCR_POWER_DELAY_NS      500000 /* 0.5ms */
286 
287 FIELD(OCR, VDD_VOLTAGE_WINDOW,          0, 24)
288 FIELD(OCR, VDD_VOLTAGE_WIN_LO,          0,  8)
289 FIELD(OCR, DUAL_VOLTAGE_CARD,           7,  1)
290 FIELD(OCR, VDD_VOLTAGE_WIN_HI,          8, 16)
291 FIELD(OCR, ACCEPT_SWITCH_1V8,          24,  1) /* Only UHS-I */
292 FIELD(OCR, UHS_II_CARD,                29,  1) /* Only UHS-II */
293 FIELD(OCR, CARD_CAPACITY,              30,  1) /* 0:SDSC, 1:SDHC/SDXC */
294 FIELD(OCR, CARD_POWER_UP,              31,  1)
295 
296 #define ACMD41_ENQUIRY_MASK     0x00ffffff
297 #define ACMD41_R3_MASK          (R_OCR_VDD_VOLTAGE_WIN_HI_MASK \
298                                | R_OCR_ACCEPT_SWITCH_1V8_MASK \
299                                | R_OCR_UHS_II_CARD_MASK \
300                                | R_OCR_CARD_CAPACITY_MASK \
301                                | R_OCR_CARD_POWER_UP_MASK)
302 
303 static void sd_set_ocr(SDState *sd)
304 {
305     /* All voltages OK */
306     sd->ocr = R_OCR_VDD_VOLTAGE_WIN_HI_MASK;
307 }
308 
309 static void sd_ocr_powerup(void *opaque)
310 {
311     SDState *sd = opaque;
312 
313     trace_sdcard_powerup();
314     assert(!FIELD_EX32(sd->ocr, OCR, CARD_POWER_UP));
315 
316     /* card power-up OK */
317     sd->ocr = FIELD_DP32(sd->ocr, OCR, CARD_POWER_UP, 1);
318 
319     if (sd->size > SDSC_MAX_CAPACITY) {
320         sd->ocr = FIELD_DP32(sd->ocr, OCR, CARD_CAPACITY, 1);
321     }
322 }
323 
324 static void sd_set_scr(SDState *sd)
325 {
326     sd->scr[0] = 0 << 4;        /* SCR structure version 1.0 */
327     if (sd->spec_version == SD_PHY_SPECv1_10_VERS) {
328         sd->scr[0] |= 1;        /* Spec Version 1.10 */
329     } else {
330         sd->scr[0] |= 2;        /* Spec Version 2.00 or Version 3.0X */
331     }
332     sd->scr[1] = (2 << 4)       /* SDSC Card (Security Version 1.01) */
333                  | 0b0101;      /* 1-bit or 4-bit width bus modes */
334     sd->scr[2] = 0x00;          /* Extended Security is not supported. */
335     if (sd->spec_version >= SD_PHY_SPECv3_01_VERS) {
336         sd->scr[2] |= 1 << 7;   /* Spec Version 3.0X */
337     }
338     sd->scr[3] = 0x00;
339     /* reserved for manufacturer usage */
340     sd->scr[4] = 0x00;
341     sd->scr[5] = 0x00;
342     sd->scr[6] = 0x00;
343     sd->scr[7] = 0x00;
344 }
345 
346 #define MID	0xaa
347 #define OID	"XY"
348 #define PNM	"QEMU!"
349 #define PRV	0x01
350 #define MDT_YR	2006
351 #define MDT_MON	2
352 
353 static void sd_set_cid(SDState *sd)
354 {
355     sd->cid[0] = MID;		/* Fake card manufacturer ID (MID) */
356     sd->cid[1] = OID[0];	/* OEM/Application ID (OID) */
357     sd->cid[2] = OID[1];
358     sd->cid[3] = PNM[0];	/* Fake product name (PNM) */
359     sd->cid[4] = PNM[1];
360     sd->cid[5] = PNM[2];
361     sd->cid[6] = PNM[3];
362     sd->cid[7] = PNM[4];
363     sd->cid[8] = PRV;		/* Fake product revision (PRV) */
364     sd->cid[9] = 0xde;		/* Fake serial number (PSN) */
365     sd->cid[10] = 0xad;
366     sd->cid[11] = 0xbe;
367     sd->cid[12] = 0xef;
368     sd->cid[13] = 0x00 |	/* Manufacture date (MDT) */
369         ((MDT_YR - 2000) / 10);
370     sd->cid[14] = ((MDT_YR % 10) << 4) | MDT_MON;
371     sd->cid[15] = (sd_crc7(sd->cid, 15) << 1) | 1;
372 }
373 
374 #define HWBLOCK_SHIFT	9			/* 512 bytes */
375 #define SECTOR_SHIFT	5			/* 16 kilobytes */
376 #define WPGROUP_SHIFT	7			/* 2 megs */
377 #define CMULT_SHIFT	9			/* 512 times HWBLOCK_SIZE */
378 #define WPGROUP_SIZE	(1 << (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT))
379 
380 static const uint8_t sd_csd_rw_mask[16] = {
381     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
382     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xfe,
383 };
384 
385 static void sd_set_csd(SDState *sd, uint64_t size)
386 {
387     uint32_t csize = (size >> (CMULT_SHIFT + HWBLOCK_SHIFT)) - 1;
388     uint32_t sectsize = (1 << (SECTOR_SHIFT + 1)) - 1;
389     uint32_t wpsize = (1 << (WPGROUP_SHIFT + 1)) - 1;
390 
391     if (size <= SDSC_MAX_CAPACITY) { /* Standard Capacity SD */
392         sd->csd[0] = 0x00;	/* CSD structure */
393         sd->csd[1] = 0x26;	/* Data read access-time-1 */
394         sd->csd[2] = 0x00;	/* Data read access-time-2 */
395         sd->csd[3] = 0x32;      /* Max. data transfer rate: 25 MHz */
396         sd->csd[4] = 0x5f;	/* Card Command Classes */
397         sd->csd[5] = 0x50 |	/* Max. read data block length */
398             HWBLOCK_SHIFT;
399         sd->csd[6] = 0xe0 |	/* Partial block for read allowed */
400             ((csize >> 10) & 0x03);
401         sd->csd[7] = 0x00 |	/* Device size */
402             ((csize >> 2) & 0xff);
403         sd->csd[8] = 0x3f |	/* Max. read current */
404             ((csize << 6) & 0xc0);
405         sd->csd[9] = 0xfc |	/* Max. write current */
406             ((CMULT_SHIFT - 2) >> 1);
407         sd->csd[10] = 0x40 |	/* Erase sector size */
408             (((CMULT_SHIFT - 2) << 7) & 0x80) | (sectsize >> 1);
409         sd->csd[11] = 0x00 |	/* Write protect group size */
410             ((sectsize << 7) & 0x80) | wpsize;
411         sd->csd[12] = 0x90 |	/* Write speed factor */
412             (HWBLOCK_SHIFT >> 2);
413         sd->csd[13] = 0x20 |	/* Max. write data block length */
414             ((HWBLOCK_SHIFT << 6) & 0xc0);
415         sd->csd[14] = 0x00;	/* File format group */
416     } else {			/* SDHC */
417         size /= 512 * KiB;
418         size -= 1;
419         sd->csd[0] = 0x40;
420         sd->csd[1] = 0x0e;
421         sd->csd[2] = 0x00;
422         sd->csd[3] = 0x32;
423         sd->csd[4] = 0x5b;
424         sd->csd[5] = 0x59;
425         sd->csd[6] = 0x00;
426         sd->csd[7] = (size >> 16) & 0xff;
427         sd->csd[8] = (size >> 8) & 0xff;
428         sd->csd[9] = (size & 0xff);
429         sd->csd[10] = 0x7f;
430         sd->csd[11] = 0x80;
431         sd->csd[12] = 0x0a;
432         sd->csd[13] = 0x40;
433         sd->csd[14] = 0x00;
434     }
435     sd->csd[15] = (sd_crc7(sd->csd, 15) << 1) | 1;
436 }
437 
438 static void sd_set_rca(SDState *sd)
439 {
440     sd->rca += 0x4567;
441 }
442 
443 FIELD(CSR, AKE_SEQ_ERROR,               3,  1)
444 FIELD(CSR, APP_CMD,                     5,  1)
445 FIELD(CSR, FX_EVENT,                    6,  1)
446 FIELD(CSR, READY_FOR_DATA,              8,  1)
447 FIELD(CSR, CURRENT_STATE,               9,  4)
448 FIELD(CSR, ERASE_RESET,                13,  1)
449 FIELD(CSR, CARD_ECC_DISABLED,          14,  1)
450 FIELD(CSR, WP_ERASE_SKIP,              15,  1)
451 FIELD(CSR, CSD_OVERWRITE,              16,  1)
452 FIELD(CSR, DEFERRED_RESPONSE,          17,  1)
453 FIELD(CSR, ERROR,                      19,  1)
454 FIELD(CSR, CC_ERROR,                   20,  1)
455 FIELD(CSR, CARD_ECC_FAILED,            21,  1)
456 FIELD(CSR, ILLEGAL_COMMAND,            22,  1)
457 FIELD(CSR, COM_CRC_ERROR,              23,  1)
458 FIELD(CSR, LOCK_UNLOCK_FAILED,         24,  1)
459 FIELD(CSR, CARD_IS_LOCKED,             25,  1)
460 FIELD(CSR, WP_VIOLATION,               26,  1)
461 FIELD(CSR, ERASE_PARAM,                27,  1)
462 FIELD(CSR, ERASE_SEQ_ERROR,            28,  1)
463 FIELD(CSR, BLOCK_LEN_ERROR,            29,  1)
464 FIELD(CSR, ADDRESS_ERROR,              30,  1)
465 FIELD(CSR, OUT_OF_RANGE,               31,  1)
466 
467 /* Card status bits, split by clear condition:
468  * A : According to the card current state
469  * B : Always related to the previous command
470  * C : Cleared by read
471  */
472 #define CARD_STATUS_A           (R_CSR_READY_FOR_DATA_MASK \
473                                | R_CSR_CARD_ECC_DISABLED_MASK \
474                                | R_CSR_CARD_IS_LOCKED_MASK)
475 #define CARD_STATUS_B           (R_CSR_CURRENT_STATE_MASK \
476                                | R_CSR_ILLEGAL_COMMAND_MASK \
477                                | R_CSR_COM_CRC_ERROR_MASK)
478 #define CARD_STATUS_C           (R_CSR_AKE_SEQ_ERROR_MASK \
479                                | R_CSR_APP_CMD_MASK \
480                                | R_CSR_ERASE_RESET_MASK \
481                                | R_CSR_WP_ERASE_SKIP_MASK \
482                                | R_CSR_CSD_OVERWRITE_MASK \
483                                | R_CSR_ERROR_MASK \
484                                | R_CSR_CC_ERROR_MASK \
485                                | R_CSR_CARD_ECC_FAILED_MASK \
486                                | R_CSR_LOCK_UNLOCK_FAILED_MASK \
487                                | R_CSR_WP_VIOLATION_MASK \
488                                | R_CSR_ERASE_PARAM_MASK \
489                                | R_CSR_ERASE_SEQ_ERROR_MASK \
490                                | R_CSR_BLOCK_LEN_ERROR_MASK \
491                                | R_CSR_ADDRESS_ERROR_MASK \
492                                | R_CSR_OUT_OF_RANGE_MASK)
493 
494 static void sd_set_cardstatus(SDState *sd)
495 {
496     sd->card_status = 0x00000100;
497 }
498 
499 static void sd_set_sdstatus(SDState *sd)
500 {
501     memset(sd->sd_status, 0, 64);
502 }
503 
504 static int sd_req_crc_validate(SDRequest *req)
505 {
506     uint8_t buffer[5];
507     buffer[0] = 0x40 | req->cmd;
508     stl_be_p(&buffer[1], req->arg);
509     return 0;
510     return sd_crc7(buffer, 5) != req->crc;	/* TODO */
511 }
512 
513 static void sd_response_r1_make(SDState *sd, uint8_t *response)
514 {
515     stl_be_p(response, sd->card_status);
516 
517     /* Clear the "clear on read" status bits */
518     sd->card_status &= ~CARD_STATUS_C;
519 }
520 
521 static void sd_response_r3_make(SDState *sd, uint8_t *response)
522 {
523     stl_be_p(response, sd->ocr & ACMD41_R3_MASK);
524 }
525 
526 static void sd_response_r6_make(SDState *sd, uint8_t *response)
527 {
528     uint16_t status;
529 
530     status = ((sd->card_status >> 8) & 0xc000) |
531              ((sd->card_status >> 6) & 0x2000) |
532               (sd->card_status & 0x1fff);
533     sd->card_status &= ~(CARD_STATUS_C & 0xc81fff);
534     stw_be_p(response + 0, sd->rca);
535     stw_be_p(response + 2, status);
536 }
537 
538 static void sd_response_r7_make(SDState *sd, uint8_t *response)
539 {
540     stl_be_p(response, sd->vhs);
541 }
542 
543 static inline uint64_t sd_addr_to_wpnum(uint64_t addr)
544 {
545     return addr >> (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT);
546 }
547 
548 static void sd_reset(DeviceState *dev)
549 {
550     SDState *sd = SD_CARD(dev);
551     uint64_t size;
552     uint64_t sect;
553 
554     trace_sdcard_reset();
555     if (sd->blk) {
556         blk_get_geometry(sd->blk, &sect);
557     } else {
558         sect = 0;
559     }
560     size = sect << 9;
561 
562     sect = sd_addr_to_wpnum(size) + 1;
563 
564     sd->state = sd_idle_state;
565     sd->rca = 0x0000;
566     sd_set_ocr(sd);
567     sd_set_scr(sd);
568     sd_set_cid(sd);
569     sd_set_csd(sd, size);
570     sd_set_cardstatus(sd);
571     sd_set_sdstatus(sd);
572 
573     g_free(sd->wp_groups);
574     sd->wp_switch = sd->blk ? blk_is_read_only(sd->blk) : false;
575     sd->wpgrps_size = sect;
576     sd->wp_groups = bitmap_new(sd->wpgrps_size);
577     memset(sd->function_group, 0, sizeof(sd->function_group));
578     sd->erase_start = 0;
579     sd->erase_end = 0;
580     sd->size = size;
581     sd->blk_len = 0x200;
582     sd->pwd_len = 0;
583     sd->expecting_acmd = false;
584     sd->dat_lines = 0xf;
585     sd->cmd_line = true;
586     sd->multi_blk_cnt = 0;
587 }
588 
589 static bool sd_get_inserted(SDState *sd)
590 {
591     return sd->blk && blk_is_inserted(sd->blk);
592 }
593 
594 static bool sd_get_readonly(SDState *sd)
595 {
596     return sd->wp_switch;
597 }
598 
599 static void sd_cardchange(void *opaque, bool load, Error **errp)
600 {
601     SDState *sd = opaque;
602     DeviceState *dev = DEVICE(sd);
603     SDBus *sdbus;
604     bool inserted = sd_get_inserted(sd);
605     bool readonly = sd_get_readonly(sd);
606 
607     if (inserted) {
608         trace_sdcard_inserted(readonly);
609         sd_reset(dev);
610     } else {
611         trace_sdcard_ejected();
612     }
613 
614     if (sd->me_no_qdev_me_kill_mammoth_with_rocks) {
615         qemu_set_irq(sd->inserted_cb, inserted);
616         if (inserted) {
617             qemu_set_irq(sd->readonly_cb, readonly);
618         }
619     } else {
620         sdbus = SD_BUS(qdev_get_parent_bus(dev));
621         sdbus_set_inserted(sdbus, inserted);
622         if (inserted) {
623             sdbus_set_readonly(sdbus, readonly);
624         }
625     }
626 }
627 
628 static const BlockDevOps sd_block_ops = {
629     .change_media_cb = sd_cardchange,
630 };
631 
632 static bool sd_ocr_vmstate_needed(void *opaque)
633 {
634     SDState *sd = opaque;
635 
636     /* Include the OCR state (and timer) if it is not yet powered up */
637     return !FIELD_EX32(sd->ocr, OCR, CARD_POWER_UP);
638 }
639 
640 static const VMStateDescription sd_ocr_vmstate = {
641     .name = "sd-card/ocr-state",
642     .version_id = 1,
643     .minimum_version_id = 1,
644     .needed = sd_ocr_vmstate_needed,
645     .fields = (VMStateField[]) {
646         VMSTATE_UINT32(ocr, SDState),
647         VMSTATE_TIMER_PTR(ocr_power_timer, SDState),
648         VMSTATE_END_OF_LIST()
649     },
650 };
651 
652 static int sd_vmstate_pre_load(void *opaque)
653 {
654     SDState *sd = opaque;
655 
656     /* If the OCR state is not included (prior versions, or not
657      * needed), then the OCR must be set as powered up. If the OCR state
658      * is included, this will be replaced by the state restore.
659      */
660     sd_ocr_powerup(sd);
661 
662     return 0;
663 }
664 
665 static const VMStateDescription sd_vmstate = {
666     .name = "sd-card",
667     .version_id = 1,
668     .minimum_version_id = 1,
669     .pre_load = sd_vmstate_pre_load,
670     .fields = (VMStateField[]) {
671         VMSTATE_UINT32(mode, SDState),
672         VMSTATE_INT32(state, SDState),
673         VMSTATE_UINT8_ARRAY(cid, SDState, 16),
674         VMSTATE_UINT8_ARRAY(csd, SDState, 16),
675         VMSTATE_UINT16(rca, SDState),
676         VMSTATE_UINT32(card_status, SDState),
677         VMSTATE_PARTIAL_BUFFER(sd_status, SDState, 1),
678         VMSTATE_UINT32(vhs, SDState),
679         VMSTATE_BITMAP(wp_groups, SDState, 0, wpgrps_size),
680         VMSTATE_UINT32(blk_len, SDState),
681         VMSTATE_UINT32(multi_blk_cnt, SDState),
682         VMSTATE_UINT32(erase_start, SDState),
683         VMSTATE_UINT32(erase_end, SDState),
684         VMSTATE_UINT8_ARRAY(pwd, SDState, 16),
685         VMSTATE_UINT32(pwd_len, SDState),
686         VMSTATE_UINT8_ARRAY(function_group, SDState, 6),
687         VMSTATE_UINT8(current_cmd, SDState),
688         VMSTATE_BOOL(expecting_acmd, SDState),
689         VMSTATE_UINT32(blk_written, SDState),
690         VMSTATE_UINT64(data_start, SDState),
691         VMSTATE_UINT32(data_offset, SDState),
692         VMSTATE_UINT8_ARRAY(data, SDState, 512),
693         VMSTATE_UNUSED_V(1, 512),
694         VMSTATE_BOOL(enable, SDState),
695         VMSTATE_END_OF_LIST()
696     },
697     .subsections = (const VMStateDescription*[]) {
698         &sd_ocr_vmstate,
699         NULL
700     },
701 };
702 
703 /* Legacy initialization function for use by non-qdevified callers */
704 SDState *sd_init(BlockBackend *blk, bool is_spi)
705 {
706     Object *obj;
707     DeviceState *dev;
708     SDState *sd;
709     Error *err = NULL;
710 
711     obj = object_new(TYPE_SD_CARD);
712     dev = DEVICE(obj);
713     if (!qdev_prop_set_drive_err(dev, "drive", blk, &err)) {
714         error_reportf_err(err, "sd_init failed: ");
715         return NULL;
716     }
717     qdev_prop_set_bit(dev, "spi", is_spi);
718 
719     /*
720      * Realizing the device properly would put it into the QOM
721      * composition tree even though it is not plugged into an
722      * appropriate bus.  That's a no-no.  Hide the device from
723      * QOM/qdev, and call its qdev realize callback directly.
724      */
725     object_ref(obj);
726     object_unparent(obj);
727     sd_realize(dev, &err);
728     if (err) {
729         error_reportf_err(err, "sd_init failed: ");
730         return NULL;
731     }
732 
733     sd = SD_CARD(dev);
734     sd->me_no_qdev_me_kill_mammoth_with_rocks = true;
735     return sd;
736 }
737 
738 void sd_set_cb(SDState *sd, qemu_irq readonly, qemu_irq insert)
739 {
740     sd->readonly_cb = readonly;
741     sd->inserted_cb = insert;
742     qemu_set_irq(readonly, sd->blk ? blk_is_read_only(sd->blk) : 0);
743     qemu_set_irq(insert, sd->blk ? blk_is_inserted(sd->blk) : 0);
744 }
745 
746 static void sd_erase(SDState *sd)
747 {
748     int i;
749     uint64_t erase_start = sd->erase_start;
750     uint64_t erase_end = sd->erase_end;
751 
752     trace_sdcard_erase();
753     if (!sd->erase_start || !sd->erase_end) {
754         sd->card_status |= ERASE_SEQ_ERROR;
755         return;
756     }
757 
758     if (FIELD_EX32(sd->ocr, OCR, CARD_CAPACITY)) {
759         /* High capacity memory card: erase units are 512 byte blocks */
760         erase_start *= 512;
761         erase_end *= 512;
762     }
763 
764     erase_start = sd_addr_to_wpnum(erase_start);
765     erase_end = sd_addr_to_wpnum(erase_end);
766     sd->erase_start = 0;
767     sd->erase_end = 0;
768     sd->csd[14] |= 0x40;
769 
770     for (i = erase_start; i <= erase_end; i++) {
771         if (test_bit(i, sd->wp_groups)) {
772             sd->card_status |= WP_ERASE_SKIP;
773         }
774     }
775 }
776 
777 static uint32_t sd_wpbits(SDState *sd, uint64_t addr)
778 {
779     uint32_t i, wpnum;
780     uint32_t ret = 0;
781 
782     wpnum = sd_addr_to_wpnum(addr);
783 
784     for (i = 0; i < 32; i++, wpnum++, addr += WPGROUP_SIZE) {
785         if (addr < sd->size && test_bit(wpnum, sd->wp_groups)) {
786             ret |= (1 << i);
787         }
788     }
789 
790     return ret;
791 }
792 
793 static void sd_function_switch(SDState *sd, uint32_t arg)
794 {
795     int i, mode, new_func;
796     mode = !!(arg & 0x80000000);
797 
798     sd->data[0] = 0x00;		/* Maximum current consumption */
799     sd->data[1] = 0x01;
800     sd->data[2] = 0x80;		/* Supported group 6 functions */
801     sd->data[3] = 0x01;
802     sd->data[4] = 0x80;		/* Supported group 5 functions */
803     sd->data[5] = 0x01;
804     sd->data[6] = 0x80;		/* Supported group 4 functions */
805     sd->data[7] = 0x01;
806     sd->data[8] = 0x80;		/* Supported group 3 functions */
807     sd->data[9] = 0x01;
808     sd->data[10] = 0x80;	/* Supported group 2 functions */
809     sd->data[11] = 0x43;
810     sd->data[12] = 0x80;	/* Supported group 1 functions */
811     sd->data[13] = 0x03;
812 
813     for (i = 0; i < 6; i ++) {
814         new_func = (arg >> (i * 4)) & 0x0f;
815         if (mode && new_func != 0x0f)
816             sd->function_group[i] = new_func;
817         sd->data[16 - (i >> 1)] |= new_func << ((i % 2) * 4);
818     }
819     memset(&sd->data[17], 0, 47);
820     stw_be_p(sd->data + 64, sd_crc16(sd->data, 64));
821 }
822 
823 static inline bool sd_wp_addr(SDState *sd, uint64_t addr)
824 {
825     return test_bit(sd_addr_to_wpnum(addr), sd->wp_groups);
826 }
827 
828 static void sd_lock_command(SDState *sd)
829 {
830     int erase, lock, clr_pwd, set_pwd, pwd_len;
831     erase = !!(sd->data[0] & 0x08);
832     lock = sd->data[0] & 0x04;
833     clr_pwd = sd->data[0] & 0x02;
834     set_pwd = sd->data[0] & 0x01;
835 
836     if (sd->blk_len > 1)
837         pwd_len = sd->data[1];
838     else
839         pwd_len = 0;
840 
841     if (lock) {
842         trace_sdcard_lock();
843     } else {
844         trace_sdcard_unlock();
845     }
846     if (erase) {
847         if (!(sd->card_status & CARD_IS_LOCKED) || sd->blk_len > 1 ||
848                         set_pwd || clr_pwd || lock || sd->wp_switch ||
849                         (sd->csd[14] & 0x20)) {
850             sd->card_status |= LOCK_UNLOCK_FAILED;
851             return;
852         }
853         bitmap_zero(sd->wp_groups, sd->wpgrps_size);
854         sd->csd[14] &= ~0x10;
855         sd->card_status &= ~CARD_IS_LOCKED;
856         sd->pwd_len = 0;
857         /* Erasing the entire card here! */
858         fprintf(stderr, "SD: Card force-erased by CMD42\n");
859         return;
860     }
861 
862     if (sd->blk_len < 2 + pwd_len ||
863                     pwd_len <= sd->pwd_len ||
864                     pwd_len > sd->pwd_len + 16) {
865         sd->card_status |= LOCK_UNLOCK_FAILED;
866         return;
867     }
868 
869     if (sd->pwd_len && memcmp(sd->pwd, sd->data + 2, sd->pwd_len)) {
870         sd->card_status |= LOCK_UNLOCK_FAILED;
871         return;
872     }
873 
874     pwd_len -= sd->pwd_len;
875     if ((pwd_len && !set_pwd) ||
876                     (clr_pwd && (set_pwd || lock)) ||
877                     (lock && !sd->pwd_len && !set_pwd) ||
878                     (!set_pwd && !clr_pwd &&
879                      (((sd->card_status & CARD_IS_LOCKED) && lock) ||
880                       (!(sd->card_status & CARD_IS_LOCKED) && !lock)))) {
881         sd->card_status |= LOCK_UNLOCK_FAILED;
882         return;
883     }
884 
885     if (set_pwd) {
886         memcpy(sd->pwd, sd->data + 2 + sd->pwd_len, pwd_len);
887         sd->pwd_len = pwd_len;
888     }
889 
890     if (clr_pwd) {
891         sd->pwd_len = 0;
892     }
893 
894     if (lock)
895         sd->card_status |= CARD_IS_LOCKED;
896     else
897         sd->card_status &= ~CARD_IS_LOCKED;
898 }
899 
900 static sd_rsp_type_t sd_normal_command(SDState *sd, SDRequest req)
901 {
902     uint32_t rca = 0x0000;
903     uint64_t addr = (sd->ocr & (1 << 30)) ? (uint64_t) req.arg << 9 : req.arg;
904 
905     /* CMD55 precedes an ACMD, so we are not interested in tracing it.
906      * However there is no ACMD55, so we want to trace this particular case.
907      */
908     if (req.cmd != 55 || sd->expecting_acmd) {
909         trace_sdcard_normal_command(sd->proto_name,
910                                     sd_cmd_name(req.cmd), req.cmd,
911                                     req.arg, sd_state_name(sd->state));
912     }
913 
914     /* Not interpreting this as an app command */
915     sd->card_status &= ~APP_CMD;
916 
917     if (sd_cmd_type[req.cmd] == sd_ac
918         || sd_cmd_type[req.cmd] == sd_adtc) {
919         rca = req.arg >> 16;
920     }
921 
922     /* CMD23 (set block count) must be immediately followed by CMD18 or CMD25
923      * if not, its effects are cancelled */
924     if (sd->multi_blk_cnt != 0 && !(req.cmd == 18 || req.cmd == 25)) {
925         sd->multi_blk_cnt = 0;
926     }
927 
928     if (sd_cmd_class[req.cmd] == 6 && FIELD_EX32(sd->ocr, OCR, CARD_CAPACITY)) {
929         /* Only Standard Capacity cards support class 6 commands */
930         return sd_illegal;
931     }
932 
933     switch (req.cmd) {
934     /* Basic commands (Class 0 and Class 1) */
935     case 0:	/* CMD0:   GO_IDLE_STATE */
936         switch (sd->state) {
937         case sd_inactive_state:
938             return sd->spi ? sd_r1 : sd_r0;
939 
940         default:
941             sd->state = sd_idle_state;
942             sd_reset(DEVICE(sd));
943             return sd->spi ? sd_r1 : sd_r0;
944         }
945         break;
946 
947     case 1:	/* CMD1:   SEND_OP_CMD */
948         if (!sd->spi)
949             goto bad_cmd;
950 
951         sd->state = sd_transfer_state;
952         return sd_r1;
953 
954     case 2:	/* CMD2:   ALL_SEND_CID */
955         if (sd->spi)
956             goto bad_cmd;
957         switch (sd->state) {
958         case sd_ready_state:
959             sd->state = sd_identification_state;
960             return sd_r2_i;
961 
962         default:
963             break;
964         }
965         break;
966 
967     case 3:	/* CMD3:   SEND_RELATIVE_ADDR */
968         if (sd->spi)
969             goto bad_cmd;
970         switch (sd->state) {
971         case sd_identification_state:
972         case sd_standby_state:
973             sd->state = sd_standby_state;
974             sd_set_rca(sd);
975             return sd_r6;
976 
977         default:
978             break;
979         }
980         break;
981 
982     case 4:	/* CMD4:   SEND_DSR */
983         if (sd->spi)
984             goto bad_cmd;
985         switch (sd->state) {
986         case sd_standby_state:
987             break;
988 
989         default:
990             break;
991         }
992         break;
993 
994     case 5: /* CMD5: reserved for SDIO cards */
995         return sd_illegal;
996 
997     case 6:	/* CMD6:   SWITCH_FUNCTION */
998         switch (sd->mode) {
999         case sd_data_transfer_mode:
1000             sd_function_switch(sd, req.arg);
1001             sd->state = sd_sendingdata_state;
1002             sd->data_start = 0;
1003             sd->data_offset = 0;
1004             return sd_r1;
1005 
1006         default:
1007             break;
1008         }
1009         break;
1010 
1011     case 7:	/* CMD7:   SELECT/DESELECT_CARD */
1012         if (sd->spi)
1013             goto bad_cmd;
1014         switch (sd->state) {
1015         case sd_standby_state:
1016             if (sd->rca != rca)
1017                 return sd_r0;
1018 
1019             sd->state = sd_transfer_state;
1020             return sd_r1b;
1021 
1022         case sd_transfer_state:
1023         case sd_sendingdata_state:
1024             if (sd->rca == rca)
1025                 break;
1026 
1027             sd->state = sd_standby_state;
1028             return sd_r1b;
1029 
1030         case sd_disconnect_state:
1031             if (sd->rca != rca)
1032                 return sd_r0;
1033 
1034             sd->state = sd_programming_state;
1035             return sd_r1b;
1036 
1037         case sd_programming_state:
1038             if (sd->rca == rca)
1039                 break;
1040 
1041             sd->state = sd_disconnect_state;
1042             return sd_r1b;
1043 
1044         default:
1045             break;
1046         }
1047         break;
1048 
1049     case 8:	/* CMD8:   SEND_IF_COND */
1050         if (sd->spec_version < SD_PHY_SPECv2_00_VERS) {
1051             break;
1052         }
1053         if (sd->state != sd_idle_state) {
1054             break;
1055         }
1056         sd->vhs = 0;
1057 
1058         /* No response if not exactly one VHS bit is set.  */
1059         if (!(req.arg >> 8) || (req.arg >> (ctz32(req.arg & ~0xff) + 1))) {
1060             return sd->spi ? sd_r7 : sd_r0;
1061         }
1062 
1063         /* Accept.  */
1064         sd->vhs = req.arg;
1065         return sd_r7;
1066 
1067     case 9:	/* CMD9:   SEND_CSD */
1068         switch (sd->state) {
1069         case sd_standby_state:
1070             if (sd->rca != rca)
1071                 return sd_r0;
1072 
1073             return sd_r2_s;
1074 
1075         case sd_transfer_state:
1076             if (!sd->spi)
1077                 break;
1078             sd->state = sd_sendingdata_state;
1079             memcpy(sd->data, sd->csd, 16);
1080             sd->data_start = addr;
1081             sd->data_offset = 0;
1082             return sd_r1;
1083 
1084         default:
1085             break;
1086         }
1087         break;
1088 
1089     case 10:	/* CMD10:  SEND_CID */
1090         switch (sd->state) {
1091         case sd_standby_state:
1092             if (sd->rca != rca)
1093                 return sd_r0;
1094 
1095             return sd_r2_i;
1096 
1097         case sd_transfer_state:
1098             if (!sd->spi)
1099                 break;
1100             sd->state = sd_sendingdata_state;
1101             memcpy(sd->data, sd->cid, 16);
1102             sd->data_start = addr;
1103             sd->data_offset = 0;
1104             return sd_r1;
1105 
1106         default:
1107             break;
1108         }
1109         break;
1110 
1111     case 12:	/* CMD12:  STOP_TRANSMISSION */
1112         switch (sd->state) {
1113         case sd_sendingdata_state:
1114             sd->state = sd_transfer_state;
1115             return sd_r1b;
1116 
1117         case sd_receivingdata_state:
1118             sd->state = sd_programming_state;
1119             /* Bzzzzzzztt .... Operation complete.  */
1120             sd->state = sd_transfer_state;
1121             return sd_r1b;
1122 
1123         default:
1124             break;
1125         }
1126         break;
1127 
1128     case 13:	/* CMD13:  SEND_STATUS */
1129         switch (sd->mode) {
1130         case sd_data_transfer_mode:
1131             if (sd->rca != rca)
1132                 return sd_r0;
1133 
1134             return sd_r1;
1135 
1136         default:
1137             break;
1138         }
1139         break;
1140 
1141     case 15:	/* CMD15:  GO_INACTIVE_STATE */
1142         if (sd->spi)
1143             goto bad_cmd;
1144         switch (sd->mode) {
1145         case sd_data_transfer_mode:
1146             if (sd->rca != rca)
1147                 return sd_r0;
1148 
1149             sd->state = sd_inactive_state;
1150             return sd_r0;
1151 
1152         default:
1153             break;
1154         }
1155         break;
1156 
1157     /* Block read commands (Classs 2) */
1158     case 16:	/* CMD16:  SET_BLOCKLEN */
1159         switch (sd->state) {
1160         case sd_transfer_state:
1161             if (req.arg > (1 << HWBLOCK_SHIFT)) {
1162                 sd->card_status |= BLOCK_LEN_ERROR;
1163             } else {
1164                 trace_sdcard_set_blocklen(req.arg);
1165                 sd->blk_len = req.arg;
1166             }
1167 
1168             return sd_r1;
1169 
1170         default:
1171             break;
1172         }
1173         break;
1174 
1175     case 17:	/* CMD17:  READ_SINGLE_BLOCK */
1176         switch (sd->state) {
1177         case sd_transfer_state:
1178 
1179             if (addr + sd->blk_len > sd->size) {
1180                 sd->card_status |= ADDRESS_ERROR;
1181                 return sd_r1;
1182             }
1183 
1184             sd->state = sd_sendingdata_state;
1185             sd->data_start = addr;
1186             sd->data_offset = 0;
1187             return sd_r1;
1188 
1189         default:
1190             break;
1191         }
1192         break;
1193 
1194     case 18:	/* CMD18:  READ_MULTIPLE_BLOCK */
1195         switch (sd->state) {
1196         case sd_transfer_state:
1197 
1198             if (addr + sd->blk_len > sd->size) {
1199                 sd->card_status |= ADDRESS_ERROR;
1200                 return sd_r1;
1201             }
1202 
1203             sd->state = sd_sendingdata_state;
1204             sd->data_start = addr;
1205             sd->data_offset = 0;
1206             return sd_r1;
1207 
1208         default:
1209             break;
1210         }
1211         break;
1212 
1213     case 19:    /* CMD19: SEND_TUNING_BLOCK (SD) */
1214         if (sd->spec_version < SD_PHY_SPECv3_01_VERS) {
1215             break;
1216         }
1217         if (sd->state == sd_transfer_state) {
1218             sd->state = sd_sendingdata_state;
1219             sd->data_offset = 0;
1220             return sd_r1;
1221         }
1222         break;
1223 
1224     case 23:    /* CMD23: SET_BLOCK_COUNT */
1225         if (sd->spec_version < SD_PHY_SPECv3_01_VERS) {
1226             break;
1227         }
1228         switch (sd->state) {
1229         case sd_transfer_state:
1230             sd->multi_blk_cnt = req.arg;
1231             return sd_r1;
1232 
1233         default:
1234             break;
1235         }
1236         break;
1237 
1238     /* Block write commands (Class 4) */
1239     case 24:	/* CMD24:  WRITE_SINGLE_BLOCK */
1240         switch (sd->state) {
1241         case sd_transfer_state:
1242             /* Writing in SPI mode not implemented.  */
1243             if (sd->spi)
1244                 break;
1245 
1246             if (addr + sd->blk_len > sd->size) {
1247                 sd->card_status |= ADDRESS_ERROR;
1248                 return sd_r1;
1249             }
1250 
1251             sd->state = sd_receivingdata_state;
1252             sd->data_start = addr;
1253             sd->data_offset = 0;
1254             sd->blk_written = 0;
1255 
1256             if (sd_wp_addr(sd, sd->data_start)) {
1257                 sd->card_status |= WP_VIOLATION;
1258             }
1259             if (sd->csd[14] & 0x30) {
1260                 sd->card_status |= WP_VIOLATION;
1261             }
1262             return sd_r1;
1263 
1264         default:
1265             break;
1266         }
1267         break;
1268 
1269     case 25:	/* CMD25:  WRITE_MULTIPLE_BLOCK */
1270         switch (sd->state) {
1271         case sd_transfer_state:
1272             /* Writing in SPI mode not implemented.  */
1273             if (sd->spi)
1274                 break;
1275 
1276             if (addr + sd->blk_len > sd->size) {
1277                 sd->card_status |= ADDRESS_ERROR;
1278                 return sd_r1;
1279             }
1280 
1281             sd->state = sd_receivingdata_state;
1282             sd->data_start = addr;
1283             sd->data_offset = 0;
1284             sd->blk_written = 0;
1285 
1286             if (sd_wp_addr(sd, sd->data_start)) {
1287                 sd->card_status |= WP_VIOLATION;
1288             }
1289             if (sd->csd[14] & 0x30) {
1290                 sd->card_status |= WP_VIOLATION;
1291             }
1292             return sd_r1;
1293 
1294         default:
1295             break;
1296         }
1297         break;
1298 
1299     case 26:	/* CMD26:  PROGRAM_CID */
1300         if (sd->spi)
1301             goto bad_cmd;
1302         switch (sd->state) {
1303         case sd_transfer_state:
1304             sd->state = sd_receivingdata_state;
1305             sd->data_start = 0;
1306             sd->data_offset = 0;
1307             return sd_r1;
1308 
1309         default:
1310             break;
1311         }
1312         break;
1313 
1314     case 27:	/* CMD27:  PROGRAM_CSD */
1315         switch (sd->state) {
1316         case sd_transfer_state:
1317             sd->state = sd_receivingdata_state;
1318             sd->data_start = 0;
1319             sd->data_offset = 0;
1320             return sd_r1;
1321 
1322         default:
1323             break;
1324         }
1325         break;
1326 
1327     /* Write protection (Class 6) */
1328     case 28:	/* CMD28:  SET_WRITE_PROT */
1329         switch (sd->state) {
1330         case sd_transfer_state:
1331             if (addr >= sd->size) {
1332                 sd->card_status |= ADDRESS_ERROR;
1333                 return sd_r1b;
1334             }
1335 
1336             sd->state = sd_programming_state;
1337             set_bit(sd_addr_to_wpnum(addr), sd->wp_groups);
1338             /* Bzzzzzzztt .... Operation complete.  */
1339             sd->state = sd_transfer_state;
1340             return sd_r1b;
1341 
1342         default:
1343             break;
1344         }
1345         break;
1346 
1347     case 29:	/* CMD29:  CLR_WRITE_PROT */
1348         switch (sd->state) {
1349         case sd_transfer_state:
1350             if (addr >= sd->size) {
1351                 sd->card_status |= ADDRESS_ERROR;
1352                 return sd_r1b;
1353             }
1354 
1355             sd->state = sd_programming_state;
1356             clear_bit(sd_addr_to_wpnum(addr), sd->wp_groups);
1357             /* Bzzzzzzztt .... Operation complete.  */
1358             sd->state = sd_transfer_state;
1359             return sd_r1b;
1360 
1361         default:
1362             break;
1363         }
1364         break;
1365 
1366     case 30:	/* CMD30:  SEND_WRITE_PROT */
1367         switch (sd->state) {
1368         case sd_transfer_state:
1369             sd->state = sd_sendingdata_state;
1370             *(uint32_t *) sd->data = sd_wpbits(sd, req.arg);
1371             sd->data_start = addr;
1372             sd->data_offset = 0;
1373             return sd_r1b;
1374 
1375         default:
1376             break;
1377         }
1378         break;
1379 
1380     /* Erase commands (Class 5) */
1381     case 32:	/* CMD32:  ERASE_WR_BLK_START */
1382         switch (sd->state) {
1383         case sd_transfer_state:
1384             sd->erase_start = req.arg;
1385             return sd_r1;
1386 
1387         default:
1388             break;
1389         }
1390         break;
1391 
1392     case 33:	/* CMD33:  ERASE_WR_BLK_END */
1393         switch (sd->state) {
1394         case sd_transfer_state:
1395             sd->erase_end = req.arg;
1396             return sd_r1;
1397 
1398         default:
1399             break;
1400         }
1401         break;
1402 
1403     case 38:	/* CMD38:  ERASE */
1404         switch (sd->state) {
1405         case sd_transfer_state:
1406             if (sd->csd[14] & 0x30) {
1407                 sd->card_status |= WP_VIOLATION;
1408                 return sd_r1b;
1409             }
1410 
1411             sd->state = sd_programming_state;
1412             sd_erase(sd);
1413             /* Bzzzzzzztt .... Operation complete.  */
1414             sd->state = sd_transfer_state;
1415             return sd_r1b;
1416 
1417         default:
1418             break;
1419         }
1420         break;
1421 
1422     /* Lock card commands (Class 7) */
1423     case 42:	/* CMD42:  LOCK_UNLOCK */
1424         switch (sd->state) {
1425         case sd_transfer_state:
1426             sd->state = sd_receivingdata_state;
1427             sd->data_start = 0;
1428             sd->data_offset = 0;
1429             return sd_r1;
1430 
1431         default:
1432             break;
1433         }
1434         break;
1435 
1436     case 52 ... 54:
1437         /* CMD52, CMD53, CMD54: reserved for SDIO cards
1438          * (see the SDIO Simplified Specification V2.0)
1439          * Handle as illegal command but do not complain
1440          * on stderr, as some OSes may use these in their
1441          * probing for presence of an SDIO card.
1442          */
1443         return sd_illegal;
1444 
1445     /* Application specific commands (Class 8) */
1446     case 55:	/* CMD55:  APP_CMD */
1447         switch (sd->state) {
1448         case sd_ready_state:
1449         case sd_identification_state:
1450         case sd_inactive_state:
1451             return sd_illegal;
1452         case sd_idle_state:
1453             if (rca) {
1454                 qemu_log_mask(LOG_GUEST_ERROR,
1455                               "SD: illegal RCA 0x%04x for APP_CMD\n", req.cmd);
1456             }
1457         default:
1458             break;
1459         }
1460         if (!sd->spi) {
1461             if (sd->rca != rca) {
1462                 return sd_r0;
1463             }
1464         }
1465         sd->expecting_acmd = true;
1466         sd->card_status |= APP_CMD;
1467         return sd_r1;
1468 
1469     case 56:	/* CMD56:  GEN_CMD */
1470         switch (sd->state) {
1471         case sd_transfer_state:
1472             sd->data_offset = 0;
1473             if (req.arg & 1)
1474                 sd->state = sd_sendingdata_state;
1475             else
1476                 sd->state = sd_receivingdata_state;
1477             return sd_r1;
1478 
1479         default:
1480             break;
1481         }
1482         break;
1483 
1484     case 58:    /* CMD58:   READ_OCR (SPI) */
1485         if (!sd->spi) {
1486             goto bad_cmd;
1487         }
1488         return sd_r3;
1489 
1490     case 59:    /* CMD59:   CRC_ON_OFF (SPI) */
1491         if (!sd->spi) {
1492             goto bad_cmd;
1493         }
1494         goto unimplemented_spi_cmd;
1495 
1496     default:
1497     bad_cmd:
1498         qemu_log_mask(LOG_GUEST_ERROR, "SD: Unknown CMD%i\n", req.cmd);
1499         return sd_illegal;
1500 
1501     unimplemented_spi_cmd:
1502         /* Commands that are recognised but not yet implemented in SPI mode.  */
1503         qemu_log_mask(LOG_UNIMP, "SD: CMD%i not implemented in SPI mode\n",
1504                       req.cmd);
1505         return sd_illegal;
1506     }
1507 
1508     qemu_log_mask(LOG_GUEST_ERROR, "SD: CMD%i in a wrong state\n", req.cmd);
1509     return sd_illegal;
1510 }
1511 
1512 static sd_rsp_type_t sd_app_command(SDState *sd,
1513                                     SDRequest req)
1514 {
1515     trace_sdcard_app_command(sd->proto_name, sd_acmd_name(req.cmd),
1516                              req.cmd, req.arg, sd_state_name(sd->state));
1517     sd->card_status |= APP_CMD;
1518     switch (req.cmd) {
1519     case 6:	/* ACMD6:  SET_BUS_WIDTH */
1520         if (sd->spi) {
1521             goto unimplemented_spi_cmd;
1522         }
1523         switch (sd->state) {
1524         case sd_transfer_state:
1525             sd->sd_status[0] &= 0x3f;
1526             sd->sd_status[0] |= (req.arg & 0x03) << 6;
1527             return sd_r1;
1528 
1529         default:
1530             break;
1531         }
1532         break;
1533 
1534     case 13:	/* ACMD13: SD_STATUS */
1535         switch (sd->state) {
1536         case sd_transfer_state:
1537             sd->state = sd_sendingdata_state;
1538             sd->data_start = 0;
1539             sd->data_offset = 0;
1540             return sd_r1;
1541 
1542         default:
1543             break;
1544         }
1545         break;
1546 
1547     case 22:	/* ACMD22: SEND_NUM_WR_BLOCKS */
1548         switch (sd->state) {
1549         case sd_transfer_state:
1550             *(uint32_t *) sd->data = sd->blk_written;
1551 
1552             sd->state = sd_sendingdata_state;
1553             sd->data_start = 0;
1554             sd->data_offset = 0;
1555             return sd_r1;
1556 
1557         default:
1558             break;
1559         }
1560         break;
1561 
1562     case 23:	/* ACMD23: SET_WR_BLK_ERASE_COUNT */
1563         switch (sd->state) {
1564         case sd_transfer_state:
1565             return sd_r1;
1566 
1567         default:
1568             break;
1569         }
1570         break;
1571 
1572     case 41:	/* ACMD41: SD_APP_OP_COND */
1573         if (sd->spi) {
1574             /* SEND_OP_CMD */
1575             sd->state = sd_transfer_state;
1576             return sd_r1;
1577         }
1578         if (sd->state != sd_idle_state) {
1579             break;
1580         }
1581         /* If it's the first ACMD41 since reset, we need to decide
1582          * whether to power up. If this is not an enquiry ACMD41,
1583          * we immediately report power on and proceed below to the
1584          * ready state, but if it is, we set a timer to model a
1585          * delay for power up. This works around a bug in EDK2
1586          * UEFI, which sends an initial enquiry ACMD41, but
1587          * assumes that the card is in ready state as soon as it
1588          * sees the power up bit set. */
1589         if (!FIELD_EX32(sd->ocr, OCR, CARD_POWER_UP)) {
1590             if ((req.arg & ACMD41_ENQUIRY_MASK) != 0) {
1591                 timer_del(sd->ocr_power_timer);
1592                 sd_ocr_powerup(sd);
1593             } else {
1594                 trace_sdcard_inquiry_cmd41();
1595                 if (!timer_pending(sd->ocr_power_timer)) {
1596                     timer_mod_ns(sd->ocr_power_timer,
1597                                  (qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL)
1598                                   + OCR_POWER_DELAY_NS));
1599                 }
1600             }
1601         }
1602 
1603         if (FIELD_EX32(sd->ocr & req.arg, OCR, VDD_VOLTAGE_WINDOW)) {
1604             /* We accept any voltage.  10000 V is nothing.
1605              *
1606              * Once we're powered up, we advance straight to ready state
1607              * unless it's an enquiry ACMD41 (bits 23:0 == 0).
1608              */
1609             sd->state = sd_ready_state;
1610         }
1611 
1612         return sd_r3;
1613 
1614     case 42:	/* ACMD42: SET_CLR_CARD_DETECT */
1615         switch (sd->state) {
1616         case sd_transfer_state:
1617             /* Bringing in the 50KOhm pull-up resistor... Done.  */
1618             return sd_r1;
1619 
1620         default:
1621             break;
1622         }
1623         break;
1624 
1625     case 51:	/* ACMD51: SEND_SCR */
1626         switch (sd->state) {
1627         case sd_transfer_state:
1628             sd->state = sd_sendingdata_state;
1629             sd->data_start = 0;
1630             sd->data_offset = 0;
1631             return sd_r1;
1632 
1633         default:
1634             break;
1635         }
1636         break;
1637 
1638     case 18:    /* Reserved for SD security applications */
1639     case 25:
1640     case 26:
1641     case 38:
1642     case 43 ... 49:
1643         /* Refer to the "SD Specifications Part3 Security Specification" for
1644          * information about the SD Security Features.
1645          */
1646         qemu_log_mask(LOG_UNIMP, "SD: CMD%i Security not implemented\n",
1647                       req.cmd);
1648         return sd_illegal;
1649 
1650     default:
1651         /* Fall back to standard commands.  */
1652         return sd_normal_command(sd, req);
1653 
1654     unimplemented_spi_cmd:
1655         /* Commands that are recognised but not yet implemented in SPI mode.  */
1656         qemu_log_mask(LOG_UNIMP, "SD: CMD%i not implemented in SPI mode\n",
1657                       req.cmd);
1658         return sd_illegal;
1659     }
1660 
1661     qemu_log_mask(LOG_GUEST_ERROR, "SD: ACMD%i in a wrong state\n", req.cmd);
1662     return sd_illegal;
1663 }
1664 
1665 static int cmd_valid_while_locked(SDState *sd, SDRequest *req)
1666 {
1667     /* Valid commands in locked state:
1668      * basic class (0)
1669      * lock card class (7)
1670      * CMD16
1671      * implicitly, the ACMD prefix CMD55
1672      * ACMD41 and ACMD42
1673      * Anything else provokes an "illegal command" response.
1674      */
1675     if (sd->expecting_acmd) {
1676         return req->cmd == 41 || req->cmd == 42;
1677     }
1678     if (req->cmd == 16 || req->cmd == 55) {
1679         return 1;
1680     }
1681     return sd_cmd_class[req->cmd] == 0
1682             || sd_cmd_class[req->cmd] == 7;
1683 }
1684 
1685 int sd_do_command(SDState *sd, SDRequest *req,
1686                   uint8_t *response) {
1687     int last_state;
1688     sd_rsp_type_t rtype;
1689     int rsplen;
1690 
1691     if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable) {
1692         return 0;
1693     }
1694 
1695     if (sd_req_crc_validate(req)) {
1696         sd->card_status |= COM_CRC_ERROR;
1697         rtype = sd_illegal;
1698         goto send_response;
1699     }
1700 
1701     if (req->cmd >= SDMMC_CMD_MAX) {
1702         qemu_log_mask(LOG_GUEST_ERROR, "SD: incorrect command 0x%02x\n",
1703                       req->cmd);
1704         req->cmd &= 0x3f;
1705     }
1706 
1707     if (sd->card_status & CARD_IS_LOCKED) {
1708         if (!cmd_valid_while_locked(sd, req)) {
1709             sd->card_status |= ILLEGAL_COMMAND;
1710             sd->expecting_acmd = false;
1711             qemu_log_mask(LOG_GUEST_ERROR, "SD: Card is locked\n");
1712             rtype = sd_illegal;
1713             goto send_response;
1714         }
1715     }
1716 
1717     last_state = sd->state;
1718     sd_set_mode(sd);
1719 
1720     if (sd->expecting_acmd) {
1721         sd->expecting_acmd = false;
1722         rtype = sd_app_command(sd, *req);
1723     } else {
1724         rtype = sd_normal_command(sd, *req);
1725     }
1726 
1727     if (rtype == sd_illegal) {
1728         sd->card_status |= ILLEGAL_COMMAND;
1729     } else {
1730         /* Valid command, we can update the 'state before command' bits.
1731          * (Do this now so they appear in r1 responses.)
1732          */
1733         sd->current_cmd = req->cmd;
1734         sd->card_status &= ~CURRENT_STATE;
1735         sd->card_status |= (last_state << 9);
1736     }
1737 
1738 send_response:
1739     switch (rtype) {
1740     case sd_r1:
1741     case sd_r1b:
1742         sd_response_r1_make(sd, response);
1743         rsplen = 4;
1744         break;
1745 
1746     case sd_r2_i:
1747         memcpy(response, sd->cid, sizeof(sd->cid));
1748         rsplen = 16;
1749         break;
1750 
1751     case sd_r2_s:
1752         memcpy(response, sd->csd, sizeof(sd->csd));
1753         rsplen = 16;
1754         break;
1755 
1756     case sd_r3:
1757         sd_response_r3_make(sd, response);
1758         rsplen = 4;
1759         break;
1760 
1761     case sd_r6:
1762         sd_response_r6_make(sd, response);
1763         rsplen = 4;
1764         break;
1765 
1766     case sd_r7:
1767         sd_response_r7_make(sd, response);
1768         rsplen = 4;
1769         break;
1770 
1771     case sd_r0:
1772     case sd_illegal:
1773         rsplen = 0;
1774         break;
1775     default:
1776         g_assert_not_reached();
1777     }
1778     trace_sdcard_response(sd_response_name(rtype), rsplen);
1779 
1780     if (rtype != sd_illegal) {
1781         /* Clear the "clear on valid command" status bits now we've
1782          * sent any response
1783          */
1784         sd->card_status &= ~CARD_STATUS_B;
1785     }
1786 
1787 #ifdef DEBUG_SD
1788     qemu_hexdump(stderr, "Response", response, rsplen);
1789 #endif
1790 
1791     return rsplen;
1792 }
1793 
1794 static void sd_blk_read(SDState *sd, uint64_t addr, uint32_t len)
1795 {
1796     trace_sdcard_read_block(addr, len);
1797     if (!sd->blk || blk_pread(sd->blk, addr, sd->data, len) < 0) {
1798         fprintf(stderr, "sd_blk_read: read error on host side\n");
1799     }
1800 }
1801 
1802 static void sd_blk_write(SDState *sd, uint64_t addr, uint32_t len)
1803 {
1804     trace_sdcard_write_block(addr, len);
1805     if (!sd->blk || blk_pwrite(sd->blk, addr, sd->data, len, 0) < 0) {
1806         fprintf(stderr, "sd_blk_write: write error on host side\n");
1807     }
1808 }
1809 
1810 #define BLK_READ_BLOCK(a, len)	sd_blk_read(sd, a, len)
1811 #define BLK_WRITE_BLOCK(a, len)	sd_blk_write(sd, a, len)
1812 #define APP_READ_BLOCK(a, len)	memset(sd->data, 0xec, len)
1813 #define APP_WRITE_BLOCK(a, len)
1814 
1815 void sd_write_byte(SDState *sd, uint8_t value)
1816 {
1817     int i;
1818 
1819     if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable)
1820         return;
1821 
1822     if (sd->state != sd_receivingdata_state) {
1823         qemu_log_mask(LOG_GUEST_ERROR,
1824                       "%s: not in Receiving-Data state\n", __func__);
1825         return;
1826     }
1827 
1828     if (sd->card_status & (ADDRESS_ERROR | WP_VIOLATION))
1829         return;
1830 
1831     trace_sdcard_write_data(sd->proto_name,
1832                             sd_acmd_name(sd->current_cmd),
1833                             sd->current_cmd, value);
1834     switch (sd->current_cmd) {
1835     case 24:	/* CMD24:  WRITE_SINGLE_BLOCK */
1836         sd->data[sd->data_offset ++] = value;
1837         if (sd->data_offset >= sd->blk_len) {
1838             /* TODO: Check CRC before committing */
1839             sd->state = sd_programming_state;
1840             BLK_WRITE_BLOCK(sd->data_start, sd->data_offset);
1841             sd->blk_written ++;
1842             sd->csd[14] |= 0x40;
1843             /* Bzzzzzzztt .... Operation complete.  */
1844             sd->state = sd_transfer_state;
1845         }
1846         break;
1847 
1848     case 25:	/* CMD25:  WRITE_MULTIPLE_BLOCK */
1849         if (sd->data_offset == 0) {
1850             /* Start of the block - let's check the address is valid */
1851             if (sd->data_start + sd->blk_len > sd->size) {
1852                 sd->card_status |= ADDRESS_ERROR;
1853                 break;
1854             }
1855             if (sd_wp_addr(sd, sd->data_start)) {
1856                 sd->card_status |= WP_VIOLATION;
1857                 break;
1858             }
1859         }
1860         sd->data[sd->data_offset++] = value;
1861         if (sd->data_offset >= sd->blk_len) {
1862             /* TODO: Check CRC before committing */
1863             sd->state = sd_programming_state;
1864             BLK_WRITE_BLOCK(sd->data_start, sd->data_offset);
1865             sd->blk_written++;
1866             sd->data_start += sd->blk_len;
1867             sd->data_offset = 0;
1868             sd->csd[14] |= 0x40;
1869 
1870             /* Bzzzzzzztt .... Operation complete.  */
1871             if (sd->multi_blk_cnt != 0) {
1872                 if (--sd->multi_blk_cnt == 0) {
1873                     /* Stop! */
1874                     sd->state = sd_transfer_state;
1875                     break;
1876                 }
1877             }
1878 
1879             sd->state = sd_receivingdata_state;
1880         }
1881         break;
1882 
1883     case 26:	/* CMD26:  PROGRAM_CID */
1884         sd->data[sd->data_offset ++] = value;
1885         if (sd->data_offset >= sizeof(sd->cid)) {
1886             /* TODO: Check CRC before committing */
1887             sd->state = sd_programming_state;
1888             for (i = 0; i < sizeof(sd->cid); i ++)
1889                 if ((sd->cid[i] | 0x00) != sd->data[i])
1890                     sd->card_status |= CID_CSD_OVERWRITE;
1891 
1892             if (!(sd->card_status & CID_CSD_OVERWRITE))
1893                 for (i = 0; i < sizeof(sd->cid); i ++) {
1894                     sd->cid[i] |= 0x00;
1895                     sd->cid[i] &= sd->data[i];
1896                 }
1897             /* Bzzzzzzztt .... Operation complete.  */
1898             sd->state = sd_transfer_state;
1899         }
1900         break;
1901 
1902     case 27:	/* CMD27:  PROGRAM_CSD */
1903         sd->data[sd->data_offset ++] = value;
1904         if (sd->data_offset >= sizeof(sd->csd)) {
1905             /* TODO: Check CRC before committing */
1906             sd->state = sd_programming_state;
1907             for (i = 0; i < sizeof(sd->csd); i ++)
1908                 if ((sd->csd[i] | sd_csd_rw_mask[i]) !=
1909                     (sd->data[i] | sd_csd_rw_mask[i]))
1910                     sd->card_status |= CID_CSD_OVERWRITE;
1911 
1912             /* Copy flag (OTP) & Permanent write protect */
1913             if (sd->csd[14] & ~sd->data[14] & 0x60)
1914                 sd->card_status |= CID_CSD_OVERWRITE;
1915 
1916             if (!(sd->card_status & CID_CSD_OVERWRITE))
1917                 for (i = 0; i < sizeof(sd->csd); i ++) {
1918                     sd->csd[i] |= sd_csd_rw_mask[i];
1919                     sd->csd[i] &= sd->data[i];
1920                 }
1921             /* Bzzzzzzztt .... Operation complete.  */
1922             sd->state = sd_transfer_state;
1923         }
1924         break;
1925 
1926     case 42:	/* CMD42:  LOCK_UNLOCK */
1927         sd->data[sd->data_offset ++] = value;
1928         if (sd->data_offset >= sd->blk_len) {
1929             /* TODO: Check CRC before committing */
1930             sd->state = sd_programming_state;
1931             sd_lock_command(sd);
1932             /* Bzzzzzzztt .... Operation complete.  */
1933             sd->state = sd_transfer_state;
1934         }
1935         break;
1936 
1937     case 56:	/* CMD56:  GEN_CMD */
1938         sd->data[sd->data_offset ++] = value;
1939         if (sd->data_offset >= sd->blk_len) {
1940             APP_WRITE_BLOCK(sd->data_start, sd->data_offset);
1941             sd->state = sd_transfer_state;
1942         }
1943         break;
1944 
1945     default:
1946         qemu_log_mask(LOG_GUEST_ERROR, "%s: unknown command\n", __func__);
1947         break;
1948     }
1949 }
1950 
1951 #define SD_TUNING_BLOCK_SIZE    64
1952 
1953 static const uint8_t sd_tuning_block_pattern[SD_TUNING_BLOCK_SIZE] = {
1954     /* See: Physical Layer Simplified Specification Version 3.01, Table 4-2 */
1955     0xff, 0x0f, 0xff, 0x00,         0x0f, 0xfc, 0xc3, 0xcc,
1956     0xc3, 0x3c, 0xcc, 0xff,         0xfe, 0xff, 0xfe, 0xef,
1957     0xff, 0xdf, 0xff, 0xdd,         0xff, 0xfb, 0xff, 0xfb,
1958     0xbf, 0xff, 0x7f, 0xff,         0x77, 0xf7, 0xbd, 0xef,
1959     0xff, 0xf0, 0xff, 0xf0,         0x0f, 0xfc, 0xcc, 0x3c,
1960     0xcc, 0x33, 0xcc, 0xcf,         0xff, 0xef, 0xff, 0xee,
1961     0xff, 0xfd, 0xff, 0xfd,         0xdf, 0xff, 0xbf, 0xff,
1962     0xbb, 0xff, 0xf7, 0xff,         0xf7, 0x7f, 0x7b, 0xde,
1963 };
1964 
1965 uint8_t sd_read_byte(SDState *sd)
1966 {
1967     /* TODO: Append CRCs */
1968     uint8_t ret;
1969     int io_len;
1970 
1971     if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable)
1972         return 0x00;
1973 
1974     if (sd->state != sd_sendingdata_state) {
1975         qemu_log_mask(LOG_GUEST_ERROR,
1976                       "%s: not in Sending-Data state\n", __func__);
1977         return 0x00;
1978     }
1979 
1980     if (sd->card_status & (ADDRESS_ERROR | WP_VIOLATION))
1981         return 0x00;
1982 
1983     io_len = (sd->ocr & (1 << 30)) ? 512 : sd->blk_len;
1984 
1985     trace_sdcard_read_data(sd->proto_name,
1986                            sd_acmd_name(sd->current_cmd),
1987                            sd->current_cmd, io_len);
1988     switch (sd->current_cmd) {
1989     case 6:	/* CMD6:   SWITCH_FUNCTION */
1990         ret = sd->data[sd->data_offset ++];
1991 
1992         if (sd->data_offset >= 64)
1993             sd->state = sd_transfer_state;
1994         break;
1995 
1996     case 9:	/* CMD9:   SEND_CSD */
1997     case 10:	/* CMD10:  SEND_CID */
1998         ret = sd->data[sd->data_offset ++];
1999 
2000         if (sd->data_offset >= 16)
2001             sd->state = sd_transfer_state;
2002         break;
2003 
2004     case 13:	/* ACMD13: SD_STATUS */
2005         ret = sd->sd_status[sd->data_offset ++];
2006 
2007         if (sd->data_offset >= sizeof(sd->sd_status))
2008             sd->state = sd_transfer_state;
2009         break;
2010 
2011     case 17:	/* CMD17:  READ_SINGLE_BLOCK */
2012         if (sd->data_offset == 0)
2013             BLK_READ_BLOCK(sd->data_start, io_len);
2014         ret = sd->data[sd->data_offset ++];
2015 
2016         if (sd->data_offset >= io_len)
2017             sd->state = sd_transfer_state;
2018         break;
2019 
2020     case 18:	/* CMD18:  READ_MULTIPLE_BLOCK */
2021         if (sd->data_offset == 0) {
2022             if (sd->data_start + io_len > sd->size) {
2023                 sd->card_status |= ADDRESS_ERROR;
2024                 return 0x00;
2025             }
2026             BLK_READ_BLOCK(sd->data_start, io_len);
2027         }
2028         ret = sd->data[sd->data_offset ++];
2029 
2030         if (sd->data_offset >= io_len) {
2031             sd->data_start += io_len;
2032             sd->data_offset = 0;
2033 
2034             if (sd->multi_blk_cnt != 0) {
2035                 if (--sd->multi_blk_cnt == 0) {
2036                     /* Stop! */
2037                     sd->state = sd_transfer_state;
2038                     break;
2039                 }
2040             }
2041         }
2042         break;
2043 
2044     case 19:    /* CMD19:  SEND_TUNING_BLOCK (SD) */
2045         if (sd->data_offset >= SD_TUNING_BLOCK_SIZE - 1) {
2046             sd->state = sd_transfer_state;
2047         }
2048         ret = sd_tuning_block_pattern[sd->data_offset++];
2049         break;
2050 
2051     case 22:	/* ACMD22: SEND_NUM_WR_BLOCKS */
2052         ret = sd->data[sd->data_offset ++];
2053 
2054         if (sd->data_offset >= 4)
2055             sd->state = sd_transfer_state;
2056         break;
2057 
2058     case 30:	/* CMD30:  SEND_WRITE_PROT */
2059         ret = sd->data[sd->data_offset ++];
2060 
2061         if (sd->data_offset >= 4)
2062             sd->state = sd_transfer_state;
2063         break;
2064 
2065     case 51:	/* ACMD51: SEND_SCR */
2066         ret = sd->scr[sd->data_offset ++];
2067 
2068         if (sd->data_offset >= sizeof(sd->scr))
2069             sd->state = sd_transfer_state;
2070         break;
2071 
2072     case 56:	/* CMD56:  GEN_CMD */
2073         if (sd->data_offset == 0)
2074             APP_READ_BLOCK(sd->data_start, sd->blk_len);
2075         ret = sd->data[sd->data_offset ++];
2076 
2077         if (sd->data_offset >= sd->blk_len)
2078             sd->state = sd_transfer_state;
2079         break;
2080 
2081     default:
2082         qemu_log_mask(LOG_GUEST_ERROR, "%s: unknown command\n", __func__);
2083         return 0x00;
2084     }
2085 
2086     return ret;
2087 }
2088 
2089 static bool sd_data_ready(SDState *sd)
2090 {
2091     return sd->state == sd_sendingdata_state;
2092 }
2093 
2094 void sd_enable(SDState *sd, bool enable)
2095 {
2096     sd->enable = enable;
2097 }
2098 
2099 static void sd_instance_init(Object *obj)
2100 {
2101     SDState *sd = SD_CARD(obj);
2102 
2103     sd->enable = true;
2104     sd->ocr_power_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, sd_ocr_powerup, sd);
2105 }
2106 
2107 static void sd_instance_finalize(Object *obj)
2108 {
2109     SDState *sd = SD_CARD(obj);
2110 
2111     timer_del(sd->ocr_power_timer);
2112     timer_free(sd->ocr_power_timer);
2113 }
2114 
2115 static void sd_realize(DeviceState *dev, Error **errp)
2116 {
2117     SDState *sd = SD_CARD(dev);
2118     int ret;
2119 
2120     sd->proto_name = sd->spi ? "SPI" : "SD";
2121 
2122     switch (sd->spec_version) {
2123     case SD_PHY_SPECv1_10_VERS
2124      ... SD_PHY_SPECv3_01_VERS:
2125         break;
2126     default:
2127         error_setg(errp, "Invalid SD card Spec version: %u", sd->spec_version);
2128         return;
2129     }
2130 
2131     if (sd->blk) {
2132         int64_t blk_size;
2133 
2134         if (blk_is_read_only(sd->blk)) {
2135             error_setg(errp, "Cannot use read-only drive as SD card");
2136             return;
2137         }
2138 
2139         blk_size = blk_getlength(sd->blk);
2140         if (blk_size > 0 && !is_power_of_2(blk_size)) {
2141             int64_t blk_size_aligned = pow2ceil(blk_size);
2142             char *blk_size_str;
2143 
2144             blk_size_str = size_to_str(blk_size);
2145             error_setg(errp, "Invalid SD card size: %s", blk_size_str);
2146             g_free(blk_size_str);
2147 
2148             blk_size_str = size_to_str(blk_size_aligned);
2149             error_append_hint(errp,
2150                               "SD card size has to be a power of 2, e.g. %s.\n"
2151                               "You can resize disk images with"
2152                               " 'qemu-img resize <imagefile> <new-size>'\n"
2153                               "(note that this will lose data if you make the"
2154                               " image smaller than it currently is).\n",
2155                               blk_size_str);
2156             g_free(blk_size_str);
2157 
2158             return;
2159         }
2160 
2161         ret = blk_set_perm(sd->blk, BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE,
2162                            BLK_PERM_ALL, errp);
2163         if (ret < 0) {
2164             return;
2165         }
2166         blk_set_dev_ops(sd->blk, &sd_block_ops, sd);
2167     }
2168 }
2169 
2170 static Property sd_properties[] = {
2171     DEFINE_PROP_UINT8("spec_version", SDState,
2172                       spec_version, SD_PHY_SPECv2_00_VERS),
2173     DEFINE_PROP_DRIVE("drive", SDState, blk),
2174     /* We do not model the chip select pin, so allow the board to select
2175      * whether card should be in SSI or MMC/SD mode.  It is also up to the
2176      * board to ensure that ssi transfers only occur when the chip select
2177      * is asserted.  */
2178     DEFINE_PROP_BOOL("spi", SDState, spi, false),
2179     DEFINE_PROP_END_OF_LIST()
2180 };
2181 
2182 static void sd_class_init(ObjectClass *klass, void *data)
2183 {
2184     DeviceClass *dc = DEVICE_CLASS(klass);
2185     SDCardClass *sc = SD_CARD_CLASS(klass);
2186 
2187     dc->realize = sd_realize;
2188     device_class_set_props(dc, sd_properties);
2189     dc->vmsd = &sd_vmstate;
2190     dc->reset = sd_reset;
2191     dc->bus_type = TYPE_SD_BUS;
2192     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
2193 
2194     sc->set_voltage = sd_set_voltage;
2195     sc->get_dat_lines = sd_get_dat_lines;
2196     sc->get_cmd_line = sd_get_cmd_line;
2197     sc->do_command = sd_do_command;
2198     sc->write_byte = sd_write_byte;
2199     sc->read_byte = sd_read_byte;
2200     sc->data_ready = sd_data_ready;
2201     sc->enable = sd_enable;
2202     sc->get_inserted = sd_get_inserted;
2203     sc->get_readonly = sd_get_readonly;
2204 }
2205 
2206 static const TypeInfo sd_info = {
2207     .name = TYPE_SD_CARD,
2208     .parent = TYPE_DEVICE,
2209     .instance_size = sizeof(SDState),
2210     .class_size = sizeof(SDCardClass),
2211     .class_init = sd_class_init,
2212     .instance_init = sd_instance_init,
2213     .instance_finalize = sd_instance_finalize,
2214 };
2215 
2216 static void sd_register_types(void)
2217 {
2218     type_register_static(&sd_info);
2219 }
2220 
2221 type_init(sd_register_types)
2222