2 * This file is part of Cleanflight and Betaflight.
4 * Cleanflight and Betaflight are free software. You can redistribute
5 * this software and/or modify this software under the terms of the
6 * GNU General Public License as published by the Free Software
7 * Foundation, either version 3 of the License, or (at your option)
10 * Cleanflight and Betaflight are distributed in the hope that they
11 * will be useful, but WITHOUT ANY WARRANTY; without even the implied
12 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 * See the GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this software.
18 * If not, see <http://www.gnu.org/licenses/>.
28 #include "drivers/nvic.h"
29 #include "drivers/io.h"
30 #include "drivers/dma.h"
31 #include "drivers/dma_reqmap.h"
33 #include "drivers/bus_spi.h"
34 #include "drivers/time.h"
36 #include "pg/bus_spi.h"
37 #include "pg/sdcard.h"
40 #include "sdcard_impl.h"
41 #include "sdcard_standard.h"
43 #ifdef AFATFS_USE_INTROSPECTIVE_LOGGING
44 #define SDCARD_PROFILING
47 #define SDCARD_INIT_NUM_DUMMY_BYTES 10
48 #define SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY 8
49 // Chosen so that CMD8 will have the same CRC as CMD0:
50 #define SDCARD_IF_COND_CHECK_PATTERN 0xAB
52 /* Spec calls for under 400KHz */
53 #define SDCARD_MAX_SPI_INIT_CLK_HZ 400000
55 /* Operational speed <= 25MHz */
56 #define SDCARD_MAX_SPI_CLK_HZ 25000000
58 #define SDCARD_SPI_MODE SPI_MODE0_POL_LOW_EDGE_1ST
59 //#define SDCARD_SPI_MODE SPI_MODE3_POL_HIGH_EDGE_2ND
61 /* Break up 512-byte SD card sectors into chunks of this size when writing without DMA to reduce the peak overhead
62 * per call to sdcard_poll().
64 #define SDCARD_NON_DMA_CHUNK_SIZE 256
67 * Returns true if the card has already been, or is currently, initializing and hasn't encountered enough errors to
68 * trip our error threshold and be disabled (i.e. our card is in and working!)
70 static bool sdcardSpi_isFunctional(void)
72 return sdcard
.state
!= SDCARD_STATE_NOT_PRESENT
;
75 static void sdcard_select(void)
77 #ifdef USE_SPI_TRANSACTION
78 spiBusTransactionBegin(&sdcard
.busdev
);
80 IOLo(sdcard
.busdev
.busdev_u
.spi
.csnPin
);
84 static void sdcard_deselect(void)
86 // As per the SD-card spec, give the card 8 dummy clocks so it can finish its operation
87 //spiBusTransferByte(&sdcard.busdev, 0xFF);
89 while (spiBusIsBusBusy(&sdcard
.busdev
)) {
92 delayMicroseconds(10);
93 #ifdef USE_SPI_TRANSACTION
94 spiBusTransactionEnd(&sdcard
.busdev
);
96 IOHi(sdcard
.busdev
.busdev_u
.spi
.csnPin
);
101 * Handle a failure of an SD card operation by resetting the card back to its initialization phase.
103 * Increments the failure counter, and when the failure threshold is reached, disables the card until
104 * the next call to sdcard_init().
106 static void sdcard_reset(void)
108 if (!sdcard_isInserted()) {
109 sdcard
.state
= SDCARD_STATE_NOT_PRESENT
;
113 if (sdcard
.state
>= SDCARD_STATE_READY
) {
114 #ifdef USE_SPI_TRANSACTION
115 spiBusTransactionInit(&sdcard
.busdev
, SDCARD_SPI_MODE
, spiCalculateDivider(SDCARD_MAX_SPI_INIT_CLK_HZ
));
117 spiSetDivisor(sdcard
.busdev
.busdev_u
.spi
.instance
, spiCalculateDivider(SDCARD_MAX_SPI_INIT_CLK_HZ
));
121 sdcard
.failureCount
++;
122 if (sdcard
.failureCount
>= SDCARD_MAX_CONSECUTIVE_FAILURES
) {
123 sdcard
.state
= SDCARD_STATE_NOT_PRESENT
;
125 sdcard
.operationStartTime
= millis();
126 sdcard
.state
= SDCARD_STATE_RESET
;
131 * The SD card spec requires 8 clock cycles to be sent by us on the bus after most commands so it can finish its
132 * processing of that command. The easiest way for us to do this is to just wait for the bus to become idle before
133 * we transmit a command, sending at least 8-bits onto the bus when we do so.
135 static bool sdcard_waitForIdle(int maxBytesToWait
)
137 while (maxBytesToWait
> 0) {
138 uint8_t b
= spiBusTransferByte(&sdcard
.busdev
, 0xFF);
149 * Wait for up to maxDelay 0xFF idle bytes to arrive from the card, returning the first non-idle byte found.
151 * Returns 0xFF on failure.
153 static uint8_t sdcard_waitForNonIdleByte(int maxDelay
)
155 for (int i
= 0; i
< maxDelay
+ 1; i
++) { // + 1 so we can wait for maxDelay '0xFF' bytes before reading a response byte afterwards
156 uint8_t response
= spiBusTransferByte(&sdcard
.busdev
, 0xFF);
158 if (response
!= 0xFF) {
167 * Waits up to SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY bytes for the card to become ready, send a command to the card
168 * with the given argument, waits up to SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY bytes for a reply, and returns the
169 * first non-0xFF byte of the reply.
171 * You must select the card first with sdcard_select() and deselect it afterwards with sdcard_deselect().
173 * Upon failure, 0xFF is returned.
175 static uint8_t sdcard_sendCommand(uint8_t commandCode
, uint32_t commandArgument
)
177 const uint8_t command
[6] = {
179 commandArgument
>> 24,
180 commandArgument
>> 16,
181 commandArgument
>> 8,
183 0x95 /* Static CRC. This CRC is valid for CMD0 with a 0 argument, and CMD8 with 0x1AB argument, which are the only
184 commands that require a CRC */
187 // Go ahead and send the command even if the card isn't idle if this is the reset command
188 if (!sdcard_waitForIdle(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY
) && commandCode
!= SDCARD_COMMAND_GO_IDLE_STATE
)
191 spiBusRawTransfer(&sdcard
.busdev
, command
, NULL
, sizeof(command
));
194 * The card can take up to SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY bytes to send the response, in the meantime
195 * it'll transmit 0xFF filler bytes.
197 return sdcard_waitForNonIdleByte(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY
);
200 static uint8_t sdcard_sendAppCommand(uint8_t commandCode
, uint32_t commandArgument
)
202 sdcard_sendCommand(SDCARD_COMMAND_APP_CMD
, 0);
204 return sdcard_sendCommand(commandCode
, commandArgument
);
208 * Sends an IF_COND message to the card to check its version and validate its voltage requirements. Sets the global
209 * sdCardVersion with the detected version (0, 1, or 2) and returns true if the card is compatible.
211 static bool sdcard_validateInterfaceCondition(void)
213 uint8_t ifCondReply
[4];
219 uint8_t status
= sdcard_sendCommand(SDCARD_COMMAND_SEND_IF_COND
, (SDCARD_VOLTAGE_ACCEPTED_2_7_to_3_6
<< 8) | SDCARD_IF_COND_CHECK_PATTERN
);
221 // Don't deselect the card right away, because we'll want to read the rest of its reply if it's a V2 card
223 if (status
== (SDCARD_R1_STATUS_BIT_ILLEGAL_COMMAND
| SDCARD_R1_STATUS_BIT_IDLE
)) {
224 // V1 cards don't support this command
226 } else if (status
== SDCARD_R1_STATUS_BIT_IDLE
) {
227 spiBusRawTransfer(&sdcard
.busdev
, NULL
, ifCondReply
, sizeof(ifCondReply
));
230 * We don't bother to validate the SDCard's operating voltage range since the spec requires it to accept our
231 * 3.3V, but do check that it echoed back our check pattern properly.
233 if (ifCondReply
[3] == SDCARD_IF_COND_CHECK_PATTERN
) {
240 return sdcard
.version
> 0;
243 static bool sdcard_readOCRRegister(uint32_t *result
)
247 uint8_t status
= sdcard_sendCommand(SDCARD_COMMAND_READ_OCR
, 0);
251 spiBusRawTransfer(&sdcard
.busdev
, NULL
, response
, sizeof(response
));
256 *result
= (response
[0] << 24) | (response
[1] << 16) | (response
[2] << 8) | response
[3];
267 SDCARD_RECEIVE_SUCCESS
,
268 SDCARD_RECEIVE_BLOCK_IN_PROGRESS
,
270 } sdcardReceiveBlockStatus_e
;
273 * Attempt to receive a data block from the SD card.
275 * Return true on success, otherwise the card has not responded yet and you should retry later.
277 static sdcardReceiveBlockStatus_e
sdcard_receiveDataBlock(uint8_t *buffer
, int count
)
279 uint8_t dataToken
= sdcard_waitForNonIdleByte(8);
281 if (dataToken
== 0xFF) {
282 return SDCARD_RECEIVE_BLOCK_IN_PROGRESS
;
285 if (dataToken
!= SDCARD_SINGLE_BLOCK_READ_START_TOKEN
) {
286 return SDCARD_RECEIVE_ERROR
;
289 spiBusRawTransfer(&sdcard
.busdev
, NULL
, buffer
, count
);
291 // Discard trailing CRC, we don't care
292 spiBusTransferByte(&sdcard
.busdev
, 0xFF);
293 spiBusTransferByte(&sdcard
.busdev
, 0xFF);
295 return SDCARD_RECEIVE_SUCCESS
;
298 static bool sdcard_sendDataBlockFinish(void)
300 #ifdef USE_HAL_DRIVER
301 // Drain anything left in the Rx FIFO (we didn't read it during the write)
302 //This is necessary here as when using msc there is timing issue
303 while (LL_SPI_IsActiveFlag_RXNE(sdcard
.busdev
.busdev_u
.spi
.instance
)) {
304 sdcard
.busdev
.busdev_u
.spi
.instance
->DR
;
309 spiBusTransferByte(&sdcard
.busdev
, 0x00);
310 spiBusTransferByte(&sdcard
.busdev
, 0x00);
312 uint8_t dataResponseToken
= spiBusTransferByte(&sdcard
.busdev
, 0xFF);
315 * Check if the card accepted the write (no CRC error / no address error)
317 * The lower 5 bits are structured as follows:
322 * 010 - Data accepted
326 return (dataResponseToken
& 0x1F) == 0x05;
330 * Begin sending a buffer of SDCARD_BLOCK_SIZE bytes to the SD card.
332 static void sdcard_sendDataBlockBegin(const uint8_t *buffer
, bool multiBlockWrite
)
334 // Card wants 8 dummy clock cycles between the write command's response and a data block beginning:
335 spiBusTransferByte(&sdcard
.busdev
, 0xFF);
337 spiBusTransferByte(&sdcard
.busdev
, multiBlockWrite
? SDCARD_MULTIPLE_BLOCK_WRITE_START_TOKEN
: SDCARD_SINGLE_BLOCK_WRITE_START_TOKEN
);
339 if (sdcard
.useDMAForTx
) {
340 #if defined(USE_HAL_DRIVER)
341 LL_DMA_InitTypeDef init
;
343 LL_DMA_StructInit(&init
);
345 init
.Channel
= dmaGetChannel(sdcard
.dmaChannel
);
346 init
.Mode
= LL_DMA_MODE_NORMAL
;
347 init
.Direction
= LL_DMA_DIRECTION_MEMORY_TO_PERIPH
;
349 init
.PeriphOrM2MSrcAddress
= (uint32_t)&sdcard
.busdev
.busdev_u
.spi
.instance
->DR
;
350 init
.Priority
= LL_DMA_PRIORITY_LOW
;
351 init
.PeriphOrM2MSrcIncMode
= LL_DMA_PERIPH_NOINCREMENT
;
352 init
.PeriphOrM2MSrcDataSize
= LL_DMA_PDATAALIGN_BYTE
;
354 init
.MemoryOrM2MDstAddress
= (uint32_t)buffer
;
355 init
.MemoryOrM2MDstIncMode
= LL_DMA_MEMORY_INCREMENT
;
356 init
.MemoryOrM2MDstDataSize
= LL_DMA_MDATAALIGN_BYTE
;
358 init
.NbData
= SDCARD_BLOCK_SIZE
;
360 LL_DMA_DeInit(sdcard
.dma
->dma
, sdcard
.dma
->stream
);
361 LL_DMA_Init(sdcard
.dma
->dma
, sdcard
.dma
->stream
, &init
);
363 LL_DMA_EnableStream(sdcard
.dma
->dma
, sdcard
.dma
->stream
);
365 LL_SPI_EnableDMAReq_TX(sdcard
.busdev
.busdev_u
.spi
.instance
);
369 DMA_InitTypeDef init
;
371 DMA_StructInit(&init
);
373 init
.DMA_Channel
= dmaGetChannel(sdcard
.dmaChannel
);
374 init
.DMA_Memory0BaseAddr
= (uint32_t) buffer
;
375 init
.DMA_DIR
= DMA_DIR_MemoryToPeripheral
;
377 init
.DMA_M2M
= DMA_M2M_Disable
;
378 init
.DMA_MemoryBaseAddr
= (uint32_t) buffer
;
379 init
.DMA_DIR
= DMA_DIR_PeripheralDST
;
381 init
.DMA_PeripheralBaseAddr
= (uint32_t) &sdcard
.busdev
.busdev_u
.spi
.instance
->DR
;
382 init
.DMA_Priority
= DMA_Priority_Low
;
383 init
.DMA_PeripheralInc
= DMA_PeripheralInc_Disable
;
384 init
.DMA_PeripheralDataSize
= DMA_PeripheralDataSize_Byte
;
386 init
.DMA_MemoryInc
= DMA_MemoryInc_Enable
;
387 init
.DMA_MemoryDataSize
= DMA_MemoryDataSize_Byte
;
389 init
.DMA_BufferSize
= SDCARD_BLOCK_SIZE
;
390 init
.DMA_Mode
= DMA_Mode_Normal
;
392 xDMA_DeInit(sdcard
.dma
->ref
);
393 xDMA_Init(sdcard
.dma
->ref
, &init
);
395 xDMA_Cmd(sdcard
.dma
->ref
, ENABLE
);
397 SPI_I2S_DMACmd(sdcard
.busdev
.busdev_u
.spi
.instance
, SPI_I2S_DMAReq_Tx
, ENABLE
);
400 // Send the first chunk now
401 spiBusRawTransfer(&sdcard
.busdev
, buffer
, NULL
, SDCARD_NON_DMA_CHUNK_SIZE
);
405 static bool sdcard_receiveCID(void)
409 if (sdcard_receiveDataBlock(cid
, sizeof(cid
)) != SDCARD_RECEIVE_SUCCESS
) {
413 sdcard
.metadata
.manufacturerID
= cid
[0];
414 sdcard
.metadata
.oemID
= (cid
[1] << 8) | cid
[2];
415 sdcard
.metadata
.productName
[0] = cid
[3];
416 sdcard
.metadata
.productName
[1] = cid
[4];
417 sdcard
.metadata
.productName
[2] = cid
[5];
418 sdcard
.metadata
.productName
[3] = cid
[6];
419 sdcard
.metadata
.productName
[4] = cid
[7];
420 sdcard
.metadata
.productRevisionMajor
= cid
[8] >> 4;
421 sdcard
.metadata
.productRevisionMinor
= cid
[8] & 0x0F;
422 sdcard
.metadata
.productSerial
= (cid
[9] << 24) | (cid
[10] << 16) | (cid
[11] << 8) | cid
[12];
423 sdcard
.metadata
.productionYear
= (((cid
[13] & 0x0F) << 4) | (cid
[14] >> 4)) + 2000;
424 sdcard
.metadata
.productionMonth
= cid
[14] & 0x0F;
429 static bool sdcard_fetchCSD(void)
431 uint32_t readBlockLen
, blockCount
, blockCountMult
;
432 uint64_t capacityBytes
;
436 /* The CSD command's data block should always arrive within 8 idle clock cycles (SD card spec). This is because
437 * the information about card latency is stored in the CSD register itself, so we can't use that yet!
440 sdcard_sendCommand(SDCARD_COMMAND_SEND_CSD
, 0) == 0
441 && sdcard_receiveDataBlock((uint8_t*) &sdcard
.csd
, sizeof(sdcard
.csd
)) == SDCARD_RECEIVE_SUCCESS
442 && SDCARD_GET_CSD_FIELD(sdcard
.csd
, 1, TRAILER
) == 1;
445 switch (SDCARD_GET_CSD_FIELD(sdcard
.csd
, 1, CSD_STRUCTURE_VER
)) {
446 case SDCARD_CSD_STRUCTURE_VERSION_1
:
447 // Block size in bytes (doesn't have to be 512)
448 readBlockLen
= 1 << SDCARD_GET_CSD_FIELD(sdcard
.csd
, 1, READ_BLOCK_LEN
);
449 blockCountMult
= 1 << (SDCARD_GET_CSD_FIELD(sdcard
.csd
, 1, CSIZE_MULT
) + 2);
450 blockCount
= (SDCARD_GET_CSD_FIELD(sdcard
.csd
, 1, CSIZE
) + 1) * blockCountMult
;
452 // We could do this in 32 bits but it makes the 2GB case awkward
453 capacityBytes
= (uint64_t) blockCount
* readBlockLen
;
455 // Re-express that capacity (max 2GB) in our standard 512-byte block size
456 sdcard
.metadata
.numBlocks
= capacityBytes
/ SDCARD_BLOCK_SIZE
;
458 case SDCARD_CSD_STRUCTURE_VERSION_2
:
459 sdcard
.metadata
.numBlocks
= (SDCARD_GET_CSD_FIELD(sdcard
.csd
, 2, CSIZE
) + 1) * 1024;
472 * Check if the SD Card has completed its startup sequence. Must be called with sdcard.state == SDCARD_STATE_INITIALIZATION.
474 * Returns true if the card has finished its init process.
476 static bool sdcard_checkInitDone(void)
480 uint8_t status
= sdcard_sendAppCommand(SDCARD_ACOMMAND_SEND_OP_COND
, sdcard
.version
== 2 ? 1 << 30 /* We support high capacity cards */ : 0);
484 // When card init is complete, the idle bit in the response becomes zero.
485 return status
== 0x00;
488 void sdcardSpi_preInit(const sdcardConfig_t
*config
)
490 spiPreinitRegister(config
->chipSelectTag
, IOCFG_IPU
, 1);
494 * Begin the initialization process for the SD card. This must be called first before any other sdcard_ routine.
496 static void sdcardSpi_init(const sdcardConfig_t
*config
, const spiPinConfig_t
*spiConfig
)
502 sdcard
.enabled
= config
->mode
;
503 if (!sdcard
.enabled
) {
504 sdcard
.state
= SDCARD_STATE_NOT_PRESENT
;
508 SPIDevice spiDevice
= SPI_CFG_TO_DEV(config
->device
);
510 spiBusSetInstance(&sdcard
.busdev
, spiInstanceByDevice(spiDevice
));
512 if (config
->useDma
) {
513 dmaIdentifier_e dmaIdentifier
= DMA_NONE
;
516 const dmaChannelSpec_t
*dmaChannelSpec
= dmaGetChannelSpecByPeripheral(DMA_PERIPH_SPI_TX
, config
->device
, spiConfig
[spiDevice
].txDmaopt
);
518 if (dmaChannelSpec
) {
519 dmaIdentifier
= dmaGetIdentifier(dmaChannelSpec
->ref
);
520 sdcard
.dmaChannel
= dmaChannelSpec
->channel
; // XXX STM32F3 doesn't have this
523 dmaIdentifier
= config
->dmaIdentifier
;
527 sdcard
.dma
= dmaGetDescriptorByIdentifier(dmaIdentifier
);
528 dmaInit(dmaIdentifier
, OWNER_SDCARD
, 0);
529 sdcard
.useDMAForTx
= true;
531 sdcard
.useDMAForTx
= false;
536 if (config
->chipSelectTag
) {
537 chipSelectIO
= IOGetByTag(config
->chipSelectTag
);
538 IOInit(chipSelectIO
, OWNER_SDCARD_CS
, 0);
539 IOConfigGPIO(chipSelectIO
, SPI_IO_CS_CFG
);
541 chipSelectIO
= IO_NONE
;
543 sdcard
.busdev
.busdev_u
.spi
.csnPin
= chipSelectIO
;
545 // Max frequency is initially 400kHz
547 #ifdef USE_SPI_TRANSACTION
548 spiBusTransactionInit(&sdcard
.busdev
, SDCARD_SPI_MODE
, spiCalculateDivider(SDCARD_MAX_SPI_INIT_CLK_HZ
));
550 spiSetDivisor(sdcard
.busdev
.busdev_u
.spi
.instance
, spiCalculateDivider(SDCARD_MAX_SPI_INIT_CLK_HZ
));
553 // SDCard wants 1ms minimum delay after power is applied to it
556 // Transmit at least 74 dummy clock cycles with CS high so the SD card can start up
557 IOHi(sdcard
.busdev
.busdev_u
.spi
.csnPin
);
558 spiBusRawTransfer(&sdcard
.busdev
, NULL
, NULL
, SDCARD_INIT_NUM_DUMMY_BYTES
);
560 // Wait for that transmission to finish before we enable the SDCard, so it receives the required number of cycles:
562 while (spiBusIsBusBusy(&sdcard
.busdev
)) {
564 sdcard
.state
= SDCARD_STATE_NOT_PRESENT
;
565 sdcard
.failureCount
++;
570 sdcard
.operationStartTime
= millis();
571 sdcard
.state
= SDCARD_STATE_RESET
;
572 sdcard
.failureCount
= 0;
575 static bool sdcard_setBlockLength(uint32_t blockLen
)
579 uint8_t status
= sdcard_sendCommand(SDCARD_COMMAND_SET_BLOCKLEN
, blockLen
);
587 * Returns true if the card is ready to accept read/write commands.
589 static bool sdcard_isReady(void)
591 return sdcard
.state
== SDCARD_STATE_READY
|| sdcard
.state
== SDCARD_STATE_WRITING_MULTIPLE_BLOCKS
;
595 * Send the stop-transmission token to complete a multi-block write.
598 * SDCARD_OPERATION_IN_PROGRESS - We're now waiting for that stop to complete, the card will enter
599 * the SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE state.
600 * SDCARD_OPERATION_SUCCESS - The multi-block write finished immediately, the card will enter
601 * the SDCARD_READY state.
604 static sdcardOperationStatus_e
sdcard_endWriteBlocks(void)
606 sdcard
.multiWriteBlocksRemain
= 0;
608 // 8 dummy clocks to guarantee N_WR clocks between the last card response and this token
609 spiBusTransferByte(&sdcard
.busdev
, 0xFF);
611 spiBusTransferByte(&sdcard
.busdev
, SDCARD_MULTIPLE_BLOCK_WRITE_STOP_TOKEN
);
613 // Card may choose to raise a busy (non-0xFF) signal after at most N_BR (1 byte) delay
614 if (sdcard_waitForNonIdleByte(1) == 0xFF) {
615 sdcard
.state
= SDCARD_STATE_READY
;
616 return SDCARD_OPERATION_SUCCESS
;
618 sdcard
.state
= SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE
;
619 sdcard
.operationStartTime
= millis();
621 return SDCARD_OPERATION_IN_PROGRESS
;
626 * Call periodically for the SD card to perform in-progress transfers.
628 * Returns true if the card is ready to accept commands.
630 static bool sdcardSpi_poll(void)
632 if (!sdcard
.enabled
) {
633 sdcard
.state
= SDCARD_STATE_NOT_PRESENT
;
640 #ifdef SDCARD_PROFILING
641 bool profilingComplete
;
645 switch (sdcard
.state
) {
646 case SDCARD_STATE_RESET
:
649 initStatus
= sdcard_sendCommand(SDCARD_COMMAND_GO_IDLE_STATE
, 0);
653 if (initStatus
== SDCARD_R1_STATUS_BIT_IDLE
) {
654 // Check card voltage and version
655 if (sdcard_validateInterfaceCondition()) {
657 sdcard
.state
= SDCARD_STATE_CARD_INIT_IN_PROGRESS
;
660 // Bad reply/voltage, we ought to refrain from accessing the card.
661 sdcard
.state
= SDCARD_STATE_NOT_PRESENT
;
666 case SDCARD_STATE_CARD_INIT_IN_PROGRESS
:
667 if (sdcard_checkInitDone()) {
668 if (sdcard
.version
== 2) {
669 // Check for high capacity card
672 if (!sdcard_readOCRRegister(&ocr
)) {
677 sdcard
.highCapacity
= (ocr
& (1 << 30)) != 0;
679 // Version 1 cards are always low-capacity
680 sdcard
.highCapacity
= false;
683 // Now fetch the CSD and CID registers
684 if (sdcard_fetchCSD()) {
687 uint8_t status
= sdcard_sendCommand(SDCARD_COMMAND_SEND_CID
, 0);
690 // Keep the card selected to receive the response block
691 sdcard
.state
= SDCARD_STATE_INITIALIZATION_RECEIVE_CID
;
702 case SDCARD_STATE_INITIALIZATION_RECEIVE_CID
:
703 if (sdcard_receiveCID()) {
706 /* The spec is a little iffy on what the default block size is for Standard Size cards (it can be changed on
707 * standard size cards) so let's just set it to 512 explicitly so we don't have a problem.
709 if (!sdcard
.highCapacity
&& !sdcard_setBlockLength(SDCARD_BLOCK_SIZE
)) {
714 // Now we're done with init and we can switch to the full speed clock (<25MHz)
716 #ifdef USE_SPI_TRANSACTION
717 spiBusTransactionInit(&sdcard
.busdev
, SDCARD_SPI_MODE
, spiCalculateDivider(SDCARD_MAX_SPI_CLK_HZ
));
719 spiSetDivisor(sdcard
.busdev
.busdev_u
.spi
.instance
, spiCalculateDivider(SDCARD_MAX_SPI_CLK_HZ
));
722 sdcard
.multiWriteBlocksRemain
= 0;
724 sdcard
.state
= SDCARD_STATE_READY
;
726 } // else keep waiting for the CID to arrive
728 case SDCARD_STATE_SENDING_WRITE
:
729 // Have we finished sending the write yet?
730 sendComplete
= false;
732 #if defined(USE_HAL_DRIVER)
733 if (sdcard
.useDMAForTx
&& DMA_GET_FLAG_STATUS(sdcard
.dma
, DMA_IT_TCIF
)) {
734 //Clear both flags after transfer
735 DMA_CLEAR_FLAG(sdcard
.dma
, DMA_IT_TCIF
);
736 DMA_CLEAR_FLAG(sdcard
.dma
, DMA_IT_HTIF
);
737 // Drain anything left in the Rx FIFO (we didn't read it during the write)
738 while (LL_SPI_IsActiveFlag_RXNE(sdcard
.busdev
.busdev_u
.spi
.instance
)) {
739 sdcard
.busdev
.busdev_u
.spi
.instance
->DR
;
742 // Wait for the final bit to be transmitted
743 while (spiBusIsBusBusy(&sdcard
.busdev
)) {
746 LL_SPI_DisableDMAReq_TX(sdcard
.busdev
.busdev_u
.spi
.instance
);
752 if (sdcard
.useDMAForTx
&& xDMA_GetFlagStatus(sdcard
.dma
->ref
, sdcard
.dma
->completeFlag
) == SET
) {
753 xDMA_ClearFlag(sdcard
.dma
->ref
, sdcard
.dma
->completeFlag
);
755 if (sdcard
.useDMAForTx
&& DMA_GetFlagStatus(sdcard
.dma
->completeFlag
) == SET
) {
756 DMA_ClearFlag(sdcard
.dma
->completeFlag
);
759 xDMA_Cmd(sdcard
.dma
->ref
, DISABLE
);
761 // Drain anything left in the Rx FIFO (we didn't read it during the write)
762 while (SPI_I2S_GetFlagStatus(sdcard
.busdev
.busdev_u
.spi
.instance
, SPI_I2S_FLAG_RXNE
) == SET
) {
763 sdcard
.busdev
.busdev_u
.spi
.instance
->DR
;
766 // Wait for the final bit to be transmitted
767 while (spiBusIsBusBusy(&sdcard
.busdev
)) {
770 SPI_I2S_DMACmd(sdcard
.busdev
.busdev_u
.spi
.instance
, SPI_I2S_DMAReq_Tx
, DISABLE
);
775 if (!sdcard
.useDMAForTx
) {
776 // Send another chunk
777 spiBusRawTransfer(&sdcard
.busdev
, sdcard
.pendingOperation
.buffer
+ SDCARD_NON_DMA_CHUNK_SIZE
* sdcard
.pendingOperation
.chunkIndex
, NULL
, SDCARD_NON_DMA_CHUNK_SIZE
);
779 sdcard
.pendingOperation
.chunkIndex
++;
781 sendComplete
= sdcard
.pendingOperation
.chunkIndex
== SDCARD_BLOCK_SIZE
/ SDCARD_NON_DMA_CHUNK_SIZE
;
785 // Finish up by sending the CRC and checking the SD-card's acceptance/rejectance
786 if (sdcard_sendDataBlockFinish()) {
787 // The SD card is now busy committing that write to the card
788 sdcard
.state
= SDCARD_STATE_WAITING_FOR_WRITE
;
789 sdcard
.operationStartTime
= millis();
791 // Since we've transmitted the buffer we can go ahead and tell the caller their operation is complete
792 if (sdcard
.pendingOperation
.callback
) {
793 sdcard
.pendingOperation
.callback(SDCARD_BLOCK_OPERATION_WRITE
, sdcard
.pendingOperation
.blockIndex
, sdcard
.pendingOperation
.buffer
, sdcard
.pendingOperation
.callbackData
);
796 /* Our write was rejected! This could be due to a bad address but we hope not to attempt that, so assume
797 * the card is broken and needs reset.
801 // Announce write failure:
802 if (sdcard
.pendingOperation
.callback
) {
803 sdcard
.pendingOperation
.callback(SDCARD_BLOCK_OPERATION_WRITE
, sdcard
.pendingOperation
.blockIndex
, NULL
, sdcard
.pendingOperation
.callbackData
);
810 case SDCARD_STATE_WAITING_FOR_WRITE
:
811 if (sdcard_waitForIdle(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY
)) {
812 #ifdef SDCARD_PROFILING
813 profilingComplete
= true;
816 sdcard
.failureCount
= 0; // Assume the card is good if it can complete a write
818 // Still more blocks left to write in a multi-block chain?
819 if (sdcard
.multiWriteBlocksRemain
> 1) {
820 sdcard
.multiWriteBlocksRemain
--;
821 sdcard
.multiWriteNextBlock
++;
822 sdcard
.state
= SDCARD_STATE_WRITING_MULTIPLE_BLOCKS
;
823 } else if (sdcard
.multiWriteBlocksRemain
== 1) {
824 // This function changes the sd card state for us whether immediately succesful or delayed:
825 if (sdcard_endWriteBlocks() == SDCARD_OPERATION_SUCCESS
) {
828 #ifdef SDCARD_PROFILING
829 // Wait for the multi-block write to be terminated before finishing timing
830 profilingComplete
= false;
834 sdcard
.state
= SDCARD_STATE_READY
;
838 #ifdef SDCARD_PROFILING
839 if (profilingComplete
&& sdcard
.profiler
) {
840 sdcard
.profiler(SDCARD_BLOCK_OPERATION_WRITE
, sdcard
.pendingOperation
.blockIndex
, micros() - sdcard
.pendingOperation
.profileStartTime
);
843 } else if (millis() > sdcard
.operationStartTime
+ SDCARD_TIMEOUT_WRITE_MSEC
) {
845 * The caller has already been told that their write has completed, so they will have discarded
846 * their buffer and have no hope of retrying the operation. But this should be very rare and it allows
847 * them to reuse their buffer milliseconds faster than they otherwise would.
853 case SDCARD_STATE_READING
:
854 switch (sdcard_receiveDataBlock(sdcard
.pendingOperation
.buffer
, SDCARD_BLOCK_SIZE
)) {
855 case SDCARD_RECEIVE_SUCCESS
:
858 sdcard
.state
= SDCARD_STATE_READY
;
859 sdcard
.failureCount
= 0; // Assume the card is good if it can complete a read
861 #ifdef SDCARD_PROFILING
862 if (sdcard
.profiler
) {
863 sdcard
.profiler(SDCARD_BLOCK_OPERATION_READ
, sdcard
.pendingOperation
.blockIndex
, micros() - sdcard
.pendingOperation
.profileStartTime
);
867 if (sdcard
.pendingOperation
.callback
) {
868 sdcard
.pendingOperation
.callback(
869 SDCARD_BLOCK_OPERATION_READ
,
870 sdcard
.pendingOperation
.blockIndex
,
871 sdcard
.pendingOperation
.buffer
,
872 sdcard
.pendingOperation
.callbackData
876 case SDCARD_RECEIVE_BLOCK_IN_PROGRESS
:
877 if (millis() <= sdcard
.operationStartTime
+ SDCARD_TIMEOUT_READ_MSEC
) {
878 break; // Timeout not reached yet so keep waiting
880 // Timeout has expired, so fall through to convert to a fatal error
883 case SDCARD_RECEIVE_ERROR
:
888 if (sdcard
.pendingOperation
.callback
) {
889 sdcard
.pendingOperation
.callback(
890 SDCARD_BLOCK_OPERATION_READ
,
891 sdcard
.pendingOperation
.blockIndex
,
893 sdcard
.pendingOperation
.callbackData
901 case SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE
:
902 if (sdcard_waitForIdle(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY
)) {
905 sdcard
.state
= SDCARD_STATE_READY
;
907 #ifdef SDCARD_PROFILING
908 if (sdcard
.profiler
) {
909 sdcard
.profiler(SDCARD_BLOCK_OPERATION_WRITE
, sdcard
.pendingOperation
.blockIndex
, micros() - sdcard
.pendingOperation
.profileStartTime
);
912 } else if (millis() > sdcard
.operationStartTime
+ SDCARD_TIMEOUT_WRITE_MSEC
) {
917 case SDCARD_STATE_NOT_PRESENT
:
922 // Is the card's initialization taking too long?
923 if (sdcard
.state
>= SDCARD_STATE_RESET
&& sdcard
.state
< SDCARD_STATE_READY
924 && millis() - sdcard
.operationStartTime
> SDCARD_TIMEOUT_INIT_MILLIS
) {
928 return sdcard_isReady();
932 * Write the 512-byte block from the given buffer into the block with the given index.
934 * If the write does not complete immediately, your callback will be called later. If the write was successful, the
935 * buffer pointer will be the same buffer you originally passed in, otherwise the buffer will be set to NULL.
938 * SDCARD_OPERATION_IN_PROGRESS - Your buffer is currently being transmitted to the card and your callback will be
939 * called later to report the completion. The buffer pointer must remain valid until
941 * SDCARD_OPERATION_SUCCESS - Your buffer has been transmitted to the card now.
942 * SDCARD_OPERATION_BUSY - The card is already busy and cannot accept your write
943 * SDCARD_OPERATION_FAILURE - Your write was rejected by the card, card will be reset
945 static sdcardOperationStatus_e
sdcardSpi_writeBlock(uint32_t blockIndex
, uint8_t *buffer
, sdcard_operationCompleteCallback_c callback
, uint32_t callbackData
)
949 #ifdef SDCARD_PROFILING
950 sdcard
.pendingOperation
.profileStartTime
= micros();
954 switch (sdcard
.state
) {
955 case SDCARD_STATE_WRITING_MULTIPLE_BLOCKS
:
956 // Do we need to cancel the previous multi-block write?
957 if (blockIndex
!= sdcard
.multiWriteNextBlock
) {
958 if (sdcard_endWriteBlocks() == SDCARD_OPERATION_SUCCESS
) {
959 // Now we've entered the ready state, we can try again
962 return SDCARD_OPERATION_BUSY
;
966 // We're continuing a multi-block write
968 case SDCARD_STATE_READY
:
969 // We're not continuing a multi-block write so we need to send a single-block write command
972 // Standard size cards use byte addressing, high capacity cards use block addressing
973 status
= sdcard_sendCommand(SDCARD_COMMAND_WRITE_BLOCK
, sdcard
.highCapacity
? blockIndex
: blockIndex
* SDCARD_BLOCK_SIZE
);
980 return SDCARD_OPERATION_FAILURE
;
984 return SDCARD_OPERATION_BUSY
;
987 sdcard_sendDataBlockBegin(buffer
, sdcard
.state
== SDCARD_STATE_WRITING_MULTIPLE_BLOCKS
);
989 sdcard
.pendingOperation
.buffer
= buffer
;
990 sdcard
.pendingOperation
.blockIndex
= blockIndex
;
991 sdcard
.pendingOperation
.callback
= callback
;
992 sdcard
.pendingOperation
.callbackData
= callbackData
;
993 sdcard
.pendingOperation
.chunkIndex
= 1; // (for non-DMA transfers) we've sent chunk #0 already
994 sdcard
.state
= SDCARD_STATE_SENDING_WRITE
;
996 return SDCARD_OPERATION_IN_PROGRESS
;
1000 * Begin writing a series of consecutive blocks beginning at the given block index. This will allow (but not require)
1001 * the SD card to pre-erase the number of blocks you specifiy, which can allow the writes to complete faster.
1003 * Afterwards, just call sdcard_writeBlock() as normal to write those blocks consecutively.
1005 * It's okay to abort the multi-block write at any time by writing to a non-consecutive address, or by performing a read.
1008 * SDCARD_OPERATION_SUCCESS - Multi-block write has been queued
1009 * SDCARD_OPERATION_BUSY - The card is already busy and cannot accept your write
1010 * SDCARD_OPERATION_FAILURE - A fatal error occured, card will be reset
1012 static sdcardOperationStatus_e
sdcardSpi_beginWriteBlocks(uint32_t blockIndex
, uint32_t blockCount
)
1014 if (sdcard
.state
!= SDCARD_STATE_READY
) {
1015 if (sdcard
.state
== SDCARD_STATE_WRITING_MULTIPLE_BLOCKS
) {
1016 if (blockIndex
== sdcard
.multiWriteNextBlock
) {
1017 // Assume that the caller wants to continue the multi-block write they already have in progress!
1018 return SDCARD_OPERATION_SUCCESS
;
1019 } else if (sdcard_endWriteBlocks() != SDCARD_OPERATION_SUCCESS
) {
1020 return SDCARD_OPERATION_BUSY
;
1021 } // Else we've completed the previous multi-block write and can fall through to start the new one
1023 return SDCARD_OPERATION_BUSY
;
1030 sdcard_sendAppCommand(SDCARD_ACOMMAND_SET_WR_BLOCK_ERASE_COUNT
, blockCount
) == 0
1031 && sdcard_sendCommand(SDCARD_COMMAND_WRITE_MULTIPLE_BLOCK
, sdcard
.highCapacity
? blockIndex
: blockIndex
* SDCARD_BLOCK_SIZE
) == 0
1033 sdcard
.state
= SDCARD_STATE_WRITING_MULTIPLE_BLOCKS
;
1034 sdcard
.multiWriteBlocksRemain
= blockCount
;
1035 sdcard
.multiWriteNextBlock
= blockIndex
;
1037 // Leave the card selected
1038 return SDCARD_OPERATION_SUCCESS
;
1044 return SDCARD_OPERATION_FAILURE
;
1049 * Read the 512-byte block with the given index into the given 512-byte buffer.
1051 * When the read completes, your callback will be called. If the read was successful, the buffer pointer will be the
1052 * same buffer you originally passed in, otherwise the buffer will be set to NULL.
1054 * You must keep the pointer to the buffer valid until the operation completes!
1057 * true - The operation was successfully queued for later completion, your callback will be called later
1058 * false - The operation could not be started due to the card being busy (try again later).
1060 static bool sdcardSpi_readBlock(uint32_t blockIndex
, uint8_t *buffer
, sdcard_operationCompleteCallback_c callback
, uint32_t callbackData
)
1062 if (sdcard
.state
!= SDCARD_STATE_READY
) {
1063 if (sdcard
.state
== SDCARD_STATE_WRITING_MULTIPLE_BLOCKS
) {
1064 if (sdcard_endWriteBlocks() != SDCARD_OPERATION_SUCCESS
) {
1072 #ifdef SDCARD_PROFILING
1073 sdcard
.pendingOperation
.profileStartTime
= micros();
1078 // Standard size cards use byte addressing, high capacity cards use block addressing
1079 uint8_t status
= sdcard_sendCommand(SDCARD_COMMAND_READ_SINGLE_BLOCK
, sdcard
.highCapacity
? blockIndex
: blockIndex
* SDCARD_BLOCK_SIZE
);
1082 sdcard
.pendingOperation
.buffer
= buffer
;
1083 sdcard
.pendingOperation
.blockIndex
= blockIndex
;
1084 sdcard
.pendingOperation
.callback
= callback
;
1085 sdcard
.pendingOperation
.callbackData
= callbackData
;
1087 sdcard
.state
= SDCARD_STATE_READING
;
1089 sdcard
.operationStartTime
= millis();
1091 // Leave the card selected for the whole transaction
1102 * Returns true if the SD card has successfully completed its startup procedures.
1104 static bool sdcardSpi_isInitialized(void)
1106 return sdcard
.state
>= SDCARD_STATE_READY
;
1109 static const sdcardMetadata_t
* sdcardSpi_getMetadata(void)
1111 return &sdcard
.metadata
;
1114 #ifdef SDCARD_PROFILING
1116 static void sdcardSpi_setProfilerCallback(sdcard_profilerCallback_c callback
)
1118 sdcard
.profiler
= callback
;
1123 sdcardVTable_t sdcardSpiVTable
= {
1126 sdcardSpi_readBlock
,
1127 sdcardSpi_beginWriteBlocks
,
1128 sdcardSpi_writeBlock
,
1130 sdcardSpi_isFunctional
,
1131 sdcardSpi_isInitialized
,
1132 sdcardSpi_getMetadata
,
1133 #ifdef SDCARD_PROFILING
1134 sdcardSpi_setProfilerCallback
,