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