HotFix for sdcard driver on F7 when using DMA for TX (#5595)
[betaflight.git] / src / main / drivers / sdcard.c
blob14c71503caf8a5a35c2a0e9d518a6d04b34027ea
1 /*
2 * This file is part of Cleanflight.
4 * Cleanflight is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * Cleanflight is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with Cleanflight. If not, see <http://www.gnu.org/licenses/>.
18 #include <stdbool.h>
19 #include <stdint.h>
21 #include "platform.h"
23 #ifdef USE_SDCARD
25 #include "drivers/nvic.h"
26 #include "drivers/io.h"
27 #include "dma.h"
29 #include "drivers/bus_spi.h"
30 #include "drivers/time.h"
32 #include "sdcard.h"
33 #include "sdcard_standard.h"
35 #ifdef AFATFS_USE_INTROSPECTIVE_LOGGING
36 #define SDCARD_PROFILING
37 #endif
39 #define SET_CS_HIGH IOHi(sdcard.chipSelectPin)
40 #define SET_CS_LOW IOLo(sdcard.chipSelectPin)
42 #define SDCARD_INIT_NUM_DUMMY_BYTES 10
43 #define SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY 8
44 // Chosen so that CMD8 will have the same CRC as CMD0:
45 #define SDCARD_IF_COND_CHECK_PATTERN 0xAB
47 #define SDCARD_TIMEOUT_INIT_MILLIS 200
48 #define SDCARD_MAX_CONSECUTIVE_FAILURES 8
50 /* Break up 512-byte SD card sectors into chunks of this size when writing without DMA to reduce the peak overhead
51 * per call to sdcard_poll().
53 #define SDCARD_NON_DMA_CHUNK_SIZE 256
55 typedef enum {
56 // In these states we run at the initialization 400kHz clockspeed:
57 SDCARD_STATE_NOT_PRESENT = 0,
58 SDCARD_STATE_RESET,
59 SDCARD_STATE_CARD_INIT_IN_PROGRESS,
60 SDCARD_STATE_INITIALIZATION_RECEIVE_CID,
62 // In these states we run at full clock speed
63 SDCARD_STATE_READY,
64 SDCARD_STATE_READING,
65 SDCARD_STATE_SENDING_WRITE,
66 SDCARD_STATE_WAITING_FOR_WRITE,
67 SDCARD_STATE_WRITING_MULTIPLE_BLOCKS,
68 SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE
69 } sdcardState_e;
71 typedef struct sdcard_t {
72 struct {
73 uint8_t *buffer;
74 uint32_t blockIndex;
75 uint8_t chunkIndex;
77 sdcard_operationCompleteCallback_c callback;
78 uint32_t callbackData;
80 #ifdef SDCARD_PROFILING
81 uint32_t profileStartTime;
82 #endif
83 } pendingOperation;
85 uint32_t operationStartTime;
87 uint8_t failureCount;
89 uint8_t version;
90 bool highCapacity;
92 uint32_t multiWriteNextBlock;
93 uint32_t multiWriteBlocksRemain;
95 sdcardState_e state;
97 sdcardMetadata_t metadata;
98 sdcardCSD_t csd;
100 #ifdef SDCARD_PROFILING
101 sdcard_profilerCallback_c profiler;
102 #endif
103 SPI_TypeDef *instance;
104 bool enabled;
105 bool detectionInverted;
106 bool useDMAForTx;
107 IO_t cardDetectPin;
108 IO_t chipSelectPin;
109 dmaChannelDescriptor_t * dma;
110 uint8_t dmaChannel;
111 } sdcard_t;
113 static sdcard_t sdcard;
115 STATIC_ASSERT(sizeof(sdcardCSD_t) == 16, sdcard_csd_bitfields_didnt_pack_properly);
117 void sdcardInsertionDetectDeinit(void)
119 if (sdcard.cardDetectPin) {
120 IOInit(sdcard.cardDetectPin, OWNER_FREE, 0);
121 IOConfigGPIO(sdcard.cardDetectPin, IOCFG_IN_FLOATING);
125 void sdcardInsertionDetectInit(void)
127 if (sdcard.cardDetectPin) {
128 IOInit(sdcard.cardDetectPin, OWNER_SDCARD_DETECT, 0);
129 IOConfigGPIO(sdcard.cardDetectPin, IOCFG_IPU);
134 * Detect if a SD card is physically present in the memory slot.
136 bool sdcard_isInserted(void)
138 bool result = true;
139 if (sdcard.cardDetectPin) {
140 result = IORead(sdcard.cardDetectPin) != 0;
141 if (sdcard.detectionInverted) {
142 result = !result;
145 return result;
149 * Returns true if the card has already been, or is currently, initializing and hasn't encountered enough errors to
150 * trip our error threshold and be disabled (i.e. our card is in and working!)
152 bool sdcard_isFunctional(void)
154 return sdcard.state != SDCARD_STATE_NOT_PRESENT;
157 static void sdcard_select(void)
159 SET_CS_LOW;
162 static void sdcard_deselect(void)
164 // As per the SD-card spec, give the card 8 dummy clocks so it can finish its operation
165 //spiTransferByte(sdcard.instance, 0xFF);
167 while (spiIsBusBusy(sdcard.instance)) {
170 SET_CS_HIGH;
174 * Handle a failure of an SD card operation by resetting the card back to its initialization phase.
176 * Increments the failure counter, and when the failure threshold is reached, disables the card until
177 * the next call to sdcard_init().
179 static void sdcard_reset(void)
181 if (!sdcard_isInserted()) {
182 sdcard.state = SDCARD_STATE_NOT_PRESENT;
183 return;
186 if (sdcard.state >= SDCARD_STATE_READY) {
187 spiSetDivisor(sdcard.instance, SDCARD_SPI_INITIALIZATION_CLOCK_DIVIDER);
190 sdcard.failureCount++;
191 if (sdcard.failureCount >= SDCARD_MAX_CONSECUTIVE_FAILURES) {
192 sdcard.state = SDCARD_STATE_NOT_PRESENT;
193 } else {
194 sdcard.operationStartTime = millis();
195 sdcard.state = SDCARD_STATE_RESET;
200 * The SD card spec requires 8 clock cycles to be sent by us on the bus after most commands so it can finish its
201 * processing of that command. The easiest way for us to do this is to just wait for the bus to become idle before
202 * we transmit a command, sending at least 8-bits onto the bus when we do so.
204 static bool sdcard_waitForIdle(int maxBytesToWait)
206 while (maxBytesToWait > 0) {
207 uint8_t b = spiTransferByte(sdcard.instance, 0xFF);
208 if (b == 0xFF) {
209 return true;
211 maxBytesToWait--;
214 return false;
218 * Wait for up to maxDelay 0xFF idle bytes to arrive from the card, returning the first non-idle byte found.
220 * Returns 0xFF on failure.
222 static uint8_t sdcard_waitForNonIdleByte(int maxDelay)
224 for (int i = 0; i < maxDelay + 1; i++) { // + 1 so we can wait for maxDelay '0xFF' bytes before reading a response byte afterwards
225 uint8_t response = spiTransferByte(sdcard.instance, 0xFF);
227 if (response != 0xFF) {
228 return response;
232 return 0xFF;
236 * Waits up to SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY bytes for the card to become ready, send a command to the card
237 * with the given argument, waits up to SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY bytes for a reply, and returns the
238 * first non-0xFF byte of the reply.
240 * You must select the card first with sdcard_select() and deselect it afterwards with sdcard_deselect().
242 * Upon failure, 0xFF is returned.
244 static uint8_t sdcard_sendCommand(uint8_t commandCode, uint32_t commandArgument)
246 const uint8_t command[6] = {
247 0x40 | commandCode,
248 commandArgument >> 24,
249 commandArgument >> 16,
250 commandArgument >> 8,
251 commandArgument,
252 0x95 /* Static CRC. This CRC is valid for CMD0 with a 0 argument, and CMD8 with 0x1AB argument, which are the only
253 commands that require a CRC */
256 // Go ahead and send the command even if the card isn't idle if this is the reset command
257 if (!sdcard_waitForIdle(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY) && commandCode != SDCARD_COMMAND_GO_IDLE_STATE)
258 return 0xFF;
260 spiTransfer(sdcard.instance, command, NULL, sizeof(command));
263 * The card can take up to SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY bytes to send the response, in the meantime
264 * it'll transmit 0xFF filler bytes.
266 return sdcard_waitForNonIdleByte(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY);
269 static uint8_t sdcard_sendAppCommand(uint8_t commandCode, uint32_t commandArgument)
271 sdcard_sendCommand(SDCARD_COMMAND_APP_CMD, 0);
273 return sdcard_sendCommand(commandCode, commandArgument);
277 * Sends an IF_COND message to the card to check its version and validate its voltage requirements. Sets the global
278 * sdCardVersion with the detected version (0, 1, or 2) and returns true if the card is compatible.
280 static bool sdcard_validateInterfaceCondition(void)
282 uint8_t ifCondReply[4];
284 sdcard.version = 0;
286 sdcard_select();
288 uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_SEND_IF_COND, (SDCARD_VOLTAGE_ACCEPTED_2_7_to_3_6 << 8) | SDCARD_IF_COND_CHECK_PATTERN);
290 // Don't deselect the card right away, because we'll want to read the rest of its reply if it's a V2 card
292 if (status == (SDCARD_R1_STATUS_BIT_ILLEGAL_COMMAND | SDCARD_R1_STATUS_BIT_IDLE)) {
293 // V1 cards don't support this command
294 sdcard.version = 1;
295 } else if (status == SDCARD_R1_STATUS_BIT_IDLE) {
296 spiTransfer(sdcard.instance, NULL, ifCondReply, sizeof(ifCondReply));
299 * We don't bother to validate the SDCard's operating voltage range since the spec requires it to accept our
300 * 3.3V, but do check that it echoed back our check pattern properly.
302 if (ifCondReply[3] == SDCARD_IF_COND_CHECK_PATTERN) {
303 sdcard.version = 2;
307 sdcard_deselect();
309 return sdcard.version > 0;
312 static bool sdcard_readOCRRegister(uint32_t *result)
314 sdcard_select();
316 uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_READ_OCR, 0);
318 uint8_t response[4];
320 spiTransfer(sdcard.instance, NULL, response, sizeof(response));
322 if (status == 0) {
323 sdcard_deselect();
325 *result = (response[0] << 24) | (response[1] << 16) | (response[2] << 8) | response[3];
327 return true;
328 } else {
329 sdcard_deselect();
331 return false;
335 typedef enum {
336 SDCARD_RECEIVE_SUCCESS,
337 SDCARD_RECEIVE_BLOCK_IN_PROGRESS,
338 SDCARD_RECEIVE_ERROR
339 } sdcardReceiveBlockStatus_e;
342 * Attempt to receive a data block from the SD card.
344 * Return true on success, otherwise the card has not responded yet and you should retry later.
346 static sdcardReceiveBlockStatus_e sdcard_receiveDataBlock(uint8_t *buffer, int count)
348 uint8_t dataToken = sdcard_waitForNonIdleByte(8);
350 if (dataToken == 0xFF) {
351 return SDCARD_RECEIVE_BLOCK_IN_PROGRESS;
354 if (dataToken != SDCARD_SINGLE_BLOCK_READ_START_TOKEN) {
355 return SDCARD_RECEIVE_ERROR;
358 spiTransfer(sdcard.instance, NULL, buffer, count);
360 // Discard trailing CRC, we don't care
361 spiTransferByte(sdcard.instance, 0xFF);
362 spiTransferByte(sdcard.instance, 0xFF);
364 return SDCARD_RECEIVE_SUCCESS;
367 static bool sdcard_sendDataBlockFinish(void)
369 #ifdef USE_HAL_DRIVER
370 // Drain anything left in the Rx FIFO (we didn't read it during the write)
371 //This is necessary here as when using msc there is timing issue
372 while (LL_SPI_IsActiveFlag_RXNE(sdcard.instance)) {
373 sdcard.instance->DR;
375 #endif
377 // Send a dummy CRC
378 spiTransferByte(sdcard.instance, 0x00);
379 spiTransferByte(sdcard.instance, 0x00);
381 uint8_t dataResponseToken = spiTransferByte(sdcard.instance, 0xFF);
384 * Check if the card accepted the write (no CRC error / no address error)
386 * The lower 5 bits are structured as follows:
387 * | 0 | Status | 1 |
388 * | 0 | x x x | 1 |
390 * Statuses:
391 * 010 - Data accepted
392 * 101 - CRC error
393 * 110 - Write error
395 return (dataResponseToken & 0x1F) == 0x05;
399 * Begin sending a buffer of SDCARD_BLOCK_SIZE bytes to the SD card.
401 static void sdcard_sendDataBlockBegin(const uint8_t *buffer, bool multiBlockWrite)
403 // Card wants 8 dummy clock cycles between the write command's response and a data block beginning:
404 spiTransferByte(sdcard.instance, 0xFF);
406 spiTransferByte(sdcard.instance, multiBlockWrite ? SDCARD_MULTIPLE_BLOCK_WRITE_START_TOKEN : SDCARD_SINGLE_BLOCK_WRITE_START_TOKEN);
408 if (sdcard.useDMAForTx) {
409 #if defined(USE_HAL_DRIVER)
410 LL_DMA_InitTypeDef init;
412 LL_DMA_StructInit(&init);
414 init.Channel = dmaGetChannel(sdcard.dmaChannel);
415 init.Mode = LL_DMA_MODE_NORMAL;
416 init.Direction = LL_DMA_DIRECTION_MEMORY_TO_PERIPH;
418 init.PeriphOrM2MSrcAddress = (uint32_t)&sdcard.instance->DR;
419 init.Priority = LL_DMA_PRIORITY_LOW;
420 init.PeriphOrM2MSrcIncMode = LL_DMA_PERIPH_NOINCREMENT;
421 init.PeriphOrM2MSrcDataSize = LL_DMA_PDATAALIGN_BYTE;
423 init.MemoryOrM2MDstAddress = (uint32_t)buffer;
424 init.MemoryOrM2MDstIncMode = LL_DMA_MEMORY_INCREMENT;
425 init.MemoryOrM2MDstDataSize = LL_DMA_MDATAALIGN_BYTE;
427 init.NbData = SDCARD_BLOCK_SIZE;
429 LL_DMA_DeInit(sdcard.dma->dma, sdcard.dma->stream);
430 LL_DMA_Init(sdcard.dma->dma, sdcard.dma->stream, &init);
432 LL_DMA_EnableStream(sdcard.dma->dma, sdcard.dma->stream);
434 LL_SPI_EnableDMAReq_TX(sdcard.instance);
436 #else
438 DMA_InitTypeDef init;
440 DMA_StructInit(&init);
441 #ifdef STM32F4
442 init.DMA_Channel = dmaGetChannel(sdcard.dmaChannel);
443 init.DMA_Memory0BaseAddr = (uint32_t) buffer;
444 init.DMA_DIR = DMA_DIR_MemoryToPeripheral;
445 #else
446 init.DMA_M2M = DMA_M2M_Disable;
447 init.DMA_MemoryBaseAddr = (uint32_t) buffer;
448 init.DMA_DIR = DMA_DIR_PeripheralDST;
449 #endif
450 init.DMA_PeripheralBaseAddr = (uint32_t) &sdcard.instance->DR;
451 init.DMA_Priority = DMA_Priority_Low;
452 init.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
453 init.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;
455 init.DMA_MemoryInc = DMA_MemoryInc_Enable;
456 init.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
458 init.DMA_BufferSize = SDCARD_BLOCK_SIZE;
459 init.DMA_Mode = DMA_Mode_Normal;
461 DMA_DeInit(sdcard.dma->ref);
462 DMA_Init(sdcard.dma->ref, &init);
464 DMA_Cmd(sdcard.dma->ref, ENABLE);
466 SPI_I2S_DMACmd(sdcard.instance, SPI_I2S_DMAReq_Tx, ENABLE);
467 #endif
468 } else {
469 // Send the first chunk now
470 spiTransfer(sdcard.instance, buffer, NULL, SDCARD_NON_DMA_CHUNK_SIZE);
474 static bool sdcard_receiveCID(void)
476 uint8_t cid[16];
478 if (sdcard_receiveDataBlock(cid, sizeof(cid)) != SDCARD_RECEIVE_SUCCESS) {
479 return false;
482 sdcard.metadata.manufacturerID = cid[0];
483 sdcard.metadata.oemID = (cid[1] << 8) | cid[2];
484 sdcard.metadata.productName[0] = cid[3];
485 sdcard.metadata.productName[1] = cid[4];
486 sdcard.metadata.productName[2] = cid[5];
487 sdcard.metadata.productName[3] = cid[6];
488 sdcard.metadata.productName[4] = cid[7];
489 sdcard.metadata.productRevisionMajor = cid[8] >> 4;
490 sdcard.metadata.productRevisionMinor = cid[8] & 0x0F;
491 sdcard.metadata.productSerial = (cid[9] << 24) | (cid[10] << 16) | (cid[11] << 8) | cid[12];
492 sdcard.metadata.productionYear = (((cid[13] & 0x0F) << 4) | (cid[14] >> 4)) + 2000;
493 sdcard.metadata.productionMonth = cid[14] & 0x0F;
495 return true;
498 static bool sdcard_fetchCSD(void)
500 uint32_t readBlockLen, blockCount, blockCountMult;
501 uint64_t capacityBytes;
503 sdcard_select();
505 /* The CSD command's data block should always arrive within 8 idle clock cycles (SD card spec). This is because
506 * the information about card latency is stored in the CSD register itself, so we can't use that yet!
508 bool success =
509 sdcard_sendCommand(SDCARD_COMMAND_SEND_CSD, 0) == 0
510 && sdcard_receiveDataBlock((uint8_t*) &sdcard.csd, sizeof(sdcard.csd)) == SDCARD_RECEIVE_SUCCESS
511 && SDCARD_GET_CSD_FIELD(sdcard.csd, 1, TRAILER) == 1;
513 if (success) {
514 switch (SDCARD_GET_CSD_FIELD(sdcard.csd, 1, CSD_STRUCTURE_VER)) {
515 case SDCARD_CSD_STRUCTURE_VERSION_1:
516 // Block size in bytes (doesn't have to be 512)
517 readBlockLen = 1 << SDCARD_GET_CSD_FIELD(sdcard.csd, 1, READ_BLOCK_LEN);
518 blockCountMult = 1 << (SDCARD_GET_CSD_FIELD(sdcard.csd, 1, CSIZE_MULT) + 2);
519 blockCount = (SDCARD_GET_CSD_FIELD(sdcard.csd, 1, CSIZE) + 1) * blockCountMult;
521 // We could do this in 32 bits but it makes the 2GB case awkward
522 capacityBytes = (uint64_t) blockCount * readBlockLen;
524 // Re-express that capacity (max 2GB) in our standard 512-byte block size
525 sdcard.metadata.numBlocks = capacityBytes / SDCARD_BLOCK_SIZE;
526 break;
527 case SDCARD_CSD_STRUCTURE_VERSION_2:
528 sdcard.metadata.numBlocks = (SDCARD_GET_CSD_FIELD(sdcard.csd, 2, CSIZE) + 1) * 1024;
529 break;
530 default:
531 success = false;
535 sdcard_deselect();
537 return success;
541 * Check if the SD Card has completed its startup sequence. Must be called with sdcard.state == SDCARD_STATE_INITIALIZATION.
543 * Returns true if the card has finished its init process.
545 static bool sdcard_checkInitDone(void)
547 sdcard_select();
549 uint8_t status = sdcard_sendAppCommand(SDCARD_ACOMMAND_SEND_OP_COND, sdcard.version == 2 ? 1 << 30 /* We support high capacity cards */ : 0);
551 sdcard_deselect();
553 // When card init is complete, the idle bit in the response becomes zero.
554 return status == 0x00;
558 * Begin the initialization process for the SD card. This must be called first before any other sdcard_ routine.
560 void sdcard_init(const sdcardConfig_t *config)
562 sdcard.enabled = config->enabled;
563 if (!sdcard.enabled) {
564 sdcard.state = SDCARD_STATE_NOT_PRESENT;
565 return;
568 sdcard.instance = spiInstanceByDevice(config->device);
570 sdcard.useDMAForTx = config->useDma;
571 if (sdcard.useDMAForTx) {
572 #if defined(STM32F4) || defined(STM32F7)
573 sdcard.dmaChannel = config->dmaChannel;
574 #endif
575 sdcard.dma = dmaGetDescriptorByIdentifier(config->dmaIdentifier);
576 dmaInit(config->dmaIdentifier, OWNER_SDCARD, 0);
579 if (config->chipSelectTag) {
580 sdcard.chipSelectPin = IOGetByTag(config->chipSelectTag);
581 IOInit(sdcard.chipSelectPin, OWNER_SDCARD_CS, 0);
582 IOConfigGPIO(sdcard.chipSelectPin, SPI_IO_CS_CFG);
583 } else {
584 sdcard.chipSelectPin = IO_NONE;
587 if (config->cardDetectTag) {
588 sdcard.cardDetectPin = IOGetByTag(config->cardDetectTag);
589 sdcard.detectionInverted = config->cardDetectInverted;
590 } else {
591 sdcard.cardDetectPin = IO_NONE;
592 sdcard.detectionInverted = false;
595 // Max frequency is initially 400kHz
596 spiSetDivisor(sdcard.instance, SDCARD_SPI_INITIALIZATION_CLOCK_DIVIDER);
598 // SDCard wants 1ms minimum delay after power is applied to it
599 delay(1000);
601 // Transmit at least 74 dummy clock cycles with CS high so the SD card can start up
602 SET_CS_HIGH;
604 spiTransfer(sdcard.instance, NULL, NULL, SDCARD_INIT_NUM_DUMMY_BYTES);
606 // Wait for that transmission to finish before we enable the SDCard, so it receives the required number of cycles:
607 int time = 100000;
608 while (spiIsBusBusy(sdcard.instance)) {
609 if (time-- == 0) {
610 sdcard.state = SDCARD_STATE_NOT_PRESENT;
611 sdcard.failureCount++;
612 return;
616 sdcard.operationStartTime = millis();
617 sdcard.state = SDCARD_STATE_RESET;
618 sdcard.failureCount = 0;
621 static bool sdcard_setBlockLength(uint32_t blockLen)
623 sdcard_select();
625 uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_SET_BLOCKLEN, blockLen);
627 sdcard_deselect();
629 return status == 0;
633 * Returns true if the card is ready to accept read/write commands.
635 static bool sdcard_isReady(void)
637 return sdcard.state == SDCARD_STATE_READY || sdcard.state == SDCARD_STATE_WRITING_MULTIPLE_BLOCKS;
641 * Send the stop-transmission token to complete a multi-block write.
643 * Returns:
644 * SDCARD_OPERATION_IN_PROGRESS - We're now waiting for that stop to complete, the card will enter
645 * the SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE state.
646 * SDCARD_OPERATION_SUCCESS - The multi-block write finished immediately, the card will enter
647 * the SDCARD_READY state.
650 static sdcardOperationStatus_e sdcard_endWriteBlocks(void)
652 sdcard.multiWriteBlocksRemain = 0;
654 // 8 dummy clocks to guarantee N_WR clocks between the last card response and this token
655 spiTransferByte(sdcard.instance, 0xFF);
657 spiTransferByte(sdcard.instance, SDCARD_MULTIPLE_BLOCK_WRITE_STOP_TOKEN);
659 // Card may choose to raise a busy (non-0xFF) signal after at most N_BR (1 byte) delay
660 if (sdcard_waitForNonIdleByte(1) == 0xFF) {
661 sdcard.state = SDCARD_STATE_READY;
662 return SDCARD_OPERATION_SUCCESS;
663 } else {
664 sdcard.state = SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE;
665 sdcard.operationStartTime = millis();
667 return SDCARD_OPERATION_IN_PROGRESS;
672 * Call periodically for the SD card to perform in-progress transfers.
674 * Returns true if the card is ready to accept commands.
676 bool sdcard_poll(void)
678 if (!sdcard.enabled) {
679 sdcard.state = SDCARD_STATE_NOT_PRESENT;
680 return false;
683 uint8_t initStatus;
684 bool sendComplete;
686 #ifdef SDCARD_PROFILING
687 bool profilingComplete;
688 #endif
690 doMore:
691 switch (sdcard.state) {
692 case SDCARD_STATE_RESET:
693 sdcard_select();
695 initStatus = sdcard_sendCommand(SDCARD_COMMAND_GO_IDLE_STATE, 0);
697 sdcard_deselect();
699 if (initStatus == SDCARD_R1_STATUS_BIT_IDLE) {
700 // Check card voltage and version
701 if (sdcard_validateInterfaceCondition()) {
703 sdcard.state = SDCARD_STATE_CARD_INIT_IN_PROGRESS;
704 goto doMore;
705 } else {
706 // Bad reply/voltage, we ought to refrain from accessing the card.
707 sdcard.state = SDCARD_STATE_NOT_PRESENT;
710 break;
712 case SDCARD_STATE_CARD_INIT_IN_PROGRESS:
713 if (sdcard_checkInitDone()) {
714 if (sdcard.version == 2) {
715 // Check for high capacity card
716 uint32_t ocr;
718 if (!sdcard_readOCRRegister(&ocr)) {
719 sdcard_reset();
720 goto doMore;
723 sdcard.highCapacity = (ocr & (1 << 30)) != 0;
724 } else {
725 // Version 1 cards are always low-capacity
726 sdcard.highCapacity = false;
729 // Now fetch the CSD and CID registers
730 if (sdcard_fetchCSD()) {
731 sdcard_select();
733 uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_SEND_CID, 0);
735 if (status == 0) {
736 // Keep the card selected to receive the response block
737 sdcard.state = SDCARD_STATE_INITIALIZATION_RECEIVE_CID;
738 goto doMore;
739 } else {
740 sdcard_deselect();
742 sdcard_reset();
743 goto doMore;
747 break;
748 case SDCARD_STATE_INITIALIZATION_RECEIVE_CID:
749 if (sdcard_receiveCID()) {
750 sdcard_deselect();
752 /* The spec is a little iffy on what the default block size is for Standard Size cards (it can be changed on
753 * standard size cards) so let's just set it to 512 explicitly so we don't have a problem.
755 if (!sdcard.highCapacity && !sdcard_setBlockLength(SDCARD_BLOCK_SIZE)) {
756 sdcard_reset();
757 goto doMore;
760 // Now we're done with init and we can switch to the full speed clock (<25MHz)
761 spiSetDivisor(sdcard.instance, SDCARD_SPI_FULL_SPEED_CLOCK_DIVIDER);
763 sdcard.multiWriteBlocksRemain = 0;
765 sdcard.state = SDCARD_STATE_READY;
766 goto doMore;
767 } // else keep waiting for the CID to arrive
768 break;
769 case SDCARD_STATE_SENDING_WRITE:
770 // Have we finished sending the write yet?
771 sendComplete = false;
773 #if defined(USE_HAL_DRIVER)
774 if (sdcard.useDMAForTx && DMA_GET_FLAG_STATUS(sdcard.dma, DMA_IT_TCIF)) {
775 //Clear both flags after transfer
776 DMA_CLEAR_FLAG(sdcard.dma, DMA_IT_TCIF);
777 DMA_CLEAR_FLAG(sdcard.dma, DMA_IT_HTIF);
778 // Drain anything left in the Rx FIFO (we didn't read it during the write)
779 while (LL_SPI_IsActiveFlag_RXNE(sdcard.instance)) {
780 sdcard.instance->DR;
783 // Wait for the final bit to be transmitted
784 while (spiIsBusBusy(sdcard.instance)) {
787 LL_SPI_DisableDMAReq_TX(sdcard.instance);
789 sendComplete = true;
791 #else
792 #ifdef STM32F4
793 if (sdcard.useDMAForTx && DMA_GetFlagStatus(sdcard.dma->ref, sdcard.dma->completeFlag) == SET) {
794 DMA_ClearFlag(sdcard.dma->ref, sdcard.dma->completeFlag);
795 #else
796 if (sdcard.useDMAForTx && DMA_GetFlagStatus(sdcard.dma->completeFlag) == SET) {
797 DMA_ClearFlag(sdcard.dma->completeFlag);
798 #endif
800 DMA_Cmd(sdcard.dma->ref, DISABLE);
802 // Drain anything left in the Rx FIFO (we didn't read it during the write)
803 while (SPI_I2S_GetFlagStatus(sdcard.instance, SPI_I2S_FLAG_RXNE) == SET) {
804 sdcard.instance->DR;
807 // Wait for the final bit to be transmitted
808 while (spiIsBusBusy(sdcard.instance)) {
811 SPI_I2S_DMACmd(sdcard.instance, SPI_I2S_DMAReq_Tx, DISABLE);
813 sendComplete = true;
815 #endif
816 if (!sdcard.useDMAForTx) {
817 // Send another chunk
818 spiTransfer(sdcard.instance, sdcard.pendingOperation.buffer + SDCARD_NON_DMA_CHUNK_SIZE * sdcard.pendingOperation.chunkIndex, NULL, SDCARD_NON_DMA_CHUNK_SIZE);
820 sdcard.pendingOperation.chunkIndex++;
822 sendComplete = sdcard.pendingOperation.chunkIndex == SDCARD_BLOCK_SIZE / SDCARD_NON_DMA_CHUNK_SIZE;
825 if (sendComplete) {
826 // Finish up by sending the CRC and checking the SD-card's acceptance/rejectance
827 if (sdcard_sendDataBlockFinish()) {
828 // The SD card is now busy committing that write to the card
829 sdcard.state = SDCARD_STATE_WAITING_FOR_WRITE;
830 sdcard.operationStartTime = millis();
832 // Since we've transmitted the buffer we can go ahead and tell the caller their operation is complete
833 if (sdcard.pendingOperation.callback) {
834 sdcard.pendingOperation.callback(SDCARD_BLOCK_OPERATION_WRITE, sdcard.pendingOperation.blockIndex, sdcard.pendingOperation.buffer, sdcard.pendingOperation.callbackData);
836 } else {
837 /* Our write was rejected! This could be due to a bad address but we hope not to attempt that, so assume
838 * the card is broken and needs reset.
840 sdcard_reset();
842 // Announce write failure:
843 if (sdcard.pendingOperation.callback) {
844 sdcard.pendingOperation.callback(SDCARD_BLOCK_OPERATION_WRITE, sdcard.pendingOperation.blockIndex, NULL, sdcard.pendingOperation.callbackData);
847 goto doMore;
850 break;
851 case SDCARD_STATE_WAITING_FOR_WRITE:
852 if (sdcard_waitForIdle(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY)) {
853 #ifdef SDCARD_PROFILING
854 profilingComplete = true;
855 #endif
857 sdcard.failureCount = 0; // Assume the card is good if it can complete a write
859 // Still more blocks left to write in a multi-block chain?
860 if (sdcard.multiWriteBlocksRemain > 1) {
861 sdcard.multiWriteBlocksRemain--;
862 sdcard.multiWriteNextBlock++;
863 sdcard.state = SDCARD_STATE_WRITING_MULTIPLE_BLOCKS;
864 } else if (sdcard.multiWriteBlocksRemain == 1) {
865 // This function changes the sd card state for us whether immediately succesful or delayed:
866 if (sdcard_endWriteBlocks() == SDCARD_OPERATION_SUCCESS) {
867 sdcard_deselect();
868 } else {
869 #ifdef SDCARD_PROFILING
870 // Wait for the multi-block write to be terminated before finishing timing
871 profilingComplete = false;
872 #endif
874 } else {
875 sdcard.state = SDCARD_STATE_READY;
876 sdcard_deselect();
879 #ifdef SDCARD_PROFILING
880 if (profilingComplete && sdcard.profiler) {
881 sdcard.profiler(SDCARD_BLOCK_OPERATION_WRITE, sdcard.pendingOperation.blockIndex, micros() - sdcard.pendingOperation.profileStartTime);
883 #endif
884 } else if (millis() > sdcard.operationStartTime + SDCARD_TIMEOUT_WRITE_MSEC) {
886 * The caller has already been told that their write has completed, so they will have discarded
887 * their buffer and have no hope of retrying the operation. But this should be very rare and it allows
888 * them to reuse their buffer milliseconds faster than they otherwise would.
890 sdcard_reset();
891 goto doMore;
893 break;
894 case SDCARD_STATE_READING:
895 switch (sdcard_receiveDataBlock(sdcard.pendingOperation.buffer, SDCARD_BLOCK_SIZE)) {
896 case SDCARD_RECEIVE_SUCCESS:
897 sdcard_deselect();
899 sdcard.state = SDCARD_STATE_READY;
900 sdcard.failureCount = 0; // Assume the card is good if it can complete a read
902 #ifdef SDCARD_PROFILING
903 if (sdcard.profiler) {
904 sdcard.profiler(SDCARD_BLOCK_OPERATION_READ, sdcard.pendingOperation.blockIndex, micros() - sdcard.pendingOperation.profileStartTime);
906 #endif
908 if (sdcard.pendingOperation.callback) {
909 sdcard.pendingOperation.callback(
910 SDCARD_BLOCK_OPERATION_READ,
911 sdcard.pendingOperation.blockIndex,
912 sdcard.pendingOperation.buffer,
913 sdcard.pendingOperation.callbackData
916 break;
917 case SDCARD_RECEIVE_BLOCK_IN_PROGRESS:
918 if (millis() <= sdcard.operationStartTime + SDCARD_TIMEOUT_READ_MSEC) {
919 break; // Timeout not reached yet so keep waiting
921 // Timeout has expired, so fall through to convert to a fatal error
922 FALLTHROUGH;
924 case SDCARD_RECEIVE_ERROR:
925 sdcard_deselect();
927 sdcard_reset();
929 if (sdcard.pendingOperation.callback) {
930 sdcard.pendingOperation.callback(
931 SDCARD_BLOCK_OPERATION_READ,
932 sdcard.pendingOperation.blockIndex,
933 NULL,
934 sdcard.pendingOperation.callbackData
938 goto doMore;
939 break;
941 break;
942 case SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE:
943 if (sdcard_waitForIdle(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY)) {
944 sdcard_deselect();
946 sdcard.state = SDCARD_STATE_READY;
948 #ifdef SDCARD_PROFILING
949 if (sdcard.profiler) {
950 sdcard.profiler(SDCARD_BLOCK_OPERATION_WRITE, sdcard.pendingOperation.blockIndex, micros() - sdcard.pendingOperation.profileStartTime);
952 #endif
953 } else if (millis() > sdcard.operationStartTime + SDCARD_TIMEOUT_WRITE_MSEC) {
954 sdcard_reset();
955 goto doMore;
957 break;
958 case SDCARD_STATE_NOT_PRESENT:
959 default:
963 // Is the card's initialization taking too long?
964 if (sdcard.state >= SDCARD_STATE_RESET && sdcard.state < SDCARD_STATE_READY
965 && millis() - sdcard.operationStartTime > SDCARD_TIMEOUT_INIT_MILLIS) {
966 sdcard_reset();
969 return sdcard_isReady();
973 * Write the 512-byte block from the given buffer into the block with the given index.
975 * If the write does not complete immediately, your callback will be called later. If the write was successful, the
976 * buffer pointer will be the same buffer you originally passed in, otherwise the buffer will be set to NULL.
978 * Returns:
979 * SDCARD_OPERATION_IN_PROGRESS - Your buffer is currently being transmitted to the card and your callback will be
980 * called later to report the completion. The buffer pointer must remain valid until
981 * that time.
982 * SDCARD_OPERATION_SUCCESS - Your buffer has been transmitted to the card now.
983 * SDCARD_OPERATION_BUSY - The card is already busy and cannot accept your write
984 * SDCARD_OPERATION_FAILURE - Your write was rejected by the card, card will be reset
986 sdcardOperationStatus_e sdcard_writeBlock(uint32_t blockIndex, uint8_t *buffer, sdcard_operationCompleteCallback_c callback, uint32_t callbackData)
988 uint8_t status;
990 #ifdef SDCARD_PROFILING
991 sdcard.pendingOperation.profileStartTime = micros();
992 #endif
994 doMore:
995 switch (sdcard.state) {
996 case SDCARD_STATE_WRITING_MULTIPLE_BLOCKS:
997 // Do we need to cancel the previous multi-block write?
998 if (blockIndex != sdcard.multiWriteNextBlock) {
999 if (sdcard_endWriteBlocks() == SDCARD_OPERATION_SUCCESS) {
1000 // Now we've entered the ready state, we can try again
1001 goto doMore;
1002 } else {
1003 return SDCARD_OPERATION_BUSY;
1007 // We're continuing a multi-block write
1008 break;
1009 case SDCARD_STATE_READY:
1010 // We're not continuing a multi-block write so we need to send a single-block write command
1011 sdcard_select();
1013 // Standard size cards use byte addressing, high capacity cards use block addressing
1014 status = sdcard_sendCommand(SDCARD_COMMAND_WRITE_BLOCK, sdcard.highCapacity ? blockIndex : blockIndex * SDCARD_BLOCK_SIZE);
1016 if (status != 0) {
1017 sdcard_deselect();
1019 sdcard_reset();
1021 return SDCARD_OPERATION_FAILURE;
1023 break;
1024 default:
1025 return SDCARD_OPERATION_BUSY;
1028 sdcard_sendDataBlockBegin(buffer, sdcard.state == SDCARD_STATE_WRITING_MULTIPLE_BLOCKS);
1030 sdcard.pendingOperation.buffer = buffer;
1031 sdcard.pendingOperation.blockIndex = blockIndex;
1032 sdcard.pendingOperation.callback = callback;
1033 sdcard.pendingOperation.callbackData = callbackData;
1034 sdcard.pendingOperation.chunkIndex = 1; // (for non-DMA transfers) we've sent chunk #0 already
1035 sdcard.state = SDCARD_STATE_SENDING_WRITE;
1037 return SDCARD_OPERATION_IN_PROGRESS;
1041 * Begin writing a series of consecutive blocks beginning at the given block index. This will allow (but not require)
1042 * the SD card to pre-erase the number of blocks you specifiy, which can allow the writes to complete faster.
1044 * Afterwards, just call sdcard_writeBlock() as normal to write those blocks consecutively.
1046 * It's okay to abort the multi-block write at any time by writing to a non-consecutive address, or by performing a read.
1048 * Returns:
1049 * SDCARD_OPERATION_SUCCESS - Multi-block write has been queued
1050 * SDCARD_OPERATION_BUSY - The card is already busy and cannot accept your write
1051 * SDCARD_OPERATION_FAILURE - A fatal error occured, card will be reset
1053 sdcardOperationStatus_e sdcard_beginWriteBlocks(uint32_t blockIndex, uint32_t blockCount)
1055 if (sdcard.state != SDCARD_STATE_READY) {
1056 if (sdcard.state == SDCARD_STATE_WRITING_MULTIPLE_BLOCKS) {
1057 if (blockIndex == sdcard.multiWriteNextBlock) {
1058 // Assume that the caller wants to continue the multi-block write they already have in progress!
1059 return SDCARD_OPERATION_SUCCESS;
1060 } else if (sdcard_endWriteBlocks() != SDCARD_OPERATION_SUCCESS) {
1061 return SDCARD_OPERATION_BUSY;
1062 } // Else we've completed the previous multi-block write and can fall through to start the new one
1063 } else {
1064 return SDCARD_OPERATION_BUSY;
1068 sdcard_select();
1070 if (
1071 sdcard_sendAppCommand(SDCARD_ACOMMAND_SET_WR_BLOCK_ERASE_COUNT, blockCount) == 0
1072 && sdcard_sendCommand(SDCARD_COMMAND_WRITE_MULTIPLE_BLOCK, sdcard.highCapacity ? blockIndex : blockIndex * SDCARD_BLOCK_SIZE) == 0
1074 sdcard.state = SDCARD_STATE_WRITING_MULTIPLE_BLOCKS;
1075 sdcard.multiWriteBlocksRemain = blockCount;
1076 sdcard.multiWriteNextBlock = blockIndex;
1078 // Leave the card selected
1079 return SDCARD_OPERATION_SUCCESS;
1080 } else {
1081 sdcard_deselect();
1083 sdcard_reset();
1085 return SDCARD_OPERATION_FAILURE;
1090 * Read the 512-byte block with the given index into the given 512-byte buffer.
1092 * When the read completes, your callback will be called. If the read was successful, the buffer pointer will be the
1093 * same buffer you originally passed in, otherwise the buffer will be set to NULL.
1095 * You must keep the pointer to the buffer valid until the operation completes!
1097 * Returns:
1098 * true - The operation was successfully queued for later completion, your callback will be called later
1099 * false - The operation could not be started due to the card being busy (try again later).
1101 bool sdcard_readBlock(uint32_t blockIndex, uint8_t *buffer, sdcard_operationCompleteCallback_c callback, uint32_t callbackData)
1103 if (sdcard.state != SDCARD_STATE_READY) {
1104 if (sdcard.state == SDCARD_STATE_WRITING_MULTIPLE_BLOCKS) {
1105 if (sdcard_endWriteBlocks() != SDCARD_OPERATION_SUCCESS) {
1106 return false;
1108 } else {
1109 return false;
1113 #ifdef SDCARD_PROFILING
1114 sdcard.pendingOperation.profileStartTime = micros();
1115 #endif
1117 sdcard_select();
1119 // Standard size cards use byte addressing, high capacity cards use block addressing
1120 uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_READ_SINGLE_BLOCK, sdcard.highCapacity ? blockIndex : blockIndex * SDCARD_BLOCK_SIZE);
1122 if (status == 0) {
1123 sdcard.pendingOperation.buffer = buffer;
1124 sdcard.pendingOperation.blockIndex = blockIndex;
1125 sdcard.pendingOperation.callback = callback;
1126 sdcard.pendingOperation.callbackData = callbackData;
1128 sdcard.state = SDCARD_STATE_READING;
1130 sdcard.operationStartTime = millis();
1132 // Leave the card selected for the whole transaction
1134 return true;
1135 } else {
1136 sdcard_deselect();
1138 return false;
1143 * Returns true if the SD card has successfully completed its startup procedures.
1145 bool sdcard_isInitialized(void)
1147 return sdcard.state >= SDCARD_STATE_READY;
1150 const sdcardMetadata_t* sdcard_getMetadata(void)
1152 return &sdcard.metadata;
1155 #ifdef SDCARD_PROFILING
1157 void sdcard_setProfilerCallback(sdcard_profilerCallback_c callback)
1159 sdcard.profiler = callback;
1162 #endif
1164 #endif