Norimasa Okamoto / USBLocalFileSystem

Dependencies:   USBDevice

Dependents:   KL46Z-lpc81isp lpcterm2

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers SDStorage.cpp Source File

SDStorage.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. This is the one I'm implmenting because it means
00026  * it is much more portable even though not so performant, and we already
00027  * have the mbed SPI Interface!
00028  *
00029  * The main reference I'm using is Chapter 7, "SPI Mode" of:
00030  *  http://www.sdcard.org/developers/tech/sdcard/pls/Simplified_Physical_Layer_Spec.pdf
00031  *
00032  * SPI Startup
00033  * -----------
00034  * The SD card powers up in SD mode. The SPI interface mode is selected by
00035  * asserting CS low and sending the reset command (CMD0). The card will
00036  * respond with a (R1) response.
00037  *
00038  * CMD8 is optionally sent to determine the voltage range supported, and
00039  * indirectly determine whether it is a version 1.x SD/non-SD card or
00040  * version 2.x. I'll just ignore this for now.
00041  *
00042  * ACMD41 is repeatedly issued to initialise the card, until "in idle"
00043  * (bit 0) of the R1 response goes to '0', indicating it is initialised.
00044  *
00045  * You should also indicate whether the host supports High Capicity cards,
00046  * and check whether the card is high capacity - i'll also ignore this
00047  *
00048  * SPI Protocol
00049  * ------------
00050  * The SD SPI protocol is based on transactions made up of 8-bit words, with
00051  * the host starting every bus transaction by asserting the CS signal low. The
00052  * card always responds to commands, data blocks and errors.
00053  *
00054  * The protocol supports a CRC, but by default it is off (except for the
00055  * first reset CMD0, where the CRC can just be pre-calculated, and CMD8)
00056  * I'll leave the CRC off I think!
00057  *
00058  * Standard capacity cards have variable data block sizes, whereas High
00059  * Capacity cards fix the size of data block to 512 bytes. I'll therefore
00060  * just always use the Standard Capacity cards with a block size of 512 bytes.
00061  * This is set with CMD16.
00062  *
00063  * You can read and write single blocks (CMD17, CMD25) or multiple blocks
00064  * (CMD18, CMD25). For simplicity, I'll just use single block accesses. When
00065  * the card gets a read command, it responds with a response token, and then
00066  * a data token or an error.
00067  *
00068  * SPI Command Format
00069  * ------------------
00070  * Commands are 6-bytes long, containing the command, 32-bit argument, and CRC.
00071  *
00072  * +---------------+------------+------------+-----------+----------+--------------+
00073  * | 01 | cmd[5:0] | arg[31:24] | arg[23:16] | arg[15:8] | arg[7:0] | crc[6:0] | 1 |
00074  * +---------------+------------+------------+-----------+----------+--------------+
00075  *
00076  * As I'm not using CRC, I can fix that byte to what is needed for CMD0 (0x95)
00077  *
00078  * All Application Specific commands shall be preceded with APP_CMD (CMD55).
00079  *
00080  * SPI Response Format
00081  * -------------------
00082  * The main response format (R1) is a status byte (normally zero). Key flags:
00083  *  idle - 1 if the card is in an idle state/initialising
00084  *  cmd  - 1 if an illegal command code was detected
00085  *
00086  *    +-------------------------------------------------+
00087  * R1 | 0 | arg | addr | seq | crc | cmd | erase | idle |
00088  *    +-------------------------------------------------+
00089  *
00090  * R1b is the same, except it is followed by a busy signal (zeros) until
00091  * the first non-zero byte when it is ready again.
00092  *
00093  * Data Response Token
00094  * -------------------
00095  * Every data block written to the card is acknowledged by a byte
00096  * response token
00097  *
00098  * +----------------------+
00099  * | xxx | 0 | status | 1 |
00100  * +----------------------+
00101  *              010 - OK!
00102  *              101 - CRC Error
00103  *              110 - Write Error
00104  *
00105  * Single Block Read and Write
00106  * ---------------------------
00107  *
00108  * Block transfers have a byte header, followed by the data, followed
00109  * by a 16-bit CRC. In our case, the data will always be 512 bytes.
00110  *
00111  * +------+---------+---------+- -  - -+---------+-----------+----------+
00112  * | 0xFE | data[0] | data[1] |        | data[n] | crc[15:8] | crc[7:0] |
00113  * +------+---------+---------+- -  - -+---------+-----------+----------+
00114  */
00115 
00116 #include "SDStorage.h"
00117 #include "mbed_debug.h"
00118     
00119 #if 0 //#if (DEBUG2 > 3)
00120 #define SD_DBG2(...) do{fprintf(stderr,"[%s@%d] ",__PRETTY_FUNCTION__,__LINE__);fprintf(stderr,__VA_ARGS__);fprintf(stderr,"\r\n");} while(0);
00121 #else
00122 #define SD_DBG2(...) while(0)
00123 #endif
00124 
00125 #define SD_COMMAND_TIMEOUT 5000
00126  
00127 #define SD_DBG             1
00128  
00129 SDStorage::SDStorage(PinName mosi, PinName miso, PinName sclk, PinName cs) :
00130     _spi(mosi, miso, sclk), _cs(cs) {
00131     _cs = 1;
00132 
00133     //storage_initialize();
00134 }
00135  
00136 #define R1_IDLE_STATE           (1 << 0)
00137 #define R1_ERASE_RESET          (1 << 1)
00138 #define R1_ILLEGAL_COMMAND      (1 << 2)
00139 #define R1_COM_CRC_ERROR        (1 << 3)
00140 #define R1_ERASE_SEQUENCE_ERROR (1 << 4)
00141 #define R1_ADDRESS_ERROR        (1 << 5)
00142 #define R1_PARAMETER_ERROR      (1 << 6)
00143  
00144 // Types
00145 //  - v1.x Standard Capacity
00146 //  - v2.x Standard Capacity
00147 //  - v2.x High Capacity
00148 //  - Not recognised as an SD Card
00149 #define SDCARD_FAIL 0
00150 #define SDCARD_V1   1
00151 #define SDCARD_V2   2
00152 #define SDCARD_V2HC 3
00153  
00154 int SDStorage::initialise_card() {
00155     // Set to 100kHz for initialisation, and clock card with cs = 1
00156     _spi.frequency(100000);
00157     _cs = 1;
00158     for (int i = 0; i < 16; i++) {
00159         _spi.write(0xFF);
00160     }
00161     
00162     // send CMD0, should return with all zeros except IDLE STATE set (bit 0)
00163     if (_cmd(0, 0) != R1_IDLE_STATE) {
00164         debug("No disk, or could not put SD card in to SPI idle state\n");
00165         return SDCARD_FAIL;
00166     }
00167     
00168     // send CMD8 to determine whther it is ver 2.x
00169     int r = _cmd8();
00170     if (r == R1_IDLE_STATE) {
00171         return initialise_card_v2();
00172     } else if (r == (R1_IDLE_STATE | R1_ILLEGAL_COMMAND)) {
00173         return initialise_card_v1();
00174     } else {
00175         debug("Not in idle state after sending CMD8 (not an SD card?)\n");
00176         return SDCARD_FAIL;
00177     }
00178 }
00179  
00180 int SDStorage::initialise_card_v1() {
00181     for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
00182         _cmd(55, 0);
00183         if (_cmd(41, 0) == 0) {
00184             cdv = 512;
00185             debug_if(SD_DBG, "\n\rInit: SEDCARD_V1\n\r");
00186             return SDCARD_V1;
00187         }
00188     }
00189     
00190     debug("Timeout waiting for v1.x card\n");
00191     return SDCARD_FAIL;
00192 }
00193  
00194 int SDStorage::initialise_card_v2() {
00195     for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
00196         wait_ms(50);
00197         _cmd58();
00198         _cmd(55, 0);
00199         if (_cmd(41, 0x40000000) == 0) {
00200             _cmd58();
00201             debug_if(SD_DBG, "\n\rInit: SDCARD_V2\n\r");
00202             cdv = 1;
00203             return SDCARD_V2;
00204         }
00205     }
00206     
00207     debug("Timeout waiting for v2.x card\n");
00208     return SDCARD_FAIL;
00209 }
00210  
00211 int SDStorage::storage_initialize() {
00212     int i = initialise_card();
00213     debug_if(SD_DBG, "init card = %d\n", i);
00214     _sectors = _sd_sectors();
00215     
00216     // Set block length to 512 (CMD16)
00217     if (_cmd(16, 512) != 0) {
00218         debug("Set 512-byte block timed out\n");
00219         return 1;
00220     }
00221     
00222     _spi.frequency(1000000); // Set to 1MHz for data transfer
00223     return 0;
00224 }
00225  
00226 /* virtual */ int SDStorage::storage_write(const uint8_t *buffer, uint32_t block_number) {
00227     SD_DBG2("W %d", block_number);
00228     report_write_count++;
00229     // set write address for single block (CMD24)
00230     if (_cmd(24, block_number * cdv) != 0) {
00231         return 1;
00232     }
00233     
00234     // send the data block
00235     _write(buffer, 512);
00236     return 0;
00237 }
00238  
00239 /* virtual */ int SDStorage::storage_read(uint8_t *buffer, uint32_t block_number) {
00240     SD_DBG2("R %d", block_number);
00241     report_read_count++;
00242     // set read address for single block (CMD17)
00243     if (_cmd(17, block_number * cdv) != 0) {
00244         return 1;
00245     }
00246     
00247     // receive the data
00248     _read(buffer, 512);
00249     return 0;
00250 }
00251  
00252 //int SDStorage::disk_status() { return 0; }
00253 //int SDStorage::disk_sync() { return 0; }
00254 /* virtual */ uint32_t SDStorage::storage_sectors() { 
00255     report_sectors_count++;
00256     return _sectors;
00257 }
00258  
00259  
00260 // PRIVATE FUNCTIONS
00261 int SDStorage::_cmd(int cmd, int arg) {
00262     _cs = 0;
00263     
00264     // send a command
00265     _spi.write(0x40 | cmd);
00266     _spi.write(arg >> 24);
00267     _spi.write(arg >> 16);
00268     _spi.write(arg >> 8);
00269     _spi.write(arg >> 0);
00270     _spi.write(0x95);
00271     
00272     // wait for the repsonse (response[7] == 0)
00273     for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
00274         int response = _spi.write(0xFF);
00275         if (!(response & 0x80)) {
00276             _cs = 1;
00277             _spi.write(0xFF);
00278             return response;
00279         }
00280     }
00281     _cs = 1;
00282     _spi.write(0xFF);
00283     return -1; // timeout
00284 }
00285 int SDStorage::_cmdx(int cmd, int arg) {
00286     _cs = 0;
00287     
00288     // send a command
00289     _spi.write(0x40 | cmd);
00290     _spi.write(arg >> 24);
00291     _spi.write(arg >> 16);
00292     _spi.write(arg >> 8);
00293     _spi.write(arg >> 0);
00294     _spi.write(0x95);
00295     
00296     // wait for the repsonse (response[7] == 0)
00297     for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
00298         int response = _spi.write(0xFF);
00299         if (!(response & 0x80)) {
00300             return response;
00301         }
00302     }
00303     _cs = 1;
00304     _spi.write(0xFF);
00305     return -1; // timeout
00306 }
00307  
00308  
00309 int SDStorage::_cmd58() {
00310     _cs = 0;
00311     int arg = 0;
00312     
00313     // send a command
00314     _spi.write(0x40 | 58);
00315     _spi.write(arg >> 24);
00316     _spi.write(arg >> 16);
00317     _spi.write(arg >> 8);
00318     _spi.write(arg >> 0);
00319     _spi.write(0x95);
00320     
00321     // wait for the repsonse (response[7] == 0)
00322     for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
00323         int response = _spi.write(0xFF);
00324         if (!(response & 0x80)) {
00325             int ocr = _spi.write(0xFF) << 24;
00326             ocr |= _spi.write(0xFF) << 16;
00327             ocr |= _spi.write(0xFF) << 8;
00328             ocr |= _spi.write(0xFF) << 0;
00329             _cs = 1;
00330             _spi.write(0xFF);
00331             return response;
00332         }
00333     }
00334     _cs = 1;
00335     _spi.write(0xFF);
00336     return -1; // timeout
00337 }
00338  
00339 int SDStorage::_cmd8() {
00340     _cs = 0;
00341     
00342     // send a command
00343     _spi.write(0x40 | 8); // CMD8
00344     _spi.write(0x00);     // reserved
00345     _spi.write(0x00);     // reserved
00346     _spi.write(0x01);     // 3.3v
00347     _spi.write(0xAA);     // check pattern
00348     _spi.write(0x87);     // crc
00349     
00350     // wait for the repsonse (response[7] == 0)
00351     for (int i = 0; i < SD_COMMAND_TIMEOUT * 1000; i++) {
00352         char response[5];
00353         response[0] = _spi.write(0xFF);
00354         if (!(response[0] & 0x80)) {
00355             for (int j = 1; j < 5; j++) {
00356                 response[i] = _spi.write(0xFF);
00357             }
00358             _cs = 1;
00359             _spi.write(0xFF);
00360             return response[0];
00361         }
00362     }
00363     _cs = 1;
00364     _spi.write(0xFF);
00365     return -1; // timeout
00366 }
00367  
00368 int SDStorage::_read(uint8_t *buffer, uint32_t length) {
00369     _cs = 0;
00370     
00371     // read until start byte (0xFF)
00372     while (_spi.write(0xFF) != 0xFE);
00373     
00374     // read data
00375     for (int i = 0; i < length; i++) {
00376         buffer[i] = _spi.write(0xFF);
00377     }
00378     _spi.write(0xFF); // checksum
00379     _spi.write(0xFF);
00380     
00381     _cs = 1;
00382     _spi.write(0xFF);
00383     return 0;
00384 }
00385  
00386 int SDStorage::_write(const uint8_t*buffer, uint32_t length) {
00387     _cs = 0;
00388     
00389     // indicate start of block
00390     _spi.write(0xFE);
00391     
00392     // write the data
00393     for (int i = 0; i < length; i++) {
00394         _spi.write(buffer[i]);
00395     }
00396     
00397     // write the checksum
00398     _spi.write(0xFF);
00399     _spi.write(0xFF);
00400     
00401     // check the response token
00402     if ((_spi.write(0xFF) & 0x1F) != 0x05) {
00403         _cs = 1;
00404         _spi.write(0xFF);
00405         return 1;
00406     }
00407     
00408     // wait for write to finish
00409     while (_spi.write(0xFF) == 0);
00410     
00411     _cs = 1;
00412     _spi.write(0xFF);
00413     return 0;
00414 }
00415  
00416 static uint32_t ext_bits(unsigned char *data, int msb, int lsb) {
00417     uint32_t bits = 0;
00418     uint32_t size = 1 + msb - lsb;
00419     for (int i = 0; i < size; i++) {
00420         uint32_t position = lsb + i;
00421         uint32_t byte = 15 - (position >> 3);
00422         uint32_t bit = position & 0x7;
00423         uint32_t value = (data[byte] >> bit) & 1;
00424         bits |= value << i;
00425     }
00426     return bits;
00427 }
00428  
00429 uint64_t SDStorage::_sd_sectors() {
00430     uint32_t c_size, c_size_mult, read_bl_len;
00431     uint32_t block_len, mult, blocknr, capacity;
00432     uint32_t hc_c_size;
00433     uint64_t blocks;
00434     
00435     // CMD9, Response R2 (R1 byte + 16-byte block read)
00436     if (_cmdx(9, 0) != 0) {
00437         debug("Didn't get a response from the disk\n");
00438         return 0;
00439     }
00440     
00441     uint8_t csd[16];
00442     if (_read(csd, 16) != 0) {
00443         debug("Couldn't read csd response from disk\n");
00444         return 0;
00445     }
00446     
00447     // csd_structure : csd[127:126]
00448     // c_size        : csd[73:62]
00449     // c_size_mult   : csd[49:47]
00450     // read_bl_len   : csd[83:80] - the *maximum* read block length
00451     
00452     int csd_structure = ext_bits(csd, 127, 126);
00453     
00454     switch (csd_structure) {
00455         case 0:
00456             cdv = 512;
00457             c_size = ext_bits(csd, 73, 62);
00458             c_size_mult = ext_bits(csd, 49, 47);
00459             read_bl_len = ext_bits(csd, 83, 80);
00460             
00461             block_len = 1 << read_bl_len;
00462             mult = 1 << (c_size_mult + 2);
00463             blocknr = (c_size + 1) * mult;
00464             capacity = blocknr * block_len;
00465             blocks = capacity / 512;
00466             debug_if(SD_DBG, "\n\rSDCard\n\rc_size: %d \n\rcapacity: %ld \n\rsectors: %lld\n\r", c_size, capacity, blocks);
00467             break;
00468         
00469         case 1:
00470             cdv = 1;
00471             hc_c_size = ext_bits(csd, 63, 48);
00472             blocks = (hc_c_size+1)*1024;
00473             debug_if(SD_DBG, "\n\rSDHC Card \n\rhc_c_size: %d\n\rcapacity: %lld \n\rsectors: %lld\n\r", hc_c_size, blocks*512, blocks);
00474             break;
00475         
00476         default:
00477             debug("CSD struct unsupported\r\n");
00478             return 0;
00479     };
00480     return blocks;
00481 }
00482 
00483 /* virtual */ uint32_t SDStorage::storage_size()
00484 {
00485     report_size_count++;
00486     return _sectors * 512;
00487 }
00488