cachepc-qemu

Fork of AMDESE/qemu with changes for cachepc side-channel attack
git clone https://git.sinitax.com/sinitax/cachepc-qemu
Log | Files | Refs | Submodules | LICENSE | sfeed.txt

sd.c (64940B)


      1/*
      2 * SD Memory Card emulation as defined in the "SD Memory Card Physical
      3 * layer specification, Version 2.00."
      4 *
      5 * Copyright (c) 2006 Andrzej Zaborowski  <balrog@zabor.org>
      6 * Copyright (c) 2007 CodeSourcery
      7 * Copyright (c) 2018 Philippe Mathieu-Daudé <f4bug@amsat.org>
      8 *
      9 * Redistribution and use in source and binary forms, with or without
     10 * modification, are permitted provided that the following conditions
     11 * are met:
     12 *
     13 * 1. Redistributions of source code must retain the above copyright
     14 *    notice, this list of conditions and the following disclaimer.
     15 * 2. Redistributions in binary form must reproduce the above copyright
     16 *    notice, this list of conditions and the following disclaimer in
     17 *    the documentation and/or other materials provided with the
     18 *    distribution.
     19 *
     20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
     21 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
     22 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
     23 * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR
     24 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
     25 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     26 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
     27 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
     28 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
     30 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     31 */
     32
     33#include "qemu/osdep.h"
     34#include "qemu/units.h"
     35#include "qemu/cutils.h"
     36#include "hw/irq.h"
     37#include "hw/registerfields.h"
     38#include "sysemu/block-backend.h"
     39#include "hw/sd/sd.h"
     40#include "hw/sd/sdcard_legacy.h"
     41#include "migration/vmstate.h"
     42#include "qapi/error.h"
     43#include "qemu/bitmap.h"
     44#include "hw/qdev-properties.h"
     45#include "hw/qdev-properties-system.h"
     46#include "qemu/error-report.h"
     47#include "qemu/timer.h"
     48#include "qemu/log.h"
     49#include "qemu/module.h"
     50#include "qemu-common.h"
     51#include "sdmmc-internal.h"
     52#include "trace.h"
     53
     54//#define DEBUG_SD 1
     55
     56#define SDSC_MAX_CAPACITY   (2 * GiB)
     57
     58#define INVALID_ADDRESS     UINT32_MAX
     59
     60typedef enum {
     61    sd_r0 = 0,    /* no response */
     62    sd_r1,        /* normal response command */
     63    sd_r2_i,      /* CID register */
     64    sd_r2_s,      /* CSD register */
     65    sd_r3,        /* OCR register */
     66    sd_r6 = 6,    /* Published RCA response */
     67    sd_r7,        /* Operating voltage */
     68    sd_r1b = -1,
     69    sd_illegal = -2,
     70} sd_rsp_type_t;
     71
     72enum SDCardModes {
     73    sd_inactive,
     74    sd_card_identification_mode,
     75    sd_data_transfer_mode,
     76};
     77
     78enum SDCardStates {
     79    sd_inactive_state = -1,
     80    sd_idle_state = 0,
     81    sd_ready_state,
     82    sd_identification_state,
     83    sd_standby_state,
     84    sd_transfer_state,
     85    sd_sendingdata_state,
     86    sd_receivingdata_state,
     87    sd_programming_state,
     88    sd_disconnect_state,
     89};
     90
     91struct SDState {
     92    DeviceState parent_obj;
     93
     94    /* If true, created by sd_init() for a non-qdevified caller */
     95    /* TODO purge them with fire */
     96    bool me_no_qdev_me_kill_mammoth_with_rocks;
     97
     98    /* SD Memory Card Registers */
     99    uint32_t ocr;
    100    uint8_t scr[8];
    101    uint8_t cid[16];
    102    uint8_t csd[16];
    103    uint16_t rca;
    104    uint32_t card_status;
    105    uint8_t sd_status[64];
    106
    107    /* Static properties */
    108
    109    uint8_t spec_version;
    110    BlockBackend *blk;
    111    bool spi;
    112
    113    /* Runtime changeables */
    114
    115    uint32_t mode;    /* current card mode, one of SDCardModes */
    116    int32_t state;    /* current card state, one of SDCardStates */
    117    uint32_t vhs;
    118    bool wp_switch;
    119    unsigned long *wp_groups;
    120    int32_t wpgrps_size;
    121    uint64_t size;
    122    uint32_t blk_len;
    123    uint32_t multi_blk_cnt;
    124    uint32_t erase_start;
    125    uint32_t erase_end;
    126    uint8_t pwd[16];
    127    uint32_t pwd_len;
    128    uint8_t function_group[6];
    129    uint8_t current_cmd;
    130    /* True if we will handle the next command as an ACMD. Note that this does
    131     * *not* track the APP_CMD status bit!
    132     */
    133    bool expecting_acmd;
    134    uint32_t blk_written;
    135    uint64_t data_start;
    136    uint32_t data_offset;
    137    uint8_t data[512];
    138    qemu_irq readonly_cb;
    139    qemu_irq inserted_cb;
    140    QEMUTimer *ocr_power_timer;
    141    const char *proto_name;
    142    bool enable;
    143    uint8_t dat_lines;
    144    bool cmd_line;
    145};
    146
    147static void sd_realize(DeviceState *dev, Error **errp);
    148
    149static const char *sd_state_name(enum SDCardStates state)
    150{
    151    static const char *state_name[] = {
    152        [sd_idle_state]             = "idle",
    153        [sd_ready_state]            = "ready",
    154        [sd_identification_state]   = "identification",
    155        [sd_standby_state]          = "standby",
    156        [sd_transfer_state]         = "transfer",
    157        [sd_sendingdata_state]      = "sendingdata",
    158        [sd_receivingdata_state]    = "receivingdata",
    159        [sd_programming_state]      = "programming",
    160        [sd_disconnect_state]       = "disconnect",
    161    };
    162    if (state == sd_inactive_state) {
    163        return "inactive";
    164    }
    165    assert(state < ARRAY_SIZE(state_name));
    166    return state_name[state];
    167}
    168
    169static const char *sd_response_name(sd_rsp_type_t rsp)
    170{
    171    static const char *response_name[] = {
    172        [sd_r0]     = "RESP#0 (no response)",
    173        [sd_r1]     = "RESP#1 (normal cmd)",
    174        [sd_r2_i]   = "RESP#2 (CID reg)",
    175        [sd_r2_s]   = "RESP#2 (CSD reg)",
    176        [sd_r3]     = "RESP#3 (OCR reg)",
    177        [sd_r6]     = "RESP#6 (RCA)",
    178        [sd_r7]     = "RESP#7 (operating voltage)",
    179    };
    180    if (rsp == sd_illegal) {
    181        return "ILLEGAL RESP";
    182    }
    183    if (rsp == sd_r1b) {
    184        rsp = sd_r1;
    185    }
    186    assert(rsp < ARRAY_SIZE(response_name));
    187    return response_name[rsp];
    188}
    189
    190static uint8_t sd_get_dat_lines(SDState *sd)
    191{
    192    return sd->enable ? sd->dat_lines : 0;
    193}
    194
    195static bool sd_get_cmd_line(SDState *sd)
    196{
    197    return sd->enable ? sd->cmd_line : false;
    198}
    199
    200static void sd_set_voltage(SDState *sd, uint16_t millivolts)
    201{
    202    trace_sdcard_set_voltage(millivolts);
    203
    204    switch (millivolts) {
    205    case 3001 ... 3600: /* SD_VOLTAGE_3_3V */
    206    case 2001 ... 3000: /* SD_VOLTAGE_3_0V */
    207        break;
    208    default:
    209        qemu_log_mask(LOG_GUEST_ERROR, "SD card voltage not supported: %.3fV",
    210                      millivolts / 1000.f);
    211    }
    212}
    213
    214static void sd_set_mode(SDState *sd)
    215{
    216    switch (sd->state) {
    217    case sd_inactive_state:
    218        sd->mode = sd_inactive;
    219        break;
    220
    221    case sd_idle_state:
    222    case sd_ready_state:
    223    case sd_identification_state:
    224        sd->mode = sd_card_identification_mode;
    225        break;
    226
    227    case sd_standby_state:
    228    case sd_transfer_state:
    229    case sd_sendingdata_state:
    230    case sd_receivingdata_state:
    231    case sd_programming_state:
    232    case sd_disconnect_state:
    233        sd->mode = sd_data_transfer_mode;
    234        break;
    235    }
    236}
    237
    238static const sd_cmd_type_t sd_cmd_type[SDMMC_CMD_MAX] = {
    239    sd_bc,   sd_none, sd_bcr,  sd_bcr,  sd_none, sd_none, sd_none, sd_ac,
    240    sd_bcr,  sd_ac,   sd_ac,   sd_adtc, sd_ac,   sd_ac,   sd_none, sd_ac,
    241    /* 16 */
    242    sd_ac,   sd_adtc, sd_adtc, sd_none, sd_none, sd_none, sd_none, sd_none,
    243    sd_adtc, sd_adtc, sd_adtc, sd_adtc, sd_ac,   sd_ac,   sd_adtc, sd_none,
    244    /* 32 */
    245    sd_ac,   sd_ac,   sd_none, sd_none, sd_none, sd_none, sd_ac,   sd_none,
    246    sd_none, sd_none, sd_bc,   sd_none, sd_none, sd_none, sd_none, sd_none,
    247    /* 48 */
    248    sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, sd_ac,
    249    sd_adtc, sd_none, sd_none, sd_none, sd_none, sd_none, sd_none, sd_none,
    250};
    251
    252static const int sd_cmd_class[SDMMC_CMD_MAX] = {
    253    0,  0,  0,  0,  0,  9, 10,  0,  0,  0,  0,  1,  0,  0,  0,  0,
    254    2,  2,  2,  2,  3,  3,  3,  3,  4,  4,  4,  4,  6,  6,  6,  6,
    255    5,  5, 10, 10, 10, 10,  5,  9,  9,  9,  7,  7,  7,  7,  7,  7,
    256    7,  7, 10,  7,  9,  9,  9,  8,  8, 10,  8,  8,  8,  8,  8,  8,
    257};
    258
    259static uint8_t sd_crc7(const void *message, size_t width)
    260{
    261    int i, bit;
    262    uint8_t shift_reg = 0x00;
    263    const uint8_t *msg = (const uint8_t *)message;
    264
    265    for (i = 0; i < width; i ++, msg ++)
    266        for (bit = 7; bit >= 0; bit --) {
    267            shift_reg <<= 1;
    268            if ((shift_reg >> 7) ^ ((*msg >> bit) & 1))
    269                shift_reg ^= 0x89;
    270        }
    271
    272    return shift_reg;
    273}
    274
    275#define OCR_POWER_DELAY_NS      500000 /* 0.5ms */
    276
    277FIELD(OCR, VDD_VOLTAGE_WINDOW,          0, 24)
    278FIELD(OCR, VDD_VOLTAGE_WIN_LO,          0,  8)
    279FIELD(OCR, DUAL_VOLTAGE_CARD,           7,  1)
    280FIELD(OCR, VDD_VOLTAGE_WIN_HI,          8, 16)
    281FIELD(OCR, ACCEPT_SWITCH_1V8,          24,  1) /* Only UHS-I */
    282FIELD(OCR, UHS_II_CARD,                29,  1) /* Only UHS-II */
    283FIELD(OCR, CARD_CAPACITY,              30,  1) /* 0:SDSC, 1:SDHC/SDXC */
    284FIELD(OCR, CARD_POWER_UP,              31,  1)
    285
    286#define ACMD41_ENQUIRY_MASK     0x00ffffff
    287#define ACMD41_R3_MASK          (R_OCR_VDD_VOLTAGE_WIN_HI_MASK \
    288                               | R_OCR_ACCEPT_SWITCH_1V8_MASK \
    289                               | R_OCR_UHS_II_CARD_MASK \
    290                               | R_OCR_CARD_CAPACITY_MASK \
    291                               | R_OCR_CARD_POWER_UP_MASK)
    292
    293static void sd_set_ocr(SDState *sd)
    294{
    295    /* All voltages OK */
    296    sd->ocr = R_OCR_VDD_VOLTAGE_WIN_HI_MASK;
    297}
    298
    299static void sd_ocr_powerup(void *opaque)
    300{
    301    SDState *sd = opaque;
    302
    303    trace_sdcard_powerup();
    304    assert(!FIELD_EX32(sd->ocr, OCR, CARD_POWER_UP));
    305
    306    /* card power-up OK */
    307    sd->ocr = FIELD_DP32(sd->ocr, OCR, CARD_POWER_UP, 1);
    308
    309    if (sd->size > SDSC_MAX_CAPACITY) {
    310        sd->ocr = FIELD_DP32(sd->ocr, OCR, CARD_CAPACITY, 1);
    311    }
    312}
    313
    314static void sd_set_scr(SDState *sd)
    315{
    316    sd->scr[0] = 0 << 4;        /* SCR structure version 1.0 */
    317    if (sd->spec_version == SD_PHY_SPECv1_10_VERS) {
    318        sd->scr[0] |= 1;        /* Spec Version 1.10 */
    319    } else {
    320        sd->scr[0] |= 2;        /* Spec Version 2.00 or Version 3.0X */
    321    }
    322    sd->scr[1] = (2 << 4)       /* SDSC Card (Security Version 1.01) */
    323                 | 0b0101;      /* 1-bit or 4-bit width bus modes */
    324    sd->scr[2] = 0x00;          /* Extended Security is not supported. */
    325    if (sd->spec_version >= SD_PHY_SPECv3_01_VERS) {
    326        sd->scr[2] |= 1 << 7;   /* Spec Version 3.0X */
    327    }
    328    sd->scr[3] = 0x00;
    329    /* reserved for manufacturer usage */
    330    sd->scr[4] = 0x00;
    331    sd->scr[5] = 0x00;
    332    sd->scr[6] = 0x00;
    333    sd->scr[7] = 0x00;
    334}
    335
    336#define MID	0xaa
    337#define OID	"XY"
    338#define PNM	"QEMU!"
    339#define PRV	0x01
    340#define MDT_YR	2006
    341#define MDT_MON	2
    342
    343static void sd_set_cid(SDState *sd)
    344{
    345    sd->cid[0] = MID;		/* Fake card manufacturer ID (MID) */
    346    sd->cid[1] = OID[0];	/* OEM/Application ID (OID) */
    347    sd->cid[2] = OID[1];
    348    sd->cid[3] = PNM[0];	/* Fake product name (PNM) */
    349    sd->cid[4] = PNM[1];
    350    sd->cid[5] = PNM[2];
    351    sd->cid[6] = PNM[3];
    352    sd->cid[7] = PNM[4];
    353    sd->cid[8] = PRV;		/* Fake product revision (PRV) */
    354    sd->cid[9] = 0xde;		/* Fake serial number (PSN) */
    355    sd->cid[10] = 0xad;
    356    sd->cid[11] = 0xbe;
    357    sd->cid[12] = 0xef;
    358    sd->cid[13] = 0x00 |	/* Manufacture date (MDT) */
    359        ((MDT_YR - 2000) / 10);
    360    sd->cid[14] = ((MDT_YR % 10) << 4) | MDT_MON;
    361    sd->cid[15] = (sd_crc7(sd->cid, 15) << 1) | 1;
    362}
    363
    364#define HWBLOCK_SHIFT	9			/* 512 bytes */
    365#define SECTOR_SHIFT	5			/* 16 kilobytes */
    366#define WPGROUP_SHIFT	7			/* 2 megs */
    367#define CMULT_SHIFT	9			/* 512 times HWBLOCK_SIZE */
    368#define WPGROUP_SIZE	(1 << (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT))
    369
    370static const uint8_t sd_csd_rw_mask[16] = {
    371    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    372    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xfe,
    373};
    374
    375static void sd_set_csd(SDState *sd, uint64_t size)
    376{
    377    int hwblock_shift = HWBLOCK_SHIFT;
    378    uint32_t csize;
    379    uint32_t sectsize = (1 << (SECTOR_SHIFT + 1)) - 1;
    380    uint32_t wpsize = (1 << (WPGROUP_SHIFT + 1)) - 1;
    381
    382    /* To indicate 2 GiB card, BLOCK_LEN shall be 1024 bytes */
    383    if (size == SDSC_MAX_CAPACITY) {
    384        hwblock_shift += 1;
    385    }
    386    csize = (size >> (CMULT_SHIFT + hwblock_shift)) - 1;
    387
    388    if (size <= SDSC_MAX_CAPACITY) { /* Standard Capacity SD */
    389        sd->csd[0] = 0x00;	/* CSD structure */
    390        sd->csd[1] = 0x26;	/* Data read access-time-1 */
    391        sd->csd[2] = 0x00;	/* Data read access-time-2 */
    392        sd->csd[3] = 0x32;      /* Max. data transfer rate: 25 MHz */
    393        sd->csd[4] = 0x5f;	/* Card Command Classes */
    394        sd->csd[5] = 0x50 |	/* Max. read data block length */
    395            hwblock_shift;
    396        sd->csd[6] = 0xe0 |	/* Partial block for read allowed */
    397            ((csize >> 10) & 0x03);
    398        sd->csd[7] = 0x00 |	/* Device size */
    399            ((csize >> 2) & 0xff);
    400        sd->csd[8] = 0x3f |	/* Max. read current */
    401            ((csize << 6) & 0xc0);
    402        sd->csd[9] = 0xfc |	/* Max. write current */
    403            ((CMULT_SHIFT - 2) >> 1);
    404        sd->csd[10] = 0x40 |	/* Erase sector size */
    405            (((CMULT_SHIFT - 2) << 7) & 0x80) | (sectsize >> 1);
    406        sd->csd[11] = 0x00 |	/* Write protect group size */
    407            ((sectsize << 7) & 0x80) | wpsize;
    408        sd->csd[12] = 0x90 |	/* Write speed factor */
    409            (hwblock_shift >> 2);
    410        sd->csd[13] = 0x20 |	/* Max. write data block length */
    411            ((hwblock_shift << 6) & 0xc0);
    412        sd->csd[14] = 0x00;	/* File format group */
    413    } else {			/* SDHC */
    414        size /= 512 * KiB;
    415        size -= 1;
    416        sd->csd[0] = 0x40;
    417        sd->csd[1] = 0x0e;
    418        sd->csd[2] = 0x00;
    419        sd->csd[3] = 0x32;
    420        sd->csd[4] = 0x5b;
    421        sd->csd[5] = 0x59;
    422        sd->csd[6] = 0x00;
    423        sd->csd[7] = (size >> 16) & 0xff;
    424        sd->csd[8] = (size >> 8) & 0xff;
    425        sd->csd[9] = (size & 0xff);
    426        sd->csd[10] = 0x7f;
    427        sd->csd[11] = 0x80;
    428        sd->csd[12] = 0x0a;
    429        sd->csd[13] = 0x40;
    430        sd->csd[14] = 0x00;
    431    }
    432    sd->csd[15] = (sd_crc7(sd->csd, 15) << 1) | 1;
    433}
    434
    435static void sd_set_rca(SDState *sd)
    436{
    437    sd->rca += 0x4567;
    438}
    439
    440FIELD(CSR, AKE_SEQ_ERROR,               3,  1)
    441FIELD(CSR, APP_CMD,                     5,  1)
    442FIELD(CSR, FX_EVENT,                    6,  1)
    443FIELD(CSR, READY_FOR_DATA,              8,  1)
    444FIELD(CSR, CURRENT_STATE,               9,  4)
    445FIELD(CSR, ERASE_RESET,                13,  1)
    446FIELD(CSR, CARD_ECC_DISABLED,          14,  1)
    447FIELD(CSR, WP_ERASE_SKIP,              15,  1)
    448FIELD(CSR, CSD_OVERWRITE,              16,  1)
    449FIELD(CSR, DEFERRED_RESPONSE,          17,  1)
    450FIELD(CSR, ERROR,                      19,  1)
    451FIELD(CSR, CC_ERROR,                   20,  1)
    452FIELD(CSR, CARD_ECC_FAILED,            21,  1)
    453FIELD(CSR, ILLEGAL_COMMAND,            22,  1)
    454FIELD(CSR, COM_CRC_ERROR,              23,  1)
    455FIELD(CSR, LOCK_UNLOCK_FAILED,         24,  1)
    456FIELD(CSR, CARD_IS_LOCKED,             25,  1)
    457FIELD(CSR, WP_VIOLATION,               26,  1)
    458FIELD(CSR, ERASE_PARAM,                27,  1)
    459FIELD(CSR, ERASE_SEQ_ERROR,            28,  1)
    460FIELD(CSR, BLOCK_LEN_ERROR,            29,  1)
    461FIELD(CSR, ADDRESS_ERROR,              30,  1)
    462FIELD(CSR, OUT_OF_RANGE,               31,  1)
    463
    464/* Card status bits, split by clear condition:
    465 * A : According to the card current state
    466 * B : Always related to the previous command
    467 * C : Cleared by read
    468 */
    469#define CARD_STATUS_A           (R_CSR_READY_FOR_DATA_MASK \
    470                               | R_CSR_CARD_ECC_DISABLED_MASK \
    471                               | R_CSR_CARD_IS_LOCKED_MASK)
    472#define CARD_STATUS_B           (R_CSR_CURRENT_STATE_MASK \
    473                               | R_CSR_ILLEGAL_COMMAND_MASK \
    474                               | R_CSR_COM_CRC_ERROR_MASK)
    475#define CARD_STATUS_C           (R_CSR_AKE_SEQ_ERROR_MASK \
    476                               | R_CSR_APP_CMD_MASK \
    477                               | R_CSR_ERASE_RESET_MASK \
    478                               | R_CSR_WP_ERASE_SKIP_MASK \
    479                               | R_CSR_CSD_OVERWRITE_MASK \
    480                               | R_CSR_ERROR_MASK \
    481                               | R_CSR_CC_ERROR_MASK \
    482                               | R_CSR_CARD_ECC_FAILED_MASK \
    483                               | R_CSR_LOCK_UNLOCK_FAILED_MASK \
    484                               | R_CSR_WP_VIOLATION_MASK \
    485                               | R_CSR_ERASE_PARAM_MASK \
    486                               | R_CSR_ERASE_SEQ_ERROR_MASK \
    487                               | R_CSR_BLOCK_LEN_ERROR_MASK \
    488                               | R_CSR_ADDRESS_ERROR_MASK \
    489                               | R_CSR_OUT_OF_RANGE_MASK)
    490
    491static void sd_set_cardstatus(SDState *sd)
    492{
    493    sd->card_status = 0x00000100;
    494}
    495
    496static void sd_set_sdstatus(SDState *sd)
    497{
    498    memset(sd->sd_status, 0, 64);
    499}
    500
    501static int sd_req_crc_validate(SDRequest *req)
    502{
    503    uint8_t buffer[5];
    504    buffer[0] = 0x40 | req->cmd;
    505    stl_be_p(&buffer[1], req->arg);
    506    return 0;
    507    return sd_crc7(buffer, 5) != req->crc;	/* TODO */
    508}
    509
    510static void sd_response_r1_make(SDState *sd, uint8_t *response)
    511{
    512    stl_be_p(response, sd->card_status);
    513
    514    /* Clear the "clear on read" status bits */
    515    sd->card_status &= ~CARD_STATUS_C;
    516}
    517
    518static void sd_response_r3_make(SDState *sd, uint8_t *response)
    519{
    520    stl_be_p(response, sd->ocr & ACMD41_R3_MASK);
    521}
    522
    523static void sd_response_r6_make(SDState *sd, uint8_t *response)
    524{
    525    uint16_t status;
    526
    527    status = ((sd->card_status >> 8) & 0xc000) |
    528             ((sd->card_status >> 6) & 0x2000) |
    529              (sd->card_status & 0x1fff);
    530    sd->card_status &= ~(CARD_STATUS_C & 0xc81fff);
    531    stw_be_p(response + 0, sd->rca);
    532    stw_be_p(response + 2, status);
    533}
    534
    535static void sd_response_r7_make(SDState *sd, uint8_t *response)
    536{
    537    stl_be_p(response, sd->vhs);
    538}
    539
    540static inline uint64_t sd_addr_to_wpnum(uint64_t addr)
    541{
    542    return addr >> (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT);
    543}
    544
    545static void sd_reset(DeviceState *dev)
    546{
    547    SDState *sd = SD_CARD(dev);
    548    uint64_t size;
    549    uint64_t sect;
    550
    551    trace_sdcard_reset();
    552    if (sd->blk) {
    553        blk_get_geometry(sd->blk, &sect);
    554    } else {
    555        sect = 0;
    556    }
    557    size = sect << 9;
    558
    559    sect = sd_addr_to_wpnum(size) + 1;
    560
    561    sd->state = sd_idle_state;
    562    sd->rca = 0x0000;
    563    sd_set_ocr(sd);
    564    sd_set_scr(sd);
    565    sd_set_cid(sd);
    566    sd_set_csd(sd, size);
    567    sd_set_cardstatus(sd);
    568    sd_set_sdstatus(sd);
    569
    570    g_free(sd->wp_groups);
    571    sd->wp_switch = sd->blk ? !blk_is_writable(sd->blk) : false;
    572    sd->wpgrps_size = sect;
    573    sd->wp_groups = bitmap_new(sd->wpgrps_size);
    574    memset(sd->function_group, 0, sizeof(sd->function_group));
    575    sd->erase_start = INVALID_ADDRESS;
    576    sd->erase_end = INVALID_ADDRESS;
    577    sd->size = size;
    578    sd->blk_len = 0x200;
    579    sd->pwd_len = 0;
    580    sd->expecting_acmd = false;
    581    sd->dat_lines = 0xf;
    582    sd->cmd_line = true;
    583    sd->multi_blk_cnt = 0;
    584}
    585
    586static bool sd_get_inserted(SDState *sd)
    587{
    588    return sd->blk && blk_is_inserted(sd->blk);
    589}
    590
    591static bool sd_get_readonly(SDState *sd)
    592{
    593    return sd->wp_switch;
    594}
    595
    596static void sd_cardchange(void *opaque, bool load, Error **errp)
    597{
    598    SDState *sd = opaque;
    599    DeviceState *dev = DEVICE(sd);
    600    SDBus *sdbus;
    601    bool inserted = sd_get_inserted(sd);
    602    bool readonly = sd_get_readonly(sd);
    603
    604    if (inserted) {
    605        trace_sdcard_inserted(readonly);
    606        sd_reset(dev);
    607    } else {
    608        trace_sdcard_ejected();
    609    }
    610
    611    if (sd->me_no_qdev_me_kill_mammoth_with_rocks) {
    612        qemu_set_irq(sd->inserted_cb, inserted);
    613        if (inserted) {
    614            qemu_set_irq(sd->readonly_cb, readonly);
    615        }
    616    } else {
    617        sdbus = SD_BUS(qdev_get_parent_bus(dev));
    618        sdbus_set_inserted(sdbus, inserted);
    619        if (inserted) {
    620            sdbus_set_readonly(sdbus, readonly);
    621        }
    622    }
    623}
    624
    625static const BlockDevOps sd_block_ops = {
    626    .change_media_cb = sd_cardchange,
    627};
    628
    629static bool sd_ocr_vmstate_needed(void *opaque)
    630{
    631    SDState *sd = opaque;
    632
    633    /* Include the OCR state (and timer) if it is not yet powered up */
    634    return !FIELD_EX32(sd->ocr, OCR, CARD_POWER_UP);
    635}
    636
    637static const VMStateDescription sd_ocr_vmstate = {
    638    .name = "sd-card/ocr-state",
    639    .version_id = 1,
    640    .minimum_version_id = 1,
    641    .needed = sd_ocr_vmstate_needed,
    642    .fields = (VMStateField[]) {
    643        VMSTATE_UINT32(ocr, SDState),
    644        VMSTATE_TIMER_PTR(ocr_power_timer, SDState),
    645        VMSTATE_END_OF_LIST()
    646    },
    647};
    648
    649static int sd_vmstate_pre_load(void *opaque)
    650{
    651    SDState *sd = opaque;
    652
    653    /* If the OCR state is not included (prior versions, or not
    654     * needed), then the OCR must be set as powered up. If the OCR state
    655     * is included, this will be replaced by the state restore.
    656     */
    657    sd_ocr_powerup(sd);
    658
    659    return 0;
    660}
    661
    662static const VMStateDescription sd_vmstate = {
    663    .name = "sd-card",
    664    .version_id = 2,
    665    .minimum_version_id = 2,
    666    .pre_load = sd_vmstate_pre_load,
    667    .fields = (VMStateField[]) {
    668        VMSTATE_UINT32(mode, SDState),
    669        VMSTATE_INT32(state, SDState),
    670        VMSTATE_UINT8_ARRAY(cid, SDState, 16),
    671        VMSTATE_UINT8_ARRAY(csd, SDState, 16),
    672        VMSTATE_UINT16(rca, SDState),
    673        VMSTATE_UINT32(card_status, SDState),
    674        VMSTATE_PARTIAL_BUFFER(sd_status, SDState, 1),
    675        VMSTATE_UINT32(vhs, SDState),
    676        VMSTATE_BITMAP(wp_groups, SDState, 0, wpgrps_size),
    677        VMSTATE_UINT32(blk_len, SDState),
    678        VMSTATE_UINT32(multi_blk_cnt, SDState),
    679        VMSTATE_UINT32(erase_start, SDState),
    680        VMSTATE_UINT32(erase_end, SDState),
    681        VMSTATE_UINT8_ARRAY(pwd, SDState, 16),
    682        VMSTATE_UINT32(pwd_len, SDState),
    683        VMSTATE_UINT8_ARRAY(function_group, SDState, 6),
    684        VMSTATE_UINT8(current_cmd, SDState),
    685        VMSTATE_BOOL(expecting_acmd, SDState),
    686        VMSTATE_UINT32(blk_written, SDState),
    687        VMSTATE_UINT64(data_start, SDState),
    688        VMSTATE_UINT32(data_offset, SDState),
    689        VMSTATE_UINT8_ARRAY(data, SDState, 512),
    690        VMSTATE_UNUSED_V(1, 512),
    691        VMSTATE_BOOL(enable, SDState),
    692        VMSTATE_END_OF_LIST()
    693    },
    694    .subsections = (const VMStateDescription*[]) {
    695        &sd_ocr_vmstate,
    696        NULL
    697    },
    698};
    699
    700/* Legacy initialization function for use by non-qdevified callers */
    701SDState *sd_init(BlockBackend *blk, bool is_spi)
    702{
    703    Object *obj;
    704    DeviceState *dev;
    705    SDState *sd;
    706    Error *err = NULL;
    707
    708    obj = object_new(TYPE_SD_CARD);
    709    dev = DEVICE(obj);
    710    if (!qdev_prop_set_drive_err(dev, "drive", blk, &err)) {
    711        error_reportf_err(err, "sd_init failed: ");
    712        return NULL;
    713    }
    714    qdev_prop_set_bit(dev, "spi", is_spi);
    715
    716    /*
    717     * Realizing the device properly would put it into the QOM
    718     * composition tree even though it is not plugged into an
    719     * appropriate bus.  That's a no-no.  Hide the device from
    720     * QOM/qdev, and call its qdev realize callback directly.
    721     */
    722    object_ref(obj);
    723    object_unparent(obj);
    724    sd_realize(dev, &err);
    725    if (err) {
    726        error_reportf_err(err, "sd_init failed: ");
    727        return NULL;
    728    }
    729
    730    sd = SD_CARD(dev);
    731    sd->me_no_qdev_me_kill_mammoth_with_rocks = true;
    732    return sd;
    733}
    734
    735void sd_set_cb(SDState *sd, qemu_irq readonly, qemu_irq insert)
    736{
    737    sd->readonly_cb = readonly;
    738    sd->inserted_cb = insert;
    739    qemu_set_irq(readonly, sd->blk ? !blk_is_writable(sd->blk) : 0);
    740    qemu_set_irq(insert, sd->blk ? blk_is_inserted(sd->blk) : 0);
    741}
    742
    743static void sd_blk_read(SDState *sd, uint64_t addr, uint32_t len)
    744{
    745    trace_sdcard_read_block(addr, len);
    746    if (!sd->blk || blk_pread(sd->blk, addr, sd->data, len) < 0) {
    747        fprintf(stderr, "sd_blk_read: read error on host side\n");
    748    }
    749}
    750
    751static void sd_blk_write(SDState *sd, uint64_t addr, uint32_t len)
    752{
    753    trace_sdcard_write_block(addr, len);
    754    if (!sd->blk || blk_pwrite(sd->blk, addr, sd->data, len, 0) < 0) {
    755        fprintf(stderr, "sd_blk_write: write error on host side\n");
    756    }
    757}
    758
    759#define BLK_READ_BLOCK(a, len)  sd_blk_read(sd, a, len)
    760#define BLK_WRITE_BLOCK(a, len) sd_blk_write(sd, a, len)
    761#define APP_READ_BLOCK(a, len)  memset(sd->data, 0xec, len)
    762#define APP_WRITE_BLOCK(a, len)
    763
    764static void sd_erase(SDState *sd)
    765{
    766    uint64_t erase_start = sd->erase_start;
    767    uint64_t erase_end = sd->erase_end;
    768    bool sdsc = true;
    769    uint64_t wpnum;
    770    uint64_t erase_addr;
    771    int erase_len = 1 << HWBLOCK_SHIFT;
    772
    773    trace_sdcard_erase(sd->erase_start, sd->erase_end);
    774    if (sd->erase_start == INVALID_ADDRESS
    775            || sd->erase_end == INVALID_ADDRESS) {
    776        sd->card_status |= ERASE_SEQ_ERROR;
    777        sd->erase_start = INVALID_ADDRESS;
    778        sd->erase_end = INVALID_ADDRESS;
    779        return;
    780    }
    781
    782    if (FIELD_EX32(sd->ocr, OCR, CARD_CAPACITY)) {
    783        /* High capacity memory card: erase units are 512 byte blocks */
    784        erase_start *= 512;
    785        erase_end *= 512;
    786        sdsc = false;
    787    }
    788
    789    if (erase_start > sd->size || erase_end > sd->size) {
    790        sd->card_status |= OUT_OF_RANGE;
    791        sd->erase_start = INVALID_ADDRESS;
    792        sd->erase_end = INVALID_ADDRESS;
    793        return;
    794    }
    795
    796    sd->erase_start = INVALID_ADDRESS;
    797    sd->erase_end = INVALID_ADDRESS;
    798    sd->csd[14] |= 0x40;
    799
    800    memset(sd->data, 0xff, erase_len);
    801    for (erase_addr = erase_start; erase_addr <= erase_end;
    802         erase_addr += erase_len) {
    803        if (sdsc) {
    804            /* Only SDSC cards support write protect groups */
    805            wpnum = sd_addr_to_wpnum(erase_addr);
    806            assert(wpnum < sd->wpgrps_size);
    807            if (test_bit(wpnum, sd->wp_groups)) {
    808                sd->card_status |= WP_ERASE_SKIP;
    809                continue;
    810            }
    811        }
    812        BLK_WRITE_BLOCK(erase_addr, erase_len);
    813    }
    814}
    815
    816static uint32_t sd_wpbits(SDState *sd, uint64_t addr)
    817{
    818    uint32_t i, wpnum;
    819    uint32_t ret = 0;
    820
    821    wpnum = sd_addr_to_wpnum(addr);
    822
    823    for (i = 0; i < 32; i++, wpnum++, addr += WPGROUP_SIZE) {
    824        if (addr >= sd->size) {
    825            /*
    826             * If the addresses of the last groups are outside the valid range,
    827             * then the corresponding write protection bits shall be set to 0.
    828             */
    829            continue;
    830        }
    831        assert(wpnum < sd->wpgrps_size);
    832        if (test_bit(wpnum, sd->wp_groups)) {
    833            ret |= (1 << i);
    834        }
    835    }
    836
    837    return ret;
    838}
    839
    840static void sd_function_switch(SDState *sd, uint32_t arg)
    841{
    842    int i, mode, new_func;
    843    mode = !!(arg & 0x80000000);
    844
    845    sd->data[0] = 0x00;		/* Maximum current consumption */
    846    sd->data[1] = 0x01;
    847    sd->data[2] = 0x80;		/* Supported group 6 functions */
    848    sd->data[3] = 0x01;
    849    sd->data[4] = 0x80;		/* Supported group 5 functions */
    850    sd->data[5] = 0x01;
    851    sd->data[6] = 0x80;		/* Supported group 4 functions */
    852    sd->data[7] = 0x01;
    853    sd->data[8] = 0x80;		/* Supported group 3 functions */
    854    sd->data[9] = 0x01;
    855    sd->data[10] = 0x80;	/* Supported group 2 functions */
    856    sd->data[11] = 0x43;
    857    sd->data[12] = 0x80;	/* Supported group 1 functions */
    858    sd->data[13] = 0x03;
    859
    860    memset(&sd->data[14], 0, 3);
    861    for (i = 0; i < 6; i ++) {
    862        new_func = (arg >> (i * 4)) & 0x0f;
    863        if (mode && new_func != 0x0f)
    864            sd->function_group[i] = new_func;
    865        sd->data[16 - (i >> 1)] |= new_func << ((i % 2) * 4);
    866    }
    867    memset(&sd->data[17], 0, 47);
    868}
    869
    870static inline bool sd_wp_addr(SDState *sd, uint64_t addr)
    871{
    872    return test_bit(sd_addr_to_wpnum(addr), sd->wp_groups);
    873}
    874
    875static void sd_lock_command(SDState *sd)
    876{
    877    int erase, lock, clr_pwd, set_pwd, pwd_len;
    878    erase = !!(sd->data[0] & 0x08);
    879    lock = sd->data[0] & 0x04;
    880    clr_pwd = sd->data[0] & 0x02;
    881    set_pwd = sd->data[0] & 0x01;
    882
    883    if (sd->blk_len > 1)
    884        pwd_len = sd->data[1];
    885    else
    886        pwd_len = 0;
    887
    888    if (lock) {
    889        trace_sdcard_lock();
    890    } else {
    891        trace_sdcard_unlock();
    892    }
    893    if (erase) {
    894        if (!(sd->card_status & CARD_IS_LOCKED) || sd->blk_len > 1 ||
    895                        set_pwd || clr_pwd || lock || sd->wp_switch ||
    896                        (sd->csd[14] & 0x20)) {
    897            sd->card_status |= LOCK_UNLOCK_FAILED;
    898            return;
    899        }
    900        bitmap_zero(sd->wp_groups, sd->wpgrps_size);
    901        sd->csd[14] &= ~0x10;
    902        sd->card_status &= ~CARD_IS_LOCKED;
    903        sd->pwd_len = 0;
    904        /* Erasing the entire card here! */
    905        fprintf(stderr, "SD: Card force-erased by CMD42\n");
    906        return;
    907    }
    908
    909    if (sd->blk_len < 2 + pwd_len ||
    910                    pwd_len <= sd->pwd_len ||
    911                    pwd_len > sd->pwd_len + 16) {
    912        sd->card_status |= LOCK_UNLOCK_FAILED;
    913        return;
    914    }
    915
    916    if (sd->pwd_len && memcmp(sd->pwd, sd->data + 2, sd->pwd_len)) {
    917        sd->card_status |= LOCK_UNLOCK_FAILED;
    918        return;
    919    }
    920
    921    pwd_len -= sd->pwd_len;
    922    if ((pwd_len && !set_pwd) ||
    923                    (clr_pwd && (set_pwd || lock)) ||
    924                    (lock && !sd->pwd_len && !set_pwd) ||
    925                    (!set_pwd && !clr_pwd &&
    926                     (((sd->card_status & CARD_IS_LOCKED) && lock) ||
    927                      (!(sd->card_status & CARD_IS_LOCKED) && !lock)))) {
    928        sd->card_status |= LOCK_UNLOCK_FAILED;
    929        return;
    930    }
    931
    932    if (set_pwd) {
    933        memcpy(sd->pwd, sd->data + 2 + sd->pwd_len, pwd_len);
    934        sd->pwd_len = pwd_len;
    935    }
    936
    937    if (clr_pwd) {
    938        sd->pwd_len = 0;
    939    }
    940
    941    if (lock)
    942        sd->card_status |= CARD_IS_LOCKED;
    943    else
    944        sd->card_status &= ~CARD_IS_LOCKED;
    945}
    946
    947static bool address_in_range(SDState *sd, const char *desc,
    948                             uint64_t addr, uint32_t length)
    949{
    950    if (addr + length > sd->size) {
    951        qemu_log_mask(LOG_GUEST_ERROR,
    952                      "%s offset %"PRIu64" > card %"PRIu64" [%%%u]\n",
    953                      desc, addr, sd->size, length);
    954        sd->card_status |= ADDRESS_ERROR;
    955        return false;
    956    }
    957    return true;
    958}
    959
    960static sd_rsp_type_t sd_normal_command(SDState *sd, SDRequest req)
    961{
    962    uint32_t rca = 0x0000;
    963    uint64_t addr = (sd->ocr & (1 << 30)) ? (uint64_t) req.arg << 9 : req.arg;
    964
    965    /* CMD55 precedes an ACMD, so we are not interested in tracing it.
    966     * However there is no ACMD55, so we want to trace this particular case.
    967     */
    968    if (req.cmd != 55 || sd->expecting_acmd) {
    969        trace_sdcard_normal_command(sd->proto_name,
    970                                    sd_cmd_name(req.cmd), req.cmd,
    971                                    req.arg, sd_state_name(sd->state));
    972    }
    973
    974    /* Not interpreting this as an app command */
    975    sd->card_status &= ~APP_CMD;
    976
    977    if (sd_cmd_type[req.cmd] == sd_ac
    978        || sd_cmd_type[req.cmd] == sd_adtc) {
    979        rca = req.arg >> 16;
    980    }
    981
    982    /* CMD23 (set block count) must be immediately followed by CMD18 or CMD25
    983     * if not, its effects are cancelled */
    984    if (sd->multi_blk_cnt != 0 && !(req.cmd == 18 || req.cmd == 25)) {
    985        sd->multi_blk_cnt = 0;
    986    }
    987
    988    if (sd_cmd_class[req.cmd] == 6 && FIELD_EX32(sd->ocr, OCR, CARD_CAPACITY)) {
    989        /* Only Standard Capacity cards support class 6 commands */
    990        return sd_illegal;
    991    }
    992
    993    switch (req.cmd) {
    994    /* Basic commands (Class 0 and Class 1) */
    995    case 0:	/* CMD0:   GO_IDLE_STATE */
    996        switch (sd->state) {
    997        case sd_inactive_state:
    998            return sd->spi ? sd_r1 : sd_r0;
    999
   1000        default:
   1001            sd->state = sd_idle_state;
   1002            sd_reset(DEVICE(sd));
   1003            return sd->spi ? sd_r1 : sd_r0;
   1004        }
   1005        break;
   1006
   1007    case 1:	/* CMD1:   SEND_OP_CMD */
   1008        if (!sd->spi)
   1009            goto bad_cmd;
   1010
   1011        sd->state = sd_transfer_state;
   1012        return sd_r1;
   1013
   1014    case 2:	/* CMD2:   ALL_SEND_CID */
   1015        if (sd->spi)
   1016            goto bad_cmd;
   1017        switch (sd->state) {
   1018        case sd_ready_state:
   1019            sd->state = sd_identification_state;
   1020            return sd_r2_i;
   1021
   1022        default:
   1023            break;
   1024        }
   1025        break;
   1026
   1027    case 3:	/* CMD3:   SEND_RELATIVE_ADDR */
   1028        if (sd->spi)
   1029            goto bad_cmd;
   1030        switch (sd->state) {
   1031        case sd_identification_state:
   1032        case sd_standby_state:
   1033            sd->state = sd_standby_state;
   1034            sd_set_rca(sd);
   1035            return sd_r6;
   1036
   1037        default:
   1038            break;
   1039        }
   1040        break;
   1041
   1042    case 4:	/* CMD4:   SEND_DSR */
   1043        if (sd->spi)
   1044            goto bad_cmd;
   1045        switch (sd->state) {
   1046        case sd_standby_state:
   1047            break;
   1048
   1049        default:
   1050            break;
   1051        }
   1052        break;
   1053
   1054    case 5: /* CMD5: reserved for SDIO cards */
   1055        return sd_illegal;
   1056
   1057    case 6:	/* CMD6:   SWITCH_FUNCTION */
   1058        switch (sd->mode) {
   1059        case sd_data_transfer_mode:
   1060            sd_function_switch(sd, req.arg);
   1061            sd->state = sd_sendingdata_state;
   1062            sd->data_start = 0;
   1063            sd->data_offset = 0;
   1064            return sd_r1;
   1065
   1066        default:
   1067            break;
   1068        }
   1069        break;
   1070
   1071    case 7:	/* CMD7:   SELECT/DESELECT_CARD */
   1072        if (sd->spi)
   1073            goto bad_cmd;
   1074        switch (sd->state) {
   1075        case sd_standby_state:
   1076            if (sd->rca != rca)
   1077                return sd_r0;
   1078
   1079            sd->state = sd_transfer_state;
   1080            return sd_r1b;
   1081
   1082        case sd_transfer_state:
   1083        case sd_sendingdata_state:
   1084            if (sd->rca == rca)
   1085                break;
   1086
   1087            sd->state = sd_standby_state;
   1088            return sd_r1b;
   1089
   1090        case sd_disconnect_state:
   1091            if (sd->rca != rca)
   1092                return sd_r0;
   1093
   1094            sd->state = sd_programming_state;
   1095            return sd_r1b;
   1096
   1097        case sd_programming_state:
   1098            if (sd->rca == rca)
   1099                break;
   1100
   1101            sd->state = sd_disconnect_state;
   1102            return sd_r1b;
   1103
   1104        default:
   1105            break;
   1106        }
   1107        break;
   1108
   1109    case 8:	/* CMD8:   SEND_IF_COND */
   1110        if (sd->spec_version < SD_PHY_SPECv2_00_VERS) {
   1111            break;
   1112        }
   1113        if (sd->state != sd_idle_state) {
   1114            break;
   1115        }
   1116        sd->vhs = 0;
   1117
   1118        /* No response if not exactly one VHS bit is set.  */
   1119        if (!(req.arg >> 8) || (req.arg >> (ctz32(req.arg & ~0xff) + 1))) {
   1120            return sd->spi ? sd_r7 : sd_r0;
   1121        }
   1122
   1123        /* Accept.  */
   1124        sd->vhs = req.arg;
   1125        return sd_r7;
   1126
   1127    case 9:	/* CMD9:   SEND_CSD */
   1128        switch (sd->state) {
   1129        case sd_standby_state:
   1130            if (sd->rca != rca)
   1131                return sd_r0;
   1132
   1133            return sd_r2_s;
   1134
   1135        case sd_transfer_state:
   1136            if (!sd->spi)
   1137                break;
   1138            sd->state = sd_sendingdata_state;
   1139            memcpy(sd->data, sd->csd, 16);
   1140            sd->data_start = addr;
   1141            sd->data_offset = 0;
   1142            return sd_r1;
   1143
   1144        default:
   1145            break;
   1146        }
   1147        break;
   1148
   1149    case 10:	/* CMD10:  SEND_CID */
   1150        switch (sd->state) {
   1151        case sd_standby_state:
   1152            if (sd->rca != rca)
   1153                return sd_r0;
   1154
   1155            return sd_r2_i;
   1156
   1157        case sd_transfer_state:
   1158            if (!sd->spi)
   1159                break;
   1160            sd->state = sd_sendingdata_state;
   1161            memcpy(sd->data, sd->cid, 16);
   1162            sd->data_start = addr;
   1163            sd->data_offset = 0;
   1164            return sd_r1;
   1165
   1166        default:
   1167            break;
   1168        }
   1169        break;
   1170
   1171    case 12:	/* CMD12:  STOP_TRANSMISSION */
   1172        switch (sd->state) {
   1173        case sd_sendingdata_state:
   1174            sd->state = sd_transfer_state;
   1175            return sd_r1b;
   1176
   1177        case sd_receivingdata_state:
   1178            sd->state = sd_programming_state;
   1179            /* Bzzzzzzztt .... Operation complete.  */
   1180            sd->state = sd_transfer_state;
   1181            return sd_r1b;
   1182
   1183        default:
   1184            break;
   1185        }
   1186        break;
   1187
   1188    case 13:	/* CMD13:  SEND_STATUS */
   1189        switch (sd->mode) {
   1190        case sd_data_transfer_mode:
   1191            if (!sd->spi && sd->rca != rca) {
   1192                return sd_r0;
   1193            }
   1194
   1195            return sd_r1;
   1196
   1197        default:
   1198            break;
   1199        }
   1200        break;
   1201
   1202    case 15:	/* CMD15:  GO_INACTIVE_STATE */
   1203        if (sd->spi)
   1204            goto bad_cmd;
   1205        switch (sd->mode) {
   1206        case sd_data_transfer_mode:
   1207            if (sd->rca != rca)
   1208                return sd_r0;
   1209
   1210            sd->state = sd_inactive_state;
   1211            return sd_r0;
   1212
   1213        default:
   1214            break;
   1215        }
   1216        break;
   1217
   1218    /* Block read commands (Classs 2) */
   1219    case 16:	/* CMD16:  SET_BLOCKLEN */
   1220        switch (sd->state) {
   1221        case sd_transfer_state:
   1222            if (req.arg > (1 << HWBLOCK_SHIFT)) {
   1223                sd->card_status |= BLOCK_LEN_ERROR;
   1224            } else {
   1225                trace_sdcard_set_blocklen(req.arg);
   1226                sd->blk_len = req.arg;
   1227            }
   1228
   1229            return sd_r1;
   1230
   1231        default:
   1232            break;
   1233        }
   1234        break;
   1235
   1236    case 17:	/* CMD17:  READ_SINGLE_BLOCK */
   1237    case 18:	/* CMD18:  READ_MULTIPLE_BLOCK */
   1238        switch (sd->state) {
   1239        case sd_transfer_state:
   1240
   1241            if (!address_in_range(sd, "READ_BLOCK", addr, sd->blk_len)) {
   1242                return sd_r1;
   1243            }
   1244
   1245            sd->state = sd_sendingdata_state;
   1246            sd->data_start = addr;
   1247            sd->data_offset = 0;
   1248            return sd_r1;
   1249
   1250        default:
   1251            break;
   1252        }
   1253        break;
   1254
   1255    case 19:    /* CMD19: SEND_TUNING_BLOCK (SD) */
   1256        if (sd->spec_version < SD_PHY_SPECv3_01_VERS) {
   1257            break;
   1258        }
   1259        if (sd->state == sd_transfer_state) {
   1260            sd->state = sd_sendingdata_state;
   1261            sd->data_offset = 0;
   1262            return sd_r1;
   1263        }
   1264        break;
   1265
   1266    case 23:    /* CMD23: SET_BLOCK_COUNT */
   1267        if (sd->spec_version < SD_PHY_SPECv3_01_VERS) {
   1268            break;
   1269        }
   1270        switch (sd->state) {
   1271        case sd_transfer_state:
   1272            sd->multi_blk_cnt = req.arg;
   1273            return sd_r1;
   1274
   1275        default:
   1276            break;
   1277        }
   1278        break;
   1279
   1280    /* Block write commands (Class 4) */
   1281    case 24:	/* CMD24:  WRITE_SINGLE_BLOCK */
   1282    case 25:	/* CMD25:  WRITE_MULTIPLE_BLOCK */
   1283        switch (sd->state) {
   1284        case sd_transfer_state:
   1285
   1286            if (!address_in_range(sd, "WRITE_BLOCK", addr, sd->blk_len)) {
   1287                return sd_r1;
   1288            }
   1289
   1290            sd->state = sd_receivingdata_state;
   1291            sd->data_start = addr;
   1292            sd->data_offset = 0;
   1293            sd->blk_written = 0;
   1294
   1295            if (sd->size <= SDSC_MAX_CAPACITY) {
   1296                if (sd_wp_addr(sd, sd->data_start)) {
   1297                    sd->card_status |= WP_VIOLATION;
   1298                }
   1299            }
   1300            if (sd->csd[14] & 0x30) {
   1301                sd->card_status |= WP_VIOLATION;
   1302            }
   1303            return sd_r1;
   1304
   1305        default:
   1306            break;
   1307        }
   1308        break;
   1309
   1310    case 26:	/* CMD26:  PROGRAM_CID */
   1311        if (sd->spi)
   1312            goto bad_cmd;
   1313        switch (sd->state) {
   1314        case sd_transfer_state:
   1315            sd->state = sd_receivingdata_state;
   1316            sd->data_start = 0;
   1317            sd->data_offset = 0;
   1318            return sd_r1;
   1319
   1320        default:
   1321            break;
   1322        }
   1323        break;
   1324
   1325    case 27:	/* CMD27:  PROGRAM_CSD */
   1326        switch (sd->state) {
   1327        case sd_transfer_state:
   1328            sd->state = sd_receivingdata_state;
   1329            sd->data_start = 0;
   1330            sd->data_offset = 0;
   1331            return sd_r1;
   1332
   1333        default:
   1334            break;
   1335        }
   1336        break;
   1337
   1338    /* Write protection (Class 6) */
   1339    case 28:	/* CMD28:  SET_WRITE_PROT */
   1340        if (sd->size > SDSC_MAX_CAPACITY) {
   1341            return sd_illegal;
   1342        }
   1343
   1344        switch (sd->state) {
   1345        case sd_transfer_state:
   1346            if (!address_in_range(sd, "SET_WRITE_PROT", addr, 1)) {
   1347                return sd_r1b;
   1348            }
   1349
   1350            sd->state = sd_programming_state;
   1351            set_bit(sd_addr_to_wpnum(addr), sd->wp_groups);
   1352            /* Bzzzzzzztt .... Operation complete.  */
   1353            sd->state = sd_transfer_state;
   1354            return sd_r1b;
   1355
   1356        default:
   1357            break;
   1358        }
   1359        break;
   1360
   1361    case 29:	/* CMD29:  CLR_WRITE_PROT */
   1362        if (sd->size > SDSC_MAX_CAPACITY) {
   1363            return sd_illegal;
   1364        }
   1365
   1366        switch (sd->state) {
   1367        case sd_transfer_state:
   1368            if (!address_in_range(sd, "CLR_WRITE_PROT", addr, 1)) {
   1369                return sd_r1b;
   1370            }
   1371
   1372            sd->state = sd_programming_state;
   1373            clear_bit(sd_addr_to_wpnum(addr), sd->wp_groups);
   1374            /* Bzzzzzzztt .... Operation complete.  */
   1375            sd->state = sd_transfer_state;
   1376            return sd_r1b;
   1377
   1378        default:
   1379            break;
   1380        }
   1381        break;
   1382
   1383    case 30:	/* CMD30:  SEND_WRITE_PROT */
   1384        if (sd->size > SDSC_MAX_CAPACITY) {
   1385            return sd_illegal;
   1386        }
   1387
   1388        switch (sd->state) {
   1389        case sd_transfer_state:
   1390            if (!address_in_range(sd, "SEND_WRITE_PROT",
   1391                                  req.arg, sd->blk_len)) {
   1392                return sd_r1;
   1393            }
   1394
   1395            sd->state = sd_sendingdata_state;
   1396            *(uint32_t *) sd->data = sd_wpbits(sd, req.arg);
   1397            sd->data_start = addr;
   1398            sd->data_offset = 0;
   1399            return sd_r1;
   1400
   1401        default:
   1402            break;
   1403        }
   1404        break;
   1405
   1406    /* Erase commands (Class 5) */
   1407    case 32:	/* CMD32:  ERASE_WR_BLK_START */
   1408        switch (sd->state) {
   1409        case sd_transfer_state:
   1410            sd->erase_start = req.arg;
   1411            return sd_r1;
   1412
   1413        default:
   1414            break;
   1415        }
   1416        break;
   1417
   1418    case 33:	/* CMD33:  ERASE_WR_BLK_END */
   1419        switch (sd->state) {
   1420        case sd_transfer_state:
   1421            sd->erase_end = req.arg;
   1422            return sd_r1;
   1423
   1424        default:
   1425            break;
   1426        }
   1427        break;
   1428
   1429    case 38:	/* CMD38:  ERASE */
   1430        switch (sd->state) {
   1431        case sd_transfer_state:
   1432            if (sd->csd[14] & 0x30) {
   1433                sd->card_status |= WP_VIOLATION;
   1434                return sd_r1b;
   1435            }
   1436
   1437            sd->state = sd_programming_state;
   1438            sd_erase(sd);
   1439            /* Bzzzzzzztt .... Operation complete.  */
   1440            sd->state = sd_transfer_state;
   1441            return sd_r1b;
   1442
   1443        default:
   1444            break;
   1445        }
   1446        break;
   1447
   1448    /* Lock card commands (Class 7) */
   1449    case 42:	/* CMD42:  LOCK_UNLOCK */
   1450        switch (sd->state) {
   1451        case sd_transfer_state:
   1452            sd->state = sd_receivingdata_state;
   1453            sd->data_start = 0;
   1454            sd->data_offset = 0;
   1455            return sd_r1;
   1456
   1457        default:
   1458            break;
   1459        }
   1460        break;
   1461
   1462    case 52 ... 54:
   1463        /* CMD52, CMD53, CMD54: reserved for SDIO cards
   1464         * (see the SDIO Simplified Specification V2.0)
   1465         * Handle as illegal command but do not complain
   1466         * on stderr, as some OSes may use these in their
   1467         * probing for presence of an SDIO card.
   1468         */
   1469        return sd_illegal;
   1470
   1471    /* Application specific commands (Class 8) */
   1472    case 55:	/* CMD55:  APP_CMD */
   1473        switch (sd->state) {
   1474        case sd_ready_state:
   1475        case sd_identification_state:
   1476        case sd_inactive_state:
   1477            return sd_illegal;
   1478        case sd_idle_state:
   1479            if (rca) {
   1480                qemu_log_mask(LOG_GUEST_ERROR,
   1481                              "SD: illegal RCA 0x%04x for APP_CMD\n", req.cmd);
   1482            }
   1483        default:
   1484            break;
   1485        }
   1486        if (!sd->spi) {
   1487            if (sd->rca != rca) {
   1488                return sd_r0;
   1489            }
   1490        }
   1491        sd->expecting_acmd = true;
   1492        sd->card_status |= APP_CMD;
   1493        return sd_r1;
   1494
   1495    case 56:	/* CMD56:  GEN_CMD */
   1496        switch (sd->state) {
   1497        case sd_transfer_state:
   1498            sd->data_offset = 0;
   1499            if (req.arg & 1)
   1500                sd->state = sd_sendingdata_state;
   1501            else
   1502                sd->state = sd_receivingdata_state;
   1503            return sd_r1;
   1504
   1505        default:
   1506            break;
   1507        }
   1508        break;
   1509
   1510    case 58:    /* CMD58:   READ_OCR (SPI) */
   1511        if (!sd->spi) {
   1512            goto bad_cmd;
   1513        }
   1514        return sd_r3;
   1515
   1516    case 59:    /* CMD59:   CRC_ON_OFF (SPI) */
   1517        if (!sd->spi) {
   1518            goto bad_cmd;
   1519        }
   1520        return sd_r1;
   1521
   1522    default:
   1523    bad_cmd:
   1524        qemu_log_mask(LOG_GUEST_ERROR, "SD: Unknown CMD%i\n", req.cmd);
   1525        return sd_illegal;
   1526    }
   1527
   1528    qemu_log_mask(LOG_GUEST_ERROR, "SD: CMD%i in a wrong state: %s\n",
   1529                  req.cmd, sd_state_name(sd->state));
   1530    return sd_illegal;
   1531}
   1532
   1533static sd_rsp_type_t sd_app_command(SDState *sd,
   1534                                    SDRequest req)
   1535{
   1536    trace_sdcard_app_command(sd->proto_name, sd_acmd_name(req.cmd),
   1537                             req.cmd, req.arg, sd_state_name(sd->state));
   1538    sd->card_status |= APP_CMD;
   1539    switch (req.cmd) {
   1540    case 6:	/* ACMD6:  SET_BUS_WIDTH */
   1541        if (sd->spi) {
   1542            goto unimplemented_spi_cmd;
   1543        }
   1544        switch (sd->state) {
   1545        case sd_transfer_state:
   1546            sd->sd_status[0] &= 0x3f;
   1547            sd->sd_status[0] |= (req.arg & 0x03) << 6;
   1548            return sd_r1;
   1549
   1550        default:
   1551            break;
   1552        }
   1553        break;
   1554
   1555    case 13:	/* ACMD13: SD_STATUS */
   1556        switch (sd->state) {
   1557        case sd_transfer_state:
   1558            sd->state = sd_sendingdata_state;
   1559            sd->data_start = 0;
   1560            sd->data_offset = 0;
   1561            return sd_r1;
   1562
   1563        default:
   1564            break;
   1565        }
   1566        break;
   1567
   1568    case 22:	/* ACMD22: SEND_NUM_WR_BLOCKS */
   1569        switch (sd->state) {
   1570        case sd_transfer_state:
   1571            *(uint32_t *) sd->data = sd->blk_written;
   1572
   1573            sd->state = sd_sendingdata_state;
   1574            sd->data_start = 0;
   1575            sd->data_offset = 0;
   1576            return sd_r1;
   1577
   1578        default:
   1579            break;
   1580        }
   1581        break;
   1582
   1583    case 23:	/* ACMD23: SET_WR_BLK_ERASE_COUNT */
   1584        switch (sd->state) {
   1585        case sd_transfer_state:
   1586            return sd_r1;
   1587
   1588        default:
   1589            break;
   1590        }
   1591        break;
   1592
   1593    case 41:	/* ACMD41: SD_APP_OP_COND */
   1594        if (sd->spi) {
   1595            /* SEND_OP_CMD */
   1596            sd->state = sd_transfer_state;
   1597            return sd_r1;
   1598        }
   1599        if (sd->state != sd_idle_state) {
   1600            break;
   1601        }
   1602        /* If it's the first ACMD41 since reset, we need to decide
   1603         * whether to power up. If this is not an enquiry ACMD41,
   1604         * we immediately report power on and proceed below to the
   1605         * ready state, but if it is, we set a timer to model a
   1606         * delay for power up. This works around a bug in EDK2
   1607         * UEFI, which sends an initial enquiry ACMD41, but
   1608         * assumes that the card is in ready state as soon as it
   1609         * sees the power up bit set. */
   1610        if (!FIELD_EX32(sd->ocr, OCR, CARD_POWER_UP)) {
   1611            if ((req.arg & ACMD41_ENQUIRY_MASK) != 0) {
   1612                timer_del(sd->ocr_power_timer);
   1613                sd_ocr_powerup(sd);
   1614            } else {
   1615                trace_sdcard_inquiry_cmd41();
   1616                if (!timer_pending(sd->ocr_power_timer)) {
   1617                    timer_mod_ns(sd->ocr_power_timer,
   1618                                 (qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL)
   1619                                  + OCR_POWER_DELAY_NS));
   1620                }
   1621            }
   1622        }
   1623
   1624        if (FIELD_EX32(sd->ocr & req.arg, OCR, VDD_VOLTAGE_WINDOW)) {
   1625            /* We accept any voltage.  10000 V is nothing.
   1626             *
   1627             * Once we're powered up, we advance straight to ready state
   1628             * unless it's an enquiry ACMD41 (bits 23:0 == 0).
   1629             */
   1630            sd->state = sd_ready_state;
   1631        }
   1632
   1633        return sd_r3;
   1634
   1635    case 42:	/* ACMD42: SET_CLR_CARD_DETECT */
   1636        switch (sd->state) {
   1637        case sd_transfer_state:
   1638            /* Bringing in the 50KOhm pull-up resistor... Done.  */
   1639            return sd_r1;
   1640
   1641        default:
   1642            break;
   1643        }
   1644        break;
   1645
   1646    case 51:	/* ACMD51: SEND_SCR */
   1647        switch (sd->state) {
   1648        case sd_transfer_state:
   1649            sd->state = sd_sendingdata_state;
   1650            sd->data_start = 0;
   1651            sd->data_offset = 0;
   1652            return sd_r1;
   1653
   1654        default:
   1655            break;
   1656        }
   1657        break;
   1658
   1659    case 18:    /* Reserved for SD security applications */
   1660    case 25:
   1661    case 26:
   1662    case 38:
   1663    case 43 ... 49:
   1664        /* Refer to the "SD Specifications Part3 Security Specification" for
   1665         * information about the SD Security Features.
   1666         */
   1667        qemu_log_mask(LOG_UNIMP, "SD: CMD%i Security not implemented\n",
   1668                      req.cmd);
   1669        return sd_illegal;
   1670
   1671    default:
   1672        /* Fall back to standard commands.  */
   1673        return sd_normal_command(sd, req);
   1674
   1675    unimplemented_spi_cmd:
   1676        /* Commands that are recognised but not yet implemented in SPI mode.  */
   1677        qemu_log_mask(LOG_UNIMP, "SD: CMD%i not implemented in SPI mode\n",
   1678                      req.cmd);
   1679        return sd_illegal;
   1680    }
   1681
   1682    qemu_log_mask(LOG_GUEST_ERROR, "SD: ACMD%i in a wrong state\n", req.cmd);
   1683    return sd_illegal;
   1684}
   1685
   1686static int cmd_valid_while_locked(SDState *sd, const uint8_t cmd)
   1687{
   1688    /* Valid commands in locked state:
   1689     * basic class (0)
   1690     * lock card class (7)
   1691     * CMD16
   1692     * implicitly, the ACMD prefix CMD55
   1693     * ACMD41 and ACMD42
   1694     * Anything else provokes an "illegal command" response.
   1695     */
   1696    if (sd->expecting_acmd) {
   1697        return cmd == 41 || cmd == 42;
   1698    }
   1699    if (cmd == 16 || cmd == 55) {
   1700        return 1;
   1701    }
   1702    return sd_cmd_class[cmd] == 0 || sd_cmd_class[cmd] == 7;
   1703}
   1704
   1705int sd_do_command(SDState *sd, SDRequest *req,
   1706                  uint8_t *response) {
   1707    int last_state;
   1708    sd_rsp_type_t rtype;
   1709    int rsplen;
   1710
   1711    if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable) {
   1712        return 0;
   1713    }
   1714
   1715    if (sd_req_crc_validate(req)) {
   1716        sd->card_status |= COM_CRC_ERROR;
   1717        rtype = sd_illegal;
   1718        goto send_response;
   1719    }
   1720
   1721    if (req->cmd >= SDMMC_CMD_MAX) {
   1722        qemu_log_mask(LOG_GUEST_ERROR, "SD: incorrect command 0x%02x\n",
   1723                      req->cmd);
   1724        req->cmd &= 0x3f;
   1725    }
   1726
   1727    if (sd->card_status & CARD_IS_LOCKED) {
   1728        if (!cmd_valid_while_locked(sd, req->cmd)) {
   1729            sd->card_status |= ILLEGAL_COMMAND;
   1730            sd->expecting_acmd = false;
   1731            qemu_log_mask(LOG_GUEST_ERROR, "SD: Card is locked\n");
   1732            rtype = sd_illegal;
   1733            goto send_response;
   1734        }
   1735    }
   1736
   1737    last_state = sd->state;
   1738    sd_set_mode(sd);
   1739
   1740    if (sd->expecting_acmd) {
   1741        sd->expecting_acmd = false;
   1742        rtype = sd_app_command(sd, *req);
   1743    } else {
   1744        rtype = sd_normal_command(sd, *req);
   1745    }
   1746
   1747    if (rtype == sd_illegal) {
   1748        sd->card_status |= ILLEGAL_COMMAND;
   1749    } else {
   1750        /* Valid command, we can update the 'state before command' bits.
   1751         * (Do this now so they appear in r1 responses.)
   1752         */
   1753        sd->current_cmd = req->cmd;
   1754        sd->card_status &= ~CURRENT_STATE;
   1755        sd->card_status |= (last_state << 9);
   1756    }
   1757
   1758send_response:
   1759    switch (rtype) {
   1760    case sd_r1:
   1761    case sd_r1b:
   1762        sd_response_r1_make(sd, response);
   1763        rsplen = 4;
   1764        break;
   1765
   1766    case sd_r2_i:
   1767        memcpy(response, sd->cid, sizeof(sd->cid));
   1768        rsplen = 16;
   1769        break;
   1770
   1771    case sd_r2_s:
   1772        memcpy(response, sd->csd, sizeof(sd->csd));
   1773        rsplen = 16;
   1774        break;
   1775
   1776    case sd_r3:
   1777        sd_response_r3_make(sd, response);
   1778        rsplen = 4;
   1779        break;
   1780
   1781    case sd_r6:
   1782        sd_response_r6_make(sd, response);
   1783        rsplen = 4;
   1784        break;
   1785
   1786    case sd_r7:
   1787        sd_response_r7_make(sd, response);
   1788        rsplen = 4;
   1789        break;
   1790
   1791    case sd_r0:
   1792    case sd_illegal:
   1793        rsplen = 0;
   1794        break;
   1795    default:
   1796        g_assert_not_reached();
   1797    }
   1798    trace_sdcard_response(sd_response_name(rtype), rsplen);
   1799
   1800    if (rtype != sd_illegal) {
   1801        /* Clear the "clear on valid command" status bits now we've
   1802         * sent any response
   1803         */
   1804        sd->card_status &= ~CARD_STATUS_B;
   1805    }
   1806
   1807#ifdef DEBUG_SD
   1808    qemu_hexdump(stderr, "Response", response, rsplen);
   1809#endif
   1810
   1811    return rsplen;
   1812}
   1813
   1814void sd_write_byte(SDState *sd, uint8_t value)
   1815{
   1816    int i;
   1817
   1818    if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable)
   1819        return;
   1820
   1821    if (sd->state != sd_receivingdata_state) {
   1822        qemu_log_mask(LOG_GUEST_ERROR,
   1823                      "%s: not in Receiving-Data state\n", __func__);
   1824        return;
   1825    }
   1826
   1827    if (sd->card_status & (ADDRESS_ERROR | WP_VIOLATION))
   1828        return;
   1829
   1830    trace_sdcard_write_data(sd->proto_name,
   1831                            sd_acmd_name(sd->current_cmd),
   1832                            sd->current_cmd, value);
   1833    switch (sd->current_cmd) {
   1834    case 24:	/* CMD24:  WRITE_SINGLE_BLOCK */
   1835        sd->data[sd->data_offset ++] = value;
   1836        if (sd->data_offset >= sd->blk_len) {
   1837            /* TODO: Check CRC before committing */
   1838            sd->state = sd_programming_state;
   1839            BLK_WRITE_BLOCK(sd->data_start, sd->data_offset);
   1840            sd->blk_written ++;
   1841            sd->csd[14] |= 0x40;
   1842            /* Bzzzzzzztt .... Operation complete.  */
   1843            sd->state = sd_transfer_state;
   1844        }
   1845        break;
   1846
   1847    case 25:	/* CMD25:  WRITE_MULTIPLE_BLOCK */
   1848        if (sd->data_offset == 0) {
   1849            /* Start of the block - let's check the address is valid */
   1850            if (!address_in_range(sd, "WRITE_MULTIPLE_BLOCK",
   1851                                  sd->data_start, sd->blk_len)) {
   1852                break;
   1853            }
   1854            if (sd->size <= SDSC_MAX_CAPACITY) {
   1855                if (sd_wp_addr(sd, sd->data_start)) {
   1856                    sd->card_status |= WP_VIOLATION;
   1857                    break;
   1858                }
   1859            }
   1860        }
   1861        sd->data[sd->data_offset++] = value;
   1862        if (sd->data_offset >= sd->blk_len) {
   1863            /* TODO: Check CRC before committing */
   1864            sd->state = sd_programming_state;
   1865            BLK_WRITE_BLOCK(sd->data_start, sd->data_offset);
   1866            sd->blk_written++;
   1867            sd->data_start += sd->blk_len;
   1868            sd->data_offset = 0;
   1869            sd->csd[14] |= 0x40;
   1870
   1871            /* Bzzzzzzztt .... Operation complete.  */
   1872            if (sd->multi_blk_cnt != 0) {
   1873                if (--sd->multi_blk_cnt == 0) {
   1874                    /* Stop! */
   1875                    sd->state = sd_transfer_state;
   1876                    break;
   1877                }
   1878            }
   1879
   1880            sd->state = sd_receivingdata_state;
   1881        }
   1882        break;
   1883
   1884    case 26:	/* CMD26:  PROGRAM_CID */
   1885        sd->data[sd->data_offset ++] = value;
   1886        if (sd->data_offset >= sizeof(sd->cid)) {
   1887            /* TODO: Check CRC before committing */
   1888            sd->state = sd_programming_state;
   1889            for (i = 0; i < sizeof(sd->cid); i ++)
   1890                if ((sd->cid[i] | 0x00) != sd->data[i])
   1891                    sd->card_status |= CID_CSD_OVERWRITE;
   1892
   1893            if (!(sd->card_status & CID_CSD_OVERWRITE))
   1894                for (i = 0; i < sizeof(sd->cid); i ++) {
   1895                    sd->cid[i] |= 0x00;
   1896                    sd->cid[i] &= sd->data[i];
   1897                }
   1898            /* Bzzzzzzztt .... Operation complete.  */
   1899            sd->state = sd_transfer_state;
   1900        }
   1901        break;
   1902
   1903    case 27:	/* CMD27:  PROGRAM_CSD */
   1904        sd->data[sd->data_offset ++] = value;
   1905        if (sd->data_offset >= sizeof(sd->csd)) {
   1906            /* TODO: Check CRC before committing */
   1907            sd->state = sd_programming_state;
   1908            for (i = 0; i < sizeof(sd->csd); i ++)
   1909                if ((sd->csd[i] | sd_csd_rw_mask[i]) !=
   1910                    (sd->data[i] | sd_csd_rw_mask[i]))
   1911                    sd->card_status |= CID_CSD_OVERWRITE;
   1912
   1913            /* Copy flag (OTP) & Permanent write protect */
   1914            if (sd->csd[14] & ~sd->data[14] & 0x60)
   1915                sd->card_status |= CID_CSD_OVERWRITE;
   1916
   1917            if (!(sd->card_status & CID_CSD_OVERWRITE))
   1918                for (i = 0; i < sizeof(sd->csd); i ++) {
   1919                    sd->csd[i] |= sd_csd_rw_mask[i];
   1920                    sd->csd[i] &= sd->data[i];
   1921                }
   1922            /* Bzzzzzzztt .... Operation complete.  */
   1923            sd->state = sd_transfer_state;
   1924        }
   1925        break;
   1926
   1927    case 42:	/* CMD42:  LOCK_UNLOCK */
   1928        sd->data[sd->data_offset ++] = value;
   1929        if (sd->data_offset >= sd->blk_len) {
   1930            /* TODO: Check CRC before committing */
   1931            sd->state = sd_programming_state;
   1932            sd_lock_command(sd);
   1933            /* Bzzzzzzztt .... Operation complete.  */
   1934            sd->state = sd_transfer_state;
   1935        }
   1936        break;
   1937
   1938    case 56:	/* CMD56:  GEN_CMD */
   1939        sd->data[sd->data_offset ++] = value;
   1940        if (sd->data_offset >= sd->blk_len) {
   1941            APP_WRITE_BLOCK(sd->data_start, sd->data_offset);
   1942            sd->state = sd_transfer_state;
   1943        }
   1944        break;
   1945
   1946    default:
   1947        qemu_log_mask(LOG_GUEST_ERROR, "%s: unknown command\n", __func__);
   1948        break;
   1949    }
   1950}
   1951
   1952#define SD_TUNING_BLOCK_SIZE    64
   1953
   1954static const uint8_t sd_tuning_block_pattern[SD_TUNING_BLOCK_SIZE] = {
   1955    /* See: Physical Layer Simplified Specification Version 3.01, Table 4-2 */
   1956    0xff, 0x0f, 0xff, 0x00,         0x0f, 0xfc, 0xc3, 0xcc,
   1957    0xc3, 0x3c, 0xcc, 0xff,         0xfe, 0xff, 0xfe, 0xef,
   1958    0xff, 0xdf, 0xff, 0xdd,         0xff, 0xfb, 0xff, 0xfb,
   1959    0xbf, 0xff, 0x7f, 0xff,         0x77, 0xf7, 0xbd, 0xef,
   1960    0xff, 0xf0, 0xff, 0xf0,         0x0f, 0xfc, 0xcc, 0x3c,
   1961    0xcc, 0x33, 0xcc, 0xcf,         0xff, 0xef, 0xff, 0xee,
   1962    0xff, 0xfd, 0xff, 0xfd,         0xdf, 0xff, 0xbf, 0xff,
   1963    0xbb, 0xff, 0xf7, 0xff,         0xf7, 0x7f, 0x7b, 0xde,
   1964};
   1965
   1966uint8_t sd_read_byte(SDState *sd)
   1967{
   1968    /* TODO: Append CRCs */
   1969    uint8_t ret;
   1970    uint32_t io_len;
   1971
   1972    if (!sd->blk || !blk_is_inserted(sd->blk) || !sd->enable)
   1973        return 0x00;
   1974
   1975    if (sd->state != sd_sendingdata_state) {
   1976        qemu_log_mask(LOG_GUEST_ERROR,
   1977                      "%s: not in Sending-Data state\n", __func__);
   1978        return 0x00;
   1979    }
   1980
   1981    if (sd->card_status & (ADDRESS_ERROR | WP_VIOLATION))
   1982        return 0x00;
   1983
   1984    io_len = (sd->ocr & (1 << 30)) ? 512 : sd->blk_len;
   1985
   1986    trace_sdcard_read_data(sd->proto_name,
   1987                           sd_acmd_name(sd->current_cmd),
   1988                           sd->current_cmd, io_len);
   1989    switch (sd->current_cmd) {
   1990    case 6:	/* CMD6:   SWITCH_FUNCTION */
   1991        ret = sd->data[sd->data_offset ++];
   1992
   1993        if (sd->data_offset >= 64)
   1994            sd->state = sd_transfer_state;
   1995        break;
   1996
   1997    case 9:	/* CMD9:   SEND_CSD */
   1998    case 10:	/* CMD10:  SEND_CID */
   1999        ret = sd->data[sd->data_offset ++];
   2000
   2001        if (sd->data_offset >= 16)
   2002            sd->state = sd_transfer_state;
   2003        break;
   2004
   2005    case 13:	/* ACMD13: SD_STATUS */
   2006        ret = sd->sd_status[sd->data_offset ++];
   2007
   2008        if (sd->data_offset >= sizeof(sd->sd_status))
   2009            sd->state = sd_transfer_state;
   2010        break;
   2011
   2012    case 17:	/* CMD17:  READ_SINGLE_BLOCK */
   2013        if (sd->data_offset == 0)
   2014            BLK_READ_BLOCK(sd->data_start, io_len);
   2015        ret = sd->data[sd->data_offset ++];
   2016
   2017        if (sd->data_offset >= io_len)
   2018            sd->state = sd_transfer_state;
   2019        break;
   2020
   2021    case 18:	/* CMD18:  READ_MULTIPLE_BLOCK */
   2022        if (sd->data_offset == 0) {
   2023            if (!address_in_range(sd, "READ_MULTIPLE_BLOCK",
   2024                                  sd->data_start, io_len)) {
   2025                return 0x00;
   2026            }
   2027            BLK_READ_BLOCK(sd->data_start, io_len);
   2028        }
   2029        ret = sd->data[sd->data_offset ++];
   2030
   2031        if (sd->data_offset >= io_len) {
   2032            sd->data_start += io_len;
   2033            sd->data_offset = 0;
   2034
   2035            if (sd->multi_blk_cnt != 0) {
   2036                if (--sd->multi_blk_cnt == 0) {
   2037                    /* Stop! */
   2038                    sd->state = sd_transfer_state;
   2039                    break;
   2040                }
   2041            }
   2042        }
   2043        break;
   2044
   2045    case 19:    /* CMD19:  SEND_TUNING_BLOCK (SD) */
   2046        if (sd->data_offset >= SD_TUNING_BLOCK_SIZE - 1) {
   2047            sd->state = sd_transfer_state;
   2048        }
   2049        ret = sd_tuning_block_pattern[sd->data_offset++];
   2050        break;
   2051
   2052    case 22:	/* ACMD22: SEND_NUM_WR_BLOCKS */
   2053        ret = sd->data[sd->data_offset ++];
   2054
   2055        if (sd->data_offset >= 4)
   2056            sd->state = sd_transfer_state;
   2057        break;
   2058
   2059    case 30:	/* CMD30:  SEND_WRITE_PROT */
   2060        ret = sd->data[sd->data_offset ++];
   2061
   2062        if (sd->data_offset >= 4)
   2063            sd->state = sd_transfer_state;
   2064        break;
   2065
   2066    case 51:	/* ACMD51: SEND_SCR */
   2067        ret = sd->scr[sd->data_offset ++];
   2068
   2069        if (sd->data_offset >= sizeof(sd->scr))
   2070            sd->state = sd_transfer_state;
   2071        break;
   2072
   2073    case 56:	/* CMD56:  GEN_CMD */
   2074        if (sd->data_offset == 0)
   2075            APP_READ_BLOCK(sd->data_start, sd->blk_len);
   2076        ret = sd->data[sd->data_offset ++];
   2077
   2078        if (sd->data_offset >= sd->blk_len)
   2079            sd->state = sd_transfer_state;
   2080        break;
   2081
   2082    default:
   2083        qemu_log_mask(LOG_GUEST_ERROR, "%s: unknown command\n", __func__);
   2084        return 0x00;
   2085    }
   2086
   2087    return ret;
   2088}
   2089
   2090static bool sd_receive_ready(SDState *sd)
   2091{
   2092    return sd->state == sd_receivingdata_state;
   2093}
   2094
   2095static bool sd_data_ready(SDState *sd)
   2096{
   2097    return sd->state == sd_sendingdata_state;
   2098}
   2099
   2100void sd_enable(SDState *sd, bool enable)
   2101{
   2102    sd->enable = enable;
   2103}
   2104
   2105static void sd_instance_init(Object *obj)
   2106{
   2107    SDState *sd = SD_CARD(obj);
   2108
   2109    sd->enable = true;
   2110    sd->ocr_power_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, sd_ocr_powerup, sd);
   2111}
   2112
   2113static void sd_instance_finalize(Object *obj)
   2114{
   2115    SDState *sd = SD_CARD(obj);
   2116
   2117    timer_free(sd->ocr_power_timer);
   2118}
   2119
   2120static void sd_realize(DeviceState *dev, Error **errp)
   2121{
   2122    SDState *sd = SD_CARD(dev);
   2123    int ret;
   2124
   2125    sd->proto_name = sd->spi ? "SPI" : "SD";
   2126
   2127    switch (sd->spec_version) {
   2128    case SD_PHY_SPECv1_10_VERS
   2129     ... SD_PHY_SPECv3_01_VERS:
   2130        break;
   2131    default:
   2132        error_setg(errp, "Invalid SD card Spec version: %u", sd->spec_version);
   2133        return;
   2134    }
   2135
   2136    if (sd->blk) {
   2137        int64_t blk_size;
   2138
   2139        if (!blk_supports_write_perm(sd->blk)) {
   2140            error_setg(errp, "Cannot use read-only drive as SD card");
   2141            return;
   2142        }
   2143
   2144        blk_size = blk_getlength(sd->blk);
   2145        if (blk_size > 0 && !is_power_of_2(blk_size)) {
   2146            int64_t blk_size_aligned = pow2ceil(blk_size);
   2147            char *blk_size_str;
   2148
   2149            blk_size_str = size_to_str(blk_size);
   2150            error_setg(errp, "Invalid SD card size: %s", blk_size_str);
   2151            g_free(blk_size_str);
   2152
   2153            blk_size_str = size_to_str(blk_size_aligned);
   2154            error_append_hint(errp,
   2155                              "SD card size has to be a power of 2, e.g. %s.\n"
   2156                              "You can resize disk images with"
   2157                              " 'qemu-img resize <imagefile> <new-size>'\n"
   2158                              "(note that this will lose data if you make the"
   2159                              " image smaller than it currently is).\n",
   2160                              blk_size_str);
   2161            g_free(blk_size_str);
   2162
   2163            return;
   2164        }
   2165
   2166        ret = blk_set_perm(sd->blk, BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE,
   2167                           BLK_PERM_ALL, errp);
   2168        if (ret < 0) {
   2169            return;
   2170        }
   2171        blk_set_dev_ops(sd->blk, &sd_block_ops, sd);
   2172    }
   2173}
   2174
   2175static Property sd_properties[] = {
   2176    DEFINE_PROP_UINT8("spec_version", SDState,
   2177                      spec_version, SD_PHY_SPECv2_00_VERS),
   2178    DEFINE_PROP_DRIVE("drive", SDState, blk),
   2179    /* We do not model the chip select pin, so allow the board to select
   2180     * whether card should be in SSI or MMC/SD mode.  It is also up to the
   2181     * board to ensure that ssi transfers only occur when the chip select
   2182     * is asserted.  */
   2183    DEFINE_PROP_BOOL("spi", SDState, spi, false),
   2184    DEFINE_PROP_END_OF_LIST()
   2185};
   2186
   2187static void sd_class_init(ObjectClass *klass, void *data)
   2188{
   2189    DeviceClass *dc = DEVICE_CLASS(klass);
   2190    SDCardClass *sc = SD_CARD_CLASS(klass);
   2191
   2192    dc->realize = sd_realize;
   2193    device_class_set_props(dc, sd_properties);
   2194    dc->vmsd = &sd_vmstate;
   2195    dc->reset = sd_reset;
   2196    dc->bus_type = TYPE_SD_BUS;
   2197    set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
   2198
   2199    sc->set_voltage = sd_set_voltage;
   2200    sc->get_dat_lines = sd_get_dat_lines;
   2201    sc->get_cmd_line = sd_get_cmd_line;
   2202    sc->do_command = sd_do_command;
   2203    sc->write_byte = sd_write_byte;
   2204    sc->read_byte = sd_read_byte;
   2205    sc->receive_ready = sd_receive_ready;
   2206    sc->data_ready = sd_data_ready;
   2207    sc->enable = sd_enable;
   2208    sc->get_inserted = sd_get_inserted;
   2209    sc->get_readonly = sd_get_readonly;
   2210}
   2211
   2212static const TypeInfo sd_info = {
   2213    .name = TYPE_SD_CARD,
   2214    .parent = TYPE_DEVICE,
   2215    .instance_size = sizeof(SDState),
   2216    .class_size = sizeof(SDCardClass),
   2217    .class_init = sd_class_init,
   2218    .instance_init = sd_instance_init,
   2219    .instance_finalize = sd_instance_finalize,
   2220};
   2221
   2222static void sd_register_types(void)
   2223{
   2224    type_register_static(&sd_info);
   2225}
   2226
   2227type_init(sd_register_types)