summaryrefslogtreecommitdiff
path: root/memories/sdmmc
diff options
context:
space:
mode:
authorHarald Welte <laforge@gnumonks.org>2011-07-04 20:52:54 +0200
committerHarald Welte <laforge@gnumonks.org>2011-07-04 20:52:54 +0200
commit044ad7c3987460ede48ff27afd6bdb0ca05a0432 (patch)
tree924818cdb0d39ca08aec540d18da7bd406eaae8c /memories/sdmmc
import at91lib from at91lib_20100901_softpack_1_9_v_1_0_svn_v1501120100901_softpack_1_9_v_1_0_svn_v15011
it's sad to see that atmel doesn't publish their svn repo or has a centralized location or even puts proper version/release info into the library itself
Diffstat (limited to 'memories/sdmmc')
-rw-r--r--memories/sdmmc/sdmmc.dir36
-rw-r--r--memories/sdmmc/sdmmc_mci.c4048
-rw-r--r--memories/sdmmc/sdmmc_mci.h1038
-rw-r--r--memories/sdmmc/sdmmc_spi.c1453
-rw-r--r--memories/sdmmc/sdmmc_spi.h720
-rw-r--r--memories/sdmmc/sdspi.c711
-rw-r--r--memories/sdmmc/sdspi.h184
7 files changed, 8190 insertions, 0 deletions
diff --git a/memories/sdmmc/sdmmc.dir b/memories/sdmmc/sdmmc.dir
new file mode 100644
index 0000000..177fe80
--- /dev/null
+++ b/memories/sdmmc/sdmmc.dir
@@ -0,0 +1,36 @@
+/* ----------------------------------------------------------------------------
+ * ATMEL Microcontroller Software Support
+ * ----------------------------------------------------------------------------
+ * Copyright (c) 2008, Atmel Corporation
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the disclaimer below.
+ *
+ * Atmel's name may not be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
+ * DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ----------------------------------------------------------------------------
+ */
+
+//------------------------------------------------------------------------------
+/// \dir
+///
+/// !!!Purpose
+///
+/// This directory contains sdmmc drivers
+//------------------------------------------------------------------------------ \ No newline at end of file
diff --git a/memories/sdmmc/sdmmc_mci.c b/memories/sdmmc/sdmmc_mci.c
new file mode 100644
index 0000000..3202945
--- /dev/null
+++ b/memories/sdmmc/sdmmc_mci.c
@@ -0,0 +1,4048 @@
+/* ----------------------------------------------------------------------------
+ * ATMEL Microcontroller Software Support
+ * ----------------------------------------------------------------------------
+ * Copyright (c) 2008, Atmel Corporation
+
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the disclaimer below.
+ *
+ * Atmel's name may not be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
+ * DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ----------------------------------------------------------------------------
+ */
+
+//------------------------------------------------------------------------------
+// Headers
+//------------------------------------------------------------------------------
+
+#include "sdmmc_mci.h"
+
+#include <utility/assert.h>
+#include <utility/trace.h>
+
+#include <pio/pio.h>
+
+#include <string.h>
+
+//------------------------------------------------------------------------------
+// Global variables
+//------------------------------------------------------------------------------
+
+#if defined(MCI2_INTERFACE)
+unsigned char gSdmmcAutoHsEnable = 1;
+#else
+unsigned char gSdmmcAutoHsEnable = 0;
+#endif
+
+//------------------------------------------------------------------------------
+// Local constants
+//------------------------------------------------------------------------------
+
+//#define SINGLE_READ
+//#define SINGLE_WRITE
+
+// Timeout wait loop
+#define TO_LOOP 0x10000
+
+// SD card operation states
+#define SD_STATE_IDLE 0
+#define SD_STATE_INIT 1
+#define SD_STATE_READY 2
+#define SD_STATE_READ 0x10
+#define SD_STATE_RD_RDY 0x11
+#define SD_STATE_RD_BSY 0x12
+#define SD_STATE_WRITE 0x20
+#define SD_STATE_WR_RDY 0x21
+#define SD_STATE_WR_BSY 0x22
+#define SD_STATE_BOOT 0x30
+
+// Delay between sending MMC commands
+#define MMC_DELAY 0x4FF
+
+#define SD_ADDRESS(pSd, address) \
+ ( ((pSd)->totalSize == 0xFFFFFFFF) ? \
+ (address):((address) << SD_BLOCK_SIZE_BIT) )
+
+//-----------------------------------------------------------------------------
+/// MMC/SD in SPI mode reports R1 status always, and R2 for SEND_STATUS
+/// R1 is the low order byte; R2 is the next highest byte, when present.
+//-----------------------------------------------------------------------------
+#define R1_SPI_IDLE (1 << 0)
+#define R1_SPI_ERASE_RESET (1 << 1)
+#define R1_SPI_ILLEGAL_COMMAND (1 << 2)
+#define R1_SPI_COM_CRC (1 << 3)
+#define R1_SPI_ERASE_SEQ (1 << 4)
+#define R1_SPI_ADDRESS (1 << 5)
+#define R1_SPI_PARAMETER (1 << 6)
+// R1 bit 7 is always zero
+#define R2_SPI_CARD_LOCKED (1 << 0)
+#define R2_SPI_WP_ERASE_SKIP (1 << 1)
+#define R2_SPI_LOCK_UNLOCK_FAIL R2_SPI_WP_ERASE_SKIP
+#define R2_SPI_ERROR (1 << 2)
+#define R2_SPI_CC_ERROR (1 << 3)
+#define R2_SPI_CARD_ECC_ERROR (1 << 4)
+#define R2_SPI_WP_VIOLATION (1 << 5)
+#define R2_SPI_ERASE_PARAM (1 << 6)
+#define R2_SPI_OUT_OF_RANGE (1 << 7)
+#define R2_SPI_CSD_OVERWRITE R2_SPI_OUT_OF_RANGE
+
+// Status register constants
+#define STATUS_APP_CMD (1UL << 5)
+#define STATUS_SWITCH_ERROR (1UL << 7)
+#define STATUS_READY_FOR_DATA (1UL << 8)
+#define STATUS_IDLE (0UL << 9)
+#define STATUS_READY (1UL << 9)
+#define STATUS_IDENT (2UL << 9)
+#define STATUS_STBY (3UL << 9)
+#define STATUS_TRAN (4UL << 9)
+#define STATUS_DATA (5UL << 9)
+#define STATUS_RCV (6UL << 9)
+#define STATUS_PRG (7UL << 9)
+#define STATUS_DIS (8UL << 9)
+#define STATUS_STATE (0xFUL << 9)
+#define STATUS_ERASE_RESET (1UL << 13)
+#define STATUS_WP_ERASE_SKIP (1UL << 15)
+#define STATUS_CIDCSD_OVERWRITE (1UL << 16)
+#define STATUS_OVERRUN (1UL << 17)
+#define STATUS_UNERRUN (1UL << 18)
+#define STATUS_ERROR (1UL << 19)
+#define STATUS_CC_ERROR (1UL << 20)
+#define STATUS_CARD_ECC_FAILED (1UL << 21)
+#define STATUS_ILLEGAL_COMMAND (1UL << 22)
+#define STATUS_COM_CRC_ERROR (1UL << 23)
+#define STATUS_UN_LOCK_FAILED (1UL << 24)
+#define STATUS_CARD_IS_LOCKED (1UL << 25)
+#define STATUS_WP_VIOLATION (1UL << 26)
+#define STATUS_ERASE_PARAM (1UL << 27)
+#define STATUS_ERASE_SEQ_ERROR (1UL << 28)
+#define STATUS_BLOCK_LEN_ERROR (1UL << 29)
+#define STATUS_ADDRESS_MISALIGN (1UL << 30)
+#define STATUS_ADDR_OUT_OR_RANGE (1UL << 31)
+
+#define STATUS_STOP ( STATUS_CARD_IS_LOCKED \
+ | STATUS_COM_CRC_ERROR \
+ | STATUS_ILLEGAL_COMMAND \
+ | STATUS_CC_ERROR \
+ | STATUS_ERROR \
+ | STATUS_STATE \
+ | STATUS_READY_FOR_DATA )
+
+#define STATUS_WRITE ( STATUS_ADDR_OUT_OR_RANGE \
+ | STATUS_ADDRESS_MISALIGN \
+ | STATUS_BLOCK_LEN_ERROR \
+ | STATUS_WP_VIOLATION \
+ | STATUS_CARD_IS_LOCKED \
+ | STATUS_COM_CRC_ERROR \
+ | STATUS_ILLEGAL_COMMAND \
+ | STATUS_CC_ERROR \
+ | STATUS_ERROR \
+ | STATUS_ERASE_RESET \
+ | STATUS_STATE \
+ | STATUS_READY_FOR_DATA )
+
+#define STATUS_READ ( STATUS_ADDR_OUT_OR_RANGE \
+ | STATUS_ADDRESS_MISALIGN \
+ | STATUS_BLOCK_LEN_ERROR \
+ | STATUS_CARD_IS_LOCKED \
+ | STATUS_COM_CRC_ERROR \
+ | STATUS_ILLEGAL_COMMAND \
+ | STATUS_CARD_ECC_FAILED \
+ | STATUS_CC_ERROR \
+ | STATUS_ERROR \
+ | STATUS_ERASE_RESET \
+ | STATUS_STATE \
+ | STATUS_READY_FOR_DATA )
+
+#define STATUS_SD_SWITCH ( STATUS_ADDR_OUT_OR_RANGE \
+ | STATUS_CARD_IS_LOCKED \
+ | STATUS_COM_CRC_ERROR \
+ | STATUS_ILLEGAL_COMMAND \
+ | STATUS_CARD_ECC_FAILED \
+ | STATUS_CC_ERROR \
+ | STATUS_ERROR \
+ | STATUS_UNERRUN \
+ | STATUS_OVERRUN \
+ | STATUS_STATE)
+
+#define STATUS_MMC_SWITCH ( STATUS_CARD_IS_LOCKED \
+ | STATUS_COM_CRC_ERROR \
+ | STATUS_ILLEGAL_COMMAND \
+ | STATUS_CC_ERROR \
+ | STATUS_ERROR \
+ | STATUS_ERASE_RESET \
+ | STATUS_STATE \
+ | STATUS_READY_FOR_DATA \
+ | STATUS_SWITCH_ERROR )
+
+// | (0x3UL << 12) /* IO_CURRENT_STATE */
+#define STATUS_SDIO_CMD52 ( (1UL << 15) /* COM_CRC_ERROR */ \
+ | (1UL << 14) /* ILLEGAL_COMMAND */ \
+ | (1UL << 11) /* ERRIR */ \
+ | (1UL << 9) /* FUNCTION_NUMBER */ \
+ | (1UL << 8) /* OUT_OF_RANGE */)
+
+//-----------------------------------------------------------------------------
+/// OCR Register
+//-----------------------------------------------------------------------------
+#define AT91C_VDD_16_17 (1UL << 4)
+#define AT91C_VDD_17_18 (1UL << 5)
+#define AT91C_VDD_18_19 (1UL << 6)
+#define AT91C_VDD_19_20 (1UL << 7)
+#define AT91C_VDD_20_21 (1UL << 8)
+#define AT91C_VDD_21_22 (1UL << 9)
+#define AT91C_VDD_22_23 (1UL << 10)
+#define AT91C_VDD_23_24 (1UL << 11)
+#define AT91C_VDD_24_25 (1UL << 12)
+#define AT91C_VDD_25_26 (1UL << 13)
+#define AT91C_VDD_26_27 (1UL << 14)
+#define AT91C_VDD_27_28 (1UL << 15)
+#define AT91C_VDD_28_29 (1UL << 16)
+#define AT91C_VDD_29_30 (1UL << 17)
+#define AT91C_VDD_30_31 (1UL << 18)
+#define AT91C_VDD_31_32 (1UL << 19)
+#define AT91C_VDD_32_33 (1UL << 20)
+#define AT91C_VDD_33_34 (1UL << 21)
+#define AT91C_VDD_34_35 (1UL << 22)
+#define AT91C_VDD_35_36 (1UL << 23)
+#define AT91C_SDIO_MP (1UL << 27)
+#define AT91C_SDIO_NF (7UL << 28)
+#define AT91C_MMC_OCR_BIT2930 (3UL << 29)
+#define AT91C_CARD_POWER_UP_BUSY (1UL << 31)
+
+#define AT91C_MMC_HOST_VOLTAGE_RANGE (AT91C_VDD_27_28 +\
+ AT91C_VDD_28_29 +\
+ AT91C_VDD_29_30 +\
+ AT91C_VDD_30_31 +\
+ AT91C_VDD_31_32 +\
+ AT91C_VDD_32_33)
+
+// MMC OCR response for Bit 29, 30
+#define AT91C_MMC_NORM_DENSITY (0x0UL << 29)
+#define AT91C_MMC_HIGH_DENSITY (0x2UL << 29)
+
+#define AT91C_CCS (1 << 30)
+
+// MCI_CMD Register Value
+#define AT91C_POWER_ON_INIT (0 | AT91C_MCI_TRCMD_NO \
+ | AT91C_MCI_SPCMD_INIT \
+ | AT91C_MCI_OPDCMD)
+
+//-----------------------------------------------------------------------------
+/// eMMC CMD6
+//-----------------------------------------------------------------------------
+#define AT91C_EMMC_CMD6ARG_ACCESS_BITS (0x3UL << 24)
+#define AT91C_EMMC_CMD6ARG_ACCESS_SHIFT (24)
+// change command sets
+#define AT91C_EMMC_CMD6ARG_ACCESS_CMDSETS (0x0UL << 24)
+// set bits in the value field
+#define AT91C_EMMC_CMD6ARG_ACCESS_SETBITS (0x1UL << 24)
+// clear bits in the value field
+#define AT91C_EMMC_CMD6ARG_ACCESS_CLRBITS (0x2UL << 24)
+// the value field is written into the pointed byte
+#define AT91C_EMMC_CMD6ARG_ACCESS_WRBYTES (0x3UL << 24)
+#define AT91C_EMMC_CMD6ARG_INDEX_BITS (0xffUL << 16)
+#define AT91C_EMMC_CMD6ARG_INDEX_SHIFT (16)
+#define AT91C_EMMC_CMD6ARG_VALUE_BITS (0xffUL << 8)
+#define AT91C_EMMC_CMD6ARG_VALUE_SHIFT (8)
+#define AT91C_EMMC_CMD6ARG_CMDSET_BITS (0x7UL << 0)
+#define AT91C_EMMC_CMD6ARG_CMDSET_SHIFT (0)
+
+//-----------------------------------------------------------------------------
+// Command Classes
+//-----------------------------------------------------------------------------
+//
+// Class 0, 2, 4, 5, 7 and 8 are mandatory and shall be supported by
+// all SD Memory Cards.
+//
+// Basic Commands (class 0)
+//
+// Cmd0 MCI + SPI
+#define AT91C_GO_IDLE_STATE_CMD (0 | AT91C_MCI_TRCMD_NO \
+ | AT91C_MCI_SPCMD_NONE )
+// Cmd1 SPI
+#define AT91C_MMC_SEND_OP_COND_CMD (1 | AT91C_MCI_TRCMD_NO \
+ | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_OPDCMD)
+// Cmd2 MCI
+#define AT91C_ALL_SEND_CID_CMD (2 | AT91C_MCI_TRCMD_NO \
+ | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_OPDCMD \
+ | AT91C_MCI_RSPTYP_136 )
+// Cmd3 MCI
+#define AT91C_SET_RELATIVE_ADDR_CMD (3 | AT91C_MCI_TRCMD_NO \
+ | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_OPDCMD \
+ | AT91C_MCI_MAXLAT )
+// Cmd4 MCI
+#define AT91C_SET_DSR_CMD (4 | AT91C_MCI_TRCMD_NO \
+ | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_NO \
+ | AT91C_MCI_MAXLAT )
+// Cmd5 MCI
+#define AT91C_IO_SEND_OP_COND_CMD (5 | AT91C_MCI_TRCMD_NO \
+ | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_OPDCMD )
+// Cmd6 SD/MMC
+#if defined(MCI2_INTERFACE)
+#define AT91C_MMC_SWITCH_CMD (6 | AT91C_MCI_TRCMD_NO \
+ | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_R1B \
+ | AT91C_MCI_MAXLAT )
+#else
+#define AT91C_MMC_SWITCH_CMD (6 | AT91C_MCI_TRCMD_NO \
+ | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_MAXLAT )
+#endif
+#define AT91C_SD_SWITCH_CMD (6 | AT91C_MCI_TRCMD_START \
+ | AT91C_MCI_TRTYP_BLOCK \
+ | AT91C_MCI_TRDIR_READ \
+ | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_MAXLAT )
+// cmd7 MCI
+#define AT91C_SEL_DESEL_CARD_CMD (7 | AT91C_MCI_TRCMD_NO \
+ | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_MAXLAT )
+#define AT91C_SEL_CARD_CMD (7 | AT91C_MCI_TRCMD_NO \
+ | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_MAXLAT )
+#define AT91C_DESEL_CARD_CMD (7 | AT91C_MCI_TRCMD_NO \
+ | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_NO \
+ | AT91C_MCI_MAXLAT )
+// Cmd8 MCI + SPI
+#define AT91C_SEND_IF_COND (8 | AT91C_MCI_TRCMD_NO \
+ | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_MAXLAT )
+// Cmd9 MCI + SPI
+#define AT91C_SEND_CSD_CMD (9 | AT91C_MCI_TRCMD_NO \
+ | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_136 \
+ | AT91C_MCI_MAXLAT )
+// Cmd10 MCI + SPI
+#define AT91C_SEND_CID_CMD (10 | AT91C_MCI_TRCMD_NO \
+ | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_136 \
+ | AT91C_MCI_MAXLAT )
+// Cmd12 MCI + SPI
+#if defined(MCI2_INTERFACE)
+#define AT91C_STOP_TRANSMISSION_CMD (12 | AT91C_MCI_TRCMD_STOP \
+ | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_R1B \
+ | AT91C_MCI_MAXLAT )
+#else
+#define AT91C_STOP_TRANSMISSION_CMD (12 | AT91C_MCI_TRCMD_STOP \
+ | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_MAXLAT )
+#endif
+// Cmd13 MCI + SPI
+#define AT91C_SEND_STATUS_CMD (13 | AT91C_MCI_TRCMD_NO \
+ | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_MAXLAT )
+// Cmd15 MCI
+#define AT91C_GO_INACTIVE_STATE_CMD (15 | AT91C_MCI_RSPTYP_NO )
+
+// Cmd58 SPI
+#define AT91C_READ_OCR_CMD (58 | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_MAXLAT )
+// Cmd59 SPI
+#define AT91C_CRC_ON_OFF_CMD (59 | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_MAXLAT )
+
+//*------------------------------------------------
+//* Class 2 commands: Block oriented Read commands
+//*------------------------------------------------
+
+// Cmd8 for MMC
+#define AT91C_SEND_EXT_CSD_CMD (8 | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_OPDCMD_PUSHPULL \
+ | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_TRCMD_START \
+ | AT91C_MCI_TRTYP_BLOCK \
+ | AT91C_MCI_TRDIR \
+ | AT91C_MCI_MAXLAT)
+
+// Cmd16
+#define AT91C_SET_BLOCKLEN_CMD (16 | AT91C_MCI_TRCMD_NO \
+ | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_MAXLAT )
+// Cmd17
+#define AT91C_READ_SINGLE_BLOCK_CMD (17 | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_TRCMD_START \
+ | AT91C_MCI_TRTYP_BLOCK \
+ | AT91C_MCI_TRDIR \
+ | AT91C_MCI_MAXLAT)
+// Cmd18
+#define AT91C_READ_MULTIPLE_BLOCK_CMD (18 | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_TRCMD_START \
+ | AT91C_MCI_TRTYP_MULTIPLE \
+ | AT91C_MCI_TRDIR \
+ | AT91C_MCI_MAXLAT)
+
+//*------------------------------------------------
+//* Class 4 commands: Block oriented write commands
+//*------------------------------------------------
+// Cmd24
+#define AT91C_WRITE_BLOCK_CMD (24 | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_TRCMD_START \
+ | (AT91C_MCI_TRTYP_BLOCK \
+ & ~(AT91C_MCI_TRDIR)) \
+ | AT91C_MCI_MAXLAT)
+// Cmd25
+#define AT91C_WRITE_MULTIPLE_BLOCK_CMD (25 | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_TRCMD_START \
+ | (AT91C_MCI_TRTYP_MULTIPLE \
+ & ~(AT91C_MCI_TRDIR)) \
+ | AT91C_MCI_MAXLAT)
+// Cmd27
+#define AT91C_PROGRAM_CSD_CMD (27 | AT91C_MCI_RSPTYP_48 )
+
+//*----------------------------------------
+//* Class 5 commands: Erase commands
+//*----------------------------------------
+// Cmd32
+//#define AT91C_TAG_SECTOR_START_CMD (32 | AT91C_MCI_SPCMD_NONE | AT91C_MCI_RSPTYP_48 | AT91C_MCI_TRCMD_NO | AT91C_MCI_MAXLAT)
+// Cmd33
+//#define AT91C_TAG_SECTOR_END_CMD (33 | AT91C_MCI_SPCMD_NONE | AT91C_MCI_RSPTYP_48 | AT91C_MCI_TRCMD_NO | AT91C_MCI_MAXLAT)
+// Cmd38
+//#define AT91C_ERASE_CMD (38 | AT91C_MCI_SPCMD_NONE | AT91C_MCI_RSPTYP_48 | AT91C_MCI_TRCMD_NO | AT91C_MCI_MAXLAT )
+
+//*----------------------------------------
+//* Class 7 commands: Lock commands
+//*----------------------------------------
+// Cmd42
+//#define AT91C_LOCK_UNLOCK (42 | AT91C_MCI_SPCMD_NONE | AT91C_MCI_RSPTYP_48 | AT91C_MCI_TRCMD_NO | AT91C_MCI_MAXLAT) // not tested
+
+//*-----------------------------------------------
+// Class 8 commands: Application specific commands
+//*-----------------------------------------------
+// Cmd55
+#define AT91C_APP_CMD (55 | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_TRCMD_NO \
+ | AT91C_MCI_MAXLAT)
+// cmd 56
+//#define AT91C_GEN_CMD (56 | AT91C_MCI_SPCMD_NONE | AT91C_MCI_RSPTYP_48 | AT91C_MCI_TRCMD_NO | AT91C_MCI_MAXLAT) // not tested
+// ACMD6
+#define AT91C_SD_SET_BUS_WIDTH_CMD (6 | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_TRCMD_NO \
+ | AT91C_MCI_MAXLAT)
+// ACMD13
+#define AT91C_SD_STATUS_CMD (13 | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_TRCMD_START \
+ | AT91C_MCI_TRTYP_BLOCK \
+ | AT91C_MCI_TRDIR_READ \
+ | AT91C_MCI_MAXLAT)
+// ACMD22
+//#define AT91C_SD_SEND_NUM_WR_BLOCKS_CMD (22 | AT91C_MCI_SPCMD_NONE | AT91C_MCI_RSPTYP_48 | AT91C_MCI_TRCMD_NO | AT91C_MCI_MAXLAT)
+// ACMD23
+//#define AT91C_SD_SET_WR_BLK_ERASE_COUNT_CMD (23 | AT91C_MCI_SPCMD_NONE | AT91C_MCI_RSPTYP_48 | AT91C_MCI_TRCMD_NO | AT91C_MCI_MAXLAT)
+// ACMD41
+#define AT91C_SD_APP_OP_COND_CMD (41 | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_TRCMD_NO )
+// ACMD42
+//#define AT91C_SD_SET_CLR_CARD_DETECT_CMD (42 | AT91C_MCI_SPCMD_NONE | AT91C_MCI_RSPTYP_48 | AT91C_MCI_TRCMD_NO | AT91C_MCI_MAXLAT)
+// ACMD51
+#define AT91C_SD_SEND_SCR_CMD (51 | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_TRCMD_START \
+ | AT91C_MCI_TRDIR_READ \
+ | AT91C_MCI_TRTYP_BLOCK \
+ | AT91C_MCI_MAXLAT)
+
+// SDIO commands
+// CMD5, R4
+#define AT91C_SDIO_SEND_OP_COND (5 | AT91C_MCI_TRCMD_NO \
+ | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_OPDCMD)
+
+// CMD52, R5
+#define AT91C_SDIO_IO_RW_DIRECT (52| AT91C_MCI_TRCMD_NO \
+ | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_MAXLAT )
+
+// CMD53, R5
+#define AT91C_SDIO_IO_RW_EXTENDED (53 | AT91C_MCI_SPCMD_NONE \
+ | AT91C_MCI_RSPTYP_48 \
+ | AT91C_MCI_TRCMD_START \
+ | AT91C_MCI_MAXLAT)
+
+#ifdef AT91C_MCI_SPCMD_BOOTREQ
+// BOOTREQ
+#define AT91C_BOOTREQ (AT91C_MCI_SPCMD_BOOTREQ \
+ | AT91C_MCI_TRDIR_READ \
+ | AT91C_MCI_TRCMD_START \
+ | AT91C_MCI_MAXLAT)
+// BOOTEND
+#define AT91C_BOOTEND (AT91C_MCI_SPCMD_BOOTEND \
+ | AT91C_MCI_OPDCMD_PUSHPULL)
+#endif
+// Optional commands
+#define SD_ACMD6_SUPPORT (1UL << 0)
+#define SD_ACMD13_SUPPORT (1UL << 1)
+#define SD_ACMD41_SUPPORT (1UL << 2)
+#define SD_ACMD51_SUPPORT (1UL << 3)
+
+#define SD_CMD16_SUPPORT (1UL << 8)
+
+//------------------------------------------------------------------------------
+// Local functions
+//------------------------------------------------------------------------------
+
+//------------------------------------------------------------------------------
+/// DecodeR1
+/// \param R1
+//------------------------------------------------------------------------------
+void DecodeR1(unsigned char R1)
+{
+ if( (R1 & R1_SPI_IDLE)==R1_SPI_IDLE) {
+ TRACE_DEBUG("R1_SPI_IDLE\n\r");
+ }
+ if( (R1 & R1_SPI_ERASE_RESET)==R1_SPI_ERASE_RESET) {
+ TRACE_DEBUG("R1_SPI_ERASE_RESET\n\r");
+ }
+ if( (R1 & R1_SPI_ILLEGAL_COMMAND)==R1_SPI_ILLEGAL_COMMAND) {
+ TRACE_DEBUG("R1_SPI_ILLEGAL_COMMAND\n\r");
+ }
+ if( (R1 & R1_SPI_COM_CRC)==R1_SPI_COM_CRC) {
+ TRACE_DEBUG("R1_SPI_COM_CRC\n\r");
+ }
+ if( (R1 & R1_SPI_ERASE_SEQ)==R1_SPI_ERASE_SEQ) {
+ TRACE_DEBUG("R1_SPI_ERASE_SEQ\n\r");
+ }
+ if( (R1 & R1_SPI_ADDRESS)==R1_SPI_ADDRESS) {
+ TRACE_DEBUG("R1_SPI_ADDRESS\n\r");
+ }
+ if( (R1 & R1_SPI_PARAMETER)==R1_SPI_PARAMETER) {
+ TRACE_DEBUG("R1_SPI_PARAMETER\n\r");
+ }
+}
+
+//------------------------------------------------------------------------------
+/// DecodeR2
+/// \param R2
+//------------------------------------------------------------------------------
+void DecodeR2(unsigned char R2)
+{
+ if( (R2 & R2_SPI_CARD_LOCKED)==R2_SPI_CARD_LOCKED) {
+ TRACE_DEBUG("R2_SPI_CARD_LOCKED\n\r");
+ }
+ if( (R2 & R2_SPI_WP_ERASE_SKIP)==R2_SPI_WP_ERASE_SKIP) {
+ TRACE_DEBUG("R2_SPI_WP_ERASE_SKIP/R2_SPI_LOCK_UNLOCK_FAIL\n\r");
+ }
+ if( (R2 & R2_SPI_ERROR)==R2_SPI_ERROR) {
+ TRACE_DEBUG("R2_SPI_ERROR\n\r");
+ }
+ if( (R2 & R2_SPI_CC_ERROR)==R2_SPI_CC_ERROR) {
+ TRACE_DEBUG("R2_SPI_CC_ERROR\n\r");
+ }
+ if( (R2 & R2_SPI_CARD_ECC_ERROR)==R2_SPI_CARD_ECC_ERROR) {
+ TRACE_DEBUG("R2_SPI_CARD_ECC_ERROR\n\r");
+ }
+ if( (R2 & R2_SPI_WP_VIOLATION)==R2_SPI_WP_VIOLATION) {
+ TRACE_DEBUG("R2_SPI_WP_VIOLATION\n\r");
+ }
+ if( (R2 & R2_SPI_ERASE_PARAM)==R2_SPI_ERASE_PARAM) {
+ TRACE_DEBUG("R2_SPI_ERASE_PARAM\n\r");
+ }
+ if( (R2 & R2_SPI_OUT_OF_RANGE)==R2_SPI_OUT_OF_RANGE) {
+ TRACE_DEBUG("R2_SPI_OUT_OF_RANGE/R2_SPI_CSD_OVERWRITE\n\r");
+ }
+}
+
+//------------------------------------------------------------------------------
+/// Get Trans Speed Value (Kbit/s)
+/// \param tranSpeed The TRAN_SPEED value from SD(IO)/MMC enum information.
+/// \param unitList Transfer rate units (Kbit/s), 4 units listed.
+/// \param nbUnits Transfer rate units list size.
+/// \param codeList Time value codes list, 16 codes listed.
+//------------------------------------------------------------------------------
+static unsigned int MmcGetTranSpeed(unsigned int tranSpeed,
+ const unsigned int* unitList, unsigned int nbUnits,
+ const unsigned int* codeList)
+{
+ unsigned int unit, value;
+ unit = tranSpeed & 0x7;
+ if (unit < nbUnits) unit = unitList[unit];
+ else return 0;
+ value = (tranSpeed >> 3) & 0xF;
+ if (value < 16) value = codeList[value];
+ else return 0;
+ return (unit * value);
+}
+
+//------------------------------------------------------------------------------
+/// Get Trans Speed Value
+/// \param pSd
+//------------------------------------------------------------------------------
+void GetTransSpeedValue(SdCard *pSd)
+{
+ // CSD register, TRANS_SPEED bit
+ const unsigned int units[4] = {10, 100, 1000, 10000 }; // *Kbit/s
+ const unsigned int values_emmc[16] = {0, 10, 12, 13, 15, 20,
+ 26, 30, 35, 40, 45, 52,
+ 55, 60, 70, 80};
+ const unsigned int values_sdmmc[16] = {0, 10, 12, 13, 15, 20,
+ 25, 30, 35, 40, 45, 50,
+ 55, 60, 70, 80};
+ #if 0
+ unsigned int unit, value;
+ unit = (SD_CSD_TRAN_SPEED(pSd) & 0x7);
+ if(unit < 4) unit = units[unit];
+ else return;
+ value = (SD_CSD_TRAN_SPEED(pSd) >> 3) & 0xF;
+ if (value < 16) {
+ if (pSd->cardType >= CARD_MMC && SD_CID_BGA(pSd) == 1) {
+ value = values_emmc[value];
+ }
+ else
+ value = values_sdmmc[value];
+ }
+ else return;
+ pSd->transSpeed = (unit * value);
+ #else
+ pSd->transSpeed = MmcGetTranSpeed(SD_CSD_TRAN_SPEED(pSd),
+ units, 4,
+ (pSd->cardType >= CARD_MMC
+ && SD_CID_BGA(pSd) == 1) ?
+ values_emmc : values_sdmmc);
+ #endif
+ if (pSd->cardType >= CARD_MMC && SD_EXTCSD_HS_TIMING(pSd)) {
+ pSd->transSpeed *= 2;
+ }
+ TRACE_WARNING_WP("-I- SD/MMC TRANS SPEED %d KBit/s\r\n", pSd->transSpeed);
+ pSd->transSpeed *= 1000;
+}
+
+#if 1
+//------------------------------------------------------------------------------
+/// Reset the SdCmd
+//------------------------------------------------------------------------------
+static void ResetCommand(SdCmd *pCommand)
+{
+ #if 0
+ unsigned char* p = (unsigned char*)pCommand;
+ unsigned int l = sizeof(SdCmd);
+ while(l --) *p++ = 0;
+ #else
+ pCommand->cmd = 0;
+ pCommand->arg = 0;
+ pCommand->pData = 0;
+ pCommand->blockSize = 0;
+ pCommand->nbBlock = 0;
+ pCommand->pResp = 0;
+ pCommand->callback = 0;
+ pCommand->pArg = 0;
+ pCommand->resType = 0;
+ pCommand->dataTran = 0;
+ pCommand->tranType = 0;
+ pCommand->isRead = 0;
+ pCommand->status = 0;
+ #endif
+}
+#else
+// GNU halt on memset now
+# define ResetCommand(pCommand) memset(pCommand, 0, sizeof(SdCmd))
+#endif
+
+//------------------------------------------------------------------------------
+/// Delay some loop
+//------------------------------------------------------------------------------
+static void Delay(volatile unsigned int loop)
+{
+ for(;loop > 0; loop --);
+}
+
+//------------------------------------------------------------------------------
+/// Sends the current SD card driver command to the card.
+/// Returns 0 if successful; Otherwise, returns the transfer status code or
+/// SD_ERROR_DRIVER if there was a problem with the SD transfer.
+/// \param pSd Pointer to a SdCard driver instance.
+//------------------------------------------------------------------------------
+static unsigned char SendCommand(SdCard *pSd)
+{
+ SdCmd *pCommand = &(pSd->command);
+ SdDriver *pSdDriver = pSd->pSdDriver;
+ unsigned char error;
+
+ // Send command
+ error = MCI_SendCommand((Mci *)pSdDriver, (MciCmd *)pCommand);
+ if (error) {
+ TRACE_ERROR("MCI SendCommand: Failed to send command (%d)\n\r", error);
+ return SD_ERROR_DRIVER;
+ }
+
+ // Wait for command to complete (if no callback defined)
+ if (pCommand->callback == 0) {
+ while (!MCI_IsTxComplete((Mci *)pSdDriver));
+ }
+
+ // Check for using fifo to transfer data
+ #if !defined(MCI_DMA_ENABLE) && defined(MCI2_INTERFACE)
+ if (pCommand->dataTran && pCommand->nbBlock) {
+ MCI_FifoTransfer((Mci *)pSdDriver, (MciCmd *)pCommand);
+ }
+ #endif
+
+ return pCommand->status;
+}
+
+//------------------------------------------------------------------------------
+/// Initialization delay: The maximum of 1 msec, 74 clock cycles and supply ramp
+/// up time.
+/// Returns the command transfer result (see SendCommand).
+/// \param pSd Pointer to a SdCard driver instance.
+//------------------------------------------------------------------------------
+static unsigned char Pon(SdCard *pSd)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned int response;
+ unsigned char error;
+
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->cmd = AT91C_POWER_ON_INIT;
+ pCommand->pResp = &response;
+
+ // Send command
+ error = SendCommand(pSd);
+ return error;
+}
+
+#if defined(MCI2_INTERFACE) && defined(AT91C_MCI_SPCMD_BOOTREQ)
+//------------------------------------------------------------------------------
+/// Initialization delay: The maximum of 1 msec, 74 clock cycles and supply ramp
+/// up time, CMD keeps low so that the device run in boot mode.
+/// Returns the command transfer result (see SendCommand).
+/// \param pSd Pointer to a SdCard driver instance.
+//------------------------------------------------------------------------------
+static unsigned char PonBoot(SdCard *pSd)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned int response;
+ unsigned char error;
+
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->cmd = AT91C_POWER_ON_INIT;
+ pCommand->pResp = &response;
+
+ // Send command
+ error = SendCommand(pSd);
+ return error;
+}
+#endif
+
+//------------------------------------------------------------------------------
+/// Resets all cards to idle state
+/// \param pSd Pointer to a SdCard driver instance.
+/// \param arg Argument used.
+/// \return the command transfer result (see SendCommand).
+//------------------------------------------------------------------------------
+static unsigned char Cmd0(SdCard *pSd, unsigned int arg)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned int response;
+ unsigned char error;
+
+ TRACE_DEBUG("Cmd0()\n\r");
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->cmd = AT91C_GO_IDLE_STATE_CMD;
+ pCommand->arg = arg;
+ pCommand->pResp = &response;
+
+ // send command
+ error = SendCommand(pSd);
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// MMC send operation condition command.
+/// Sends host capacity support information and activates the card's
+/// initialization process.
+/// Returns the command transfer result (see SendCommand).
+/// \param pSd Pointer to a SdCard driver instance.
+/// \param hdSupport Indicate whether the host support high density MMC.
+/// \param pHdSupport Indicate whether the card is a high density MMC.
+//------------------------------------------------------------------------------
+static unsigned char Cmd1(SdCard *pSd,
+ unsigned char hdSupport,
+ unsigned char *pHdSupport)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+ unsigned int response;
+
+ TRACE_DEBUG("Cmd1()\n\r");
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->cmd = AT91C_MMC_SEND_OP_COND_CMD;
+ pCommand->arg = AT91C_MMC_HOST_VOLTAGE_RANGE;
+ if(hdSupport) {
+ pCommand->arg |= AT91C_MMC_HIGH_DENSITY;
+ }
+ else {
+ pCommand->arg |= AT91C_MMC_NORM_DENSITY;
+ }
+ pCommand->resType = 3;
+ pCommand->pResp = &response;
+
+ // send command
+ *pHdSupport = 0;
+ error = SendCommand(pSd);
+ if (error) {
+ return error;
+ }
+ if ((response & AT91C_CARD_POWER_UP_BUSY) == AT91C_CARD_POWER_UP_BUSY) { if((response & AT91C_MMC_OCR_BIT2930) == AT91C_MMC_HIGH_DENSITY) {
+ *pHdSupport = 1;
+ }
+ return 0;
+ }
+ else {
+ return SD_ERROR_DRIVER;
+ }
+}
+
+//------------------------------------------------------------------------------
+/// Asks any card to send the CID numbers
+/// on the CMD line (any card that is
+/// connected to the host will respond)
+/// Returns the command transfer result (see SendCommand).
+/// \param pSd Pointer to a SD card driver instance.
+/// \param pCid Buffer for storing the CID numbers.
+//------------------------------------------------------------------------------
+static unsigned char Cmd2(SdCard *pSd)
+{
+ SdCmd *pCommand = &(pSd->command);
+
+ TRACE_DEBUG("Cmd2()\n\r");
+ ResetCommand(pCommand);
+ // Fill the command information
+ pCommand->cmd = AT91C_ALL_SEND_CID_CMD;
+ pCommand->resType = 2;
+ pCommand->pResp = pSd->cid;
+
+ // Send the command
+ return SendCommand(pSd);
+}
+
+//------------------------------------------------------------------------------
+/// Ask the card to publish a new relative address (RCA)
+/// Returns the command transfer result (see SendCommand).
+/// \param pSd Pointer to a SD card driver instance.
+//------------------------------------------------------------------------------
+static unsigned char Cmd3(SdCard *pSd)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned int cardAddress;
+ unsigned char error;
+
+ TRACE_DEBUG("Cmd3()\n\r");
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->cmd = AT91C_SET_RELATIVE_ADDR_CMD;
+
+ // Assign relative address to MMC card
+ if ((pSd->cardType == CARD_MMC) || (pSd->cardType == CARD_MMCHD)) {
+ pCommand->arg = (0x1 << 16);
+ }
+ pCommand->resType = 1;
+ pCommand->pResp = &cardAddress;
+
+ // Send command
+ error = SendCommand(pSd);
+ if (error) {
+ return error;
+ }
+
+ // Save card address in driver
+ if ( (pSd->cardType == CARD_SD)
+ || (pSd->cardType == CARD_SDHC)) {
+ pSd->cardAddress = (cardAddress >> 16) & 0xFFFF;
+ }
+ else if (pSd->cardType >= CARD_SDIO) {
+ pSd->cardAddress = (cardAddress >> 16) & 0xFFFF;
+ }
+ else {
+ // Default MMC RCA is 0x0001
+ pSd->cardAddress = 1;
+ }
+
+ return 0;
+}
+
+#if MCI_SDIO_ENABLE
+//------------------------------------------------------------------------------
+/// SDIO send operation condition command.
+/// Sends host capacity support information and activates the card's
+/// initialization process.
+/// Returns the command transfer result (see SendCommand).
+/// \param pSd Pointer to a SdCard driver instance.
+/// \param pIo Pointer to data send as well as response buffer.
+//------------------------------------------------------------------------------
+static unsigned char Cmd5(SdCard *pSd,
+ unsigned int *pIo)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+
+ TRACE_DEBUG("Cmd5()\n\r");
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->cmd = AT91C_IO_SEND_OP_COND_CMD;
+ pCommand->arg = *pIo;
+ pCommand->resType = 4;
+ pCommand->pResp = pIo;
+
+ // send command
+ error = SendCommand(pSd);
+ return error;
+}
+#endif
+
+//------------------------------------------------------------------------------
+/// Command toggles a card between the
+/// stand-by and transfer states or between
+/// the programming and disconnect states.
+/// Returns the command transfer result (see SendCommand).
+/// \param pSd Pointer to a SD card driver instance.
+/// \param address Relative Card Address (0 deselects all).
+//------------------------------------------------------------------------------
+static unsigned char Cmd7(SdCard *pSd, unsigned int address)
+{
+ SdCmd *pCommand = &(pSd->command);
+
+ TRACE_DEBUG("Cmd7()\n\r");
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->cmd = AT91C_SEL_DESEL_CARD_CMD;
+ pCommand->arg = address << 16;
+ pCommand->resType = 1;
+
+ // Send command
+ return SendCommand(pSd);
+}
+
+//------------------------------------------------------------------------------
+/// Switches the mode of operation of the selected card (SD/MMC) or
+/// modifies the EXT_CSD registers (for MMC only).
+/// CMD6 is valid under the "trans" state.
+/// \return The command transfer result (see SendCommand).
+/// \param pSd Pointer to a SD/MMC card driver instance.
+/// \param pSwitchArg Pointer to a MmcCmd6Arg instance.
+/// \param pStatus Pointer to where the 512bit status is returned.
+/// \param pResp Pointer to where the response is returned.
+//------------------------------------------------------------------------------
+static unsigned char Cmd6(SdCard *pSd,
+ const void * pSwitchArg,
+ unsigned int * pStatus,
+ unsigned int * pResp)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned int response;
+ unsigned char error;
+ SdCmd6Arg * pSdSwitch;
+ MmcCmd6Arg * pMmcSwitch;
+
+ SANITY_CHECK(pSd);
+ SANITY_CHECK(pSwitchArg);
+
+ TRACE_DEBUG("CMD6()\n\r");
+
+ ResetCommand(pCommand);
+
+ if (pSd->cardType >= CARD_MMC) {
+ pMmcSwitch = (MmcCmd6Arg*)pSwitchArg;
+ // R1b response
+ pCommand->cmd = AT91C_MMC_SWITCH_CMD;
+ pCommand->resType = 1;
+ pCommand->arg = (pMmcSwitch->access << 24)
+ | (pMmcSwitch->index << 16)
+ | (pMmcSwitch->value << 8)
+ | (pMmcSwitch->cmdSet << 0);
+ }
+ else if (pSd->cardType >= CARD_SD) {
+
+ pSdSwitch = (SdCmd6Arg*)pSwitchArg;
+ // R1 response & 512 bits of status on DAT
+ pCommand->cmd = AT91C_SD_SWITCH_CMD;
+ pCommand->resType = 1;
+ pCommand->arg = (pSdSwitch->mode << 31)
+ | (pSdSwitch->reserved << 30)
+ | (pSdSwitch->reserveFG6 << 20)
+ | (pSdSwitch->reserveFG5 << 16)
+ | (pSdSwitch->reserveFG4 << 12)
+ | (pSdSwitch->reserveFG3 << 8)
+ | (pSdSwitch->command << 4)
+ | (pSdSwitch->accessMode << 0);
+ if (pStatus) {
+ pCommand->blockSize = 512 / 8;
+ pCommand->nbBlock = 1;
+ pCommand->pData = (unsigned char*)pStatus;
+
+ pCommand->dataTran = 1;
+ pCommand->isRead = 1;
+ pCommand->tranType = MCI_NEW_TRANSFER;
+ }
+ }
+ pCommand->pResp = &response;
+
+ TRACE_INFO("CMD6(%d) arg 0x%X\n\r", pSd->cardType, pCommand->arg);
+
+ error = SendCommand(pSd);
+
+ if (error)
+ return error;
+ else if (pResp)
+ *pResp = response;
+
+ return 0;
+}
+
+//------------------------------------------------------------------------------
+/// SD: Sends SD Memory Card interface condition, which includes host supply
+/// voltage information and asks the card whether card supports voltage.
+/// Should be performed at initialization time to detect the card type.
+/// MMC: SEND_EXT_CSD, to get EXT_CSD register as a block of data.
+/// Valid under "trans" state.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param sdCmd For SD Memory Card interface condition
+/// \param arg Expected supply voltage(SD) or 512 byte buffer pointer (MMC).
+/// \return 0 if successful;
+/// otherwise returns SD_ERROR_NORESPONSE if the card did not answer
+/// the command, or SD_ERROR_DRIVER.
+//------------------------------------------------------------------------------
+static unsigned char Cmd8(SdCard *pSd,
+ unsigned char sdCmd,
+ void* arg)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned int response;
+ unsigned char error;
+ unsigned char supplyVoltage = (unsigned char)((unsigned int)arg);
+
+ TRACE_DEBUG("Cmd8()\n\r");
+ ResetCommand(pCommand);
+
+ if (sdCmd) {
+
+ // Fill command information
+ pCommand->cmd = AT91C_SEND_IF_COND;
+ pCommand->arg = (supplyVoltage << 8) | (0xAA);
+ pCommand->resType = 7;
+
+ TRACE_DEBUG("supplyVoltage: 0x%x\n\r", supplyVoltage);
+ }
+ else {
+
+ pCommand->cmd = AT91C_SEND_EXT_CSD_CMD;
+ pCommand->resType = 1;
+
+ pCommand->blockSize = SD_BLOCK_SIZE;
+ pCommand->nbBlock = 512 / SD_BLOCK_SIZE;
+ pCommand->pData = arg;
+
+ pCommand->dataTran = 1;
+ pCommand->isRead = 1;
+ pCommand->tranType = MCI_NEW_TRANSFER;
+ }
+ pCommand->pResp = &response;
+
+ // Send command
+ error = SendCommand(pSd);
+
+ if (sdCmd) {
+
+ // Check result
+ if (error == MCI_STATUS_NORESPONSE) {
+
+ return SD_ERROR_NORESPONSE;
+ }
+ // SD_R7
+ // Bit 0 - 7: check pattern (echo-back)
+ // Bit 8 -11: voltage accepted
+ else if (!error &&
+ ((response & 0x00000FFF) == ((supplyVoltage << 8) | 0xAA))) {
+ return 0;
+ }
+ else {
+ return SD_ERROR_DRIVER;
+ }
+ }
+
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// Addressed card sends its card-specific
+/// data (CSD) on the CMD line.
+/// Returns the command transfer result (see SendCommand).
+/// \param pSd Pointer to a SD card driver instance.
+//------------------------------------------------------------------------------
+static unsigned char Cmd9(SdCard *pSd)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+
+ TRACE_DEBUG("Cmd9()\n\r");
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->cmd = AT91C_SEND_CSD_CMD;
+ pCommand->arg = pSd->cardAddress << 16;
+ pCommand->resType = 2;
+ pCommand->pResp = pSd->csd;
+
+ // Send command
+ error = SendCommand(pSd);
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// Forces the card to stop transmission
+/// \param pSd Pointer to a SD card driver instance.
+/// \param stopRead Stop reading stream/writing stream.
+/// \param pStatus Pointer to a status variable.
+//------------------------------------------------------------------------------
+static unsigned char Cmd12(SdCard *pSd,
+ unsigned char stopRead,
+ unsigned int *pStatus)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+ unsigned int response;
+
+ TRACE_DEBUG("Cmd12()\n\r");
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->cmd = AT91C_STOP_TRANSMISSION_CMD;
+ pCommand->isRead = stopRead;
+ pCommand->tranType = MCI_STOP_TRANSFER;
+ pCommand->resType = 1;
+ pCommand->pResp = &response;
+
+ // Send command
+ error = SendCommand(pSd);
+ if (pStatus) *pStatus = response;
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// Addressed card sends its status register.
+/// Returns the command transfer result (see SendCommand).
+/// \param pSd Pointer to a SD card driver instance.
+/// \param pStatus Pointer to a status variable.
+//------------------------------------------------------------------------------
+static unsigned char Cmd13(SdCard *pSd, unsigned int *pStatus)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+
+ TRACE_DEBUG("Cmd13()\n\r");
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->cmd = AT91C_SEND_STATUS_CMD;
+ pCommand->arg = pSd->cardAddress << 16;
+ pCommand->resType = 1;
+ pCommand->pResp = pStatus;
+
+ // Send command
+ error = SendCommand(pSd);
+
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// In the case of a Standard Capacity SD Memory Card, this command sets the
+/// block length (in bytes) for all following block commands
+/// (read, write, lock).
+/// Default block length is fixed to 512 Bytes.
+/// Set length is valid for memory access commands only if partial block read
+/// operation are allowed in CSD.
+/// In the case of a High Capacity SD Memory Card, block length set by CMD16
+/// command does not affect the memory read and write commands. Always 512
+/// Bytes fixed block length is used. This command is effective for LOCK_UNLOCK
+/// command. In both cases, if block length is set larger than 512Bytes, the
+/// card sets the BLOCK_LEN_ERROR bit.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param blockLength Block length in bytes.
+//------------------------------------------------------------------------------
+static unsigned char Cmd16(SdCard *pSd, unsigned short blockLength)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+ unsigned int response;
+
+ TRACE_DEBUG("Cmd16()\n\r");
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->cmd = AT91C_SET_BLOCKLEN_CMD;
+ pCommand->arg = blockLength;
+ pCommand->resType = 1;
+ pCommand->pResp = &response;
+
+ // Send command
+ error = SendCommand(pSd);
+
+ return error;
+}
+
+#ifdef SINGLE_READ
+static unsigned char Cmd17(SdCard *pSd,
+ unsigned char *pData,
+ unsigned int address,
+ unsigned int *pStatus)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+ unsigned int response;
+
+ TRACE_DEBUG("Cmd17()\n\r");
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->cmd = AT91C_READ_SINGLE_BLOCK_CMD;
+ pCommand->arg = address;
+ pCommand->resType = 1;
+ pCommand->pResp = &response;
+
+ pCommand->blockSize = SD_BLOCK_SIZE;
+ pCommand->nbBlock = 1;
+ pCommand->pData = pData;
+
+ pCommand->dataTran = 1;
+ pCommand->isRead = 1;
+ pCommand->tranType = MCI_NEW_TRANSFER;
+
+ // Send command
+ error = SendCommand(pSd);
+
+ if (pStatus) *pStatus = response;
+ return error;
+}
+#endif
+
+//------------------------------------------------------------------------------
+/// Continously transfers datablocks from card to host until interrupted by a
+/// STOP_TRANSMISSION command.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param blockSize Block size (shall be set to 512 in case of high capacity).
+/// \param pData Pointer to the DW aligned buffer to be filled.
+/// \param address SD card address.
+//------------------------------------------------------------------------------
+static unsigned char Cmd18(SdCard *pSd,
+ unsigned short nbBlock,
+ unsigned char *pData,
+ unsigned int address,
+ unsigned int *pStatus)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+ unsigned int response;
+
+ TRACE_DEBUG("Cmd18()\n\r");
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->cmd = AT91C_READ_MULTIPLE_BLOCK_CMD;
+ pCommand->arg = address;
+ pCommand->resType = 1;
+ pCommand->pResp = &response;
+
+ pCommand->blockSize = SD_BLOCK_SIZE;
+ pCommand->nbBlock = nbBlock;
+ pCommand->pData = pData;
+
+ pCommand->dataTran = 1;
+ pCommand->isRead = 1;
+ pCommand->tranType = MCI_NEW_TRANSFER;
+
+ // Send command
+ error = SendCommand(pSd);
+
+ if (pStatus) *pStatus = response;
+
+ return error;
+}
+#ifdef SINGLE_WRITE
+static unsigned char Cmd24(SdCard *pSd,
+ unsigned char *pData,
+ unsigned int address,
+ unsigned int *pStatus)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+ unsigned int response;
+
+ TRACE_DEBUG("Cmd24()\n\r");
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->cmd = AT91C_WRITE_BLOCK_CMD;
+ pCommand->arg = address;
+ pCommand->resType = 1;
+ pCommand->pResp = &response;
+
+ pCommand->blockSize = SD_BLOCK_SIZE;
+ pCommand->nbBlock = 1;
+ pCommand->pData = pData;
+
+ pCommand->dataTran = 1;
+ pCommand->isRead = 0;
+ pCommand->tranType = MCI_NEW_TRANSFER;
+
+ // Send command
+ error = SendCommand(pSd);
+
+ if (pStatus) *pStatus = response;
+ return error;
+}
+#endif
+//------------------------------------------------------------------------------
+/// Write block command
+/// \param pSd Pointer to a SD card driver instance.
+/// \param blockSize Block size (shall be set to 512 in case of high capacity).
+/// \param pData Pointer to the DW aligned buffer to be filled.
+/// \param address SD card address.
+//------------------------------------------------------------------------------
+static unsigned char Cmd25(SdCard *pSd,
+ unsigned short nbBlock,
+ unsigned char *pData,
+ unsigned int address,
+ unsigned int *pStatus)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+ unsigned int response;
+
+ TRACE_DEBUG("Cmd25()\n\r");
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->cmd = AT91C_WRITE_MULTIPLE_BLOCK_CMD;
+ pCommand->arg = address;
+ pCommand->resType = 1;
+ pCommand->pResp = &response;
+
+ pCommand->blockSize = SD_BLOCK_SIZE;
+ pCommand->nbBlock = nbBlock;
+ pCommand->pData = pData;
+
+ pCommand->dataTran = 1;
+ pCommand->tranType = MCI_NEW_TRANSFER;
+
+ // Send command
+ error = SendCommand(pSd);
+ if (pStatus) *pStatus = response;
+
+ return error;
+}
+
+#if MCI_SDIO_ENABLE
+//------------------------------------------------------------------------------
+/// SDIO R/W Byte Direct, response R5
+/// \param pSd Pointer to SdCard instance.
+/// \param func Number of function.
+/// \param rw The direction of IO operation, 1 for write.
+/// \param raw Read after write
+/// \param addr The register address to access.
+/// \param pIoData Pointer to fill written data and response.
+//------------------------------------------------------------------------------
+static unsigned char Cmd52(SdCard *pSd,
+ unsigned char func,
+ unsigned char rw,
+ unsigned char raw,
+ unsigned int addr,
+ unsigned int *pIoData)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+ unsigned int response;
+ unsigned char byte = 0;
+
+ TRACE_DEBUG("Cmd52()\n\r");
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->cmd = AT91C_SDIO_IO_RW_DIRECT;
+ // - argument
+ if (pIoData) byte = *pIoData;
+ pCommand->arg = byte
+ | (addr << 9) // register address 25: 9
+ | (raw << 27) // ReadAfterWrite 27
+ | (func << 28) // FunctionNumber 30:28
+ | (rw << 31); // R/W 31
+ pCommand->resType = 5;
+ pCommand->pResp = &response;
+ // Send command
+ error = SendCommand(pSd);
+ if (pIoData) *pIoData = response;
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// SDIO R/W Extended, response R5
+/// \param pSd Pointer to SdCard instance.
+/// \param func Number of function.
+/// \param rw The direction of IO operation, 1 for write.
+/// \param blockMode R/O on a block basis
+/// \param incAddress R/W to incrementing address (1) or fixed address (0)
+/// \param addr The register address to access.
+/// \param pIoData Pointer to fill written data and response.
+/// \param size Data size base on bytes or blocks depending on blockMode
+/// \param pResp Pointer to response buffer
+//------------------------------------------------------------------------------
+static unsigned char Cmd53(SdCard *pSd,
+ unsigned char func,
+ unsigned char rw,
+ unsigned char blockMode,
+ unsigned char incAddress,
+ unsigned int addr,
+ unsigned char *pIoData,
+ unsigned short size,
+ unsigned int *pResp)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+
+ TRACE_DEBUG("Cmd53()\n\r");
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->cmd = AT91C_SDIO_IO_RW_EXTENDED;
+ // - argument
+ pCommand->arg = size
+ | (addr << 9) // register address 25: 9
+ | (incAddress << 26) // OP Code 26
+ | (blockMode << 27) // ReadAfterWrite 27
+ | (func << 28) // FunctionNumber 30:28
+ | (rw << 31); // R/W 31
+ pCommand->resType = 5;
+ pCommand->pResp = pResp;
+
+ // - Write...
+ if (rw) {}
+ else {
+ pCommand->cmd |= AT91C_MCI_TRDIR_READ;
+ pCommand->isRead = 1;
+ }
+ // - Block...
+ if (blockMode) {
+ pCommand->cmd |= AT91C_MCI_TRTYP_SDIO_BLOCK
+ | AT91C_MCI_TRCMD_START;
+ pCommand->blockSize = SD_BLOCK_SIZE;
+ }
+ else {
+ pCommand->cmd |= AT91C_MCI_TRTYP_SDIO_BYTE
+ | AT91C_MCI_TRCMD_START;
+ pCommand->blockSize = 1;
+ }
+ pCommand->nbBlock = size;
+ pCommand->pData = pIoData;
+ pCommand->dataTran = 1;
+ pCommand->tranType = MCI_NEW_TRANSFER;
+
+ // Send command
+ error = SendCommand(pSd);
+ return error;
+}
+#endif
+
+//------------------------------------------------------------------------------
+/// Initialization delay: The maximum of 1 msec, 74 clock cycles and supply
+/// ramp up time.
+/// Returns the command transfer result (see SendCommand).
+/// \param pSd Pointer to a SD card driver instance.
+//------------------------------------------------------------------------------
+static unsigned char Cmd55(SdCard *pSd)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+ unsigned int response;
+
+ TRACE_DEBUG("Cmd55()\n\r");
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->cmd = AT91C_APP_CMD;
+ pCommand->arg = (pSd->cardAddress << 16);
+ pCommand->resType = 1;
+ pCommand->pResp = &response;
+
+ // Send command
+ error = SendCommand(pSd);
+
+ return error;
+}
+
+/*
+//------------------------------------------------------------------------------
+/// SPI Mode, Reads the OCR register of a card
+/// Returns the command transfer result (see SendCommand).
+/// \param pSd Pointer to a SD card driver instance.
+/// \param pOcr OCR value of the card
+//------------------------------------------------------------------------------
+static unsigned char Cmd58(SdCard *pSd, unsigned int *pOcr)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+ unsigned int response[2];
+
+ TRACE_DEBUG("Cmd58()\n\r");
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->cmd = AT91C_READ_OCR_CMD;
+ pCommand->resType = 3;
+ pCommand->pResp = &response[0];
+
+ // Send command
+ error = SendCommand(pSd);
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// SPI Mode, Set CRC option of a card
+/// Returns the command transfer result (see SendCommand).
+/// \param pSd Pointer to a SD card driver instance.
+/// \param option CRC option, 1 to turn on, 0 to trun off
+//------------------------------------------------------------------------------
+static unsigned char Cmd59(SdCard *pSd, unsigned char option)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+ unsigned int response;
+
+ TRACE_DEBUG("Cmd59()\n\r");
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->cmd = AT91C_CRC_ON_OFF_CMD;
+ pCommand->arg = (option & 0x1);
+ pCommand->resType = 1;
+ pCommand->pResp = &response;
+
+ // Send command
+ error = SendCommand(pSd);
+
+ return error;
+}
+*/
+
+//------------------------------------------------------------------------------
+/// Defines the data bus width (00=1bit or 10=4 bits bus) to be used for data
+/// transfer.
+/// The allowed data bus widths are given in SCR register.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param busWidth Bus width in bits.
+/// \return the command transfer result (see SendCommand).
+//------------------------------------------------------------------------------
+static unsigned char Acmd6(SdCard *pSd, unsigned char busWidth)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+ unsigned int response;
+
+ TRACE_DEBUG("Acmd6()\n\r");
+
+ error = Cmd55(pSd);
+ if (error) {
+ TRACE_ERROR("Acmd6.Cmd55: %d\n\r", error);
+ return error;
+ }
+
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->cmd = AT91C_SD_SET_BUS_WIDTH_CMD;
+ pCommand->arg = (busWidth == 4) ? SD_STAT_DATA_BUS_WIDTH_4BIT :
+ SD_STAT_DATA_BUS_WIDTH_1BIT;
+ pCommand->resType = 1;
+ pCommand->pResp = &response;
+
+ // Send command
+ return SendCommand(pSd);
+}
+
+//------------------------------------------------------------------------------
+/// The SD Status contains status bits that are related to the SD memory Card
+/// proprietary features and may be used for future application-specific usage.
+/// Can be sent to a card only in 'tran_state'.
+//------------------------------------------------------------------------------
+static unsigned char Acmd13(SdCard *pSd, unsigned int * pSdSTAT)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+ unsigned int response[1];
+
+ TRACE_DEBUG("Acmd13()\n\r");
+
+ error = Cmd55(pSd);
+ if (error) {
+ TRACE_ERROR("Acmd13.Cmd55: %d\n\r", error);
+ return error;
+ }
+
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->cmd = AT91C_SD_STATUS_CMD;
+ pCommand->resType = 1;
+ pCommand->pResp = response;
+
+ pCommand->blockSize = 512 / 8;
+ pCommand->nbBlock = 1;
+ pCommand->pData = (unsigned char*)pSdSTAT;
+
+ pCommand->dataTran = 1;
+ pCommand->isRead = 1;
+ pCommand->tranType = MCI_NEW_TRANSFER;
+
+ // Send command
+ error = SendCommand(pSd);
+
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// Asks to all cards to send their operations conditions.
+/// Returns the command transfer result (see SendCommand).
+/// \param pSd Pointer to a SD card driver instance.
+/// \param hcs Shall be true if Host support High capacity.
+/// \param pCCS Set the pointed flag to 1 if hcs != 0 and SD OCR CCS flag is set.
+//------------------------------------------------------------------------------
+static unsigned char Acmd41(SdCard *pSd, unsigned char hcs, unsigned char *pCCS)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+ unsigned int response;
+
+ do {
+ error = Cmd55(pSd);
+ if (error) {
+ return error;
+ }
+
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->cmd = AT91C_SD_APP_OP_COND_CMD;
+ pCommand->arg = AT91C_MMC_HOST_VOLTAGE_RANGE;
+ if (hcs) {
+ pCommand->arg |= AT91C_CCS;
+ }
+
+ pCommand->resType = 3;
+ pCommand->pResp = &response;
+
+ // Send command
+ TRACE_DEBUG("Acmd41()\n\r");
+ error = SendCommand(pSd);
+ if (error) {
+ return error;
+ }
+ *pCCS = ((response & AT91C_CCS) != 0);
+ }
+ while ((response & AT91C_CARD_POWER_UP_BUSY) != AT91C_CARD_POWER_UP_BUSY);
+
+ return 0;
+}
+
+//------------------------------------------------------------------------------
+/// SD Card Configuration Register (SCR) provides information on the SD Memory
+/// Card's special features that were configured into the given card. The size
+/// of SCR register is 64 bits.
+//------------------------------------------------------------------------------
+static unsigned char Acmd51(SdCard *pSd, unsigned int * pSCR)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+ unsigned int response[1];
+
+ TRACE_DEBUG("Acmd51()\n\r");
+
+ error = Cmd55(pSd);
+ if (error) {
+ TRACE_ERROR("Acmd51.Cmd55: %d\n\r", error);
+ return error;
+ }
+
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->cmd = AT91C_SD_SEND_SCR_CMD;
+ pCommand->resType = 1;
+ pCommand->pResp = response;
+
+ pCommand->blockSize = 64 / 8;
+ pCommand->nbBlock = 1;
+ pCommand->pData = (unsigned char*)pSCR;
+
+ pCommand->dataTran = 1;
+ pCommand->isRead = 1;
+ pCommand->tranType = MCI_NEW_TRANSFER;
+
+ // Send command
+ error = SendCommand(pSd);
+
+ //if (!error) Int2MsbFirstStream((unsigned char*)pSCR, 8 / 4);
+
+ return error;
+}
+
+#if defined(MCI2_INTERFACE) && defined(AT91C_MCI_SPCMD_BOOTREQ)
+//------------------------------------------------------------------------------
+/// Terminate boot stream.
+/// \param pSd Pointer to SdCard instance.
+//------------------------------------------------------------------------------
+static unsigned char BootEnd(SdCard *pSd)
+{
+ SdCmd * pCommand = &(pSd->command);
+
+ TRACE_DEBUG("BootEnd()\n\r");
+ ResetCommand(pCommand);
+
+ // Send boot end
+ pCommand->cmd = AT91C_BOOTEND;
+
+ return SendCommand(pSd);
+}
+
+//------------------------------------------------------------------------------
+/// In boot operation mode, the processor can read boot data from the slave,
+/// by keeping the CMD line low after power-on before issuing CMD1.
+/// BootEnd() must be invoked after the boot request done.
+/// \param pSd Pointer to SdCard instance.
+/// \param pBuffer The buffer holding received data.
+/// \param length The buffer length.
+//------------------------------------------------------------------------------
+static unsigned char BootREQ(SdCard *pSd,
+ unsigned char* pBuffer,
+ unsigned int nbBlocks,
+ unsigned char ackEnable)
+{
+ SdCmd * pCommand = &(pSd->command);
+ unsigned char error;
+
+ TRACE_DEBUG("BootREQ()\n\r");
+ ResetCommand(pCommand);
+
+ // Send boot request
+ pCommand->cmd = ackEnable ? (AT91C_BOOTREQ | AT91C_MCI_BOOTACK)
+ : AT91C_BOOTREQ;
+ pCommand->blockSize = SD_BLOCK_SIZE;
+ pCommand->nbBlock = nbBlocks;
+ pCommand->pData = pBuffer;
+ pCommand->isRead = 1;
+ pCommand->tranType = MCI_NEW_TRANSFER;
+
+ error = SendCommand(pSd);
+ if (error) {
+ TRACE_ERROR("BootOperation.BootReq: %d\n\r", error);
+ return error;
+ }
+ return error;
+}
+#endif
+
+//------------------------------------------------------------------------------
+/// Continue to transfer datablocks from card to host until interrupted by a
+/// STOP_TRANSMISSION command.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param blockSize Block size (shall be set to 512 in case of high capacity).
+/// \param pData Pointer to the application buffer to be filled.
+/// \param address SD card address.
+//------------------------------------------------------------------------------
+static unsigned char ContinuousRead(SdCard *pSd,
+ unsigned short nbBlock,
+ unsigned char *pData,
+ SdCallback pCb,
+ void *pArg)
+{
+ SdCmd *pCommand = &(pSd->command);
+
+ TRACE_DEBUG("Read()\n\r");
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->blockSize = SD_BLOCK_SIZE;
+ pCommand->nbBlock = nbBlock;
+ pCommand->pData = pData;
+
+ pCommand->dataTran = 1;
+ pCommand->tranType = MCI_CONTINUE_TRANSFER;
+ pCommand->isRead = 1;
+
+ pCommand->callback = pCb;
+ pCommand->pArg = pArg;
+
+ // Send command
+ return SendCommand(pSd);
+}
+
+//------------------------------------------------------------------------------
+/// Continue to transfer datablocks from host to card until interrupted by a
+/// STOP_TRANSMISSION command.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param blockSize Block size (shall be set to 512 in case of high capacity).
+/// \param pData Pointer to the application buffer to be filled.
+//------------------------------------------------------------------------------
+static unsigned char ContinuousWrite(SdCard *pSd,
+ unsigned short nbBlock,
+ const unsigned char *pData,
+ SdCallback pCb,
+ void *pArg)
+{
+ SdCmd *pCommand = &(pSd->command);
+
+ TRACE_DEBUG("Write()\n\r");
+ ResetCommand(pCommand);
+ // Fill command information
+ pCommand->blockSize = SD_BLOCK_SIZE;
+ pCommand->nbBlock = nbBlock;
+ pCommand->pData = (unsigned char*)pData;
+
+ pCommand->dataTran = 1;
+ pCommand->tranType = MCI_CONTINUE_TRANSFER;
+
+ pCommand->callback = pCb;
+ pCommand->pArg = pArg;
+
+ // Send command
+ return SendCommand(pSd);
+}
+
+//------------------------------------------------------------------------------
+/// Try SW Reset several times (CMD0 with ARG 0)
+/// \param pSd Pointer to a SD card driver instance.
+/// \param retry Retry times.
+/// \return 0 or MCI error code.
+//------------------------------------------------------------------------------
+static unsigned char SwReset(SdCard *pSd, unsigned int retry)
+{
+ unsigned int i;
+ unsigned char error = 0;
+
+ for (i = 0; i < retry; i ++) {
+ error = Cmd0(pSd, 0);
+ if (error != MCI_STATUS_NORESPONSE)
+ break;
+ }
+ return error;
+}
+/*
+//------------------------------------------------------------------------------
+/// Re-init card to trans state.
+//------------------------------------------------------------------------------
+static unsigned char ReInit(SdCard *pSd)
+{
+ #if 0
+ unsigned char error;
+ error = SwReset(pSd, 1);
+ if (error) {
+ TRACE_ERROR("ReInit.Cmd0: %d\n\r", error);
+ return error;
+ }
+ error = Cmd1(pSd);
+ if (error) {
+ TRACE_ERROR("ReInit.Cmd1: %d\n\r", error);
+ return error;
+ }
+ error = Cmd2(pSd);
+ if (error) {
+ TRACE_ERROR("ReInit.Cmd2: %d\n\r", error);
+ return error;
+ }
+ error = Cmd3(pSd);
+ if (error) {
+ TRACE_ERROR("ReInit.Cmd3: %d\n\r", error);
+ return error;
+ }
+ error = Cmd7(pSd, pSd->cardAddress);
+ if (error) {
+ TRACE_ERROR("ReInit.Cmd7: %d\n\r", error);
+ return error;
+ }
+ #endif
+ return 0;
+}
+*/
+//------------------------------------------------------------------------------
+/// Move SD card to transfer state.
+//------------------------------------------------------------------------------
+static unsigned char MoveToTranState(SdCard * pSd)
+{
+ unsigned char error;
+ unsigned int status;
+
+ // Quit transfer state
+ if((pSd->state == SD_STATE_READ)
+ || (pSd->state == SD_STATE_WRITE)) {
+
+ error = Cmd12(pSd,
+ (pSd->state == SD_STATE_READ),
+ &status);
+ if (error) {
+ TRACE_ERROR("MvToTran.Cmd12: %d\n\r", error);
+ return error;
+ }
+ }
+
+ // Put device into tran state
+ error = Cmd13(pSd, &status);
+ if (error) {
+ TRACE_ERROR("MvToTran.Cmd13: %d\n\r", error);
+ return error;
+ }
+ if ((status & STATUS_STATE) == STATUS_STBY) {
+ error = Cmd7(pSd, pSd->cardAddress);
+ if (error) {
+ TRACE_ERROR("MvToTran.Cmd7: %d\n\r", error);
+ return error;
+ }
+ }
+
+ return 0;
+}
+
+#if defined(SINGLE_READ) || defined(SINGLE_WRITE)
+static unsigned char PerformSingleTransfer(SdCard *pSd,
+ unsigned int address,
+ unsigned char *pData,
+ unsigned char isRead)
+{
+ unsigned int status;
+ unsigned char error = 0;
+
+ /* Reset transfer state if previous in multi- mode */
+ if( (pSd->state == SD_STATE_READ)
+ || (pSd->state == SD_STATE_WRITE)) {
+ /* Stop transfer */
+ error = Cmd12(pSd, (pSd->state == SD_STATE_READ), &status);
+ if (error) {
+ TRACE_ERROR("SingleTx.Cmd12: st%x, er%d\n\r", pSd->state, error);
+ }
+ pSd->state = SD_STATE_READY;
+ pSd->preBlock = 0xFFFFFFFF;
+ }
+
+#ifdef SINGLE_READ
+ if(isRead) {
+ // Wait for card to be ready for data transfers
+ do {
+ error = Cmd13(pSd, &status);
+ if (error) {
+ TRACE_ERROR("SingleTx.RD.Cmd13: %d\n\r", error);
+ return error;
+ }
+ if( ((status & STATUS_STATE) == STATUS_IDLE)
+ ||((status & STATUS_STATE) == STATUS_READY)
+ ||((status & STATUS_STATE) == STATUS_IDENT)) {
+ TRACE_ERROR("SingleTx.mode\n\r");
+ return SD_ERROR_NOT_INITIALIZED;
+ }
+ // If the card is in sending data state or in receivce data state
+ if ( ((status & STATUS_STATE) == STATUS_RCV)
+ ||((status & STATUS_STATE) == STATUS_DATA) ){
+
+ TRACE_DEBUG("SingleTx.state = 0x%X\n\r", (status & STATUS_STATE) >> 9);
+ }
+ }
+ while ( ((status & STATUS_READY_FOR_DATA) == 0)
+ || ((status & STATUS_STATE) != STATUS_TRAN) );
+ ASSERT((status & STATUS_STATE) == STATUS_TRAN,
+ "SD Card can't be configured in transfer state 0x%X\n\r",
+ (status & STATUS_STATE)>>9);
+ // Read data
+ // Move to Sending data state
+ error = Cmd17(pSd, pData, SD_ADDRESS(pSd,address), &status);
+ if (error) {
+ TRACE_ERROR("SingleTx.Cmd17: %d\n\r", error);
+ return error;
+ }
+ if (status & ~(STATUS_READY_FOR_DATA | STATUS_STATE)) {
+ TRACE_ERROR("CMD17.stat: %x\n\r",
+ status & ~(STATUS_READY_FOR_DATA | STATUS_STATE));
+ return SD_ERROR_DRIVER;
+ }
+ return error;
+ }
+#endif
+#ifdef SINGLE_WRITE
+ // Write
+ {
+ // Wait for card to be ready for data transfers
+ do {
+ error = Cmd13(pSd, &status);
+ if (error) {
+ TRACE_ERROR("SingleTx.WR.Cmd13: %d\n\r", error);
+ return error;
+ }
+ }
+ while ((status & STATUS_READY_FOR_DATA) == 0);
+ // Move to Sending data state
+ error = Cmd24(pSd, pData, SD_ADDRESS(pSd,address), &status);
+ if (error) {
+ TRACE_DEBUG("SingleTx.Cmd25: %d\n\r", error);
+ return error;
+ }
+ if (status & (STATUS_WRITE & ~(STATUS_READY_FOR_DATA | STATUS_STATE))) {
+ TRACE_ERROR("CMD24(0x%x).stat: %x\n\r",
+ SD_ADDRESS(pSd,address),
+ status & (STATUS_WRITE
+ & ~(STATUS_READY_FOR_DATA | STATUS_STATE)));
+ return SD_ERROR_DRIVER;
+ }
+ }
+ return error;
+#endif
+}
+#endif
+
+//------------------------------------------------------------------------------
+/// Move SD card to transfer state. The buffer size must be at
+/// least 512 byte long. This function checks the SD card status register and
+/// address the card if required before sending the transfer command.
+/// Returns 0 if successful; otherwise returns an code describing the error.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param address Address of the block to transfer.
+/// \param nbBlocks Number of blocks to be transfer, 0 for infinite transfer.
+/// \param pData Data buffer whose size is at least the block size.
+/// \param isRead 1 for read data and 0 for write data.
+//------------------------------------------------------------------------------
+static unsigned char MoveToTransferState(SdCard *pSd,
+ unsigned int address,
+ unsigned short nbBlocks,
+ unsigned char *pData,
+ unsigned char isRead)
+{
+ unsigned int status;
+ unsigned char error;
+
+ if( (pSd->state == SD_STATE_READ)
+ || (pSd->state == SD_STATE_WRITE)) {
+#if 1//!defined(MCI2_INTERFACE)
+ if (pSd->state == SD_STATE_WRITE) {
+ DBGU_PutChar(0);
+ DBGU_PutChar(0);
+ DBGU_PutChar(0);
+ DBGU_PutChar(0);
+ }
+#endif
+ // RW MULTI with length
+ error = Cmd12(pSd,
+ (pSd->state == SD_STATE_READ),
+ &status);
+ if (error) {
+ TRACE_ERROR("MTTranState.Cmd12: st%x, er%d\n\r", pSd->state, error);
+ return error;
+ }
+#if !defined(MCI2_INTERFACE)
+ // RW MULTI Infinite
+ if (pSd->state == SD_STATE_WRITE) {
+ while(MCI_CheckBusy((Mci *)pSd->pSdDriver) != 0);
+ }
+#endif
+ }
+
+ if(isRead) {
+ // Wait for card to be ready for data transfers
+ do {
+ error = Cmd13(pSd, &status);
+ if (error) {
+ TRACE_ERROR("MTTranState.RD.Cmd13: %d\n\r", error);
+ return error;
+ }
+ if( ((status & STATUS_STATE) == STATUS_IDLE)
+ ||((status & STATUS_STATE) == STATUS_READY)
+ ||((status & STATUS_STATE) == STATUS_IDENT)) {
+ TRACE_ERROR("Pb Card Identification mode\n\r");
+ return SD_ERROR_NOT_INITIALIZED;
+ }
+ // If the card is in sending data state or in receivce data state
+ if ( ((status & STATUS_STATE) == STATUS_RCV)
+ ||((status & STATUS_STATE) == STATUS_DATA) ){
+
+ TRACE_DEBUG("state = 0x%X\n\r", (status & STATUS_STATE) >> 9);
+ }
+ }
+ while ( ((status & STATUS_READY_FOR_DATA) == 0)
+ || ((status & STATUS_STATE) != STATUS_TRAN) );
+ ASSERT((status & STATUS_STATE) == STATUS_TRAN,
+ "SD Card can't be configured in transfer state 0x%X\n\r",
+ (status & STATUS_STATE)>>9);
+ // Read data
+ // Move to Sending data state
+ error = Cmd18(pSd, nbBlocks, pData, SD_ADDRESS(pSd,address), &status);
+ if (error) {
+ TRACE_ERROR("MTTranState.Cmd18: %d\n\r", error);
+ return error;
+ }
+ if (status & ~(STATUS_READY_FOR_DATA | STATUS_STATE)) {
+ TRACE_ERROR("CMD18.stat: %x\n\r",
+ status & ~(STATUS_READY_FOR_DATA | STATUS_STATE));
+ return SD_ERROR_DRIVER;
+ }
+ }
+ else {
+ // Wait for card to be ready for data transfers
+ do {
+ error = Cmd13(pSd, &status);
+ if (error) {
+ TRACE_ERROR("MoveToTransferState.WR.Cmd13: %d\n\r", error);
+ return error;
+ }
+ }
+ while ((status & STATUS_READY_FOR_DATA) == 0);
+ // Move to Sending data state
+ error = Cmd25(pSd, nbBlocks, pData, SD_ADDRESS(pSd,address), &status);
+ if (error) {
+ TRACE_DEBUG("MoveToTransferState.Cmd25: %d\n\r", error);
+ return error;
+ }
+ if (status & (STATUS_WRITE & ~(STATUS_READY_FOR_DATA | STATUS_STATE))) {
+ TRACE_ERROR("CMD25(0x%x, %d).stat: %x\n\r",
+ SD_ADDRESS(pSd,address), nbBlocks,
+ status & (STATUS_WRITE
+ & ~(STATUS_READY_FOR_DATA | STATUS_STATE)));
+ return SD_ERROR_DRIVER;
+ }
+ }
+
+ if (!error) pSd->preBlock = address + (nbBlocks-1);
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// Switch the bus width of card
+//------------------------------------------------------------------------------
+
+//------------------------------------------------------------------------------
+/// Switch the HS mode of card
+/// \param pSd Pointer to SdCard instance.
+/// \param hsEnable 1 to enable, 0 to disable.
+//------------------------------------------------------------------------------
+static unsigned char SdMmcSwitchHsMode(SdCard *pSd, unsigned char hsEnable)
+{
+ unsigned int status;
+ unsigned char error = SD_ERROR_DRIVER;
+ if (pSd->mode == hsEnable)
+ return 0;
+ if (pSd->cardType >= CARD_MMC) {
+ MmcCmd6Arg cmd6Arg;
+ cmd6Arg.access = 0x3;
+ cmd6Arg.index = SD_EXTCSD_HS_TIMING_INDEX;
+ cmd6Arg.value = hsEnable ? SD_EXTCSD_HS_TIMING_ENABLE
+ : SD_EXTCSD_HS_TIMING_DISABLE;
+ cmd6Arg.cmdSet = 0;
+ error = Cmd6(pSd, &cmd6Arg, 0, &status);
+ if (error) {
+ TRACE_ERROR("MMC SwitchHs.Cmd6: %d\n\r", error);
+ }
+ else if (status & STATUS_SWITCH_ERROR) {
+ TRACE_WARNING("MMC HS SW Fail\n\r");
+ error = SD_ERROR_DRIVER;
+ }
+ else {
+ TRACE_WARNING_WP("-I- MMC HS %d\n\r", hsEnable);
+ pSd->mode = hsEnable;
+ }
+ }
+ else if (pSd->cardType >= CARD_SD) {
+ SdCmd6Arg cmd6Arg;
+ unsigned int switchStatus[512/32];
+ cmd6Arg.mode = 1;
+ cmd6Arg.reserved = 0;
+ cmd6Arg.reserveFG6 = 0xF;
+ cmd6Arg.reserveFG5 = 0xF;
+ cmd6Arg.reserveFG4 = 0xF;
+ cmd6Arg.reserveFG3 = 0xF;
+ cmd6Arg.command = 0;
+ cmd6Arg.accessMode = 1;
+ error = Cmd6(pSd,
+ &cmd6Arg,
+ switchStatus,
+ &status);
+ #if 0
+ unsigned int i;
+ printf("SD Switch status:");
+ for(i = 0; i < 512 / 8; i ++) {
+ if ((i % 8) == 0) printf("\n\r[%3d]", i);
+ printf(" %02x", ((char*)switchStatus)[i]);
+ }
+ printf("\n\r");
+ printf(" _FG1_INFO %x\n\r",
+ SD_SW_STAT_FUN_GRP1_INFO(switchStatus));
+ printf(" _FG1_RC %x\n\r",
+ SD_SW_STAT_FUN_GRP1_RC(switchStatus));
+ printf(" _FG1_BUSY %x\n\r",
+ SD_SW_STAT_FUN_GRP1_BUSY(switchStatus));
+ printf(" _FG1_DS_V %x\n\r",
+ SD_SW_STAT_DATA_STRUCT_VER(switchStatus));
+ #endif
+ if (error) {
+ TRACE_ERROR("SD SwitchHs.Cmd6: %d\n\r", error);
+ }
+ else if (status & STATUS_SWITCH_ERROR) {
+ TRACE_WARNING("SD HS SW Fail\n\r");
+ error = SD_ERROR_DRIVER;
+ }
+ else if (SD_SW_STAT_FUN_GRP1_RC(switchStatus)
+ == SD_SW_STAT_FUN_GRP_RC_ERROR) {
+ TRACE_ERROR_WP("-I- SD HS Not Supported\n\r");
+ error = SD_ERROR_DRIVER;
+ }
+ else if (SD_SW_STAT_FUN_GRP1_BUSY(switchStatus)) {
+ TRACE_WARNING("SD HS Busy\n\r");
+ error = SD_ERROR_DRIVER;
+ }
+ else {
+ TRACE_WARNING_WP("-I- SD HS %d\n\r", hsEnable);
+ pSd->mode = hsEnable;
+ }
+ }
+
+ return error;
+}
+
+#if defined(MCI2_INTERFACE) && defined(AT91C_MCI_SPCMD_BOOTREQ)
+//------------------------------------------------------------------------------
+/// Process a list of SWITCH command
+/// \param pSd Pointer to SdCard instance.
+/// \param pArgList Argument list.
+/// \param listSize Number of arguments listed.
+/// \return 0, or error code and argument index.
+//------------------------------------------------------------------------------
+static unsigned short MmcSwitchSettings(SdCard *pSd,
+ const MmcCmd6Arg * pArgList,
+ unsigned int listSize,
+ unsigned int * pErrSta)
+{
+ unsigned int i, status;
+ unsigned char error;
+
+ SANITY_CHECK(pSd);
+ SANITY_CHECK(pArgList);
+
+ for (i = 0; i < listSize; i ++) {
+ error = Cmd6(pSd, &pArgList[i], 0, &status);
+ if (pErrSta) *pErrSta = status;
+ if (error) {
+ return (error | (i << 8));
+ }
+ if (status & ~(STATUS_STATE | STATUS_READY_FOR_DATA)) {
+ TRACE_WARNING("Error in SWITCH.%d, 0x%x\n\r",
+ pArgList[i].index, status);
+ }
+ else {
+ TRACE_INFO("SWITCH.%d: 0x%x\n\r",
+ pArgList[i].index, status);
+ }
+ }
+ return 0;
+}
+#endif
+
+//------------------------------------------------------------------------------
+/// Switch card state between STBY and TRAN
+/// \param pSd Pointer to a SD card driver instance.
+/// \param address Card address to TRAN, 0 to STBY
+/// \param check Whether to check the state
+//------------------------------------------------------------------------------
+static unsigned char MmcSelectCard(SdCard *pSd,
+ unsigned short address,
+ unsigned char check)
+{
+ unsigned char error;
+ unsigned int status;
+ unsigned int targetState = address ? STATUS_TRAN : STATUS_STBY;
+ unsigned int srcState = address ? STATUS_STBY : STATUS_TRAN;
+ if (pSd->cardType == CARD_SDIO) check = 0;
+
+ // At this stage the Initialization and identification process is achieved
+ // The SD card is supposed to be in Stand-by State
+ while(check) {
+ error = Cmd13(pSd, &status);
+ if (error) {
+ TRACE_ERROR("MmcSelectCard.Cmd13 (%d)\n\r", error);
+ return error;
+ }
+ if ((status & STATUS_READY_FOR_DATA)) {
+ unsigned int currState = status & STATUS_STATE;
+ if (currState == targetState) return 0;
+ if (currState != srcState) {
+ TRACE_ERROR("MmcSelectCard, wrong state %x\n\r", currState);
+ return SD_ERROR_DRIVER;
+ }
+ break;
+ }
+ }
+
+ // witch to TRAN mode to Select the current SD/MMC
+ // so that SD ACMD6 can process or EXT_CSD can read.
+ error = Cmd7(pSd, address);
+ if (error == SD_ERROR_NOT_INITIALIZED && address == 0) {}
+ else if (error) {
+ TRACE_ERROR("MmcSelectCard.Cmd7 (%d)\n\r", error);
+ }
+
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// Get EXT_CSD information
+/// \param pSd Pointer to a SD card driver instance.
+//------------------------------------------------------------------------------
+static unsigned char MmcGetExtInformation(SdCard *pSd)
+{
+ unsigned char error;
+ unsigned int i;
+
+ // CSD 1.2 or Higher version
+ if(SD_CSD_STRUCTURE(pSd) >= 2) {
+
+ /* Clear EXT_CSD data */
+ for (i = 0;i < 512/4; i ++) pSd->extData[i] = 0;
+ error = Cmd8(pSd, 0, pSd->extData);
+ if (error) {
+ TRACE_ERROR("MmcGetExt.Cmd8: %d\n\r", error);
+ }
+ }
+ return 0;
+}
+
+//------------------------------------------------------------------------------
+/// Get SCR and SD Status information
+/// \param pSd Pointer to a SD card driver instance.
+//------------------------------------------------------------------------------
+static unsigned char SdGetExtInformation(SdCard *pSd)
+{
+ unsigned char error;
+
+ // Reset data (64 + 512 bits, 8 + 64 bytes)
+ // memset(pSd->extData, 0x00, 512);
+
+ // SD Status
+ if (pSd->optCmdBitMap & SD_ACMD13_SUPPORT) {
+ error = Acmd13(pSd, &pSd->extData[SD_EXT_OFFSET_SD_STAT]);
+ if (error) {
+ TRACE_ERROR("SdGetExt.Acmd13: %d\n\r", error);
+ pSd->optCmdBitMap &= ~SD_ACMD13_SUPPORT;
+ }
+ }
+
+ // SD SCR
+ error = Acmd51(pSd, &pSd->extData[SD_EXT_OFFSET_SD_SCR]);
+ if (error) {
+ TRACE_ERROR("SdGetExt.Acmd51: %d\n\r", error);
+ }
+
+ return 0;
+}
+
+//------------------------------------------------------------------------------
+/// Update SD/MMC information.
+/// Update CSD for card speed switch.
+/// Update ExtDATA for any card function switch.
+/// \param pSd Pointer to a SD card driver instance.
+/// \return error code when update CSD error.
+//------------------------------------------------------------------------------
+static unsigned char SdMmcUpdateInformation(SdCard *pSd,
+ unsigned char csd,
+ unsigned char extData)
+{
+ unsigned char error;
+
+ // Update CSD for new TRAN_SPEED value
+ if (csd) {
+ MmcSelectCard(pSd, 0, 1);
+ Delay(800);
+ error = Cmd9(pSd);
+ if (error ) {
+ TRACE_ERROR("SdMmcUpdateInfo.Cmd9 (%d)\n\r", error);
+ return error;
+ }
+ error = MmcSelectCard(pSd, pSd->cardAddress, 1);
+ }
+ if (pSd->cardType >= CARD_MMC) MmcGetExtInformation(pSd);
+ else if (pSd->cardType >= CARD_SD) SdGetExtInformation(pSd);
+ GetTransSpeedValue(pSd);
+
+ return 0;
+}
+
+#if MCI_SDIO_ENABLE
+//------------------------------------------------------------------------------
+/// Find ManfID, Func0 tuple.
+//------------------------------------------------------------------------------
+static unsigned char SdioFindTuples(SdCard * pSd,
+ unsigned int address, unsigned int size,
+ unsigned int *pAddrManfID,
+ unsigned int *pAddrFunc0)
+{
+ unsigned char error, tmp[3];
+ unsigned int addr = address;
+ unsigned char nbFound = 0;
+ for (;;) {
+ error = SDIO_ReadDirect(pSd, 0, addr, tmp, 3);
+ if (error)
+ return error;
+ // ManfID
+ if (tmp[0] == CISTPL_MANFID) {
+ if (pAddrManfID) *pAddrManfID = addr;
+ nbFound ++;
+ }
+ // Func0
+ if (tmp[0] == CISTPL_FUNCE && tmp[2] == 0x00) {
+ if (pAddrFunc0) *pAddrFunc0 = addr;
+ nbFound ++;
+ }
+ // END
+ if (tmp[0] == CISTPL_END) break;
+
+ // All found
+ if (nbFound >= 2) break;
+ // Not tuple?
+ if (tmp[1] == 0) break;
+
+ // Next address
+ addr += (tmp[1] + 2);
+ if (addr > (address + size))
+ break;
+ }
+ return 0;
+}
+#endif
+
+//------------------------------------------------------------------------------
+// Global functions
+//------------------------------------------------------------------------------
+
+#if MCI_SDIO_ENABLE
+//------------------------------------------------------------------------------
+/// Read at least one byte from SDIO card, using RW_DIRECT command.
+/// \param pSd Pointer to SdCard instance.
+/// \param funNb Function number.
+/// \param address First byte address of data in SDIO card.
+/// \param pBytes Pointer to data buffer.
+/// \param size Buffer size.
+//------------------------------------------------------------------------------
+unsigned char SDIO_ReadDirect(SdCard *pSd,
+ unsigned char funNb,
+ unsigned int address,
+ unsigned char *pBytes,
+ unsigned int size)
+{
+ unsigned char error;
+ unsigned int status;
+ if (pSd->cardType < CARD_SDIO) {
+ return SD_ERROR_NOT_SUPPORT;
+ }
+ if (size == 0)
+ return SD_ERROR_DRIVER;
+
+ while(size --) {
+ status = 0;
+ error = Cmd52(pSd, funNb, 0, 0, address ++, &status);
+ if (pBytes) *pBytes ++ = (unsigned char)status;
+ if (error) {
+ TRACE_ERROR("SDIO_ReadDirect.Cmd52: %d, %x\n\r", error, status);
+ return SD_ERROR_DRIVER;
+ }
+ }
+
+ return 0;
+}
+
+//------------------------------------------------------------------------------
+/// Write one byte to SDIO card, using RW_DIRECT command.
+/// \param pSd Pointer to SdCard instance.
+/// \param funNb Function number.
+/// \param address First byte address of data in SDIO card.
+/// \param pBytes Pointer to data buffer.
+/// \param size Buffer size.
+//------------------------------------------------------------------------------
+unsigned char SDIO_WriteDirect(SdCard *pSd,
+ unsigned char funNb,
+ unsigned int address,
+ unsigned char byte)
+{
+ if (pSd->cardType < CARD_SDIO) {
+ return SD_ERROR_NOT_SUPPORT;
+ }
+ unsigned char error;
+ unsigned int status;
+ status = byte;
+ error = Cmd52(pSd, funNb, 1, 0, address, &status);
+ if (error) {
+ TRACE_ERROR("SDIO_ReadDirect.Cmd52: %d, %x\n\r", error, status);
+ return SD_ERROR_DRIVER;
+ }
+
+ return 0;
+}
+
+//------------------------------------------------------------------------------
+/// Read byte by byte from SDIO card, using RW_EXT command.
+/// \param pSd Pointer to SdCard instance.
+/// \param funNb Function number.
+/// \param address First byte address of data in SDIO card.
+/// \param isFixedAddr Address not increased.
+/// \param pBytes Pointer to data buffer.
+/// \param size Buffer size.
+//------------------------------------------------------------------------------
+unsigned char SDIO_ReadBytes(SdCard *pSd,
+ unsigned char funNb,
+ unsigned int address,
+ unsigned char isFixedAddr,
+ unsigned char *pBytes,
+ unsigned int size)
+{
+ unsigned char error;
+ unsigned int status;
+ if (pSd->cardType < CARD_SDIO) {
+ return SD_ERROR_NOT_SUPPORT;
+ }
+
+ if (size == 0)
+ return SD_ERROR_DRIVER;
+
+ error = Cmd53(pSd, funNb,
+ 0, 0, !isFixedAddr,
+ address, pBytes, size, &status);
+ if (error || (status & STATUS_SDIO_CMD52)) {
+ TRACE_ERROR("SDIO_ReadBytes.Cmd53: %d, %x\n\r", error, status);
+ return SD_ERROR_DRIVER;
+ }
+
+ return 0;
+}
+
+//------------------------------------------------------------------------------
+/// Write byte by byte to SDIO card, using RW_EXT command.
+/// \param pSd Pointer to SdCard instance.
+/// \param funNb Function number.
+/// \param address First byte address of data in SDIO card.
+/// \param isFixedAddr Address not increased.
+/// \param pBytes Pointer to data buffer.
+/// \param size Buffer size.
+//------------------------------------------------------------------------------
+unsigned char SDIO_WriteBytes(SdCard *pSd,
+ unsigned char funNb,
+ unsigned int address,
+ unsigned char isFixedAddr,
+ unsigned char *pBytes,
+ unsigned int size)
+{
+ unsigned char error;
+ unsigned int status;
+ if (pSd->cardType < CARD_SDIO) {
+ return SD_ERROR_NOT_SUPPORT;
+ }
+ if (size == 0)
+ return SD_ERROR_DRIVER;
+
+ error = Cmd53(pSd, funNb,
+ 1, 0, !isFixedAddr,
+ address, pBytes, size, &status);
+ if (error || (status & STATUS_SDIO_CMD52)) {
+ TRACE_ERROR("SDIO_ReadBytes.Cmd53: %d, %x\n\r", error, status);
+ return SD_ERROR_DRIVER;
+ }
+
+ return 0;
+}
+#endif
+
+//------------------------------------------------------------------------------
+/// Read Block of data in a buffer pointed by pData. The buffer size must be at
+/// least 512 byte long. This function checks the SD card status register and
+/// address the card if required before sending the read command.
+/// Returns 0 if successful; otherwise returns an code describing the error.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param address Address of the block to read.
+/// \param pData Data buffer whose size is at least the block size, it can
+/// be 1,2 or 4-bytes aligned when used with DMA.
+/// \param length Number of blocks to be read.
+/// \param pCallback Pointer to callback function that invoked when read done.
+/// 0 to start a blocked read.
+/// \param pArgs Pointer to callback function arguments.
+//------------------------------------------------------------------------------
+unsigned char SD_Read(SdCard *pSd,
+ unsigned int address,
+ void *pData,
+ unsigned short length,
+ SdCallback pCallback,
+ void *pArgs)
+{
+ unsigned char error;
+
+ // If callback is defined, performe none blocked reading
+ if (pCallback) {
+ if (MCI_IsTxComplete((Mci *)pSd) == 0) {
+ return SD_ERROR_BUSY;
+ }
+ }
+
+ if ( pSd->state != SD_STATE_READ
+ || pSd->preBlock + 1 != address ) {
+ // Start infinite block reading
+ error = MoveToTransferState(pSd, address, 0, 0, 1);
+ }
+ else error = 0;
+ if (!error) {
+ pSd->state = SD_STATE_READ;
+ pSd->preBlock = address + (length - 1);
+ error = ContinuousRead(pSd,
+ length,
+ pData,
+ pCallback, pArgs);
+ }
+ TRACE_DEBUG("SDrd(%u,%u):%u\n\r", address, length, error);
+
+ return 0;
+}
+
+//------------------------------------------------------------------------------
+/// Write Block of data in a buffer pointed by pData. The buffer size must be at
+/// least 512 byte long. This function checks the SD card status register and
+/// address the card if required before sending the read command.
+/// Returns 0 if successful; otherwise returns an code describing the error.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param address Address of the block to read.
+/// \param pData Data buffer whose size is at least the block size, it can
+/// be 1,2 or 4-bytes aligned when used with DMA.
+/// \param length Number of blocks to be read.
+/// \param pCallback Pointer to callback function that invoked when read done.
+/// 0 to start a blocked read.
+/// \param pArgs Pointer to callback function arguments.
+//------------------------------------------------------------------------------
+unsigned char SD_Write(SdCard *pSd,
+ unsigned int address,
+ void *pData,
+ unsigned short length,
+ SdCallback pCallback,
+ void *pArgs)
+{
+ unsigned char error;
+ // If callback is defined, performe none blocked writing
+ if (pCallback) {
+ if (MCI_IsTxComplete((Mci *)pSd) == 0) {
+ return SD_ERROR_BUSY;
+ }
+ }
+ if ( pSd->state != SD_STATE_WRITE
+ || pSd->preBlock + 1 != address ) {
+ // Start infinite block writing
+ error = MoveToTransferState(pSd, address, 0, 0, 0);
+ }
+ else error = 0;
+ if (!error) {
+ pSd->state = SD_STATE_WRITE;
+ error = ContinuousWrite(pSd,
+ length,
+ pData,
+ pCallback, pArgs);
+ pSd->preBlock = address + (length - 1);
+ }
+ TRACE_DEBUG("SDwr(%u,%u):%u\n\r", address, length, error);
+
+ return 0;
+}
+
+//------------------------------------------------------------------------------
+/// Read Block of data in a buffer pointed by pData. The buffer size must be at
+/// least 512 byte long. This function checks the SD card status register and
+/// address the card if required before sending the read command.
+/// Returns 0 if successful; otherwise returns an code describing the error.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param address Address of the block to read.
+/// \param nbBlocks Number of blocks to be read.
+/// \param pData Data buffer whose size is at least the block size, it can
+/// be 1,2 or 4-bytes aligned when used with DMA.
+//------------------------------------------------------------------------------
+unsigned char SD_ReadBlock(SdCard *pSd,
+ unsigned int address,
+ unsigned short nbBlocks,
+ unsigned char *pData)
+{
+ unsigned char error = 0;
+
+ SANITY_CHECK(pSd);
+ SANITY_CHECK(pData);
+ SANITY_CHECK(nbBlocks);
+
+ TRACE_DEBUG("ReadBlk(%d,%d)\n\r", address, nbBlocks);
+#if defined(SINGLE_READ)
+ while(nbBlocks --) {
+ error = PerformSingleTransfer(pSd, address, pData, 1);
+ if (error)
+ break;
+ // SDHC
+ if (pSd->totalSize == 0xFFFFFFFF) {
+ address += 1;
+ pData = &pData[512];
+ }
+ else {
+ address += 1;
+ pData = &pData[512];
+ }
+ }
+ return error;
+#endif
+#if !defined(MCI2_INTERFACE)
+ #if !defined(AT91C_MCI_RDPROOF)
+ error = MoveToTransferState(pSd, address, nbBlocks, pData, 1);
+ pSd->state = SD_STATE_READ;
+ #else
+ if((pSd->state == SD_STATE_READ)
+ && ((pSd->preBlock + 1) == address)) {
+
+ #if defined(at91rm9200)
+ error = Cmd12(pSd, 0);
+ if (error) {
+ return error;
+ }
+ #else
+ TRACE_DEBUG("SD_ReadBlock:ContinuousRead\n\r");
+ error = ContinuousRead(pSd,
+ nbBlocks,
+ pData,
+ 0, 0);
+ pSd->preBlock = address + (nbBlocks-1);
+ #endif
+ }
+ else {
+ error = MoveToTransferState(pSd, address, nbBlocks, pData, 1);
+ pSd->state = SD_STATE_READ;
+ }
+ #endif
+#else
+ if ( pSd->state != SD_STATE_READ
+ || pSd->preBlock + 1 != address ) {
+ // Start infinite block reading
+ error = MoveToTransferState(pSd, address, 0, 0, 1);
+ }
+ if (!error) {
+ pSd->state = SD_STATE_READ;
+ error = ContinuousRead(pSd,
+ nbBlocks,
+ pData,
+ 0, 0);
+ if (!error) pSd->preBlock = address + (nbBlocks - 1);
+ }
+#endif
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// Write Block of data pointed by pData. The buffer size must be at
+/// least 512 byte long. This function checks the SD card status register and
+/// address the card if required before sending the read command.
+/// Returns 0 if successful; otherwise returns an SD_ERROR code.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param address Address of block to write.
+/// \param nbBlocks Number of blocks to be read
+/// \param pData Data buffer whose size is at least the block size, it can
+/// be 1,2 or 4-bytes aligned when used with DMA.
+//------------------------------------------------------------------------------
+unsigned char SD_WriteBlock(SdCard *pSd,
+ unsigned int address,
+ unsigned short nbBlocks,
+ const unsigned char *pData)
+{
+ unsigned char error = 0;
+
+ SANITY_CHECK(pSd);
+ SANITY_CHECK(pData);
+ SANITY_CHECK(nbBlocks);
+
+ TRACE_DEBUG("WriteBlk(%d,%d)\n\r", address, nbBlocks);
+
+#if defined(SINGLE_WRITE)
+ unsigned char *pB = (unsigned char*)pData;
+ while(nbBlocks --) {
+ error = PerformSingleTransfer(pSd, address, pB, 0);
+ if (error)
+ break;
+ // SDHC
+ if (pSd->totalSize == 0xFFFFFFFF) {
+ address += 1;
+ pB = &pB[512];
+ }
+ else {
+ address += 1;
+ pB = &pB[512];
+ }
+ }
+ return error;
+#endif
+#if !defined(MCI2_INTERFACE)
+ #if !defined(AT91C_MCI_WRPROOF)
+ error = MoveToTransferState(pSd, address, nbBlocks,
+ (unsigned char *)pData, 0);
+ pSd->state = SD_STATE_WRITE;
+ #else
+ if((pSd->state == SD_STATE_WRITE)
+ && ((pSd->preBlock + 1) == address)) {
+
+ TRACE_DEBUG("SD_WriteBlock:ContinuousWrite\n\r");
+ error = ContinuousWrite(pSd,
+ nbBlocks,
+ pData,
+ 0, 0);
+ pSd->preBlock = address + (nbBlocks-1);
+ }
+ else {
+
+ //TRACE_FATAL("SD_WriteBlock:MoveToTransferState\n\r");
+ error = MoveToTransferState(pSd, address, nbBlocks,
+ (unsigned char *)pData, 0);
+ pSd->state = SD_STATE_WRITE;
+ }
+ #endif
+#else
+ if ( pSd->state != SD_STATE_WRITE
+ || pSd->preBlock + 1 != address ) {
+ // Start infinite block writing
+ error = MoveToTransferState(pSd, address, 0, 0, 0);
+ }
+ if (!error) {
+ pSd->state = SD_STATE_WRITE;
+ error = ContinuousWrite(pSd,
+ nbBlocks,
+ pData,
+ 0, 0);
+ if (!error) pSd->preBlock = address + (nbBlocks - 1);
+ }
+#endif
+
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// Run the SDcard SD/MMC/SDIO Mode initialization sequence.
+/// This function resets both IO and memory controller, runs the initialisation
+/// procedure and the identification process. Then it leaves the card in ready
+/// state. The following command must check the card type and continue to put
+/// the card into tran(for memory card) or cmd(for io card) state for data
+/// exchange.
+/// Returns 0 if successful; otherwise returns an SD_ERROR code.
+/// \param pSd Pointer to a SD card driver instance.
+//------------------------------------------------------------------------------
+static unsigned char SdMmcIdentify(SdCard *pSd)
+{
+ unsigned char mem = 0, io = 0, f8 = 0, mp = 1, ccs = 0;
+ unsigned char error = 0;
+#if MCI_SDIO_ENABLE
+ unsigned int status;
+#endif
+
+ // Reset HC to default HS and BusMode
+ MCI_EnableHsMode(pSd->pSdDriver, 0);
+ MCI_SetBusWidth(pSd->pSdDriver, MCI_SDCBUS_1BIT);
+
+#if MCI_SDIO_ENABLE
+ // Reset SDIO
+ // CMD52, write 1 to RES bit in the CCCR (bit 3 of register 6)
+ status = (0x1 << 3);
+ error = Cmd52(pSd, 0, 1, 0, 6, &status);
+ if (!error && ((status & STATUS_SDIO_CMD52) == 0)) {}
+ else if (error == MCI_STATUS_NORESPONSE) {}
+ else {
+ TRACE_DEBUG("SdMmcIdentify.Cmd52 fail: %d, %x\n\r", error, status);
+ }
+#endif
+
+ // Reset MEM
+ error = SwReset(pSd, 1);
+ if (error) {
+ TRACE_DEBUG("SdMmcIdentify.SwReset: %d\n\r", error)
+ }
+
+ // CMD8 is newly added in the Physical Layer Specification Version 2.00 to
+ // support multiple voltage ranges and used to check whether the card
+ // supports supplied voltage. The version 2.00 host shall issue CMD8 and
+ // verify voltage before card initialization.
+ // The host that does not support CMD8 shall supply high voltage range...
+ error = Cmd8(pSd, 1, (void*)1);
+ if (error == 0) {
+ f8 = 1;
+ }
+ else if (error != SD_ERROR_NORESPONSE) {
+ TRACE_ERROR("SdMmcIdentify.Cmd8: %d\n\r", error);
+ return SD_ERROR_DRIVER;
+ }
+ else {
+ // Delay after "no response"
+ Delay(800);
+ }
+
+#if MCI_SDIO_ENABLE
+ // CMD5 is added for SDIO OCR check
+ status = 0;
+ error = Cmd5(pSd, &status);
+ if (error) {
+ TRACE_WARNING("SdMmcIdentify.Cmd5: %d\n\r", error);
+ }
+ // SDIO or SD COMBO: FN > 0
+ else if ((status & AT91C_SDIO_NF) > 0) {
+ // Set New Voltage
+ unsigned int cmd5Retries = 10000;
+ do {
+ status &= AT91C_MMC_HOST_VOLTAGE_RANGE;
+ error = Cmd5(pSd, &status);
+ if (status & AT91C_CARD_POWER_UP_BUSY)
+ break;
+ } while(!error && cmd5Retries --);
+ if (error) {
+ TRACE_ERROR("SdMmcIdentify.Cmd5 V: %d\n\r", error);
+ return SD_ERROR_DRIVER;
+ }
+ TRACE_INFO("SDIO\n\r");
+ io = 1;
+ // SDIO only?
+ if ((status & AT91C_SDIO_MP) == 0) mp = 0;
+ }
+#endif
+ // SD or MMC or COMBO: mp is 1
+ if (mp) {
+ // Try SD memory initialize
+ error = Acmd41(pSd, f8, &ccs);
+ if (error) {
+ unsigned int cmd1Retries = 10000;
+ TRACE_DEBUG("SdMmcIdentify.Acmd41: %d, try MMC\n\r", error);
+
+ // Try MMC initialize
+ error = SwReset(pSd, 10);
+ if (error) {
+ TRACE_ERROR("SdMmcIdentify.Mmc.SwReset: %d\n\r", error);
+ return SD_ERROR_DRIVER;
+ }
+ // - Set Voltage
+ do {
+ error = Cmd1(pSd, 1, &ccs);
+ }
+ while ((error) && (cmd1Retries-- > 0));
+ if (error) {
+ TRACE_ERROR("SdMmcIdentify.Cmd1: %d\n\r", error);
+ return SD_ERROR_DRIVER;
+ }
+ else if (ccs) {
+ pSd->cardType = CARD_MMCHD;
+ }
+ else {
+ pSd->cardType = CARD_MMC;
+ }
+
+ // MMC Identified OK
+ return 0;
+ }
+ else if (ccs) {
+ TRACE_INFO("SDHC MEM\n\r");
+ }
+ else {
+ TRACE_INFO("SD MEM\n\r");
+ }
+ mem = 1;
+ }
+
+ // SD(IO)+MEM ?
+ if (!mem) {
+ // SDIO only
+ if (io) {
+ pSd->cardType = CARD_SDIO;
+ return 0;
+ }
+ }
+ // SD COMBO, continue with memory initialize
+ else if (io) {
+ if (ccs) pSd->cardType = CARD_SDHCCOMBO;
+ else pSd->cardType = CARD_SDCOMBO;
+ }
+ // SD(HC), continue with memory initialize
+ else {
+ if (ccs) pSd->cardType = CARD_SDHC;
+ else pSd->cardType = CARD_SD;
+ }
+ return 0;
+}
+
+//------------------------------------------------------------------------------
+/// Run the SDcard SD Mode enumeration sequence. This function runs after the
+/// initialisation procedure and the identification process. It sets the
+/// SD card in transfer state to set the block length and the bus width.
+/// Returns 0 if successful; otherwise returns an SD_ERROR code.
+/// \param pSd Pointer to a SD card driver instance.
+//------------------------------------------------------------------------------
+static unsigned char SdMmcEnum(SdCard *pSd)
+{
+ unsigned char mem = 0, io = 0;
+ unsigned int status;
+ unsigned short error;
+ unsigned char isHsSupport = 0;
+ unsigned char updateInformation = 0;
+
+ if (pSd->cardType & CARD_TYPE_bmSDMMC) mem = 1;
+ if (pSd->cardType & CARD_TYPE_bmSDIO) io = 1;
+
+ // For MEM
+ // The host then issues the command ALL_SEND_CID (CMD2) to the card to get
+ // its unique card identification (CID) number.
+ // Card that is unidentified (i.e. which is in Ready State) sends its CID
+ // number as the response (on the CMD line).
+ if (mem) {
+ error = Cmd2(pSd);
+ if (error) {
+ TRACE_ERROR("SdMmcEnum.Cmd2: %d\n\r", error);
+ return SD_ERROR_DRIVER;
+ }
+ }
+
+ // For SDIO & MEM
+ // Thereafter, the host issues CMD3 (SEND_RELATIVE_ADDR) asks the
+ // card to publish a new relative card address (RCA), which is shorter than
+ // CID and which is used to address the card in the future data transfer
+ // mode. Once the RCA is received the card state changes to the Stand-by
+ // State. At this point, if the host wants to assign another RCA number, it
+ // can ask the card to publish a new number by sending another CMD3 command
+ // to the card. The last published RCA is the actual RCA number of the card.
+ error = Cmd3(pSd);
+ if (error) {
+ TRACE_ERROR("SdMmcInit.Cmd3 %d\n\r", error);
+ return SD_ERROR_DRIVER;
+ }
+
+ // For MEM
+ // SEND_CSD (CMD9) to obtain the Card Specific Data (CSD register),
+ // e.g. block length, card storage capacity, etc...
+ if (mem) {
+ error = Cmd9(pSd);
+ if (error) {
+ TRACE_ERROR("SdMmcInit.Cmd9 %d\n\r", error);
+ return SD_ERROR_DRIVER;
+ }
+ }
+
+ // For SDIO & MEM
+ // Now select the card, to TRAN state
+ error = MmcSelectCard(pSd, pSd->cardAddress, 0);
+ if (error) {
+ TRACE_ERROR("SdMmcInit.Sel %d\n\r", error);
+ return SD_ERROR_DRIVER;
+ }
+ // SDIO only card, enumeration done
+ if (!mem && io) {
+ // Default tranSpeed: 25MHz
+ pSd->transSpeed = 25000000;
+ return 0;
+ }
+
+ // For MEM cards or combo
+ // If the card support EXT_CSD, read it!
+ TRACE_INFO("Card Type %d, CSD_STRUCTURE %d\n\r",
+ pSd->cardType, SD_CSD_STRUCTURE(pSd));
+
+ // Get extended information of the card
+ SdMmcUpdateInformation(pSd, 0, 0);
+
+ // Advanced settings for HD & HS card
+ if (pSd->cardType >= CARD_MMC){
+
+ MmcCmd6Arg cmd6Arg;
+
+ // MMC4 or later
+ if (SD_CSD_SPEC_VERS(pSd) >= 4) {
+
+ unsigned char busWidth, widthMode;
+
+ // Calculate MMC busWidth (limited by slot information)
+ switch (pSd->pSdDriver->mciMode & AT91C_MCI_SCDBUS) {
+ #if defined(AT91C_MCI_SCDBUS_8BITS)
+ case AT91C_MCI_SCDBUS_8BITS:
+ busWidth = 8;
+ widthMode = MCI_SDCBUS_8BIT;
+ break;
+ #endif
+
+ #if defined(AT91C_MCI_SCDBUS_4BITS)
+ case AT91C_MCI_SCDBUS_4BITS:
+ busWidth = 4;
+ widthMode = MCI_SDCBUS_4BIT;
+ break;
+ #endif
+
+ default:
+ busWidth = 1;
+ widthMode = MCI_SDCBUS_1BIT;
+ }
+
+ // Switch to max bus width (4 now)
+ cmd6Arg.access = 0x1;
+ cmd6Arg.index = SD_EXTCSD_BUS_WIDTH_INDEX;
+ cmd6Arg.value = SD_EXTCSD_BUS_WIDTH_4BIT;
+ cmd6Arg.cmdSet = 0;
+ error = Cmd6(pSd, &cmd6Arg, 0, &status);
+ if (!error) {
+
+ TRACE_WARNING_WP("-I- MMC %d-BIT BUS\n\r", busWidth);
+ if (status
+ & (STATUS_MMC_SWITCH
+ & ~(STATUS_STATE | STATUS_READY_FOR_DATA))) {
+ printf("-E- Status %x\n\r", status);
+ }
+ else {
+ MCI_SetBusWidth(pSd->pSdDriver, widthMode);
+ updateInformation = 1;
+ }
+ }
+ else {
+ TRACE_WARNING("MMC %d-BIT not supported\n\r", busWidth)
+ }
+ }
+
+ // CARD_TYPE 3
+ if (SD_CSD_STRUCTURE(pSd) >= 2
+ && (SD_EXTCSD_CARD_TYPE(pSd) & 0x2)) {
+
+ #if !defined(OP_BOOTSTRAP_MCI_on)
+ // Switch to HS mode
+ if (gSdmmcAutoHsEnable) {
+ cmd6Arg.access = 0x3;
+ cmd6Arg.index = SD_EXTCSD_HS_TIMING_INDEX;
+ cmd6Arg.value = SD_EXTCSD_HS_TIMING_ENABLE;
+ cmd6Arg.cmdSet = 0;
+ error = Cmd6(pSd, &cmd6Arg, 0, &status);
+ if (error
+ || (status
+ & (STATUS_MMC_SWITCH
+ & ~(STATUS_STATE | STATUS_READY_FOR_DATA)))) {
+ TRACE_WARNING("MMC HS Fail, st %x\n\r", status);
+ }
+ else {
+ MCI_EnableHsMode(pSd->pSdDriver, 1);
+ TRACE_WARNING_WP("-I- MMC HS Enabled\n\r");
+ isHsSupport = 1;
+ updateInformation = 1;
+ }
+ }
+ #endif // end of OP_BOOTSTRAP_MCI_on
+ }
+ }
+ else if (pSd->cardType >= CARD_SD) {
+ #if 1
+ // Switch to 4-bits bus width
+ // (All SD Card shall support 1-bit, 4 bitswidth)
+ error = Acmd6(pSd, 4);
+ TRACE_WARNING_WP("-I- SD 4-BITS BUS\n\r");
+ if (error) {
+ TRACE_ERROR("SdMmcInit.12 (%d)\n\r", error);
+ return error;
+ }
+ MCI_SetBusWidth(pSd->pSdDriver, MCI_SDCBUS_4BIT);
+
+ #if !defined(OP_BOOTSTRAP_MCI_on)
+ // SD Spec V1.10 or higher, switch to high-speed mode
+ if (gSdmmcAutoHsEnable) {
+ if (SD_SCR_SD_SPEC(pSd) >= SD_SCR_SD_SPEC_1_10) {
+ SdCmd6Arg cmd6Arg;
+ unsigned int switchStatus[512/32];
+ cmd6Arg.mode = 1;
+ cmd6Arg.reserved = 0;
+ cmd6Arg.reserveFG6 = 0xF;
+ cmd6Arg.reserveFG5 = 0xF;
+ cmd6Arg.reserveFG4 = 0xF;
+ cmd6Arg.reserveFG3 = 0xF;
+ cmd6Arg.command = 0;
+ cmd6Arg.accessMode = 1;
+ error = Cmd6(pSd,
+ &cmd6Arg,
+ switchStatus,
+ &status);
+ #if 0
+ unsigned int i;
+ printf("SD Switch status:");
+ for(i = 0; i < 512 / 8; i ++) {
+ if ((i % 8) == 0) printf("\n\r[%3d]", i);
+ printf(" %02x", ((char*)switchStatus)[i]);
+ }
+ printf("\n\r");
+ printf(" _FG1_INFO %x\n\r",
+ SD_SW_STAT_FUN_GRP1_INFO(switchStatus));
+ printf(" _FG1_RC %x\n\r",
+ SD_SW_STAT_FUN_GRP1_RC(switchStatus));
+ printf(" _FG1_BUSY %x\n\r",
+ SD_SW_STAT_FUN_GRP1_BUSY(switchStatus));
+ printf(" _FG1_DS_V %x\n\r",
+ SD_SW_STAT_DATA_STRUCT_VER(switchStatus));
+ #endif
+ if (error || (status & STATUS_SWITCH_ERROR)) {
+ TRACE_WARNING("SD HS Fail\n\r");
+ }
+ else if (SD_SW_STAT_FUN_GRP1_RC(switchStatus)
+ == SD_SW_STAT_FUN_GRP_RC_ERROR) {
+ TRACE_ERROR_WP("-I- SD HS Not Supported\n\r");
+ }
+ else if (SD_SW_STAT_FUN_GRP1_BUSY(switchStatus)) {
+ TRACE_WARNING("SD HS Busy\n\r")
+ }
+ else {
+ MCI_EnableHsMode(pSd->pSdDriver, 1);
+ TRACE_WARNING_WP("-I- SD HS Enable\n\r");
+ isHsSupport = 1;
+ }
+ }
+ }
+ #endif
+ // Update
+ updateInformation = 1;
+ #endif
+ }
+
+ if (updateInformation) {
+
+ SdMmcUpdateInformation(pSd, isHsSupport, 1);
+ }
+ return 0;
+}
+
+//------------------------------------------------------------------------------
+/// Run the SDcard initialization sequence. This function runs the
+/// initialisation procedure and the identification process, then it sets the
+/// SD card in transfer state to set the block length and the bus width.
+/// Returns 0 if successful; otherwise returns an SD_ERROR code.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param pSdDriver Pointer to SD driver already initialized.
+//------------------------------------------------------------------------------
+unsigned char SD_Init(SdCard *pSd, SdDriver *pSdDriver)
+{
+ unsigned char error;
+
+ //TRACE_DEBUG("SD_Init()\n\r");
+
+ // Initialize SdCard structure
+ pSd->pSdDriver = pSdDriver;
+ pSd->cardAddress = 0;
+ pSd->preBlock = 0xffffffff;
+ pSd->state = SD_STATE_INIT;
+ pSd->cardType = CARD_UNKNOWN;
+ pSd->optCmdBitMap = 0xFFFFFFFF;
+ pSd->mode = 0;
+ ResetCommand(&pSd->command);
+
+ // Initialization delay: The maximum of 1 msec, 74 clock cycles and supply
+ // ramp up time. Supply ramp up time provides the time that the power is
+ // built up to the operating level (the bus master supply voltage) and the
+ // time to wait until the SD card can accept the first command.
+
+ // Power On Init Special Command
+ //TRACE_DEBUG("Pon()\n\r");
+ error = Pon(pSd);
+ if (error) {
+ TRACE_ERROR("SD_Init.1 (%d)\n\r", error);
+ return error;
+ }
+ // After power-on or CMD0, all cards?CMD lines are in input mode, waiting
+ // for start bit of the next command.
+ // The cards are initialized with a default relative card address
+ // (RCA=0x0000) and with a default driver stage register setting
+ // (lowest speed, highest driving current capability).
+ error = SdMmcIdentify(pSd);
+ if (error) {
+ TRACE_ERROR("SD_Init.Identify\n\r");
+ return error;
+ }
+ error = SdMmcEnum(pSd);
+ if (error) {
+ TRACE_ERROR("SD_Init.Enum\n\r");
+ return error;
+ }
+
+ // In the case of a Standard Capacity SD Memory Card, this command sets the
+ // block length (in bytes) for all following block commands
+ // (read, write, lock).
+ // Default block length is fixed to 512 Bytes.
+ // Set length is valid for memory access commands only if partial block read
+ // operation are allowed in CSD.
+ // In the case of a High Capacity SD Memory Card, block length set by CMD16
+ // command does not affect the memory read and write commands. Always 512
+ // Bytes fixed block length is used. This command is effective for
+ // LOCK_UNLOCK command.
+ // In both cases, if block length is set larger than 512Bytes, the card sets
+ // the BLOCK_LEN_ERROR bit.
+ if (pSd->cardType == CARD_SD) {
+ error = Cmd16(pSd, SD_BLOCK_SIZE);
+ if (error) {
+ pSd->optCmdBitMap &= ~SD_CMD16_SUPPORT;
+ TRACE_INFO("SD_Init.Cmd16 (%d)\n\r", error);
+ TRACE_INFO("Fail to set BLK_LEN, default is 512\n\r");
+ }
+ }
+
+ // Reset status for R/W
+ pSd->state = SD_STATE_READY;
+
+ // If SDIO Card
+ if (pSd->cardType == CARD_SDIO) {
+ pSd->blockNr = 0;
+ pSd->totalSize = 0;
+ }
+ // If MMC Card & get size from EXT_CSD
+ else if (pSd->cardType >= CARD_MMC && SD_CSD_C_SIZE(pSd) == 0xFFF) {
+ pSd->blockNr = SD_EXTCSD_BLOCKNR(pSd);
+ // Block number less than 0x100000000/512
+ if (pSd->blockNr > 0x800000)
+ pSd->totalSize = 0xFFFFFFFF;
+ else
+ pSd->totalSize = SD_EXTCSD_TOTAL_SIZE(pSd);
+ }
+ // If SD CSD v2.0
+ else if(pSd->cardType >= CARD_SD
+ && pSd->cardType < CARD_MMC
+ && SD_CSD_STRUCTURE(pSd) >= 1) {
+ pSd->blockNr = SD_CSD_BLOCKNR_HC(pSd);
+ pSd->totalSize = 0xFFFFFFFF;
+ }
+ // Normal card
+ else {
+ pSd->totalSize = SD_CSD_TOTAL_SIZE(pSd);
+ pSd->blockNr = SD_CSD_BLOCKNR(pSd);
+ }
+
+ if (pSd->cardType == CARD_UNKNOWN) {
+ return SD_ERROR_NOT_INITIALIZED;
+ }
+ else {
+ return 0;
+ }
+}
+
+//------------------------------------------------------------------------------
+/// Stop the SDcard. This function stops all SD operations.
+/// Returns 0 if successful; otherwise returns an SD_ERROR code.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param pSdDriver Pointer to MCI driver already initialized.
+//------------------------------------------------------------------------------
+unsigned char SD_Stop(SdCard *pSd, SdDriver *pSdDriver)
+{
+ unsigned char error;
+ SdCmd *pCommand = &(pSd->command);
+
+ if (pSd == 0 || pSdDriver == 0)
+ return 0;
+
+ if(pCommand->tranType == MCI_CONTINUE_TRANSFER)
+ {
+ TRACE_DEBUG("SD_StopTransmission()\n\r");
+
+ error = Cmd12(pSd, (pSd->state != SD_STATE_WRITE), 0);
+ if(error) {
+ return error;
+ }
+ }
+
+ MCI_Close((Mci *)pSdDriver);
+ return 0;
+}
+
+//------------------------------------------------------------------------------
+/// Switch the SD/MMC card to High-Speed mode.
+/// pSd->transSpeed will change to new speed limit.
+/// Invoke MCI_SetSpeed() and MCI_EnableHsMode() to change MCI timing after.
+/// For SD/MMC card, the speed mode will not change back until another init.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param hsMode 1 to enable HS mode, 0 to disable
+/// 0xFF to return current mode.
+/// \return current mode is hsMode is 0xFF;
+/// error code if hsMode is 0 or 1.
+//------------------------------------------------------------------------------
+unsigned char SD_HighSpeedMode(SdCard *pSd,
+ unsigned char hsMode)
+{
+ unsigned char error = 0;
+
+ if (hsMode == 0xFF)
+ return pSd->mode;
+ if (hsMode == 0) {
+ TRACE_WARNING("Can not switch, do re-init to disable HS mode\n\r");
+ return SD_ERROR_DRIVER;
+ }
+
+ // Quit transfer state
+ error = MoveToTranState(pSd);
+ if (error) {
+ TRACE_ERROR("SD_HighSpeedMode.Tran: %d\n\r", error);
+ return error;
+ }
+
+ if (pSd->mode != hsMode) {
+ error = SdMmcSwitchHsMode(pSd, hsMode);
+ if (error == 0)
+ error = SdMmcUpdateInformation(pSd, 1, 1);
+ }
+ // Reset state for data R/W
+ pSd->state = SD_STATE_READY;
+
+ return error;
+}
+
+unsigned char SD_BusWidth(SdCard *pSd,
+ unsigned char busWidth)
+{
+ return 0;
+}
+
+#if defined(MCI2_INTERFACE) && defined(AT91C_MCI_SPCMD_BOOTREQ)
+//------------------------------------------------------------------------------
+/// Read Block of data in a buffer pointed by pData. The buffer size must be at
+/// least 512 byte long. This function checks the SD card status register and
+/// address the card if required before sending the read command.
+/// Returns 0 if successful; otherwise returns an code describing the error.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param address Address of the block to read.
+/// \param nbBlocks Number of blocks to be read.
+/// \param pData Data buffer whose size is at least the block size.
+//------------------------------------------------------------------------------
+unsigned char MMC_BootRead(SdCard *pSd,
+ unsigned int nbBlocks,
+ unsigned char *pData)
+{
+ unsigned char error;
+ unsigned char bootAck = 0;
+ unsigned char busWidth = MCI_SDCBUS_4BIT;
+
+ SANITY_CHECK(pSd);
+
+ if (pSd->state != SD_STATE_BOOT)
+ return SD_ERROR_DRIVER;
+
+ #if 0
+ switch(SD_EXTCSD_BOOT_BUS_WIDTH(pSd)) {
+ case SD_EXTCSD_BOOT_BUS_1BIT:
+ busWidth = MCI_SDCBUS_1BIT;
+ break;
+ case SD_EXTCSD_BOOT_BUS_8BIT:
+ busWidth = MCI_SDCBUS_8BIT;
+ break;
+ }
+
+ if (SD_EXTCSD_BOOT_CONFIG(pSd) & SD_EXTCSD_BOOT_PARTITION_ACK)
+ bootAck = 1;
+ #endif
+
+ MCI_SetBusWidth((Mci*)pSd->pSdDriver, busWidth);
+ error = BootREQ(pSd, pData, nbBlocks, bootAck);
+ pSd->state = SD_STATE_BOOT;
+
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// In boot operation mode, the master can read boot data from the slave.
+/// By keeping CMD line low after power-on
+/// \param pSd Pointer to a SD card driver instance.
+//------------------------------------------------------------------------------
+unsigned char MMC_BootInit(SdCard *pSd)
+{
+ unsigned char error = 0;
+
+ SANITY_CHECK(pSd);
+
+ error = PonBoot(pSd);
+
+ if (!error) {
+
+ //error = BootREQ(pSd, 0, 0, 0);
+
+ if (!error)
+ pSd->state = SD_STATE_BOOT;
+ else {
+ TRACE_ERROR("MMC_BootInit.BootREQ: %d\n\r", error);
+ }
+ }
+ else {
+ TRACE_ERROR("MMC_BootInit.PonBoot: %d\n\r", error);
+ }
+
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// In boot operation mode, the master can read boot data from the slave.
+/// By sending CMD0 with argument + 0xFFFFFFFA
+/// \param pSd Pointer to a SD card driver instance.
+//------------------------------------------------------------------------------
+unsigned char MMC_BootStart(SdCard *pSd)
+{
+ unsigned char error;
+
+ SANITY_CHECK(pSd);
+
+ if (pSd->state == SD_STATE_BOOT)
+ return 0;
+
+ if (pSd->cardType >= CARD_MMC
+ && SD_CSD_STRUCTURE(pSd) >= 2
+ && SD_CID_BGA(pSd) == 1
+ && SD_EXTCSD_BOOT_INFO(pSd) == 1) {}
+ else
+ return SD_ERROR_NOT_SUPPORT;
+
+ error = Cmd0(pSd, 0xFFFFFFFA);
+ pSd->state = SD_STATE_BOOT;
+
+ return 0;
+}
+
+//------------------------------------------------------------------------------
+/// Terminate the boot operation mode
+/// \param pSd Pointer to a SD card driver instance.
+//------------------------------------------------------------------------------
+unsigned char MMC_BootStop(SdCard *pSd)
+{
+ unsigned char error;
+
+ SANITY_CHECK(pSd);
+
+ if (pSd->state != SD_STATE_BOOT)
+ return 0;
+
+ error = BootEnd(pSd);
+
+ if(!error)
+ pSd->state = SD_STATE_IDLE;
+
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// Setup Boot Settings
+/// \param resetBus Wether bus width is reset to 1-bit after quit boot mode.
+/// \param busWidth The bus width in boot operation.
+/// \param bootPart The partition used for boot operation.
+/// \param accPart The partition to access with normal read/write.
+/// \param bootAck Enable boot acknoledge.
+/// \return 0 or error code.
+//------------------------------------------------------------------------------
+unsigned char MMC_SetupBootMode(SdCard *pSd,
+ unsigned char resetBus,
+ unsigned char busWidth,
+ unsigned char bootPart,
+ unsigned char accPart,
+ unsigned char bootAck)
+{
+ unsigned int status;
+ unsigned short error;
+ const MmcCmd6Arg bootArgs[] = {
+ // BOOT_CONFIG
+ {3, 179, (bootAck << 6)|(bootPart << 3)|(accPart << 0), 0},
+ // BOOT_BUS_WIDTH
+ {3, 177, (busWidth << 2)|(resetBus << 0), 0}
+ };
+
+ SANITY_CHECK(pSd);
+ if ( pSd->cardType >= CARD_MMC
+ && SD_CSD_STRUCTURE(pSd) >= 2
+ && SD_CID_CBS(pSd) == 1) {}
+ else return SD_ERROR_NOT_SUPPORT;
+ //if (MMC_GetBootSizeKB(pSd) == 0) return SD_ERROR_NOT_SUPPORT;
+
+ // Quit transfer state
+ error = MoveToTranState(pSd);
+ if (error) {
+ TRACE_ERROR("MMC_SetupBootMode.Tran: %d\n\r", error);
+ return error;
+ }
+
+ // Setup all boot informations
+ error = MmcSwitchSettings(pSd,
+ bootArgs,
+ sizeof(bootArgs)/sizeof(MmcCmd6Arg),
+ &status);
+ if (error) {
+ TRACE_ERROR("MMC_SetupBootMode.Cmd6: 0x%x, %x\n\r", error, status);
+ return (unsigned char)error;
+ }
+
+ // Update the EXT_CSD
+ #if 1
+ error = Cmd8(pSd, 0, pSd->extData);
+ if (error) {
+ TRACE_ERROR("MMC_SetupBootMode.Cmd8 (%d)\n\r", error);
+ }
+
+ #if 0
+ if ( SD_EXTCSD_BOOT_BUS_WIDTH(pSd) != bootArgs[0].value
+ || SD_EXTCSD_BOOT_CONFIG(pSd) != bootArgs[1].value ) {
+
+ TRACE_ERROR("MMC_SetupBootMode: ExtCSD not changed\n\r");
+
+ #if 1
+ Cmd13(pSd, &status);
+ TRACE_INFO(" CARD status: 0x%x\n\r", status);
+ #endif
+ return SD_ERROR_DRIVER;
+ }
+ #endif
+ #endif
+
+ // Reset state for data R/W
+ pSd->state = SD_STATE_READY;
+
+ return 0;
+}
+
+//------------------------------------------------------------------------------
+/// \return 0 or error code.
+//------------------------------------------------------------------------------
+unsigned char MMC_StopBootMode()
+{
+ return 0;
+}
+#endif
+
+
+//------------------------------------------------------------------------------
+/// \return size of the card in KB
+//------------------------------------------------------------------------------
+unsigned int MMC_GetTotalSizeKB(SdCard *pSd)
+{
+ SANITY_CHECK(pSd);
+
+ if (pSd->totalSize == 0xFFFFFFFF) {
+
+ return pSd->blockNr / 2;
+ }
+
+ return pSd->totalSize / 1024;
+}
+
+
+//------------------------------------------------------------------------------
+/// \return size of boot area if the card support boot operation.
+//------------------------------------------------------------------------------
+unsigned int MMC_GetBootSizeKB(SdCard *pSd)
+{
+ SANITY_CHECK(pSd);
+ if ( pSd->cardType >= CARD_MMC
+ && SD_CSD_STRUCTURE(pSd) >= 2) {
+
+ return SD_EXTCSD_BOOT_SIZE_MULTI(pSd) * 128;
+ }
+ return 0;
+}
+
+#if MCI_SDIO_ENABLE
+//------------------------------------------------------------------------------
+/// Display the content of the CCCR
+//------------------------------------------------------------------------------
+void SDIO_DisplayCardInformation(SdCard *pSd)
+{
+ unsigned int tmp = 0, addrCIS = 0, addrManfID = 0, addrFunc0 = 0;
+ unsigned char* p = (unsigned char*)&tmp;
+ unsigned char buf[8];
+
+ switch(pSd->cardType) {
+ case CARD_SDIO:
+ TRACE_INFO("** SDIO ONLY card\n\r");
+ break;
+ case CARD_SDCOMBO:
+ case CARD_SDHCCOMBO:
+ TRACE_INFO("** SDIO Combo card\n\r");
+ break;
+ default:
+ TRACE_INFO("** NO SDIO, CCCR not supported\n\r");
+ return;
+ }
+ // CCCR
+ TRACE_INFO("====== CCCR ======\n\r");
+ SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_CCCR_REG, p, 1);
+ TRACE_INFO(".SDIO %02X\n\r", (tmp & SDIO_SDIO) >> 4);
+ TRACE_INFO(".CCCR %02X\n\r", (tmp & SDIO_CCCR) >> 0);
+ SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_SD_REV_REG, p, 1);
+ TRACE_INFO(".SD %02X\n\r", (tmp & SDIO_SD) >> 0);
+ SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_IOE_REG, p, 1);
+ TRACE_INFO(".IOE %02X\n\r", (tmp & SDIO_IOE) >> 0);
+ SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_IOR_REG, p, 1);
+ TRACE_INFO(".IOR %02X\n\r", (tmp & SDIO_IOR) >> 0);
+ SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_IEN_REG, p, 1);
+ TRACE_INFO(".IEN %02X\n\r", (tmp & SDIO_IEN) >> 0);
+ SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_INT_REG, p, 1);
+ TRACE_INFO(".INT %02X\n\r", (tmp & SDIO_INT) >> 0);
+ SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_BUS_CTRL_REG, p, 1);
+ TRACE_INFO(".CD %x\n\r", (tmp & SDIO_CD) >> 7);
+ TRACE_INFO(".SCSI %x\n\r", (tmp & SDIO_SCSI) >> 6);
+ TRACE_INFO(".ECSI %x\n\r", (tmp & SDIO_ECSI) >> 5);
+ TRACE_INFO(".BUS_WIDTH %x\n\r", (tmp & SDIO_BUSWIDTH) >> 0);
+ SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_CAP_REG, p, 1);
+ TRACE_INFO(".4BLS %x\n\r", (tmp & SDIO_4BLS) >> 7);
+ TRACE_INFO(".LSC %x\n\r", (tmp & SDIO_LSC) >> 6);
+ TRACE_INFO(".E4MI %x\n\r", (tmp & SDIO_E4MI) >> 5);
+ TRACE_INFO(".S4MI %x\n\r", (tmp & SDIO_S4MI) >> 4);
+ TRACE_INFO(".SBS %x\n\r", (tmp & SDIO_SBS) >> 3);
+ TRACE_INFO(".SRW %x\n\r", (tmp & SDIO_SRW) >> 2);
+ TRACE_INFO(".SMB %x\n\r", (tmp & SDIO_SMB) >> 1);
+ TRACE_INFO(".SDC %x\n\r", (tmp & SDIO_SDC) >> 0);
+ SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_CIS_PTR_REG, p, 3);
+ TRACE_INFO(".CIS_PTR %06X\n\r", tmp);
+ addrCIS = tmp; tmp = 0;
+ SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_BUS_SUSP_REG, p, 1);
+ TRACE_INFO(".BR %x\n\r", (tmp & SDIO_BR) >> 1);
+ TRACE_INFO(".BS %x\n\r", (tmp & SDIO_BS) >> 0);
+ SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_FUN_SEL_REG, p, 1);
+ TRACE_INFO(".DF %x\n\r", (tmp & SDIO_DF) >> 7);
+ TRACE_INFO(".FS %x\n\r", (tmp & SDIO_FS) >> 0);
+ SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_EXEC_REG, p, 1);
+ TRACE_INFO(".EX %x\n\r", (tmp & SDIO_EX));
+ TRACE_INFO(".EXM %x\n\r", (tmp & SDIO_EXM) >> 0);
+ SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_READY_REG, p, 1);
+ TRACE_INFO(".RF %x\n\r", (tmp & SDIO_RF));
+ TRACE_INFO(".RFM %x\n\r", (tmp & SDIO_RFM) >> 0);
+ SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_FN0_BLKSIZ_REG, p, 2);
+ TRACE_INFO(".FN0_SIZE %d(%04X)\n\r", tmp, tmp);
+ tmp = 0;
+ SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_POWER_REG, p, 1);
+ TRACE_INFO(".EMPC %x\n\r", (tmp & SDIO_EMPC) >> 1);
+ TRACE_INFO(".SMPC %x\n\r", (tmp & SDIO_SMPC) >> 0);
+ SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_HS_REG, p, 1);
+ TRACE_INFO(".EHS %x\n\r", (tmp & SDIO_EHS) >> 1);
+ TRACE_INFO(".SHS %x\n\r", (tmp & SDIO_SHS) >> 0);
+ // Metaformat
+ SdioFindTuples(pSd, addrCIS, 128, &addrManfID, &addrFunc0);
+ if (addrManfID != 0) {
+ SDIO_ReadDirect(pSd, SDIO_CIA, addrManfID, buf, 6);
+ TRACE_INFO("==== CISTPL_MANFID ====\n\r");
+ TRACE_INFO("._MANF %04X\n\r", buf[2] + (buf[3] << 8));
+ TRACE_INFO("._CARD %04X\n\r", buf[4] + (buf[5] << 8));
+ }
+ if (addrFunc0 != 0) {
+ SDIO_ReadDirect(pSd, SDIO_CIA, addrFunc0, buf, 6);
+ TRACE_INFO("== CISTPL_FUNCE Fun0 ==\n\r");
+ TRACE_INFO("._FN0_BLK_SIZE %d(0x%04X)\n\r",
+ buf[3] + (buf[4] << 8), buf[3] + (buf[4] << 8));
+ TRACE_INFO("._MAX_TRAN_SPEED %02X\n\r", buf[5]);
+ }
+}
+#endif
+
+//------------------------------------------------------------------------------
+/// Display the content of the CID register
+/// \param pCid Pointer to the Cid register value
+//------------------------------------------------------------------------------
+void SD_DisplayRegisterCID(SdCard *pSd)
+{
+ // CID for memory card only
+ if (pSd->cardType == CARD_UNKNOWN || pSd->cardType >= CARD_SDIO)
+ return;
+
+ TRACE_INFO("======= CID =======\n\r");
+ #if 0
+ TRACE_INFO(" .Card/BGA %X\n\r", SD_CID_BGA(pSd));
+ #else
+ TRACE_INFO("CID MID Manufacturer ID %02X\n\r",
+ SD_CID_MID(pSd));
+
+ TRACE_INFO("CID OID OEM/Application ID %c%c\n\r",
+ (char)SD_CID_OID_BYTE_1(pSd),
+ (char)SD_CID_OID_BYTE_0(pSd));
+
+ TRACE_INFO("CID PNM Product revision %c%c%c%c%c\n\r",
+ (char)SD_CID_PNM_BYTE_4(pSd),
+ (char)SD_CID_PNM_BYTE_3(pSd),
+ (char)SD_CID_PNM_BYTE_2(pSd),
+ (char)SD_CID_PNM_BYTE_1(pSd),
+ (char)SD_CID_PNM_BYTE_0(pSd));
+
+ TRACE_INFO("CID PRV Product serial number %02X%04X\n\r",
+ SD_CID_PRV_2(pSd),
+ SD_CID_PRV_1(pSd));
+
+ TRACE_INFO("CID MDT Manufacturing date %04d/%02d\n\r",
+ (unsigned short)SD_CID_MDT_YEAR(pSd),
+ (unsigned char)SD_CID_MDT_MONTH(pSd));
+
+ TRACE_INFO("CID CRC checksum %02X\n\r",
+ SD_CID_CRC(pSd));
+ #endif
+}
+
+//------------------------------------------------------------------------------
+/// Display the content of the CSD register
+/// \param pSd
+//------------------------------------------------------------------------------
+void SD_DisplayRegisterCSD(SdCard *pSd)
+{
+ // CID for memory card only
+ if (pSd->cardType == CARD_UNKNOWN || pSd->cardType >= CARD_SDIO)
+ return;
+
+ TRACE_INFO("======== CSD ========");
+ #if 0
+ {
+ unsigned int i;
+ unsigned char *p = (unsigned char *)pSd->csd;
+ for(i = 0; i < 128 / 8; i++) {
+ if ((i % 16) == 0) TRACE_INFO_WP("\n\r [%3d]:", i);
+ TRACE_INFO_WP(" %2x", p[i]);
+ }
+ TRACE_INFO_WP("\n\r");
+ TRACE_INFO("------------------------\n\r");
+ }
+ #else
+ TRACE_INFO_WP("\n\r");
+ #endif
+ TRACE_INFO(" .CSD_STRUCTURE 0x%x\r\n", SD_CSD_STRUCTURE(pSd));
+ TRACE_INFO(" .SPEC_VERS 0x%x\r\n", SD_CSD_SPEC_VERS(pSd));
+ TRACE_INFO(" .TAAC 0x%X\r\n", SD_CSD_TAAC(pSd) );
+ TRACE_INFO(" .NSAC 0x%X\r\n", SD_CSD_NSAC(pSd) );
+ TRACE_INFO(" .TRAN_SPEED 0x%X\r\n", SD_CSD_TRAN_SPEED(pSd) );
+ TRACE_INFO(" .CCC 0x%X\r\n", SD_CSD_CCC(pSd) );
+ TRACE_INFO(" .READ_BL_LEN 0x%X\r\n", SD_CSD_READ_BL_LEN(pSd) );
+ TRACE_INFO(" .READ_BL_PARTIAL 0x%X\r\n", SD_CSD_READ_BL_PARTIAL(pSd) );
+ TRACE_INFO(" .WRITE_BLK_MISALIGN 0x%X\r\n", SD_CSD_WRITE_BLK_MISALIGN(pSd));
+ TRACE_INFO(" .READ_BLK_MISALIGN 0x%X\r\n", SD_CSD_READ_BLK_MISALIGN(pSd) );
+ TRACE_INFO(" .DSR_IMP 0x%X\r\n", SD_CSD_DSR_IMP(pSd) );
+ TRACE_INFO(" .C_SIZE 0x%X\r\n", SD_CSD_C_SIZE(pSd) );
+ TRACE_INFO(" .C_SIZE_HC 0x%X\r\n", SD_CSD_C_SIZE_HC(pSd) );
+ TRACE_INFO(" .VDD_R_CURR_MIN 0x%X\r\n", SD_CSD_VDD_R_CURR_MIN(pSd) );
+ TRACE_INFO(" .VDD_R_CURR_MAX 0x%X\r\n", SD_CSD_VDD_R_CURR_MAX(pSd) );
+ TRACE_INFO(" .VDD_W_CURR_MIN 0x%X\r\n", SD_CSD_VDD_W_CURR_MIN(pSd) );
+ TRACE_INFO(" .VDD_W_CURR_MAX 0x%X\r\n", SD_CSD_VDD_W_CURR_MAX(pSd) );
+ TRACE_INFO(" .C_SIZE_MULT 0x%X\r\n", SD_CSD_C_SIZE_MULT(pSd) );
+ TRACE_INFO(" .ERASE_BLK_EN 0x%X\r\n", SD_CSD_ERASE_BLK_EN(pSd) );
+ TRACE_INFO(" .SECTOR_SIZE 0x%X\r\n", SD_CSD_SECTOR_SIZE(pSd) );
+ TRACE_INFO(" .WP_GRP_SIZE 0x%X\r\n", SD_CSD_WP_GRP_SIZE(pSd) );
+ TRACE_INFO(" .WP_GRP_ENABLE 0x%X\r\n", SD_CSD_WP_GRP_ENABLE(pSd) );
+ TRACE_INFO(" .R2W_FACTOR 0x%X\r\n", SD_CSD_R2W_FACTOR(pSd) );
+ TRACE_INFO(" .WRITE_BL_LEN 0x%X\r\n", SD_CSD_WRITE_BL_LEN(pSd) );
+ TRACE_INFO(" .WRITE_BL_PARTIAL 0x%X\r\n", SD_CSD_WRITE_BL_PARTIAL(pSd) );
+ TRACE_INFO(" .FILE_FORMAT_GRP 0x%X\r\n", SD_CSD_FILE_FORMAT_GRP(pSd) );
+ TRACE_INFO(" .COPY 0x%X\r\n", SD_CSD_COPY(pSd) );
+ TRACE_INFO(" .PERM_WRITE_PROTECT 0x%X\r\n", SD_CSD_PERM_WRITE_PROTECT(pSd));
+ TRACE_INFO(" .TMP_WRITE_PROTECT 0x%X\r\n", SD_CSD_TMP_WRITE_PROTECT(pSd) );
+ TRACE_INFO(" .FILE_FORMAT 0x%X\r\n", SD_CSD_FILE_FORMAT(pSd) );
+ TRACE_INFO(" .ECC 0x%X\r\n", SD_CSD_ECC(pSd) );
+ TRACE_INFO(" .CRC 0x%X\r\n", SD_CSD_CRC(pSd) );
+ TRACE_INFO(" .MULT 0x%X\r\n", SD_CSD_MULT(pSd) );
+ TRACE_INFO(" .BLOCKNR 0x%X\r\n", SD_CSD_BLOCKNR(pSd) );
+ TRACE_INFO(" .BLOCKNR_HC 0x%X\r\n", SD_CSD_BLOCKNR_HC(pSd) );
+ TRACE_INFO(" .BLOCK_LEN 0x%X\r\n", SD_CSD_BLOCK_LEN(pSd) );
+ TRACE_INFO(" .TOTAL_SIZE 0x%X\r\n", SD_CSD_TOTAL_SIZE(pSd) );
+ TRACE_INFO(" .TOTAL_SIZE_HC 0x%X\r\n", SD_CSD_TOTAL_SIZE_HC(pSd) );
+ TRACE_INFO(" -SD_TOTAL_SIZE 0x%X\r\n", SD_TOTAL_SIZE(pSd) );
+ TRACE_INFO(" -SD_TOTAL_BLOCK 0x%X\r\n", SD_TOTAL_BLOCK(pSd) );
+}
+
+//------------------------------------------------------------------------------
+/// Display the content of the EXT_CSD register
+/// \param pSd
+//------------------------------------------------------------------------------
+void SD_DisplayRegisterECSD(SdCard *pSd)
+{
+ if (pSd->cardType >= CARD_MMC && pSd->cardType <= CARD_MMCHD
+ && SD_CSD_STRUCTURE(pSd) >= 2) {}
+ else {
+ TRACE_INFO("** EXT_CSD NOT SUPPORTED\n\r");
+ return;
+ }
+ TRACE_INFO("======= EXT_CSD =======");
+ #if 0
+ {
+ unsigned int i;
+ unsigned char *p = (unsigned char *)pSd->extData;
+ for(i = 0; i < 512; i++) {
+ if ((i % 16) == 0) TRACE_INFO_WP("\n\r [%3d]:", i);
+ TRACE_INFO_WP(" %2x", p[i]);
+ }
+ TRACE_INFO_WP("\n\r");
+ TRACE_INFO("------------------------\n\r");
+ }
+ #else
+ TRACE_INFO_WP("\n\r");
+ #endif
+ TRACE_INFO(" .S_CMD_SET : 0x%X\n\r",
+ SD_EXTCSD_S_CMD_SET(pSd));
+ TRACE_INFO(" .BOOT_INFO : 0x%X\n\r",
+ SD_EXTCSD_BOOT_INFO(pSd));
+ TRACE_INFO(" .BOOT_SIZE_MULTI : 0x%X\n\r",
+ SD_EXTCSD_BOOT_SIZE_MULTI(pSd));
+ TRACE_INFO(" .ACC_SIZE : 0x%X\n\r",
+ SD_EXTCSD_ACC_SIZE(pSd));
+ TRACE_INFO(" .HC_ERASE_GRP_SIZE : 0x%X\n\r",
+ SD_EXTCSD_HC_ERASE_GRP_SIZE(pSd));
+ TRACE_INFO(" .ERASE_TIMEOUT_MULT : 0x%X\n\r",
+ SD_EXTCSD_ERASE_TIMEOUT_MULT(pSd));
+ TRACE_INFO(" .REL_WR_SEC_C : 0x%X\n\r",
+ SD_EXTCSD_REL_WR_SEC_C(pSd));
+ TRACE_INFO(" .HC_WP_GRP_SIZE : 0x%X\n\r",
+ SD_EXTCSD_HC_WP_GRP_SIZE(pSd));
+ TRACE_INFO(" .S_C_VCC : 0x%X\n\r",
+ SD_EXTCSD_S_C_VCC(pSd));
+ TRACE_INFO(" .S_C_VCCQ : 0x%X\n\r",
+ SD_EXTCSD_S_C_VCCQ(pSd));
+ TRACE_INFO(" .S_A_TIMEOUT : 0x%X\n\r",
+ SD_EXTCSD_S_A_TIMEOUT(pSd));
+ TRACE_INFO(" .SEC_COUNT : 0x%X\n\r",
+ SD_EXTCSD_SEC_COUNT(pSd));
+ TRACE_INFO(" .MIN_PERF_W_8_52 : 0x%X\n\r",
+ SD_EXTCSD_MIN_PERF_W_8_52(pSd));
+ TRACE_INFO(" .MIN_PERF_R_8_52 : 0x%X\n\r",
+ SD_EXTCSD_MIN_PERF_R_8_52(pSd));
+ TRACE_INFO(" .MIN_PERF_W_8_26_4_52 : 0x%X\n\r",
+ SD_EXTCSD_MIN_PERF_W_8_26_4_52(pSd));
+ TRACE_INFO(" .MIN_PERF_R_8_26_4_52 : 0x%X\n\r",
+ SD_EXTCSD_MIN_PERF_R_8_26_4_52(pSd));
+ TRACE_INFO(" .MIN_PERF_W_4_26 : 0x%X\n\r",
+ SD_EXTCSD_MIN_PERF_W_4_26(pSd));
+ TRACE_INFO(" .MIN_PERF_R_4_26 : 0x%X\n\r",
+ SD_EXTCSD_MIN_PERF_R_4_26(pSd));
+ TRACE_INFO(" .PWR_CL_26_360 : 0x%X\n\r",
+ SD_EXTCSD_PWR_CL_26_360(pSd));
+ TRACE_INFO(" .PWR_CL_52_360 : 0x%X\n\r",
+ SD_EXTCSD_PWR_CL_52_360(pSd));
+ TRACE_INFO(" .PWR_CL_26_195 : 0x%X\n\r",
+ SD_EXTCSD_PWR_CL_26_195(pSd));
+ TRACE_INFO(" .PWR_CL_52_195 : 0x%X\n\r",
+ SD_EXTCSD_PWR_CL_52_195(pSd));
+ TRACE_INFO(" .CARD_TYPE : 0x%X\n\r",
+ SD_EXTCSD_CARD_TYPE(pSd));
+ TRACE_INFO(" .CSD_STRUCTURE : 0x%X\n\r",
+ SD_EXTCSD_CSD_STRUCTURE(pSd));
+ TRACE_INFO(" .EXT_CSD_REV : 0x%X\n\r",
+ SD_EXTCSD_EXT_CSD_REV(pSd));
+ TRACE_INFO(" .CMD_SET : 0x%X\n\r",
+ SD_EXTCSD_CMD_SET(pSd));
+ TRACE_INFO(" .CMD_SET_REV : 0x%X\n\r",
+ SD_EXTCSD_CMD_SET_REV(pSd));
+ TRACE_INFO(" .POWER_CLASS : 0x%X\n\r",
+ SD_EXTCSD_POWER_CLASS(pSd));
+ TRACE_INFO(" .HS_TIMING : 0x%X\n\r",
+ SD_EXTCSD_HS_TIMING(pSd));
+ TRACE_INFO(" .BUS_WIDTH : 0x%X\n\r",
+ SD_EXTCSD_BUS_WIDTH(pSd));
+ TRACE_INFO(" .ERASED_MEM_CONT : 0x%X\n\r",
+ SD_EXTCSD_ERASED_MEM_CONT(pSd));
+ TRACE_INFO(" .BOOT_CONFIG : 0x%X\n\r",
+ SD_EXTCSD_BOOT_CONFIG(pSd));
+ TRACE_INFO(" .BOOT_BUS_WIDTH : 0x%X\n\r",
+ SD_EXTCSD_BOOT_BUS_WIDTH(pSd));
+ TRACE_INFO(" .ERASE_GROUP_DEF : 0x%X\n\r",
+ SD_EXTCSD_ERASE_GROUP_DEF(pSd));
+}
+
+//------------------------------------------------------------------------------
+/// Display the content of the SCR register
+/// \param pSd Pointer to SdCard instance.
+//------------------------------------------------------------------------------
+void SD_DisplayRegisterSCR(SdCard *pSd)
+{
+ if (pSd->cardType >= CARD_SD && pSd->cardType <= CARD_SDHC) {}
+ else {
+ TRACE_INFO("** SCR NOT Supported!\n\r");
+ return;
+ }
+ TRACE_INFO("========== SCR ==========");
+ #if 0
+ {
+ unsigned int i;
+ unsigned char *p = (unsigned char*)pSd->extData;
+ //TRACE_INFO_WP("\n\r");
+ //TRACE_INFO("DATA @ 0x%X", (unsigned int)p);
+ for(i = 0; i < 16; i ++) {
+ if ((i % 8) == 0) TRACE_INFO_WP("\n\r [%3d]:", i);
+ TRACE_INFO_WP(" %02x", p[i]);
+ }
+ TRACE_INFO_WP("\n\r");
+ TRACE_INFO("------------------------\n\r");
+ }
+ #else
+ TRACE_INFO_WP("\n\r");
+ #endif
+
+ TRACE_INFO(" .SCR_STRUCTURE :0x%X\n\r",
+ SD_SCR_SCR_STRUCTURE(pSd));
+ TRACE_INFO(" .SD_SPEC :0x%X\n\r",
+ SD_SCR_SD_SPEC(pSd));
+ TRACE_INFO(" .DATA_STAT_AFTER_ERASE :0x%X\n\r",
+ SD_SCR_DATA_STAT_AFTER_ERASE(pSd));
+ TRACE_INFO(" .SD_SECURITY :0x%X\n\r",
+ SD_SCR_SD_SECURITY(pSd));
+ TRACE_INFO(" .SD_BUS_WIDTHS :0x%X\n\r",
+ SD_SCR_SD_BUS_WIDTHS(pSd));
+}
+
+//------------------------------------------------------------------------------
+/// Display the content of the SD Status
+/// \param pSd Pointer to SdCard instance.
+//------------------------------------------------------------------------------
+void SD_DisplaySdStatus(SdCard *pSd)
+{
+ if ( pSd->cardType >= CARD_SD
+ && pSd->cardType <= CARD_SDHC
+ && (pSd->optCmdBitMap & SD_ACMD13_SUPPORT) ) {}
+ else {
+ TRACE_INFO("** SD Status NOT Supported!\n\r");
+ return;
+ }
+ TRACE_INFO("=========== STAT ============");
+ #if 0
+ {
+ unsigned int i;
+ unsigned char *p = (unsigned char*)pSd->extData;
+ //TRACE_INFO_WP("\n\r");
+ //TRACE_INFO("DATA @ 0x%X", (unsigned int)p);
+ for(i = 0; i < 72; i ++) {
+ if ((i % 8) == 0) TRACE_INFO_WP("\n\r [%3d]:", i);
+ TRACE_INFO_WP(" %02x", p[i]);
+ }
+ TRACE_INFO_WP("\n\r");
+ TRACE_INFO("------------------------\n\r");
+ }
+ #else
+ TRACE_INFO_WP("\n\r");
+ #endif
+
+ TRACE_INFO(" .DAT_BUS_WIDTH :0x%X\n\r",
+ SD_STAT_DAT_BUS_WIDTH(pSd));
+ TRACE_INFO(" .SECURED_MODE :0x%X\n\r",
+ SD_STAT_SECURED_MODE(pSd));
+ TRACE_INFO(" .SD_CARD_TYPE :0x%X\n\r",
+ SD_STAT_SD_CARD_TYPE(pSd));
+ TRACE_INFO(" .SIZE_OF_PROTECTED_AREA :0x%X\n\r",
+ SD_STAT_SIZE_OF_PROTECTED_AREA(pSd));
+ TRACE_INFO(" .SPEED_CLASS :0x%X\n\r",
+ SD_STAT_SPEED_CLASS(pSd));
+ TRACE_INFO(" .PERFORMANCE_MOVE :0x%X\n\r",
+ SD_STAT_PERFORMANCE_MOVE(pSd));
+ TRACE_INFO(" .AU_SIZE :0x%X\n\r",
+ SD_STAT_AU_SIZE(pSd));
+ TRACE_INFO(" .ERASE_SIZE :0x%X\n\r",
+ SD_STAT_ERASE_SIZE(pSd));
+ TRACE_INFO(" .ERASE_TIMEOUT :0x%X\n\r",
+ SD_STAT_ERASE_TIMEOUT(pSd));
+ TRACE_INFO(" .ERASE_OFFSET :0x%X\n\r",
+ SD_STAT_ERASE_OFFSET(pSd));
+}
diff --git a/memories/sdmmc/sdmmc_mci.h b/memories/sdmmc/sdmmc_mci.h
new file mode 100644
index 0000000..0e1bb62
--- /dev/null
+++ b/memories/sdmmc/sdmmc_mci.h
@@ -0,0 +1,1038 @@
+/* ----------------------------------------------------------------------------
+ * ATMEL Microcontroller Software Support
+ * ----------------------------------------------------------------------------
+ * Copyright (c) 2008, Atmel Corporation
+
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the disclaimer below.
+ *
+ * Atmel's name may not be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
+ * DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ----------------------------------------------------------------------------
+ */
+
+//------------------------------------------------------------------------------
+/// \page "sdcard sd mode initialization and identification"
+///
+/// !Purpose
+///
+/// sdcard sd mode initialization and identification sequence
+///
+/// !Description
+/// - Host sends Cmd0 to do card reset, card is in "idle state".
+/// - Host sends Cmd8 and checks the response of the card, only sdcard supports physical
+/// layer version 2.00 will response correctly to Cmd8, and this command is mandatory to be
+/// sent before ACmd41 for sdcard which support physical layer version 2.00, to enable new
+/// functions or to validate a dual-voltage card.
+/// - refer to "If Cmd8 response ok" branch for the initialize of sdcard 2.0.
+/// - refer to "If Cmd8 response fail" branch for the initialize of sdcard 1.x, mmc card, sdcard2.0
+/// with invalid voltage.
+/// - If Cmd8 response ok
+/// - Host sends ACmd41* with argument "HCS" equal to "1".
+/// - If the response to ACmd41 failed, it means the card does not match the voltage
+/// desired by the host, the card will be put into inactive state, initialize ends.
+/// - If the response with "CCS" equal to "1", the card is a version 2.0 high capacity sdcard,
+/// refer to "Card Initialize" for the succeeding initialize sequence.
+/// - If the response with "CCS" equal to "0", the card is a version 2.0 standard capacity sdcard.
+/// refer to "Card Initialize" for the succeeding initialize sequence.
+/// - If Cmd8 response fail
+/// - Host sends ACmd41* argument "HCS" equal to "0".
+/// - If the response to ACmd41 ok, the card is a version 1.x sdcard, refer to "Card Initialize" for
+/// the succeeding initialize sequence.
+/// - If the response to ACmd41 fails
+/// - Host sends Cmd0 to reset card.
+/// - Host sends Cmd1 with argument "hdSupport" equal to "1" to card.
+/// - If card has response to Cmd1, the card is a MMC card, refer to "Card Initialize" for the
+/// succeeding initialize sequence. Furthermore, if the response with bit[30:29] equal to
+/// "00" or "11", the card is a High Density MMC, else the card is a standard MMC.
+/// - If card has no response to Cmd1, the card is either an unknown card or a card does
+/// not match host's voltage, the initialize ends.
+/// - Card Initialize
+/// - Host sends Cmd2 to get the its unique card identification number (CID).
+/// - Host sends Cmd3 to ask the card to publish a new relative card address (RCA), once the
+/// RCA is received the card state changes to the "stand-by state".
+/// - Host sends Cmd9 to get the Card Specific Data (CSD).
+/// - At this stage, the initialization and identification process is over, the following steps are done
+/// for the sdcard's succeeding operation.
+/// - Host sends Cmd13 to obtain the card status, make sure the card is "ready-for-data".
+/// - Host sends Cmd7 to transit card in "transfer state".
+/// - If card is a sdcard*, hosts send ACmd6 to set bus to 4-wire mode.
+/// - If card is a mmc card, the bus is set as 1-wire mode.
+///
+/// \note Send Cmd55 before send ACmd41. \endnote
+/// \note sdcard include ver 1.x sdcard, ver2.0 standard capacity sdcard, ver2.0 high capacity sdcard \endnote
+//------------------------------------------------------------------------------
+
+//------------------------------------------------------------------------------
+/// \page "sdcard sd mode write"
+///
+/// !Purpose
+///
+/// sdcard sd mode write process
+///
+/// !Description
+/// - Make sure sdcard is under "transfer state", if the sdcard is under other state, host will send
+/// Cmd12 to stop the current operation and to transit sdcard to "stand-by state".
+/// - Host sends Cmd13 to check sdcard's status, to make sure sdcard is "ready-for-data".
+/// - Host sends Cmd25 to do multiple blocks write, the address here is different between high capacity
+/// sdcard and normal sdcard, the address of SDHC is equal to the block number, while normal sdcard's
+/// address is equal to block number times 512.
+///
+/// !Write Optimization
+/// - To optimize the write multiple blocks, try to keep the sdcard in the "rcv state" as long as possible.
+/// after send WRITE_MULTIPLE_BLOCK command, set the block number in the MCI_BLKR as 0, each time a
+/// new write start, do not re-send the WRITE_MULTIPLE_BLOCK command, just re-configure the PDC. In
+/// this case, host does not have to send STOP_TRANSMISSION to transfer the sdcard's state and the
+/// performance is optimized.
+/// - MoveToTransferState will check the state of the sdcard, and send STOP_TRANSMISSION if need
+/// to transfer state. Normally this function is called between the state tranfer.
+/// - ContinuousWrite will be called if WRITE_MULTIPLE_BLOCK already been sent and this function
+/// will not re-send the write command, but will re-configure PDC accordingly.
+//------------------------------------------------------------------------------
+
+//------------------------------------------------------------------------------
+/// \page "sdcard sd mode read"
+///
+/// !Purpose
+///
+/// sdcard sd mode read process
+///
+/// !Description
+/// - Make sure sdcard is under "transfer state", if the sdcard is under other state, host will send
+/// Cmd12 to stop the current operation and to transit sdcard to "stand-by state".
+/// - Host sends Cmd13 to check sdcard's status, to make sure sdcard is "ready-for-data".
+/// - Host sends Cmd18 to do multiple blocks read, the address here is different between high capacity
+/// sdcard and normal sdcard, the address of SDHC is equal to the block number, while normal sdcard's
+/// address is equal to block number times 512.
+///
+/// !Read Optimization
+/// - To optimize the read multiple blocks, try to keep the sdcard in the "data state" as long as possible.
+/// after send READ_MULTIPLE_BLOCK command, set the block number in the MCI_BLKR as 0, each time a
+/// new read start, do not re-send the READ_MULTIPLE_BLOCK command, just re-configure the PDC. In this
+/// case, host does not have to send STOP_TRANSMISSION to transfer the sdcard's state and the
+/// performance is optimized.
+/// - MoveToTransferState will check the state of the sdcard, and send STOP_TRANSMISSION if need
+/// to transfer state. Normally this function is called between the state tranfer.
+/// - ContinuousRead will be called if READ_MULTIPLE_BLOCK already been sent and this function
+/// will not re-send the read command, but will re-configure PDC accordingly.
+//------------------------------------------------------------------------------
+
+//------------------------------------------------------------------------------
+/// \page "sdhc"
+///
+/// !Purpose
+///
+/// highlight of sdhc
+///
+/// !Sdhc initialization and identification
+///
+/// - Refer to page "sdcard sd mode initialization and identification" for the initialization and identification
+/// sequence of a sdhc.
+///
+/// !Functional difference between sdhc and standard capacity sdcard
+///
+/// - Command argument is different:
+/// - Sdhc uses block address format in memory access commands*, block length is fixed to 512 bytes.
+/// - Standard capacity sdcard uses byte address format in memory access commands, block length
+/// is defined in Cmd16.
+/// - Partial access and misalign access are disabled in sdhc as the block address is used.
+/// - Sdhc does not support write-protected commands (Cmd28, Cmd29, Cmd30).
+///
+/// \note Memory access commands means block read commands (CMD17, CMD18), block write commands
+/// (CMD24, CMD25), and block erase commands (CMD32, CMD33).
+///
+//------------------------------------------------------------------------------
+
+//------------------------------------------------------------------------------
+/// \page "sdmmc_mci"
+///
+/// !Purpose
+///
+/// Implementation for sdcard sd mode physical layer driver. Supply a set of sdcard sd mode's
+/// interface.
+///
+/// !Usage
+///
+/// -# SD_Init: Run the SDcard initialization sequence
+/// -# SD_MCI_Init : Run the SDcard SD Mode initialization sequence
+/// -# SD_Stop: Stop the SDcard by sending Cmd12
+/// -# SD_ReadBlock : Read blocks of data
+/// -# SD_WriteBlock : Write blocks of data
+/// -# Cmd0 : Resets all cards to idle state
+/// -# Cmd1 : MMC send operation condition command
+/// -# Cmd2 : Asks any card to send the CID numbers on the CMD line
+/// -# Cmd3 : Ask the card to publish a new relative address
+/// -# Cmd7 : Command toggles a card between the stand-by and transfer states or between
+/// the programming and disconnect states
+/// -# Cmd8 : Sends SD Memory Card interface condition, which includes host supply voltage
+/// information and asks the card whether card supports voltage
+/// -# Cmd9 : Addressed card sends its card-specific data (CSD) on the CMD line
+/// -# Cmd12 : Forces the card to stop transmission
+/// -# Cmd13 : Addressed card sends its status register
+/// -# Cmd16 : Set block length
+/// -# Cmd18 : Read multiple blocks
+/// -# Cmd25 : Write multiple blocks
+/// -# Cmd55 : App command, should be sent before application specific command
+/// -# Acmd6 : Defines the data bus width
+/// -# Acmd41 : Asks to all cards to send their operations conditions
+/// -# CmdEMMC8 : Sends eMMC EXT_CSD command
+/// -# CmdEMMC6 : Switches the mode of operation of the selected card or modifies the
+/// EXT_CSD registers
+//------------------------------------------------------------------------------
+
+#ifndef SDMMC_MCI_H
+#define SDMMC_MCI_H
+
+//------------------------------------------------------------------------------
+// Header
+//------------------------------------------------------------------------------
+
+#include <board.h>
+
+#if !defined(MCI2_INTERFACE)
+#include <mci/mci.h>
+#else
+#include <mci/mci_hs.h>
+#endif
+
+//------------------------------------------------------------------------------
+// Constants
+//------------------------------------------------------------------------------
+
+
+/// There was an error with the SD driver.
+#define SD_ERROR_DRIVER 1
+/// The SD card did not answer the command.
+#define SD_ERROR_NORESPONSE 2
+/// The SD card did not answer the command.
+#define SD_ERROR_NOT_INITIALIZED 3
+/// The SD card is busy
+#define SD_ERROR_BUSY 4
+/// The operation is not supported
+#define SD_ERROR_NOT_SUPPORT 5
+
+/// Card types
+#define CARD_TYPE_bmHC (1 << 0) /// Bit for High-Capacity(Density)
+#define CARD_TYPE_bmSDMMC (0x3 << 1) /// Bit mask for SD/MMC
+#define CARD_TYPE_bmSD (0x1 << 1) /// Bit for SD
+#define CARD_TYPE_bmMMC (0x2 << 1) /// Bit for MMC
+#define CARD_TYPE_bmSDIO (1 << 3) /// Bit for SDIO
+
+/// Card can not identified
+#define CARD_UNKNOWN (0)
+/// SD Card (0x2)
+#define CARD_SD (CARD_TYPE_bmSD)
+/// SD High Capacity Card (0x3)
+#define CARD_SDHC (CARD_TYPE_bmSD|CARD_TYPE_bmHC)
+/// MMC Card (0x4)
+#define CARD_MMC (CARD_TYPE_bmMMC)
+/// MMC High-Density Card (0x5)
+#define CARD_MMCHD (CARD_TYPE_bmMMC|CARD_TYPE_bmHC)
+/// SDIO only card (0x8)
+#define CARD_SDIO (CARD_TYPE_bmSDIO)
+/// SDIO Combo, with SD embedded (0xA)
+#define CARD_SDCOMBO (CARD_TYPE_bmSDIO|CARD_SD)
+/// SDIO Combo, with SDHC embedded (0xB)
+#define CARD_SDHCCOMBO (CARD_TYPE_bmSDIO|CARD_SDHC)
+
+/// SD card block size in bytes.
+#define SD_BLOCK_SIZE 512
+/// SD card block size binary shift value
+#define SD_BLOCK_SIZE_BIT 9
+
+//- MMC Card Command Types
+/// Broadcast commands (bc), no response
+#define MMC_CCT_BC 0
+/// Broadcase commands with response (bcr)
+#define MMC_CCT_BCR 1
+/// Addressed commands (ac), no data transfer on DAT lines
+#define MMC_CCT_AC 2
+/// Addressed data transfer commands (adtc), data transfer on DAT lines
+#define MMC_CCT_ADTC 3
+
+//- MMC Card Command Classes (CCC)
+/// Class 0: basic
+#define MMC_CCC_BASIC 0
+/// Class 1: stream read
+#define MMC_CCC_STREAM_READ 1
+/// Class 2: block read
+#define MMC_CCC_BLOCK_READ 2
+/// Class 3: stream write
+#define MMC_CCC_STREAM_WRITE 3
+/// Class 4: block write
+#define MMC_CCC_BLOCK_WRITE 4
+/// Class 5: erase
+#define MMC_CCC_ERASE 5
+/// Class 6: write protection
+#define MMC_CCC_WRITE_PROTECTION 6
+/// Class 7: lock card
+#define MMC_CCC_LOCK_CARD 7
+/// Class 8: application specific
+#define MMC_CCC_APP_SPEC 8
+/// Class 9: I/O mode
+#define MMC_CCC_IO_MODE 9
+
+//- MMC/SD Card Command Response Type
+/// R1 (normal response command), 48bits
+#define MMC_RESP_R1 1
+#define SD_RESP_R1 MMC_RESP_R1
+/// R1b: busy signal transmitted on the data line DAT0
+#define MMC_RESP_R1b 1
+#define SD_RESP_R1b MMC_RESP_R1b
+/// R2: 136bits, CID, CSD register
+#define MMC_RESP_R2 2
+#define SD_RESP_R2 MMC_RESP_R2
+/// R3: 48bits, OCR
+#define MMC_RESP_R3 3
+#define SD_RESP_R3 MMC_RESP_R3
+/// R4 (Fast I/O), 48bits
+#define MMC_RESP_R4 4
+/// R5 (Interrupt request), 48bits
+#define MMC_RESP_R5 5
+/// R6 (Published RCA response), 48bits
+#define SD_RESP_R6 6
+/// R7 (Card interface condition), 48bits
+#define SD_RESP_R7 7
+
+//- MMC Card CMD6 access mode
+#define MMC_SWITCH_CMDSET 0
+#define MMC_SWITCH_SETBITS 1
+#define MMC_SWITCH_CLRBITS 2
+#define MMC_SWITCH_WRITE 3
+
+//-MMC Boot partition enable
+/// Boot partition 1 enabled for boot
+#define MMC_BOOT_PART_1 1
+/// Boot partition 2 enabled for boot
+#define MMC_BOOT_PART_2 2
+/// User area enabled for boot
+#define MMC_BOOT_PART_USER 7
+
+//-MMC Boot partition access
+/// R/W boot partition 1
+#define MMC_BOOT_ACC_PART1 1
+/// R/W boot partition 2
+#define MMC_BOOT_ACC_PART2 2
+
+//------------------------------------------------------------------------------
+// Macros
+//------------------------------------------------------------------------------
+
+// CID register access macros (128 bits, 4 * 32 bits).
+#define SD_CID(pSd, bitfield, bits) ( (pSd->cid[3-(bitfield)/32] >> ((bitfield)%32)) & ((1 << (bits)) - 1))
+#define SD_CID_MID(pSd) SD_CID(pSd, 120, 8) ///< Manufacturer ID
+#define SD_CID_BGA(pSd) SD_CID(pSd, 112, 2) ///< Card/BGA(eMMC)
+#define SD_CID_CBS(pSd) SD_CID(pSd, 112, 2) ///< Card/BGA(eMMC)
+#define SD_CID_OID_BYTE_1(pSd) SD_CID(pSd, 112, 8) ///< OEM/Application ID byte 1
+#define SD_CID_OID_BYTE_0(pSd) SD_CID(pSd, 104, 8) ///< OEM/Application ID byte 0
+#define SD_CID_PNM_BYTE_4(pSd) SD_CID(pSd, 96, 8) ///< Product revision byte 4
+#define SD_CID_PNM_BYTE_3(pSd) SD_CID(pSd, 88, 8) ///< Product revision byte 3
+#define SD_CID_PNM_BYTE_2(pSd) SD_CID(pSd, 80, 8) ///< Product revision byte 2
+#define SD_CID_PNM_BYTE_1(pSd) SD_CID(pSd, 72, 8) ///< Product revision byte 1
+#define SD_CID_PNM_BYTE_0(pSd) SD_CID(pSd, 64, 8) ///< Product revision byte 0
+#define SD_CID_PRV_1(pSd) SD_CID(pSd, 24, 8) ///< Product serial number 1
+#define SD_CID_PRV_2(pSd) SD_CID(pSd, 32,24) ///< Product serial number 2
+#define SD_CID_MDT_YEAR(pSd) (SD_CID(pSd, 12, 8))+2000///< Manufacturing date year
+#define SD_CID_MDT_MONTH(pSd) SD_CID(pSd, 8, 4) ///< Manufacturing date month
+#define SD_CID_CRC(pSd) SD_CID(pSd, 1, 7) ///< CRC7 checksum
+
+// CSD register access macros (128 bits, 4 * 32 bits).
+#define SD_CSD(pSd, bitfield, bits) ((((pSd)->csd)[3-(bitfield)/32] >> ((bitfield)%32)) & ((1 << (bits)) - 1))
+#define SD_CSD_STRUCTURE(pSd) SD_CSD(pSd, 126, 2) ///< CSD structure 00b Version 1.0 01b version 2.0 High Cap
+#define SD_CSD_SPEC_VERS(pSd) SD_CSD(pSd, 122, 4) ///< System Specification Version Number
+#define SD_CSD_TAAC(pSd) SD_CSD(pSd, 112, 8) ///< Data read-access-time-1
+#define SD_CSD_NSAC(pSd) SD_CSD(pSd, 104, 8) ///< Data read access-time-2 in CLK cycles
+#define SD_CSD_TRAN_SPEED(pSd) SD_CSD(pSd, 96, 8) ///< Max. data transfer rate
+#define SD_CSD_CCC(pSd) SD_CSD(pSd, 84, 12) ///< Card command class
+#define SD_CSD_READ_BL_LEN(pSd) SD_CSD(pSd, 80, 4) ///< Max. read data block length
+#define SD_CSD_READ_BL_PARTIAL(pSd) SD_CSD(pSd, 79, 1) ///< Bartial blocks for read allowed
+#define SD_CSD_WRITE_BLK_MISALIGN(pSd) SD_CSD(pSd, 78, 1) ///< Write block misalignment
+#define SD_CSD_READ_BLK_MISALIGN(pSd) SD_CSD(pSd, 77, 1) ///< Read block misalignment
+#define SD_CSD_DSR_IMP(pSd) SD_CSD(pSd, 76, 1) ///< DSP implemented
+#define SD_CSD_C_SIZE(pSd) ((SD_CSD(pSd, 72, 2) << 10) + \
+ (SD_CSD(pSd, 64, 8) << 2) + \
+ SD_CSD(pSd, 62, 2)) ///< Device size
+#define SD_CSD_C_SIZE_HC(pSd) ((SD_CSD(pSd, 64, 6) << 16) + \
+ (SD_CSD(pSd, 56, 8) << 8) + \
+ SD_CSD(pSd, 48, 8)) ///< Device size v2.0 High Capacity
+#define SD_CSD_VDD_R_CURR_MIN(pSd) SD_CSD(pSd, 59, 3) ///< Max. read current @VDD min
+#define SD_CSD_VDD_R_CURR_MAX(pSd) SD_CSD(pSd, 56, 3) ///< Max. read current @VDD max
+#define SD_CSD_VDD_W_CURR_MIN(pSd) SD_CSD(pSd, 53, 3) ///< Max. write current @VDD min
+#define SD_CSD_VDD_W_CURR_MAX(pSd) SD_CSD(pSd, 50, 3) ///< Max. write current @VDD max
+#define SD_CSD_C_SIZE_MULT(pSd) SD_CSD(pSd, 47, 3) ///< Device size multiplier
+#define SD_CSD_ERASE_BLK_EN(pSd) SD_CSD(pSd, 46, 1) ///< Erase single block enable
+#define MMC_CSD_ERASE_BLK_EN(pSd) SD_CSD(pSd, 46, 1) ///< Erase single block enable
+#define MMC_CSD_ERASE_GRP_SIZE(pSd) SD_CSD(pSd, 42, 4) ///< Erase group size
+#define SD_CSD_ERASE_GRP_MULT(pSd) SD_CSD(pSd, 37, 4) ///< Erase group size multiplier
+#define SD_CSD_SECTOR_SIZE(pSd) ((SD_CSD(pSd, 40, 6) << 1) + SD_CSD(pSd, 39, 1)) ///< Erase sector size
+#define SD_CSD_WP_GRP_SIZE(pSd) SD_CSD(pSd, 32, 7) ///< Write protect group size
+#define SD_CSD_WP_GRP_ENABLE(pSd) SD_CSD(pSd, 31, 1) ///< write protect group enable
+#define SD_CSD_R2W_FACTOR(pSd) SD_CSD(pSd, 26, 3) ///< Write speed factor
+#define SD_CSD_WRITE_BL_LEN(pSd) ((SD_CSD(pSd, 24, 2) << 2) + SD_CSD(pSd, 22, 2)) ///< Max write block length
+#define SD_CSD_WRITE_BL_PARTIAL(pSd) SD_CSD(pSd, 21, 1) ///< Partial blocks for write allowed
+#define SD_CSD_CONTENT_PROT_APP(pSd) SD_CSD(pSd, 16, 1) ///< File format group
+#define SD_CSD_FILE_FORMAT_GRP(pSd) SD_CSD(pSd, 15, 1) ///< File format group
+#define SD_CSD_COPY(pSd) SD_CSD(pSd, 14, 1) ///< Copy flag (OTP)
+#define SD_CSD_PERM_WRITE_PROTECT(pSd) SD_CSD(pSd, 13, 1) ///< Permanent write protect
+#define SD_CSD_TMP_WRITE_PROTECT(pSd) SD_CSD(pSd, 12, 1) ///< Temporary write protection
+#define SD_CSD_FILE_FORMAT(pSd) SD_CSD(pSd, 10, 2) ///< File format
+#define SD_CSD_ECC(pSd) SD_CSD(pSd, 8, 2) ///< CRC
+#define SD_CSD_CRC(pSd) SD_CSD(pSd, 1, 7) ///< CRC
+#define SD_CSD_MULT(pSd) (1 << (SD_CSD_C_SIZE_MULT(pSd) + 2))
+#define SD_CSD_BLOCKNR(pSd) ((SD_CSD_C_SIZE(pSd) + 1) * SD_CSD_MULT(pSd))
+#define SD_CSD_BLOCKNR_HC(pSd) ((SD_CSD_C_SIZE_HC(pSd) + 1) * 1024)
+#define SD_CSD_BLOCK_LEN(pSd) (1 << SD_CSD_READ_BL_LEN(pSd))
+#define SD_CSD_TOTAL_SIZE(pSd) (SD_CSD_BLOCKNR(pSd) * SD_CSD_BLOCK_LEN(pSd))
+#define SD_CSD_TOTAL_SIZE_HC(pSd) ((SD_CSD_C_SIZE_HC(pSd) + 1) * 512* 1024)
+#define SD_TOTAL_SIZE(pSd) ((pSd)->totalSize)
+#define SD_TOTAL_BLOCK(pSd) ((pSd)->blockNr)
+
+// SCR register access macros (64 bits, 2 * 32 bits, 8 * 8 bits).
+#define SD_EXT_OFFSET_SD_SCR 0 // DW
+#define SD_SCR(pSd, bitfield, bits) \
+ ( ((char*)(pSd)->extData)[7 - ((bitfield)/8)] >> ((bitfield)%8) \
+ & ((1 << (bits)) - 1) \
+ )
+#define SD_SCR_SCR_STRUCTURE(pSd) SD_SCR(pSd, 60, 4)
+#define SD_SCR_SCR_STRUCTURE_1_0 0
+#define SD_SCR_SD_SPEC(pSd) SD_SCR(pSd, 56, 4)
+#define SD_SCR_SD_SPEC_1_0_01 0
+#define SD_SCR_SD_SPEC_1_10 1
+#define SD_SCR_SD_SPEC_2_00 2
+#define SD_SCR_DATA_STAT_AFTER_ERASE(pSd) SD_SCR(pSd, 55, 1)
+#define SD_SCR_SD_SECURITY(pSd) SD_SCR(pSd, 52, 3)
+#define SD_SCR_SD_SECURITY_NO 0
+#define SD_SCR_SD_SECURITY_NOTUSED 1
+#define SD_SCR_SD_SECURITY_1_01 2
+#define SD_SCR_SD_SECURITY_2_00 3
+#define SD_SCR_SD_BUS_WIDTHS(pSd) SD_SCR(pSd, 48, 4)
+#define SD_SCR_SD_BUS_WIDTH_1BITS (1 << 0)
+#define SD_SCR_SD_BUS_WIDTH_4BITS (1 << 2)
+
+// SD Status access macros (512 bits, 16 * 32 bits, 64 * 8 bits).
+#define SD_EXT_OFFSET_SD_STAT 2 // DW
+#define SD_STAT(pSd, bitfield, bits) \
+ ( ((char*)&(pSd)->extData[2])[63 - ((bitfield)/8)] >> ((bitfield)%8) \
+ & ((1 << (bits)) - 1) \
+ )
+/// Bus width, 00: default, 10:4-bit
+#define SD_STAT_DAT_BUS_WIDTH(pSd) SD_STAT(pSd, 510, 2)
+#define SD_STAT_DATA_BUS_WIDTH_1BIT 0x0
+#define SD_STAT_DATA_BUS_WIDTH_4BIT 0x2
+/// Secured Mode
+#define SD_STAT_SECURED_MODE(pSd) SD_STAT(pSd, 509, 1)
+/// SD Memory Cards as defined in 1.01~2.00
+#define SD_STAT_SD_CARD_TYPE(pSd) (SD_STAT(pSd, 480, 8) \
+ + (SD_STAT(pSd, 488, 8) << 8) )
+/// STD: ThisSize*Multi*BlockLen, HC: Size in bytes
+#define SD_STAT_SIZE_OF_PROTECTED_AREA(pSd) (SD_STAT(pSd, 448, 8) \
+ + (SD_STAT(pSd, 456, 8) << 8) \
+ + (SD_STAT(pSd, 464, 8) << 16) \
+ + (SD_STAT(pSd, 472, 8) << 24) )
+/// Speed Class, value can be calculated by Pw/2
+#define SD_STAT_SPEED_CLASS(pSd) SD_STAT(pSd, 440, 8)
+#define SD_STAT_SPEED_CLASS_0 0
+#define SD_STAT_SPEED_CLASS_2 1 // >= 2MB/s
+#define SD_STAT_SPEED_CLASS_4 2 // >= 4MB/s
+#define SD_STAT_SPEED_CLASS_6 3 // >= 6MB/s
+/// 8-bit, by 1MB/s step.
+#define SD_STAT_PERFORMANCE_MOVE(pSd) SD_STAT(pSd, 432, 8)
+/// AU Size, in power of 2 from 16KB
+#define SD_STAT_AU_SIZE(pSd) SD_STAT(pSd, 428, 4)
+#define SD_STAT_AU_SIZE_16K 1
+#define SD_STAT_AU_SIZE_32K 2
+#define SD_STAT_AU_SIZE_64K 3
+#define SD_STAT_AU_SIZE_128K 4
+#define SD_STAT_AU_SIZE_256K 5
+#define SD_STAT_AU_SIZE_512K 6
+#define SD_STAT_AU_SIZE_1M 7
+#define SD_STAT_AU_SIZE_2M 8
+#define SD_STAT_AU_SIZE_4M 9
+/// 16-bit, number of AUs erased.
+#define SD_STAT_ERASE_SIZE(pSd) (SD_STAT(pSd, 408, 8) \
+ + (SD_STAT(pSd, 416, 8) << 8) )
+#define SD_STAT_ERASE_TIMEOUT(pSd) SD_STAT(pSd, 402, 6)
+#define SD_STAT_ERASE_OFFSET(pSd) SD_STAT(pSd, 400, 2)
+
+// SD Switch Status access macros (512 bits, 16 * 32 bits, 64 * 8 bits).
+#define SD_SW_STAT(p, bitfield, bits) \
+ ( ((char*)(p))[63 - ((bitfield)/8)] >> ((bitfield)%8) \
+ & ((1 << (bits)) - 1) \
+ )
+#define SD_SW_STAT_MAX_CURRENT_CONSUMPTION(p) ( SD_SW_STAT(p, 496, 8) \
+ + (SD_SW_STAT(p, 504, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP6_INFO(p) ( SD_SW_STAT(p, 480, 8) \
+ + (SD_SW_STAT(p, 488, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP5_INFO(p) ( SD_SW_STAT(p, 464, 8) \
+ + (SD_SW_STAT(p, 472, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP4_INFO(p) ( SD_SW_STAT(p, 448, 8) \
+ + (SD_SW_STAT(p, 456, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP3_INFO(p) ( SD_SW_STAT(p, 432, 8) \
+ + (SD_SW_STAT(p, 440, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP2_INFO(p) ( SD_SW_STAT(p, 416, 8) \
+ + (SD_SW_STAT(p, 424, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP1_INFO(p) ( SD_SW_STAT(p, 400, 8) \
+ + (SD_SW_STAT(p, 408, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP6_RC(p) SD_SW_STAT(p, 396, 4)
+#define SD_SW_STAT_FUN_GRP5_RC(p) SD_SW_STAT(p, 392, 4)
+#define SD_SW_STAT_FUN_GRP4_RC(p) SD_SW_STAT(p, 388, 4)
+#define SD_SW_STAT_FUN_GRP3_RC(p) SD_SW_STAT(p, 384, 4)
+#define SD_SW_STAT_FUN_GRP2_RC(p) SD_SW_STAT(p, 380, 4)
+#define SD_SW_STAT_FUN_GRP1_RC(p) SD_SW_STAT(p, 376, 4)
+#define SD_SW_STAT_FUN_GRP_RC_ERROR 0xF
+#define SD_SW_STAT_DATA_STRUCT_VER(p) SD_SW_STAT(p, 368, 8)
+#define SD_SW_STAT_FUN_GRP6_BUSY(p) ( SD_SW_STAT(p, 352, 8) \
+ + (SD_SW_STAT(p, 360, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP5_BUSY(p) ( SD_SW_STAT(p, 336, 8) \
+ + (SD_SW_STAT(p, 344, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP4_BUSY(p) ( SD_SW_STAT(p, 320, 8) \
+ + (SD_SW_STAT(p, 328, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP3_BUSY(p) ( SD_SW_STAT(p, 304, 8) \
+ + (SD_SW_STAT(p, 312, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP2_BUSY(p) ( SD_SW_STAT(p, 288, 8) \
+ + (SD_SW_STAT(p, 296, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP1_BUSY(p) ( SD_SW_STAT(p, 272, 8) \
+ + (SD_SW_STAT(p, 280, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP_FUN_BUSY(funNdx) (1 << (funNdx))
+
+// EXT_CSD register definition.
+#define SD_EXTCSD_S_CMD_SET_INDEX 504 // Below belongs to Properties Segment
+#define SD_EXTCSD_BOOT_INFO_INDEX 228
+#define SD_EXTCSD_BOOT_SIZE_MULTI_INDEX 226
+#define SD_EXTCSD_ACC_SIZE_INDEX 225
+#define SD_EXTCSD_HC_ERASE_GRP_SIZE_INDEX 224
+#define SD_EXTCSD_ERASE_TIMEOUT_MULT_INDEX 223
+#define SD_EXTCSD_REL_WR_SEC_C_INDEX 222
+#define SD_EXTCSD_HC_WP_GRP_SIZE_INDEX 221
+#define SD_EXTCSD_S_C_VCC_INDEX 220
+#define SD_EXTCSD_S_C_VCCQ_INDEX 219
+#define SD_EXTCSD_S_A_TIMEOUT_INDEX 217
+#define SD_EXTCSD_SEC_COUNT_INDEX 212
+#define SD_EXTCSD_MIN_PERF_W_8_52_INDEX 210
+#define SD_EXTCSD_MIN_PERF_R_8_52_INDEX 209
+#define SD_EXTCSD_MIN_PERF_W_8_26_4_52_INDEX 208
+#define SD_EXTCSD_MIN_PERF_R_8_26_4_52_INDEX 207
+#define SD_EXTCSD_MIN_PERF_W_4_26_INDEX 206
+#define SD_EXTCSD_MIN_PERF_R_4_26_INDEX 205
+#define SD_EXTCSD_PWR_CL_26_360_INDEX 203
+#define SD_EXTCSD_PWR_CL_52_360_INDEX 202
+#define SD_EXTCSD_PWR_CL_26_195_INDEX 201
+#define SD_EXTCSD_PWR_CL_52_195_INDEX 200
+#define SD_EXTCSD_CARD_TYPE_INDEX 196
+#define SD_EXTCSD_CSD_STRUCTURE_INDEX 194
+#define SD_EXTCSD_EXT_CSD_REV_INDEX 192
+
+#define SD_EXTCSD_CMD_SET_INDEX 191 //Below belongs to Mode Segment
+#define SD_EXTCSD_CMD_SET_REV_INDEX 189
+#define SD_EXTCSD_POWER_CLASS_INDEX 187
+#define SD_EXTCSD_HS_TIMING_INDEX 185
+#define SD_EXTCSD_BUS_WIDTH_INDEX 183
+#define SD_EXTCSD_ERASED_MEM_CONT_INDEX 181
+#define SD_EXTCSD_BOOT_CONFIG_INDEX 179
+#define SD_EXTCSD_BOOT_BUS_WIDTH_INDEX 177
+#define SD_EXTCSD_ERASE_GROUP_DEF_INDEX 175
+
+// Ext_CSD register access marco
+#define MMC_EXTCSD_U8(pSd, bytefield) \
+ ( ((unsigned char*)((pSd)->extData))[(bytefield)] )
+#define MMC_EXTCSD_U16(pSd, bytefield) \
+ ( (((unsigned char*)((pSd)->extData))[(bytefield) ] << 0) + \
+ (((unsigned char*)((pSd)->extData))[(bytefield) + 1] << 8) )
+#define MMC_EXTCSD_U32(pSd, bytefield) \
+ ( (((unsigned char*)((pSd)->extData))[(bytefield) ] << 0) + \
+ (((unsigned char*)((pSd)->extData))[(bytefield) + 1] << 8) + \
+ (((unsigned char*)((pSd)->extData))[(bytefield) + 2] << 16) + \
+ (((unsigned char*)((pSd)->extData))[(bytefield) + 24] << 24) )
+#define MMC_EXTCSD(pSd) ((unsigned char*)((pSd)->extData))
+#define SD_EXTCSD_S_CMD_SET(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_S_CMD_SET_INDEX]) // Supported Command Sets
+#define SD_EXTCSD_BOOT_INFO(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_BOOT_INFO_INDEX]) // Boot information
+#define SD_EXTCSD_BOOT_SIZE_MULTI(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_BOOT_SIZE_MULTI_INDEX]) // Boot partition size
+#define SD_EXTCSD_ACC_SIZE(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_ACC_SIZE_INDEX]) // Access size
+#define SD_EXTCSD_HC_ERASE_GRP_SIZE(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_HC_ERASE_GRP_SIZE_INDEX]) // High-capacity erase unit size
+#define SD_EXTCSD_ERASE_TIMEOUT_MULT(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_ERASE_TIMEOUT_MULT_INDEX]) // High-capacity erase timeout
+#define SD_EXTCSD_REL_WR_SEC_C(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_REL_WR_SEC_C_INDEX]) // Reliable write sector count
+#define SD_EXTCSD_HC_WP_GRP_SIZE(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_HC_WP_GRP_SIZE_INDEX]) // High-capacity write protect group size
+#define SD_EXTCSD_S_C_VCC(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_S_C_VCC_INDEX]) // Sleep current(VCC)
+#define SD_EXTCSD_S_C_VCCQ(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_S_C_VCCQ_INDEX]) // Sleep current(VCCQ)
+#define SD_EXTCSD_S_A_TIMEOUT(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_S_A_TIMEOUT_INDEX]) // Sleep/awake timeout
+#define SD_EXTCSD_SEC_COUNT(pSd) ((MMC_EXTCSD(pSd)[SD_EXTCSD_SEC_COUNT_INDEX]) + \
+ (MMC_EXTCSD(pSd)[SD_EXTCSD_SEC_COUNT_INDEX+1] << 8 ) + \
+ (MMC_EXTCSD(pSd)[SD_EXTCSD_SEC_COUNT_INDEX+2] << 16 ) + \
+ (MMC_EXTCSD(pSd)[SD_EXTCSD_SEC_COUNT_INDEX+3] << 24 )) //Sector Count
+#define SD_EXTCSD_MIN_PERF_W_8_52(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_MIN_PERF_W_8_52_INDEX]) // Minimum Write Performance for 8bit at 52MHz
+#define SD_EXTCSD_MIN_PERF_R_8_52(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_MIN_PERF_R_8_52_INDEX]) // Minimum Read Performance for 8bit at 52MHz
+#define SD_EXTCSD_MIN_PERF_W_8_26_4_52(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_MIN_PERF_W_8_26_4_52_INDEX]) // Minimum Write Performance for 8bit at 26MHz, for 4bit at 52MHz
+#define SD_EXTCSD_MIN_PERF_R_8_26_4_52(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_MIN_PERF_R_8_26_4_52_INDEX]) // Minimum Read Performance for 8bit at 26MHz, for 4bit at 52MHz
+#define SD_EXTCSD_MIN_PERF_W_4_26(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_MIN_PERF_W_4_26_INDEX]) // Minimum Write Performance for 4bit at 26MHz
+#define SD_EXTCSD_MIN_PERF_R_4_26(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_MIN_PERF_R_4_26_INDEX]) // Minimum Read Performance for 4bit at 26MHz
+#define SD_EXTCSD_PWR_CL_26_360(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_PWR_CL_26_360_INDEX]) // Power class for 26MHz at 3.6v
+#define SD_EXTCSD_PWR_CL_52_360(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_PWR_CL_52_360_INDEX]) // Power class for 52MHz at 3.6v
+#define SD_EXTCSD_PWR_CL_26_195(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_PWR_CL_26_195_INDEX]) // Power class for 26MHz at 1.95v
+#define SD_EXTCSD_PWR_CL_52_195(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_PWR_CL_52_195_INDEX]) // Power class for 52MHz at 1.95v
+#define SD_EXTCSD_CARD_TYPE(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_CARD_TYPE_INDEX]) // Card type
+#define SD_EXTCSD_CSD_STRUCTURE(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_CSD_STRUCTURE_INDEX]) // CSD structure version
+#define SD_EXTCSD_EXT_CSD_REV(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_EXT_CSD_REV_INDEX]) // Extended CSD structure version
+#define SD_EXTCSD_CMD_SET(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_CMD_SET_INDEX]) // Command set
+#define SD_EXTCSD_CMD_SET_REV(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_CMD_SET_REV_INDEX]) // Command set revision
+#define SD_EXTCSD_POWER_CLASS(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_POWER_CLASS_INDEX]) // Power class
+#define SD_EXTCSD_HS_TIMING(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_HS_TIMING_INDEX]) // High-speed interface timing
+#define SD_EXTCSD_BUS_WIDTH(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_BUS_WIDTH_INDEX]) // Bus width mode
+#define SD_EXTCSD_ERASED_MEM_CONT(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_ERASED_MEM_CONT_INDEX]) // Erased memory content
+#define SD_EXTCSD_BOOT_CONFIG(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_BOOT_CONFIG_INDEX]) // Boot configuration
+#define SD_EXTCSD_BOOT_BUS_WIDTH(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_BOOT_BUS_WIDTH_INDEX]) // Boot bus width
+#define SD_EXTCSD_ERASE_GROUP_DEF(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_ERASE_GROUP_DEF_INDEX]) // High-density erase group definition
+
+// EXTCSD total size and block number
+#define SD_EXTCSD_TOTAL_SIZE(pSd) (SD_EXTCSD_SEC_COUNT(pSd)*512)
+#define SD_EXTCSD_BLOCKNR(pSd) (SD_EXTCSD_SEC_COUNT(pSd))
+
+// Bus width Byte
+#define SD_EXTCSD_BUS_WIDTH_1BIT (0x0UL)
+#define SD_EXTCSD_BUS_WIDTH_4BIT (0x1UL)
+#define SD_EXTCSD_BUS_WIDTH_8BIT (0x2UL)
+
+// High speed mode
+#define SD_EXTCSD_HS_TIMING_ENABLE (0x1UL)
+#define SD_EXTCSD_HS_TIMING_DISABLE (0x0UL)
+
+// Boot config
+#define SD_EXTCSD_BOOT_PARTITION_ACCESS (0x7UL) // boot partition access
+#define SD_EXTCSD_BOOT_PART_NO_ACCESS (0x0UL)
+#define SD_EXTCSD_BOOT_PART_RW_PART1 (0x1UL)
+#define SD_EXTCSD_BOOT_PART_RW_PART2 (0x2UL)
+#define SD_EXTCSD_BOOT_PARTITION_ENABLE (0x7UL << 3) // boot partition enable
+#define SD_EXTCSD_BOOT_PART_DISABLE (0x0UL << 3)
+#define SD_EXTCSD_BOOT_PART_ENABLE_PART1 (0x1UL << 3)
+#define SD_EXTCSD_BOOT_PART_ENABLE_PART2 (0x2UL << 3)
+#define SD_EXTCSD_BOOT_PART_ENABLE_USER (0x7UL << 3)
+#define SD_EXTCSD_BOOT_PARTITION_ACK (0x1UL << 7) // boot acknowledge
+#define SD_EXTCSD_BOOT_PART_NOACK (0x0UL << 7)
+#define SD_EXTCSD_BOOT_PART_ACK (0x1UL << 7)
+
+// Boot bus width
+#define SD_EXTCSD_BOOT_BUS_WIDTH_BIT (0x3UL) // boot bus width
+#define SD_EXTCSD_BOOT_BUS_1BIT (0x0UL)
+#define SD_EXTCSD_BOOT_BUS_4BIT (0x1UL)
+#define SD_EXTCSD_BOOT_BUS_8BIT (0x2UL)
+#define SD_EXTCSD_RESET_BOOT_BUS_WIDTH_BIT (0x1UL << 2) // boot bus width
+#define SD_EXTCSD_RESET_BOOT_BUS (0x0UL << 2)
+#define SD_EXTCSD_RETAIN_BOOT_BUS (0x1UL << 2)
+
+// Mode Switch Arguments for CMD6
+#define MMC_CMD6_ARG_ACCESS
+#define MMC_CMD6_ARG_INDEX
+#define MMC_CMD6_ARG_VALUE
+#define MMC_CMD6_ARG_CMDSET
+
+// SDIO functions
+#define SDIO_CIA 0 /// SDIO Function 0 (CIA)
+#define SDIO_FN0 0 /// SDIO Function 0
+#define SDIO_FN1 1 /// SDIO Function 1
+#define SDIO_FN2 2 /// SDIO Function 2
+#define SDIO_FN3 3 /// SDIO Function 3
+#define SDIO_FN4 4 /// SDIO Function 4
+#define SDIO_FN5 5 /// SDIO Function 5
+#define SDIO_FN6 6 /// SDIO Function 6
+#define SDIO_FN7 7 /// SDIO Function 7
+
+// SDIO Card Common Control Registers (CCCR)
+#define SDIO_CCCR_REG 0x00 /// CCCR/SDIO revision (RO)
+#define SDIO_CCCR (0xFUL << 0)/// CCCR Format Version number
+#define SDIO_CCCR_1_00 (0x0UL << 0)/// CCCR/FBR Version 1.00
+#define SDIO_CCCR_1_10 (0x1UL << 0)/// CCCR/FBR Version 1.10
+#define SDIO_CCCR_1_20 (0x2UL << 0)/// CCCR/FBR Version 1.20
+#define SDIO_SDIO (0xFUL << 4)/// SDIO Specification
+#define SDIO_SDIO_1_00 (0x0UL << 4)/// SDIO Specification 1.00
+#define SDIO_SDIO_1_10 (0x1UL << 4)/// SDIO Specification 1.10
+#define SDIO_SDIO_1_20 (0x2UL << 4)/// SDIO Specification 1.20(unreleased)
+#define SDIO_SDIO_2_00 (0x3UL << 4)/// SDIO Specification Version 2.00
+#define SDIO_SD_REV_REG 0x01 /// SD Specification Revision (RO)
+#define SDIO_SD (0xFUL << 0)/// SD Physical Specification
+#define SDIO_SD_1_01 (0x0UL << 0)/// SD 1.01 (Mar 2000)
+#define SDIO_SD_1_10 (0x1UL << 0)/// SD 1.10 (Oct 2004)
+#define SDIO_SD_2_00 (0x2UL << 0)/// SD 2.00 (May 2006)
+#define SDIO_IOE_REG 0x02 /// I/O Enable (R/W)
+#define SDIO_IOE 0xFEUL /// Enable/Disable Function
+#define SDIO_IOE_FN1 (0x1UL << 1)/// Function 1 Enable/Disable
+#define SDIO_IOE_FN2 (0x1UL << 2)/// Function 2 Enable/Disable
+#define SDIO_IOE_FN3 (0x1UL << 3)/// Function 3 Enable/Disable
+#define SDIO_IOE_FN4 (0x1UL << 4)/// Function 4 Enable/Disable
+#define SDIO_IOE_FN5 (0x1UL << 5)/// Function 5 Enable/Disable
+#define SDIO_IOE_FN6 (0x1UL << 6)/// Function 6 Enable/Disable
+#define SDIO_IOE_FN7 (0x1UL << 7)/// Function 7 Enable/Disable
+#define SDIO_IOR_REG 0x03 /// I/O Ready (RO)
+#define SDIO_IOR 0xFEUL /// I/O Function Ready
+#define SDIO_IOR_FN1 (0x1UL << 1)/// Function 1 ready
+#define SDIO_IOR_FN2 (0x1UL << 2)/// Function 2 ready
+#define SDIO_IOR_FN3 (0x1UL << 3)/// Function 3 ready
+#define SDIO_IOR_FN4 (0x1UL << 4)/// Function 4 ready
+#define SDIO_IOR_FN5 (0x1UL << 5)/// Function 5 ready
+#define SDIO_IOR_FN6 (0x1UL << 6)/// Function 6 ready
+#define SDIO_IOR_FN7 (0x1UL << 7)/// Function 7 ready
+#define SDIO_IEN_REG 0x04 /// Int Enable
+#define SDIO_IENM 0x01UL /// Int Enable Master (R/W)
+#define SDIO_IEN 0xFEUL /// Int Enable for function (R/W)
+#define SDIO_IEN_FN1 (0x1UL << 1)/// Function 1 Int Enable
+#define SDIO_IEN_FN2 (0x1UL << 2)/// Function 2 Int Enable
+#define SDIO_IEN_FN3 (0x1UL << 3)/// Function 3 Int Enable
+#define SDIO_IEN_FN4 (0x1UL << 4)/// Function 4 Int Enable
+#define SDIO_IEN_FN5 (0x1UL << 5)/// Function 5 Int Enable
+#define SDIO_IEN_FN6 (0x1UL << 6)/// Function 6 Int Enable
+#define SDIO_IEN_FN7 (0x1UL << 7)/// Function 7 Int Enable
+#define SDIO_INT_REG 0x05 /// Int Pending
+#define SDIO_INT 0xFE /// Int Pending for functions (RO)
+#define SDIO_INT_FN1 (0x1UL << 1)/// Function 1 Int pending
+#define SDIO_INT_FN2 (0x1UL << 2)/// Function 2 Int pending
+#define SDIO_INT_FN3 (0x1UL << 3)/// Function 3 Int pending
+#define SDIO_INT_FN4 (0x1UL << 4)/// Function 4 Int pending
+#define SDIO_INT_FN5 (0x1UL << 5)/// Function 5 Int pending
+#define SDIO_INT_FN6 (0x1UL << 6)/// Function 6 Int pending
+#define SDIO_INT_FN7 (0x1UL << 7)/// Function 7 Int pending
+#define SDIO_IOA_REG 0x06 /// I/O Abort
+#define SDIO_AS (0x7UL << 0)/// Abort Select In Order (WO)
+#define SDIO_AS_FN1 (0x1UL << 0)/// Abort function 1 IO
+#define SDIO_AS_FN2 (0x2UL << 0)/// Abort function 2 IO
+#define SDIO_AS_FN3 (0x3UL << 0)/// Abort function 3 IO
+#define SDIO_AS_FN4 (0x4UL << 0)/// Abort function 4 IO
+#define SDIO_AS_FN5 (0x5UL << 0)/// Abort function 5 IO
+#define SDIO_AS_FN6 (0x6UL << 0)/// Abort function 6 IO
+#define SDIO_AS_FN7 (0x7UL << 0)/// Abort function 7 IO
+#define SDIO_RES (0x1UL << 3)/// IO CARD RESET (WO)
+#define SDIO_BUS_CTRL_REG 0x07 /// Bus Interface Control
+#define SDIO_BUSWIDTH (0x3UL << 0)/// Data bus width (R/W)
+#define SDIO_BUSWIDTH_1B (0x0UL << 0)/// 1-bit data bus
+#define SDIO_BUSWIDTH_4B (0x2UL << 0)/// 4-bit data bus
+#define SDIO_ECSI (0x1UL << 5)/// Enable Continuous SPI interrupt (R/W)
+#define SDIO_SCSI (0x1UL << 6)/// Support Continuous SPI interrupt (RO)
+#define SDIO_CD (0x1UL << 7)/// Connect(0)/Disconnect(1) pull-up on CD/DAT[3] (R/W)
+#define SDIO_CAP_REG 0x08 /// Card Capability
+#define SDIO_SDC (0x1UL << 0)/// Support Direct Commands during data transfer (RO)
+#define SDIO_SMB (0x1UL << 1)/// Support Multi-Block (RO)
+#define SDIO_SRW (0x1UL << 2)/// Support Read Wait (RO)
+#define SDIO_SBS (0x1UL << 3)/// Support Suspend/Resume (RO)
+#define SDIO_S4MI (0x1UL << 4)/// Support interrupt between blocks of data in 4-bit SD mode (RO)
+#define SDIO_E4MI (0x1UL << 5)/// Enable interrupt between blocks of data in 4-bit SD mode (R/W)
+#define SDIO_LSC (0x1UL << 6)/// Low-Speed Card (RO)
+#define SDIO_4BLS (0x1UL << 7)/// 4-bit support for Low-Speed Card (RO)
+#define SDIO_CIS_PTR_REG 0x09 /// Pointer to CIS (3B, LSB first)
+#define SDIO_BUS_SUSP_REG 0x0C /// Bus Suspend
+#define SDIO_BS (0x1UL << 0)/// Bus Status (transfer on DAT[x] lines) (RO)
+#define SDIO_BR (0x1UL << 1)/// Bus Release Request/Status (R/W)
+#define SDIO_FUN_SEL_REG 0x0D /// Function select
+#define SDIO_DF (0x1UL << 7)/// Resume Data Flag (RO)
+#define SDIO_FS (0xFUL << 0)/// Select Function (R/W)
+#define SDIO_FS_CIA (0x0UL << 0)/// Select CIA (function 0)
+#define SDIO_FS_FN1 (0x1UL << 0)/// Select Function 1
+#define SDIO_FS_FN2 (0x2UL << 0)/// Select Function 2
+#define SDIO_FS_FN3 (0x3UL << 0)/// Select Function 3
+#define SDIO_FS_FN4 (0x4UL << 0)/// Select Function 4
+#define SDIO_FS_FN5 (0x5UL << 0)/// Select Function 5
+#define SDIO_FS_FN6 (0x6UL << 0)/// Select Function 6
+#define SDIO_FS_FN7 (0x7UL << 0)/// Select Function 7
+#define SDIO_FS_MEM (0x8UL << 0)/// Select memory in combo card
+#define SDIO_EXEC_REG 0x0E /// Exec Flags (RO)
+#define SDIO_EXM (0x1UL << 0)/// Executing status of memory
+#define SDIO_EX (0xFEUL) /// Executing status of functions
+#define SDIO_EX_FN1 (0x1UL << 1)/// Executing status of function 1
+#define SDIO_EX_FN2 (0x1UL << 2)/// Executing status of function 2
+#define SDIO_EX_FN3 (0x1UL << 3)/// Executing status of function 3
+#define SDIO_EX_FN4 (0x1UL << 4)/// Executing status of function 4
+#define SDIO_EX_FN5 (0x1UL << 5)/// Executing status of function 5
+#define SDIO_EX_FN6 (0x1UL << 6)/// Executing status of function 6
+#define SDIO_EX_FN7 (0x1UL << 7)/// Executing status of function 7
+#define SDIO_READY_REG 0x0F /// Ready Flags (RO)
+#define SDIO_RFM (0x1UL << 0)/// Ready Flag for memory
+#define SDIO_RF (0xFEUL) /// Ready Flag for functions
+#define SDIO_RF_FN1 (0x1UL << 1)/// Ready Flag for function 1
+#define SDIO_RF_FN2 (0x1UL << 2)/// Ready Flag for function 2
+#define SDIO_RF_FN3 (0x1UL << 3)/// Ready Flag for function 3
+#define SDIO_RF_FN4 (0x1UL << 4)/// Ready Flag for function 4
+#define SDIO_RF_FN5 (0x1UL << 5)/// Ready Flag for function 5
+#define SDIO_RF_FN6 (0x1UL << 6)/// Ready Flag for function 6
+#define SDIO_RF_FN7 (0x1UL << 7)/// Ready Flag for function 7
+#define SDIO_FN0_BLKSIZ_REG 0x10 /// FN0 Block Size (2B, LSB first) (R/W)
+#define SDIO_POWER_REG 0x12 /// Power Control
+#define SDIO_SMPC (0x1UL << 0)/// Support Master Power Control (RO)
+#define SDIO_EMPC (0x1UL << 1)/// Enable Master Power Control (R/W)
+#define SDIO_HS_REG 0x13 /// High-Speed
+#define SDIO_SHS (0x1UL << 0)/// Support High-Speed (RO)
+#define SDIO_EHS (0x1UL << 1)/// Enable High-Speed (R/W)
+
+// SDIO Function Basic Registers (FBR)
+#define SDIO_FBR_ADDR(fn, x) (0x100*(fn) + (x))
+#define SDIO_FBR_CSA_IF 0x0 /// CSA and function interface code (RO)
+#define SDIO_IFC (0xFUL << 0)/// Standard SDIO Fun Interface Code
+#define SDIO_IFC_NO_IF (0x0UL << 0)/// No SDIO standard interface
+#define SDIO_IFC_UART (0x1UL << 0)/// UART
+#define SDIO_IFC_TA_BT (0x2UL << 0)/// Type-A Bluetooth
+#define SDIO_IFC_TB_BT (0x3UL << 0)/// Type-B Bluetooth
+#define SDIO_IFC_GPS (0x4UL << 0)/// GPS
+#define SDIO_IFC_CAMERA (0x5UL << 0)/// Camera
+#define SDIO_IFC_PHS (0x6UL << 0)/// PHS
+#define SDIO_IFC_WLAN (0x7UL << 0)/// WLAN
+#define SDIO_IFC_ATA (0x8UL << 0)/// Embedded SDIO-ATA
+#define SDIO_IFC_EXT (0xFUL << 0)/// Check EXT interface code
+#define SDIO_SCSA (0x1UL << 6)/// Function supports Code Storage Area (CSA)
+#define SDIO_FBR_CSA (0x1UL << 7)/// Function CSA enable
+#define SDIO_FBR_EXT_IF 0x1 /// Extended function interface code (RO)
+#define SDIO_FBR_PWR 0x2 /// function power control
+#define SDIO_SPS (0x1UL << 0)/// function support power selection (RO)
+#define SDIO_EPS (0x1UL << 1)/// Low Current Mode/High Current Mode (R/W)
+#define SDIO_FBR_CIS_PTR 0x9 /// Address pointer to function CIS (3B, LSB first) (RO)
+#define SDIO_FBR_CSA_PTR 0xC /// Address pointer to CSA (3B, LSB first) (R/W)
+#define SDIO_FBR_CSA_DATA 0xF /// Read/Write fifo to CSA (R/W)
+#define SDIO_FBR_BLK_SIZ 0x10 /// Block size (2B, LSB first) (R/W)
+
+// SDIO Card Metaformat
+#define CISTPL_NULL 0x00 /// Null tuple (PCMCIA 3.1.9)
+#define CISTPL_DEVICE 0x01 /// Device tuple (PCMCIA 3.2.2)
+#define CISTPL_CHECKSUM 0x10 /// Checksum control (PCMCIA 3.1.1)
+#define CISTPL_VERS_1 0x15 /// Level 1 version (PCMCIA 3.2.10)
+#define CISTPL_ALTSTR 0x16 /// Alternate Language String (PCMCIA 3.2.1)
+#define CISTPL_MANFID 0x20 /// Manufacturer Identification String (PCMCIA 3.2.9)
+#define CISTPL_FUNCID 0x21 /// Function Identification (PCMCIA 3.2.7)
+#define CISTPL_FUNCE 0x22 /// Function Extensions (PCMCIA 3.2.6)
+#define CISTPL_SDIO_STD 0x91 /// Additional information for SDIO (PCMCIA 6.1.2)
+#define CISTPL_SDIO_EXT 0x92 /// Reserved for future SDIO (PCMCIA 6.1.3)
+#define CISTPL_END 0xFF /// The End-of-chain Tuple (PCMCIA 3.1.2)
+
+//------------------------------------------------------------------------------
+// Types
+//------------------------------------------------------------------------------
+
+typedef MciCallback SdCallback;
+typedef MciCmd SdCmd;
+typedef Mci SdDriver;
+
+//------------------------------------------------------------------------------
+/// Sdcard driver structure. It holds the current command being processed and
+/// the SD card address.
+//------------------------------------------------------------------------------
+typedef struct _SdCard {
+
+ /// Pointer to the underlying MCI driver.
+ SdDriver *pSdDriver;
+ /// Current MCI command being processed.
+ SdCmd command;
+ /// Card IDentification (CID register)
+ unsigned int cid[4];
+ /// Card-specific data (CSD register)
+ unsigned int csd[4];
+ /// SD SCR(64 bit), Status(512 bit) or MMC EXT_CSD(512 bytes) register
+ unsigned int extData[512 / 4];
+ /// Previous access block number.
+ unsigned int preBlock;
+ /// Card total size
+ unsigned int totalSize;
+ /// Card block number
+ unsigned int blockNr;
+ /// Card option command support list
+ unsigned int optCmdBitMap;
+ /// Card CSD TRANS_SPEED
+ unsigned int transSpeed;
+ /// SD card current address.
+ unsigned short cardAddress;
+ /// Card type
+ unsigned char cardType;
+ /// Card access mode
+ unsigned char mode;
+ /// State after sd command complete
+ unsigned char state;
+} SdCard;
+
+typedef struct _MmcCmd6Arg {
+
+ /// Access
+ unsigned char access;
+ /// Index
+ unsigned char index;
+ /// Value
+ unsigned char value;
+ /// Cmd Set
+ unsigned char cmdSet;
+} MmcCmd6Arg;
+
+typedef struct _SdCmd6Arg {
+ unsigned int accessMode:4, /// [ 3: 0] function group 1, access mode
+ command:4, /// [ 7: 4] function group 2, command system
+ reserveFG3:4, /// [11: 8] function group 3, 0xF or 0x0
+ reserveFG4:4, /// [15:12] function group 4, 0xF or 0x0
+ reserveFG5:4, /// [19:16] function group 5, 0xF or 0x0
+ reserveFG6:4, /// [23:20] function group 6, 0xF or 0x0
+ reserved:7, /// [30:24] reserved 0
+ mode:1; /// [31 ] Mode, 0: Check, 1: Switch
+} SdCmd6Arg;
+
+/// General header struct for Tuple
+typedef struct _CisTplHeader {
+ unsigned char tpl_code; /// Tuple code
+ unsigned char tpl_link; /// Link to next tuple
+} CisTplHeader;
+
+///
+typedef struct _CisTpl_ManfID {
+ unsigned char tpl_code; /// CISTPL_MANFID (20H)
+ unsigned char tpl_link; /// Link to next tuple (at least 4)
+ unsigned char tplmid_manf[2]; /// SDIO Card manufacturer code
+ unsigned char tplmid_card[2]; /// manufacturer information (Part Nb, Rev.)
+} CisTpl_ManfID;
+
+/// Function Identification Tuple
+typedef struct _CisTpl_FuncID {
+ unsigned char tpl_code; /// CISTPL_FUNCID (0x21)
+ unsigned char tpl_link; /// Link to next tuple (0x02)
+ unsigned char tplfid_function; /// Card function code (0x0C)
+ unsigned char tplfid_sysinit; /// System initialization bit mask (0x00)
+} CisTpl_FuncID;
+
+/// Function Extenstion Tuple
+typedef struct _CisTpl_FuncE {
+ unsigned char tpl_code; /// CISTPL_FUNCE (0x22)
+ unsigned char tpl_link; /// Link to next tuple
+ unsigned char tplfe_type; /// Type of extended data
+ unsigned char tplfe_data[1]; /// Function information
+} CisTpl_FuncE;
+
+/// Tuple for Function 0 (common)
+typedef struct _CisTpl_Func0 {
+ unsigned char tpl_code; /// CISTPL_FUNCE (0x22)
+ unsigned char tpl_link; /// Link to next tuple (0x04)
+ unsigned char tplfe_type; /// Type of extended data (0x00)
+ unsigned char tplfe_fn0_blk_size[2];/// Max block size and byte count
+ unsigned char tple_max_tran_speed; /// Indicates the max transfer rate
+} CisTpl_Func0;
+
+/// Tuple for Function 1-7
+typedef struct _CisTpl_FuncN {
+ unsigned char tpl_code; /// CISTPL_FUNCE (0x22)
+ unsigned char tpl_link; /// Link to next tuple (0x2A)
+ unsigned char tplfe_type; /// Type of extended data (0x01)
+ unsigned char tplfe_function_info;/// Bits significant information
+ unsigned char tplfe_std_io_rev; /// Version level of App Spec. for STD SDIO
+ unsigned char tplfe_card_psn[4];/// Product Serial Number
+ unsigned char tplfe_csa_size[4];/// Size of the CSA space
+ unsigned char tplfe_csa_property;/// Flags identifying properties of CSA
+ unsigned char tplfe_max_blk_size[2];/// Max block size and byte count
+ unsigned char tplfe_ocr[4]; /// OCR value (SD Spec.)
+ unsigned char tplfe_op_min_pwr; /// Min current in mA
+ unsigned char tplfe_op_avg_pwr; /// Avg current in mA
+ unsigned char tplfe_op_max_pwr; /// Max(peak) current in mA
+ unsigned char tplfe_sb_min_pwr; /// Min standby current in mA
+ unsigned char tplfe_sb_avg_pwr; /// Avg standby current in mA
+ unsigned char tplfe_sb_max_pwr; /// Max standby current in mA
+ unsigned char tplfe_min_bw[2]; /// Min data transfer bandwidth, in KB/s
+ unsigned char tplfe_opt_bw[2]; /// Optimum data transfer bandwidth, in KB/s
+ unsigned char tplfe_enable_timeout_val[2];/// Time out IOEx->IORx, in 10ms
+ unsigned char tplfe_sp_avg_pwr_3_3_v[2];/// same as tplfe_op_avg_pwr
+ unsigned char tplfe_sp_max_pwr_3_3_v[2];/// same as tplfe_op_max_pwr
+ unsigned char tplfe_hg_avg_pwr_3_3_v[2];/// Higher Current Mode avg current in mA
+ unsigned char tplfe_hg_max_pwr_3_3_v[2];/// Higher Current Mode peak current in mA
+ unsigned char tplfe_lp_avg_pwr_3_3_v[2];/// Lower Current Mode avg current in mA
+ unsigned char tplfe_lp_max_pwr_3_3_v[2];/// Lower Current Mode avg current in mA
+} CisTpl_FuncN;
+
+//------------------------------------------------------------------------------
+// Global functions
+//------------------------------------------------------------------------------
+
+extern unsigned char SD_Init(SdCard *pSd,
+ SdDriver *pSdDriver);
+
+extern unsigned char SDIO_ReadDirect(SdCard * pSd,
+ unsigned char funNb,
+ unsigned int address,
+ unsigned char * pBytes,
+ unsigned int size);
+extern unsigned char SDIO_WriteDirect(SdCard * pSd,
+ unsigned char funNb,
+ unsigned int address,
+ unsigned char byte);
+extern unsigned char SDIO_ReadBytes(SdCard * pSd,
+ unsigned char funNb,
+ unsigned int address,
+ unsigned char isFixedAddr,
+ unsigned char * pBytes,
+ unsigned int size);
+extern unsigned char SDIO_WriteBytes(SdCard * pSd,
+ unsigned char funNb,
+ unsigned int address,
+ unsigned char isFixedAddr,
+ unsigned char * pBytes,
+ unsigned int size);
+
+extern unsigned char SD_Read(SdCard *pSd,
+ unsigned int address,
+ void *pData,
+ unsigned short length,
+ SdCallback pCallback,
+ void *pArgs);
+
+extern unsigned char SD_Write(SdCard *pSd,
+ unsigned int address,
+ void *pData,
+ unsigned short length,
+ SdCallback pCallback,
+ void *pArgs);
+
+extern unsigned char SD_ReadBlock(
+ SdCard *pSd,
+ unsigned int address,
+ unsigned short nbBlocks,
+ unsigned char *pData);
+
+extern unsigned char SD_WriteBlock(
+ SdCard *pSd,
+ unsigned int address,
+ unsigned short nbBlocks,
+ const unsigned char *pData);
+
+extern unsigned char SD_Stop(SdCard *pSd, SdDriver *pSdDriver);
+
+extern unsigned char SD_HighSpeedMode(SdCard *pSd,
+ unsigned char cardHsMode);
+
+extern unsigned char MMC_SetupBootMode(SdCard * pSd,
+ unsigned char resetBus,
+ unsigned char busWidth,
+ unsigned char bootPart,
+ unsigned char accPart,
+ unsigned char bootAck);
+
+extern unsigned char MMC_BootInit(SdCard * pSd);
+extern unsigned char MMC_BootRead(SdCard * pSd,
+ unsigned int nbBlocks,
+ unsigned char * pData);
+extern unsigned char MMC_BootStop(SdCard * pSd);
+
+extern unsigned int MMC_GetTotalSizeKB(SdCard *pSd);
+
+extern void SDIO_DisplayCardInformation(SdCard *pSd);
+
+extern void SD_DisplayRegisterCID(SdCard *pSd);
+
+extern void SD_DisplayRegisterCSD(SdCard *pSd);
+
+extern void SD_DisplayRegisterECSD(SdCard * pSd);
+
+extern void SD_DisplayRegisterSCR(SdCard * pSd);
+
+extern void SD_DisplaySdStatus(SdCard * pSd);
+
+#endif //#ifndef SDCARD_H
+
diff --git a/memories/sdmmc/sdmmc_spi.c b/memories/sdmmc/sdmmc_spi.c
new file mode 100644
index 0000000..73426a1
--- /dev/null
+++ b/memories/sdmmc/sdmmc_spi.c
@@ -0,0 +1,1453 @@
+/* ----------------------------------------------------------------------------
+ * ATMEL Microcontroller Software Support
+ * ----------------------------------------------------------------------------
+ * Copyright (c) 2008, Atmel Corporation
+
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the disclaimer below.
+ *
+ * Atmel's name may not be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
+ * DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ----------------------------------------------------------------------------
+ */
+
+//------------------------------------------------------------------------------
+// Headers
+//------------------------------------------------------------------------------
+
+#include "sdmmc_spi.h"
+#include "sdspi.h"
+#include <board.h>
+#include <utility/assert.h>
+#include <utility/trace.h>
+
+#include <string.h>
+
+//------------------------------------------------------------------------------
+// Local constants
+//------------------------------------------------------------------------------
+
+// SD card operation states
+#define SD_STATE_STBY 0
+#define SD_STATE_DATA 1
+#define SD_STATE_RCV 2
+
+// Card type
+#define UNKNOWN_CARD 0
+#define CARD_SD 1
+#define CARD_SDHC 2
+#define CARD_MMC 3
+
+// Delay between sending MMC commands
+#define MMC_DELAY 0x4FF
+
+//#define SD_ADDRESS(pSd, address) (((pSd)->cardType == CARD_SDHC) ? \
+// (address):((address) << SD_BLOCK_SIZE_BIT))
+#define SD_ADDRESS(pSd, address) \
+ ( ((pSd)->totalSize == 0xFFFFFFFF) ? \
+ (address) : ((address) << SD_BLOCK_SIZE_BIT) )
+
+//-----------------------------------------------------------------------------
+/// MMC/SD in SPI mode reports R1 status always, and R2 for SEND_STATUS
+/// R1 is the low order byte; R2 is the next highest byte, when present.
+//-----------------------------------------------------------------------------
+#define R1_SPI_IDLE (1 << 0)
+#define R1_SPI_ERASE_RESET (1 << 1)
+#define R1_SPI_ILLEGAL_COMMAND (1 << 2)
+#define R1_SPI_COM_CRC (1 << 3)
+#define R1_SPI_ERASE_SEQ (1 << 4)
+#define R1_SPI_ADDRESS (1 << 5)
+#define R1_SPI_PARAMETER (1 << 6)
+// R1 bit 7 is always zero
+#define R2_SPI_CARD_LOCKED (1 << 0)
+#define R2_SPI_WP_ERASE_SKIP (1 << 1)
+#define R2_SPI_LOCK_UNLOCK_FAIL R2_SPI_WP_ERASE_SKIP
+#define R2_SPI_ERROR (1 << 2)
+#define R2_SPI_CC_ERROR (1 << 3)
+#define R2_SPI_CARD_ECC_ERROR (1 << 4)
+#define R2_SPI_WP_VIOLATION (1 << 5)
+#define R2_SPI_ERASE_PARAM (1 << 6)
+#define R2_SPI_OUT_OF_RANGE (1 << 7)
+#define R2_SPI_CSD_OVERWRITE R2_SPI_OUT_OF_RANGE
+
+// Status register constants
+#define STATUS_READY_FOR_DATA (1 << 8)
+#define STATUS_IDLE (0 << 9)
+#define STATUS_READY (1 << 9)
+#define STATUS_IDENT (2 << 9)
+#define STATUS_STBY (3 << 9)
+#define STATUS_TRAN (4 << 9)
+#define STATUS_DATA (5 << 9)
+#define STATUS_RCV (6 << 9)
+#define STATUS_PRG (7 << 9)
+#define STATUS_DIS (8 << 9)
+#define STATUS_STATE (0xF << 9)
+
+//-----------------------------------------------------------------------------
+/// OCR Register
+//-----------------------------------------------------------------------------
+#define AT91C_VDD_16_17 (1 << 4)
+#define AT91C_VDD_17_18 (1 << 5)
+#define AT91C_VDD_18_19 (1 << 6)
+#define AT91C_VDD_19_20 (1 << 7)
+#define AT91C_VDD_20_21 (1 << 8)
+#define AT91C_VDD_21_22 (1 << 9)
+#define AT91C_VDD_22_23 (1 << 10)
+#define AT91C_VDD_23_24 (1 << 11)
+#define AT91C_VDD_24_25 (1 << 12)
+#define AT91C_VDD_25_26 (1 << 13)
+#define AT91C_VDD_26_27 (1 << 14)
+#define AT91C_VDD_27_28 (1 << 15)
+#define AT91C_VDD_28_29 (1 << 16)
+#define AT91C_VDD_29_30 (1 << 17)
+#define AT91C_VDD_30_31 (1 << 18)
+#define AT91C_VDD_31_32 (1 << 19)
+#define AT91C_VDD_32_33 (1 << 20)
+#define AT91C_VDD_33_34 (1 << 21)
+#define AT91C_VDD_34_35 (1 << 22)
+#define AT91C_VDD_35_36 (1 << 23)
+#define AT91C_CARD_POWER_UP_BUSY (1 << 31)
+
+#define AT91C_MMC_HOST_VOLTAGE_RANGE (AT91C_VDD_27_28 +\
+ AT91C_VDD_28_29 +\
+ AT91C_VDD_29_30 +\
+ AT91C_VDD_30_31 +\
+ AT91C_VDD_31_32 +\
+ AT91C_VDD_32_33)
+#define AT91C_CCS (1 << 30)
+
+// SPI_CMD Register Value
+#define AT91C_POWER_ON_INIT (0)
+
+//-----------------------------------------------------------------------------
+// Command Classes
+//-----------------------------------------------------------------------------
+//
+// Class 0, 2, 4, 5, 7 and 8 are mandatory and shall be supported by all SD Memory Cards.
+// Basic Commands (class 0)
+//
+// Cmd0 MCI + SPI
+#define AT91C_GO_IDLE_STATE_CMD (0)
+// Cmd1 SPI
+#define AT91C_MMC_SEND_OP_COND_CMD (1)
+// Cmd2 MCI
+#define AT91C_ALL_SEND_CID_CMD (2)
+// Cmd3 MCI
+#define AT91C_SET_RELATIVE_ADDR_CMD (3)
+// Cmd4 MCI
+//#define AT91C_SET_DSR_CMD (4)
+// cmd7 MCI
+#define AT91C_SEL_DESEL_CARD_CMD (7)
+// Cmd8 MCI + SPI
+#define AT91C_SEND_IF_COND (8)
+// Cmd9 MCI + SPI
+#define AT91C_SEND_CSD_CMD (9)
+// Cmd10 MCI + SPI
+#define AT91C_SEND_CID_CMD (10)
+// Cmd12 MCI + SPI
+#define AT91C_STOP_TRANSMISSION_CMD (12)
+// Cmd13 MCI + SPI
+#define AT91C_SEND_STATUS_CMD (13)
+// Cmd15 MCI
+//#define AT91C_GO_INACTIVE_STATE_CMD (15)
+// Cmd58 SPI
+#define AT91C_READ_OCR_CMD (58)
+// Cmd59 SPI
+#define AT91C_CRC_ON_OFF_CMD (59)
+//#define AT91C_MMC_ALL_SEND_CID_CMD (2)
+//#define AT91C_MMC_SET_RELATIVE_ADDR_CMD (3)
+//#define AT91C_MMC_READ_DAT_UNTIL_STOP_CMD (11)
+//#define AT91C_STOP_TRANSMISSION_SYNC_CMD (12)
+
+//*------------------------------------------------
+//* Class 2 commands: Block oriented Read commands
+//*------------------------------------------------
+// Cmd16
+#define AT91C_SET_BLOCKLEN_CMD (16)
+// Cmd17
+#define AT91C_READ_SINGLE_BLOCK_CMD (17)
+// Cmd18
+#define AT91C_READ_MULTIPLE_BLOCK_CMD (18)
+
+//*------------------------------------------------
+//* Class 4 commands: Block oriented write commands
+//*------------------------------------------------
+// Cmd24
+#define AT91C_WRITE_BLOCK_CMD (24)
+// Cmd25
+#define AT91C_WRITE_MULTIPLE_BLOCK_CMD (25)
+// Cmd27
+//#define AT91C_PROGRAM_CSD_CMD (27)
+
+//*----------------------------------------
+//* Class 5 commands: Erase commands
+//*----------------------------------------
+// Cmd32
+//#define AT91C_TAG_SECTOR_START_CMD (32)
+// Cmd33
+//#define AT91C_TAG_SECTOR_END_CMD (33)
+// Cmd38
+//#define AT91C_ERASE_CMD (38)
+
+//*----------------------------------------
+//* Class 7 commands: Lock commands
+//*----------------------------------------
+// Cmd42
+//#define AT91C_LOCK_UNLOCK (42)
+
+//*-----------------------------------------------
+// Class 8 commands: Application specific commands
+//*-----------------------------------------------
+// Cmd55
+#define AT91C_APP_CMD (55)
+// cmd 56
+//#define AT91C_GEN_CMD (56)
+// ACMD6
+#define AT91C_SDCARD_SET_BUS_WIDTH_CMD (6)
+// ACMD13
+//#define AT91C_SDCARD_STATUS_CMD (13)
+// ACMD22
+//#define AT91C_SDCARD_SEND_NUM_WR_BLOCKS_CMD (22)
+// ACMD23
+//#define AT91C_SDCARD_SET_WR_BLK_ERASE_COUNT_CMD (23)
+// ACMD41
+#define AT91C_SDCARD_APP_OP_COND_CMD (41)
+// ACMD42
+//#define AT91C_SDCARD_SET_CLR_CARD_DETECT_CMD (42)
+// ACMD51
+#define AT91C_SDCARD_SEND_SCR_CMD (51)
+
+//------------------------------------------------------------------------------
+// Local functions
+//------------------------------------------------------------------------------
+
+//------------------------------------------------------------------------------
+/// Delay some loop
+//------------------------------------------------------------------------------
+static void Delay(volatile unsigned int loop)
+{
+ for(;loop > 0; loop --);
+}
+
+//------------------------------------------------------------------------------
+/// Sends the current SD card driver command to the card.
+/// Returns 0 if successful; Otherwise, returns the transfer status code or
+/// SD_ERROR_DRIVER if there was a problem with the SD transfer.
+/// \param pSd Pointer to a SdCard driver instance.
+//------------------------------------------------------------------------------
+static unsigned char SendCommand(SdCard *pSd)
+{
+ SdCmd *pCommand = &(pSd->command);
+ SdDriver *pSdDriver = pSd->pSdDriver;
+ unsigned char error;
+ unsigned int i;
+
+ // Send command
+ SDSPI_NCS((SdSpi *)pSdDriver);
+
+ error = SDSPI_SendCommand((SdSpi *)pSdDriver, (SdSpiCmd *)pCommand);
+ if (error) {
+ TRACE_ERROR("SendCmd%d,%d (%d)\n\r",
+ pCommand->cmd & 0x3F, pCommand->conTrans,
+ error);
+ return SD_ERROR_DRIVER;
+ }
+
+ // Wait for command to complete
+ while (!SDSPI_IsTxComplete((SdSpiCmd *)pCommand));
+
+ // Delay between sending commands.
+ Delay(MMC_DELAY);
+
+ return pCommand->status;
+}
+
+//------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
+void DecodeR1(unsigned char R1)
+{
+ if( (R1 & R1_SPI_IDLE)==R1_SPI_IDLE) {
+ TRACE_DEBUG("R1_SPI_IDLE\n\r");
+ }
+ if( (R1 & R1_SPI_ERASE_RESET)==R1_SPI_ERASE_RESET) {
+ TRACE_DEBUG("R1_SPI_ERASE_RESET\n\r");
+ }
+ if( (R1 & R1_SPI_ILLEGAL_COMMAND)==R1_SPI_ILLEGAL_COMMAND) {
+ TRACE_DEBUG("R1_SPI_ILLEGAL_COMMAND\n\r");
+ }
+ if( (R1 & R1_SPI_COM_CRC)==R1_SPI_COM_CRC) {
+ TRACE_DEBUG("R1_SPI_COM_CRC\n\r");
+ }
+ if( (R1 & R1_SPI_ERASE_SEQ)==R1_SPI_ERASE_SEQ) {
+ TRACE_DEBUG("R1_SPI_ERASE_SEQ\n\r");
+ }
+ if( (R1 & R1_SPI_ADDRESS)==R1_SPI_ADDRESS) {
+ TRACE_DEBUG("R1_SPI_ADDRESS\n\r");
+ }
+ if( (R1 & R1_SPI_PARAMETER)==R1_SPI_PARAMETER) {
+ TRACE_DEBUG("R1_SPI_PARAMETER\n\r");
+ }
+}
+
+//------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
+void DecodeR2(unsigned char R2)
+{
+ if( (R2 & R2_SPI_CARD_LOCKED)==R2_SPI_CARD_LOCKED) {
+ TRACE_DEBUG("R2_SPI_CARD_LOCKED\n\r");
+ }
+ if( (R2 & R2_SPI_WP_ERASE_SKIP)==R2_SPI_WP_ERASE_SKIP) {
+ TRACE_DEBUG("R2_SPI_WP_ERASE_SKIP/R2_SPI_LOCK_UNLOCK_FAIL\n\r");
+ }
+ if( (R2 & R2_SPI_ERROR)==R2_SPI_ERROR) {
+ TRACE_DEBUG("R2_SPI_ERROR\n\r");
+ }
+ if( (R2 & R2_SPI_CC_ERROR)==R2_SPI_CC_ERROR) {
+ TRACE_DEBUG("R2_SPI_CC_ERROR\n\r");
+ }
+ if( (R2 & R2_SPI_CARD_ECC_ERROR)==R2_SPI_CARD_ECC_ERROR) {
+ TRACE_DEBUG("R2_SPI_CARD_ECC_ERROR\n\r");
+ }
+ if( (R2 & R2_SPI_WP_VIOLATION)==R2_SPI_WP_VIOLATION) {
+ TRACE_DEBUG("R2_SPI_WP_VIOLATION\n\r");
+ }
+ if( (R2 & R2_SPI_ERASE_PARAM)==R2_SPI_ERASE_PARAM) {
+ TRACE_DEBUG("R2_SPI_ERASE_PARAM\n\r");
+ }
+ if( (R2 & R2_SPI_OUT_OF_RANGE)==R2_SPI_OUT_OF_RANGE) {
+ TRACE_DEBUG("R2_SPI_OUT_OF_RANGE/R2_SPI_CSD_OVERWRITE\n\r");
+ }
+}
+
+//------------------------------------------------------------------------------
+/// Check SPI mode response 1.
+/// Returns 0 if no error; Otherwise, returns error.
+/// \param pResp Pointer to response token.
+//------------------------------------------------------------------------------
+static unsigned char SD_SPI_R1(unsigned char *pResp)
+{
+ DecodeR1(*pResp);
+
+ if((*pResp & 0x7E) !=0) {
+ // An error occured
+ return SD_ERROR_NORESPONSE;
+ }
+ else {
+ return 0;
+ }
+}
+
+//------------------------------------------------------------------------------
+/// Check SPI mode response 1b.
+/// Returns 0 if no error; Otherwise, returns error.
+/// \param pResp Pointer to response token.
+//------------------------------------------------------------------------------
+static unsigned char SD_SPI_R1b(unsigned char *pResp)
+{
+ // A zero value indicates card is busy.
+ // A non-zero value indicates the card is ready for the next command.
+ if( (*pResp) == 0 ) {
+ TRACE_INFO("Card is busy\n\r");
+ return SD_ERROR_BUSY;
+ }
+
+ DecodeR1(*(pResp+1));
+ if(((*(pResp+1)) & 0x7E) !=0) {
+ // An error occured
+ return SD_ERROR_NORESPONSE;
+ }
+ else {
+ return 0;
+ }
+}
+
+//------------------------------------------------------------------------------
+/// Check SPI mode response 2.
+/// Returns 0 if no error; Otherwise, returns error.
+/// \param pResp Pointer to response token.
+//------------------------------------------------------------------------------
+static unsigned char SD_SPI_R2(unsigned char *pResp)
+{
+ DecodeR1(*pResp);
+ DecodeR2(*(pResp+1));
+
+ if((( *pResp & 0x7e ) != 0) && (*(pResp+1) != 0)) {
+ return SD_ERROR_NORESPONSE;
+ }
+ else {
+ return 0;
+ }
+}
+
+//------------------------------------------------------------------------------
+/// Check SPI mode response 3.
+/// Returns 0 if no error; Otherwise, returns error.
+/// \param pResp Pointer to response token.
+//------------------------------------------------------------------------------
+static unsigned char SD_SPI_R3(unsigned char *pResp, unsigned int *ocr)
+{
+ // *pResp: bit 32-39: R1
+ if(( *pResp & 0x7e ) != 0) {
+ return SD_ERROR_NORESPONSE;
+ }
+ else {
+ // bit 0-31: OCR
+ *ocr = ((*(pResp+1) << 24) \
+ |(*(pResp+2) << 16) \
+ |(*(pResp+3) << 8) \
+ | *(pResp+4));
+ return 0;
+ }
+}
+
+//------------------------------------------------------------------------------
+/// Check SPI mode response 7.
+/// Returns 0 if no error; Otherwise, returns error.
+/// \param pResp Pointer to response token.
+//------------------------------------------------------------------------------
+static unsigned char SD_SPI_R7(unsigned char *pResp, unsigned char *isSdhc)
+{
+ *isSdhc = 0;
+
+ if(( *pResp & 0x7e ) != 0) {
+ return SD_ERROR_NORESPONSE;
+ }
+ else {
+ // *(pResp+4): bit 0- 7: check pattern
+ // *(pResp+3): bit 8-11: voltage accepted: 0x01: 2.7-3.6V
+ if ((*(pResp+3) == 0x1) && (*(pResp+4) == 0xAA)) {
+ *isSdhc = 1;
+ }
+ else {
+ *isSdhc = 0;
+ }
+ return 0;
+ }
+}
+
+//------------------------------------------------------------------------------
+/// Initialization delay: The maximum of 1 msec, 74 clock cycles and supply ramp
+/// up time.
+/// Returns the command transfer result (see SendCommand).
+/// \param pSd Pointer to a SdCard driver instance.
+//------------------------------------------------------------------------------
+static unsigned char Pon(SdCard *pSd)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned int response;
+ unsigned char error;
+
+ TRACE_DEBUG("Pon()\n\r");
+ memset(pCommand, 0, sizeof(SdCmd));
+ // Fill command information
+ pCommand->cmd = AT91C_POWER_ON_INIT;
+ pCommand->resType = 1;
+ pCommand->pResp = &response;
+
+ // Send command
+ error = SendCommand(pSd);
+ if( error == 0 ) {
+ error = SD_SPI_R1((unsigned char *)&response);
+ }
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// Resets all cards to idle state
+/// Returns the command transfer result (see SendCommand).
+/// \param pSd Pointer to a SdCard driver instance.
+//------------------------------------------------------------------------------
+static unsigned char Cmd0(SdCard *pSd)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned int response;
+ unsigned char error;
+
+ TRACE_DEBUG("Cmd0()\n\r");
+ memset(pCommand, 0, sizeof(SdCmd));
+ // Fill command information
+ pCommand->cmd = AT91C_GO_IDLE_STATE_CMD;
+ pCommand->resType = 1;
+ pCommand->pResp = &response;
+
+ // send command
+ error = SendCommand(pSd);
+ if (error == 0)
+ error = SD_SPI_R1((unsigned char *)&response);
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// MMC send operation condition command.
+/// Sends host capacity support information and activates the card's
+/// initialization process.
+/// Returns the command transfer result (see SendCommand).
+/// \param pSd Pointer to a SdCard driver instance.
+//------------------------------------------------------------------------------
+static unsigned char Cmd1(SdCard *pSd)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+ unsigned int response;
+
+ TRACE_DEBUG("Cmd1()\n\r");
+ memset(pCommand, 0, sizeof(SdCmd));
+ // Fill command information
+ pCommand->cmd = AT91C_MMC_SEND_OP_COND_CMD;
+ pCommand->arg = AT91C_MMC_HOST_VOLTAGE_RANGE;
+ pCommand->resType = 1;
+ pCommand->pResp = &response;
+
+ // send command
+ error = SendCommand(pSd);
+ if (error) {
+ return error;
+ }
+
+ error = SD_SPI_R1((unsigned char *)&response);
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// Sends SD Memory Card interface
+/// condition, which includes host supply
+/// voltage information and asks the card
+/// whether card supports voltage.
+/// Returns 0 if successful; otherwise returns SD_ERROR_NORESPONSE if the card did
+/// not answer the command, or SD_ERROR_DRIVER.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param supplyVoltage Expected supply voltage.
+//------------------------------------------------------------------------------
+static unsigned char Cmd8(SdCard *pSd, unsigned char supplyVoltage)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned int response[2];
+ unsigned char error;
+ unsigned char isSdhc;
+
+ TRACE_DEBUG("Cmd8()\n\r");
+ memset(pCommand, 0, sizeof(SdCmd));
+ // Fill command information
+ pCommand->cmd = AT91C_SEND_IF_COND;
+ pCommand->arg = (supplyVoltage << 8) | (0xAA);
+ pCommand->resType = 7;
+ pCommand->pResp = &response[0];
+
+ TRACE_DEBUG("supplyVoltage: 0x%x\n\r", supplyVoltage);
+
+ // Send command
+ error = SendCommand(pSd);
+
+ TRACE_DEBUG("SD_R7[0]: 0x%x\n\r", response[0]);
+ TRACE_DEBUG("SD_R7[1]: 0x%x\n\r", response[1]);
+ error = SD_SPI_R7((unsigned char *)&response, &isSdhc);
+ if( error == SD_ERROR_NORESPONSE ) {
+ TRACE_DEBUG("Cmd8 R7 error:%d \n\r", error);
+ return error;
+ }
+ else {
+ if(isSdhc == 1) {
+ TRACE_DEBUG("Cmd8 Ver 2.00 isSdhc:%d\n\r", isSdhc);
+ return 0;
+ }
+ else {
+ TRACE_DEBUG("Cmd8 Ver 1.X isSdhc:%d\n\r", isSdhc);
+ return error;
+ }
+ }
+}
+
+//------------------------------------------------------------------------------
+/// Addressed card sends its card-specific
+/// data (CSD) on the CMD line.
+/// Returns the command transfer result (see SendCommand).
+/// \param pSd Pointer to a SD card driver instance.
+//------------------------------------------------------------------------------
+static unsigned char Cmd9(SdCard *pSd)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+ unsigned int response = 0;
+ unsigned char csdData[16];
+ unsigned int i;
+
+ TRACE_DEBUG("Cmd9()\n\r");
+ memset(pCommand, 0, sizeof(SdCmd));
+ // Fill command information
+ pCommand->cmd = AT91C_SEND_CSD_CMD;
+ pCommand->resType = 1;
+ pCommand->blockSize = 16;
+ pCommand->pData = csdData;
+ pCommand->isRead = 1;
+ pCommand->pResp = &response;
+
+ // Send command
+ error = SendCommand(pSd);
+
+ // In SPI mode, reading CSD is the same as reading data.
+ for (i = 0; i < 4; i++) {
+ pSd->csd[i] = csdData[i*4] << 24 |
+ csdData[i*4+1] << 16 |
+ csdData[i*4+2] << 8 |
+ csdData[i*4+3];
+ }
+ error = SD_SPI_R1((unsigned char *)&response);
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// Forces the card to stop transmission
+/// \param pSd Pointer to a SD card driver instance.
+/// \param pStatus Pointer to a status variable.
+//------------------------------------------------------------------------------
+static unsigned char Cmd12(SdCard *pSd)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+ unsigned int response;
+
+ TRACE_DEBUG("Cmd12()\n\r");
+ memset(pCommand, 0, sizeof(SdCmd));
+ // Fill command information
+ pCommand->cmd = AT91C_STOP_TRANSMISSION_CMD;
+ pCommand->conTrans = SPI_NEW_TRANSFER;
+ pCommand->resType = 1;
+ pCommand->pResp = &response;
+
+ // Send command
+ error = SendCommand(pSd);
+
+ //TRACE_DEBUG("cmd12 resp 0x%X\n\r",response);
+ error = SD_SPI_R1b((unsigned char *)&response);
+ if (error == SD_ERROR_BUSY) {
+ while (SDSPI_WaitDataBusy((SdSpi *)pSd->pSdDriver) == 1);
+ error = 0;
+ }
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// Addressed card sends its status register.
+/// Returns the command transfer result (see SendCommand).
+/// \param pSd Pointer to a SD card driver instance.
+/// \param pStatus Pointer to a status variable.
+//------------------------------------------------------------------------------
+static unsigned char Cmd13(SdCard *pSd, unsigned int *pStatus)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+
+ TRACE_DEBUG("Cmd13()\n\r");
+ memset(pCommand, 0, sizeof(SdCmd));
+ // Fill command information
+ pCommand->cmd = AT91C_SEND_STATUS_CMD;
+ pCommand->resType = 2;
+ pCommand->pResp = pStatus;
+
+ // Send command
+ error = SendCommand(pSd);
+ error = SD_SPI_R2((unsigned char *)pStatus);
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// In the case of a Standard Capacity SD Memory Card, this command sets the
+/// block length (in bytes) for all following block commands (read, write, lock).
+/// Default block length is fixed to 512 Bytes.
+/// Set length is valid for memory access commands only if partial block read
+/// operation are allowed in CSD.
+/// In the case of a High Capacity SD Memory Card, block length set by CMD16
+/// command does not affect the memory read and write commands. Always 512
+/// Bytes fixed block length is used. This command is effective for LOCK_UNLOCK command.
+/// In both cases, if block length is set larger than 512Bytes, the card sets the
+/// BLOCK_LEN_ERROR bit.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param blockLength Block length in bytes.
+//------------------------------------------------------------------------------
+static unsigned char Cmd16(SdCard *pSd, unsigned short blockLength)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+ unsigned int response;
+
+ TRACE_DEBUG("Cmd16()\n\r");
+ memset(pCommand, 0, sizeof(SdCmd));
+ // Fill command information
+ pCommand->cmd = AT91C_SET_BLOCKLEN_CMD;
+ pCommand->arg = blockLength;
+ pCommand->resType = 1;
+ pCommand->pResp = &response;
+
+ // Send command
+ error = SendCommand(pSd);
+ error = SD_SPI_R1((unsigned char *)&response);
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// Continously transfers datablocks from card to host until interrupted by a
+/// STOP_TRANSMISSION command.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param blockSize Block size (shall be set to 512 in case of high capacity).
+/// \param pData Pointer to the application buffer to be filled.
+/// \param address SD card address.
+//------------------------------------------------------------------------------
+static unsigned char Cmd18(SdCard *pSd,
+ unsigned short nbBlock,
+ unsigned char *pData,
+ unsigned int address)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+ unsigned int response;
+
+ //TRACE_DEBUG("Cmd18()\n\r");
+ memset(pCommand, 0, sizeof(SdCmd));
+ // Fill command information
+ pCommand->cmd = AT91C_READ_MULTIPLE_BLOCK_CMD;
+ pCommand->arg = address;
+ pCommand->blockSize = SD_BLOCK_SIZE;
+ pCommand->nbBlock = nbBlock;
+ pCommand->pData = pData;
+ pCommand->isRead = 1;
+ pCommand->conTrans = SPI_NEW_TRANSFER;
+ pCommand->resType = 1;
+ pCommand->pResp = &response;
+
+ // Send command
+ error = SendCommand(pSd);
+ error = SD_SPI_R1((unsigned char *)&response);
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// Write block command
+/// \param pSd Pointer to a SD card driver instance.
+/// \param blockSize Block size (shall be set to 512 in case of high capacity).
+/// \param pData Pointer to the application buffer to be filled.
+/// \param address SD card address.
+//------------------------------------------------------------------------------
+static unsigned char Cmd25(SdCard *pSd,
+ unsigned short nbBlock,
+ unsigned char *pData,
+ unsigned int address)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+ unsigned int response;
+
+ TRACE_DEBUG("Cmd25()\n\r");
+ memset(pCommand, 0, sizeof(SdCmd));
+ // Fill command information
+ pCommand->cmd = AT91C_WRITE_MULTIPLE_BLOCK_CMD;
+ pCommand->arg = address;
+ pCommand->blockSize = SD_BLOCK_SIZE;
+ pCommand->nbBlock = nbBlock;
+ pCommand->pData = (unsigned char *) pData;
+ pCommand->conTrans = SPI_NEW_TRANSFER;
+ pCommand->resType = 1;
+ pCommand->pResp = &response;
+
+ // Send command
+ error = SendCommand(pSd);
+
+ if (!error) error = SD_SPI_R1((unsigned char *)&response);
+ return error;
+}
+
+
+//------------------------------------------------------------------------------
+/// Initialization delay: The maximum of 1 msec, 74 clock cycles and supply
+/// ramp up time.
+/// Returns the command transfer result (see SendCommand).
+/// \param pSd Pointer to a SD card driver instance.
+//------------------------------------------------------------------------------
+static unsigned char Cmd55(SdCard *pSd)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+ unsigned int response;
+
+ TRACE_DEBUG("Cmd55()\n\r");
+ memset(pCommand, 0, sizeof(SdCmd));
+ // Fill command information
+ pCommand->cmd = AT91C_APP_CMD;
+ pCommand->resType = 1;
+ pCommand->pResp = &response;
+
+ // Send command
+ error = SendCommand(pSd);
+ error = SD_SPI_R1((unsigned char *)&response);
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// SPI Mode, Reads the OCR register of a card
+/// Returns the command transfer result (see SendCommand).
+/// \param pSd Pointer to a SD card driver instance.
+/// \param pOcr OCR value of the card
+//------------------------------------------------------------------------------
+static unsigned char Cmd58(SdCard *pSd, unsigned int *pOcr)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+ unsigned int response[2];
+
+ TRACE_DEBUG("Cmd58()\n\r");
+ memset(pCommand, 0, sizeof(SdCmd));
+ // Fill command information
+ pCommand->cmd = AT91C_READ_OCR_CMD;
+ pCommand->resType = 3;
+ pCommand->pResp = &response[0];
+
+ // Send command
+ error = SendCommand(pSd);
+ error = SD_SPI_R3((unsigned char *)&response, pOcr);
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// SPI Mode, Set CRC option of a card
+/// Returns the command transfer result (see SendCommand).
+/// \param pSd Pointer to a SD card driver instance.
+/// \param option CRC option, 1 to turn on, 0 to trun off
+//------------------------------------------------------------------------------
+static unsigned char Cmd59(SdCard *pSd, unsigned char option)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+ unsigned int response;
+
+ TRACE_DEBUG("Cmd59()\n\r");
+ memset(pCommand, 0, sizeof(SdCmd));
+ // Fill command information
+ pCommand->cmd = AT91C_CRC_ON_OFF_CMD;
+ pCommand->arg = (option & 0x1);
+ pCommand->resType = 1;
+ pCommand->pResp = &response;
+
+ // Send command
+ error = SendCommand(pSd);
+ error = SD_SPI_R1((unsigned char *)&response);
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// Asks to all cards to send their operations conditions.
+/// Returns the command transfer result (see SendCommand).
+/// \param pSd Pointer to a SD card driver instance.
+/// \param hcs Shall be true if Host support High capacity.
+/// \param pCCS Set the pointed flag to 1 if hcs != 0 and SD OCR CCS flag is set.
+//------------------------------------------------------------------------------
+static unsigned char Acmd41(SdCard *pSd, unsigned char hcs, unsigned char *pCCS)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned char error;
+ unsigned int response;
+
+ do {
+ error = Cmd55(pSd);
+ if (error) {
+ return error;
+ }
+
+ memset(pCommand, 0, sizeof(SdCmd));
+ // Fill command information
+ pCommand->cmd = AT91C_SDCARD_APP_OP_COND_CMD;
+ pCommand->arg = AT91C_MMC_HOST_VOLTAGE_RANGE;
+ if (hcs) {
+ pCommand->arg |= AT91C_CCS;
+ }
+
+ pCommand->resType = 1;
+ pCommand->pResp = &response;
+
+ // Send command
+ TRACE_DEBUG("Acmd41()\n\r");
+ error = SendCommand(pSd);
+ if (error) {
+ return error;
+ }
+ error = SD_SPI_R1((unsigned char *)&response);
+ if (error) {
+ return error;
+ }
+ // continue if in idle mode
+ if ((response & 0x1) != 0) { // R1_SPI_IDLE
+ continue;
+ }
+ *pCCS = ((response & AT91C_CCS) != 0);
+ return 0;
+ }
+ while ((response & AT91C_CARD_POWER_UP_BUSY) != AT91C_CARD_POWER_UP_BUSY);
+
+ return 0;
+}
+
+
+//------------------------------------------------------------------------------
+/// Continue to transfer datablocks from card to host until interrupted by a
+/// STOP_TRANSMISSION command.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param blockSize Block size (shall be set to 512 in case of high capacity).
+/// \param pData Pointer to the application buffer to be filled.
+/// \param address SD card address.
+//------------------------------------------------------------------------------
+static unsigned char ContinuousRead(SdCard *pSd,
+ unsigned short nbBlock,
+ unsigned char *pData,
+ unsigned int address)
+{
+ SdCmd *pCommand = &(pSd->command);
+
+ TRACE_DEBUG("ContinuousRD(%d)\n\r", address);
+ memset(pCommand, 0, sizeof(SdCmd));
+ // Fill command information
+ pCommand->blockSize = SD_BLOCK_SIZE;
+ pCommand->nbBlock = nbBlock;
+ pCommand->pData = pData;
+ pCommand->isRead = 1;
+ pCommand->conTrans = SPI_CONTINUE_TRANSFER;
+
+ // Send command
+ return SendCommand(pSd);
+}
+
+//------------------------------------------------------------------------------
+/// Continue to transfer datablocks from host to card until interrupted by a
+/// STOP_TRANSMISSION command.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param blockSize Block size (shall be set to 512 in case of high capacity).
+/// \param pData Pointer to the application buffer to be filled.
+/// \param address SD card address.
+//------------------------------------------------------------------------------
+static unsigned char ContinuousWrite(SdCard *pSd,
+ unsigned short nbBlock,
+ const unsigned char *pData,
+ unsigned int address)
+{
+ SdCmd *pCommand = &(pSd->command);
+ unsigned int response;
+
+ TRACE_DEBUG("ContinuousWR(%d)\n\r", address);
+ memset(pCommand, 0, sizeof(SdCmd));
+ // Fill command information
+ pCommand->blockSize = SD_BLOCK_SIZE;
+ pCommand->nbBlock = nbBlock;
+ pCommand->pData = (unsigned char *) pData;
+ pCommand->isRead = 0;
+ pCommand->conTrans = SPI_CONTINUE_TRANSFER;
+ pCommand->pResp = &response;
+
+ // Send command
+ return SendCommand(pSd);
+}
+
+//------------------------------------------------------------------------------
+/// Move SD card to transfer state. The buffer size must be at
+/// least 512 byte long. This function checks the SD card status register and
+/// address the card if required before sending the transfer command.
+/// Returns 0 if successful; otherwise returns an code describing the error.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param address Address of the block to transfer.
+/// \param nbBlocks Number of blocks to be transfer.
+/// \param pData Data buffer whose size is at least the block size.
+/// \param isRead 1 for read data and 0 for write data.
+//------------------------------------------------------------------------------
+static unsigned char MoveToTransferState(SdCard *pSd,
+ unsigned int address,
+ unsigned short nbBlocks,
+ unsigned char *pData,
+ unsigned char isRead)
+{
+ unsigned int status;
+ unsigned char error;
+ SdDriver *pSdDriver = pSd->pSdDriver;
+
+ if((pSd->state == SD_STATE_DATA)
+ || (pSd->state == SD_STATE_RCV)) {
+
+ // SD SPI mode uses stop transmission token to stop multiple block write.
+ if ((pSd->state == SD_STATE_RCV) ) {
+ SDSPI_StopTranToken((SdSpi *)pSdDriver);
+ SDSPI_Wait((SdSpi *)pSdDriver, 1);
+ while (SDSPI_WaitDataBusy((SdSpi *)pSdDriver) == 1);
+ pSd->state = SD_STATE_STBY;
+ }
+ else {
+ error = Cmd12(pSd);
+ if (error) {
+ return error;
+ }
+ }
+ }
+ pSd->preBlock = address + (nbBlocks-1);
+
+ if(isRead) {
+ TRACE_DEBUG("Read\n\r");
+ // Wait for card to be ready for data transfers
+ do {
+ //TRACE_DEBUG("state = 0x%X\n\r", (status & STATUS_STATE) >> 9);
+ error = Cmd13(pSd, &status);
+ if (error) {
+ TRACE_DEBUG("Pb MTTS cmd13\n\r");
+ return error;
+ }
+ break;
+ }
+ while (((status & STATUS_READY_FOR_DATA) == 0) ||
+ ((status & STATUS_STATE) != STATUS_TRAN));
+ // Read data
+ // Move to Sending data state
+ error = Cmd18(pSd, nbBlocks, pData, SD_ADDRESS(pSd,address));
+ if (error) {
+ return error;
+ }
+
+ pSd->state = SD_STATE_DATA;
+ }
+ else {
+ TRACE_DEBUG("Write\n\r");
+ // Wait for card to be ready for data transfers
+ do {
+ error = Cmd13(pSd, &status);
+ if (error) {
+ TRACE_DEBUG("error cmd 13\n\r");
+ return error;
+ }
+ break;
+ }
+ while ((status & STATUS_READY_FOR_DATA) == 0);
+
+ // Move to Sending data state
+ error = Cmd25(pSd, nbBlocks, pData, SD_ADDRESS(pSd,address));
+ if (error) {
+ TRACE_DEBUG("error cmd 25\n\r");
+ return error;
+ }
+
+ pSd->state = SD_STATE_RCV;
+ }
+
+ return error;
+}
+
+//------------------------------------------------------------------------------
+// Global functions
+//------------------------------------------------------------------------------
+
+//------------------------------------------------------------------------------
+/// Read Block of data in a buffer pointed by pData. The buffer size must be at
+/// least 512 byte long. This function checks the SD card status register and
+/// address the card if required before sending the read command.
+/// Returns 0 if successful; otherwise returns an code describing the error.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param address Address of the block to read.
+/// \param nbBlocks Number of blocks to be read.
+/// \param pData Data buffer whose size is at least the block size.
+//------------------------------------------------------------------------------
+unsigned char SD_ReadBlock(SdCard *pSd,
+ unsigned int address,
+ unsigned short nbBlocks,
+ unsigned char *pData)
+{
+ unsigned char error;
+
+ SANITY_CHECK(pSd);
+ SANITY_CHECK(pData);
+ SANITY_CHECK(nbBlocks);
+#if 1
+ error = MoveToTransferState(pSd, address, nbBlocks, pData, 1);
+#else
+ if((pSd->state == SD_STATE_DATA)
+ && ((pSd->preBlock + 1) == address)) {
+
+#if defined(at91rm9200)
+ error = Cmd12(pSd);
+ if (error) {
+ return error;
+ }
+#else
+ error = ContinuousRead(pSd, nbBlocks, pData, SD_ADDRESS(pSd,address));
+ pSd->preBlock = address + (nbBlocks-1);
+#endif
+ }
+ else {
+ error = MoveToTransferState(pSd, address, nbBlocks, pData, 1);
+ }
+#endif
+ return error;
+}
+
+//------------------------------------------------------------------------------
+/// Write Block of data pointed by pData. The buffer size must be at
+/// least 512 byte long. This function checks the SD card status register and
+/// address the card if required before sending the read command.
+/// Returns 0 if successful; otherwise returns an SD_ERROR code.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param address Address of block to write.
+/// \param nbBlocks Number of blocks to be read
+/// \param pData Pointer to a 512 bytes buffer to be transfered
+//------------------------------------------------------------------------------
+unsigned char SD_WriteBlock(SdCard *pSd,
+ unsigned int address,
+ unsigned short nbBlocks,
+ const unsigned char *pData)
+{
+ unsigned char error;
+
+ SANITY_CHECK(pSd);
+ SANITY_CHECK(pData);
+ SANITY_CHECK(nbBlocks);
+
+ if((pSd->state == SD_STATE_RCV)
+ && ((pSd->preBlock + 1) == address)) {
+
+ error = ContinuousWrite(pSd, nbBlocks, pData, SD_ADDRESS(pSd,address));
+ pSd->preBlock = address + (nbBlocks-1);
+ }
+ else {
+
+ //TRACE_FATAL("SD_WriteBlock:MoveToTransferState\n\r");
+ error = MoveToTransferState(pSd, address, nbBlocks,
+ (unsigned char *)pData, 0);
+ }
+ return error;
+}
+
+
+//------------------------------------------------------------------------------
+/// Run the SDcard SPI Mode initialization sequence. This function runs the
+/// initialisation procedure and the identification process, then it sets the SD
+/// card in transfer state to set the block length.
+/// Returns 0 if successful; otherwise returns an SD_ERROR code.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param pSdDriver Pointer to SD driver already initialized.
+//------------------------------------------------------------------------------
+unsigned char SD_SPI_Init(SdCard *pSd, SdDriver *pSpi)
+{
+ unsigned char isCCSet;
+ unsigned char error;
+ unsigned char cmd8Retries = 2;
+ unsigned char cmd1Retries = 1;
+ unsigned int pOCR;
+
+ // The command GO_IDLE_STATE (CMD0) is the software reset command and sets card into Idle State
+ // regardless of the current card state.
+ error = Cmd0(pSd);
+ if (error) {
+ TRACE_ERROR("Error during initialization (%d)\n\r", error);
+ return error;
+ }
+
+ // CMD8 is newly added in the Physical Layer Specification Version 2.00 to support multiple voltage
+ // ranges and used to check whether the card supports supplied voltage. The version 2.00 host shall
+ // issue CMD8 and verify voltage before card initialization.
+ // The host that does not support CMD8 shall supply high voltage range...
+ do {
+ error = Cmd8(pSd, 1);
+ }
+ while ((error == SD_ERROR_NORESPONSE) && (cmd8Retries-- > 0));
+
+ if (error == SD_ERROR_NORESPONSE) {
+ // No response : Ver2.00 or later SD Memory Card(voltage mismatch)
+ // or Ver1.X SD Memory Card
+ // or not SD Memory Card
+
+ TRACE_DEBUG("No response to Cmd8\n\r");
+
+ // CMD58 ? !
+ error = Cmd58(pSd, &pOCR);
+ if (error) {
+ TRACE_ERROR("Error during initialization (%d), 8\n\r", error);
+ return error;
+ }
+
+ // ACMD41 is a synchronization command used to negotiate the operation voltage range and to poll the
+ // cards until they are out of their power-up sequence.
+ error = Acmd41(pSd, 0, &isCCSet);
+ if (error) {
+ // Acmd41 failed : MMC card or unknown card
+ error = Cmd0(pSd);
+ if (error) {
+ TRACE_ERROR("Error during initialization (%d)\n\r", error);
+ return error;
+ }
+ do {
+ error = Cmd1(pSd);
+ }
+ while ((error) && (cmd1Retries-- > 0));
+
+ if (error) {
+ TRACE_ERROR("Error during initialization (%d)\n\r", error);
+ return error;
+ }
+ else {
+ pSd->cardType = CARD_MMC;
+ }
+ }
+ else {
+ if(isCCSet == 0) {
+ TRACE_DEBUG("CARD SD\n\r");
+ pSd->cardType = CARD_SD;
+ }
+ }
+ }
+ else if (!error) {
+ error = Cmd58(pSd, &pOCR);
+ if (error) {
+ TRACE_ERROR("Error during initialization (%d), 8\n\r", error);
+ return error;
+ }
+
+ // Valid response : Ver2.00 or later SD Memory Card
+ error = Acmd41(pSd, 1, &isCCSet);
+ if (error) {
+ TRACE_ERROR("Error during initialization (%d)\n\r", error);
+ return error;
+ }
+ error = Cmd58(pSd, &pOCR);
+ if (error) {
+ TRACE_ERROR("Error during initialization (%d), 8\n\r", error);
+ return error;
+ }
+ if (isCCSet) {
+ TRACE_DEBUG("CARD SDHC\n\r");
+ pSd->cardType = CARD_SDHC;
+ }
+ else {
+ TRACE_DEBUG("CARD SD\n\r");
+ pSd->cardType = CARD_SD;
+ }
+ }
+ else {
+ TRACE_ERROR("Error during initialization (%d)\n\r", error);
+ return error;
+ }
+
+ if (pSd->cardType != CARD_MMC) {
+ // The host issues CRC_ON_OFF (CMD59) to set data CRC on/off
+ // The host can turn the CRC option on and off using the CRC_ON_OFF command (CMD59).
+ // Host should enable CRC verification before issuing ACMD41.
+ error = Cmd59(pSd,0); // turn crc option OFF
+ if (error) {
+
+ TRACE_ERROR("Error during initialization (%d)\n\r, 59", error);
+ return error;
+ }
+ }
+
+ // The host issues SEND_CSD (CMD9) to obtain the Card Specific Data (CSD register),
+ // e.g. block length, card storage capacity, etc...
+ error = Cmd9(pSd);
+ if (error) {
+
+ TRACE_ERROR("Error during initialization (%d), 9\n\r", error);
+ return error;
+ }
+ return 0;
+}
+//
+
+//------------------------------------------------------------------------------
+/// Run the SDcard initialization sequence. This function runs the initialisation
+/// procedure and the identification process, then it sets the SD card in transfer
+/// state to set the block length and the bus width.
+/// Returns 0 if successful; otherwise returns an SD_ERROR code.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param pSdDriver Pointer to SD driver already initialized.
+/// \param mode Select SD or SPI access mode
+//------------------------------------------------------------------------------
+unsigned char SD_Init(SdCard *pSd, SdDriver *pSdDriver)
+{
+ unsigned char error;
+
+ //TRACE_DEBUG("SD_Init()\n\r");
+
+ // Initialize SdCard structure
+ pSd->pSdDriver = pSdDriver;
+ pSd->cardAddress = 0;
+ pSd->preBlock = 0xffffffff;
+ pSd->state = SD_STATE_STBY;
+ pSd->cardType = UNKNOWN_CARD;
+ memset(&(pSd->command), 0, sizeof(SdCmd));
+
+ // Initialization delay: The maximum of 1 msec, 74 clock cycles and supply ramp up time
+ // ‘Supply ramp up time?provides the time that the power is built up to the operating level (the bus
+ // master supply voltage) and the time to wait until the SD card can accept the first command
+
+ // Power On Init Special Command
+ //TRACE_DEBUG("Pon()\n\r");
+ error = Pon(pSd);
+ if (error) {
+ TRACE_ERROR("SD_Init.Pon: (%d)\n\r", error);
+ return error;
+ }
+
+ // After power-on or CMD0, all cards?CMD lines are in input mode, waiting for start bit of the next command.
+ // The cards are initialized with a default relative card address (RCA=0x0000) and with a default
+ // driver stage register setting (lowest speed, highest driving current capability).
+
+ error = SD_SPI_Init(pSd, pSdDriver);
+ if (error) {
+ TRACE_ERROR("SD_Init._Init (%d)\n\r", error);
+ return error;
+ }
+
+ // In the case of a Standard Capacity SD Memory Card, this command sets the
+ // block length (in bytes) for all following block commands (read, write, lock).
+ // Default block length is fixed to 512 Bytes.
+ // Set length is valid for memory access commands only if partial block read
+ // operation are allowed in CSD.
+ // In the case of a High Capacity SD Memory Card, block length set by CMD16
+ // command does not affect the memory read and write commands. Always 512
+ // Bytes fixed block length is used. This command is effective for LOCK_UNLOCK command.
+ // In both cases, if block length is set larger than 512Bytes, the card sets the
+ // BLOCK_LEN_ERROR bit.
+ if (pSd->cardType == CARD_SD) {
+ error = Cmd16(pSd, SD_BLOCK_SIZE);
+ if (error) {
+ TRACE_ERROR("SD_Init.Cmd16: (%d)\n\r", error);
+ return error;
+ }
+ }
+
+ // If MMC Card & get size from EXT_CSD
+ if (pSd->cardType >= CARD_MMC && SD_CSD_C_SIZE(pSd) == 0xFFF) {
+#if 0
+ pSd->blockNr = SD_EXTCSD_BLOCKNR(pSd);
+ // Block number less than 0x100000000/512
+ if (pSd->blockNr > 0x800000)
+ pSd->totalSize = 0xFFFFFFFF;
+ else
+ pSd->totalSize = SD_EXTCSD_TOTAL_SIZE(pSd);
+#endif
+ }
+ // If SD CSD v2.0
+ else if(pSd->cardType >= CARD_SD && SD_CSD_STRUCTURE(pSd) >= 1) {
+ pSd->blockNr = SD_CSD_BLOCKNR_HC(pSd);
+ pSd->totalSize = 0xFFFFFFFF;
+ }
+ // Normal card
+ else {
+ pSd->totalSize = SD_CSD_TOTAL_SIZE(pSd);
+ pSd->blockNr = SD_CSD_BLOCKNR(pSd);
+ }
+
+ if (pSd->cardType == UNKNOWN_CARD) {
+ return SD_ERROR_NOT_INITIALIZED;
+ }
+ else {
+ return 0;
+ }
+}
+
+//------------------------------------------------------------------------------
+/// Stop the SDcard. This function stops all SD operations.
+/// Returns 0 if successful; otherwise returns an SD_ERROR code.
+/// \param pSd Pointer to a SD card driver instance.
+/// \param pSdDriver Pointer to MCI driver already initialized.
+//------------------------------------------------------------------------------
+unsigned char SD_Stop(SdCard *pSd, SdDriver *pSdDriver)
+{
+ unsigned char error;
+ SdCmd *pCommand = &(pSd->command);
+
+ SANITY_CHECK(pSd);
+ SANITY_CHECK(pSdDriver);
+
+ if(pCommand->conTrans == SPI_CONTINUE_TRANSFER)
+ {
+ TRACE_DEBUG("SD_StopTransmission()\n\r");
+
+ error = Cmd12(pSd);
+ if(error) {
+ return error;
+ }
+ }
+
+ SDSPI_Close((SdSpi *)pSdDriver);
+ return 0;
+}
+
+
+
+//------------------------------------------------------------------------------
+/// Display the content of the CSD register
+/// \param pSd
+//------------------------------------------------------------------------------
+void SD_DisplayRegisterCSD(SdCard *pSd)
+{
+ TRACE_INFO("======== CSD ========");
+ #if 0
+ {
+ unsigned int i;
+ unsigned char *p = (unsigned char *)pSd->csd;
+ for(i = 0; i < 128 / 8; i++) {
+ if ((i % 16) == 0) TRACE_INFO_WP("\n\r [%3d]:", i);
+ TRACE_INFO_WP(" %2x", p[i]);
+ }
+ TRACE_INFO_WP("\n\r");
+ TRACE_INFO("------------------------\n\r");
+ }
+ #else
+ TRACE_INFO_WP("\n\r");
+ #endif
+ TRACE_INFO(" .CSD_STRUCTURE 0x%x\r\n", SD_CSD_STRUCTURE(pSd));
+ TRACE_INFO(" .SPEC_VERS 0x%x\r\n", SD_CSD_SPEC_VERS(pSd));
+ TRACE_INFO(" .TAAC 0x%X\r\n", SD_CSD_TAAC(pSd) );
+ TRACE_INFO(" .NSAC 0x%X\r\n", SD_CSD_NSAC(pSd) );
+ TRACE_INFO(" .TRAN_SPEED 0x%X\r\n", SD_CSD_TRAN_SPEED(pSd) );
+ TRACE_INFO(" .CCC 0x%X\r\n", SD_CSD_CCC(pSd) );
+ TRACE_INFO(" .READ_BL_LEN 0x%X\r\n", SD_CSD_READ_BL_LEN(pSd) );
+ TRACE_INFO(" .READ_BL_PARTIAL 0x%X\r\n", SD_CSD_READ_BL_PARTIAL(pSd) );
+ TRACE_INFO(" .WRITE_BLK_MISALIGN 0x%X\r\n", SD_CSD_WRITE_BLK_MISALIGN(pSd));
+ TRACE_INFO(" .READ_BLK_MISALIGN 0x%X\r\n", SD_CSD_READ_BLK_MISALIGN(pSd) );
+ TRACE_INFO(" .DSR_IMP 0x%X\r\n", SD_CSD_DSR_IMP(pSd) );
+ TRACE_INFO(" .C_SIZE 0x%X\r\n", SD_CSD_C_SIZE(pSd) );
+ TRACE_INFO(" .C_SIZE_HC 0x%X\r\n", SD_CSD_C_SIZE_HC(pSd) );
+ TRACE_INFO(" .VDD_R_CURR_MIN 0x%X\r\n", SD_CSD_VDD_R_CURR_MIN(pSd) );
+ TRACE_INFO(" .VDD_R_CURR_MAX 0x%X\r\n", SD_CSD_VDD_R_CURR_MAX(pSd) );
+ TRACE_INFO(" .VDD_W_CURR_MIN 0x%X\r\n", SD_CSD_VDD_W_CURR_MIN(pSd) );
+ TRACE_INFO(" .VDD_W_CURR_MAX 0x%X\r\n", SD_CSD_VDD_W_CURR_MAX(pSd) );
+ TRACE_INFO(" .C_SIZE_MULT 0x%X\r\n", SD_CSD_C_SIZE_MULT(pSd) );
+ TRACE_INFO(" .ERASE_BLK_EN 0x%X\r\n", SD_CSD_ERASE_BLK_EN(pSd) );
+ TRACE_INFO(" .SECTOR_SIZE 0x%X\r\n", SD_CSD_SECTOR_SIZE(pSd) );
+ TRACE_INFO(" .WP_GRP_SIZE 0x%X\r\n", SD_CSD_WP_GRP_SIZE(pSd) );
+ TRACE_INFO(" .WP_GRP_ENABLE 0x%X\r\n", SD_CSD_WP_GRP_ENABLE(pSd) );
+ TRACE_INFO(" .R2W_FACTOR 0x%X\r\n", SD_CSD_R2W_FACTOR(pSd) );
+ TRACE_INFO(" .WRITE_BL_LEN 0x%X\r\n", SD_CSD_WRITE_BL_LEN(pSd) );
+ TRACE_INFO(" .WRITE_BL_PARTIAL 0x%X\r\n", SD_CSD_WRITE_BL_PARTIAL(pSd) );
+ TRACE_INFO(" .FILE_FORMAT_GRP 0x%X\r\n", SD_CSD_FILE_FORMAT_GRP(pSd) );
+ TRACE_INFO(" .COPY 0x%X\r\n", SD_CSD_COPY(pSd) );
+ TRACE_INFO(" .PERM_WRITE_PROTECT 0x%X\r\n", SD_CSD_PERM_WRITE_PROTECT(pSd));
+ TRACE_INFO(" .TMP_WRITE_PROTECT 0x%X\r\n", SD_CSD_TMP_WRITE_PROTECT(pSd) );
+ TRACE_INFO(" .FILE_FORMAT 0x%X\r\n", SD_CSD_FILE_FORMAT(pSd) );
+ TRACE_INFO(" .ECC 0x%X\r\n", SD_CSD_ECC(pSd) );
+ TRACE_INFO(" .CRC 0x%X\r\n", SD_CSD_CRC(pSd) );
+ TRACE_INFO(" .MULT 0x%X\r\n", SD_CSD_MULT(pSd) );
+ TRACE_INFO(" .BLOCKNR 0x%X\r\n", SD_CSD_BLOCKNR(pSd) );
+ TRACE_INFO(" .BLOCKNR_HC 0x%X\r\n", SD_CSD_BLOCKNR_HC(pSd) );
+ TRACE_INFO(" .BLOCK_LEN 0x%X\r\n", SD_CSD_BLOCK_LEN(pSd) );
+ TRACE_INFO(" .TOTAL_SIZE 0x%X\r\n", SD_CSD_TOTAL_SIZE(pSd) );
+ TRACE_INFO(" .TOTAL_SIZE_HC 0x%X\r\n", SD_CSD_TOTAL_SIZE_HC(pSd) );
+ TRACE_INFO(" -SD_TOTAL_SIZE 0x%X\r\n", SD_TOTAL_SIZE(pSd) );
+ TRACE_INFO(" -SD_TOTAL_BLOCK 0x%X\r\n", SD_TOTAL_BLOCK(pSd) );
+}
+
diff --git a/memories/sdmmc/sdmmc_spi.h b/memories/sdmmc/sdmmc_spi.h
new file mode 100644
index 0000000..3df15cd
--- /dev/null
+++ b/memories/sdmmc/sdmmc_spi.h
@@ -0,0 +1,720 @@
+/* ----------------------------------------------------------------------------
+ * ATMEL Microcontroller Software Support
+ * ----------------------------------------------------------------------------
+ * Copyright (c) 2008, Atmel Corporation
+
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the disclaimer below.
+ *
+ * Atmel's name may not be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
+ * DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ----------------------------------------------------------------------------
+ */
+
+//------------------------------------------------------------------------------
+/// \page "sdmmc_spi"
+///
+/// !Purpose
+///
+/// Implementation for sdcard spi mode physical layer driver. Supply a set of sdcard spi mode's
+/// interface.
+///
+/// !Usage
+///
+/// -# SD_Init: Run the SDcard initialization sequence
+/// -# SD_SPI_Init : Run the SDcard SPI Mode initialization sequence
+/// -# SD_Stop: Stop the SDcard by sending Cmd12
+/// -# SD_ReadBlock : Read blocks of data
+/// -# SD_WriteBlock : Write blocks of data
+//------------------------------------------------------------------------------
+
+//------------------------------------------------------------------------------
+/// \page "sdcard spi mode initialization and identification"
+///
+/// !Purpose
+///
+/// sdcard spi mode initialization and identification sequence
+///
+/// !Description
+/// - Host sends Cmd0 to do card reset, card is in "idle state".
+/// - Host sends Cmd8 and checks the response of the card, only sdcard supports physical
+/// layer version 2.00 will response correctly to Cmd8, and this command is mandatory to be
+/// sent before ACmd41 for sdcard which support physical layer version 2.00, to enable new
+/// functions or to validate a dual-voltage card.
+/// - refer to "If Cmd8 response ok" branch for the initialize of sdcard 2.0.
+/// - refer to "If Cmd8 response fail" branch for the initialize of sdcard 1.x, mmc card, sdcard2.0
+/// with invalid voltage.
+/// - If Cmd8 response ok
+/// - Host sends Cmd58 to read OCR register to validate the voltage.
+/// - If the response to Cmd58 is fail, initialize ends, the card is put into inactive state.
+/// - If the response to Cmd58 is ok, continue to the next step.
+/// - Host sends ACmd41* with argument "HCS" equal to "1".
+/// - If the response to ACmd41 failed, it means the card does not match the voltage
+/// desired by the host, the card will be put into inactive state, initialize ends.
+/// - If the response with "CCS" equal to "1", the card is a version 2.0 high capacity sdcard,
+/// refer to "Card Initialize" for the succeeding initialize sequence.
+/// - If the response with "CCS" equal to "0", the card is a version 2.0 standard capacity sdcard.
+/// refer to "Card Initialize" for the succeeding initialize sequence.
+/// - If Cmd8 response fail
+/// - Host sends Cmd58 to read OCR register to validate the voltage.
+/// - If the response to Cmd58 is fail, initialize ends, the card is put into inactive state.
+/// - If the response to Cmd58 is ok, continue to the next step.
+/// - Host sends ACmd41* argument "HCS" equal to "0".
+/// - If the response to ACmd41 ok, the card is a version 1.x sdcard, refer to "Card Initialize" for
+/// the succeeding initialize sequence.
+/// - If the response to ACmd41 fails
+/// - Host sends Cmd0 to reset card.
+/// - Host sends Cmd1 to card.
+/// - If card has response to Cmd1, the card is a MMC card, refer to "Card Initialize" for the
+/// succeeding initialize sequence.
+/// - If card has no response to Cmd1, the card is either an unknown card or a card does
+/// not match host's voltage, the initialize ends.
+/// - Card Initialize
+/// - At this stage, the initialization and identification process is over, the following steps are done
+/// for the sdcard's succeeding operation.
+/// - Host sends Cmd59 to turn sdcard's CRC option off.
+/// - Host sends Cmd9 to get the Card Specific Data (CSD).
+///
+/// \note Send Cmd55 before send ACmd41. \endnote
+/// \note sdcard include ver 1.x sdcard, ver2.0 standard capacity sdcard, ver2.0 high capacity sdcard \endnote
+//------------------------------------------------------------------------------
+
+//------------------------------------------------------------------------------
+/// \page "sdcard spi mode write"
+///
+/// !Purpose
+///
+/// sdcard spi mode write process
+///
+/// !Description
+/// - Make sure sdcard is under "transfer state", if the sdcard is under other state, host will send
+/// Cmd12 or use stop transmission token to stop multiple block write, and to transit sdcard to
+/// "stand-by state".
+/// - Host sends Cmd13 to check sdcard's status, to make sure sdcard is "ready-for-data".
+/// - Host sends Cmd25 to do multiple blocks write, the address here is different between high capacity
+/// sdcard and normal sdcard, the address of SDHC is equal to the block number, while normal sdcard's
+/// address is equal to block number times 512.
+//------------------------------------------------------------------------------
+
+//------------------------------------------------------------------------------
+/// \page "sdcard spi mode read"
+///
+/// !Purpose
+///
+/// sdcard spi mode read process
+///
+/// !Description
+/// - Make sure sdcard is under "transfer state", if the sdcard is under other state, host will send
+/// Cmd12 or use stop transmission token to stop multiple block read and to transit sdcard to
+/// "stand-by state".
+/// - Host sends Cmd13 to check sdcard's status, to make sure sdcard is "ready-for-data".
+/// - Host sends Cmd18 to do multiple blocks read, the address here is different between high capacity
+/// sdcard and normal sdcard, the address of SDHC is equal to the block number, while normal sdcard's
+/// address is equal to block number times 512.
+//------------------------------------------------------------------------------
+
+//------------------------------------------------------------------------------
+/// \page "sdhc"
+///
+/// !Purpose
+///
+/// highlight of sdhc
+///
+/// !Sdhc initialization and identification
+///
+/// - Refer to page "sdcard spi mode initialization and identification" for the initialization and identification
+/// sequence of a sdhc.
+///
+/// !Functional difference between sdhc and standard capacity sdcard
+///
+/// - Command argument is different:
+/// - Sdhc uses block address format in memory access commands*, block length is fixed to 512 bytes.
+/// - Standard capacity sdcard uses byte address format in memory access commands, block length
+/// is defined in Cmd16.
+/// - Partial access and misalign access are disabled in sdhc as the block address is used.
+/// - Sdhc does not support write-protected commands (Cmd28, Cmd29, Cmd30).
+///
+/// \note Memory access commands means block read commands (CMD17, CMD18), block write commands
+/// (CMD24, CMD25), and block erase commands (CMD32, CMD33).
+///
+//------------------------------------------------------------------------------
+
+//------------------------------------------------------------------------------
+/// \page "sdmmc_spi"
+///
+/// !Purpose
+///
+/// Implementation for sdcard sd mode physical layer driver. Supply a set of sdcard sd mode's
+/// interface.
+///
+/// !Usage
+///
+/// -# SD_Init: Run the SDcard initialization sequence
+/// -# SD_MCI_Init : Run the SDcard SD Mode initialization sequence
+/// -# SD_Stop: Stop the SDcard by sending Cmd12
+/// -# SD_ReadBlock : Read blocks of data
+/// -# SD_WriteBlock : Write blocks of data
+/// -# Cmd0 : Resets all cards to idle state
+/// -# Cmd1 : MMC send operation condition command
+/// -# Cmd2 : Asks any card to send the CID numbers on the CMD line
+/// -# Cmd3 : Ask the card to publish a new relative address
+/// -# Cmd7 : Command toggles a card between the stand-by and transfer states or between
+/// the programming and disconnect states
+/// -# Cmd8 : Sends SD Memory Card interface condition, which includes host supply voltage
+/// information and asks the card whether card supports voltage
+/// -# Cmd9 : Addressed card sends its card-specific data (CSD) on the CMD line
+/// -# Cmd12 : Forces the card to stop transmission
+/// -# Cmd13 : Addressed card sends its status register
+/// -# Cmd16 : Set block length
+/// -# Cmd18 : Read multiple blocks
+/// -# Cmd25 : Write multiple blocks
+/// -# Cmd55 : App command, should be sent before application specific command
+/// -# Acmd6 : Defines the data bus width
+/// -# Acmd41 : Asks to all cards to send their operations conditions
+/// -# CmdEMMC8 : Sends eMMC EXT_CSD command
+/// -# CmdEMMC6 : Switches the mode of operation of the selected card or modifies the
+/// EXT_CSD registers
+//------------------------------------------------------------------------------
+
+#ifndef SDCARD_H
+#define SDCARD_H
+
+//------------------------------------------------------------------------------
+// Constants
+//------------------------------------------------------------------------------
+
+
+/// There was an error with the SD driver.
+#define SD_ERROR_DRIVER 1
+/// The SD card did not answer the command.
+#define SD_ERROR_NORESPONSE 2
+/// The SD card did not answer the command.
+#define SD_ERROR_NOT_INITIALIZED 3
+/// The SD card is busy
+#define SD_ERROR_BUSY 4
+/// The operation is not supported
+#define SD_ERROR_NOT_SUPPORT 5
+
+/// SD card block size in bytes.
+#define SD_BLOCK_SIZE 512
+/// SD card block size binary shift value
+#define SD_BLOCK_SIZE_BIT 9
+
+//- MMC Card Command Types
+/// Broadcast commands (bc), no response
+#define MMC_CCT_BC 0
+/// Broadcase commands with response (bcr)
+#define MMC_CCT_BCR 1
+/// Addressed commands (ac), no data transfer on DAT lines
+#define MMC_CCT_AC 2
+/// Addressed data transfer commands (adtc), data transfer on DAT lines
+#define MMC_CCT_ADTC 3
+
+//- MMC Card Command Classes (CCC)
+/// Class 0: basic
+#define MMC_CCC_BASIC 0
+/// Class 1: stream read
+#define MMC_CCC_STREAM_READ 1
+/// Class 2: block read
+#define MMC_CCC_BLOCK_READ 2
+/// Class 3: stream write
+#define MMC_CCC_STREAM_WRITE 3
+/// Class 4: block write
+#define MMC_CCC_BLOCK_WRITE 4
+/// Class 5: erase
+#define MMC_CCC_ERASE 5
+/// Class 6: write protection
+#define MMC_CCC_WRITE_PROTECTION 6
+/// Class 7: lock card
+#define MMC_CCC_LOCK_CARD 7
+/// Class 8: application specific
+#define MMC_CCC_APP_SPEC 8
+/// Class 9: I/O mode
+#define MMC_CCC_IO_MODE 9
+
+//- MMC/SD Card Command Response Type
+/// R1 (normal response command), 48bits
+#define MMC_RESP_R1 1
+#define SD_RESP_R1 MMC_RESP_R1
+/// R1b: busy signal transmitted on the data line DAT0
+#define MMC_RESP_R1b 1
+#define SD_RESP_R1b MMC_RESP_R1b
+/// R2: 136bits, CID, CSD register
+#define MMC_RESP_R2 2
+#define SD_RESP_R2 MMC_RESP_R2
+/// R3: 48bits, OCR
+#define MMC_RESP_R3 3
+#define SD_RESP_R3 MMC_RESP_R3
+/// R4 (Fast I/O), 48bits
+#define MMC_RESP_R4 4
+/// R5 (Interrupt request), 48bits
+#define MMC_RESP_R5 5
+/// R6 (Published RCA response), 48bits
+#define SD_RESP_R6 6
+/// R7 (Card interface condition), 48bits
+#define SD_RESP_R7 7
+
+//- MMC Card CMD6 access mode
+#define MMC_SWITCH_CMDSET 0
+#define MMC_SWITCH_SETBITS 1
+#define MMC_SWITCH_CLRBITS 2
+#define MMC_SWITCH_WRITE 3
+
+//-MMC Boot partition enable
+/// Boot partition 1 enabled for boot
+#define MMC_BOOT_PART_1 1
+/// Boot partition 2 enabled for boot
+#define MMC_BOOT_PART_2 2
+/// User area enabled for boot
+#define MMC_BOOT_PART_USER 7
+
+//-MMC Boot partition access
+/// R/W boot partition 1
+#define MMC_BOOT_ACC_PART1 1
+/// R/W boot partition 2
+#define MMC_BOOT_ACC_PART2 2
+
+//------------------------------------------------------------------------------
+// Macros
+//------------------------------------------------------------------------------
+
+// CID register access macros (128 bits, 4 * 32 bits).
+#define SD_CID(pSd, bitfield, bits) ( (pSd->cid[3-(bitfield)/32] >> ((bitfield)%32)) & ((1 << (bits)) - 1))
+#define SD_CID_MID(pSd) SD_CID(pSd, 120, 8) ///< Manufacturer ID
+#define SD_CID_BGA(pSd) SD_CID(pSd, 112, 2) ///< Card/BGA(eMMC)
+#define SD_CID_CBS(pSd) SD_CID(pSd, 112, 2) ///< Card/BGA(eMMC)
+#define SD_CID_OID_BYTE_1(pSd) SD_CID(pSd, 112, 8) ///< OEM/Application ID byte 1
+#define SD_CID_OID_BYTE_0(pSd) SD_CID(pSd, 104, 8) ///< OEM/Application ID byte 0
+#define SD_CID_PNM_BYTE_4(pSd) SD_CID(pSd, 96, 8) ///< Product revision byte 4
+#define SD_CID_PNM_BYTE_3(pSd) SD_CID(pSd, 88, 8) ///< Product revision byte 3
+#define SD_CID_PNM_BYTE_2(pSd) SD_CID(pSd, 80, 8) ///< Product revision byte 2
+#define SD_CID_PNM_BYTE_1(pSd) SD_CID(pSd, 72, 8) ///< Product revision byte 1
+#define SD_CID_PNM_BYTE_0(pSd) SD_CID(pSd, 64, 8) ///< Product revision byte 0
+#define SD_CID_PRV_1(pSd) SD_CID(pSd, 24, 8) ///< Product serial number 1
+#define SD_CID_PRV_2(pSd) SD_CID(pSd, 32,24) ///< Product serial number 2
+#define SD_CID_MDT_YEAR(pSd) (SD_CID(pSd, 12, 8))+2000///< Manufacturing date year
+#define SD_CID_MDT_MONTH(pSd) SD_CID(pSd, 8, 4) ///< Manufacturing date month
+#define SD_CID_CRC(pSd) SD_CID(pSd, 1, 7) ///< CRC7 checksum
+
+// CSD register access macros (128 bits, 4 * 32 bits).
+#define SD_CSD(pSd, bitfield, bits) ((((pSd)->csd)[3-(bitfield)/32] >> ((bitfield)%32)) & ((1 << (bits)) - 1))
+#define SD_CSD_STRUCTURE(pSd) SD_CSD(pSd, 126, 2) ///< CSD structure 00b Version 1.0 01b version 2.0 High Cap
+#define SD_CSD_SPEC_VERS(pSd) SD_CSD(pSd, 122, 4) ///< System Specification Version Number
+#define SD_CSD_TAAC(pSd) SD_CSD(pSd, 112, 8) ///< Data read-access-time-1
+#define SD_CSD_NSAC(pSd) SD_CSD(pSd, 104, 8) ///< Data read access-time-2 in CLK cycles
+#define SD_CSD_TRAN_SPEED(pSd) SD_CSD(pSd, 96, 8) ///< Max. data transfer rate
+#define SD_CSD_CCC(pSd) SD_CSD(pSd, 84, 12) ///< Card command class
+#define SD_CSD_READ_BL_LEN(pSd) SD_CSD(pSd, 80, 4) ///< Max. read data block length
+#define SD_CSD_READ_BL_PARTIAL(pSd) SD_CSD(pSd, 79, 1) ///< Bartial blocks for read allowed
+#define SD_CSD_WRITE_BLK_MISALIGN(pSd) SD_CSD(pSd, 78, 1) ///< Write block misalignment
+#define SD_CSD_READ_BLK_MISALIGN(pSd) SD_CSD(pSd, 77, 1) ///< Read block misalignment
+#define SD_CSD_DSR_IMP(pSd) SD_CSD(pSd, 76, 1) ///< DSP implemented
+#define SD_CSD_C_SIZE(pSd) ((SD_CSD(pSd, 72, 2) << 10) + \
+ (SD_CSD(pSd, 64, 8) << 2) + \
+ SD_CSD(pSd, 62, 2)) ///< Device size
+#define SD_CSD_C_SIZE_HC(pSd) ((SD_CSD(pSd, 64, 6) << 16) + \
+ (SD_CSD(pSd, 56, 8) << 8) + \
+ SD_CSD(pSd, 48, 8)) ///< Device size v2.0 High Capacity
+#define SD_CSD_VDD_R_CURR_MIN(pSd) SD_CSD(pSd, 59, 3) ///< Max. read current @VDD min
+#define SD_CSD_VDD_R_CURR_MAX(pSd) SD_CSD(pSd, 56, 3) ///< Max. read current @VDD max
+#define SD_CSD_VDD_W_CURR_MIN(pSd) SD_CSD(pSd, 53, 3) ///< Max. write current @VDD min
+#define SD_CSD_VDD_W_CURR_MAX(pSd) SD_CSD(pSd, 50, 3) ///< Max. write current @VDD max
+#define SD_CSD_C_SIZE_MULT(pSd) SD_CSD(pSd, 47, 3) ///< Device size multiplier
+#define SD_CSD_ERASE_BLK_EN(pSd) SD_CSD(pSd, 46, 1) ///< Erase single block enable
+#define MMC_CSD_ERASE_BLK_EN(pSd) SD_CSD(pSd, 46, 1) ///< Erase single block enable
+#define MMC_CSD_ERASE_GRP_SIZE(pSd) SD_CSD(pSd, 42, 4) ///< Erase group size
+#define SD_CSD_ERASE_GRP_MULT(pSd) SD_CSD(pSd, 37, 4) ///< Erase group size multiplier
+#define SD_CSD_SECTOR_SIZE(pSd) ((SD_CSD(pSd, 40, 6) << 1) + SD_CSD(pSd, 39, 1)) ///< Erase sector size
+#define SD_CSD_WP_GRP_SIZE(pSd) SD_CSD(pSd, 32, 7) ///< Write protect group size
+#define SD_CSD_WP_GRP_ENABLE(pSd) SD_CSD(pSd, 31, 1) ///< write protect group enable
+#define SD_CSD_R2W_FACTOR(pSd) SD_CSD(pSd, 26, 3) ///< Write speed factor
+#define SD_CSD_WRITE_BL_LEN(pSd) ((SD_CSD(pSd, 24, 2) << 2) + SD_CSD(pSd, 22, 2)) ///< Max write block length
+#define SD_CSD_WRITE_BL_PARTIAL(pSd) SD_CSD(pSd, 21, 1) ///< Partial blocks for write allowed
+#define SD_CSD_CONTENT_PROT_APP(pSd) SD_CSD(pSd, 16, 1) ///< File format group
+#define SD_CSD_FILE_FORMAT_GRP(pSd) SD_CSD(pSd, 15, 1) ///< File format group
+#define SD_CSD_COPY(pSd) SD_CSD(pSd, 14, 1) ///< Copy flag (OTP)
+#define SD_CSD_PERM_WRITE_PROTECT(pSd) SD_CSD(pSd, 13, 1) ///< Permanent write protect
+#define SD_CSD_TMP_WRITE_PROTECT(pSd) SD_CSD(pSd, 12, 1) ///< Temporary write protection
+#define SD_CSD_FILE_FORMAT(pSd) SD_CSD(pSd, 10, 2) ///< File format
+#define SD_CSD_ECC(pSd) SD_CSD(pSd, 8, 2) ///< CRC
+#define SD_CSD_CRC(pSd) SD_CSD(pSd, 1, 7) ///< CRC
+#define SD_CSD_MULT(pSd) (1 << (SD_CSD_C_SIZE_MULT(pSd) + 2))
+#define SD_CSD_BLOCKNR(pSd) ((SD_CSD_C_SIZE(pSd) + 1) * SD_CSD_MULT(pSd))
+#define SD_CSD_BLOCKNR_HC(pSd) ((SD_CSD_C_SIZE_HC(pSd) + 1) * 1024)
+#define SD_CSD_BLOCK_LEN(pSd) (1 << SD_CSD_READ_BL_LEN(pSd))
+#define SD_CSD_TOTAL_SIZE(pSd) (SD_CSD_BLOCKNR(pSd) * SD_CSD_BLOCK_LEN(pSd))
+#define SD_CSD_TOTAL_SIZE_HC(pSd) ((SD_CSD_C_SIZE_HC(pSd) + 1) * 512* 1024)
+#define SD_TOTAL_SIZE(pSd) ((pSd)->totalSize)
+#define SD_TOTAL_BLOCK(pSd) ((pSd)->blockNr)
+
+// SCR register access macros (64 bits, 2 * 32 bits, 8 * 8 bits).
+#define SD_EXT_OFFSET_SD_SCR 0 // DW
+#define SD_SCR(pSd, bitfield, bits) \
+ ( ((char*)(pSd)->extData)[7 - ((bitfield)/8)] >> ((bitfield)%8) \
+ & ((1 << (bits)) - 1) \
+ )
+#define SD_SCR_SCR_STRUCTURE(pSd) SD_SCR(pSd, 60, 4)
+#define SD_SCR_SCR_STRUCTURE_1_0 0
+#define SD_SCR_SD_SPEC(pSd) SD_SCR(pSd, 56, 4)
+#define SD_SCR_SD_SPEC_1_0_01 0
+#define SD_SCR_SD_SPEC_1_10 1
+#define SD_SCR_SD_SPEC_2_00 2
+#define SD_SCR_DATA_STAT_AFTER_ERASE(pSd) SD_SCR(pSd, 55, 1)
+#define SD_SCR_SD_SECURITY(pSd) SD_SCR(pSd, 52, 3)
+#define SD_SCR_SD_SECURITY_NO 0
+#define SD_SCR_SD_SECURITY_NOTUSED 1
+#define SD_SCR_SD_SECURITY_1_01 2
+#define SD_SCR_SD_SECURITY_2_00 3
+#define SD_SCR_SD_BUS_WIDTHS(pSd) SD_SCR(pSd, 48, 4)
+#define SD_SCR_SD_BUS_WIDTH_1BITS (1 << 0)
+#define SD_SCR_SD_BUS_WIDTH_4BITS (1 << 2)
+
+// SD Status access macros (512 bits, 16 * 32 bits, 64 * 8 bits).
+#define SD_EXT_OFFSET_SD_STAT 2 // DW
+#define SD_STAT(pSd, bitfield, bits) \
+ ( ((char*)&(pSd)->extData[2])[63 - ((bitfield)/8)] >> ((bitfield)%8) \
+ & ((1 << (bits)) - 1) \
+ )
+/// Bus width, 00: default, 10:4-bit
+#define SD_STAT_DAT_BUS_WIDTH(pSd) SD_STAT(pSd, 510, 2)
+#define SD_STAT_DATA_BUS_WIDTH_1BIT 0x0
+#define SD_STAT_DATA_BUS_WIDTH_4BIT 0x2
+/// Secured Mode
+#define SD_STAT_SECURED_MODE(pSd) SD_STAT(pSd, 509, 1)
+/// SD Memory Cards as defined in 1.01~2.00
+#define SD_STAT_SD_CARD_TYPE(pSd) (SD_STAT(pSd, 480, 8) \
+ + (SD_STAT(pSd, 488, 8) << 8) )
+/// STD: ThisSize*Multi*BlockLen, HC: Size in bytes
+#define SD_STAT_SIZE_OF_PROTECTED_AREA(pSd) (SD_STAT(pSd, 448, 8) \
+ + (SD_STAT(pSd, 456, 8) << 8) \
+ + (SD_STAT(pSd, 464, 8) << 16) \
+ + (SD_STAT(pSd, 472, 8) << 24) )
+/// Speed Class, value can be calculated by Pw/2
+#define SD_STAT_SPEED_CLASS(pSd) SD_STAT(pSd, 440, 8)
+#define SD_STAT_SPEED_CLASS_0 0
+#define SD_STAT_SPEED_CLASS_2 1 // >= 2MB/s
+#define SD_STAT_SPEED_CLASS_4 2 // >= 4MB/s
+#define SD_STAT_SPEED_CLASS_6 3 // >= 6MB/s
+/// 8-bit, by 1MB/s step.
+#define SD_STAT_PERFORMANCE_MOVE(pSd) SD_STAT(pSd, 432, 8)
+/// AU Size, in power of 2 from 16KB
+#define SD_STAT_AU_SIZE(pSd) SD_STAT(pSd, 428, 4)
+#define SD_STAT_AU_SIZE_16K 1
+#define SD_STAT_AU_SIZE_32K 2
+#define SD_STAT_AU_SIZE_64K 3
+#define SD_STAT_AU_SIZE_128K 4
+#define SD_STAT_AU_SIZE_256K 5
+#define SD_STAT_AU_SIZE_512K 6
+#define SD_STAT_AU_SIZE_1M 7
+#define SD_STAT_AU_SIZE_2M 8
+#define SD_STAT_AU_SIZE_4M 9
+/// 16-bit, number of AUs erased.
+#define SD_STAT_ERASE_SIZE(pSd) (SD_STAT(pSd, 408, 8) \
+ + (SD_STAT(pSd, 416, 8) << 8) )
+#define SD_STAT_ERASE_TIMEOUT(pSd) SD_STAT(pSd, 402, 6)
+#define SD_STAT_ERASE_OFFSET(pSd) SD_STAT(pSd, 400, 2)
+
+// SD Switch Status access macros (512 bits, 16 * 32 bits, 64 * 8 bits).
+#define SD_SW_STAT(p, bitfield, bits) \
+ ( ((char*)(p))[63 - ((bitfield)/8)] >> ((bitfield)%8) \
+ & ((1 << (bits)) - 1) \
+ )
+#define SD_SW_STAT_MAX_CURRENT_CONSUMPTION(p) ( SD_SW_STAT(p, 496, 8) \
+ + (SD_SW_STAT(p, 504, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP6_INFO(p) ( SD_SW_STAT(p, 480, 8) \
+ + (SD_SW_STAT(p, 488, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP5_INFO(p) ( SD_SW_STAT(p, 464, 8) \
+ + (SD_SW_STAT(p, 472, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP4_INFO(p) ( SD_SW_STAT(p, 448, 8) \
+ + (SD_SW_STAT(p, 456, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP3_INFO(p) ( SD_SW_STAT(p, 432, 8) \
+ + (SD_SW_STAT(p, 440, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP2_INFO(p) ( SD_SW_STAT(p, 416, 8) \
+ + (SD_SW_STAT(p, 424, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP1_INFO(p) ( SD_SW_STAT(p, 400, 8) \
+ + (SD_SW_STAT(p, 408, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP6_RC(p) SD_SW_STAT(p, 396, 4)
+#define SD_SW_STAT_FUN_GRP5_RC(p) SD_SW_STAT(p, 392, 4)
+#define SD_SW_STAT_FUN_GRP4_RC(p) SD_SW_STAT(p, 388, 4)
+#define SD_SW_STAT_FUN_GRP3_RC(p) SD_SW_STAT(p, 384, 4)
+#define SD_SW_STAT_FUN_GRP2_RC(p) SD_SW_STAT(p, 380, 4)
+#define SD_SW_STAT_FUN_GRP1_RC(p) SD_SW_STAT(p, 376, 4)
+#define SD_SW_STAT_FUN_GRP_RC_ERROR 0xF
+#define SD_SW_STAT_DATA_STRUCT_VER(p) SD_SW_STAT(p, 368, 8)
+#define SD_SW_STAT_FUN_GRP6_BUSY(p) ( SD_SW_STAT(p, 352, 8) \
+ + (SD_SW_STAT(p, 360, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP5_BUSY(p) ( SD_SW_STAT(p, 336, 8) \
+ + (SD_SW_STAT(p, 344, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP4_BUSY(p) ( SD_SW_STAT(p, 320, 8) \
+ + (SD_SW_STAT(p, 328, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP3_BUSY(p) ( SD_SW_STAT(p, 304, 8) \
+ + (SD_SW_STAT(p, 312, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP2_BUSY(p) ( SD_SW_STAT(p, 288, 8) \
+ + (SD_SW_STAT(p, 296, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP1_BUSY(p) ( SD_SW_STAT(p, 272, 8) \
+ + (SD_SW_STAT(p, 280, 8) << 8) )
+#define SD_SW_STAT_FUN_GRP_FUN_BUSY(funNdx) (1 << (funNdx))
+
+// EXT_CSD register definition.
+#define SD_EXTCSD_S_CMD_SET_INDEX 504 // Below belongs to Properties Segment
+#define SD_EXTCSD_BOOT_INFO_INDEX 228
+#define SD_EXTCSD_BOOT_SIZE_MULTI_INDEX 226
+#define SD_EXTCSD_ACC_SIZE_INDEX 225
+#define SD_EXTCSD_HC_ERASE_GRP_SIZE_INDEX 224
+#define SD_EXTCSD_ERASE_TIMEOUT_MULT_INDEX 223
+#define SD_EXTCSD_REL_WR_SEC_C_INDEX 222
+#define SD_EXTCSD_HC_WP_GRP_SIZE_INDEX 221
+#define SD_EXTCSD_S_C_VCC_INDEX 220
+#define SD_EXTCSD_S_C_VCCQ_INDEX 219
+#define SD_EXTCSD_S_A_TIMEOUT_INDEX 217
+#define SD_EXTCSD_SEC_COUNT_INDEX 212
+#define SD_EXTCSD_MIN_PERF_W_8_52_INDEX 210
+#define SD_EXTCSD_MIN_PERF_R_8_52_INDEX 209
+#define SD_EXTCSD_MIN_PERF_W_8_26_4_52_INDEX 208
+#define SD_EXTCSD_MIN_PERF_R_8_26_4_52_INDEX 207
+#define SD_EXTCSD_MIN_PERF_W_4_26_INDEX 206
+#define SD_EXTCSD_MIN_PERF_R_4_26_INDEX 205
+#define SD_EXTCSD_PWR_CL_26_360_INDEX 203
+#define SD_EXTCSD_PWR_CL_52_360_INDEX 202
+#define SD_EXTCSD_PWR_CL_26_195_INDEX 201
+#define SD_EXTCSD_PWR_CL_52_195_INDEX 200
+#define SD_EXTCSD_CARD_TYPE_INDEX 196
+#define SD_EXTCSD_CSD_STRUCTURE_INDEX 194
+#define SD_EXTCSD_EXT_CSD_REV_INDEX 192
+
+#define SD_EXTCSD_CMD_SET_INDEX 191 //Below belongs to Mode Segment
+#define SD_EXTCSD_CMD_SET_REV_INDEX 189
+#define SD_EXTCSD_POWER_CLASS_INDEX 187
+#define SD_EXTCSD_HS_TIMING_INDEX 185
+#define SD_EXTCSD_BUS_WIDTH_INDEX 183
+#define SD_EXTCSD_ERASED_MEM_CONT_INDEX 181
+#define SD_EXTCSD_BOOT_CONFIG_INDEX 179
+#define SD_EXTCSD_BOOT_BUS_WIDTH_INDEX 177
+#define SD_EXTCSD_ERASE_GROUP_DEF_INDEX 175
+
+// Ext_CSD register access marco
+#define MMC_EXTCSD_U8(pSd, bytefield) \
+ ( ((unsigned char*)((pSd)->extData))[(bytefield)] )
+#define MMC_EXTCSD_U16(pSd, bytefield) \
+ ( (((unsigned char*)((pSd)->extData))[(bytefield) ] << 0) + \
+ (((unsigned char*)((pSd)->extData))[(bytefield) + 1] << 8) )
+#define MMC_EXTCSD_U32(pSd, bytefield) \
+ ( (((unsigned char*)((pSd)->extData))[(bytefield) ] << 0) + \
+ (((unsigned char*)((pSd)->extData))[(bytefield) + 1] << 8) + \
+ (((unsigned char*)((pSd)->extData))[(bytefield) + 2] << 16) + \
+ (((unsigned char*)((pSd)->extData))[(bytefield) + 24] << 24) )
+#define MMC_EXTCSD(pSd) ((unsigned char*)((pSd)->extData))
+#define SD_EXTCSD_S_CMD_SET(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_S_CMD_SET_INDEX]) // Supported Command Sets
+#define SD_EXTCSD_BOOT_INFO(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_BOOT_INFO_INDEX]) // Boot information
+#define SD_EXTCSD_BOOT_SIZE_MULTI(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_BOOT_SIZE_MULTI_INDEX]) // Boot partition size
+#define SD_EXTCSD_ACC_SIZE(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_ACC_SIZE_INDEX]) // Access size
+#define SD_EXTCSD_HC_ERASE_GRP_SIZE(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_HC_ERASE_GRP_SIZE_INDEX]) // High-capacity erase unit size
+#define SD_EXTCSD_ERASE_TIMEOUT_MULT(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_ERASE_TIMEOUT_MULT_INDEX]) // High-capacity erase timeout
+#define SD_EXTCSD_REL_WR_SEC_C(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_REL_WR_SEC_C_INDEX]) // Reliable write sector count
+#define SD_EXTCSD_HC_WP_GRP_SIZE(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_HC_WP_GRP_SIZE_INDEX]) // High-capacity write protect group size
+#define SD_EXTCSD_S_C_VCC(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_S_C_VCC_INDEX]) // Sleep current(VCC)
+#define SD_EXTCSD_S_C_VCCQ(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_S_C_VCCQ_INDEX]) // Sleep current(VCCQ)
+#define SD_EXTCSD_S_A_TIMEOUT(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_S_A_TIMEOUT_INDEX]) // Sleep/awake timeout
+#define SD_EXTCSD_SEC_COUNT(pSd) ((MMC_EXTCSD(pSd)[SD_EXTCSD_SEC_COUNT_INDEX]) + \
+ (MMC_EXTCSD(pSd)[SD_EXTCSD_SEC_COUNT_INDEX+1] << 8 ) + \
+ (MMC_EXTCSD(pSd)[SD_EXTCSD_SEC_COUNT_INDEX+2] << 16 ) + \
+ (MMC_EXTCSD(pSd)[SD_EXTCSD_SEC_COUNT_INDEX+3] << 24 )) //Sector Count
+#define SD_EXTCSD_MIN_PERF_W_8_52(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_MIN_PERF_W_8_52_INDEX]) // Minimum Write Performance for 8bit at 52MHz
+#define SD_EXTCSD_MIN_PERF_R_8_52(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_MIN_PERF_R_8_52_INDEX]) // Minimum Read Performance for 8bit at 52MHz
+#define SD_EXTCSD_MIN_PERF_W_8_26_4_52(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_MIN_PERF_W_8_26_4_52_INDEX]) // Minimum Write Performance for 8bit at 26MHz, for 4bit at 52MHz
+#define SD_EXTCSD_MIN_PERF_R_8_26_4_52(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_MIN_PERF_R_8_26_4_52_INDEX]) // Minimum Read Performance for 8bit at 26MHz, for 4bit at 52MHz
+#define SD_EXTCSD_MIN_PERF_W_4_26(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_MIN_PERF_W_4_26_INDEX]) // Minimum Write Performance for 4bit at 26MHz
+#define SD_EXTCSD_MIN_PERF_R_4_26(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_MIN_PERF_R_4_26_INDEX]) // Minimum Read Performance for 4bit at 26MHz
+#define SD_EXTCSD_PWR_CL_26_360(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_PWR_CL_26_360_INDEX]) // Power class for 26MHz at 3.6v
+#define SD_EXTCSD_PWR_CL_52_360(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_PWR_CL_52_360_INDEX]) // Power class for 52MHz at 3.6v
+#define SD_EXTCSD_PWR_CL_26_195(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_PWR_CL_26_195_INDEX]) // Power class for 26MHz at 1.95v
+#define SD_EXTCSD_PWR_CL_52_195(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_PWR_CL_52_195_INDEX]) // Power class for 52MHz at 1.95v
+#define SD_EXTCSD_CARD_TYPE(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_CARD_TYPE_INDEX]) // Card type
+#define SD_EXTCSD_CSD_STRUCTURE(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_CSD_STRUCTURE_INDEX]) // CSD structure version
+#define SD_EXTCSD_EXT_CSD_REV(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_EXT_CSD_REV_INDEX]) // Extended CSD structure version
+#define SD_EXTCSD_CMD_SET(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_CMD_SET_INDEX]) // Command set
+#define SD_EXTCSD_CMD_SET_REV(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_CMD_SET_REV_INDEX]) // Command set revision
+#define SD_EXTCSD_POWER_CLASS(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_POWER_CLASS_INDEX]) // Power class
+#define SD_EXTCSD_HS_TIMING(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_HS_TIMING_INDEX]) // High-speed interface timing
+#define SD_EXTCSD_BUS_WIDTH(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_BUS_WIDTH_INDEX]) // Bus width mode
+#define SD_EXTCSD_ERASED_MEM_CONT(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_ERASED_MEM_CONT_INDEX]) // Erased memory content
+#define SD_EXTCSD_BOOT_CONFIG(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_BOOT_CONFIG_INDEX]) // Boot configuration
+#define SD_EXTCSD_BOOT_BUS_WIDTH(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_BOOT_BUS_WIDTH_INDEX]) // Boot bus width
+#define SD_EXTCSD_ERASE_GROUP_DEF(pSd) (MMC_EXTCSD(pSd)[SD_EXTCSD_ERASE_GROUP_DEF_INDEX]) // High-density erase group definition
+
+// EXTCSD total size and block number
+#define SD_EXTCSD_TOTAL_SIZE(pSd) (SD_EXTCSD_SEC_COUNT(pSd)*512)
+#define SD_EXTCSD_BLOCKNR(pSd) (SD_EXTCSD_SEC_COUNT(pSd))
+
+// Bus width Byte
+#define SD_EXTCSD_BUS_WIDTH_1BIT (0x0UL)
+#define SD_EXTCSD_BUS_WIDTH_4BIT (0x1UL)
+#define SD_EXTCSD_BUS_WIDTH_8BIT (0x2UL)
+
+// High speed mode
+#define SD_EXTCSD_HS_TIMING_ENABLE (0x1UL)
+#define SD_EXTCSD_HS_TIMING_DISABLE (0x0UL)
+
+// Boot config
+#define SD_EXTCSD_BOOT_PARTITION_ACCESS (0x7UL) // boot partition access
+#define SD_EXTCSD_BOOT_PART_NO_ACCESS (0x0UL)
+#define SD_EXTCSD_BOOT_PART_RW_PART1 (0x1UL)
+#define SD_EXTCSD_BOOT_PART_RW_PART2 (0x2UL)
+#define SD_EXTCSD_BOOT_PARTITION_ENABLE (0x7UL << 3) // boot partition enable
+#define SD_EXTCSD_BOOT_PART_DISABLE (0x0UL << 3)
+#define SD_EXTCSD_BOOT_PART_ENABLE_PART1 (0x1UL << 3)
+#define SD_EXTCSD_BOOT_PART_ENABLE_PART2 (0x2UL << 3)
+#define SD_EXTCSD_BOOT_PART_ENABLE_USER (0x7UL << 3)
+#define SD_EXTCSD_BOOT_PARTITION_ACK (0x1UL << 7) // boot acknowledge
+#define SD_EXTCSD_BOOT_PART_NOACK (0x0UL << 7)
+#define SD_EXTCSD_BOOT_PART_ACK (0x1UL << 7)
+
+// Boot bus width
+#define SD_EXTCSD_BOOT_BUS_WIDTH_BIT (0x3UL) // boot bus width
+#define SD_EXTCSD_BOOT_BUS_1BIT (0x0UL)
+#define SD_EXTCSD_BOOT_BUS_4BIT (0x1UL)
+#define SD_EXTCSD_BOOT_BUS_8BIT (0x2UL)
+#define SD_EXTCSD_RESET_BOOT_BUS_WIDTH_BIT (0x1UL << 2) // boot bus width
+#define SD_EXTCSD_RESET_BOOT_BUS (0x0UL << 2)
+#define SD_EXTCSD_RETAIN_BOOT_BUS (0x1UL << 2)
+
+// Mode Switch Arguments for CMD6
+#define MMC_CMD6_ARG_ACCESS
+#define MMC_CMD6_ARG_INDEX
+#define MMC_CMD6_ARG_VALUE
+#define MMC_CMD6_ARG_CMDSET
+
+// SCR register access macros.
+#define SD_SCR_BUS_WIDTHS(pScr) ((pScr[1] >> 16) & 0xF) ///< Describes all the DAT bus that are supported by this card
+#define SD_SCR_BUS_WIDTH_4BITS (1 << 1) ///< 4bit Bus Width is supported
+#define SD_SCR_BUS_WIDTH_1BIT (1 << 0) ///< 1bit Bus Width is supported
+
+//------------------------------------------------------------------------------
+// Types
+//------------------------------------------------------------------------------
+
+/// SD end-of-transfer callback function.
+typedef void (*SdCallback)(unsigned char status, void *pCommand);
+
+//------------------------------------------------------------------------------
+/// SD Transfer Request prepared by the application upper layer. This structure
+/// is sent to the SD_SendCommand function to start the transfer. At the end of
+/// the transfer, the callback is invoked by the interrupt handler.
+//------------------------------------------------------------------------------
+typedef struct _SdCmd {
+
+ /// Command status.
+ volatile char status;
+ /// Command code.
+ unsigned int cmd;
+ /// Command argument.
+ unsigned int arg;
+ /// Data buffer.
+ unsigned char *pData;
+ /// Size of data buffer in bytes.
+ unsigned short blockSize;
+ /// Number of blocks to be transfered
+ unsigned short nbBlock;
+ /// Indicate if continue to transfer data
+ unsigned char conTrans;
+ /// Indicates if the command is a read operation.
+ unsigned char isRead;
+ /// Response buffer.
+ unsigned int *pResp;
+ /// SD card response type.
+ unsigned char resType;
+ /// Optional user-provided callback function.
+ SdCallback callback;
+ /// Optional argument to the callback function.
+ void *pArg;
+
+} SdCmd;
+
+//------------------------------------------------------------------------------
+/// SD driver structure. Holds the internal state of the SD driver and
+/// prevents parallel access to a SPI peripheral.
+//------------------------------------------------------------------------------
+typedef struct {
+
+ /// Pointer to a SPI peripheral.
+ //AT91S_MCI *pSdHw;
+ /// SPI peripheral identifier.
+ unsigned char spiId;
+ /// MCI HW mode
+ unsigned char mciMode;
+ /// Pointer to currently executing command.
+ SdCmd *pCommand;
+ /// Mutex.
+ volatile char semaphore;
+
+} SdDriver;
+
+//------------------------------------------------------------------------------
+/// Sdcard driver structure. It holds the current command being processed and
+/// the SD card address.
+//------------------------------------------------------------------------------
+typedef struct _SdCard {
+
+ /// Pointer to the underlying MCI driver.
+ SdDriver *pSdDriver;
+ /// Current MCI command being processed.
+ SdCmd command;
+ /// Card-specific data (CSD register)
+ unsigned int csd[4];
+ /// Previous access block number.
+ unsigned int preBlock;
+ /// Card total size
+ unsigned int totalSize;
+ /// Card block number
+ unsigned int blockNr;
+ /// SD card current address.
+ unsigned short cardAddress;
+ /// Card type
+ unsigned char cardType;
+ /// Card access mode
+ unsigned char mode;
+ /// State after sd command complete
+ unsigned char state;
+} SdCard;
+
+//------------------------------------------------------------------------------
+// Global functions
+//------------------------------------------------------------------------------
+
+extern unsigned char SD_Init(SdCard *pSd,
+ SdDriver *pSdDriver);
+
+extern unsigned char SD_ReadBlock(
+ SdCard *pSd,
+ unsigned int address,
+ unsigned short nbBlocks,
+ unsigned char *pData);
+
+extern unsigned char SD_WriteBlock(
+ SdCard *pSd,
+ unsigned int address,
+ unsigned short nbBlocks,
+ const unsigned char *pData);
+
+extern unsigned char SD_Stop(SdCard *pSd, SdDriver *pSdDriver);
+
+extern void SD_DisplayRegisterCSD(SdCard *pSd);
+
+#endif //#ifndef SDCARD_H
+
diff --git a/memories/sdmmc/sdspi.c b/memories/sdmmc/sdspi.c
new file mode 100644
index 0000000..93b7629
--- /dev/null
+++ b/memories/sdmmc/sdspi.c
@@ -0,0 +1,711 @@
+/* ----------------------------------------------------------------------------
+ * ATMEL Microcontroller Software Support
+ * ----------------------------------------------------------------------------
+ * Copyright (c) 2008, Atmel Corporation
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the disclaimer below.
+ *
+ * Atmel's name may not be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
+ * DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ----------------------------------------------------------------------------
+ */
+
+//------------------------------------------------------------------------------
+// Headers
+//------------------------------------------------------------------------------
+
+#include "sdspi.h"
+#include <utility/assert.h>
+#include <utility/trace.h>
+#include <board.h>
+#include <crc7.h>
+#include <crc-itu-t.h>
+#include <crc16.h>
+#include <crc-ccitt.h>
+#include <string.h>
+
+//------------------------------------------------------------------------------
+// Macros
+//------------------------------------------------------------------------------
+
+/// Transfer is pending.
+#define SDSPI_STATUS_PENDING 1
+/// Transfer has been aborted because an error occured.
+#define SDSPI_STATUS_ERROR 2
+
+/// SPI driver is currently in use.
+#define SDSPI_ERROR_LOCK 1
+
+// Data Tokens
+#define SDSPI_START_BLOCK_1 0xFE // Single/Multiple read, single write
+#define SDSPI_START_BLOCK_2 0xFC // Multiple block write
+#define SDSPI_STOP_TRAN 0xFD // Cmd12
+
+//------------------------------------------------------------------------------
+// Exported functions
+//------------------------------------------------------------------------------
+
+//------------------------------------------------------------------------------
+/// Initializes the SD Spi structure and the corresponding SPI hardware.
+/// \param pSpid Pointer to a Spid instance.
+/// \param pSpiHw Associated SPI peripheral.
+/// \param spiId SPI peripheral identifier.
+//------------------------------------------------------------------------------
+void SDSPI_Configure(SdSpi *pSdSpi,
+ AT91PS_SPI pSpiHw,
+ unsigned char spiId)
+{
+ // Initialize the SPI structure
+ pSdSpi->pSpiHw = pSpiHw;
+ pSdSpi->spiId = spiId;
+ pSdSpi->semaphore = 1;
+
+ // Enable the SPI clock
+ AT91C_BASE_PMC->PMC_PCER = (1 << pSdSpi->spiId);
+
+ // Execute a software reset of the SPI twice
+ pSpiHw->SPI_CR = AT91C_SPI_SWRST;
+ pSpiHw->SPI_CR = AT91C_SPI_SWRST;
+
+ // Configure SPI in Master Mode with No CS selected !!!
+ pSpiHw->SPI_MR = AT91C_SPI_MSTR | AT91C_SPI_MODFDIS | AT91C_SPI_PCS;
+
+ // Disables the receiver PDC transfer requests
+ // Disables the transmitter PDC transfer requests.
+ pSpiHw->SPI_PTCR = AT91C_PDC_RXTDIS | AT91C_PDC_TXTDIS;
+
+ // Enable the SPI
+ pSpiHw->SPI_CR = AT91C_SPI_SPIEN;
+
+ // Disable the SPI clock
+ AT91C_BASE_PMC->PMC_PCDR = (1 << pSdSpi->spiId);
+}
+
+//------------------------------------------------------------------------------
+/// Configures the parameters for the device corresponding to the cs.
+/// \param pSdSpi Pointer to a SdSpi instance.
+/// \param cs number corresponding to the SPI chip select.
+/// \param csr SPI_CSR value to setup.
+//------------------------------------------------------------------------------
+void SDSPI_ConfigureCS(SdSpi *pSdSpi, unsigned char cs, unsigned int csr)
+{
+ unsigned int spiMr;
+ AT91S_SPI *pSpiHw = pSdSpi->pSpiHw;
+
+ // Enable the SPI clock
+ AT91C_BASE_PMC->PMC_PCER = (1 << pSdSpi->spiId);
+
+ //TRACE_DEBUG("CSR[%d]=0x%8X\n\r", cs, csr);
+ pSpiHw->SPI_CSR[cs] = csr;
+
+//jcb to put in sendcommand
+ // Write to the MR register
+ spiMr = pSpiHw->SPI_MR;
+ spiMr |= AT91C_SPI_PCS;
+ spiMr &= ~((1 << cs) << 16);
+ pSpiHw->SPI_MR = spiMr;
+
+ // Disable the SPI clock
+ AT91C_BASE_PMC->PMC_PCDR = (1 << pSdSpi->spiId);
+}
+
+//------------------------------------------------------------------------------
+/// Use PDC for SPI data transfer.
+/// Return 0 if no error, otherwise return error status.
+/// \param pSdSpi Pointer to a SdSpi instance.
+/// \param pData Data pointer.
+/// \param size Data transfer byte count.
+//------------------------------------------------------------------------------
+unsigned char SDSPI_PDC(SdSpi *pSdSpi, unsigned char *pData, unsigned int size)
+{
+ AT91PS_SPI pSpiHw = pSdSpi->pSpiHw;
+ unsigned int spiIer;
+
+ if (pSdSpi->semaphore == 0) {
+ TRACE_DEBUG("No semaphore\n\r");
+ return SDSPI_ERROR_LOCK;
+ }
+ pSdSpi->semaphore--;
+
+ // Enable the SPI clock
+ AT91C_BASE_PMC->PMC_PCER = (1 << pSdSpi->spiId);
+
+ // Disable transmitter and receiver
+ pSpiHw->SPI_PTCR = AT91C_PDC_RXTDIS | AT91C_PDC_TXTDIS;
+
+ // Receive Pointer Register
+ pSpiHw->SPI_RPR = (int)pData;
+ // Receive Counter Register
+ pSpiHw->SPI_RCR = size;
+ // Transmit Pointer Register
+ pSpiHw->SPI_TPR = (int) pData;
+ // Transmit Counter Register
+ pSpiHw->SPI_TCR = size;
+
+ spiIer = AT91C_SPI_RXBUFF;
+
+ // Enable transmitter and receiver
+ pSpiHw->SPI_PTCR = AT91C_PDC_RXTEN | AT91C_PDC_TXTEN;
+
+ // Interrupt enable shall be done after PDC TXTEN and RXTEN
+ pSpiHw->SPI_IER = spiIer;
+
+ return 0;
+}
+
+//! Should be moved to a new file
+//------------------------------------------------------------------------------
+/// Read data on SPI data bus;
+/// Returns 1 if read fails, returns 0 if no error.
+/// \param pSdSpi Pointer to a SD SPI driver instance.
+/// \param pData Data pointer.
+/// \param size Data size.
+//------------------------------------------------------------------------------
+unsigned char SDSPI_Read(SdSpi *pSdSpi, unsigned char *pData, unsigned int size)
+{
+ unsigned char error;
+
+ // MOSI should hold high during read, or there will be wrong data in received data.
+ memset(pData, 0xff, size);
+
+ error = SDSPI_PDC(pSdSpi, pData, size);
+
+ while(SDSPI_IsBusy(pSdSpi) == 1);
+
+ if( error == 0 ) {
+ return 0;
+ }
+ else {
+ TRACE_DEBUG("PB SDSPI_Read\n\r");
+ return 1;
+ }
+}
+
+//------------------------------------------------------------------------------
+/// Write data on SPI data bus;
+/// Returns 1 if write fails, returns 0 if no error.
+/// \param pSdSpi Pointer to a SD SPI driver instance.
+/// \param pData Data pointer.
+/// \param size Data size.
+//------------------------------------------------------------------------------
+unsigned char SDSPI_Write(SdSpi *pSdSpi, unsigned char *pData, unsigned int size)
+{
+ unsigned char error;
+
+ error = SDSPI_PDC(pSdSpi, pData, size);
+
+ while(SDSPI_IsBusy(pSdSpi) == 1);
+
+ if( error == 0 ) {
+ return 0;
+ }
+ else {
+ TRACE_DEBUG("PB SDSPI_Write\n\r");
+ return 1;
+ }
+}
+
+//------------------------------------------------------------------------------
+/// Return 1 if data busy.
+//------------------------------------------------------------------------------
+unsigned char SDSPI_WaitDataBusy(SdSpi *pSdSpi)
+{
+ unsigned char busyData;
+
+ SDSPI_Read(pSdSpi, &busyData, 1);
+
+ if (busyData != 0xff) {
+ return 1;
+ }
+ else {
+ return 0;
+ }
+}
+
+//------------------------------------------------------------------------------
+/// Convert SD MCI command to a SPI mode command token.
+/// \param pCmdToken Pointer to the SD command token.
+/// \param arg SD command argument
+//------------------------------------------------------------------------------
+void SDSPI_MakeCmd(unsigned char *pCmdToken, unsigned int arg)
+{
+ unsigned char sdCmdNum;
+ unsigned char crc = 0;
+ unsigned char crcPrev = 0;
+
+ sdCmdNum = 0x3f & *pCmdToken;
+ *pCmdToken = sdCmdNum | 0x40;
+ *(pCmdToken+1) = (arg >> 24) & 0xff;
+ *(pCmdToken+2) = (arg >> 16) & 0xff;
+ *(pCmdToken+3) = (arg >> 8) & 0xff;
+ *(pCmdToken+4) = arg & 0xff;
+
+ crc = crc7(crcPrev, (unsigned char *)(pCmdToken), 5);
+
+ *(pCmdToken+5) = (crc << 1) | 1;
+}
+
+//------------------------------------------------------------------------------
+/// Get response after send SD command.
+/// Return 0 if no error, otherwise indicate an error.
+/// \param pSdSpi Pointer to the SD SPI instance.
+/// \param pCommand Pointer to the SD command
+//------------------------------------------------------------------------------
+unsigned char SDSPI_GetCmdResp(SdSpi *pSdSpi, SdSpiCmd *pCommand)
+{
+ unsigned char resp[8]; // response
+ unsigned char error;
+ unsigned int respRetry = 8; //NCR max 8, refer to card datasheet
+
+ memset(resp, 0, 8);
+
+ // NCR: 1 ~ 8 * (8)
+ // Wait for response start bit.
+ do {
+ error = SDSPI_Read(pSdSpi, &resp[0], 1);
+ if (error) {
+ TRACE_INFO("_GetCmdResp Err: 0x%X\n\r", error);
+ return error;
+ }
+ if ((resp[0]&0x80) == 0) {
+ break;
+ }
+ respRetry--;
+ } while(respRetry > 0);
+
+ if (respRetry == 0) {
+ TRACE_WARNING("Cmd %d No Resp\n\r", pCommand->cmd & 0x3F);
+ return SDSPI_NO_RESPONSE;
+ }
+
+ switch (pCommand->resType) {
+ case 1:
+ *(pCommand->pResp) = resp[0];
+ break;
+
+ case 2:
+ error = SDSPI_Read(pSdSpi, &resp[1], 1);
+ if (error) {
+ return SDSPI_ERROR;
+ }
+ *(pCommand->pResp) = resp[0]
+ | (resp[1] << 8);
+ break;
+
+ // Response 3, get OCR
+ case 3:
+ error = SDSPI_Read(pSdSpi, &resp[1], 4);
+ if (error) {
+ return SDSPI_ERROR;
+ }
+ *(pCommand->pResp) = resp[0]
+ | (resp[1] << 8)
+ | (resp[2] << 16)
+ | (resp[3] << 24);
+ *(pCommand->pResp+1) = resp[4];
+ break;
+
+ case 7:
+ TRACE_DEBUG("case 7\n\r");
+ error = SDSPI_Read(pSdSpi, &resp[1], 4);
+ if (error) {
+ return SDSPI_ERROR;
+ }
+ *(pCommand->pResp) = resp[0]
+ | (resp[1] << 8)
+ | (resp[2] << 16)
+ | (resp[3] << 24);
+ *(pCommand->pResp+1) = resp[4];
+ break;
+
+ default:
+ TRACE_DEBUG("No Resp Type?\n\r");
+ break;
+ }
+
+ return SDSPI_SUCCESS;
+}
+
+//------------------------------------------------------------------------------
+/// Get response after send data.
+/// Return SDSPI_DATA_NO_RESP or data response token.
+/// \param pSdSpi Pointer to the SD SPI instance.
+/// \param pCommand Pointer to the SD command
+//------------------------------------------------------------------------------
+unsigned char SDSPI_GetDataResp(SdSpi *pSdSpi, SdSpiCmd *pCommand)
+{
+ unsigned char resp = 0; // response
+ unsigned char error;
+ unsigned int respRetry = 100; //NCR max 8, refer to card datasheet
+
+ // Wait for response start bit.
+ do {
+ error = SDSPI_Read(pSdSpi, &resp, 1);
+ if (error) {
+ return SDSPI_ERROR;
+ }
+
+ // Data Response Token
+ if ((resp & 0x11) == 0x1)
+ return (resp & 0x1F);
+
+ //if ((resp & 0xF0) == 0)
+ // break;
+
+ respRetry--;
+ } while(respRetry > 0);
+
+ return SDSPI_DATA_NO_RESP;
+}
+
+//------------------------------------------------------------------------------
+/// Starts a SPI master transfer. This is a non blocking function. It will
+/// return as soon as the transfer is started.
+/// Returns 0 if the transfer has been started successfully; otherwise returns
+/// error.
+/// \param pSdSpi Pointer to a SdSpi instance.
+/// \param pCommand Pointer to the SPI command to execute.
+//------------------------------------------------------------------------------
+unsigned char SDSPI_SendCommand(SdSpi *pSdSpi, SdSpiCmd *pCommand)
+{
+ AT91S_SPI *pSpiHw = pSdSpi->pSpiHw;
+ unsigned char CmdToken[6];
+ unsigned char *pData;
+ unsigned int blockSize;
+ unsigned int i;
+ unsigned char error;
+ unsigned char dataHeader;
+ unsigned int dataRetry1 = 200000;
+ unsigned int dataRetry2 = 200000;
+ unsigned char crc[2];
+ unsigned char crcPrev = 0;
+ unsigned char crcPrev2 = 0;
+
+ SANITY_CHECK(pSdSpi);
+ SANITY_CHECK(pSpiHw);
+ SANITY_CHECK(pCommand);
+
+ CmdToken[0] = pCommand->cmd & 0x3F;
+ pData = pCommand->pData;
+ blockSize = pCommand->blockSize;
+
+ SDSPI_MakeCmd((unsigned char *)&CmdToken, pCommand->arg);
+
+ // Command is now being executed
+ pSdSpi->pCommand = pCommand;
+ pCommand->status = SDSPI_STATUS_PENDING;
+
+ // Send the command
+ if((pCommand->conTrans == SPI_NEW_TRANSFER) || (blockSize == 0)) {
+
+ TRACE_DEBUG("SendCmd%d\n\r", pCommand->cmd & 0x3F);
+ for(i = 0; i < 6; i++) {
+ error = SDSPI_Write(pSdSpi, &CmdToken[i], 1);
+ if (error) {
+ TRACE_DEBUG("Error WrCmd[i]: %d\n\r", i, error);
+ return error;
+ }
+ }
+ error = SDSPI_GetCmdResp(pSdSpi, pCommand);
+ if (error) {
+ TRACE_DEBUG("Error GetResp: %d\n\r", error);
+ return error;
+ }
+ }
+
+ if( (blockSize > 0) && (pCommand->nbBlock == 0) ) {
+ pCommand->nbBlock = 1;
+ }
+
+ // For data block operations
+ while (pCommand->nbBlock > 0) {
+
+ // If data block size is invalid, return error
+ if (blockSize == 0) {
+ TRACE_DEBUG("Block Size = 0\n\r");
+ return 1;
+ }
+
+ // DATA transfer from card to host
+ if (pCommand->isRead) {
+
+ TRACE_DEBUG("RD\n\r");
+
+ do {
+ SDSPI_Read(pSdSpi, &dataHeader, 1);
+ TRACE_DEBUG("R Hdr %x\n\r", dataHeader);
+ if (dataHeader == SDSPI_START_BLOCK_1) {
+ break;
+ }
+ else if((dataHeader & 0xf0) == 0x00) {
+ pCommand->status = SDSPI_STATUS_ERROR;
+ TRACE_ERROR("R Data Hdr 0x%X!\n\r", dataHeader);
+ return SDSPI_ERROR;
+ }
+ dataRetry1 --;
+ } while(dataRetry1 > 0);
+
+ if (dataRetry1 == 0) {
+ TRACE_DEBUG("Timeout data RD retry\n\r");
+ return SDSPI_ERROR;
+ }
+
+ SDSPI_Read(pSdSpi, pData, blockSize);
+
+ // CRC is not for R3, CSD, CID
+ if ((pCommand->cmd & 0x3f) != 9 &&
+ (pCommand->cmd & 0x3f) != 10 &&
+ pCommand->resType != 3)
+ {
+
+ SDSPI_Read(pSdSpi, crc, 2);
+#ifdef SDSPI_CRC_ON
+ // Check data CRC
+ TRACE_DEBUG("Check Data CRC\n\r");
+ crcPrev = 0;
+ crcPrev2 = 0;
+ if (crc[0] != ((crc_itu_t(crcPrev, pData, blockSize) & 0xff00) >> 8 )
+ || crc[1] != (crc_itu_t(crcPrev2, pData, blockSize) & 0xff)) {
+ TRACE_ERROR("CRC error 0x%X 0x%X 0x%X\n\r", \
+ crc[0], crc[1], crc_itu_t(pData, blockSize));
+ return SDSPI_ERROR;
+ }
+#endif
+ }
+ }
+
+ // DATA transfer from host to card
+ else {
+
+ TRACE_DEBUG("WR\n\r");
+
+ SANITY_CHECK(pCommand->pResp);
+
+ //SDSPI_NCS(pSdSpi);
+ if ( (pCommand->conTrans == SPI_CONTINUE_TRANSFER)
+ || ((pCommand->cmd & 0x3f) == 25)) {
+ dataHeader = SDSPI_START_BLOCK_2;
+ }
+ else {
+ dataHeader = SDSPI_START_BLOCK_1;
+ }
+
+ crcPrev = 0;
+ crc[0] = (crc_itu_t(crcPrev, pData, blockSize) & 0xff00) >> 8;
+ crcPrev2 = 0;
+ crc[1] = (crc_itu_t(crcPrev2, pData, blockSize) & 0xff);
+ SDSPI_Write(pSdSpi, &dataHeader, 1);
+ SDSPI_Write(pSdSpi, pData, blockSize);
+ SDSPI_Write(pSdSpi, crc, 2);
+
+ // Check response status
+ error = SDSPI_GetDataResp(pSdSpi, pCommand);
+ switch(error) {
+
+ case SDSPI_DATA_ACCEPTED: break;
+
+ case SDSPI_DATA_CRC_ERR:
+ TRACE_ERROR("WR CRC\n\r");
+ return SDSPI_ERROR;
+
+ case SDSPI_DATA_WR_ERR:
+ TRACE_ERROR("WR ERR\n\r");
+ return SDSPI_ERROR;
+
+ default:
+ TRACE_ERROR("WR RESP %x\n\r", error);
+ return SDSPI_ERROR;
+ }
+
+ do {
+ if (SDSPI_WaitDataBusy(pSdSpi) == 0) {
+ break;
+ }
+ dataRetry2--;
+ } while(dataRetry2 > 0);
+
+ if (dataRetry2 == 0) {
+ TRACE_ERROR("WR Busy timeout\n\r");
+ return SDSPI_BUSY;
+ }
+ }
+ pData += blockSize;
+ pCommand->nbBlock--;
+ }
+
+ if (pCommand->status == SDSPI_STATUS_PENDING) {
+ pCommand->status = 0;
+ }
+
+ //TRACE_DEBUG("end SDSPI_SendCommand\n\r");
+ return 0;
+}
+//!
+
+//------------------------------------------------------------------------------
+/// The SPI_Handler must be called by the SPI Interrupt Service Routine with the
+/// corresponding Spi instance.
+/// The SPI_Handler will unlock the Spi semaphore and invoke the upper application
+/// callback.
+/// \param pSdSpi Pointer to a SdSpi instance.
+//------------------------------------------------------------------------------
+void SDSPI_Handler(SdSpi *pSdSpi)
+{
+ SdSpiCmd *pCommand = pSdSpi->pCommand;
+ AT91S_SPI *pSpiHw = pSdSpi->pSpiHw;
+ volatile unsigned int spiSr;
+
+ // Read the status register
+ spiSr = pSpiHw->SPI_SR;
+ if(spiSr & AT91C_SPI_RXBUFF) {
+
+ if (pCommand->status == SDSPI_STATUS_PENDING) {
+ pCommand->status = 0;
+ }
+ // Disable transmitter and receiver
+ pSpiHw->SPI_PTCR = AT91C_PDC_RXTDIS | AT91C_PDC_TXTDIS;
+
+ // Disable the SPI clock
+ AT91C_BASE_PMC->PMC_PCDR = (1 << pSdSpi->spiId);
+
+ // Disable buffer complete interrupt
+ pSpiHw->SPI_IDR = AT91C_SPI_RXBUFF | AT91C_SPI_ENDTX;
+
+ // Release the SPI semaphore
+ pSdSpi->semaphore++;
+ }
+
+ // Invoke the callback associated with the current command
+ if (pCommand && pCommand->callback) {
+ pCommand->callback(0, pCommand);
+ }
+}
+
+//------------------------------------------------------------------------------
+/// Returns 1 if the given SPI transfer is complete; otherwise returns 0.
+/// \param pCommand Pointer to a SdSpiCmd instance.
+//------------------------------------------------------------------------------
+unsigned char SDSPI_IsTxComplete(SdSpiCmd *pCommand)
+{
+ if (pCommand->status != SDSPI_STATUS_PENDING) {
+ if (pCommand->status != 0){
+ TRACE_DEBUG("SPI_IsTxComplete %d\n\r", pCommand->status);
+ }
+ return 1;
+ }
+ else {
+ return 0;
+ }
+}
+
+//------------------------------------------------------------------------------
+/// Close a SPI driver instance and the underlying peripheral.
+/// \param pSdSpi Pointer to a SD SPI driver instance.
+//------------------------------------------------------------------------------
+void SDSPI_Close(SdSpi *pSdSpi)
+{
+ AT91S_SPI *pSpiHw = pSdSpi->pSpiHw;
+
+ SANITY_CHECK(pSdSpi);
+ SANITY_CHECK(pSpiHw);
+
+ // Enable the SPI clock
+ AT91C_BASE_PMC->PMC_PCER = (1 << pSdSpi->spiId);
+
+ // Disable the PDC transfer
+ pSpiHw->SPI_PTCR = AT91C_PDC_RXTDIS | AT91C_PDC_TXTDIS;
+
+ // Disable the SPI
+ pSpiHw->SPI_CR = AT91C_SPI_SPIDIS;
+
+ // Disable the SPI clock
+ AT91C_BASE_PMC->PMC_PCDR = (1 << pSdSpi->spiId);
+
+ // Disable all the interrupts
+ pSpiHw->SPI_IDR = 0xFFFFFFFF;
+}
+
+//------------------------------------------------------------------------------
+/// Returns 1 if the SPI driver is currently busy programming;
+/// otherwise returns 0.
+/// \param pSdSpi Pointer to a SD SPI driver instance.
+//------------------------------------------------------------------------------
+unsigned char SDSPI_IsBusy(SdSpi *pSdSpi)
+{
+ if (pSdSpi->semaphore == 0) {
+ return 1;
+ }
+ else {
+ return 0;
+ }
+}
+
+//------------------------------------------------------------------------------
+/// Wait several cycles on SPI bus;
+/// Returns 0 to indicates no error, otherwise return 1.
+/// \param pSdSpi Pointer to a SD SPI driver instance.
+/// \param cycles Wait data cycles.
+//------------------------------------------------------------------------------
+unsigned char SDSPI_Wait(SdSpi *pSdSpi, unsigned int cycles)
+{
+ unsigned int i = cycles;
+ unsigned char data = 0xff;
+
+ for (; i > 0; i--) {
+ if (SDSPI_Read(pSdSpi, &data, 1)) {
+ return 1;
+ }
+ }
+ return 0;
+}
+
+//------------------------------------------------------------------------------
+/// Send stop transfer data token;
+/// Returns 0 to indicates no error, otherwise return 1.
+/// \param pSdSpi Pointer to a SD SPI driver instance.
+//------------------------------------------------------------------------------
+unsigned char SDSPI_StopTranToken(SdSpi *pSdSpi)
+{
+ unsigned char stopToken = SDSPI_STOP_TRAN;
+
+ TRACE_DEBUG("SDSPI_StopTranToken\n\r");
+ return SDSPI_Write(pSdSpi, &stopToken, 1);
+}
+
+//------------------------------------------------------------------------------
+/// Wait, SD card Ncs cycles;
+/// Returns 0 to indicates no error, otherwise return 1.
+/// \param pSdSpi Pointer to a SD SPI driver instance.
+//------------------------------------------------------------------------------
+unsigned char SDSPI_NCS(SdSpi *pSdSpi)
+{
+ unsigned int i;
+ unsigned char ncs;
+
+ for(i = 0; i < 15; i++) {
+ ncs = 0xff;
+ if (SDSPI_Write(pSdSpi, &ncs, 1)) {
+ return 1;
+ }
+ }
+ return 0;
+}
+
+
diff --git a/memories/sdmmc/sdspi.h b/memories/sdmmc/sdspi.h
new file mode 100644
index 0000000..9f267ec
--- /dev/null
+++ b/memories/sdmmc/sdspi.h
@@ -0,0 +1,184 @@
+/* ----------------------------------------------------------------------------
+ * ATMEL Microcontroller Software Support
+ * ----------------------------------------------------------------------------
+ * Copyright (c) 2008, Atmel Corporation
+
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the disclaimer below.
+ *
+ * Atmel's name may not be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
+ * DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ----------------------------------------------------------------------------
+ */
+
+//------------------------------------------------------------------------------
+/// \page "sdspi"
+///
+/// !Purpose
+///
+/// sdcard spi-bus driver
+///
+/// !Usage
+///
+/// -# SDSPI_Configure: Initializes the SD Spi structure and the corresponding SPI hardware
+/// -# SDSPI_ConfigureCS : Configures the parameters for the device corresponding to the cs
+/// -# SDSPI_Read: Read data on SPI data bus
+/// -# SDSPI_Write : Write data on SPI data bus
+/// -# SDSPI_SendCommand : Starts a SPI master transfer
+/// -# SDSPI_StopTranToken : Send stop transfer data token
+//------------------------------------------------------------------------------
+
+#ifndef SDSPI_H
+#define SDSPI_H
+
+//------------------------------------------------------------------------------
+// Headers
+//------------------------------------------------------------------------------
+
+#include <board.h>
+#include <spi/spi.h>
+
+#define SDSPI_SUCCESS 0
+#define SDSPI_ERROR 1
+#define SDSPI_NO_RESPONSE 2
+#define SDSPI_BUSY 4
+
+// Data Response Token RC
+#define SDSPI_DATA_NO_RESP 0x1
+#define SDSPI_DATA_ACCEPTED 0x5
+#define SDSPI_DATA_CRC_ERR 0xB
+#define SDSPI_DATA_WR_ERR 0xD
+
+/// SPI CSR value
+//#define SDSPI_CSR(scbr) ( AT91C_SPI_CPOL \
+// | AT91C_SPI_BITS_8 \
+// | (((scbr)<< 8) & AT91C_SPI_SCBR) \
+// | ( (0x08 << 16) & AT91C_SPI_DLYBS)\
+// | ( (0x01 << 24) & AT91C_SPI_DLYBCT) )
+
+/// Calculates the value of the SCBR field of the Chip Select Register given
+/// MCK and SPCK.
+#define SPID_CSR_SCBR(mck, spck) ((((mck) / (spck)) << 8) & AT91C_SPI_SCBR)
+
+/// Calculates the value of the DLYBS field of the Chip Select Register given
+/// the delay in ns and MCK.
+#define SPID_CSR_DLYBS(mck, delay) \
+ ((((((delay) * ((mck) / 1000000)) / 1000) + 1) << 16) & AT91C_SPI_DLYBS)
+
+/// Calculates the value of the DLYBCT field of the Chip Select Register given
+/// the delay in ns and MCK.
+#define SPID_CSR_DLYBCT(mck, delay) \
+ ((((((delay) / 32 * ((mck) / 1000000)) / 1000) + 1) << 24) & AT91C_SPI_DLYBCT)
+
+#define SDSPI_CSR(mck, spck) \
+ (AT91C_SPI_NCPHA | SPID_CSR_DLYBCT(mck, 20) \
+ | SPID_CSR_DLYBS(mck, 20) | SPID_CSR_SCBR(mck, spck) \
+ | 0 /*AT91C_SPI_CSAAT*/ \
+ )
+
+
+/// Start new data transfer
+#define SPI_NEW_TRANSFER 0
+/// Continue data transfer
+#define SPI_CONTINUE_TRANSFER 1
+
+/// SD end-of-transfer callback function.
+typedef void (*SdSpiCallback)(unsigned char status, void *pCommand);
+
+//------------------------------------------------------------------------------
+/// SPI Transfer Request prepared by the application upper layer. This structure
+/// is sent to the SDSPI_SendCommand function to start the transfer. At the end of
+/// the transfer, the callback is invoked by the interrupt handler.
+//------------------------------------------------------------------------------
+typedef struct _SdSpiCmd {
+
+ /// Command status.
+ volatile char status;
+ /// Command code.
+ unsigned int cmd;
+ /// Command argument.
+ unsigned int arg;
+ /// Data buffer.
+ unsigned char *pData;
+ /// Size of data buffer in bytes.
+ unsigned short blockSize;
+ /// Number of blocks to be transfered
+ unsigned short nbBlock;
+ /// Indicate if continue to transfer data
+ unsigned char conTrans;
+ /// Indicates if the command is a read operation.
+ unsigned char isRead;
+ /// Response buffer.
+ unsigned int *pResp;
+ /// Size of SD card response in bytes.
+ unsigned char resType;
+ /// Optional user-provided callback function.
+ SdSpiCallback callback;
+ /// Optional argument to the callback function.
+ void *pArg;
+
+} SdSpiCmd;
+
+/// Above should be put into SD card header file.
+
+//------------------------------------------------------------------------------
+/// SPI driver structure. Holds the internal state of the SPI driver and
+/// prevents parallel access to a SPI peripheral.
+//------------------------------------------------------------------------------
+typedef struct {
+
+ /// Pointer to a SPI peripheral.
+ AT91S_SPI *pSpiHw;
+ /// Pointer to currently executing command.
+ SdSpiCmd *pCommand;
+ /// Default max timeout (calculated from TAAC & NSAC)
+ ///unsigned int max;
+ /// SPI peripheral identifier.
+ unsigned char spiId;
+ /// Mutex.
+ volatile char semaphore;
+
+} SdSpi;
+
+extern void SDSPI_Configure(SdSpi *pSdSpi,AT91PS_SPI pSpiHw,unsigned char spiId);
+
+extern void SDSPI_SetSpeed(SdSpi *pSdSpi, unsigned int spiSpeed);
+
+extern unsigned char SDSPI_SendCommand(SdSpi *pSdSpi, SdSpiCmd *pSdSpiCmd);
+
+extern void SDSPI_Handler(SdSpi *pSdSpi);
+
+extern unsigned char SDSPI_IsTxComplete(SdSpiCmd *pSdSpiCmd);
+
+extern unsigned char SDSPI_IsBusy(SdSpi *pSdSpi);
+
+extern unsigned char SDSPI_NCS(SdSpi *pSdSpi);
+
+extern void SDSPI_Close(SdSpi *pSdSpi);
+
+extern void SDSPI_ConfigureCS(SdSpi *pSdSpi, unsigned char cs, unsigned int csr);
+
+extern unsigned char SDSPI_StopTranToken(SdSpi *pSdSpi);
+
+extern unsigned char SDSPI_Wait(SdSpi *pSdSpi, unsigned int cycles);
+
+extern unsigned char SDSPI_WaitDataBusy(SdSpi *pSdSpi);
+
+#endif
+
personal git repositories of Harald Welte. Your mileage may vary