Removed excess trailing spaces before new lines on licenses.
[betaflight.git] / src / main / drivers / sdcard.c
blob1664ea22a2b15b93fe6ed4ce807670e2f6bc76e0
1 /*
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)
8 * any later version.
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/>.
21 #include <stdbool.h>
22 #include <stdint.h>
24 #include "platform.h"
26 #ifdef USE_SDCARD
28 #include "drivers/nvic.h"
29 #include "drivers/io.h"
30 #include "dma.h"
32 #include "drivers/bus_spi.h"
33 #include "drivers/time.h"
35 #include "sdcard.h"
36 #include "sdcard_standard.h"
38 #ifdef AFATFS_USE_INTROSPECTIVE_LOGGING
39 #define SDCARD_PROFILING
40 #endif
42 #define SET_CS_HIGH IOHi(sdcard.chipSelectPin)
43 #define SET_CS_LOW IOLo(sdcard.chipSelectPin)
45 #define SDCARD_INIT_NUM_DUMMY_BYTES 10
46 #define SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY 8
47 // Chosen so that CMD8 will have the same CRC as CMD0:
48 #define SDCARD_IF_COND_CHECK_PATTERN 0xAB
50 #define SDCARD_TIMEOUT_INIT_MILLIS 200
51 #define SDCARD_MAX_CONSECUTIVE_FAILURES 8
53 /* Break up 512-byte SD card sectors into chunks of this size when writing without DMA to reduce the peak overhead
54 * per call to sdcard_poll().
56 #define SDCARD_NON_DMA_CHUNK_SIZE 256
58 typedef enum {
59 // In these states we run at the initialization 400kHz clockspeed:
60 SDCARD_STATE_NOT_PRESENT = 0,
61 SDCARD_STATE_RESET,
62 SDCARD_STATE_CARD_INIT_IN_PROGRESS,
63 SDCARD_STATE_INITIALIZATION_RECEIVE_CID,
65 // In these states we run at full clock speed
66 SDCARD_STATE_READY,
67 SDCARD_STATE_READING,
68 SDCARD_STATE_SENDING_WRITE,
69 SDCARD_STATE_WAITING_FOR_WRITE,
70 SDCARD_STATE_WRITING_MULTIPLE_BLOCKS,
71 SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE
72 } sdcardState_e;
74 typedef struct sdcard_t {
75 struct {
76 uint8_t *buffer;
77 uint32_t blockIndex;
78 uint8_t chunkIndex;
80 sdcard_operationCompleteCallback_c callback;
81 uint32_t callbackData;
83 #ifdef SDCARD_PROFILING
84 uint32_t profileStartTime;
85 #endif
86 } pendingOperation;
88 uint32_t operationStartTime;
90 uint8_t failureCount;
92 uint8_t version;
93 bool highCapacity;
95 uint32_t multiWriteNextBlock;
96 uint32_t multiWriteBlocksRemain;
98 sdcardState_e state;
100 sdcardMetadata_t metadata;
101 sdcardCSD_t csd;
103 #ifdef SDCARD_PROFILING
104 sdcard_profilerCallback_c profiler;
105 #endif
106 SPI_TypeDef *instance;
107 bool enabled;
108 bool detectionInverted;
109 bool useDMAForTx;
110 IO_t cardDetectPin;
111 IO_t chipSelectPin;
112 dmaChannelDescriptor_t * dma;
113 uint8_t dmaChannel;
114 } sdcard_t;
116 static sdcard_t sdcard;
118 STATIC_ASSERT(sizeof(sdcardCSD_t) == 16, sdcard_csd_bitfields_didnt_pack_properly);
120 void sdcardInsertionDetectDeinit(void)
122 if (sdcard.cardDetectPin) {
123 IOInit(sdcard.cardDetectPin, OWNER_FREE, 0);
124 IOConfigGPIO(sdcard.cardDetectPin, IOCFG_IN_FLOATING);
128 void sdcardInsertionDetectInit(void)
130 if (sdcard.cardDetectPin) {
131 IOInit(sdcard.cardDetectPin, OWNER_SDCARD_DETECT, 0);
132 IOConfigGPIO(sdcard.cardDetectPin, IOCFG_IPU);
137 * Detect if a SD card is physically present in the memory slot.
139 bool sdcard_isInserted(void)
141 bool result = true;
142 if (sdcard.cardDetectPin) {
143 result = IORead(sdcard.cardDetectPin) != 0;
144 if (sdcard.detectionInverted) {
145 result = !result;
148 return result;
152 * Returns true if the card has already been, or is currently, initializing and hasn't encountered enough errors to
153 * trip our error threshold and be disabled (i.e. our card is in and working!)
155 bool sdcard_isFunctional(void)
157 return sdcard.state != SDCARD_STATE_NOT_PRESENT;
160 static void sdcard_select(void)
162 SET_CS_LOW;
165 static void sdcard_deselect(void)
167 // As per the SD-card spec, give the card 8 dummy clocks so it can finish its operation
168 //spiTransferByte(sdcard.instance, 0xFF);
170 while (spiIsBusBusy(sdcard.instance)) {
173 SET_CS_HIGH;
177 * Handle a failure of an SD card operation by resetting the card back to its initialization phase.
179 * Increments the failure counter, and when the failure threshold is reached, disables the card until
180 * the next call to sdcard_init().
182 static void sdcard_reset(void)
184 if (!sdcard_isInserted()) {
185 sdcard.state = SDCARD_STATE_NOT_PRESENT;
186 return;
189 if (sdcard.state >= SDCARD_STATE_READY) {
190 spiSetDivisor(sdcard.instance, SDCARD_SPI_INITIALIZATION_CLOCK_DIVIDER);
193 sdcard.failureCount++;
194 if (sdcard.failureCount >= SDCARD_MAX_CONSECUTIVE_FAILURES) {
195 sdcard.state = SDCARD_STATE_NOT_PRESENT;
196 } else {
197 sdcard.operationStartTime = millis();
198 sdcard.state = SDCARD_STATE_RESET;
203 * The SD card spec requires 8 clock cycles to be sent by us on the bus after most commands so it can finish its
204 * processing of that command. The easiest way for us to do this is to just wait for the bus to become idle before
205 * we transmit a command, sending at least 8-bits onto the bus when we do so.
207 static bool sdcard_waitForIdle(int maxBytesToWait)
209 while (maxBytesToWait > 0) {
210 uint8_t b = spiTransferByte(sdcard.instance, 0xFF);
211 if (b == 0xFF) {
212 return true;
214 maxBytesToWait--;
217 return false;
221 * Wait for up to maxDelay 0xFF idle bytes to arrive from the card, returning the first non-idle byte found.
223 * Returns 0xFF on failure.
225 static uint8_t sdcard_waitForNonIdleByte(int maxDelay)
227 for (int i = 0; i < maxDelay + 1; i++) { // + 1 so we can wait for maxDelay '0xFF' bytes before reading a response byte afterwards
228 uint8_t response = spiTransferByte(sdcard.instance, 0xFF);
230 if (response != 0xFF) {
231 return response;
235 return 0xFF;
239 * Waits up to SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY bytes for the card to become ready, send a command to the card
240 * with the given argument, waits up to SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY bytes for a reply, and returns the
241 * first non-0xFF byte of the reply.
243 * You must select the card first with sdcard_select() and deselect it afterwards with sdcard_deselect().
245 * Upon failure, 0xFF is returned.
247 static uint8_t sdcard_sendCommand(uint8_t commandCode, uint32_t commandArgument)
249 const uint8_t command[6] = {
250 0x40 | commandCode,
251 commandArgument >> 24,
252 commandArgument >> 16,
253 commandArgument >> 8,
254 commandArgument,
255 0x95 /* Static CRC. This CRC is valid for CMD0 with a 0 argument, and CMD8 with 0x1AB argument, which are the only
256 commands that require a CRC */
259 // Go ahead and send the command even if the card isn't idle if this is the reset command
260 if (!sdcard_waitForIdle(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY) && commandCode != SDCARD_COMMAND_GO_IDLE_STATE)
261 return 0xFF;
263 spiTransfer(sdcard.instance, command, NULL, sizeof(command));
266 * The card can take up to SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY bytes to send the response, in the meantime
267 * it'll transmit 0xFF filler bytes.
269 return sdcard_waitForNonIdleByte(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY);
272 static uint8_t sdcard_sendAppCommand(uint8_t commandCode, uint32_t commandArgument)
274 sdcard_sendCommand(SDCARD_COMMAND_APP_CMD, 0);
276 return sdcard_sendCommand(commandCode, commandArgument);
280 * Sends an IF_COND message to the card to check its version and validate its voltage requirements. Sets the global
281 * sdCardVersion with the detected version (0, 1, or 2) and returns true if the card is compatible.
283 static bool sdcard_validateInterfaceCondition(void)
285 uint8_t ifCondReply[4];
287 sdcard.version = 0;
289 sdcard_select();
291 uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_SEND_IF_COND, (SDCARD_VOLTAGE_ACCEPTED_2_7_to_3_6 << 8) | SDCARD_IF_COND_CHECK_PATTERN);
293 // Don't deselect the card right away, because we'll want to read the rest of its reply if it's a V2 card
295 if (status == (SDCARD_R1_STATUS_BIT_ILLEGAL_COMMAND | SDCARD_R1_STATUS_BIT_IDLE)) {
296 // V1 cards don't support this command
297 sdcard.version = 1;
298 } else if (status == SDCARD_R1_STATUS_BIT_IDLE) {
299 spiTransfer(sdcard.instance, NULL, ifCondReply, sizeof(ifCondReply));
302 * We don't bother to validate the SDCard's operating voltage range since the spec requires it to accept our
303 * 3.3V, but do check that it echoed back our check pattern properly.
305 if (ifCondReply[3] == SDCARD_IF_COND_CHECK_PATTERN) {
306 sdcard.version = 2;
310 sdcard_deselect();
312 return sdcard.version > 0;
315 static bool sdcard_readOCRRegister(uint32_t *result)
317 sdcard_select();
319 uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_READ_OCR, 0);
321 uint8_t response[4];
323 spiTransfer(sdcard.instance, NULL, response, sizeof(response));
325 if (status == 0) {
326 sdcard_deselect();
328 *result = (response[0] << 24) | (response[1] << 16) | (response[2] << 8) | response[3];
330 return true;
331 } else {
332 sdcard_deselect();
334 return false;
338 typedef enum {
339 SDCARD_RECEIVE_SUCCESS,
340 SDCARD_RECEIVE_BLOCK_IN_PROGRESS,
341 SDCARD_RECEIVE_ERROR
342 } sdcardReceiveBlockStatus_e;
345 * Attempt to receive a data block from the SD card.
347 * Return true on success, otherwise the card has not responded yet and you should retry later.
349 static sdcardReceiveBlockStatus_e sdcard_receiveDataBlock(uint8_t *buffer, int count)
351 uint8_t dataToken = sdcard_waitForNonIdleByte(8);
353 if (dataToken == 0xFF) {
354 return SDCARD_RECEIVE_BLOCK_IN_PROGRESS;
357 if (dataToken != SDCARD_SINGLE_BLOCK_READ_START_TOKEN) {
358 return SDCARD_RECEIVE_ERROR;
361 spiTransfer(sdcard.instance, NULL, buffer, count);
363 // Discard trailing CRC, we don't care
364 spiTransferByte(sdcard.instance, 0xFF);
365 spiTransferByte(sdcard.instance, 0xFF);
367 return SDCARD_RECEIVE_SUCCESS;
370 static bool sdcard_sendDataBlockFinish(void)
372 #ifdef USE_HAL_DRIVER
373 // Drain anything left in the Rx FIFO (we didn't read it during the write)
374 //This is necessary here as when using msc there is timing issue
375 while (LL_SPI_IsActiveFlag_RXNE(sdcard.instance)) {
376 sdcard.instance->DR;
378 #endif
380 // Send a dummy CRC
381 spiTransferByte(sdcard.instance, 0x00);
382 spiTransferByte(sdcard.instance, 0x00);
384 uint8_t dataResponseToken = spiTransferByte(sdcard.instance, 0xFF);
387 * Check if the card accepted the write (no CRC error / no address error)
389 * The lower 5 bits are structured as follows:
390 * | 0 | Status | 1 |
391 * | 0 | x x x | 1 |
393 * Statuses:
394 * 010 - Data accepted
395 * 101 - CRC error
396 * 110 - Write error
398 return (dataResponseToken & 0x1F) == 0x05;
402 * Begin sending a buffer of SDCARD_BLOCK_SIZE bytes to the SD card.
404 static void sdcard_sendDataBlockBegin(const uint8_t *buffer, bool multiBlockWrite)
406 // Card wants 8 dummy clock cycles between the write command's response and a data block beginning:
407 spiTransferByte(sdcard.instance, 0xFF);
409 spiTransferByte(sdcard.instance, multiBlockWrite ? SDCARD_MULTIPLE_BLOCK_WRITE_START_TOKEN : SDCARD_SINGLE_BLOCK_WRITE_START_TOKEN);
411 if (sdcard.useDMAForTx) {
412 #if defined(USE_HAL_DRIVER)
413 LL_DMA_InitTypeDef init;
415 LL_DMA_StructInit(&init);
417 init.Channel = dmaGetChannel(sdcard.dmaChannel);
418 init.Mode = LL_DMA_MODE_NORMAL;
419 init.Direction = LL_DMA_DIRECTION_MEMORY_TO_PERIPH;
421 init.PeriphOrM2MSrcAddress = (uint32_t)&sdcard.instance->DR;
422 init.Priority = LL_DMA_PRIORITY_LOW;
423 init.PeriphOrM2MSrcIncMode = LL_DMA_PERIPH_NOINCREMENT;
424 init.PeriphOrM2MSrcDataSize = LL_DMA_PDATAALIGN_BYTE;
426 init.MemoryOrM2MDstAddress = (uint32_t)buffer;
427 init.MemoryOrM2MDstIncMode = LL_DMA_MEMORY_INCREMENT;
428 init.MemoryOrM2MDstDataSize = LL_DMA_MDATAALIGN_BYTE;
430 init.NbData = SDCARD_BLOCK_SIZE;
432 LL_DMA_DeInit(sdcard.dma->dma, sdcard.dma->stream);
433 LL_DMA_Init(sdcard.dma->dma, sdcard.dma->stream, &init);
435 LL_DMA_EnableStream(sdcard.dma->dma, sdcard.dma->stream);
437 LL_SPI_EnableDMAReq_TX(sdcard.instance);
439 #else
441 DMA_InitTypeDef init;
443 DMA_StructInit(&init);
444 #ifdef STM32F4
445 init.DMA_Channel = dmaGetChannel(sdcard.dmaChannel);
446 init.DMA_Memory0BaseAddr = (uint32_t) buffer;
447 init.DMA_DIR = DMA_DIR_MemoryToPeripheral;
448 #else
449 init.DMA_M2M = DMA_M2M_Disable;
450 init.DMA_MemoryBaseAddr = (uint32_t) buffer;
451 init.DMA_DIR = DMA_DIR_PeripheralDST;
452 #endif
453 init.DMA_PeripheralBaseAddr = (uint32_t) &sdcard.instance->DR;
454 init.DMA_Priority = DMA_Priority_Low;
455 init.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
456 init.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;
458 init.DMA_MemoryInc = DMA_MemoryInc_Enable;
459 init.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
461 init.DMA_BufferSize = SDCARD_BLOCK_SIZE;
462 init.DMA_Mode = DMA_Mode_Normal;
464 DMA_DeInit(sdcard.dma->ref);
465 DMA_Init(sdcard.dma->ref, &init);
467 DMA_Cmd(sdcard.dma->ref, ENABLE);
469 SPI_I2S_DMACmd(sdcard.instance, SPI_I2S_DMAReq_Tx, ENABLE);
470 #endif
471 } else {
472 // Send the first chunk now
473 spiTransfer(sdcard.instance, buffer, NULL, SDCARD_NON_DMA_CHUNK_SIZE);
477 static bool sdcard_receiveCID(void)
479 uint8_t cid[16];
481 if (sdcard_receiveDataBlock(cid, sizeof(cid)) != SDCARD_RECEIVE_SUCCESS) {
482 return false;
485 sdcard.metadata.manufacturerID = cid[0];
486 sdcard.metadata.oemID = (cid[1] << 8) | cid[2];
487 sdcard.metadata.productName[0] = cid[3];
488 sdcard.metadata.productName[1] = cid[4];
489 sdcard.metadata.productName[2] = cid[5];
490 sdcard.metadata.productName[3] = cid[6];
491 sdcard.metadata.productName[4] = cid[7];
492 sdcard.metadata.productRevisionMajor = cid[8] >> 4;
493 sdcard.metadata.productRevisionMinor = cid[8] & 0x0F;
494 sdcard.metadata.productSerial = (cid[9] << 24) | (cid[10] << 16) | (cid[11] << 8) | cid[12];
495 sdcard.metadata.productionYear = (((cid[13] & 0x0F) << 4) | (cid[14] >> 4)) + 2000;
496 sdcard.metadata.productionMonth = cid[14] & 0x0F;
498 return true;
501 static bool sdcard_fetchCSD(void)
503 uint32_t readBlockLen, blockCount, blockCountMult;
504 uint64_t capacityBytes;
506 sdcard_select();
508 /* The CSD command's data block should always arrive within 8 idle clock cycles (SD card spec). This is because
509 * the information about card latency is stored in the CSD register itself, so we can't use that yet!
511 bool success =
512 sdcard_sendCommand(SDCARD_COMMAND_SEND_CSD, 0) == 0
513 && sdcard_receiveDataBlock((uint8_t*) &sdcard.csd, sizeof(sdcard.csd)) == SDCARD_RECEIVE_SUCCESS
514 && SDCARD_GET_CSD_FIELD(sdcard.csd, 1, TRAILER) == 1;
516 if (success) {
517 switch (SDCARD_GET_CSD_FIELD(sdcard.csd, 1, CSD_STRUCTURE_VER)) {
518 case SDCARD_CSD_STRUCTURE_VERSION_1:
519 // Block size in bytes (doesn't have to be 512)
520 readBlockLen = 1 << SDCARD_GET_CSD_FIELD(sdcard.csd, 1, READ_BLOCK_LEN);
521 blockCountMult = 1 << (SDCARD_GET_CSD_FIELD(sdcard.csd, 1, CSIZE_MULT) + 2);
522 blockCount = (SDCARD_GET_CSD_FIELD(sdcard.csd, 1, CSIZE) + 1) * blockCountMult;
524 // We could do this in 32 bits but it makes the 2GB case awkward
525 capacityBytes = (uint64_t) blockCount * readBlockLen;
527 // Re-express that capacity (max 2GB) in our standard 512-byte block size
528 sdcard.metadata.numBlocks = capacityBytes / SDCARD_BLOCK_SIZE;
529 break;
530 case SDCARD_CSD_STRUCTURE_VERSION_2:
531 sdcard.metadata.numBlocks = (SDCARD_GET_CSD_FIELD(sdcard.csd, 2, CSIZE) + 1) * 1024;
532 break;
533 default:
534 success = false;
538 sdcard_deselect();
540 return success;
544 * Check if the SD Card has completed its startup sequence. Must be called with sdcard.state == SDCARD_STATE_INITIALIZATION.
546 * Returns true if the card has finished its init process.
548 static bool sdcard_checkInitDone(void)
550 sdcard_select();
552 uint8_t status = sdcard_sendAppCommand(SDCARD_ACOMMAND_SEND_OP_COND, sdcard.version == 2 ? 1 << 30 /* We support high capacity cards */ : 0);
554 sdcard_deselect();
556 // When card init is complete, the idle bit in the response becomes zero.
557 return status == 0x00;
561 * Begin the initialization process for the SD card. This must be called first before any other sdcard_ routine.
563 void sdcard_init(const sdcardConfig_t *config)
565 sdcard.enabled = config->enabled;
566 if (!sdcard.enabled) {
567 sdcard.state = SDCARD_STATE_NOT_PRESENT;
568 return;
571 sdcard.instance = spiInstanceByDevice(config->device);
573 sdcard.useDMAForTx = config->useDma;
574 if (sdcard.useDMAForTx) {
575 #if defined(STM32F4) || defined(STM32F7)
576 sdcard.dmaChannel = config->dmaChannel;
577 #endif
578 sdcard.dma = dmaGetDescriptorByIdentifier(config->dmaIdentifier);
579 dmaInit(config->dmaIdentifier, OWNER_SDCARD, 0);
582 if (config->chipSelectTag) {
583 sdcard.chipSelectPin = IOGetByTag(config->chipSelectTag);
584 IOInit(sdcard.chipSelectPin, OWNER_SDCARD_CS, 0);
585 IOConfigGPIO(sdcard.chipSelectPin, SPI_IO_CS_CFG);
586 } else {
587 sdcard.chipSelectPin = IO_NONE;
590 if (config->cardDetectTag) {
591 sdcard.cardDetectPin = IOGetByTag(config->cardDetectTag);
592 sdcard.detectionInverted = config->cardDetectInverted;
593 } else {
594 sdcard.cardDetectPin = IO_NONE;
595 sdcard.detectionInverted = false;
598 // Max frequency is initially 400kHz
599 spiSetDivisor(sdcard.instance, SDCARD_SPI_INITIALIZATION_CLOCK_DIVIDER);
601 // SDCard wants 1ms minimum delay after power is applied to it
602 delay(1000);
604 // Transmit at least 74 dummy clock cycles with CS high so the SD card can start up
605 SET_CS_HIGH;
607 spiTransfer(sdcard.instance, NULL, NULL, SDCARD_INIT_NUM_DUMMY_BYTES);
609 // Wait for that transmission to finish before we enable the SDCard, so it receives the required number of cycles:
610 int time = 100000;
611 while (spiIsBusBusy(sdcard.instance)) {
612 if (time-- == 0) {
613 sdcard.state = SDCARD_STATE_NOT_PRESENT;
614 sdcard.failureCount++;
615 return;
619 sdcard.operationStartTime = millis();
620 sdcard.state = SDCARD_STATE_RESET;
621 sdcard.failureCount = 0;
624 static bool sdcard_setBlockLength(uint32_t blockLen)
626 sdcard_select();
628 uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_SET_BLOCKLEN, blockLen);
630 sdcard_deselect();
632 return status == 0;
636 * Returns true if the card is ready to accept read/write commands.
638 static bool sdcard_isReady(void)
640 return sdcard.state == SDCARD_STATE_READY || sdcard.state == SDCARD_STATE_WRITING_MULTIPLE_BLOCKS;
644 * Send the stop-transmission token to complete a multi-block write.
646 * Returns:
647 * SDCARD_OPERATION_IN_PROGRESS - We're now waiting for that stop to complete, the card will enter
648 * the SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE state.
649 * SDCARD_OPERATION_SUCCESS - The multi-block write finished immediately, the card will enter
650 * the SDCARD_READY state.
653 static sdcardOperationStatus_e sdcard_endWriteBlocks(void)
655 sdcard.multiWriteBlocksRemain = 0;
657 // 8 dummy clocks to guarantee N_WR clocks between the last card response and this token
658 spiTransferByte(sdcard.instance, 0xFF);
660 spiTransferByte(sdcard.instance, SDCARD_MULTIPLE_BLOCK_WRITE_STOP_TOKEN);
662 // Card may choose to raise a busy (non-0xFF) signal after at most N_BR (1 byte) delay
663 if (sdcard_waitForNonIdleByte(1) == 0xFF) {
664 sdcard.state = SDCARD_STATE_READY;
665 return SDCARD_OPERATION_SUCCESS;
666 } else {
667 sdcard.state = SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE;
668 sdcard.operationStartTime = millis();
670 return SDCARD_OPERATION_IN_PROGRESS;
675 * Call periodically for the SD card to perform in-progress transfers.
677 * Returns true if the card is ready to accept commands.
679 bool sdcard_poll(void)
681 if (!sdcard.enabled) {
682 sdcard.state = SDCARD_STATE_NOT_PRESENT;
683 return false;
686 uint8_t initStatus;
687 bool sendComplete;
689 #ifdef SDCARD_PROFILING
690 bool profilingComplete;
691 #endif
693 doMore:
694 switch (sdcard.state) {
695 case SDCARD_STATE_RESET:
696 sdcard_select();
698 initStatus = sdcard_sendCommand(SDCARD_COMMAND_GO_IDLE_STATE, 0);
700 sdcard_deselect();
702 if (initStatus == SDCARD_R1_STATUS_BIT_IDLE) {
703 // Check card voltage and version
704 if (sdcard_validateInterfaceCondition()) {
706 sdcard.state = SDCARD_STATE_CARD_INIT_IN_PROGRESS;
707 goto doMore;
708 } else {
709 // Bad reply/voltage, we ought to refrain from accessing the card.
710 sdcard.state = SDCARD_STATE_NOT_PRESENT;
713 break;
715 case SDCARD_STATE_CARD_INIT_IN_PROGRESS:
716 if (sdcard_checkInitDone()) {
717 if (sdcard.version == 2) {
718 // Check for high capacity card
719 uint32_t ocr;
721 if (!sdcard_readOCRRegister(&ocr)) {
722 sdcard_reset();
723 goto doMore;
726 sdcard.highCapacity = (ocr & (1 << 30)) != 0;
727 } else {
728 // Version 1 cards are always low-capacity
729 sdcard.highCapacity = false;
732 // Now fetch the CSD and CID registers
733 if (sdcard_fetchCSD()) {
734 sdcard_select();
736 uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_SEND_CID, 0);
738 if (status == 0) {
739 // Keep the card selected to receive the response block
740 sdcard.state = SDCARD_STATE_INITIALIZATION_RECEIVE_CID;
741 goto doMore;
742 } else {
743 sdcard_deselect();
745 sdcard_reset();
746 goto doMore;
750 break;
751 case SDCARD_STATE_INITIALIZATION_RECEIVE_CID:
752 if (sdcard_receiveCID()) {
753 sdcard_deselect();
755 /* The spec is a little iffy on what the default block size is for Standard Size cards (it can be changed on
756 * standard size cards) so let's just set it to 512 explicitly so we don't have a problem.
758 if (!sdcard.highCapacity && !sdcard_setBlockLength(SDCARD_BLOCK_SIZE)) {
759 sdcard_reset();
760 goto doMore;
763 // Now we're done with init and we can switch to the full speed clock (<25MHz)
764 spiSetDivisor(sdcard.instance, SDCARD_SPI_FULL_SPEED_CLOCK_DIVIDER);
766 sdcard.multiWriteBlocksRemain = 0;
768 sdcard.state = SDCARD_STATE_READY;
769 goto doMore;
770 } // else keep waiting for the CID to arrive
771 break;
772 case SDCARD_STATE_SENDING_WRITE:
773 // Have we finished sending the write yet?
774 sendComplete = false;
776 #if defined(USE_HAL_DRIVER)
777 if (sdcard.useDMAForTx && DMA_GET_FLAG_STATUS(sdcard.dma, DMA_IT_TCIF)) {
778 //Clear both flags after transfer
779 DMA_CLEAR_FLAG(sdcard.dma, DMA_IT_TCIF);
780 DMA_CLEAR_FLAG(sdcard.dma, DMA_IT_HTIF);
781 // Drain anything left in the Rx FIFO (we didn't read it during the write)
782 while (LL_SPI_IsActiveFlag_RXNE(sdcard.instance)) {
783 sdcard.instance->DR;
786 // Wait for the final bit to be transmitted
787 while (spiIsBusBusy(sdcard.instance)) {
790 LL_SPI_DisableDMAReq_TX(sdcard.instance);
792 sendComplete = true;
794 #else
795 #ifdef STM32F4
796 if (sdcard.useDMAForTx && DMA_GetFlagStatus(sdcard.dma->ref, sdcard.dma->completeFlag) == SET) {
797 DMA_ClearFlag(sdcard.dma->ref, sdcard.dma->completeFlag);
798 #else
799 if (sdcard.useDMAForTx && DMA_GetFlagStatus(sdcard.dma->completeFlag) == SET) {
800 DMA_ClearFlag(sdcard.dma->completeFlag);
801 #endif
803 DMA_Cmd(sdcard.dma->ref, DISABLE);
805 // Drain anything left in the Rx FIFO (we didn't read it during the write)
806 while (SPI_I2S_GetFlagStatus(sdcard.instance, SPI_I2S_FLAG_RXNE) == SET) {
807 sdcard.instance->DR;
810 // Wait for the final bit to be transmitted
811 while (spiIsBusBusy(sdcard.instance)) {
814 SPI_I2S_DMACmd(sdcard.instance, SPI_I2S_DMAReq_Tx, DISABLE);
816 sendComplete = true;
818 #endif
819 if (!sdcard.useDMAForTx) {
820 // Send another chunk
821 spiTransfer(sdcard.instance, sdcard.pendingOperation.buffer + SDCARD_NON_DMA_CHUNK_SIZE * sdcard.pendingOperation.chunkIndex, NULL, SDCARD_NON_DMA_CHUNK_SIZE);
823 sdcard.pendingOperation.chunkIndex++;
825 sendComplete = sdcard.pendingOperation.chunkIndex == SDCARD_BLOCK_SIZE / SDCARD_NON_DMA_CHUNK_SIZE;
828 if (sendComplete) {
829 // Finish up by sending the CRC and checking the SD-card's acceptance/rejectance
830 if (sdcard_sendDataBlockFinish()) {
831 // The SD card is now busy committing that write to the card
832 sdcard.state = SDCARD_STATE_WAITING_FOR_WRITE;
833 sdcard.operationStartTime = millis();
835 // Since we've transmitted the buffer we can go ahead and tell the caller their operation is complete
836 if (sdcard.pendingOperation.callback) {
837 sdcard.pendingOperation.callback(SDCARD_BLOCK_OPERATION_WRITE, sdcard.pendingOperation.blockIndex, sdcard.pendingOperation.buffer, sdcard.pendingOperation.callbackData);
839 } else {
840 /* Our write was rejected! This could be due to a bad address but we hope not to attempt that, so assume
841 * the card is broken and needs reset.
843 sdcard_reset();
845 // Announce write failure:
846 if (sdcard.pendingOperation.callback) {
847 sdcard.pendingOperation.callback(SDCARD_BLOCK_OPERATION_WRITE, sdcard.pendingOperation.blockIndex, NULL, sdcard.pendingOperation.callbackData);
850 goto doMore;
853 break;
854 case SDCARD_STATE_WAITING_FOR_WRITE:
855 if (sdcard_waitForIdle(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY)) {
856 #ifdef SDCARD_PROFILING
857 profilingComplete = true;
858 #endif
860 sdcard.failureCount = 0; // Assume the card is good if it can complete a write
862 // Still more blocks left to write in a multi-block chain?
863 if (sdcard.multiWriteBlocksRemain > 1) {
864 sdcard.multiWriteBlocksRemain--;
865 sdcard.multiWriteNextBlock++;
866 sdcard.state = SDCARD_STATE_WRITING_MULTIPLE_BLOCKS;
867 } else if (sdcard.multiWriteBlocksRemain == 1) {
868 // This function changes the sd card state for us whether immediately succesful or delayed:
869 if (sdcard_endWriteBlocks() == SDCARD_OPERATION_SUCCESS) {
870 sdcard_deselect();
871 } else {
872 #ifdef SDCARD_PROFILING
873 // Wait for the multi-block write to be terminated before finishing timing
874 profilingComplete = false;
875 #endif
877 } else {
878 sdcard.state = SDCARD_STATE_READY;
879 sdcard_deselect();
882 #ifdef SDCARD_PROFILING
883 if (profilingComplete && sdcard.profiler) {
884 sdcard.profiler(SDCARD_BLOCK_OPERATION_WRITE, sdcard.pendingOperation.blockIndex, micros() - sdcard.pendingOperation.profileStartTime);
886 #endif
887 } else if (millis() > sdcard.operationStartTime + SDCARD_TIMEOUT_WRITE_MSEC) {
889 * The caller has already been told that their write has completed, so they will have discarded
890 * their buffer and have no hope of retrying the operation. But this should be very rare and it allows
891 * them to reuse their buffer milliseconds faster than they otherwise would.
893 sdcard_reset();
894 goto doMore;
896 break;
897 case SDCARD_STATE_READING:
898 switch (sdcard_receiveDataBlock(sdcard.pendingOperation.buffer, SDCARD_BLOCK_SIZE)) {
899 case SDCARD_RECEIVE_SUCCESS:
900 sdcard_deselect();
902 sdcard.state = SDCARD_STATE_READY;
903 sdcard.failureCount = 0; // Assume the card is good if it can complete a read
905 #ifdef SDCARD_PROFILING
906 if (sdcard.profiler) {
907 sdcard.profiler(SDCARD_BLOCK_OPERATION_READ, sdcard.pendingOperation.blockIndex, micros() - sdcard.pendingOperation.profileStartTime);
909 #endif
911 if (sdcard.pendingOperation.callback) {
912 sdcard.pendingOperation.callback(
913 SDCARD_BLOCK_OPERATION_READ,
914 sdcard.pendingOperation.blockIndex,
915 sdcard.pendingOperation.buffer,
916 sdcard.pendingOperation.callbackData
919 break;
920 case SDCARD_RECEIVE_BLOCK_IN_PROGRESS:
921 if (millis() <= sdcard.operationStartTime + SDCARD_TIMEOUT_READ_MSEC) {
922 break; // Timeout not reached yet so keep waiting
924 // Timeout has expired, so fall through to convert to a fatal error
925 FALLTHROUGH;
927 case SDCARD_RECEIVE_ERROR:
928 sdcard_deselect();
930 sdcard_reset();
932 if (sdcard.pendingOperation.callback) {
933 sdcard.pendingOperation.callback(
934 SDCARD_BLOCK_OPERATION_READ,
935 sdcard.pendingOperation.blockIndex,
936 NULL,
937 sdcard.pendingOperation.callbackData
941 goto doMore;
942 break;
944 break;
945 case SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE:
946 if (sdcard_waitForIdle(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY)) {
947 sdcard_deselect();
949 sdcard.state = SDCARD_STATE_READY;
951 #ifdef SDCARD_PROFILING
952 if (sdcard.profiler) {
953 sdcard.profiler(SDCARD_BLOCK_OPERATION_WRITE, sdcard.pendingOperation.blockIndex, micros() - sdcard.pendingOperation.profileStartTime);
955 #endif
956 } else if (millis() > sdcard.operationStartTime + SDCARD_TIMEOUT_WRITE_MSEC) {
957 sdcard_reset();
958 goto doMore;
960 break;
961 case SDCARD_STATE_NOT_PRESENT:
962 default:
966 // Is the card's initialization taking too long?
967 if (sdcard.state >= SDCARD_STATE_RESET && sdcard.state < SDCARD_STATE_READY
968 && millis() - sdcard.operationStartTime > SDCARD_TIMEOUT_INIT_MILLIS) {
969 sdcard_reset();
972 return sdcard_isReady();
976 * Write the 512-byte block from the given buffer into the block with the given index.
978 * If the write does not complete immediately, your callback will be called later. If the write was successful, the
979 * buffer pointer will be the same buffer you originally passed in, otherwise the buffer will be set to NULL.
981 * Returns:
982 * SDCARD_OPERATION_IN_PROGRESS - Your buffer is currently being transmitted to the card and your callback will be
983 * called later to report the completion. The buffer pointer must remain valid until
984 * that time.
985 * SDCARD_OPERATION_SUCCESS - Your buffer has been transmitted to the card now.
986 * SDCARD_OPERATION_BUSY - The card is already busy and cannot accept your write
987 * SDCARD_OPERATION_FAILURE - Your write was rejected by the card, card will be reset
989 sdcardOperationStatus_e sdcard_writeBlock(uint32_t blockIndex, uint8_t *buffer, sdcard_operationCompleteCallback_c callback, uint32_t callbackData)
991 uint8_t status;
993 #ifdef SDCARD_PROFILING
994 sdcard.pendingOperation.profileStartTime = micros();
995 #endif
997 doMore:
998 switch (sdcard.state) {
999 case SDCARD_STATE_WRITING_MULTIPLE_BLOCKS:
1000 // Do we need to cancel the previous multi-block write?
1001 if (blockIndex != sdcard.multiWriteNextBlock) {
1002 if (sdcard_endWriteBlocks() == SDCARD_OPERATION_SUCCESS) {
1003 // Now we've entered the ready state, we can try again
1004 goto doMore;
1005 } else {
1006 return SDCARD_OPERATION_BUSY;
1010 // We're continuing a multi-block write
1011 break;
1012 case SDCARD_STATE_READY:
1013 // We're not continuing a multi-block write so we need to send a single-block write command
1014 sdcard_select();
1016 // Standard size cards use byte addressing, high capacity cards use block addressing
1017 status = sdcard_sendCommand(SDCARD_COMMAND_WRITE_BLOCK, sdcard.highCapacity ? blockIndex : blockIndex * SDCARD_BLOCK_SIZE);
1019 if (status != 0) {
1020 sdcard_deselect();
1022 sdcard_reset();
1024 return SDCARD_OPERATION_FAILURE;
1026 break;
1027 default:
1028 return SDCARD_OPERATION_BUSY;
1031 sdcard_sendDataBlockBegin(buffer, sdcard.state == SDCARD_STATE_WRITING_MULTIPLE_BLOCKS);
1033 sdcard.pendingOperation.buffer = buffer;
1034 sdcard.pendingOperation.blockIndex = blockIndex;
1035 sdcard.pendingOperation.callback = callback;
1036 sdcard.pendingOperation.callbackData = callbackData;
1037 sdcard.pendingOperation.chunkIndex = 1; // (for non-DMA transfers) we've sent chunk #0 already
1038 sdcard.state = SDCARD_STATE_SENDING_WRITE;
1040 return SDCARD_OPERATION_IN_PROGRESS;
1044 * Begin writing a series of consecutive blocks beginning at the given block index. This will allow (but not require)
1045 * the SD card to pre-erase the number of blocks you specifiy, which can allow the writes to complete faster.
1047 * Afterwards, just call sdcard_writeBlock() as normal to write those blocks consecutively.
1049 * It's okay to abort the multi-block write at any time by writing to a non-consecutive address, or by performing a read.
1051 * Returns:
1052 * SDCARD_OPERATION_SUCCESS - Multi-block write has been queued
1053 * SDCARD_OPERATION_BUSY - The card is already busy and cannot accept your write
1054 * SDCARD_OPERATION_FAILURE - A fatal error occured, card will be reset
1056 sdcardOperationStatus_e sdcard_beginWriteBlocks(uint32_t blockIndex, uint32_t blockCount)
1058 if (sdcard.state != SDCARD_STATE_READY) {
1059 if (sdcard.state == SDCARD_STATE_WRITING_MULTIPLE_BLOCKS) {
1060 if (blockIndex == sdcard.multiWriteNextBlock) {
1061 // Assume that the caller wants to continue the multi-block write they already have in progress!
1062 return SDCARD_OPERATION_SUCCESS;
1063 } else if (sdcard_endWriteBlocks() != SDCARD_OPERATION_SUCCESS) {
1064 return SDCARD_OPERATION_BUSY;
1065 } // Else we've completed the previous multi-block write and can fall through to start the new one
1066 } else {
1067 return SDCARD_OPERATION_BUSY;
1071 sdcard_select();
1073 if (
1074 sdcard_sendAppCommand(SDCARD_ACOMMAND_SET_WR_BLOCK_ERASE_COUNT, blockCount) == 0
1075 && sdcard_sendCommand(SDCARD_COMMAND_WRITE_MULTIPLE_BLOCK, sdcard.highCapacity ? blockIndex : blockIndex * SDCARD_BLOCK_SIZE) == 0
1077 sdcard.state = SDCARD_STATE_WRITING_MULTIPLE_BLOCKS;
1078 sdcard.multiWriteBlocksRemain = blockCount;
1079 sdcard.multiWriteNextBlock = blockIndex;
1081 // Leave the card selected
1082 return SDCARD_OPERATION_SUCCESS;
1083 } else {
1084 sdcard_deselect();
1086 sdcard_reset();
1088 return SDCARD_OPERATION_FAILURE;
1093 * Read the 512-byte block with the given index into the given 512-byte buffer.
1095 * When the read completes, your callback will be called. If the read was successful, the buffer pointer will be the
1096 * same buffer you originally passed in, otherwise the buffer will be set to NULL.
1098 * You must keep the pointer to the buffer valid until the operation completes!
1100 * Returns:
1101 * true - The operation was successfully queued for later completion, your callback will be called later
1102 * false - The operation could not be started due to the card being busy (try again later).
1104 bool sdcard_readBlock(uint32_t blockIndex, uint8_t *buffer, sdcard_operationCompleteCallback_c callback, uint32_t callbackData)
1106 if (sdcard.state != SDCARD_STATE_READY) {
1107 if (sdcard.state == SDCARD_STATE_WRITING_MULTIPLE_BLOCKS) {
1108 if (sdcard_endWriteBlocks() != SDCARD_OPERATION_SUCCESS) {
1109 return false;
1111 } else {
1112 return false;
1116 #ifdef SDCARD_PROFILING
1117 sdcard.pendingOperation.profileStartTime = micros();
1118 #endif
1120 sdcard_select();
1122 // Standard size cards use byte addressing, high capacity cards use block addressing
1123 uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_READ_SINGLE_BLOCK, sdcard.highCapacity ? blockIndex : blockIndex * SDCARD_BLOCK_SIZE);
1125 if (status == 0) {
1126 sdcard.pendingOperation.buffer = buffer;
1127 sdcard.pendingOperation.blockIndex = blockIndex;
1128 sdcard.pendingOperation.callback = callback;
1129 sdcard.pendingOperation.callbackData = callbackData;
1131 sdcard.state = SDCARD_STATE_READING;
1133 sdcard.operationStartTime = millis();
1135 // Leave the card selected for the whole transaction
1137 return true;
1138 } else {
1139 sdcard_deselect();
1141 return false;
1146 * Returns true if the SD card has successfully completed its startup procedures.
1148 bool sdcard_isInitialized(void)
1150 return sdcard.state >= SDCARD_STATE_READY;
1153 const sdcardMetadata_t* sdcard_getMetadata(void)
1155 return &sdcard.metadata;
1158 #ifdef SDCARD_PROFILING
1160 void sdcard_setProfilerCallback(sdcard_profilerCallback_c callback)
1162 sdcard.profiler = callback;
1165 #endif
1167 #endif