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