xref: /openbmc/qemu/hw/sd/sd.c (revision 39de9984)
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 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     DeviceState *dev;
567     Error *err = NULL;
568 
569     dev = qdev_create(NULL, TYPE_SD_CARD);
570     qdev_prop_set_drive(dev, "drive", blk, &err);
571     if (err) {
572         error_report("sd_init failed: %s", error_get_pretty(err));
573         return NULL;
574     }
575     qdev_prop_set_bit(dev, "spi", is_spi);
576     object_property_set_bool(OBJECT(dev), true, "realized", &err);
577     if (err) {
578         error_report("sd_init failed: %s", error_get_pretty(err));
579         return NULL;
580     }
581 
582     return SD_CARD(dev);
583 }
584 
585 void sd_set_cb(SDState *sd, qemu_irq readonly, qemu_irq insert)
586 {
587     sd->readonly_cb = readonly;
588     sd->inserted_cb = insert;
589     qemu_set_irq(readonly, sd->blk ? blk_is_read_only(sd->blk) : 0);
590     qemu_set_irq(insert, sd->blk ? blk_is_inserted(sd->blk) : 0);
591 }
592 
593 static void sd_erase(SDState *sd)
594 {
595     int i;
596     uint64_t erase_start = sd->erase_start;
597     uint64_t erase_end = sd->erase_end;
598 
599     if (!sd->erase_start || !sd->erase_end) {
600         sd->card_status |= ERASE_SEQ_ERROR;
601         return;
602     }
603 
604     if (extract32(sd->ocr, OCR_CCS_BITN, 1)) {
605         /* High capacity memory card: erase units are 512 byte blocks */
606         erase_start *= 512;
607         erase_end *= 512;
608     }
609 
610     erase_start = sd_addr_to_wpnum(erase_start);
611     erase_end = sd_addr_to_wpnum(erase_end);
612     sd->erase_start = 0;
613     sd->erase_end = 0;
614     sd->csd[14] |= 0x40;
615 
616     for (i = erase_start; i <= erase_end; i++) {
617         if (test_bit(i, sd->wp_groups)) {
618             sd->card_status |= WP_ERASE_SKIP;
619         }
620     }
621 }
622 
623 static uint32_t sd_wpbits(SDState *sd, uint64_t addr)
624 {
625     uint32_t i, wpnum;
626     uint32_t ret = 0;
627 
628     wpnum = sd_addr_to_wpnum(addr);
629 
630     for (i = 0; i < 32; i++, wpnum++, addr += WPGROUP_SIZE) {
631         if (addr < sd->size && test_bit(wpnum, sd->wp_groups)) {
632             ret |= (1 << i);
633         }
634     }
635 
636     return ret;
637 }
638 
639 static void sd_function_switch(SDState *sd, uint32_t arg)
640 {
641     int i, mode, new_func, crc;
642     mode = !!(arg & 0x80000000);
643 
644     sd->data[0] = 0x00;		/* Maximum current consumption */
645     sd->data[1] = 0x01;
646     sd->data[2] = 0x80;		/* Supported group 6 functions */
647     sd->data[3] = 0x01;
648     sd->data[4] = 0x80;		/* Supported group 5 functions */
649     sd->data[5] = 0x01;
650     sd->data[6] = 0x80;		/* Supported group 4 functions */
651     sd->data[7] = 0x01;
652     sd->data[8] = 0x80;		/* Supported group 3 functions */
653     sd->data[9] = 0x01;
654     sd->data[10] = 0x80;	/* Supported group 2 functions */
655     sd->data[11] = 0x43;
656     sd->data[12] = 0x80;	/* Supported group 1 functions */
657     sd->data[13] = 0x03;
658     for (i = 0; i < 6; i ++) {
659         new_func = (arg >> (i * 4)) & 0x0f;
660         if (mode && new_func != 0x0f)
661             sd->function_group[i] = new_func;
662         sd->data[14 + (i >> 1)] = new_func << ((i * 4) & 4);
663     }
664     memset(&sd->data[17], 0, 47);
665     crc = sd_crc16(sd->data, 64);
666     sd->data[65] = crc >> 8;
667     sd->data[66] = crc & 0xff;
668 }
669 
670 static inline bool sd_wp_addr(SDState *sd, uint64_t addr)
671 {
672     return test_bit(sd_addr_to_wpnum(addr), sd->wp_groups);
673 }
674 
675 static void sd_lock_command(SDState *sd)
676 {
677     int erase, lock, clr_pwd, set_pwd, pwd_len;
678     erase = !!(sd->data[0] & 0x08);
679     lock = sd->data[0] & 0x04;
680     clr_pwd = sd->data[0] & 0x02;
681     set_pwd = sd->data[0] & 0x01;
682 
683     if (sd->blk_len > 1)
684         pwd_len = sd->data[1];
685     else
686         pwd_len = 0;
687 
688     if (erase) {
689         if (!(sd->card_status & CARD_IS_LOCKED) || sd->blk_len > 1 ||
690                         set_pwd || clr_pwd || lock || sd->wp_switch ||
691                         (sd->csd[14] & 0x20)) {
692             sd->card_status |= LOCK_UNLOCK_FAILED;
693             return;
694         }
695         bitmap_zero(sd->wp_groups, sd->wpgrps_size);
696         sd->csd[14] &= ~0x10;
697         sd->card_status &= ~CARD_IS_LOCKED;
698         sd->pwd_len = 0;
699         /* Erasing the entire card here! */
700         fprintf(stderr, "SD: Card force-erased by CMD42\n");
701         return;
702     }
703 
704     if (sd->blk_len < 2 + pwd_len ||
705                     pwd_len <= sd->pwd_len ||
706                     pwd_len > sd->pwd_len + 16) {
707         sd->card_status |= LOCK_UNLOCK_FAILED;
708         return;
709     }
710 
711     if (sd->pwd_len && memcmp(sd->pwd, sd->data + 2, sd->pwd_len)) {
712         sd->card_status |= LOCK_UNLOCK_FAILED;
713         return;
714     }
715 
716     pwd_len -= sd->pwd_len;
717     if ((pwd_len && !set_pwd) ||
718                     (clr_pwd && (set_pwd || lock)) ||
719                     (lock && !sd->pwd_len && !set_pwd) ||
720                     (!set_pwd && !clr_pwd &&
721                      (((sd->card_status & CARD_IS_LOCKED) && lock) ||
722                       (!(sd->card_status & CARD_IS_LOCKED) && !lock)))) {
723         sd->card_status |= LOCK_UNLOCK_FAILED;
724         return;
725     }
726 
727     if (set_pwd) {
728         memcpy(sd->pwd, sd->data + 2 + sd->pwd_len, pwd_len);
729         sd->pwd_len = pwd_len;
730     }
731 
732     if (clr_pwd) {
733         sd->pwd_len = 0;
734     }
735 
736     if (lock)
737         sd->card_status |= CARD_IS_LOCKED;
738     else
739         sd->card_status &= ~CARD_IS_LOCKED;
740 }
741 
742 static sd_rsp_type_t sd_normal_command(SDState *sd,
743                                        SDRequest req)
744 {
745     uint32_t rca = 0x0000;
746     uint64_t addr = (sd->ocr & (1 << 30)) ? (uint64_t) req.arg << 9 : req.arg;
747 
748     /* Not interpreting this as an app command */
749     sd->card_status &= ~APP_CMD;
750 
751     if (sd_cmd_type[req.cmd & 0x3F] == sd_ac
752         || sd_cmd_type[req.cmd & 0x3F] == sd_adtc) {
753         rca = req.arg >> 16;
754     }
755 
756     /* CMD23 (set block count) must be immediately followed by CMD18 or CMD25
757      * if not, its effects are cancelled */
758     if (sd->multi_blk_cnt != 0 && !(req.cmd == 18 || req.cmd == 25)) {
759         sd->multi_blk_cnt = 0;
760     }
761 
762     DPRINTF("CMD%d 0x%08x state %d\n", req.cmd, req.arg, sd->state);
763     switch (req.cmd) {
764     /* Basic commands (Class 0 and Class 1) */
765     case 0:	/* CMD0:   GO_IDLE_STATE */
766         switch (sd->state) {
767         case sd_inactive_state:
768             return sd->spi ? sd_r1 : sd_r0;
769 
770         default:
771             sd->state = sd_idle_state;
772             sd_reset(DEVICE(sd));
773             return sd->spi ? sd_r1 : sd_r0;
774         }
775         break;
776 
777     case 1:	/* CMD1:   SEND_OP_CMD */
778         if (!sd->spi)
779             goto bad_cmd;
780 
781         sd->state = sd_transfer_state;
782         return sd_r1;
783 
784     case 2:	/* CMD2:   ALL_SEND_CID */
785         if (sd->spi)
786             goto bad_cmd;
787         switch (sd->state) {
788         case sd_ready_state:
789             sd->state = sd_identification_state;
790             return sd_r2_i;
791 
792         default:
793             break;
794         }
795         break;
796 
797     case 3:	/* CMD3:   SEND_RELATIVE_ADDR */
798         if (sd->spi)
799             goto bad_cmd;
800         switch (sd->state) {
801         case sd_identification_state:
802         case sd_standby_state:
803             sd->state = sd_standby_state;
804             sd_set_rca(sd);
805             return sd_r6;
806 
807         default:
808             break;
809         }
810         break;
811 
812     case 4:	/* CMD4:   SEND_DSR */
813         if (sd->spi)
814             goto bad_cmd;
815         switch (sd->state) {
816         case sd_standby_state:
817             break;
818 
819         default:
820             break;
821         }
822         break;
823 
824     case 5: /* CMD5: reserved for SDIO cards */
825         return sd_illegal;
826 
827     case 6:	/* CMD6:   SWITCH_FUNCTION */
828         if (sd->spi)
829             goto bad_cmd;
830         switch (sd->mode) {
831         case sd_data_transfer_mode:
832             sd_function_switch(sd, req.arg);
833             sd->state = sd_sendingdata_state;
834             sd->data_start = 0;
835             sd->data_offset = 0;
836             return sd_r1;
837 
838         default:
839             break;
840         }
841         break;
842 
843     case 7:	/* CMD7:   SELECT/DESELECT_CARD */
844         if (sd->spi)
845             goto bad_cmd;
846         switch (sd->state) {
847         case sd_standby_state:
848             if (sd->rca != rca)
849                 return sd_r0;
850 
851             sd->state = sd_transfer_state;
852             return sd_r1b;
853 
854         case sd_transfer_state:
855         case sd_sendingdata_state:
856             if (sd->rca == rca)
857                 break;
858 
859             sd->state = sd_standby_state;
860             return sd_r1b;
861 
862         case sd_disconnect_state:
863             if (sd->rca != rca)
864                 return sd_r0;
865 
866             sd->state = sd_programming_state;
867             return sd_r1b;
868 
869         case sd_programming_state:
870             if (sd->rca == rca)
871                 break;
872 
873             sd->state = sd_disconnect_state;
874             return sd_r1b;
875 
876         default:
877             break;
878         }
879         break;
880 
881     case 8:	/* CMD8:   SEND_IF_COND */
882         /* Physical Layer Specification Version 2.00 command */
883         switch (sd->state) {
884         case sd_idle_state:
885             sd->vhs = 0;
886 
887             /* No response if not exactly one VHS bit is set.  */
888             if (!(req.arg >> 8) || (req.arg >> (ctz32(req.arg & ~0xff) + 1))) {
889                 return sd->spi ? sd_r7 : sd_r0;
890             }
891 
892             /* Accept.  */
893             sd->vhs = req.arg;
894             return sd_r7;
895 
896         default:
897             break;
898         }
899         break;
900 
901     case 9:	/* CMD9:   SEND_CSD */
902         switch (sd->state) {
903         case sd_standby_state:
904             if (sd->rca != rca)
905                 return sd_r0;
906 
907             return sd_r2_s;
908 
909         case sd_transfer_state:
910             if (!sd->spi)
911                 break;
912             sd->state = sd_sendingdata_state;
913             memcpy(sd->data, sd->csd, 16);
914             sd->data_start = addr;
915             sd->data_offset = 0;
916             return sd_r1;
917 
918         default:
919             break;
920         }
921         break;
922 
923     case 10:	/* CMD10:  SEND_CID */
924         switch (sd->state) {
925         case sd_standby_state:
926             if (sd->rca != rca)
927                 return sd_r0;
928 
929             return sd_r2_i;
930 
931         case sd_transfer_state:
932             if (!sd->spi)
933                 break;
934             sd->state = sd_sendingdata_state;
935             memcpy(sd->data, sd->cid, 16);
936             sd->data_start = addr;
937             sd->data_offset = 0;
938             return sd_r1;
939 
940         default:
941             break;
942         }
943         break;
944 
945     case 11:	/* CMD11:  READ_DAT_UNTIL_STOP */
946         if (sd->spi)
947             goto bad_cmd;
948         switch (sd->state) {
949         case sd_transfer_state:
950             sd->state = sd_sendingdata_state;
951             sd->data_start = req.arg;
952             sd->data_offset = 0;
953 
954             if (sd->data_start + sd->blk_len > sd->size)
955                 sd->card_status |= ADDRESS_ERROR;
956             return sd_r0;
957 
958         default:
959             break;
960         }
961         break;
962 
963     case 12:	/* CMD12:  STOP_TRANSMISSION */
964         switch (sd->state) {
965         case sd_sendingdata_state:
966             sd->state = sd_transfer_state;
967             return sd_r1b;
968 
969         case sd_receivingdata_state:
970             sd->state = sd_programming_state;
971             /* Bzzzzzzztt .... Operation complete.  */
972             sd->state = sd_transfer_state;
973             return sd_r1b;
974 
975         default:
976             break;
977         }
978         break;
979 
980     case 13:	/* CMD13:  SEND_STATUS */
981         switch (sd->mode) {
982         case sd_data_transfer_mode:
983             if (sd->rca != rca)
984                 return sd_r0;
985 
986             return sd_r1;
987 
988         default:
989             break;
990         }
991         break;
992 
993     case 15:	/* CMD15:  GO_INACTIVE_STATE */
994         if (sd->spi)
995             goto bad_cmd;
996         switch (sd->mode) {
997         case sd_data_transfer_mode:
998             if (sd->rca != rca)
999                 return sd_r0;
1000 
1001             sd->state = sd_inactive_state;
1002             return sd_r0;
1003 
1004         default:
1005             break;
1006         }
1007         break;
1008 
1009     /* Block read commands (Classs 2) */
1010     case 16:	/* CMD16:  SET_BLOCKLEN */
1011         switch (sd->state) {
1012         case sd_transfer_state:
1013             if (req.arg > (1 << HWBLOCK_SHIFT))
1014                 sd->card_status |= BLOCK_LEN_ERROR;
1015             else
1016                 sd->blk_len = req.arg;
1017 
1018             return sd_r1;
1019 
1020         default:
1021             break;
1022         }
1023         break;
1024 
1025     case 17:	/* CMD17:  READ_SINGLE_BLOCK */
1026         switch (sd->state) {
1027         case sd_transfer_state:
1028             sd->state = sd_sendingdata_state;
1029             sd->data_start = addr;
1030             sd->data_offset = 0;
1031 
1032             if (sd->data_start + sd->blk_len > sd->size)
1033                 sd->card_status |= ADDRESS_ERROR;
1034             return sd_r1;
1035 
1036         default:
1037             break;
1038         }
1039         break;
1040 
1041     case 18:	/* CMD18:  READ_MULTIPLE_BLOCK */
1042         switch (sd->state) {
1043         case sd_transfer_state:
1044             sd->state = sd_sendingdata_state;
1045             sd->data_start = addr;
1046             sd->data_offset = 0;
1047 
1048             if (sd->data_start + sd->blk_len > sd->size)
1049                 sd->card_status |= ADDRESS_ERROR;
1050             return sd_r1;
1051 
1052         default:
1053             break;
1054         }
1055         break;
1056 
1057     case 23:    /* CMD23: SET_BLOCK_COUNT */
1058         switch (sd->state) {
1059         case sd_transfer_state:
1060             sd->multi_blk_cnt = req.arg;
1061             return sd_r1;
1062 
1063         default:
1064             break;
1065         }
1066         break;
1067 
1068     /* Block write commands (Class 4) */
1069     case 24:	/* CMD24:  WRITE_SINGLE_BLOCK */
1070         if (sd->spi)
1071             goto unimplemented_cmd;
1072         switch (sd->state) {
1073         case sd_transfer_state:
1074             /* Writing in SPI mode not implemented.  */
1075             if (sd->spi)
1076                 break;
1077             sd->state = sd_receivingdata_state;
1078             sd->data_start = addr;
1079             sd->data_offset = 0;
1080             sd->blk_written = 0;
1081 
1082             if (sd->data_start + sd->blk_len > sd->size)
1083                 sd->card_status |= ADDRESS_ERROR;
1084             if (sd_wp_addr(sd, sd->data_start))
1085                 sd->card_status |= WP_VIOLATION;
1086             if (sd->csd[14] & 0x30)
1087                 sd->card_status |= WP_VIOLATION;
1088             return sd_r1;
1089 
1090         default:
1091             break;
1092         }
1093         break;
1094 
1095     case 25:	/* CMD25:  WRITE_MULTIPLE_BLOCK */
1096         if (sd->spi)
1097             goto unimplemented_cmd;
1098         switch (sd->state) {
1099         case sd_transfer_state:
1100             /* Writing in SPI mode not implemented.  */
1101             if (sd->spi)
1102                 break;
1103             sd->state = sd_receivingdata_state;
1104             sd->data_start = addr;
1105             sd->data_offset = 0;
1106             sd->blk_written = 0;
1107 
1108             if (sd->data_start + sd->blk_len > sd->size)
1109                 sd->card_status |= ADDRESS_ERROR;
1110             if (sd_wp_addr(sd, sd->data_start))
1111                 sd->card_status |= WP_VIOLATION;
1112             if (sd->csd[14] & 0x30)
1113                 sd->card_status |= WP_VIOLATION;
1114             return sd_r1;
1115 
1116         default:
1117             break;
1118         }
1119         break;
1120 
1121     case 26:	/* CMD26:  PROGRAM_CID */
1122         if (sd->spi)
1123             goto bad_cmd;
1124         switch (sd->state) {
1125         case sd_transfer_state:
1126             sd->state = sd_receivingdata_state;
1127             sd->data_start = 0;
1128             sd->data_offset = 0;
1129             return sd_r1;
1130 
1131         default:
1132             break;
1133         }
1134         break;
1135 
1136     case 27:	/* CMD27:  PROGRAM_CSD */
1137         if (sd->spi)
1138             goto unimplemented_cmd;
1139         switch (sd->state) {
1140         case sd_transfer_state:
1141             sd->state = sd_receivingdata_state;
1142             sd->data_start = 0;
1143             sd->data_offset = 0;
1144             return sd_r1;
1145 
1146         default:
1147             break;
1148         }
1149         break;
1150 
1151     /* Write protection (Class 6) */
1152     case 28:	/* CMD28:  SET_WRITE_PROT */
1153         switch (sd->state) {
1154         case sd_transfer_state:
1155             if (addr >= sd->size) {
1156                 sd->card_status |= ADDRESS_ERROR;
1157                 return sd_r1b;
1158             }
1159 
1160             sd->state = sd_programming_state;
1161             set_bit(sd_addr_to_wpnum(addr), sd->wp_groups);
1162             /* Bzzzzzzztt .... Operation complete.  */
1163             sd->state = sd_transfer_state;
1164             return sd_r1b;
1165 
1166         default:
1167             break;
1168         }
1169         break;
1170 
1171     case 29:	/* CMD29:  CLR_WRITE_PROT */
1172         switch (sd->state) {
1173         case sd_transfer_state:
1174             if (addr >= sd->size) {
1175                 sd->card_status |= ADDRESS_ERROR;
1176                 return sd_r1b;
1177             }
1178 
1179             sd->state = sd_programming_state;
1180             clear_bit(sd_addr_to_wpnum(addr), sd->wp_groups);
1181             /* Bzzzzzzztt .... Operation complete.  */
1182             sd->state = sd_transfer_state;
1183             return sd_r1b;
1184 
1185         default:
1186             break;
1187         }
1188         break;
1189 
1190     case 30:	/* CMD30:  SEND_WRITE_PROT */
1191         switch (sd->state) {
1192         case sd_transfer_state:
1193             sd->state = sd_sendingdata_state;
1194             *(uint32_t *) sd->data = sd_wpbits(sd, req.arg);
1195             sd->data_start = addr;
1196             sd->data_offset = 0;
1197             return sd_r1b;
1198 
1199         default:
1200             break;
1201         }
1202         break;
1203 
1204     /* Erase commands (Class 5) */
1205     case 32:	/* CMD32:  ERASE_WR_BLK_START */
1206         switch (sd->state) {
1207         case sd_transfer_state:
1208             sd->erase_start = req.arg;
1209             return sd_r1;
1210 
1211         default:
1212             break;
1213         }
1214         break;
1215 
1216     case 33:	/* CMD33:  ERASE_WR_BLK_END */
1217         switch (sd->state) {
1218         case sd_transfer_state:
1219             sd->erase_end = req.arg;
1220             return sd_r1;
1221 
1222         default:
1223             break;
1224         }
1225         break;
1226 
1227     case 38:	/* CMD38:  ERASE */
1228         switch (sd->state) {
1229         case sd_transfer_state:
1230             if (sd->csd[14] & 0x30) {
1231                 sd->card_status |= WP_VIOLATION;
1232                 return sd_r1b;
1233             }
1234 
1235             sd->state = sd_programming_state;
1236             sd_erase(sd);
1237             /* Bzzzzzzztt .... Operation complete.  */
1238             sd->state = sd_transfer_state;
1239             return sd_r1b;
1240 
1241         default:
1242             break;
1243         }
1244         break;
1245 
1246     /* Lock card commands (Class 7) */
1247     case 42:	/* CMD42:  LOCK_UNLOCK */
1248         if (sd->spi)
1249             goto unimplemented_cmd;
1250         switch (sd->state) {
1251         case sd_transfer_state:
1252             sd->state = sd_receivingdata_state;
1253             sd->data_start = 0;
1254             sd->data_offset = 0;
1255             return sd_r1;
1256 
1257         default:
1258             break;
1259         }
1260         break;
1261 
1262     case 52:
1263     case 53:
1264         /* CMD52, CMD53: reserved for SDIO cards
1265          * (see the SDIO Simplified Specification V2.0)
1266          * Handle as illegal command but do not complain
1267          * on stderr, as some OSes may use these in their
1268          * probing for presence of an SDIO card.
1269          */
1270         return sd_illegal;
1271 
1272     /* Application specific commands (Class 8) */
1273     case 55:	/* CMD55:  APP_CMD */
1274         if (sd->rca != rca)
1275             return sd_r0;
1276 
1277         sd->expecting_acmd = true;
1278         sd->card_status |= APP_CMD;
1279         return sd_r1;
1280 
1281     case 56:	/* CMD56:  GEN_CMD */
1282         fprintf(stderr, "SD: GEN_CMD 0x%08x\n", req.arg);
1283 
1284         switch (sd->state) {
1285         case sd_transfer_state:
1286             sd->data_offset = 0;
1287             if (req.arg & 1)
1288                 sd->state = sd_sendingdata_state;
1289             else
1290                 sd->state = sd_receivingdata_state;
1291             return sd_r1;
1292 
1293         default:
1294             break;
1295         }
1296         break;
1297 
1298     default:
1299     bad_cmd:
1300         qemu_log_mask(LOG_GUEST_ERROR, "SD: Unknown CMD%i\n", req.cmd);
1301         return sd_illegal;
1302 
1303     unimplemented_cmd:
1304         /* Commands that are recognised but not yet implemented in SPI mode.  */
1305         qemu_log_mask(LOG_UNIMP, "SD: CMD%i not implemented in SPI mode\n",
1306                       req.cmd);
1307         return sd_illegal;
1308     }
1309 
1310     qemu_log_mask(LOG_GUEST_ERROR, "SD: CMD%i in a wrong state\n", req.cmd);
1311     return sd_illegal;
1312 }
1313 
1314 static sd_rsp_type_t sd_app_command(SDState *sd,
1315                                     SDRequest req)
1316 {
1317     DPRINTF("ACMD%d 0x%08x\n", req.cmd, req.arg);
1318     sd->card_status |= APP_CMD;
1319     switch (req.cmd) {
1320     case 6:	/* ACMD6:  SET_BUS_WIDTH */
1321         switch (sd->state) {
1322         case sd_transfer_state:
1323             sd->sd_status[0] &= 0x3f;
1324             sd->sd_status[0] |= (req.arg & 0x03) << 6;
1325             return sd_r1;
1326 
1327         default:
1328             break;
1329         }
1330         break;
1331 
1332     case 13:	/* ACMD13: SD_STATUS */
1333         switch (sd->state) {
1334         case sd_transfer_state:
1335             sd->state = sd_sendingdata_state;
1336             sd->data_start = 0;
1337             sd->data_offset = 0;
1338             return sd_r1;
1339 
1340         default:
1341             break;
1342         }
1343         break;
1344 
1345     case 22:	/* ACMD22: SEND_NUM_WR_BLOCKS */
1346         switch (sd->state) {
1347         case sd_transfer_state:
1348             *(uint32_t *) sd->data = sd->blk_written;
1349 
1350             sd->state = sd_sendingdata_state;
1351             sd->data_start = 0;
1352             sd->data_offset = 0;
1353             return sd_r1;
1354 
1355         default:
1356             break;
1357         }
1358         break;
1359 
1360     case 23:	/* ACMD23: SET_WR_BLK_ERASE_COUNT */
1361         switch (sd->state) {
1362         case sd_transfer_state:
1363             return sd_r1;
1364 
1365         default:
1366             break;
1367         }
1368         break;
1369 
1370     case 41:	/* ACMD41: SD_APP_OP_COND */
1371         if (sd->spi) {
1372             /* SEND_OP_CMD */
1373             sd->state = sd_transfer_state;
1374             return sd_r1;
1375         }
1376         switch (sd->state) {
1377         case sd_idle_state:
1378             /* If it's the first ACMD41 since reset, we need to decide
1379              * whether to power up. If this is not an enquiry ACMD41,
1380              * we immediately report power on and proceed below to the
1381              * ready state, but if it is, we set a timer to model a
1382              * delay for power up. This works around a bug in EDK2
1383              * UEFI, which sends an initial enquiry ACMD41, but
1384              * assumes that the card is in ready state as soon as it
1385              * sees the power up bit set. */
1386             if (!(sd->ocr & OCR_POWER_UP)) {
1387                 if ((req.arg & ACMD41_ENQUIRY_MASK) != 0) {
1388                     timer_del(sd->ocr_power_timer);
1389                     sd_ocr_powerup(sd);
1390                 } else if (!timer_pending(sd->ocr_power_timer)) {
1391                     timer_mod_ns(sd->ocr_power_timer,
1392                                  (qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL)
1393                                   + OCR_POWER_DELAY_NS));
1394                 }
1395             }
1396 
1397             /* We accept any voltage.  10000 V is nothing.
1398              *
1399              * Once we're powered up, we advance straight to ready state
1400              * unless it's an enquiry ACMD41 (bits 23:0 == 0).
1401              */
1402             if (req.arg & ACMD41_ENQUIRY_MASK) {
1403                 sd->state = sd_ready_state;
1404             }
1405 
1406             return sd_r3;
1407 
1408         default:
1409             break;
1410         }
1411         break;
1412 
1413     case 42:	/* ACMD42: SET_CLR_CARD_DETECT */
1414         switch (sd->state) {
1415         case sd_transfer_state:
1416             /* Bringing in the 50KOhm pull-up resistor... Done.  */
1417             return sd_r1;
1418 
1419         default:
1420             break;
1421         }
1422         break;
1423 
1424     case 51:	/* ACMD51: SEND_SCR */
1425         switch (sd->state) {
1426         case sd_transfer_state:
1427             sd->state = sd_sendingdata_state;
1428             sd->data_start = 0;
1429             sd->data_offset = 0;
1430             return sd_r1;
1431 
1432         default:
1433             break;
1434         }
1435         break;
1436 
1437     default:
1438         /* Fall back to standard commands.  */
1439         return sd_normal_command(sd, req);
1440     }
1441 
1442     qemu_log_mask(LOG_GUEST_ERROR, "SD: ACMD%i in a wrong state\n", req.cmd);
1443     return sd_illegal;
1444 }
1445 
1446 static int cmd_valid_while_locked(SDState *sd, SDRequest *req)
1447 {
1448     /* Valid commands in locked state:
1449      * basic class (0)
1450      * lock card class (7)
1451      * CMD16
1452      * implicitly, the ACMD prefix CMD55
1453      * ACMD41 and ACMD42
1454      * Anything else provokes an "illegal command" response.
1455      */
1456     if (sd->expecting_acmd) {
1457         return req->cmd == 41 || req->cmd == 42;
1458     }
1459     if (req->cmd == 16 || req->cmd == 55) {
1460         return 1;
1461     }
1462     return sd_cmd_class[req->cmd & 0x3F] == 0
1463             || sd_cmd_class[req->cmd & 0x3F] == 7;
1464 }
1465 
1466 int sd_do_command(SDState *sd, SDRequest *req,
1467                   uint8_t *response) {
1468     int last_state;
1469     sd_rsp_type_t rtype;
1470     int rsplen;
1471 
1472     if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable) {
1473         return 0;
1474     }
1475 
1476     if (sd_req_crc_validate(req)) {
1477         sd->card_status |= COM_CRC_ERROR;
1478         rtype = sd_illegal;
1479         goto send_response;
1480     }
1481 
1482     if (sd->card_status & CARD_IS_LOCKED) {
1483         if (!cmd_valid_while_locked(sd, req)) {
1484             sd->card_status |= ILLEGAL_COMMAND;
1485             sd->expecting_acmd = false;
1486             qemu_log_mask(LOG_GUEST_ERROR, "SD: Card is locked\n");
1487             rtype = sd_illegal;
1488             goto send_response;
1489         }
1490     }
1491 
1492     last_state = sd->state;
1493     sd_set_mode(sd);
1494 
1495     if (sd->expecting_acmd) {
1496         sd->expecting_acmd = false;
1497         rtype = sd_app_command(sd, *req);
1498     } else {
1499         rtype = sd_normal_command(sd, *req);
1500     }
1501 
1502     if (rtype == sd_illegal) {
1503         sd->card_status |= ILLEGAL_COMMAND;
1504     } else {
1505         /* Valid command, we can update the 'state before command' bits.
1506          * (Do this now so they appear in r1 responses.)
1507          */
1508         sd->current_cmd = req->cmd;
1509         sd->card_status &= ~CURRENT_STATE;
1510         sd->card_status |= (last_state << 9);
1511     }
1512 
1513 send_response:
1514     switch (rtype) {
1515     case sd_r1:
1516     case sd_r1b:
1517         sd_response_r1_make(sd, response);
1518         rsplen = 4;
1519         break;
1520 
1521     case sd_r2_i:
1522         memcpy(response, sd->cid, sizeof(sd->cid));
1523         rsplen = 16;
1524         break;
1525 
1526     case sd_r2_s:
1527         memcpy(response, sd->csd, sizeof(sd->csd));
1528         rsplen = 16;
1529         break;
1530 
1531     case sd_r3:
1532         sd_response_r3_make(sd, response);
1533         rsplen = 4;
1534         break;
1535 
1536     case sd_r6:
1537         sd_response_r6_make(sd, response);
1538         rsplen = 4;
1539         break;
1540 
1541     case sd_r7:
1542         sd_response_r7_make(sd, response);
1543         rsplen = 4;
1544         break;
1545 
1546     case sd_r0:
1547     case sd_illegal:
1548     default:
1549         rsplen = 0;
1550         break;
1551     }
1552 
1553     if (rtype != sd_illegal) {
1554         /* Clear the "clear on valid command" status bits now we've
1555          * sent any response
1556          */
1557         sd->card_status &= ~CARD_STATUS_B;
1558     }
1559 
1560 #ifdef DEBUG_SD
1561     if (rsplen) {
1562         int i;
1563         DPRINTF("Response:");
1564         for (i = 0; i < rsplen; i++)
1565             fprintf(stderr, " %02x", response[i]);
1566         fprintf(stderr, " state %d\n", sd->state);
1567     } else {
1568         DPRINTF("No response %d\n", sd->state);
1569     }
1570 #endif
1571 
1572     return rsplen;
1573 }
1574 
1575 static void sd_blk_read(SDState *sd, uint64_t addr, uint32_t len)
1576 {
1577     uint64_t end = addr + len;
1578 
1579     DPRINTF("sd_blk_read: addr = 0x%08llx, len = %d\n",
1580             (unsigned long long) addr, len);
1581     if (!sd->blk || blk_read(sd->blk, addr >> 9, sd->buf, 1) < 0) {
1582         fprintf(stderr, "sd_blk_read: read error on host side\n");
1583         return;
1584     }
1585 
1586     if (end > (addr & ~511) + 512) {
1587         memcpy(sd->data, sd->buf + (addr & 511), 512 - (addr & 511));
1588 
1589         if (blk_read(sd->blk, end >> 9, sd->buf, 1) < 0) {
1590             fprintf(stderr, "sd_blk_read: read error on host side\n");
1591             return;
1592         }
1593         memcpy(sd->data + 512 - (addr & 511), sd->buf, end & 511);
1594     } else
1595         memcpy(sd->data, sd->buf + (addr & 511), len);
1596 }
1597 
1598 static void sd_blk_write(SDState *sd, uint64_t addr, uint32_t len)
1599 {
1600     uint64_t end = addr + len;
1601 
1602     if ((addr & 511) || len < 512)
1603         if (!sd->blk || blk_read(sd->blk, addr >> 9, sd->buf, 1) < 0) {
1604             fprintf(stderr, "sd_blk_write: read error on host side\n");
1605             return;
1606         }
1607 
1608     if (end > (addr & ~511) + 512) {
1609         memcpy(sd->buf + (addr & 511), sd->data, 512 - (addr & 511));
1610         if (blk_write(sd->blk, addr >> 9, sd->buf, 1) < 0) {
1611             fprintf(stderr, "sd_blk_write: write error on host side\n");
1612             return;
1613         }
1614 
1615         if (blk_read(sd->blk, end >> 9, sd->buf, 1) < 0) {
1616             fprintf(stderr, "sd_blk_write: read error on host side\n");
1617             return;
1618         }
1619         memcpy(sd->buf, sd->data + 512 - (addr & 511), end & 511);
1620         if (blk_write(sd->blk, end >> 9, sd->buf, 1) < 0) {
1621             fprintf(stderr, "sd_blk_write: write error on host side\n");
1622         }
1623     } else {
1624         memcpy(sd->buf + (addr & 511), sd->data, len);
1625         if (!sd->blk || blk_write(sd->blk, addr >> 9, sd->buf, 1) < 0) {
1626             fprintf(stderr, "sd_blk_write: write error on host side\n");
1627         }
1628     }
1629 }
1630 
1631 #define BLK_READ_BLOCK(a, len)	sd_blk_read(sd, a, len)
1632 #define BLK_WRITE_BLOCK(a, len)	sd_blk_write(sd, a, len)
1633 #define APP_READ_BLOCK(a, len)	memset(sd->data, 0xec, len)
1634 #define APP_WRITE_BLOCK(a, len)
1635 
1636 void sd_write_data(SDState *sd, uint8_t value)
1637 {
1638     int i;
1639 
1640     if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable)
1641         return;
1642 
1643     if (sd->state != sd_receivingdata_state) {
1644         qemu_log_mask(LOG_GUEST_ERROR,
1645                       "sd_write_data: not in Receiving-Data state\n");
1646         return;
1647     }
1648 
1649     if (sd->card_status & (ADDRESS_ERROR | WP_VIOLATION))
1650         return;
1651 
1652     switch (sd->current_cmd) {
1653     case 24:	/* CMD24:  WRITE_SINGLE_BLOCK */
1654         sd->data[sd->data_offset ++] = value;
1655         if (sd->data_offset >= sd->blk_len) {
1656             /* TODO: Check CRC before committing */
1657             sd->state = sd_programming_state;
1658             BLK_WRITE_BLOCK(sd->data_start, sd->data_offset);
1659             sd->blk_written ++;
1660             sd->csd[14] |= 0x40;
1661             /* Bzzzzzzztt .... Operation complete.  */
1662             sd->state = sd_transfer_state;
1663         }
1664         break;
1665 
1666     case 25:	/* CMD25:  WRITE_MULTIPLE_BLOCK */
1667         if (sd->data_offset == 0) {
1668             /* Start of the block - let's check the address is valid */
1669             if (sd->data_start + sd->blk_len > sd->size) {
1670                 sd->card_status |= ADDRESS_ERROR;
1671                 break;
1672             }
1673             if (sd_wp_addr(sd, sd->data_start)) {
1674                 sd->card_status |= WP_VIOLATION;
1675                 break;
1676             }
1677         }
1678         sd->data[sd->data_offset++] = value;
1679         if (sd->data_offset >= sd->blk_len) {
1680             /* TODO: Check CRC before committing */
1681             sd->state = sd_programming_state;
1682             BLK_WRITE_BLOCK(sd->data_start, sd->data_offset);
1683             sd->blk_written++;
1684             sd->data_start += sd->blk_len;
1685             sd->data_offset = 0;
1686             sd->csd[14] |= 0x40;
1687 
1688             /* Bzzzzzzztt .... Operation complete.  */
1689             if (sd->multi_blk_cnt != 0) {
1690                 if (--sd->multi_blk_cnt == 0) {
1691                     /* Stop! */
1692                     sd->state = sd_transfer_state;
1693                     break;
1694                 }
1695             }
1696 
1697             sd->state = sd_receivingdata_state;
1698         }
1699         break;
1700 
1701     case 26:	/* CMD26:  PROGRAM_CID */
1702         sd->data[sd->data_offset ++] = value;
1703         if (sd->data_offset >= sizeof(sd->cid)) {
1704             /* TODO: Check CRC before committing */
1705             sd->state = sd_programming_state;
1706             for (i = 0; i < sizeof(sd->cid); i ++)
1707                 if ((sd->cid[i] | 0x00) != sd->data[i])
1708                     sd->card_status |= CID_CSD_OVERWRITE;
1709 
1710             if (!(sd->card_status & CID_CSD_OVERWRITE))
1711                 for (i = 0; i < sizeof(sd->cid); i ++) {
1712                     sd->cid[i] |= 0x00;
1713                     sd->cid[i] &= sd->data[i];
1714                 }
1715             /* Bzzzzzzztt .... Operation complete.  */
1716             sd->state = sd_transfer_state;
1717         }
1718         break;
1719 
1720     case 27:	/* CMD27:  PROGRAM_CSD */
1721         sd->data[sd->data_offset ++] = value;
1722         if (sd->data_offset >= sizeof(sd->csd)) {
1723             /* TODO: Check CRC before committing */
1724             sd->state = sd_programming_state;
1725             for (i = 0; i < sizeof(sd->csd); i ++)
1726                 if ((sd->csd[i] | sd_csd_rw_mask[i]) !=
1727                     (sd->data[i] | sd_csd_rw_mask[i]))
1728                     sd->card_status |= CID_CSD_OVERWRITE;
1729 
1730             /* Copy flag (OTP) & Permanent write protect */
1731             if (sd->csd[14] & ~sd->data[14] & 0x60)
1732                 sd->card_status |= CID_CSD_OVERWRITE;
1733 
1734             if (!(sd->card_status & CID_CSD_OVERWRITE))
1735                 for (i = 0; i < sizeof(sd->csd); i ++) {
1736                     sd->csd[i] |= sd_csd_rw_mask[i];
1737                     sd->csd[i] &= sd->data[i];
1738                 }
1739             /* Bzzzzzzztt .... Operation complete.  */
1740             sd->state = sd_transfer_state;
1741         }
1742         break;
1743 
1744     case 42:	/* CMD42:  LOCK_UNLOCK */
1745         sd->data[sd->data_offset ++] = value;
1746         if (sd->data_offset >= sd->blk_len) {
1747             /* TODO: Check CRC before committing */
1748             sd->state = sd_programming_state;
1749             sd_lock_command(sd);
1750             /* Bzzzzzzztt .... Operation complete.  */
1751             sd->state = sd_transfer_state;
1752         }
1753         break;
1754 
1755     case 56:	/* CMD56:  GEN_CMD */
1756         sd->data[sd->data_offset ++] = value;
1757         if (sd->data_offset >= sd->blk_len) {
1758             APP_WRITE_BLOCK(sd->data_start, sd->data_offset);
1759             sd->state = sd_transfer_state;
1760         }
1761         break;
1762 
1763     default:
1764         qemu_log_mask(LOG_GUEST_ERROR, "sd_write_data: unknown command\n");
1765         break;
1766     }
1767 }
1768 
1769 uint8_t sd_read_data(SDState *sd)
1770 {
1771     /* TODO: Append CRCs */
1772     uint8_t ret;
1773     int io_len;
1774 
1775     if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable)
1776         return 0x00;
1777 
1778     if (sd->state != sd_sendingdata_state) {
1779         qemu_log_mask(LOG_GUEST_ERROR,
1780                       "sd_read_data: not in Sending-Data state\n");
1781         return 0x00;
1782     }
1783 
1784     if (sd->card_status & (ADDRESS_ERROR | WP_VIOLATION))
1785         return 0x00;
1786 
1787     io_len = (sd->ocr & (1 << 30)) ? 512 : sd->blk_len;
1788 
1789     switch (sd->current_cmd) {
1790     case 6:	/* CMD6:   SWITCH_FUNCTION */
1791         ret = sd->data[sd->data_offset ++];
1792 
1793         if (sd->data_offset >= 64)
1794             sd->state = sd_transfer_state;
1795         break;
1796 
1797     case 9:	/* CMD9:   SEND_CSD */
1798     case 10:	/* CMD10:  SEND_CID */
1799         ret = sd->data[sd->data_offset ++];
1800 
1801         if (sd->data_offset >= 16)
1802             sd->state = sd_transfer_state;
1803         break;
1804 
1805     case 11:	/* CMD11:  READ_DAT_UNTIL_STOP */
1806         if (sd->data_offset == 0)
1807             BLK_READ_BLOCK(sd->data_start, io_len);
1808         ret = sd->data[sd->data_offset ++];
1809 
1810         if (sd->data_offset >= io_len) {
1811             sd->data_start += io_len;
1812             sd->data_offset = 0;
1813             if (sd->data_start + io_len > sd->size) {
1814                 sd->card_status |= ADDRESS_ERROR;
1815                 break;
1816             }
1817         }
1818         break;
1819 
1820     case 13:	/* ACMD13: SD_STATUS */
1821         ret = sd->sd_status[sd->data_offset ++];
1822 
1823         if (sd->data_offset >= sizeof(sd->sd_status))
1824             sd->state = sd_transfer_state;
1825         break;
1826 
1827     case 17:	/* CMD17:  READ_SINGLE_BLOCK */
1828         if (sd->data_offset == 0)
1829             BLK_READ_BLOCK(sd->data_start, io_len);
1830         ret = sd->data[sd->data_offset ++];
1831 
1832         if (sd->data_offset >= io_len)
1833             sd->state = sd_transfer_state;
1834         break;
1835 
1836     case 18:	/* CMD18:  READ_MULTIPLE_BLOCK */
1837         if (sd->data_offset == 0)
1838             BLK_READ_BLOCK(sd->data_start, io_len);
1839         ret = sd->data[sd->data_offset ++];
1840 
1841         if (sd->data_offset >= io_len) {
1842             sd->data_start += io_len;
1843             sd->data_offset = 0;
1844 
1845             if (sd->multi_blk_cnt != 0) {
1846                 if (--sd->multi_blk_cnt == 0) {
1847                     /* Stop! */
1848                     sd->state = sd_transfer_state;
1849                     break;
1850                 }
1851             }
1852 
1853             if (sd->data_start + io_len > sd->size) {
1854                 sd->card_status |= ADDRESS_ERROR;
1855                 break;
1856             }
1857         }
1858         break;
1859 
1860     case 22:	/* ACMD22: SEND_NUM_WR_BLOCKS */
1861         ret = sd->data[sd->data_offset ++];
1862 
1863         if (sd->data_offset >= 4)
1864             sd->state = sd_transfer_state;
1865         break;
1866 
1867     case 30:	/* CMD30:  SEND_WRITE_PROT */
1868         ret = sd->data[sd->data_offset ++];
1869 
1870         if (sd->data_offset >= 4)
1871             sd->state = sd_transfer_state;
1872         break;
1873 
1874     case 51:	/* ACMD51: SEND_SCR */
1875         ret = sd->scr[sd->data_offset ++];
1876 
1877         if (sd->data_offset >= sizeof(sd->scr))
1878             sd->state = sd_transfer_state;
1879         break;
1880 
1881     case 56:	/* CMD56:  GEN_CMD */
1882         if (sd->data_offset == 0)
1883             APP_READ_BLOCK(sd->data_start, sd->blk_len);
1884         ret = sd->data[sd->data_offset ++];
1885 
1886         if (sd->data_offset >= sd->blk_len)
1887             sd->state = sd_transfer_state;
1888         break;
1889 
1890     default:
1891         qemu_log_mask(LOG_GUEST_ERROR, "sd_read_data: unknown command\n");
1892         return 0x00;
1893     }
1894 
1895     return ret;
1896 }
1897 
1898 bool sd_data_ready(SDState *sd)
1899 {
1900     return sd->state == sd_sendingdata_state;
1901 }
1902 
1903 void sd_enable(SDState *sd, bool enable)
1904 {
1905     sd->enable = enable;
1906 }
1907 
1908 static void sd_instance_init(Object *obj)
1909 {
1910     SDState *sd = SD_CARD(obj);
1911 
1912     sd->enable = true;
1913     sd->ocr_power_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, sd_ocr_powerup, sd);
1914 }
1915 
1916 static void sd_realize(DeviceState *dev, Error **errp)
1917 {
1918     SDState *sd = SD_CARD(dev);
1919 
1920     if (sd->blk && blk_is_read_only(sd->blk)) {
1921         error_setg(errp, "Cannot use read-only drive as SD card");
1922         return;
1923     }
1924 
1925     sd->buf = blk_blockalign(sd->blk, 512);
1926 
1927     if (sd->blk) {
1928         blk_set_dev_ops(sd->blk, &sd_block_ops, sd);
1929     }
1930 }
1931 
1932 static Property sd_properties[] = {
1933     DEFINE_PROP_DRIVE("drive", SDState, blk),
1934     /* We do not model the chip select pin, so allow the board to select
1935      * whether card should be in SSI or MMC/SD mode.  It is also up to the
1936      * board to ensure that ssi transfers only occur when the chip select
1937      * is asserted.  */
1938     DEFINE_PROP_BOOL("spi", SDState, spi, false),
1939     DEFINE_PROP_END_OF_LIST()
1940 };
1941 
1942 static void sd_class_init(ObjectClass *klass, void *data)
1943 {
1944     DeviceClass *dc = DEVICE_CLASS(klass);
1945     SDCardClass *sc = SD_CARD_CLASS(klass);
1946 
1947     dc->realize = sd_realize;
1948     dc->props = sd_properties;
1949     dc->vmsd = &sd_vmstate;
1950     dc->reset = sd_reset;
1951     dc->bus_type = TYPE_SD_BUS;
1952 
1953     sc->do_command = sd_do_command;
1954     sc->write_data = sd_write_data;
1955     sc->read_data = sd_read_data;
1956     sc->data_ready = sd_data_ready;
1957     sc->enable = sd_enable;
1958     sc->get_inserted = sd_get_inserted;
1959     sc->get_readonly = sd_get_readonly;
1960 }
1961 
1962 static const TypeInfo sd_info = {
1963     .name = TYPE_SD_CARD,
1964     .parent = TYPE_DEVICE,
1965     .instance_size = sizeof(SDState),
1966     .class_size = sizeof(SDCardClass),
1967     .class_init = sd_class_init,
1968     .instance_init = sd_instance_init,
1969 };
1970 
1971 static void sd_register_types(void)
1972 {
1973     type_register_static(&sd_info);
1974 }
1975 
1976 type_init(sd_register_types)
1977