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