elec 350 courcework by oscar simons

Dependencies:   BMP280

Fork of Task617-mbedos by University of Plymouth - Stages 1, 2 and 3

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