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