xref: /openbmc/qemu/hw/sd/sd.c (revision c11b0583)
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 "sysemu/block-backend.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 #define ACMD41_ENQUIRY_MASK 0x00ffffff
47 
48 typedef enum {
49     sd_r0 = 0,    /* no response */
50     sd_r1,        /* normal response command */
51     sd_r2_i,      /* CID register */
52     sd_r2_s,      /* CSD register */
53     sd_r3,        /* OCR register */
54     sd_r6 = 6,    /* Published RCA response */
55     sd_r7,        /* Operating voltage */
56     sd_r1b = -1,
57     sd_illegal = -2,
58 } sd_rsp_type_t;
59 
60 enum SDCardModes {
61     sd_inactive,
62     sd_card_identification_mode,
63     sd_data_transfer_mode,
64 };
65 
66 enum SDCardStates {
67     sd_inactive_state = -1,
68     sd_idle_state = 0,
69     sd_ready_state,
70     sd_identification_state,
71     sd_standby_state,
72     sd_transfer_state,
73     sd_sendingdata_state,
74     sd_receivingdata_state,
75     sd_programming_state,
76     sd_disconnect_state,
77 };
78 
79 struct SDState {
80     uint32_t mode;    /* current card mode, one of SDCardModes */
81     int32_t state;    /* current card state, one of SDCardStates */
82     uint32_t ocr;
83     uint8_t scr[8];
84     uint8_t cid[16];
85     uint8_t csd[16];
86     uint16_t rca;
87     uint32_t card_status;
88     uint8_t sd_status[64];
89     uint32_t vhs;
90     bool wp_switch;
91     unsigned long *wp_groups;
92     int32_t wpgrps_size;
93     uint64_t size;
94     uint32_t blk_len;
95     uint32_t erase_start;
96     uint32_t erase_end;
97     uint8_t pwd[16];
98     uint32_t pwd_len;
99     uint8_t function_group[6];
100 
101     bool spi;
102     uint8_t current_cmd;
103     /* True if we will handle the next command as an ACMD. Note that this does
104      * *not* track the APP_CMD status bit!
105      */
106     bool expecting_acmd;
107     uint32_t blk_written;
108     uint64_t data_start;
109     uint32_t data_offset;
110     uint8_t data[512];
111     qemu_irq readonly_cb;
112     qemu_irq inserted_cb;
113     BlockBackend *blk;
114     uint8_t *buf;
115 
116     bool enable;
117 };
118 
119 static void sd_set_mode(SDState *sd)
120 {
121     switch (sd->state) {
122     case sd_inactive_state:
123         sd->mode = sd_inactive;
124         break;
125 
126     case sd_idle_state:
127     case sd_ready_state:
128     case sd_identification_state:
129         sd->mode = sd_card_identification_mode;
130         break;
131 
132     case sd_standby_state:
133     case sd_transfer_state:
134     case sd_sendingdata_state:
135     case sd_receivingdata_state:
136     case sd_programming_state:
137     case sd_disconnect_state:
138         sd->mode = sd_data_transfer_mode;
139         break;
140     }
141 }
142 
143 static const sd_cmd_type_t sd_cmd_type[64] = {
144     sd_bc,   sd_none, sd_bcr,  sd_bcr,  sd_none, sd_none, sd_none, sd_ac,
145     sd_bcr,  sd_ac,   sd_ac,   sd_adtc, sd_ac,   sd_ac,   sd_none, sd_ac,
146     sd_ac,   sd_adtc, sd_adtc, sd_none, sd_none, sd_none, sd_none, sd_none,
147     sd_adtc, sd_adtc, sd_adtc, sd_adtc, sd_ac,   sd_ac,   sd_adtc, sd_none,
148     sd_ac,   sd_ac,   sd_none, sd_none, sd_none, sd_none, sd_ac,   sd_none,
149     sd_none, sd_none, sd_bc,   sd_none, sd_none, sd_none, sd_none, sd_none,
150     sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, sd_ac,
151     sd_adtc, sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, sd_none,
152 };
153 
154 static const int sd_cmd_class[64] = {
155     0,  0,  0,  0,  0,  9, 10,  0,  0,  0,  0,  1,  0,  0,  0,  0,
156     2,  2,  2,  2,  3,  3,  3,  3,  4,  4,  4,  4,  6,  6,  6,  6,
157     5,  5, 10, 10, 10, 10,  5,  9,  9,  9,  7,  7,  7,  7,  7,  7,
158     7,  7, 10,  7,  9,  9,  9,  8,  8, 10,  8,  8,  8,  8,  8,  8,
159 };
160 
161 static uint8_t sd_crc7(void *message, size_t width)
162 {
163     int i, bit;
164     uint8_t shift_reg = 0x00;
165     uint8_t *msg = (uint8_t *) message;
166 
167     for (i = 0; i < width; i ++, msg ++)
168         for (bit = 7; bit >= 0; bit --) {
169             shift_reg <<= 1;
170             if ((shift_reg >> 7) ^ ((*msg >> bit) & 1))
171                 shift_reg ^= 0x89;
172         }
173 
174     return shift_reg;
175 }
176 
177 static uint16_t sd_crc16(void *message, size_t width)
178 {
179     int i, bit;
180     uint16_t shift_reg = 0x0000;
181     uint16_t *msg = (uint16_t *) message;
182     width <<= 1;
183 
184     for (i = 0; i < width; i ++, msg ++)
185         for (bit = 15; bit >= 0; bit --) {
186             shift_reg <<= 1;
187             if ((shift_reg >> 15) ^ ((*msg >> bit) & 1))
188                 shift_reg ^= 0x1011;
189         }
190 
191     return shift_reg;
192 }
193 
194 static void sd_set_ocr(SDState *sd)
195 {
196     /* All voltages OK, card power-up OK, Standard Capacity SD Memory Card */
197     sd->ocr = 0x80ffff00;
198 }
199 
200 static void sd_set_scr(SDState *sd)
201 {
202     sd->scr[0] = 0x00;		/* SCR Structure */
203     sd->scr[1] = 0x2f;		/* SD Security Support */
204     sd->scr[2] = 0x00;
205     sd->scr[3] = 0x00;
206     sd->scr[4] = 0x00;
207     sd->scr[5] = 0x00;
208     sd->scr[6] = 0x00;
209     sd->scr[7] = 0x00;
210 }
211 
212 #define MID	0xaa
213 #define OID	"XY"
214 #define PNM	"QEMU!"
215 #define PRV	0x01
216 #define MDT_YR	2006
217 #define MDT_MON	2
218 
219 static void sd_set_cid(SDState *sd)
220 {
221     sd->cid[0] = MID;		/* Fake card manufacturer ID (MID) */
222     sd->cid[1] = OID[0];	/* OEM/Application ID (OID) */
223     sd->cid[2] = OID[1];
224     sd->cid[3] = PNM[0];	/* Fake product name (PNM) */
225     sd->cid[4] = PNM[1];
226     sd->cid[5] = PNM[2];
227     sd->cid[6] = PNM[3];
228     sd->cid[7] = PNM[4];
229     sd->cid[8] = PRV;		/* Fake product revision (PRV) */
230     sd->cid[9] = 0xde;		/* Fake serial number (PSN) */
231     sd->cid[10] = 0xad;
232     sd->cid[11] = 0xbe;
233     sd->cid[12] = 0xef;
234     sd->cid[13] = 0x00 |	/* Manufacture date (MDT) */
235         ((MDT_YR - 2000) / 10);
236     sd->cid[14] = ((MDT_YR % 10) << 4) | MDT_MON;
237     sd->cid[15] = (sd_crc7(sd->cid, 15) << 1) | 1;
238 }
239 
240 #define HWBLOCK_SHIFT	9			/* 512 bytes */
241 #define SECTOR_SHIFT	5			/* 16 kilobytes */
242 #define WPGROUP_SHIFT	7			/* 2 megs */
243 #define CMULT_SHIFT	9			/* 512 times HWBLOCK_SIZE */
244 #define WPGROUP_SIZE	(1 << (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT))
245 
246 static const uint8_t sd_csd_rw_mask[16] = {
247     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
248     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xfe,
249 };
250 
251 static void sd_set_csd(SDState *sd, uint64_t size)
252 {
253     uint32_t csize = (size >> (CMULT_SHIFT + HWBLOCK_SHIFT)) - 1;
254     uint32_t sectsize = (1 << (SECTOR_SHIFT + 1)) - 1;
255     uint32_t wpsize = (1 << (WPGROUP_SHIFT + 1)) - 1;
256 
257     if (size <= 0x40000000) {	/* Standard Capacity SD */
258         sd->csd[0] = 0x00;	/* CSD structure */
259         sd->csd[1] = 0x26;	/* Data read access-time-1 */
260         sd->csd[2] = 0x00;	/* Data read access-time-2 */
261         sd->csd[3] = 0x5a;	/* Max. data transfer rate */
262         sd->csd[4] = 0x5f;	/* Card Command Classes */
263         sd->csd[5] = 0x50 |	/* Max. read data block length */
264             HWBLOCK_SHIFT;
265         sd->csd[6] = 0xe0 |	/* Partial block for read allowed */
266             ((csize >> 10) & 0x03);
267         sd->csd[7] = 0x00 |	/* Device size */
268             ((csize >> 2) & 0xff);
269         sd->csd[8] = 0x3f |	/* Max. read current */
270             ((csize << 6) & 0xc0);
271         sd->csd[9] = 0xfc |	/* Max. write current */
272             ((CMULT_SHIFT - 2) >> 1);
273         sd->csd[10] = 0x40 |	/* Erase sector size */
274             (((CMULT_SHIFT - 2) << 7) & 0x80) | (sectsize >> 1);
275         sd->csd[11] = 0x00 |	/* Write protect group size */
276             ((sectsize << 7) & 0x80) | wpsize;
277         sd->csd[12] = 0x90 |	/* Write speed factor */
278             (HWBLOCK_SHIFT >> 2);
279         sd->csd[13] = 0x20 |	/* Max. write data block length */
280             ((HWBLOCK_SHIFT << 6) & 0xc0);
281         sd->csd[14] = 0x00;	/* File format group */
282         sd->csd[15] = (sd_crc7(sd->csd, 15) << 1) | 1;
283     } else {			/* SDHC */
284         size /= 512 * 1024;
285         size -= 1;
286         sd->csd[0] = 0x40;
287         sd->csd[1] = 0x0e;
288         sd->csd[2] = 0x00;
289         sd->csd[3] = 0x32;
290         sd->csd[4] = 0x5b;
291         sd->csd[5] = 0x59;
292         sd->csd[6] = 0x00;
293         sd->csd[7] = (size >> 16) & 0xff;
294         sd->csd[8] = (size >> 8) & 0xff;
295         sd->csd[9] = (size & 0xff);
296         sd->csd[10] = 0x7f;
297         sd->csd[11] = 0x80;
298         sd->csd[12] = 0x0a;
299         sd->csd[13] = 0x40;
300         sd->csd[14] = 0x00;
301         sd->csd[15] = 0x00;
302         sd->ocr |= 1 << 30;     /* High Capacity SD Memory Card */
303     }
304 }
305 
306 static void sd_set_rca(SDState *sd)
307 {
308     sd->rca += 0x4567;
309 }
310 
311 /* Card status bits, split by clear condition:
312  * A : According to the card current state
313  * B : Always related to the previous command
314  * C : Cleared by read
315  */
316 #define CARD_STATUS_A	0x02004100
317 #define CARD_STATUS_B	0x00c01e00
318 #define CARD_STATUS_C	0xfd39a028
319 
320 static void sd_set_cardstatus(SDState *sd)
321 {
322     sd->card_status = 0x00000100;
323 }
324 
325 static void sd_set_sdstatus(SDState *sd)
326 {
327     memset(sd->sd_status, 0, 64);
328 }
329 
330 static int sd_req_crc_validate(SDRequest *req)
331 {
332     uint8_t buffer[5];
333     buffer[0] = 0x40 | req->cmd;
334     buffer[1] = (req->arg >> 24) & 0xff;
335     buffer[2] = (req->arg >> 16) & 0xff;
336     buffer[3] = (req->arg >> 8) & 0xff;
337     buffer[4] = (req->arg >> 0) & 0xff;
338     return 0;
339     return sd_crc7(buffer, 5) != req->crc;	/* TODO */
340 }
341 
342 static void sd_response_r1_make(SDState *sd, uint8_t *response)
343 {
344     uint32_t status = sd->card_status;
345     /* Clear the "clear on read" status bits */
346     sd->card_status &= ~CARD_STATUS_C;
347 
348     response[0] = (status >> 24) & 0xff;
349     response[1] = (status >> 16) & 0xff;
350     response[2] = (status >> 8) & 0xff;
351     response[3] = (status >> 0) & 0xff;
352 }
353 
354 static void sd_response_r3_make(SDState *sd, uint8_t *response)
355 {
356     response[0] = (sd->ocr >> 24) & 0xff;
357     response[1] = (sd->ocr >> 16) & 0xff;
358     response[2] = (sd->ocr >> 8) & 0xff;
359     response[3] = (sd->ocr >> 0) & 0xff;
360 }
361 
362 static void sd_response_r6_make(SDState *sd, uint8_t *response)
363 {
364     uint16_t arg;
365     uint16_t status;
366 
367     arg = sd->rca;
368     status = ((sd->card_status >> 8) & 0xc000) |
369              ((sd->card_status >> 6) & 0x2000) |
370               (sd->card_status & 0x1fff);
371     sd->card_status &= ~(CARD_STATUS_C & 0xc81fff);
372 
373     response[0] = (arg >> 8) & 0xff;
374     response[1] = arg & 0xff;
375     response[2] = (status >> 8) & 0xff;
376     response[3] = status & 0xff;
377 }
378 
379 static void sd_response_r7_make(SDState *sd, uint8_t *response)
380 {
381     response[0] = (sd->vhs >> 24) & 0xff;
382     response[1] = (sd->vhs >> 16) & 0xff;
383     response[2] = (sd->vhs >>  8) & 0xff;
384     response[3] = (sd->vhs >>  0) & 0xff;
385 }
386 
387 static inline uint64_t sd_addr_to_wpnum(uint64_t addr)
388 {
389     return addr >> (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT);
390 }
391 
392 static void sd_reset(SDState *sd)
393 {
394     uint64_t size;
395     uint64_t sect;
396 
397     if (sd->blk) {
398         blk_get_geometry(sd->blk, &sect);
399     } else {
400         sect = 0;
401     }
402     size = sect << 9;
403 
404     sect = sd_addr_to_wpnum(size) + 1;
405 
406     sd->state = sd_idle_state;
407     sd->rca = 0x0000;
408     sd_set_ocr(sd);
409     sd_set_scr(sd);
410     sd_set_cid(sd);
411     sd_set_csd(sd, size);
412     sd_set_cardstatus(sd);
413     sd_set_sdstatus(sd);
414 
415     g_free(sd->wp_groups);
416     sd->wp_switch = sd->blk ? blk_is_read_only(sd->blk) : false;
417     sd->wpgrps_size = sect;
418     sd->wp_groups = bitmap_new(sd->wpgrps_size);
419     memset(sd->function_group, 0, sizeof(sd->function_group));
420     sd->erase_start = 0;
421     sd->erase_end = 0;
422     sd->size = size;
423     sd->blk_len = 0x200;
424     sd->pwd_len = 0;
425     sd->expecting_acmd = false;
426 }
427 
428 static void sd_cardchange(void *opaque, bool load)
429 {
430     SDState *sd = opaque;
431 
432     qemu_set_irq(sd->inserted_cb, blk_is_inserted(sd->blk));
433     if (blk_is_inserted(sd->blk)) {
434         sd_reset(sd);
435         qemu_set_irq(sd->readonly_cb, sd->wp_switch);
436     }
437 }
438 
439 static const BlockDevOps sd_block_ops = {
440     .change_media_cb = sd_cardchange,
441 };
442 
443 static const VMStateDescription sd_vmstate = {
444     .name = "sd-card",
445     .version_id = 1,
446     .minimum_version_id = 1,
447     .fields = (VMStateField[]) {
448         VMSTATE_UINT32(mode, SDState),
449         VMSTATE_INT32(state, SDState),
450         VMSTATE_UINT8_ARRAY(cid, SDState, 16),
451         VMSTATE_UINT8_ARRAY(csd, SDState, 16),
452         VMSTATE_UINT16(rca, SDState),
453         VMSTATE_UINT32(card_status, SDState),
454         VMSTATE_PARTIAL_BUFFER(sd_status, SDState, 1),
455         VMSTATE_UINT32(vhs, SDState),
456         VMSTATE_BITMAP(wp_groups, SDState, 0, wpgrps_size),
457         VMSTATE_UINT32(blk_len, SDState),
458         VMSTATE_UINT32(erase_start, SDState),
459         VMSTATE_UINT32(erase_end, SDState),
460         VMSTATE_UINT8_ARRAY(pwd, SDState, 16),
461         VMSTATE_UINT32(pwd_len, SDState),
462         VMSTATE_UINT8_ARRAY(function_group, SDState, 6),
463         VMSTATE_UINT8(current_cmd, SDState),
464         VMSTATE_BOOL(expecting_acmd, SDState),
465         VMSTATE_UINT32(blk_written, SDState),
466         VMSTATE_UINT64(data_start, SDState),
467         VMSTATE_UINT32(data_offset, SDState),
468         VMSTATE_UINT8_ARRAY(data, SDState, 512),
469         VMSTATE_BUFFER_POINTER_UNSAFE(buf, SDState, 1, 512),
470         VMSTATE_BOOL(enable, SDState),
471         VMSTATE_END_OF_LIST()
472     }
473 };
474 
475 /* We do not model the chip select pin, so allow the board to select
476    whether card should be in SSI or MMC/SD mode.  It is also up to the
477    board to ensure that ssi transfers only occur when the chip select
478    is asserted.  */
479 SDState *sd_init(BlockBackend *blk, bool is_spi)
480 {
481     SDState *sd;
482 
483     if (blk && blk_is_read_only(blk)) {
484         fprintf(stderr, "sd_init: Cannot use read-only drive\n");
485         return NULL;
486     }
487 
488     sd = (SDState *) g_malloc0(sizeof(SDState));
489     sd->buf = blk_blockalign(blk, 512);
490     sd->spi = is_spi;
491     sd->enable = true;
492     sd->blk = blk;
493     sd_reset(sd);
494     if (sd->blk) {
495         blk_attach_dev_nofail(sd->blk, sd);
496         blk_set_dev_ops(sd->blk, &sd_block_ops, sd);
497     }
498     vmstate_register(NULL, -1, &sd_vmstate, sd);
499     return sd;
500 }
501 
502 void sd_set_cb(SDState *sd, qemu_irq readonly, qemu_irq insert)
503 {
504     sd->readonly_cb = readonly;
505     sd->inserted_cb = insert;
506     qemu_set_irq(readonly, sd->blk ? blk_is_read_only(sd->blk) : 0);
507     qemu_set_irq(insert, sd->blk ? blk_is_inserted(sd->blk) : 0);
508 }
509 
510 static void sd_erase(SDState *sd)
511 {
512     int i;
513     uint64_t erase_start = sd->erase_start;
514     uint64_t erase_end = sd->erase_end;
515 
516     if (!sd->erase_start || !sd->erase_end) {
517         sd->card_status |= ERASE_SEQ_ERROR;
518         return;
519     }
520 
521     if (extract32(sd->ocr, OCR_CCS_BITN, 1)) {
522         /* High capacity memory card: erase units are 512 byte blocks */
523         erase_start *= 512;
524         erase_end *= 512;
525     }
526 
527     erase_start = sd_addr_to_wpnum(erase_start);
528     erase_end = sd_addr_to_wpnum(erase_end);
529     sd->erase_start = 0;
530     sd->erase_end = 0;
531     sd->csd[14] |= 0x40;
532 
533     for (i = erase_start; i <= erase_end; i++) {
534         if (test_bit(i, sd->wp_groups)) {
535             sd->card_status |= WP_ERASE_SKIP;
536         }
537     }
538 }
539 
540 static uint32_t sd_wpbits(SDState *sd, uint64_t addr)
541 {
542     uint32_t i, wpnum;
543     uint32_t ret = 0;
544 
545     wpnum = sd_addr_to_wpnum(addr);
546 
547     for (i = 0; i < 32; i++, wpnum++, addr += WPGROUP_SIZE) {
548         if (addr < sd->size && test_bit(wpnum, sd->wp_groups)) {
549             ret |= (1 << i);
550         }
551     }
552 
553     return ret;
554 }
555 
556 static void sd_function_switch(SDState *sd, uint32_t arg)
557 {
558     int i, mode, new_func, crc;
559     mode = !!(arg & 0x80000000);
560 
561     sd->data[0] = 0x00;		/* Maximum current consumption */
562     sd->data[1] = 0x01;
563     sd->data[2] = 0x80;		/* Supported group 6 functions */
564     sd->data[3] = 0x01;
565     sd->data[4] = 0x80;		/* Supported group 5 functions */
566     sd->data[5] = 0x01;
567     sd->data[6] = 0x80;		/* Supported group 4 functions */
568     sd->data[7] = 0x01;
569     sd->data[8] = 0x80;		/* Supported group 3 functions */
570     sd->data[9] = 0x01;
571     sd->data[10] = 0x80;	/* Supported group 2 functions */
572     sd->data[11] = 0x43;
573     sd->data[12] = 0x80;	/* Supported group 1 functions */
574     sd->data[13] = 0x03;
575     for (i = 0; i < 6; i ++) {
576         new_func = (arg >> (i * 4)) & 0x0f;
577         if (mode && new_func != 0x0f)
578             sd->function_group[i] = new_func;
579         sd->data[14 + (i >> 1)] = new_func << ((i * 4) & 4);
580     }
581     memset(&sd->data[17], 0, 47);
582     crc = sd_crc16(sd->data, 64);
583     sd->data[65] = crc >> 8;
584     sd->data[66] = crc & 0xff;
585 }
586 
587 static inline bool sd_wp_addr(SDState *sd, uint64_t addr)
588 {
589     return test_bit(sd_addr_to_wpnum(addr), sd->wp_groups);
590 }
591 
592 static void sd_lock_command(SDState *sd)
593 {
594     int erase, lock, clr_pwd, set_pwd, pwd_len;
595     erase = !!(sd->data[0] & 0x08);
596     lock = sd->data[0] & 0x04;
597     clr_pwd = sd->data[0] & 0x02;
598     set_pwd = sd->data[0] & 0x01;
599 
600     if (sd->blk_len > 1)
601         pwd_len = sd->data[1];
602     else
603         pwd_len = 0;
604 
605     if (erase) {
606         if (!(sd->card_status & CARD_IS_LOCKED) || sd->blk_len > 1 ||
607                         set_pwd || clr_pwd || lock || sd->wp_switch ||
608                         (sd->csd[14] & 0x20)) {
609             sd->card_status |= LOCK_UNLOCK_FAILED;
610             return;
611         }
612         bitmap_zero(sd->wp_groups, sd->wpgrps_size);
613         sd->csd[14] &= ~0x10;
614         sd->card_status &= ~CARD_IS_LOCKED;
615         sd->pwd_len = 0;
616         /* Erasing the entire card here! */
617         fprintf(stderr, "SD: Card force-erased by CMD42\n");
618         return;
619     }
620 
621     if (sd->blk_len < 2 + pwd_len ||
622                     pwd_len <= sd->pwd_len ||
623                     pwd_len > sd->pwd_len + 16) {
624         sd->card_status |= LOCK_UNLOCK_FAILED;
625         return;
626     }
627 
628     if (sd->pwd_len && memcmp(sd->pwd, sd->data + 2, sd->pwd_len)) {
629         sd->card_status |= LOCK_UNLOCK_FAILED;
630         return;
631     }
632 
633     pwd_len -= sd->pwd_len;
634     if ((pwd_len && !set_pwd) ||
635                     (clr_pwd && (set_pwd || lock)) ||
636                     (lock && !sd->pwd_len && !set_pwd) ||
637                     (!set_pwd && !clr_pwd &&
638                      (((sd->card_status & CARD_IS_LOCKED) && lock) ||
639                       (!(sd->card_status & CARD_IS_LOCKED) && !lock)))) {
640         sd->card_status |= LOCK_UNLOCK_FAILED;
641         return;
642     }
643 
644     if (set_pwd) {
645         memcpy(sd->pwd, sd->data + 2 + sd->pwd_len, pwd_len);
646         sd->pwd_len = pwd_len;
647     }
648 
649     if (clr_pwd) {
650         sd->pwd_len = 0;
651     }
652 
653     if (lock)
654         sd->card_status |= CARD_IS_LOCKED;
655     else
656         sd->card_status &= ~CARD_IS_LOCKED;
657 }
658 
659 static sd_rsp_type_t sd_normal_command(SDState *sd,
660                                        SDRequest req)
661 {
662     uint32_t rca = 0x0000;
663     uint64_t addr = (sd->ocr & (1 << 30)) ? (uint64_t) req.arg << 9 : req.arg;
664 
665     /* Not interpreting this as an app command */
666     sd->card_status &= ~APP_CMD;
667 
668     if (sd_cmd_type[req.cmd] == sd_ac || sd_cmd_type[req.cmd] == sd_adtc)
669         rca = req.arg >> 16;
670 
671     DPRINTF("CMD%d 0x%08x state %d\n", req.cmd, req.arg, sd->state);
672     switch (req.cmd) {
673     /* Basic commands (Class 0 and Class 1) */
674     case 0:	/* CMD0:   GO_IDLE_STATE */
675         switch (sd->state) {
676         case sd_inactive_state:
677             return sd->spi ? sd_r1 : sd_r0;
678 
679         default:
680             sd->state = sd_idle_state;
681             sd_reset(sd);
682             return sd->spi ? sd_r1 : sd_r0;
683         }
684         break;
685 
686     case 1:	/* CMD1:   SEND_OP_CMD */
687         if (!sd->spi)
688             goto bad_cmd;
689 
690         sd->state = sd_transfer_state;
691         return sd_r1;
692 
693     case 2:	/* CMD2:   ALL_SEND_CID */
694         if (sd->spi)
695             goto bad_cmd;
696         switch (sd->state) {
697         case sd_ready_state:
698             sd->state = sd_identification_state;
699             return sd_r2_i;
700 
701         default:
702             break;
703         }
704         break;
705 
706     case 3:	/* CMD3:   SEND_RELATIVE_ADDR */
707         if (sd->spi)
708             goto bad_cmd;
709         switch (sd->state) {
710         case sd_identification_state:
711         case sd_standby_state:
712             sd->state = sd_standby_state;
713             sd_set_rca(sd);
714             return sd_r6;
715 
716         default:
717             break;
718         }
719         break;
720 
721     case 4:	/* CMD4:   SEND_DSR */
722         if (sd->spi)
723             goto bad_cmd;
724         switch (sd->state) {
725         case sd_standby_state:
726             break;
727 
728         default:
729             break;
730         }
731         break;
732 
733     case 5: /* CMD5: reserved for SDIO cards */
734         return sd_illegal;
735 
736     case 6:	/* CMD6:   SWITCH_FUNCTION */
737         if (sd->spi)
738             goto bad_cmd;
739         switch (sd->mode) {
740         case sd_data_transfer_mode:
741             sd_function_switch(sd, req.arg);
742             sd->state = sd_sendingdata_state;
743             sd->data_start = 0;
744             sd->data_offset = 0;
745             return sd_r1;
746 
747         default:
748             break;
749         }
750         break;
751 
752     case 7:	/* CMD7:   SELECT/DESELECT_CARD */
753         if (sd->spi)
754             goto bad_cmd;
755         switch (sd->state) {
756         case sd_standby_state:
757             if (sd->rca != rca)
758                 return sd_r0;
759 
760             sd->state = sd_transfer_state;
761             return sd_r1b;
762 
763         case sd_transfer_state:
764         case sd_sendingdata_state:
765             if (sd->rca == rca)
766                 break;
767 
768             sd->state = sd_standby_state;
769             return sd_r1b;
770 
771         case sd_disconnect_state:
772             if (sd->rca != rca)
773                 return sd_r0;
774 
775             sd->state = sd_programming_state;
776             return sd_r1b;
777 
778         case sd_programming_state:
779             if (sd->rca == rca)
780                 break;
781 
782             sd->state = sd_disconnect_state;
783             return sd_r1b;
784 
785         default:
786             break;
787         }
788         break;
789 
790     case 8:	/* CMD8:   SEND_IF_COND */
791         /* Physical Layer Specification Version 2.00 command */
792         switch (sd->state) {
793         case sd_idle_state:
794             sd->vhs = 0;
795 
796             /* No response if not exactly one VHS bit is set.  */
797             if (!(req.arg >> 8) || (req.arg >> (ctz32(req.arg & ~0xff) + 1))) {
798                 return sd->spi ? sd_r7 : sd_r0;
799             }
800 
801             /* Accept.  */
802             sd->vhs = req.arg;
803             return sd_r7;
804 
805         default:
806             break;
807         }
808         break;
809 
810     case 9:	/* CMD9:   SEND_CSD */
811         switch (sd->state) {
812         case sd_standby_state:
813             if (sd->rca != rca)
814                 return sd_r0;
815 
816             return sd_r2_s;
817 
818         case sd_transfer_state:
819             if (!sd->spi)
820                 break;
821             sd->state = sd_sendingdata_state;
822             memcpy(sd->data, sd->csd, 16);
823             sd->data_start = addr;
824             sd->data_offset = 0;
825             return sd_r1;
826 
827         default:
828             break;
829         }
830         break;
831 
832     case 10:	/* CMD10:  SEND_CID */
833         switch (sd->state) {
834         case sd_standby_state:
835             if (sd->rca != rca)
836                 return sd_r0;
837 
838             return sd_r2_i;
839 
840         case sd_transfer_state:
841             if (!sd->spi)
842                 break;
843             sd->state = sd_sendingdata_state;
844             memcpy(sd->data, sd->cid, 16);
845             sd->data_start = addr;
846             sd->data_offset = 0;
847             return sd_r1;
848 
849         default:
850             break;
851         }
852         break;
853 
854     case 11:	/* CMD11:  READ_DAT_UNTIL_STOP */
855         if (sd->spi)
856             goto bad_cmd;
857         switch (sd->state) {
858         case sd_transfer_state:
859             sd->state = sd_sendingdata_state;
860             sd->data_start = req.arg;
861             sd->data_offset = 0;
862 
863             if (sd->data_start + sd->blk_len > sd->size)
864                 sd->card_status |= ADDRESS_ERROR;
865             return sd_r0;
866 
867         default:
868             break;
869         }
870         break;
871 
872     case 12:	/* CMD12:  STOP_TRANSMISSION */
873         switch (sd->state) {
874         case sd_sendingdata_state:
875             sd->state = sd_transfer_state;
876             return sd_r1b;
877 
878         case sd_receivingdata_state:
879             sd->state = sd_programming_state;
880             /* Bzzzzzzztt .... Operation complete.  */
881             sd->state = sd_transfer_state;
882             return sd_r1b;
883 
884         default:
885             break;
886         }
887         break;
888 
889     case 13:	/* CMD13:  SEND_STATUS */
890         switch (sd->mode) {
891         case sd_data_transfer_mode:
892             if (sd->rca != rca)
893                 return sd_r0;
894 
895             return sd_r1;
896 
897         default:
898             break;
899         }
900         break;
901 
902     case 15:	/* CMD15:  GO_INACTIVE_STATE */
903         if (sd->spi)
904             goto bad_cmd;
905         switch (sd->mode) {
906         case sd_data_transfer_mode:
907             if (sd->rca != rca)
908                 return sd_r0;
909 
910             sd->state = sd_inactive_state;
911             return sd_r0;
912 
913         default:
914             break;
915         }
916         break;
917 
918     /* Block read commands (Classs 2) */
919     case 16:	/* CMD16:  SET_BLOCKLEN */
920         switch (sd->state) {
921         case sd_transfer_state:
922             if (req.arg > (1 << HWBLOCK_SHIFT))
923                 sd->card_status |= BLOCK_LEN_ERROR;
924             else
925                 sd->blk_len = req.arg;
926 
927             return sd_r1;
928 
929         default:
930             break;
931         }
932         break;
933 
934     case 17:	/* CMD17:  READ_SINGLE_BLOCK */
935         switch (sd->state) {
936         case sd_transfer_state:
937             sd->state = sd_sendingdata_state;
938             sd->data_start = addr;
939             sd->data_offset = 0;
940 
941             if (sd->data_start + sd->blk_len > sd->size)
942                 sd->card_status |= ADDRESS_ERROR;
943             return sd_r1;
944 
945         default:
946             break;
947         }
948         break;
949 
950     case 18:	/* CMD18:  READ_MULTIPLE_BLOCK */
951         switch (sd->state) {
952         case sd_transfer_state:
953             sd->state = sd_sendingdata_state;
954             sd->data_start = addr;
955             sd->data_offset = 0;
956 
957             if (sd->data_start + sd->blk_len > sd->size)
958                 sd->card_status |= ADDRESS_ERROR;
959             return sd_r1;
960 
961         default:
962             break;
963         }
964         break;
965 
966     /* Block write commands (Class 4) */
967     case 24:	/* CMD24:  WRITE_SINGLE_BLOCK */
968         if (sd->spi)
969             goto unimplemented_cmd;
970         switch (sd->state) {
971         case sd_transfer_state:
972             /* Writing in SPI mode not implemented.  */
973             if (sd->spi)
974                 break;
975             sd->state = sd_receivingdata_state;
976             sd->data_start = addr;
977             sd->data_offset = 0;
978             sd->blk_written = 0;
979 
980             if (sd->data_start + sd->blk_len > sd->size)
981                 sd->card_status |= ADDRESS_ERROR;
982             if (sd_wp_addr(sd, sd->data_start))
983                 sd->card_status |= WP_VIOLATION;
984             if (sd->csd[14] & 0x30)
985                 sd->card_status |= WP_VIOLATION;
986             return sd_r1;
987 
988         default:
989             break;
990         }
991         break;
992 
993     case 25:	/* CMD25:  WRITE_MULTIPLE_BLOCK */
994         if (sd->spi)
995             goto unimplemented_cmd;
996         switch (sd->state) {
997         case sd_transfer_state:
998             /* Writing in SPI mode not implemented.  */
999             if (sd->spi)
1000                 break;
1001             sd->state = sd_receivingdata_state;
1002             sd->data_start = addr;
1003             sd->data_offset = 0;
1004             sd->blk_written = 0;
1005 
1006             if (sd->data_start + sd->blk_len > sd->size)
1007                 sd->card_status |= ADDRESS_ERROR;
1008             if (sd_wp_addr(sd, sd->data_start))
1009                 sd->card_status |= WP_VIOLATION;
1010             if (sd->csd[14] & 0x30)
1011                 sd->card_status |= WP_VIOLATION;
1012             return sd_r1;
1013 
1014         default:
1015             break;
1016         }
1017         break;
1018 
1019     case 26:	/* CMD26:  PROGRAM_CID */
1020         if (sd->spi)
1021             goto bad_cmd;
1022         switch (sd->state) {
1023         case sd_transfer_state:
1024             sd->state = sd_receivingdata_state;
1025             sd->data_start = 0;
1026             sd->data_offset = 0;
1027             return sd_r1;
1028 
1029         default:
1030             break;
1031         }
1032         break;
1033 
1034     case 27:	/* CMD27:  PROGRAM_CSD */
1035         if (sd->spi)
1036             goto unimplemented_cmd;
1037         switch (sd->state) {
1038         case sd_transfer_state:
1039             sd->state = sd_receivingdata_state;
1040             sd->data_start = 0;
1041             sd->data_offset = 0;
1042             return sd_r1;
1043 
1044         default:
1045             break;
1046         }
1047         break;
1048 
1049     /* Write protection (Class 6) */
1050     case 28:	/* CMD28:  SET_WRITE_PROT */
1051         switch (sd->state) {
1052         case sd_transfer_state:
1053             if (addr >= sd->size) {
1054                 sd->card_status |= ADDRESS_ERROR;
1055                 return sd_r1b;
1056             }
1057 
1058             sd->state = sd_programming_state;
1059             set_bit(sd_addr_to_wpnum(addr), sd->wp_groups);
1060             /* Bzzzzzzztt .... Operation complete.  */
1061             sd->state = sd_transfer_state;
1062             return sd_r1b;
1063 
1064         default:
1065             break;
1066         }
1067         break;
1068 
1069     case 29:	/* CMD29:  CLR_WRITE_PROT */
1070         switch (sd->state) {
1071         case sd_transfer_state:
1072             if (addr >= sd->size) {
1073                 sd->card_status |= ADDRESS_ERROR;
1074                 return sd_r1b;
1075             }
1076 
1077             sd->state = sd_programming_state;
1078             clear_bit(sd_addr_to_wpnum(addr), sd->wp_groups);
1079             /* Bzzzzzzztt .... Operation complete.  */
1080             sd->state = sd_transfer_state;
1081             return sd_r1b;
1082 
1083         default:
1084             break;
1085         }
1086         break;
1087 
1088     case 30:	/* CMD30:  SEND_WRITE_PROT */
1089         switch (sd->state) {
1090         case sd_transfer_state:
1091             sd->state = sd_sendingdata_state;
1092             *(uint32_t *) sd->data = sd_wpbits(sd, req.arg);
1093             sd->data_start = addr;
1094             sd->data_offset = 0;
1095             return sd_r1b;
1096 
1097         default:
1098             break;
1099         }
1100         break;
1101 
1102     /* Erase commands (Class 5) */
1103     case 32:	/* CMD32:  ERASE_WR_BLK_START */
1104         switch (sd->state) {
1105         case sd_transfer_state:
1106             sd->erase_start = req.arg;
1107             return sd_r1;
1108 
1109         default:
1110             break;
1111         }
1112         break;
1113 
1114     case 33:	/* CMD33:  ERASE_WR_BLK_END */
1115         switch (sd->state) {
1116         case sd_transfer_state:
1117             sd->erase_end = req.arg;
1118             return sd_r1;
1119 
1120         default:
1121             break;
1122         }
1123         break;
1124 
1125     case 38:	/* CMD38:  ERASE */
1126         switch (sd->state) {
1127         case sd_transfer_state:
1128             if (sd->csd[14] & 0x30) {
1129                 sd->card_status |= WP_VIOLATION;
1130                 return sd_r1b;
1131             }
1132 
1133             sd->state = sd_programming_state;
1134             sd_erase(sd);
1135             /* Bzzzzzzztt .... Operation complete.  */
1136             sd->state = sd_transfer_state;
1137             return sd_r1b;
1138 
1139         default:
1140             break;
1141         }
1142         break;
1143 
1144     /* Lock card commands (Class 7) */
1145     case 42:	/* CMD42:  LOCK_UNLOCK */
1146         if (sd->spi)
1147             goto unimplemented_cmd;
1148         switch (sd->state) {
1149         case sd_transfer_state:
1150             sd->state = sd_receivingdata_state;
1151             sd->data_start = 0;
1152             sd->data_offset = 0;
1153             return sd_r1;
1154 
1155         default:
1156             break;
1157         }
1158         break;
1159 
1160     case 52:
1161     case 53:
1162         /* CMD52, CMD53: reserved for SDIO cards
1163          * (see the SDIO Simplified Specification V2.0)
1164          * Handle as illegal command but do not complain
1165          * on stderr, as some OSes may use these in their
1166          * probing for presence of an SDIO card.
1167          */
1168         return sd_illegal;
1169 
1170     /* Application specific commands (Class 8) */
1171     case 55:	/* CMD55:  APP_CMD */
1172         if (sd->rca != rca)
1173             return sd_r0;
1174 
1175         sd->expecting_acmd = true;
1176         sd->card_status |= APP_CMD;
1177         return sd_r1;
1178 
1179     case 56:	/* CMD56:  GEN_CMD */
1180         fprintf(stderr, "SD: GEN_CMD 0x%08x\n", req.arg);
1181 
1182         switch (sd->state) {
1183         case sd_transfer_state:
1184             sd->data_offset = 0;
1185             if (req.arg & 1)
1186                 sd->state = sd_sendingdata_state;
1187             else
1188                 sd->state = sd_receivingdata_state;
1189             return sd_r1;
1190 
1191         default:
1192             break;
1193         }
1194         break;
1195 
1196     default:
1197     bad_cmd:
1198         fprintf(stderr, "SD: Unknown CMD%i\n", req.cmd);
1199         return sd_illegal;
1200 
1201     unimplemented_cmd:
1202         /* Commands that are recognised but not yet implemented in SPI mode.  */
1203         fprintf(stderr, "SD: CMD%i not implemented in SPI mode\n", req.cmd);
1204         return sd_illegal;
1205     }
1206 
1207     fprintf(stderr, "SD: CMD%i in a wrong state\n", req.cmd);
1208     return sd_illegal;
1209 }
1210 
1211 static sd_rsp_type_t sd_app_command(SDState *sd,
1212                                     SDRequest req)
1213 {
1214     DPRINTF("ACMD%d 0x%08x\n", req.cmd, req.arg);
1215     sd->card_status |= APP_CMD;
1216     switch (req.cmd) {
1217     case 6:	/* ACMD6:  SET_BUS_WIDTH */
1218         switch (sd->state) {
1219         case sd_transfer_state:
1220             sd->sd_status[0] &= 0x3f;
1221             sd->sd_status[0] |= (req.arg & 0x03) << 6;
1222             return sd_r1;
1223 
1224         default:
1225             break;
1226         }
1227         break;
1228 
1229     case 13:	/* ACMD13: SD_STATUS */
1230         switch (sd->state) {
1231         case sd_transfer_state:
1232             sd->state = sd_sendingdata_state;
1233             sd->data_start = 0;
1234             sd->data_offset = 0;
1235             return sd_r1;
1236 
1237         default:
1238             break;
1239         }
1240         break;
1241 
1242     case 22:	/* ACMD22: SEND_NUM_WR_BLOCKS */
1243         switch (sd->state) {
1244         case sd_transfer_state:
1245             *(uint32_t *) sd->data = sd->blk_written;
1246 
1247             sd->state = sd_sendingdata_state;
1248             sd->data_start = 0;
1249             sd->data_offset = 0;
1250             return sd_r1;
1251 
1252         default:
1253             break;
1254         }
1255         break;
1256 
1257     case 23:	/* ACMD23: SET_WR_BLK_ERASE_COUNT */
1258         switch (sd->state) {
1259         case sd_transfer_state:
1260             return sd_r1;
1261 
1262         default:
1263             break;
1264         }
1265         break;
1266 
1267     case 41:	/* ACMD41: SD_APP_OP_COND */
1268         if (sd->spi) {
1269             /* SEND_OP_CMD */
1270             sd->state = sd_transfer_state;
1271             return sd_r1;
1272         }
1273         switch (sd->state) {
1274         case sd_idle_state:
1275             /* We accept any voltage.  10000 V is nothing.
1276              *
1277              * We don't model init delay so just advance straight to ready state
1278              * unless it's an enquiry ACMD41 (bits 23:0 == 0).
1279              */
1280             if (req.arg & ACMD41_ENQUIRY_MASK) {
1281                 sd->state = sd_ready_state;
1282             }
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->blk || !blk_is_inserted(sd->blk) || !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->blk || blk_read(sd->blk, 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 (blk_read(sd->blk, 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->blk || blk_read(sd->blk, 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 (blk_write(sd->blk, addr >> 9, sd->buf, 1) < 0) {
1488             fprintf(stderr, "sd_blk_write: write error on host side\n");
1489             return;
1490         }
1491 
1492         if (blk_read(sd->blk, 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 (blk_write(sd->blk, 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->blk || blk_write(sd->blk, 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->blk || !blk_is_inserted(sd->blk) || !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->blk || !blk_is_inserted(sd->blk) || !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