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