Toyomasa Watarai
/
Mbed-example-WS-W27
Mbed Cloud example program for workshop in W27 2018.
Embed:
(wiki syntax)
Show/hide line numbers
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.6.1 and above */ 00146 #if defined(MBED_MAJOR_VERSION) && MBED_MAJOR_VERSION >= 5 00147 #if (MBED_VERSION < MBED_ENCODE_VERSION(5,6,1)) 00148 #error "Incompatible mbed-os version detected! Required 5.6.1 and above" 00149 #endif 00150 #else 00151 #warning "mbed-os version 5.6.1 or above required" 00152 #endif 00153 00154 #define SD_COMMAND_TIMEOUT 5000 /*!< Timeout in ms for response */ 00155 #define SD_CMD0_GO_IDLE_STATE_RETRIES 5 /*!< Number of retries for sending CMDO */ 00156 #define SD_DBG 0 /*!< 1 - Enable debugging */ 00157 #define SD_CMD_TRACE 0 /*!< 1 - Enable SD command tracing */ 00158 00159 #define SD_BLOCK_DEVICE_ERROR_WOULD_BLOCK -5001 /*!< operation would block */ 00160 #define SD_BLOCK_DEVICE_ERROR_UNSUPPORTED -5002 /*!< unsupported operation */ 00161 #define SD_BLOCK_DEVICE_ERROR_PARAMETER -5003 /*!< invalid parameter */ 00162 #define SD_BLOCK_DEVICE_ERROR_NO_INIT -5004 /*!< uninitialized */ 00163 #define SD_BLOCK_DEVICE_ERROR_NO_DEVICE -5005 /*!< device is missing or not connected */ 00164 #define SD_BLOCK_DEVICE_ERROR_WRITE_PROTECTED -5006 /*!< write protected */ 00165 #define SD_BLOCK_DEVICE_ERROR_UNUSABLE -5007 /*!< unusable card */ 00166 #define SD_BLOCK_DEVICE_ERROR_NO_RESPONSE -5008 /*!< No response from device */ 00167 #define SD_BLOCK_DEVICE_ERROR_CRC -5009 /*!< CRC error */ 00168 #define SD_BLOCK_DEVICE_ERROR_ERASE -5010 /*!< Erase error: reset/sequence */ 00169 #define SD_BLOCK_DEVICE_ERROR_WRITE -5011 /*!< SPI Write error: !SPI_DATA_ACCEPTED */ 00170 00171 #define BLOCK_SIZE_HC 512 /*!< Block size supported for SD card is 512 bytes */ 00172 #define WRITE_BL_PARTIAL 0 /*!< Partial block write - Not supported */ 00173 #define CRC_SUPPORT 0 /*!< CRC - Not supported */ 00174 #define SPI_CMD(x) (0x40 | (x & 0x3f)) 00175 00176 /* R1 Response Format */ 00177 #define R1_NO_RESPONSE (0xFF) 00178 #define R1_RESPONSE_RECV (0x80) 00179 #define R1_IDLE_STATE (1 << 0) 00180 #define R1_ERASE_RESET (1 << 1) 00181 #define R1_ILLEGAL_COMMAND (1 << 2) 00182 #define R1_COM_CRC_ERROR (1 << 3) 00183 #define R1_ERASE_SEQUENCE_ERROR (1 << 4) 00184 #define R1_ADDRESS_ERROR (1 << 5) 00185 #define R1_PARAMETER_ERROR (1 << 6) 00186 00187 // Types 00188 #define SDCARD_NONE 0 /**< No card is present */ 00189 #define SDCARD_V1 1 /**< v1.x Standard Capacity */ 00190 #define SDCARD_V2 2 /**< v2.x Standard capacity SD card */ 00191 #define SDCARD_V2HC 3 /**< v2.x High capacity SD card */ 00192 #define CARD_UNKNOWN 4 /**< Unknown or unsupported card */ 00193 00194 /* SIZE in Bytes */ 00195 #define PACKET_SIZE 6 /*!< SD Packet size CMD+ARG+CRC */ 00196 #define R1_RESPONSE_SIZE 1 /*!< Size of R1 response */ 00197 #define R2_RESPONSE_SIZE 2 /*!< Size of R2 response */ 00198 #define R3_R7_RESPONSE_SIZE 5 /*!< Size of R3/R7 response */ 00199 00200 /* R1b Response */ 00201 #define DEVICE_BUSY (0x00) 00202 00203 /* R2 Response Format */ 00204 #define R2_CARD_LOCKED (1 << 0) 00205 #define R2_CMD_FAILED (1 << 1) 00206 #define R2_ERROR (1 << 2) 00207 #define R2_CC_ERROR (1 << 3) 00208 #define R2_CC_FAILED (1 << 4) 00209 #define R2_WP_VIOLATION (1 << 5) 00210 #define R2_ERASE_PARAM (1 << 6) 00211 #define R2_OUT_OF_RANGE (1 << 7) 00212 00213 /* R3 Response : OCR Register */ 00214 #define OCR_HCS_CCS (0x1 << 30) 00215 #define OCR_LOW_VOLTAGE (0x01 << 24) 00216 #define OCR_3_3V (0x1 << 20) 00217 00218 /* R7 response pattern for CMD8 */ 00219 #define CMD8_PATTERN (0xAA) 00220 00221 /* CRC Enable */ 00222 #define CRC_ENABLE (0) /*!< CRC 1 - Enable 0 - Disable */ 00223 00224 /* Control Tokens */ 00225 #define SPI_DATA_RESPONSE_MASK (0x1F) 00226 #define SPI_DATA_ACCEPTED (0x05) 00227 #define SPI_DATA_CRC_ERROR (0x0B) 00228 #define SPI_DATA_WRITE_ERROR (0x0D) 00229 #define SPI_START_BLOCK (0xFE) /*!< For Single Block Read/Write and Multiple Block Read */ 00230 #define SPI_START_BLK_MUL_WRITE (0xFC) /*!< Start Multi-block write */ 00231 #define SPI_STOP_TRAN (0xFD) /*!< Stop Multi-block write */ 00232 00233 #define SPI_DATA_READ_ERROR_MASK (0xF) /*!< Data Error Token: 4 LSB bits */ 00234 #define SPI_READ_ERROR (0x1 << 0) /*!< Error */ 00235 #define SPI_READ_ERROR_CC (0x1 << 1) /*!< CC Error*/ 00236 #define SPI_READ_ERROR_ECC_C (0x1 << 2) /*!< Card ECC failed */ 00237 #define SPI_READ_ERROR_OFR (0x1 << 3) /*!< Out of Range */ 00238 00239 SDBlockDevice::SDBlockDevice(PinName mosi, PinName miso, PinName sclk, PinName cs, uint64_t hz) 00240 : _sectors(0), _spi(mosi, miso, sclk), _cs(cs), _is_initialized(0) 00241 { 00242 _cs = 1; 00243 _card_type = SDCARD_NONE; 00244 00245 // Set default to 100kHz for initialisation and 1MHz for data transfer 00246 _init_sck = 100000; 00247 _transfer_sck = hz; 00248 00249 // Only HC block size is supported. 00250 _block_size = BLOCK_SIZE_HC; 00251 _erase_size = BLOCK_SIZE_HC; 00252 } 00253 00254 SDBlockDevice::~SDBlockDevice() 00255 { 00256 if (_is_initialized) { 00257 deinit(); 00258 } 00259 } 00260 00261 int SDBlockDevice::_initialise_card() 00262 { 00263 // Detail debugging is for commands 00264 _dbg = SD_DBG ? SD_CMD_TRACE : 0; 00265 int32_t status = BD_ERROR_OK; 00266 uint32_t response, arg; 00267 00268 // Initialize the SPI interface: Card by default is in SD mode 00269 _spi_init(); 00270 00271 // The card is transitioned from SDCard mode to SPI mode by sending the CMD0 + CS Asserted("0") 00272 if (_go_idle_state() != R1_IDLE_STATE) { 00273 debug_if(SD_DBG, "No disk, or could not put SD card in to SPI idle state\n"); 00274 return SD_BLOCK_DEVICE_ERROR_NO_DEVICE; 00275 } 00276 00277 // Send CMD8, if the card rejects the command then it's probably using the 00278 // legacy protocol, or is a MMC, or just flat-out broken 00279 status = _cmd8(); 00280 if (BD_ERROR_OK != status && SD_BLOCK_DEVICE_ERROR_UNSUPPORTED != status) { 00281 return status; 00282 } 00283 00284 // Read OCR - CMD58 Response contains OCR register 00285 if (BD_ERROR_OK != (status = _cmd(CMD58_READ_OCR, 0x0, 0x0, &response))) { 00286 return status; 00287 } 00288 00289 // Check if card supports voltage range: 3.3V 00290 if (!(response & OCR_3_3V)) { 00291 _card_type = CARD_UNKNOWN; 00292 status = SD_BLOCK_DEVICE_ERROR_UNUSABLE; 00293 return status; 00294 } 00295 00296 // HCS is set 1 for HC/XC capacity cards for ACMD41, if supported 00297 arg = 0x0; 00298 if (SDCARD_V2 == _card_type) { 00299 arg |= OCR_HCS_CCS; 00300 } 00301 00302 /* Idle state bit in the R1 response of ACMD41 is used by the card to inform the host 00303 * if initialization of ACMD41 is completed. "1" indicates that the card is still initializing. 00304 * "0" indicates completion of initialization. The host repeatedly issues ACMD41 until 00305 * this bit is set to "0". 00306 */ 00307 _spi_timer.start(); 00308 do { 00309 status = _cmd(ACMD41_SD_SEND_OP_COND, arg, 1, &response); 00310 } while ((response & R1_IDLE_STATE) && (_spi_timer.read_ms() < SD_COMMAND_TIMEOUT)); 00311 _spi_timer.stop(); 00312 00313 // Initialization complete: ACMD41 successful 00314 if ((BD_ERROR_OK != status) || (0x00 != response)) { 00315 _card_type = CARD_UNKNOWN; 00316 debug_if(SD_DBG, "Timeout waiting for card\n"); 00317 return status; 00318 } 00319 00320 if (SDCARD_V2 == _card_type) { 00321 // Get the card capacity CCS: CMD58 00322 if (BD_ERROR_OK == (status = _cmd(CMD58_READ_OCR, 0x0, 0x0, &response))) { 00323 // High Capacity card 00324 if (response & OCR_HCS_CCS) { 00325 _card_type = SDCARD_V2HC; 00326 debug_if(SD_DBG, "Card Initialized: High Capacity Card \n"); 00327 } else { 00328 debug_if(SD_DBG, "Card Initialized: Standard Capacity Card: Version 2.x \n"); 00329 } 00330 } 00331 } else { 00332 _card_type = SDCARD_V1; 00333 debug_if(SD_DBG, "Card Initialized: Version 1.x Card\n"); 00334 } 00335 00336 // Disable CRC 00337 status = _cmd(CMD59_CRC_ON_OFF, 0); 00338 00339 return status; 00340 } 00341 00342 00343 int SDBlockDevice::init() 00344 { 00345 lock(); 00346 int err = _initialise_card(); 00347 _is_initialized = (err == BD_ERROR_OK); 00348 if (!_is_initialized) { 00349 debug_if(SD_DBG, "Fail to initialize card\n"); 00350 unlock(); 00351 return err; 00352 } 00353 debug_if(SD_DBG, "init card = %d\n", _is_initialized); 00354 _sectors = _sd_sectors(); 00355 // CMD9 failed 00356 if (0 == _sectors) { 00357 unlock(); 00358 return BD_ERROR_DEVICE_ERROR; 00359 } 00360 00361 // Set block length to 512 (CMD16) 00362 if (_cmd(CMD16_SET_BLOCKLEN, _block_size) != 0) { 00363 debug_if(SD_DBG, "Set %d-byte block timed out\n", _block_size); 00364 unlock(); 00365 return BD_ERROR_DEVICE_ERROR; 00366 } 00367 00368 // Set SCK for data transfer 00369 err = _freq(); 00370 if (err) { 00371 unlock(); 00372 return err; 00373 } 00374 unlock(); 00375 return BD_ERROR_OK; 00376 } 00377 00378 int SDBlockDevice::deinit() 00379 { 00380 lock(); 00381 _is_initialized = false; 00382 _sectors = 0; 00383 unlock(); 00384 return 0; 00385 } 00386 00387 00388 int SDBlockDevice::program(const void *b, bd_addr_t addr, bd_size_t size) 00389 { 00390 if (!is_valid_program(addr, size)) { 00391 return SD_BLOCK_DEVICE_ERROR_PARAMETER; 00392 } 00393 00394 lock(); 00395 if (!_is_initialized) { 00396 unlock(); 00397 return SD_BLOCK_DEVICE_ERROR_NO_INIT; 00398 } 00399 00400 const uint8_t *buffer = static_cast<const uint8_t*>(b); 00401 int status = BD_ERROR_OK; 00402 uint8_t response; 00403 00404 // Get block count 00405 bd_addr_t blockCnt = size / _block_size; 00406 00407 // SDSC Card (CCS=0) uses byte unit address 00408 // SDHC and SDXC Cards (CCS=1) use block unit address (512 Bytes unit) 00409 if(SDCARD_V2HC == _card_type) { 00410 addr = addr / _block_size; 00411 } 00412 00413 // Send command to perform write operation 00414 if (blockCnt == 1) { 00415 // Single block write command 00416 if (BD_ERROR_OK != (status = _cmd(CMD24_WRITE_BLOCK, addr))) { 00417 unlock(); 00418 return status; 00419 } 00420 00421 // Write data 00422 response = _write(buffer, SPI_START_BLOCK, _block_size); 00423 00424 // Only CRC and general write error are communicated via response token 00425 if ((response == SPI_DATA_CRC_ERROR) || (response == SPI_DATA_WRITE_ERROR)) { 00426 debug_if(SD_DBG, "Single Block Write failed: 0x%x \n", response); 00427 status = SD_BLOCK_DEVICE_ERROR_WRITE; 00428 } 00429 } else { 00430 // Pre-erase setting prior to multiple block write operation 00431 _cmd(ACMD23_SET_WR_BLK_ERASE_COUNT, blockCnt, 1); 00432 00433 // Multiple block write command 00434 if (BD_ERROR_OK != (status = _cmd(CMD25_WRITE_MULTIPLE_BLOCK, addr))) { 00435 unlock(); 00436 return status; 00437 } 00438 00439 // Write the data: one block at a time 00440 do { 00441 response = _write(buffer, SPI_START_BLK_MUL_WRITE, _block_size); 00442 if (response != SPI_DATA_ACCEPTED) { 00443 debug_if(SD_DBG, "Multiple Block Write failed: 0x%x \n", response); 00444 break; 00445 } 00446 buffer += _block_size; 00447 }while (--blockCnt); // Receive all blocks of data 00448 00449 /* In a Multiple Block write operation, the stop transmission will be done by 00450 * sending 'Stop Tran' token instead of 'Start Block' token at the beginning 00451 * of the next block 00452 */ 00453 _spi.write(SPI_STOP_TRAN); 00454 } 00455 00456 _deselect(); 00457 unlock(); 00458 return status; 00459 } 00460 00461 int SDBlockDevice::read(void *b, bd_addr_t addr, bd_size_t size) 00462 { 00463 if (!is_valid_read(addr, size)) { 00464 return SD_BLOCK_DEVICE_ERROR_PARAMETER; 00465 } 00466 00467 lock(); 00468 if (!_is_initialized) { 00469 unlock(); 00470 return SD_BLOCK_DEVICE_ERROR_PARAMETER; 00471 } 00472 00473 uint8_t *buffer = static_cast<uint8_t *>(b); 00474 int status = BD_ERROR_OK; 00475 bd_addr_t blockCnt = size / _block_size; 00476 00477 // SDSC Card (CCS=0) uses byte unit address 00478 // SDHC and SDXC Cards (CCS=1) use block unit address (512 Bytes unit) 00479 if (SDCARD_V2HC == _card_type) { 00480 addr = addr / _block_size; 00481 } 00482 00483 // Write command ro receive data 00484 if (blockCnt > 1) { 00485 status = _cmd(CMD18_READ_MULTIPLE_BLOCK, addr); 00486 } else { 00487 status = _cmd(CMD17_READ_SINGLE_BLOCK, addr); 00488 } 00489 if (BD_ERROR_OK != status) { 00490 unlock(); 00491 return status; 00492 } 00493 00494 // receive the data : one block at a time 00495 while (blockCnt) { 00496 if (0 != _read(buffer, _block_size)) { 00497 status = SD_BLOCK_DEVICE_ERROR_NO_RESPONSE; 00498 break; 00499 } 00500 buffer += _block_size; 00501 --blockCnt; 00502 } 00503 _deselect(); 00504 00505 // Send CMD12(0x00000000) to stop the transmission for multi-block transfer 00506 if (size > _block_size) { 00507 status = _cmd(CMD12_STOP_TRANSMISSION, 0x0); 00508 } 00509 unlock(); 00510 return status; 00511 } 00512 00513 bool SDBlockDevice::_is_valid_trim(bd_addr_t addr, bd_size_t size) 00514 { 00515 return ( 00516 addr % _erase_size == 0 && 00517 size % _erase_size == 0 && 00518 addr + size <= this->size()); 00519 } 00520 00521 int SDBlockDevice::trim(bd_addr_t addr, bd_size_t size) 00522 { 00523 if (!_is_valid_trim(addr, size)) { 00524 return SD_BLOCK_DEVICE_ERROR_PARAMETER; 00525 } 00526 00527 lock(); 00528 if (!_is_initialized) { 00529 unlock(); 00530 return SD_BLOCK_DEVICE_ERROR_NO_INIT; 00531 } 00532 int status = BD_ERROR_OK; 00533 00534 size -= _block_size; 00535 // SDSC Card (CCS=0) uses byte unit address 00536 // SDHC and SDXC Cards (CCS=1) use block unit address (512 Bytes unit) 00537 if (SDCARD_V2HC == _card_type) { 00538 size = size / _block_size; 00539 addr = addr / _block_size; 00540 } 00541 00542 // Start lba sent in start command 00543 if (BD_ERROR_OK != (status = _cmd(CMD32_ERASE_WR_BLK_START_ADDR, addr))) { 00544 unlock(); 00545 return status; 00546 } 00547 00548 // End lba = addr+size sent in end addr command 00549 if (BD_ERROR_OK != (status = _cmd(CMD33_ERASE_WR_BLK_END_ADDR, addr+size))) { 00550 unlock(); 00551 return status; 00552 } 00553 status = _cmd(CMD38_ERASE, 0x0); 00554 unlock(); 00555 return status; 00556 } 00557 00558 bd_size_t SDBlockDevice::get_read_size() const 00559 { 00560 return _block_size; 00561 } 00562 00563 bd_size_t SDBlockDevice::get_program_size() const 00564 { 00565 return _block_size; 00566 } 00567 00568 bd_size_t SDBlockDevice::size() const 00569 { 00570 return _block_size*_sectors; 00571 } 00572 00573 void SDBlockDevice::debug(bool dbg) 00574 { 00575 _dbg = dbg; 00576 } 00577 00578 int SDBlockDevice::frequency(uint64_t freq) 00579 { 00580 lock(); 00581 _transfer_sck = freq; 00582 int err = _freq(); 00583 unlock(); 00584 return err; 00585 } 00586 00587 // PRIVATE FUNCTIONS 00588 int SDBlockDevice::_freq(void) 00589 { 00590 // Max frequency supported is 25MHZ 00591 if (_transfer_sck <= 25000000) { 00592 _spi.frequency(_transfer_sck); 00593 return 0; 00594 } else { // TODO: Switch function to be implemented for higher frequency 00595 _transfer_sck = 25000000; 00596 _spi.frequency(_transfer_sck); 00597 return -EINVAL; 00598 } 00599 } 00600 00601 uint8_t SDBlockDevice::_cmd_spi(SDBlockDevice::cmdSupported cmd, uint32_t arg) { 00602 uint8_t response; 00603 char cmdPacket[PACKET_SIZE]; 00604 00605 // Prepare the command packet 00606 cmdPacket[0] = SPI_CMD(cmd); 00607 cmdPacket[1] = (arg >> 24); 00608 cmdPacket[2] = (arg >> 16); 00609 cmdPacket[3] = (arg >> 8); 00610 cmdPacket[4] = (arg >> 0); 00611 // CMD0 is executed in SD mode, hence should have correct CRC 00612 // CMD8 CRC verification is always enabled 00613 switch(cmd) { 00614 case CMD0_GO_IDLE_STATE: 00615 cmdPacket[5] = 0x95; 00616 break; 00617 case CMD8_SEND_IF_COND: 00618 cmdPacket[5] = 0x87; 00619 break; 00620 default: 00621 cmdPacket[5] = 0xFF; // Make sure bit 0-End bit is high 00622 break; 00623 } 00624 00625 // send a command 00626 for (int i = 0; i < PACKET_SIZE; i++) { 00627 _spi.write(cmdPacket[i]); 00628 } 00629 00630 // The received byte immediataly following CMD12 is a stuff byte, 00631 // it should be discarded before receive the response of the CMD12. 00632 if (CMD12_STOP_TRANSMISSION == cmd) { 00633 _spi.write(SPI_FILL_CHAR); 00634 } 00635 00636 // Loop for response: Response is sent back within command response time (NCR), 0 to 8 bytes for SDC 00637 for (int i = 0; i < 0x10; i++) { 00638 response = _spi.write(SPI_FILL_CHAR); 00639 // Got the response 00640 if (!(response & R1_RESPONSE_RECV)) { 00641 break; 00642 } 00643 } 00644 return response; 00645 } 00646 00647 int SDBlockDevice::_cmd(SDBlockDevice::cmdSupported cmd, uint32_t arg, bool isAcmd, uint32_t *resp) { 00648 int32_t status = BD_ERROR_OK; 00649 uint32_t response; 00650 00651 // Select card and wait for card to be ready before sending next command 00652 // Note: next command will fail if card is not ready 00653 _select(); 00654 00655 // No need to wait for card to be ready when sending the stop command 00656 if (CMD12_STOP_TRANSMISSION != cmd) { 00657 if (false == _wait_ready(SD_COMMAND_TIMEOUT)) { 00658 debug_if(SD_DBG, "Card not ready yet \n"); 00659 } 00660 } 00661 00662 // Re-try command 00663 for(int i = 0; i < 3; i++) { 00664 // Send CMD55 for APP command first 00665 if (isAcmd) { 00666 response = _cmd_spi(CMD55_APP_CMD, 0x0); 00667 // Wait for card to be ready after CMD55 00668 if (false == _wait_ready(SD_COMMAND_TIMEOUT)) { 00669 debug_if(SD_DBG, "Card not ready yet \n"); 00670 } 00671 } 00672 00673 // Send command over SPI interface 00674 response = _cmd_spi(cmd, arg); 00675 if (R1_NO_RESPONSE == response) { 00676 debug_if(SD_DBG, "No response CMD:%d \n", cmd); 00677 continue; 00678 } 00679 break; 00680 } 00681 00682 // Pass the response to the command call if required 00683 if (NULL != resp) { 00684 *resp = response; 00685 } 00686 00687 // Process the response R1 : Exit on CRC/Illegal command error/No response 00688 if (R1_NO_RESPONSE == response) { 00689 _deselect(); 00690 debug_if(SD_DBG, "No response CMD:%d response: 0x%x\n",cmd, response); 00691 return SD_BLOCK_DEVICE_ERROR_NO_DEVICE; // No device 00692 } 00693 if (response & R1_COM_CRC_ERROR) { 00694 _deselect(); 00695 debug_if(SD_DBG, "CRC error CMD:%d response 0x%x \n",cmd, response); 00696 return SD_BLOCK_DEVICE_ERROR_CRC; // CRC error 00697 } 00698 if (response & R1_ILLEGAL_COMMAND) { 00699 _deselect(); 00700 debug_if(SD_DBG, "Illegal command CMD:%d response 0x%x\n",cmd, response); 00701 if (CMD8_SEND_IF_COND == cmd) { // Illegal command is for Ver1 or not SD Card 00702 _card_type = CARD_UNKNOWN; 00703 } 00704 return SD_BLOCK_DEVICE_ERROR_UNSUPPORTED; // Command not supported 00705 } 00706 00707 debug_if(_dbg, "CMD:%d \t arg:0x%x \t Response:0x%x \n", cmd, arg, response); 00708 // Set status for other errors 00709 if ((response & R1_ERASE_RESET) || (response & R1_ERASE_SEQUENCE_ERROR)) { 00710 status = SD_BLOCK_DEVICE_ERROR_ERASE; // Erase error 00711 }else if ((response & R1_ADDRESS_ERROR) || (response & R1_PARAMETER_ERROR)) { 00712 // Misaligned address / invalid address block length 00713 status = SD_BLOCK_DEVICE_ERROR_PARAMETER; 00714 } 00715 00716 // Get rest of the response part for other commands 00717 switch(cmd) { 00718 case CMD8_SEND_IF_COND: // Response R7 00719 debug_if(_dbg, "V2-Version Card\n"); 00720 _card_type = SDCARD_V2; 00721 // Note: No break here, need to read rest of the response 00722 case CMD58_READ_OCR: // Response R3 00723 response = (_spi.write(SPI_FILL_CHAR) << 24); 00724 response |= (_spi.write(SPI_FILL_CHAR) << 16); 00725 response |= (_spi.write(SPI_FILL_CHAR) << 8); 00726 response |= _spi.write(SPI_FILL_CHAR); 00727 debug_if(_dbg, "R3/R7: 0x%x \n", response); 00728 break; 00729 00730 case CMD12_STOP_TRANSMISSION: // Response R1b 00731 case CMD38_ERASE: 00732 _wait_ready(SD_COMMAND_TIMEOUT); 00733 break; 00734 00735 case ACMD13_SD_STATUS: // Response R2 00736 response = _spi.write(SPI_FILL_CHAR); 00737 debug_if(_dbg, "R2: 0x%x \n", response); 00738 break; 00739 00740 default: // Response R1 00741 break; 00742 } 00743 00744 // Pass the updated response to the command 00745 if (NULL != resp) { 00746 *resp = response; 00747 } 00748 00749 // Do not deselect card if read is in progress. 00750 if (((CMD9_SEND_CSD == cmd) || (ACMD22_SEND_NUM_WR_BLOCKS == cmd) || 00751 (CMD24_WRITE_BLOCK == cmd) || (CMD25_WRITE_MULTIPLE_BLOCK == cmd) || 00752 (CMD17_READ_SINGLE_BLOCK == cmd) || (CMD18_READ_MULTIPLE_BLOCK == cmd)) 00753 && (BD_ERROR_OK == status)) { 00754 return BD_ERROR_OK; 00755 } 00756 // Deselect card 00757 _deselect(); 00758 return status; 00759 } 00760 00761 int SDBlockDevice::_cmd8() { 00762 uint32_t arg = (CMD8_PATTERN << 0); // [7:0]check pattern 00763 uint32_t response = 0; 00764 int32_t status = BD_ERROR_OK; 00765 00766 arg |= (0x1 << 8); // 2.7-3.6V // [11:8]supply voltage(VHS) 00767 00768 status = _cmd(CMD8_SEND_IF_COND, arg, 0x0, &response); 00769 // Verify voltage and pattern for V2 version of card 00770 if ((BD_ERROR_OK == status) && (SDCARD_V2 == _card_type)) { 00771 // If check pattern is not matched, CMD8 communication is not valid 00772 if((response & 0xFFF) != arg) 00773 { 00774 debug_if(SD_DBG, "CMD8 Pattern mismatch 0x%x : 0x%x\n", arg, response); 00775 _card_type = CARD_UNKNOWN; 00776 status = SD_BLOCK_DEVICE_ERROR_UNUSABLE; 00777 } 00778 } 00779 return status; 00780 } 00781 00782 uint32_t SDBlockDevice::_go_idle_state() { 00783 uint32_t response; 00784 00785 /* Reseting the MCU SPI master may not reset the on-board SDCard, in which 00786 * case when MCU power-on occurs the SDCard will resume operations as 00787 * though there was no reset. In this scenario the first CMD0 will 00788 * not be interpreted as a command and get lost. For some cards retrying 00789 * the command overcomes this situation. */ 00790 for (int i = 0; i < SD_CMD0_GO_IDLE_STATE_RETRIES; i++) { 00791 _cmd(CMD0_GO_IDLE_STATE, 0x0, 0x0, &response); 00792 if (R1_IDLE_STATE == response) 00793 break; 00794 wait_ms(1); 00795 } 00796 return response; 00797 } 00798 00799 int SDBlockDevice::_read_bytes(uint8_t *buffer, uint32_t length) { 00800 uint16_t crc; 00801 00802 // read until start byte (0xFE) 00803 if (false == _wait_token(SPI_START_BLOCK)) { 00804 debug_if(SD_DBG, "Read timeout\n"); 00805 _deselect(); 00806 return SD_BLOCK_DEVICE_ERROR_NO_RESPONSE; 00807 } 00808 00809 // read data 00810 for (uint32_t i = 0; i < length; i++) { 00811 buffer[i] = _spi.write(SPI_FILL_CHAR); 00812 } 00813 00814 // Read the CRC16 checksum for the data block 00815 crc = (_spi.write(SPI_FILL_CHAR) << 8); 00816 crc |= _spi.write(SPI_FILL_CHAR); 00817 00818 _deselect(); 00819 return 0; 00820 } 00821 00822 int SDBlockDevice::_read(uint8_t *buffer, uint32_t length) { 00823 uint16_t crc; 00824 00825 // read until start byte (0xFE) 00826 if (false == _wait_token(SPI_START_BLOCK)) { 00827 debug_if(SD_DBG, "Read timeout\n"); 00828 _deselect(); 00829 return SD_BLOCK_DEVICE_ERROR_NO_RESPONSE; 00830 } 00831 00832 // read data 00833 _spi.write(NULL, 0, (char*)buffer, length); 00834 00835 // Read the CRC16 checksum for the data block 00836 crc = (_spi.write(SPI_FILL_CHAR) << 8); 00837 crc |= _spi.write(SPI_FILL_CHAR); 00838 00839 return 0; 00840 } 00841 00842 uint8_t SDBlockDevice::_write(const uint8_t *buffer, uint8_t token, uint32_t length) { 00843 uint16_t crc = 0xFFFF; 00844 uint8_t response = 0xFF; 00845 00846 // indicate start of block 00847 _spi.write(token); 00848 00849 // write the data 00850 _spi.write((char*)buffer, length, NULL, 0); 00851 00852 // write the checksum CRC16 00853 _spi.write(crc >> 8); 00854 _spi.write(crc); 00855 00856 // check the response token 00857 response = _spi.write(SPI_FILL_CHAR); 00858 00859 // Wait for last block to be written 00860 if (false == _wait_ready(SD_COMMAND_TIMEOUT)) { 00861 debug_if(SD_DBG, "Card not ready yet \n"); 00862 } 00863 00864 return (response & SPI_DATA_RESPONSE_MASK); 00865 } 00866 00867 static uint32_t ext_bits(unsigned char *data, int msb, int lsb) { 00868 uint32_t bits = 0; 00869 uint32_t size = 1 + msb - lsb; 00870 for (uint32_t i = 0; i < size; i++) { 00871 uint32_t position = lsb + i; 00872 uint32_t byte = 15 - (position >> 3); 00873 uint32_t bit = position & 0x7; 00874 uint32_t value = (data[byte] >> bit) & 1; 00875 bits |= value << i; 00876 } 00877 return bits; 00878 } 00879 00880 bd_size_t SDBlockDevice::_sd_sectors() { 00881 uint32_t c_size, c_size_mult, read_bl_len; 00882 uint32_t block_len, mult, blocknr; 00883 uint32_t hc_c_size; 00884 bd_size_t blocks = 0, capacity = 0; 00885 00886 // CMD9, Response R2 (R1 byte + 16-byte block read) 00887 if (_cmd(CMD9_SEND_CSD, 0x0) != 0x0) { 00888 debug_if(SD_DBG, "Didn't get a response from the disk\n"); 00889 return 0; 00890 } 00891 uint8_t csd[16]; 00892 if (_read_bytes(csd, 16) != 0) { 00893 debug_if(SD_DBG, "Couldn't read csd response from disk\n"); 00894 return 0; 00895 } 00896 00897 // csd_structure : csd[127:126] 00898 int csd_structure = ext_bits(csd, 127, 126); 00899 switch (csd_structure) { 00900 case 0: 00901 c_size = ext_bits(csd, 73, 62); // c_size : csd[73:62] 00902 c_size_mult = ext_bits(csd, 49, 47); // c_size_mult : csd[49:47] 00903 read_bl_len = ext_bits(csd, 83, 80); // read_bl_len : csd[83:80] - the *maximum* read block length 00904 block_len = 1 << read_bl_len; // BLOCK_LEN = 2^READ_BL_LEN 00905 mult = 1 << (c_size_mult + 2); // MULT = 2^C_SIZE_MULT+2 (C_SIZE_MULT < 8) 00906 blocknr = (c_size + 1) * mult; // BLOCKNR = (C_SIZE+1) * MULT 00907 capacity = blocknr * block_len; // memory capacity = BLOCKNR * BLOCK_LEN 00908 blocks = capacity / _block_size; 00909 debug_if(SD_DBG, "Standard Capacity: c_size: %d \n", c_size); 00910 debug_if(SD_DBG, "Sectors: 0x%x : %llu\n", blocks, blocks); 00911 debug_if(SD_DBG, "Capacity: 0x%x : %llu MB\n", capacity, (capacity/(1024U*1024U))); 00912 00913 // ERASE_BLK_EN = 1: Erase in multiple of 512 bytes supported 00914 if (ext_bits(csd, 46, 46)) { 00915 _erase_size = BLOCK_SIZE_HC; 00916 } else { 00917 // ERASE_BLK_EN = 1: Erase in multiple of SECTOR_SIZE supported 00918 _erase_size = BLOCK_SIZE_HC * (ext_bits(csd, 45, 39) + 1); 00919 } 00920 break; 00921 00922 case 1: 00923 hc_c_size = ext_bits(csd, 69, 48); // device size : C_SIZE : [69:48] 00924 blocks = (hc_c_size+1) << 10; // block count = C_SIZE+1) * 1K byte (512B is block size) 00925 debug_if(SD_DBG, "SDHC/SDXC Card: hc_c_size: %d \n", hc_c_size); 00926 debug_if(SD_DBG, "Sectors: 0x%x : %llu\n", blocks, blocks); 00927 debug_if(SD_DBG, "Capacity: %llu MB\n", (blocks/(2048U))); 00928 // ERASE_BLK_EN is fixed to 1, which means host can erase one or multiple of 512 bytes. 00929 _erase_size = BLOCK_SIZE_HC; 00930 break; 00931 00932 default: 00933 debug_if(SD_DBG, "CSD struct unsupported\r\n"); 00934 return 0; 00935 }; 00936 return blocks; 00937 } 00938 00939 // SPI function to wait till chip is ready and sends start token 00940 bool SDBlockDevice::_wait_token(uint8_t token) { 00941 _spi_timer.reset(); 00942 _spi_timer.start(); 00943 00944 do { 00945 if (token == _spi.write(SPI_FILL_CHAR)) { 00946 _spi_timer.stop(); 00947 return true; 00948 } 00949 } while (_spi_timer.read_ms() < 300); // Wait for 300 msec for start token 00950 _spi_timer.stop(); 00951 debug_if(SD_DBG, "_wait_token: timeout\n"); 00952 return false; 00953 } 00954 00955 // SPI function to wait till chip is ready 00956 // The host controller should wait for end of the process until DO goes high (a 0xFF is received). 00957 bool SDBlockDevice::_wait_ready(uint16_t ms) { 00958 uint8_t response; 00959 _spi_timer.reset(); 00960 _spi_timer.start(); 00961 do { 00962 response = _spi.write(SPI_FILL_CHAR); 00963 if (response == 0xFF) { 00964 _spi_timer.stop(); 00965 return true; 00966 } 00967 } while (_spi_timer.read_ms() < ms); 00968 _spi_timer.stop(); 00969 return false; 00970 } 00971 00972 // SPI function to wait for count 00973 void SDBlockDevice::_spi_wait(uint8_t count) 00974 { 00975 for (uint8_t i = 0; i < count; ++i) { 00976 _spi.write(SPI_FILL_CHAR); 00977 } 00978 } 00979 00980 void SDBlockDevice::_spi_init() { 00981 _spi.lock(); 00982 // Set to SCK for initialization, and clock card with cs = 1 00983 _spi.frequency(_init_sck); 00984 _spi.format(8, 0); 00985 _spi.set_default_write_value(SPI_FILL_CHAR); 00986 // Initial 74 cycles required for few cards, before selecting SPI mode 00987 _cs = 1; 00988 _spi_wait(10); 00989 _spi.unlock(); 00990 } 00991 00992 void SDBlockDevice::_select() { 00993 _spi.lock(); 00994 _spi.write(SPI_FILL_CHAR); 00995 _cs = 0; 00996 } 00997 00998 void SDBlockDevice::_deselect() { 00999 _cs = 1; 01000 _spi.write(SPI_FILL_CHAR); 01001 _spi.unlock(); 01002 } 01003 01004 #endif /* DEVICE_SPI */
Generated on Tue Jul 12 2022 16:22:11 by 1.7.2