Jack Berkhout / SDBlockDevice

Dependents:   20180621_FT813 IOT_Lec7_SD_with_Acclerometer_empty GPS-Tracking-Velo IOT_Lec9_SD

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers SDBlockDevice.cpp Source File

SDBlockDevice.cpp

00001 /* mbed Microcontroller Library
00002  * Copyright (c) 2006-2013 ARM Limited
00003  *
00004  * Licensed under the Apache License, Version 2.0 (the "License");
00005  * you may not use this file except in compliance with the License.
00006  * You may obtain a copy of the License at
00007  *
00008  *     http://www.apache.org/licenses/LICENSE-2.0
00009  *
00010  * Unless required by applicable law or agreed to in writing, software
00011  * distributed under the License is distributed on an "AS IS" BASIS,
00012  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00013  * See the License for the specific language governing permissions and
00014  * limitations under the License.
00015  */
00016 
00017 /* Introduction
00018  * ------------
00019  * SD and MMC cards support a number of interfaces, but common to them all
00020  * is one based on SPI. Since we already have the mbed SPI Interface, it will
00021  * be used for SD cards.
00022  *
00023  * The main reference I'm using is Chapter 7, "SPI Mode" of:
00024  *  http://www.sdcard.org/developers/tech/sdcard/pls/Simplified_Physical_Layer_Spec.pdf
00025  *
00026  * SPI Startup
00027  * -----------
00028  * The SD card powers up in SD mode. The start-up procedure is complicated
00029  * by the requirement to support older SDCards in a backwards compatible
00030  * way with the new higher capacity variants SDHC and SDHC.
00031  *
00032  * The following figures from the specification with associated text describe
00033  * the SPI mode initialisation process:
00034  *  - Figure 7-1: SD Memory Card State Diagram (SPI mode)
00035  *  - Figure 7-2: SPI Mode Initialization Flow
00036  *
00037  * Firstly, a low initial clock should be selected (in the range of 100-
00038  * 400kHZ). After initialisation has been completed, the switch to a
00039  * higher clock speed can be made (e.g. 1MHz). Newer cards will support
00040  * higher speeds than the default _transfer_sck defined here.
00041  *
00042  * Next, note the following from the SDCard specification (note to
00043  * Figure 7-1):
00044  *
00045  *  In any of the cases CMD1 is not recommended because it may be difficult for the host
00046  *  to distinguish between MultiMediaCard and SD Memory Card
00047  *
00048  * Hence CMD1 is not used for the initialisation sequence.
00049  *
00050  * The SPI interface mode is selected by asserting CS low and sending the
00051  * reset command (CMD0). The card will respond with a (R1) response.
00052  * In practice many cards initially respond with 0xff or invalid data
00053  * which is ignored. Data is read until a valid response is received
00054  * or the number of re-reads has exceeded a maximim count. If a valid
00055  * response is not received then the CMD0 can be retried. This
00056  * has been found to successfully initialise cards where the SPI master
00057  * (on MCU) has been reset but the SDCard has not, so the first
00058  * CMD0 may be lost.
00059  *
00060  * CMD8 is optionally sent to determine the voltage range supported, and
00061  * indirectly determine whether it is a version 1.x SD/non-SD card or
00062  * version 2.x. I'll just ignore this for now.
00063  *
00064  * ACMD41 is repeatedly issued to initialise the card, until "in idle"
00065  * (bit 0) of the R1 response goes to '0', indicating it is initialised.
00066  *
00067  * You should also indicate whether the host supports High Capicity cards,
00068  * and check whether the card is high capacity - i'll also ignore this
00069  *
00070  * SPI Protocol
00071  * ------------
00072  * The SD SPI protocol is based on transactions made up of 8-bit words, with
00073  * the host starting every bus transaction by asserting the CS signal low. The
00074  * card always responds to commands, data blocks and errors.
00075  *
00076  * The protocol supports a CRC, but by default it is off (except for the
00077  * first reset CMD0, where the CRC can just be pre-calculated, and CMD8)
00078  * I'll leave the CRC off I think!
00079  *
00080  * Standard capacity cards have variable data block sizes, whereas High
00081  * Capacity cards fix the size of data block to 512 bytes. I'll therefore
00082  * just always use the Standard Capacity cards with a block size of 512 bytes.
00083  * This is set with CMD16.
00084  *
00085  * You can read and write single blocks (CMD17, CMD25) or multiple blocks
00086  * (CMD18, CMD25). For simplicity, I'll just use single block accesses. When
00087  * the card gets a read command, it responds with a response token, and then
00088  * a data token or an error.
00089  *
00090  * SPI Command Format
00091  * ------------------
00092  * Commands are 6-bytes long, containing the command, 32-bit argument, and CRC.
00093  *
00094  * +---------------+------------+------------+-----------+----------+--------------+
00095  * | 01 | cmd[5:0] | arg[31:24] | arg[23:16] | arg[15:8] | arg[7:0] | crc[6:0] | 1 |
00096  * +---------------+------------+------------+-----------+----------+--------------+
00097  *
00098  * As I'm not using CRC, I can fix that byte to what is needed for CMD0 (0x95)
00099  *
00100  * All Application Specific commands shall be preceded with APP_CMD (CMD55).
00101  *
00102  * SPI Response Format
00103  * -------------------
00104  * The main response format (R1) is a status byte (normally zero). Key flags:
00105  *  idle - 1 if the card is in an idle state/initialising
00106  *  cmd  - 1 if an illegal command code was detected
00107  *
00108  *    +-------------------------------------------------+
00109  * R1 | 0 | arg | addr | seq | crc | cmd | erase | idle |
00110  *    +-------------------------------------------------+
00111  *
00112  * R1b is the same, except it is followed by a busy signal (zeros) until
00113  * the first non-zero byte when it is ready again.
00114  *
00115  * Data Response Token
00116  * -------------------
00117  * Every data block written to the card is acknowledged by a byte
00118  * response token
00119  *
00120  * +----------------------+
00121  * | xxx | 0 | status | 1 |
00122  * +----------------------+
00123  *              010 - OK!
00124  *              101 - CRC Error
00125  *              110 - Write Error
00126  *
00127  * Single Block Read and Write
00128  * ---------------------------
00129  *
00130  * Block transfers have a byte header, followed by the data, followed
00131  * by a 16-bit CRC. In our case, the data will always be 512 bytes.
00132  *
00133  * +------+---------+---------+- -  - -+---------+-----------+----------+
00134  * | 0xFE | data[0] | data[1] |        | data[n] | crc[15:8] | crc[7:0] |
00135  * +------+---------+---------+- -  - -+---------+-----------+----------+
00136  */
00137 
00138 /* If the target has no SPI support then SDCard is not supported */
00139 #ifdef DEVICE_SPI
00140 
00141 #include "SDBlockDevice.h"
00142 #include "mbed_debug.h"
00143 #include <errno.h>
00144 
00145 /* Required version: 5.8.0 and above */
00146 #if defined(    MBED_MAJOR_VERSION) && MBED_MAJOR_VERSION >= 5
00147 #if (MBED_VERSION < MBED_ENCODE_VERSION(5,8,0))
00148 #error "Incompatible mbed-os version detected! Required 5.8.0 and above"
00149 #endif
00150 #else
00151 #warning "mbed-os version 5.8.0 or above required"
00152 #endif
00153 
00154 #ifndef MBED_CONF_SD_CMD_TIMEOUT
00155 #define MBED_CONF_SD_CMD_TIMEOUT                 5000   /*!< Timeout in ms for response */
00156 #endif
00157 
00158 #ifndef MBED_CONF_SD_CMD0_IDLE_STATE_RETRIES
00159 #define MBED_CONF_SD_CMD0_IDLE_STATE_RETRIES     5      /*!< Number of retries for sending CMDO */
00160 #endif
00161 
00162 #ifndef MBED_CONF_SD_INIT_FREQUENCY
00163 #define MBED_CONF_SD_INIT_FREQUENCY              27000000 /*!< Initialization frequency Range (100KHz-400KHz) */
00164 #endif
00165 
00166 
00167 #define SD_COMMAND_TIMEOUT                       MBED_CONF_SD_CMD_TIMEOUT
00168 #define SD_CMD0_GO_IDLE_STATE_RETRIES            MBED_CONF_SD_CMD0_IDLE_STATE_RETRIES
00169 #define SD_DBG                                   0      /*!< 1 - Enable debugging */
00170 #define SD_CMD_TRACE                             0      /*!< 1 - Enable SD command tracing */
00171 
00172 #define SD_BLOCK_DEVICE_ERROR_WOULD_BLOCK        -5001  /*!< operation would block */
00173 #define SD_BLOCK_DEVICE_ERROR_UNSUPPORTED        -5002  /*!< unsupported operation */
00174 #define SD_BLOCK_DEVICE_ERROR_PARAMETER          -5003  /*!< invalid parameter */
00175 #define SD_BLOCK_DEVICE_ERROR_NO_INIT            -5004  /*!< uninitialized */
00176 #define SD_BLOCK_DEVICE_ERROR_NO_DEVICE          -5005  /*!< device is missing or not connected */
00177 #define SD_BLOCK_DEVICE_ERROR_WRITE_PROTECTED    -5006  /*!< write protected */
00178 #define SD_BLOCK_DEVICE_ERROR_UNUSABLE           -5007  /*!< unusable card */
00179 #define SD_BLOCK_DEVICE_ERROR_NO_RESPONSE        -5008  /*!< No response from device */
00180 #define SD_BLOCK_DEVICE_ERROR_CRC                -5009  /*!< CRC error */
00181 #define SD_BLOCK_DEVICE_ERROR_ERASE              -5010  /*!< Erase error: reset/sequence */
00182 #define SD_BLOCK_DEVICE_ERROR_WRITE              -5011  /*!< SPI Write error: !SPI_DATA_ACCEPTED */
00183 
00184 #define BLOCK_SIZE_HC                            512    /*!< Block size supported for SD card is 512 bytes  */
00185 #define WRITE_BL_PARTIAL                         0      /*!< Partial block write - Not supported */
00186 #define SPI_CMD(x) (0x40 | (x & 0x3f))
00187 
00188 /* R1 Response Format */
00189 #define R1_NO_RESPONSE          (0xFF)
00190 #define R1_RESPONSE_RECV        (0x80)
00191 #define R1_IDLE_STATE           (1 << 0)
00192 #define R1_ERASE_RESET          (1 << 1)
00193 #define R1_ILLEGAL_COMMAND      (1 << 2)
00194 #define R1_COM_CRC_ERROR        (1 << 3)
00195 #define R1_ERASE_SEQUENCE_ERROR (1 << 4)
00196 #define R1_ADDRESS_ERROR        (1 << 5)
00197 #define R1_PARAMETER_ERROR      (1 << 6)
00198 
00199 // Types
00200 #define SDCARD_NONE              0           /**< No card is present */
00201 #define SDCARD_V1                1           /**< v1.x Standard Capacity */
00202 #define SDCARD_V2                2           /**< v2.x Standard capacity SD card */
00203 #define SDCARD_V2HC              3           /**< v2.x High capacity SD card */
00204 #define CARD_UNKNOWN             4           /**< Unknown or unsupported card */
00205 
00206 /* SIZE in Bytes */
00207 #define PACKET_SIZE              6           /*!< SD Packet size CMD+ARG+CRC */
00208 #define R1_RESPONSE_SIZE         1           /*!< Size of R1 response */
00209 #define R2_RESPONSE_SIZE         2           /*!< Size of R2 response */
00210 #define R3_R7_RESPONSE_SIZE      5           /*!< Size of R3/R7 response */
00211 
00212 /* R1b Response */
00213 #define DEVICE_BUSY             (0x00)
00214 
00215 /* R2 Response Format */
00216 #define R2_CARD_LOCKED          (1 << 0)
00217 #define R2_CMD_FAILED           (1 << 1)
00218 #define R2_ERROR                (1 << 2)
00219 #define R2_CC_ERROR             (1 << 3)
00220 #define R2_CC_FAILED            (1 << 4)
00221 #define R2_WP_VIOLATION         (1 << 5)
00222 #define R2_ERASE_PARAM          (1 << 6)
00223 #define R2_OUT_OF_RANGE         (1 << 7)
00224 
00225 /* R3 Response : OCR Register */
00226 #define OCR_HCS_CCS             (0x1 << 30)
00227 #define OCR_LOW_VOLTAGE         (0x01 << 24)
00228 #define OCR_3_3V                (0x1 << 20)
00229 
00230 /* R7 response pattern for CMD8 */
00231 #define CMD8_PATTERN             (0xAA)
00232 
00233 /*  CRC Enable  */
00234 #define CRC_ENABLE               (0)         /*!< CRC 1 - Enable 0 - Disable */
00235 
00236 /* Control Tokens   */
00237 #define SPI_DATA_RESPONSE_MASK   (0x1F)
00238 #define SPI_DATA_ACCEPTED        (0x05)
00239 #define SPI_DATA_CRC_ERROR       (0x0B)
00240 #define SPI_DATA_WRITE_ERROR     (0x0D)
00241 #define SPI_START_BLOCK          (0xFE)      /*!< For Single Block Read/Write and Multiple Block Read */
00242 #define SPI_START_BLK_MUL_WRITE  (0xFC)      /*!< Start Multi-block write */
00243 #define SPI_STOP_TRAN            (0xFD)      /*!< Stop Multi-block write */
00244 
00245 #define SPI_DATA_READ_ERROR_MASK (0xF)       /*!< Data Error Token: 4 LSB bits */
00246 #define SPI_READ_ERROR           (0x1 << 0)  /*!< Error */
00247 #define SPI_READ_ERROR_CC        (0x1 << 1)  /*!< CC Error*/
00248 #define SPI_READ_ERROR_ECC_C     (0x1 << 2)  /*!< Card ECC failed */
00249 #define SPI_READ_ERROR_OFR       (0x1 << 3)  /*!< Out of Range */
00250 
00251 SDBlockDevice::SDBlockDevice(PinName mosi, PinName miso, PinName sclk, PinName cs, uint64_t hz, bool crc_on)
00252     : _sectors(0), _spi(mosi, miso, sclk), _cs(cs), _is_initialized(0), 
00253       _crc_on(crc_on), _crc16(0, 0, false, false)
00254 {
00255     _cs = 1;
00256     _card_type = SDCARD_NONE;
00257 
00258     // Set default to 100kHz for initialisation and 1MHz for data transfer
00259     MBED_STATIC_ASSERT(((MBED_CONF_SD_INIT_FREQUENCY >= 100000) && (MBED_CONF_SD_INIT_FREQUENCY <= 60000000)),
00260                        "Initialization frequency should be between 100KHz to 400KHz");
00261     _init_sck = MBED_CONF_SD_INIT_FREQUENCY;
00262     _transfer_sck = hz;
00263 
00264     // Only HC block size is supported.
00265     _block_size = BLOCK_SIZE_HC;
00266     _erase_size = BLOCK_SIZE_HC;
00267 }
00268 
00269 SDBlockDevice::~SDBlockDevice()
00270 {
00271     if (_is_initialized) {
00272         deinit();
00273     }
00274 }
00275 
00276 int SDBlockDevice::_initialise_card()
00277 {
00278     // Detail debugging is for commands
00279     _dbg = SD_DBG ? SD_CMD_TRACE : 0;
00280     int32_t status = BD_ERROR_OK;
00281     uint32_t response, arg;
00282 
00283     // Initialize the SPI interface: Card by default is in SD mode
00284     _spi_init();
00285 
00286     // The card is transitioned from SDCard mode to SPI mode by sending the CMD0 + CS Asserted("0")
00287     if (_go_idle_state() != R1_IDLE_STATE) {
00288         debug_if(SD_DBG, "No disk, or could not put SD card in to SPI idle state\n");
00289         return SD_BLOCK_DEVICE_ERROR_NO_DEVICE;
00290     }
00291 
00292     // Send CMD8, if the card rejects the command then it's probably using the
00293     // legacy protocol, or is a MMC, or just flat-out broken
00294     status = _cmd8();
00295     if (BD_ERROR_OK != status && SD_BLOCK_DEVICE_ERROR_UNSUPPORTED != status) {
00296         return status;
00297     }
00298 
00299     if (_crc_on) {
00300         // Enable CRC
00301         status = _cmd(CMD59_CRC_ON_OFF, _crc_on);
00302     }
00303 
00304     // Read OCR - CMD58 Response contains OCR register
00305     if (BD_ERROR_OK != (status = _cmd(CMD58_READ_OCR, 0x0, 0x0, &response))) {
00306         return status;
00307     }
00308 
00309     // Check if card supports voltage range: 3.3V
00310     if (!(response & OCR_3_3V)) {
00311         _card_type = CARD_UNKNOWN;
00312         status = SD_BLOCK_DEVICE_ERROR_UNUSABLE;
00313         return status;
00314     }
00315 
00316     // HCS is set 1 for HC/XC capacity cards for ACMD41, if supported
00317     arg = 0x0;
00318     if (SDCARD_V2 == _card_type) {
00319         arg |= OCR_HCS_CCS;
00320     }
00321 
00322     /* Idle state bit in the R1 response of ACMD41 is used by the card to inform the host
00323      * if initialization of ACMD41 is completed. "1" indicates that the card is still initializing.
00324      * "0" indicates completion of initialization. The host repeatedly issues ACMD41 until
00325      * this bit is set to "0".
00326      */
00327     _spi_timer.start();
00328     do {
00329         status = _cmd(ACMD41_SD_SEND_OP_COND, arg, 1, &response);
00330     } while ((response & R1_IDLE_STATE) && (_spi_timer.read_ms() < SD_COMMAND_TIMEOUT));
00331     _spi_timer.stop();
00332 
00333     // Initialization complete: ACMD41 successful
00334     if ((BD_ERROR_OK != status) || (0x00 != response)) {
00335         _card_type = CARD_UNKNOWN;
00336         debug_if(SD_DBG, "Timeout waiting for card\n");
00337         return status;
00338     }
00339 
00340     if (SDCARD_V2 == _card_type) {
00341         // Get the card capacity CCS: CMD58
00342         if (BD_ERROR_OK == (status = _cmd(CMD58_READ_OCR, 0x0, 0x0, &response))) {
00343             // High Capacity card
00344             if (response & OCR_HCS_CCS) {
00345                 _card_type = SDCARD_V2HC;
00346                 debug_if(SD_DBG, "Card Initialized: High Capacity Card \n");
00347             } else {
00348                 debug_if(SD_DBG, "Card Initialized: Standard Capacity Card: Version 2.x \n");
00349             }
00350         }
00351     } else {
00352         _card_type = SDCARD_V1;
00353         debug_if(SD_DBG, "Card Initialized: Version 1.x Card\n");
00354     }
00355 
00356     if (!_crc_on) {
00357         // Disable CRC
00358         status = _cmd(CMD59_CRC_ON_OFF, _crc_on);
00359     }
00360     return status;
00361 }
00362 
00363 
00364 int SDBlockDevice::init()
00365 {
00366     lock();
00367 
00368     int err = _initialise_card();
00369     _is_initialized = (err == BD_ERROR_OK);
00370     if (!_is_initialized) {
00371         debug_if(SD_DBG, "Fail to initialize card\n");
00372         unlock();
00373         return err;
00374     }
00375     debug_if(SD_DBG, "init card = %d\n", _is_initialized);
00376     _sectors = _sd_sectors();
00377     // CMD9 failed
00378     if (0 == _sectors) {
00379         unlock();
00380         return BD_ERROR_DEVICE_ERROR;
00381     }
00382 
00383     // Set block length to 512 (CMD16)
00384     if (_cmd(CMD16_SET_BLOCKLEN, _block_size) != 0) {
00385         debug_if(SD_DBG, "Set %d-byte block timed out\n", _block_size);
00386         unlock();
00387         return BD_ERROR_DEVICE_ERROR;
00388     }
00389 
00390     // Set SCK for data transfer
00391     err = _freq();
00392     if (err) {
00393         unlock();
00394         return err;
00395     }
00396     unlock();
00397     return BD_ERROR_OK;
00398 }
00399 
00400 int SDBlockDevice::deinit()
00401 {
00402     lock();
00403     _is_initialized = false;
00404     _sectors = 0;
00405     unlock();
00406     return 0;
00407 }
00408 
00409 
00410 int SDBlockDevice::program(const void *b, bd_addr_t addr, bd_size_t size)
00411 {
00412     if (!is_valid_program(addr, size)) {
00413         return SD_BLOCK_DEVICE_ERROR_PARAMETER;
00414     }
00415 
00416     lock();
00417     if (!_is_initialized) {
00418         unlock();
00419         return SD_BLOCK_DEVICE_ERROR_NO_INIT;
00420     }
00421 
00422     const uint8_t *buffer = static_cast<const uint8_t*>(b);
00423     int status = BD_ERROR_OK;
00424     uint8_t response;
00425 
00426     // Get block count
00427     bd_addr_t blockCnt = size / _block_size;
00428 
00429     // SDSC Card (CCS=0) uses byte unit address
00430     // SDHC and SDXC Cards (CCS=1) use block unit address (512 Bytes unit)
00431     if(SDCARD_V2HC == _card_type) {
00432         addr = addr / _block_size;
00433     }
00434 
00435     // Send command to perform write operation
00436     if (blockCnt == 1) {
00437         // Single block write command
00438         if (BD_ERROR_OK != (status = _cmd(CMD24_WRITE_BLOCK, addr))) {
00439             unlock();
00440             return status;
00441         }
00442 
00443         // Write data
00444         response = _write(buffer, SPI_START_BLOCK, _block_size);
00445 
00446         // Only CRC and general write error are communicated via response token
00447         if (response != SPI_DATA_ACCEPTED) {
00448             debug_if(SD_DBG, "Single Block Write failed: 0x%x \n", response);
00449             status = SD_BLOCK_DEVICE_ERROR_WRITE;
00450         }
00451     } else {
00452         // Pre-erase setting prior to multiple block write operation
00453         _cmd(ACMD23_SET_WR_BLK_ERASE_COUNT, blockCnt, 1);
00454 
00455         // Multiple block write command
00456         if (BD_ERROR_OK != (status = _cmd(CMD25_WRITE_MULTIPLE_BLOCK, addr))) {
00457             unlock();
00458             return status;
00459         }
00460 
00461         // Write the data: one block at a time
00462         do {
00463             response = _write(buffer, SPI_START_BLK_MUL_WRITE, _block_size);
00464             if (response != SPI_DATA_ACCEPTED) {
00465                 debug_if(SD_DBG, "Multiple Block Write failed: 0x%x \n", response);
00466                 break;
00467             }
00468             buffer += _block_size;
00469         }while (--blockCnt);     // Receive all blocks of data
00470 
00471         /* In a Multiple Block write operation, the stop transmission will be done by
00472          * sending 'Stop Tran' token instead of 'Start Block' token at the beginning
00473          * of the next block
00474          */
00475         _spi.write(SPI_STOP_TRAN);
00476     }
00477 
00478     _deselect();
00479     unlock();
00480     return status;
00481 }
00482 
00483 int SDBlockDevice::read(void *b, bd_addr_t addr, bd_size_t size)
00484 {
00485     if (!is_valid_read(addr, size)) {
00486         return SD_BLOCK_DEVICE_ERROR_PARAMETER;
00487     }
00488 
00489     lock();
00490     if (!_is_initialized) {
00491         unlock();
00492         return SD_BLOCK_DEVICE_ERROR_PARAMETER;
00493     }
00494 
00495     uint8_t *buffer = static_cast<uint8_t *>(b);
00496     int status = BD_ERROR_OK;
00497     bd_addr_t blockCnt =  size / _block_size;
00498 
00499     // SDSC Card (CCS=0) uses byte unit address
00500     // SDHC and SDXC Cards (CCS=1) use block unit address (512 Bytes unit)
00501     if (SDCARD_V2HC == _card_type) {
00502         addr = addr / _block_size;
00503     }
00504 
00505     // Write command ro receive data
00506     if (blockCnt > 1) {
00507         status = _cmd(CMD18_READ_MULTIPLE_BLOCK, addr);
00508     } else {
00509         status = _cmd(CMD17_READ_SINGLE_BLOCK, addr);
00510     }
00511     if (BD_ERROR_OK != status) {
00512         unlock();
00513         return status;
00514     }
00515 
00516     // receive the data : one block at a time
00517     while (blockCnt) {
00518         if (0 != _read(buffer, _block_size)) {
00519             status = SD_BLOCK_DEVICE_ERROR_NO_RESPONSE;
00520             break;
00521         }
00522         buffer += _block_size;
00523         --blockCnt;
00524     }
00525     _deselect();
00526 
00527     // Send CMD12(0x00000000) to stop the transmission for multi-block transfer
00528     if (size > _block_size) {
00529         status = _cmd(CMD12_STOP_TRANSMISSION, 0x0);
00530     }
00531     unlock();
00532     return status;
00533 }
00534 
00535 bool SDBlockDevice::_is_valid_trim(bd_addr_t addr, bd_size_t size)
00536 {
00537     return (
00538         addr % _erase_size == 0 &&
00539         size % _erase_size == 0 &&
00540         addr + size <= this->size());
00541 }
00542 
00543 int SDBlockDevice::trim(bd_addr_t addr, bd_size_t size)
00544 {
00545     if (!_is_valid_trim(addr, size)) {
00546         return SD_BLOCK_DEVICE_ERROR_PARAMETER;
00547     }
00548 
00549     lock();
00550     if (!_is_initialized) {
00551         unlock();
00552         return SD_BLOCK_DEVICE_ERROR_NO_INIT;
00553     }
00554     int status = BD_ERROR_OK;
00555 
00556     size -= _block_size;
00557     // SDSC Card (CCS=0) uses byte unit address
00558     // SDHC and SDXC Cards (CCS=1) use block unit address (512 Bytes unit)
00559     if (SDCARD_V2HC == _card_type) {
00560         size = size / _block_size;
00561         addr = addr / _block_size;
00562     }
00563 
00564     // Start lba sent in start command
00565     if (BD_ERROR_OK != (status = _cmd(CMD32_ERASE_WR_BLK_START_ADDR, addr))) {
00566         unlock();
00567         return status;
00568     }
00569 
00570     // End lba = addr+size sent in end addr command
00571     if (BD_ERROR_OK != (status = _cmd(CMD33_ERASE_WR_BLK_END_ADDR, addr+size))) {
00572         unlock();
00573         return status;
00574     }
00575     status = _cmd(CMD38_ERASE, 0x0);
00576     unlock();
00577     return status;
00578 }
00579 
00580 bd_size_t SDBlockDevice::get_read_size() const
00581 {
00582     return _block_size;
00583 }
00584 
00585 bd_size_t SDBlockDevice::get_program_size() const
00586 {
00587     return _block_size;
00588 }
00589 
00590 bd_size_t SDBlockDevice::size() const
00591 {
00592     return _block_size*_sectors;
00593 }
00594 
00595 void SDBlockDevice::debug(bool dbg)
00596 {
00597     _dbg = dbg;
00598 }
00599 
00600 int SDBlockDevice::frequency(uint64_t freq)
00601 {
00602     lock();
00603     _transfer_sck = freq;
00604     int err = _freq();
00605     unlock();
00606     return err;
00607 }
00608 
00609 // PRIVATE FUNCTIONS
00610 int SDBlockDevice::_freq(void)
00611 {
00612     // Max frequency supported is 25MHZ
00613     if (_transfer_sck <= 25000000) {
00614         _spi.frequency(_transfer_sck);
00615         return 0;
00616     } else {  // TODO: Switch function to be implemented for higher frequency
00617         _transfer_sck = 25000000;
00618         _spi.frequency(_transfer_sck);
00619         return -EINVAL;
00620     }
00621 }
00622 
00623 uint8_t SDBlockDevice::_cmd_spi(SDBlockDevice::cmdSupported cmd, uint32_t arg) {
00624     uint8_t response;
00625     char cmdPacket[PACKET_SIZE];
00626     uint32_t crc;
00627 
00628     // Prepare the command packet
00629     cmdPacket[0] = SPI_CMD(cmd);
00630     cmdPacket[1] = (arg >> 24);
00631     cmdPacket[2] = (arg >> 16);
00632     cmdPacket[3] = (arg >> 8);
00633     cmdPacket[4] = (arg >> 0);
00634 
00635     if (_crc_on) {
00636         _crc7.compute((void *)cmdPacket, 5, &crc);
00637         cmdPacket[5] = (char)(crc | 0x01);
00638     } else {
00639         // CMD0 is executed in SD mode, hence should have correct CRC
00640         // CMD8 CRC verification is always enabled
00641         switch(cmd) {
00642             case CMD0_GO_IDLE_STATE:
00643                 cmdPacket[5] = 0x95;
00644                 break;
00645             case CMD8_SEND_IF_COND:
00646                 cmdPacket[5] = 0x87;
00647                 break;
00648             default:
00649                 cmdPacket[5] = 0xFF;    // Make sure bit 0-End bit is high
00650                 break;
00651         }
00652     }
00653 
00654     // send a command
00655     for (int i = 0; i < PACKET_SIZE; i++) {
00656         _spi.write(cmdPacket[i]);
00657     }
00658 
00659     // The received byte immediataly following CMD12 is a stuff byte,
00660     // it should be discarded before receive the response of the CMD12.
00661     if (CMD12_STOP_TRANSMISSION == cmd) {
00662         _spi.write(SPI_FILL_CHAR);
00663     }
00664 
00665     // Loop for response: Response is sent back within command response time (NCR), 0 to 8 bytes for SDC
00666     for (int i = 0; i < 0x10; i++) {
00667         response = _spi.write(SPI_FILL_CHAR);
00668         // Got the response
00669         if (!(response & R1_RESPONSE_RECV)) {
00670             break;
00671         }
00672     }
00673     return response;
00674 }
00675 
00676 int SDBlockDevice::_cmd(SDBlockDevice::cmdSupported cmd, uint32_t arg, bool isAcmd, uint32_t *resp) {
00677     int32_t status = BD_ERROR_OK;
00678     uint32_t response;
00679 
00680     // Select card and wait for card to be ready before sending next command
00681     // Note: next command will fail if card is not ready
00682     _select();
00683 
00684     // No need to wait for card to be ready when sending the stop command
00685     if (CMD12_STOP_TRANSMISSION != cmd) {
00686         if (false == _wait_ready(SD_COMMAND_TIMEOUT)) {
00687             debug_if(SD_DBG, "Card not ready yet \n");
00688         }
00689     }
00690 
00691     // Re-try command
00692     for(int i = 0; i < 3; i++) {
00693         // Send CMD55 for APP command first
00694         if (isAcmd) {
00695             response = _cmd_spi(CMD55_APP_CMD, 0x0);
00696             // Wait for card to be ready after CMD55
00697             if (false == _wait_ready(SD_COMMAND_TIMEOUT)) {
00698                 debug_if(SD_DBG, "Card not ready yet \n");
00699             }
00700         }
00701 
00702         // Send command over SPI interface
00703         response = _cmd_spi(cmd, arg);
00704         if (R1_NO_RESPONSE == response) {
00705             debug_if(SD_DBG, "No response CMD:%d \n", cmd);
00706             continue;
00707         }
00708         break;
00709     }
00710 
00711     // Pass the response to the command call if required
00712     if (NULL != resp) {
00713         *resp = response;
00714     }
00715 
00716     // Process the response R1  : Exit on CRC/Illegal command error/No response
00717     if (R1_NO_RESPONSE == response) {
00718         _deselect();
00719         debug_if(SD_DBG, "No response CMD:%d response: 0x%x\n",cmd, response);
00720         return SD_BLOCK_DEVICE_ERROR_NO_DEVICE;         // No device
00721     }
00722     if (response & R1_COM_CRC_ERROR) {
00723         _deselect();
00724         debug_if(SD_DBG, "CRC error CMD:%d response 0x%x \n",cmd, response);
00725         return SD_BLOCK_DEVICE_ERROR_CRC;                // CRC error
00726     }
00727     if (response & R1_ILLEGAL_COMMAND) {
00728         _deselect();
00729         debug_if(SD_DBG, "Illegal command CMD:%d response 0x%x\n",cmd, response);
00730         if (CMD8_SEND_IF_COND == cmd) {                  // Illegal command is for Ver1 or not SD Card
00731             _card_type = CARD_UNKNOWN;
00732         }
00733         return SD_BLOCK_DEVICE_ERROR_UNSUPPORTED;      // Command not supported
00734     }
00735 
00736     debug_if(_dbg, "CMD:%d \t arg:0x%x \t Response:0x%x \n", cmd, arg, response);
00737     // Set status for other errors
00738     if ((response & R1_ERASE_RESET) || (response & R1_ERASE_SEQUENCE_ERROR)) {
00739         status = SD_BLOCK_DEVICE_ERROR_ERASE;            // Erase error
00740     }else if ((response & R1_ADDRESS_ERROR) || (response & R1_PARAMETER_ERROR)) {
00741         // Misaligned address / invalid address block length
00742         status = SD_BLOCK_DEVICE_ERROR_PARAMETER;
00743     }
00744 
00745     // Get rest of the response part for other commands
00746     switch(cmd) {
00747         case CMD8_SEND_IF_COND:             // Response R7
00748             debug_if(_dbg, "V2-Version Card\n");
00749             _card_type = SDCARD_V2;
00750             // Note: No break here, need to read rest of the response
00751         case CMD58_READ_OCR:                // Response R3
00752             response  = (_spi.write(SPI_FILL_CHAR) << 24);
00753             response |= (_spi.write(SPI_FILL_CHAR) << 16);
00754             response |= (_spi.write(SPI_FILL_CHAR) << 8);
00755             response |= _spi.write(SPI_FILL_CHAR);
00756             debug_if(_dbg, "R3/R7: 0x%x \n", response);
00757             break;
00758 
00759         case CMD12_STOP_TRANSMISSION:       // Response R1b
00760         case CMD38_ERASE:
00761             _wait_ready(SD_COMMAND_TIMEOUT);
00762             break;
00763 
00764         case ACMD13_SD_STATUS:             // Response R2
00765             response = _spi.write(SPI_FILL_CHAR);
00766             debug_if(_dbg, "R2: 0x%x \n", response);
00767             break;
00768 
00769         default:                            // Response R1
00770             break;
00771     }
00772 
00773     // Pass the updated response to the command
00774     if (NULL != resp) {
00775         *resp = response;
00776     }
00777 
00778     // Do not deselect card if read is in progress.
00779     if (((CMD9_SEND_CSD == cmd) || (ACMD22_SEND_NUM_WR_BLOCKS == cmd) ||
00780         (CMD24_WRITE_BLOCK == cmd) || (CMD25_WRITE_MULTIPLE_BLOCK == cmd) ||
00781         (CMD17_READ_SINGLE_BLOCK == cmd) || (CMD18_READ_MULTIPLE_BLOCK == cmd))
00782         && (BD_ERROR_OK == status)) {
00783         return BD_ERROR_OK;
00784     }
00785     // Deselect card
00786     _deselect();
00787     return status;
00788 }
00789 
00790 int SDBlockDevice::_cmd8() {
00791     uint32_t arg = (CMD8_PATTERN << 0);         // [7:0]check pattern
00792     uint32_t response = 0;
00793     int32_t status = BD_ERROR_OK;
00794 
00795     arg |= (0x1 << 8);  // 2.7-3.6V             // [11:8]supply voltage(VHS)
00796 
00797     status = _cmd(CMD8_SEND_IF_COND, arg, 0x0, &response);
00798     // Verify voltage and pattern for V2 version of card
00799     if ((BD_ERROR_OK == status) && (SDCARD_V2 == _card_type)) {
00800         // If check pattern is not matched, CMD8 communication is not valid
00801         if((response & 0xFFF) != arg)
00802         {
00803             debug_if(SD_DBG, "CMD8 Pattern mismatch 0x%x : 0x%x\n", arg, response);
00804             _card_type = CARD_UNKNOWN;
00805             status = SD_BLOCK_DEVICE_ERROR_UNUSABLE;
00806         }
00807     }
00808     return status;
00809 }
00810 
00811 uint32_t SDBlockDevice::_go_idle_state() {
00812     uint32_t response;
00813 
00814     /* Reseting the MCU SPI master may not reset the on-board SDCard, in which
00815      * case when MCU power-on occurs the SDCard will resume operations as
00816      * though there was no reset. In this scenario the first CMD0 will
00817      * not be interpreted as a command and get lost. For some cards retrying
00818      * the command overcomes this situation. */
00819     for (int i = 0; i < SD_CMD0_GO_IDLE_STATE_RETRIES; i++) {
00820         _cmd(CMD0_GO_IDLE_STATE, 0x0, 0x0, &response);
00821         if (R1_IDLE_STATE == response)
00822             break;
00823         wait_ms(1);
00824     }
00825     return response;
00826 }
00827 
00828 int SDBlockDevice::_read_bytes(uint8_t *buffer, uint32_t length) {
00829     uint16_t crc;
00830 
00831     // read until start byte (0xFE)
00832     if (false == _wait_token(SPI_START_BLOCK)) {
00833         debug_if(SD_DBG, "Read timeout\n");
00834         _deselect();
00835         return SD_BLOCK_DEVICE_ERROR_NO_RESPONSE;
00836     }
00837 
00838     // read data
00839     for (uint32_t i = 0; i < length; i++) {
00840         buffer[i] = _spi.write(SPI_FILL_CHAR);
00841     }
00842 
00843     // Read the CRC16 checksum for the data block
00844     crc = (_spi.write(SPI_FILL_CHAR) << 8);
00845     crc |= _spi.write(SPI_FILL_CHAR);
00846 
00847     if (_crc_on) {
00848         uint32_t crc_result;
00849         // Compute and verify checksum
00850         _crc16.compute((void *)buffer, length, &crc_result);
00851         if ((uint16_t)crc_result != crc) {
00852             debug_if(SD_DBG, "_read_bytes: Invalid CRC received 0x%x result of computation 0x%x\n",
00853                         crc, crc_result);
00854             _deselect();
00855             return SD_BLOCK_DEVICE_ERROR_CRC;
00856         }
00857     }
00858 
00859     _deselect();
00860     return 0;
00861 }
00862 
00863 int SDBlockDevice::_read(uint8_t *buffer, uint32_t length) {
00864     uint16_t crc;
00865 
00866     // read until start byte (0xFE)
00867     if (false == _wait_token(SPI_START_BLOCK)) {
00868         debug_if(SD_DBG, "Read timeout\n");
00869         _deselect();
00870         return SD_BLOCK_DEVICE_ERROR_NO_RESPONSE;
00871     }
00872 
00873     // read data
00874     _spi.write(NULL, 0, (char*)buffer, length);
00875 
00876     // Read the CRC16 checksum for the data block
00877     crc = (_spi.write(SPI_FILL_CHAR) << 8);
00878     crc |= _spi.write(SPI_FILL_CHAR);
00879 
00880     if (_crc_on) {
00881         uint32_t crc_result;
00882         // Compute and verify checksum
00883         _crc16.compute((void *)buffer, length, &crc_result);
00884         if ((uint16_t)crc_result != crc) {
00885             debug_if(SD_DBG, "_read_bytes: Invalid CRC received 0x%x result of computation 0x%x\n",
00886                         crc, crc_result);
00887             return SD_BLOCK_DEVICE_ERROR_CRC;
00888         }
00889     }
00890 
00891     return 0;
00892 }
00893 
00894 uint8_t SDBlockDevice::_write(const uint8_t *buffer, uint8_t token, uint32_t length) {
00895     
00896     uint32_t crc = (~0);
00897     uint8_t response = 0xFF;
00898 
00899     // indicate start of block
00900     _spi.write(token);
00901 
00902     // write the data
00903     _spi.write((char*)buffer, length, NULL, 0);
00904 
00905     if (_crc_on) {
00906         // Compute CRC
00907         _crc16.compute((void *)buffer, length, &crc);
00908     }
00909 
00910     // write the checksum CRC16
00911     _spi.write(crc >> 8);
00912     _spi.write(crc);
00913 
00914 
00915     // check the response token
00916     response = _spi.write(SPI_FILL_CHAR);
00917 
00918     // Wait for last block to be written
00919     if (false == _wait_ready(SD_COMMAND_TIMEOUT)) {
00920         debug_if(SD_DBG, "Card not ready yet \n");
00921     }
00922 
00923     return (response & SPI_DATA_RESPONSE_MASK);
00924 }
00925 
00926 static uint32_t ext_bits(unsigned char *data, int msb, int lsb) {
00927     uint32_t bits = 0;
00928     uint32_t size = 1 + msb - lsb;
00929     for (uint32_t i = 0; i < size; i++) {
00930         uint32_t position = lsb + i;
00931         uint32_t byte = 15 - (position >> 3);
00932         uint32_t bit = position & 0x7;
00933         uint32_t value = (data[byte] >> bit) & 1;
00934         bits |= value << i;
00935     }
00936     return bits;
00937 }
00938 
00939 bd_size_t SDBlockDevice::_sd_sectors() {
00940     uint32_t c_size, c_size_mult, read_bl_len;
00941     uint32_t block_len, mult, blocknr;
00942     uint32_t hc_c_size;
00943     bd_size_t blocks = 0, capacity = 0;
00944 
00945     // CMD9, Response R2 (R1 byte + 16-byte block read)
00946     if (_cmd(CMD9_SEND_CSD, 0x0) != 0x0) {
00947         debug_if(SD_DBG, "Didn't get a response from the disk\n");
00948         return 0;
00949     }
00950     uint8_t csd[16];
00951     if (_read_bytes(csd, 16) != 0) {
00952         debug_if(SD_DBG, "Couldn't read csd response from disk\n");
00953         return 0;
00954     }
00955 
00956     // csd_structure : csd[127:126]
00957     int csd_structure = ext_bits(csd, 127, 126);
00958     switch (csd_structure) {
00959         case 0:
00960             c_size = ext_bits(csd, 73, 62);              // c_size        : csd[73:62]
00961             c_size_mult = ext_bits(csd, 49, 47);         // c_size_mult   : csd[49:47]
00962             read_bl_len = ext_bits(csd, 83, 80);         // read_bl_len   : csd[83:80] - the *maximum* read block length
00963             block_len = 1 << read_bl_len;                // BLOCK_LEN = 2^READ_BL_LEN
00964             mult = 1 << (c_size_mult + 2);               // MULT = 2^C_SIZE_MULT+2 (C_SIZE_MULT < 8)
00965             blocknr = (c_size + 1) * mult;               // BLOCKNR = (C_SIZE+1) * MULT
00966             capacity = blocknr * block_len;              // memory capacity = BLOCKNR * BLOCK_LEN
00967             blocks = capacity / _block_size;
00968             debug_if(SD_DBG, "Standard Capacity: c_size: %d \n", c_size);
00969             debug_if(SD_DBG, "Sectors: 0x%x : %llu\n", blocks, blocks);
00970             debug_if(SD_DBG, "Capacity: 0x%x : %llu MB\n", capacity, (capacity/(1024U*1024U)));
00971 
00972             // ERASE_BLK_EN = 1: Erase in multiple of 512 bytes supported
00973             if (ext_bits(csd, 46, 46)) {
00974                 _erase_size = BLOCK_SIZE_HC;
00975             } else {
00976                 // ERASE_BLK_EN = 1: Erase in multiple of SECTOR_SIZE supported
00977                 _erase_size = BLOCK_SIZE_HC * (ext_bits(csd, 45, 39) + 1);
00978             }
00979             break;
00980 
00981         case 1:
00982             hc_c_size = ext_bits(csd, 69, 48);            // device size : C_SIZE : [69:48]
00983             blocks = (hc_c_size+1) << 10;                 // block count = C_SIZE+1) * 1K byte (512B is block size)
00984             debug_if(SD_DBG, "SDHC/SDXC Card: hc_c_size: %d \n", hc_c_size);
00985             debug_if(SD_DBG, "Sectors: 0x%x : %llu\n", blocks, blocks);
00986             debug_if(SD_DBG, "Capacity: %llu MB\n", (blocks/(2048U)));
00987             // ERASE_BLK_EN is fixed to 1, which means host can erase one or multiple of 512 bytes.
00988             _erase_size = BLOCK_SIZE_HC;
00989             break;
00990 
00991         default:
00992             debug_if(SD_DBG, "CSD struct unsupported\r\n");
00993             return 0;
00994     };
00995     return blocks;
00996 }
00997 
00998 // SPI function to wait till chip is ready and sends start token
00999 bool SDBlockDevice::_wait_token(uint8_t token) {
01000     _spi_timer.reset();
01001     _spi_timer.start();
01002 
01003     do {
01004         if (token == _spi.write(SPI_FILL_CHAR)) {
01005             _spi_timer.stop();
01006             return true;
01007         }
01008     } while (_spi_timer.read_ms() < 300);       // Wait for 300 msec for start token
01009     _spi_timer.stop();
01010     debug_if(SD_DBG, "_wait_token: timeout\n");
01011     return false;
01012 }
01013 
01014 // SPI function to wait till chip is ready
01015 // The host controller should wait for end of the process until DO goes high (a 0xFF is received).
01016 bool SDBlockDevice::_wait_ready(uint16_t ms) {
01017     uint8_t response;
01018     _spi_timer.reset();
01019     _spi_timer.start();
01020     do {
01021         response = _spi.write(SPI_FILL_CHAR);
01022         if (response == 0xFF) {
01023             _spi_timer.stop();
01024             return true;
01025         }
01026     } while (_spi_timer.read_ms() < ms);
01027     _spi_timer.stop();
01028     return false;
01029 }
01030 
01031 // SPI function to wait for count
01032 void SDBlockDevice::_spi_wait(uint8_t count)
01033 {
01034     for (uint8_t i = 0; i < count; ++i) {
01035         _spi.write(SPI_FILL_CHAR);
01036     }
01037 }
01038 
01039 void SDBlockDevice::_spi_init() {
01040     _spi.lock();
01041     // Set to SCK for initialization, and clock card with cs = 1
01042     _spi.frequency(_init_sck);
01043     _spi.format(8, 0);
01044     _spi.set_default_write_value(SPI_FILL_CHAR);
01045     // Initial 74 cycles required for few cards, before selecting SPI mode
01046     _cs = 1;
01047     _spi_wait(10);
01048     _spi.unlock();
01049 }
01050 
01051 void SDBlockDevice::_select() {
01052     _spi.lock();
01053     _spi.write(SPI_FILL_CHAR);
01054     _cs = 0;
01055 }
01056 
01057 void SDBlockDevice::_deselect() {
01058     _cs = 1;
01059     _spi.write(SPI_FILL_CHAR);
01060     _spi.unlock();
01061 }
01062 
01063 #endif  /* DEVICE_SPI */