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