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