Ditching default target for `make` in favour of `make all` (#14099)
[betaflight.git] / src / main / drivers / sdcard_spi.c
blob33a038eb8a9a9bf7724cdf096fbb05cc742adad1
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_SPI
28 #include "drivers/bus_spi.h"
29 #include "drivers/dma.h"
30 #include "drivers/dma_reqmap.h"
31 #include "drivers/io.h"
32 #include "drivers/nvic.h"
33 #include "drivers/time.h"
35 #include "pg/bus_spi.h"
36 #include "pg/sdcard.h"
38 #include "sdcard.h"
39 #include "sdcard_impl.h"
40 #include "sdcard_standard.h"
42 #ifdef AFATFS_USE_INTROSPECTIVE_LOGGING
43 #define SDCARD_PROFILING
44 #endif
46 #define SDCARD_INIT_NUM_DUMMY_BYTES 10
47 #define SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY 8
48 // Chosen so that CMD8 will have the same CRC as CMD0:
49 #define SDCARD_IF_COND_CHECK_PATTERN 0xAB
51 /* Spec calls for under 400KHz */
52 #define SDCARD_MAX_SPI_INIT_CLK_HZ 400000
54 /* Operational speed <= 25MHz */
55 #define SDCARD_MAX_SPI_CLK_HZ 25000000
57 #define SDCARD_SPI_MODE SPI_MODE0_POL_LOW_EDGE_1ST
58 //#define SDCARD_SPI_MODE SPI_MODE3_POL_HIGH_EDGE_2ND
60 /* Break up 512-byte SD card sectors into chunks of this size when writing without DMA to reduce the peak overhead
61 * per call to sdcard_poll().
63 #define SDCARD_NON_DMA_CHUNK_SIZE 256
65 /**
66 * Returns true if the card has already been, or is currently, initializing and hasn't encountered enough errors to
67 * trip our error threshold and be disabled (i.e. our card is in and working!)
69 static bool sdcardSpi_isFunctional(void)
71 return sdcard.state != SDCARD_STATE_NOT_PRESENT;
74 static void sdcard_deselect(void)
76 // As per the SD-card spec, give the card 8 dummy clocks so it can finish its operation
77 //spiReadWrite(&sdcard.dev, 0xFF);
79 spiWait(&sdcard.dev);
81 delayMicroseconds(10);
83 // Negate CS
84 spiRelease(&sdcard.dev);
87 /**
88 * Handle a failure of an SD card operation by resetting the card back to its initialization phase.
90 * Increments the failure counter, and when the failure threshold is reached, disables the card until
91 * the next call to sdcard_init().
93 static void sdcard_reset(void)
95 if (!sdcard_isInserted()) {
96 sdcard.state = SDCARD_STATE_NOT_PRESENT;
97 return;
100 if (sdcard.state >= SDCARD_STATE_READY) {
101 spiSetClkDivisor(&sdcard.dev, spiCalculateDivider(SDCARD_MAX_SPI_INIT_CLK_HZ));
104 sdcard.failureCount++;
105 if (sdcard.failureCount >= SDCARD_MAX_CONSECUTIVE_FAILURES) {
106 sdcard.state = SDCARD_STATE_NOT_PRESENT;
107 } else {
108 sdcard.operationStartTime = millis();
109 sdcard.state = SDCARD_STATE_RESET;
113 // Called in ISR context
114 // Wait until idle indicated by a read value of SDCARD_IDLE_TOKEN
115 busStatus_e sdcard_callbackIdle(uint32_t arg)
117 sdcard_t *sdcard = (sdcard_t *)arg;
118 extDevice_t *dev = &sdcard->dev;
120 uint8_t idleByte = dev->bus->curSegment->u.buffers.rxData[0];
122 if (idleByte == SDCARD_IDLE_TOKEN) {
123 // Default for next call to sdcard_callbackNotIdle()
124 sdcard->idleCount = SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY;
125 return BUS_READY;
128 if (--sdcard->idleCount <= 0) {
129 dev->bus->curSegment->u.buffers.rxData[0] = 0x00;
130 return BUS_ABORT;
133 return BUS_BUSY;
136 // Called in ISR context
137 // Wait until idle is no longer indicated by a read value of SDCARD_IDLE_TOKEN
138 busStatus_e sdcard_callbackNotIdle(uint32_t arg)
140 sdcard_t *sdcard = (sdcard_t *)arg;
141 extDevice_t *dev = &sdcard->dev;
143 uint8_t idleByte = dev->bus->curSegment->u.buffers.rxData[0];
145 if (idleByte != SDCARD_IDLE_TOKEN) {
146 return BUS_READY;
149 if (sdcard->idleCount-- <= 0) {
150 return BUS_ABORT;
153 return BUS_BUSY;
157 * The SD card spec requires 8 clock cycles to be sent by us on the bus after most commands so it can finish its
158 * processing of that command. The easiest way for us to do this is to just wait for the bus to become idle before
159 * we transmit a command, sending at least 8-bits onto the bus when we do so.
161 static bool sdcard_waitForIdle(int maxBytesToWait)
163 uint8_t idleByte;
165 // Note that this does not release the CS at the end of the transaction
166 busSegment_t segments[] = {
167 {.u.buffers = {NULL, &idleByte}, sizeof(idleByte), false, sdcard_callbackIdle},
168 {.u.link = {NULL, NULL}, 0, true, NULL},
172 sdcard.idleCount = maxBytesToWait;
174 spiSequence(&sdcard.dev, &segments[0]);
176 // Block pending completion of SPI access
177 spiWait(&sdcard.dev);
179 return (idleByte == SDCARD_IDLE_TOKEN);
183 * Wait for up to maxDelay SDCARD_IDLE_TOKEN idle bytes to arrive from the card, returning the first non-idle byte found.
185 * Returns 0xFF on failure.
187 static uint8_t sdcard_waitForNonIdleByte(int maxDelay)
189 uint8_t idleByte;
191 // Note that this does not release the CS at the end of the transaction
192 busSegment_t segments[] = {
193 {.u.buffers = {NULL, &idleByte}, sizeof(idleByte), false, sdcard_callbackNotIdle},
194 {.u.link = {NULL, NULL}, 0, true, NULL},
198 sdcard.idleCount = maxDelay;
200 spiSequence(&sdcard.dev, &segments[0]);
202 // Block pending completion of SPI access
203 spiWait(&sdcard.dev);
205 return idleByte;
209 * Waits up to SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY bytes for the card to become ready, send a command to the card
210 * with the given argument, waits up to SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY bytes for a reply, and returns the
211 * first non-0xFF byte of the reply.
213 * Upon failure, -1 is returned.
215 static int sdcard_sendCommand(uint8_t commandCode, uint32_t commandArgument)
217 uint8_t command[6] = {
218 0x40 | commandCode,
219 commandArgument >> 24,
220 commandArgument >> 16,
221 commandArgument >> 8,
222 commandArgument,
223 0x95 /* Static CRC. This CRC is valid for CMD0 with a 0 argument, and CMD8 with 0x1AB argument, which are the only
224 commands that require a CRC */
227 uint8_t idleByte;
228 uint8_t cmdResponse;
230 // Note that this does not release the CS at the end of the transaction
231 busSegment_t segments[] = {
232 {.u.buffers = {NULL, &idleByte}, sizeof(idleByte), false, sdcard_callbackIdle},
233 {.u.buffers = {command, NULL}, sizeof(command), false, NULL},
234 {.u.buffers = {NULL, &cmdResponse}, sizeof(cmdResponse), false, sdcard_callbackNotIdle},
235 {.u.link = {NULL, NULL}, 0, true, NULL},
239 sdcard.idleCount = SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY;
241 spiSequence(&sdcard.dev, &segments[0]);
243 // Block pending completion of SPI access
244 spiWait(&sdcard.dev);
246 if ((idleByte != SDCARD_IDLE_TOKEN) && commandCode != SDCARD_COMMAND_GO_IDLE_STATE) {
247 return -1;
250 return cmdResponse;
253 static uint8_t sdcard_sendAppCommand(uint8_t commandCode, uint32_t commandArgument)
255 sdcard_sendCommand(SDCARD_COMMAND_APP_CMD, 0);
257 return sdcard_sendCommand(commandCode, commandArgument);
261 * Sends an IF_COND message to the card to check its version and validate its voltage requirements. Sets the global
262 * sdCardVersion with the detected version (0, 1, or 2) and returns true if the card is compatible.
264 static bool sdcard_validateInterfaceCondition(void)
266 uint8_t ifCondReply[4];
268 sdcard.version = 0;
270 uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_SEND_IF_COND, (SDCARD_VOLTAGE_ACCEPTED_2_7_to_3_6 << 8) | SDCARD_IF_COND_CHECK_PATTERN);
272 // Don't deselect the card right away, because we'll want to read the rest of its reply if it's a V2 card
274 if (status == (SDCARD_R1_STATUS_BIT_ILLEGAL_COMMAND | SDCARD_R1_STATUS_BIT_IDLE)) {
275 // V1 cards don't support this command
276 sdcard.version = 1;
277 } else if (status == SDCARD_R1_STATUS_BIT_IDLE) {
278 // Note that this does not release the CS at the end of the transaction
279 busSegment_t segments[] = {
280 {.u.buffers = {NULL, ifCondReply}, sizeof(ifCondReply), false, NULL},
281 {.u.link = {NULL, NULL}, 0, true, NULL},
285 spiSequence(&sdcard.dev, &segments[0]);
287 // Block pending completion of SPI access
288 spiWait(&sdcard.dev);
291 * We don't bother to validate the SDCard's operating voltage range since the spec requires it to accept our
292 * 3.3V, but do check that it echoed back our check pattern properly.
294 if (ifCondReply[3] == SDCARD_IF_COND_CHECK_PATTERN) {
295 sdcard.version = 2;
299 sdcard_deselect();
301 return sdcard.version > 0;
304 static bool sdcard_readOCRRegister(uint32_t *result)
306 uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_READ_OCR, 0);
308 uint8_t response[4];
310 // Note that this does not release the CS at the end of the transaction
311 busSegment_t segments[] = {
312 {.u.buffers = {NULL, response}, sizeof(response), false, NULL},
313 {.u.link = {NULL, NULL}, 0, true, NULL},
317 spiSequence(&sdcard.dev, &segments[0]);
319 // Block pending completion of SPI access
320 spiWait(&sdcard.dev);
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;
341 /// Called in ISR context
342 // Wait until the arrival of the SDCARD_SINGLE_BLOCK_READ_START_TOKEN token
343 busStatus_e sdcard_callbackNotIdleDataBlock(uint32_t arg)
345 sdcard_t *sdcard = (sdcard_t *)arg;
346 extDevice_t *dev = &sdcard->dev;
348 uint8_t idleByte = dev->bus->curSegment->u.buffers.rxData[0];
350 if (idleByte == SDCARD_SINGLE_BLOCK_READ_START_TOKEN) {
351 return BUS_READY;
354 if (idleByte != SDCARD_IDLE_TOKEN) {
355 return BUS_ABORT;
358 if (sdcard->idleCount-- <= 0) {
359 return BUS_ABORT;
362 return BUS_BUSY;
366 * Attempt to receive a data block from the SD card.
368 * Return true on success, otherwise the card has not responded yet and you should retry later.
370 static sdcardReceiveBlockStatus_e sdcard_receiveDataBlock(uint8_t *buffer, int count)
372 uint8_t dataToken;
374 sdcard.idleCount = 8;
376 // Note that this does not release the CS at the end of the transaction
377 busSegment_t segments[] = {
378 {.u.buffers = {NULL, &dataToken}, sizeof(dataToken), false, sdcard_callbackNotIdleDataBlock},
379 {.u.buffers = {NULL, buffer}, count, false, NULL},
380 // Discard trailing CRC, we don't care
381 {.u.buffers = {NULL, NULL}, 2, false, NULL},
382 {.u.link = {NULL, NULL}, 0, true, NULL},
386 spiSequence(&sdcard.dev, &segments[0]);
388 // Block pending completion of SPI access
389 spiWait(&sdcard.dev);
391 switch (dataToken) {
392 case SDCARD_IDLE_TOKEN:
393 return SDCARD_RECEIVE_BLOCK_IN_PROGRESS;
394 case SDCARD_SINGLE_BLOCK_READ_START_TOKEN:
395 return SDCARD_RECEIVE_SUCCESS;
396 default:
397 return SDCARD_RECEIVE_ERROR;
401 static bool sdcard_sendDataBlockFinish(void)
403 uint16_t dummyCRC = 0;
404 uint8_t dataResponseToken;
405 // Note that this does not release the CS at the end of the transaction
406 busSegment_t segments[] = {
407 {.u.buffers = {(uint8_t *)&dummyCRC, NULL}, sizeof(dummyCRC), false, NULL},
408 {.u.buffers = {NULL, &dataResponseToken}, sizeof(dataResponseToken), false, NULL},
409 {.u.link = {NULL, NULL}, 0, true, NULL},
413 spiSequence(&sdcard.dev, &segments[0]);
415 // Block pending completion of SPI access
416 spiWait(&sdcard.dev);
419 * Check if the card accepted the write (no CRC error / no address error)
421 * The lower 5 bits are structured as follows:
422 * | 0 | Status | 1 |
423 * | 0 | x x x | 1 |
425 * Statuses:
426 * 010 - Data accepted
427 * 101 - CRC error
428 * 110 - Write error
430 return (dataResponseToken & 0x1F) == 0x05;
434 * Begin sending a buffer of SDCARD_BLOCK_SIZE bytes to the SD card.
436 static void sdcard_sendDataBlockBegin(uint8_t *buffer, bool multiBlockWrite)
438 static uint8_t token;
440 token = multiBlockWrite ? SDCARD_MULTIPLE_BLOCK_WRITE_START_TOKEN : SDCARD_SINGLE_BLOCK_WRITE_START_TOKEN;
442 // Note that this does not release the CS at the end of the transaction
443 static busSegment_t segments[] = {
444 // Write a single 0xff
445 {.u.buffers = {NULL, NULL}, 1, false, NULL},
446 {.u.buffers = {&token, NULL}, sizeof(token), false, NULL},
447 {.u.buffers = {NULL, NULL}, 0, false, NULL},
448 {.u.link = {NULL, NULL}, 0, true, NULL},
452 segments[2].u.buffers.txData = buffer;
453 segments[2].len = spiUseDMA(&sdcard.dev) ? SDCARD_BLOCK_SIZE : SDCARD_NON_DMA_CHUNK_SIZE;
455 spiSequence(&sdcard.dev, &segments[0]);
457 // Don't block pending completion of SPI access
460 static bool sdcard_receiveCID(void)
462 uint8_t cid[16];
464 if (sdcard_receiveDataBlock(cid, sizeof(cid)) != SDCARD_RECEIVE_SUCCESS) {
465 return false;
468 sdcard.metadata.manufacturerID = cid[0];
469 sdcard.metadata.oemID = (cid[1] << 8) | cid[2];
470 sdcard.metadata.productName[0] = cid[3];
471 sdcard.metadata.productName[1] = cid[4];
472 sdcard.metadata.productName[2] = cid[5];
473 sdcard.metadata.productName[3] = cid[6];
474 sdcard.metadata.productName[4] = cid[7];
475 sdcard.metadata.productRevisionMajor = cid[8] >> 4;
476 sdcard.metadata.productRevisionMinor = cid[8] & 0x0F;
477 sdcard.metadata.productSerial = (cid[9] << 24) | (cid[10] << 16) | (cid[11] << 8) | cid[12];
478 sdcard.metadata.productionYear = (((cid[13] & 0x0F) << 4) | (cid[14] >> 4)) + 2000;
479 sdcard.metadata.productionMonth = cid[14] & 0x0F;
481 return true;
484 static bool sdcard_fetchCSD(void)
486 uint32_t readBlockLen, blockCount, blockCountMult;
487 uint64_t capacityBytes;
489 /* The CSD command's data block should always arrive within 8 idle clock cycles (SD card spec). This is because
490 * the information about card latency is stored in the CSD register itself, so we can't use that yet!
492 bool success =
493 sdcard_sendCommand(SDCARD_COMMAND_SEND_CSD, 0) == 0
494 && sdcard_receiveDataBlock((uint8_t*) &sdcard.csd, sizeof(sdcard.csd)) == SDCARD_RECEIVE_SUCCESS
495 && SDCARD_GET_CSD_FIELD(sdcard.csd, 1, TRAILER) == 1;
497 if (success) {
498 switch (SDCARD_GET_CSD_FIELD(sdcard.csd, 1, CSD_STRUCTURE_VER)) {
499 case SDCARD_CSD_STRUCTURE_VERSION_1:
500 // Block size in bytes (doesn't have to be 512)
501 readBlockLen = 1 << SDCARD_GET_CSD_FIELD(sdcard.csd, 1, READ_BLOCK_LEN);
502 blockCountMult = 1 << (SDCARD_GET_CSD_FIELD(sdcard.csd, 1, CSIZE_MULT) + 2);
503 blockCount = (SDCARD_GET_CSD_FIELD(sdcard.csd, 1, CSIZE) + 1) * blockCountMult;
505 // We could do this in 32 bits but it makes the 2GB case awkward
506 capacityBytes = (uint64_t) blockCount * readBlockLen;
508 // Re-express that capacity (max 2GB) in our standard 512-byte block size
509 sdcard.metadata.numBlocks = capacityBytes / SDCARD_BLOCK_SIZE;
510 break;
511 case SDCARD_CSD_STRUCTURE_VERSION_2:
512 sdcard.metadata.numBlocks = (SDCARD_GET_CSD_FIELD(sdcard.csd, 2, CSIZE) + 1) * 1024;
513 break;
514 default:
515 success = false;
519 sdcard_deselect();
521 return success;
525 * Check if the SD Card has completed its startup sequence. Must be called with sdcard.state == SDCARD_STATE_INITIALIZATION.
527 * Returns true if the card has finished its init process.
529 static bool sdcard_checkInitDone(void)
531 uint8_t status = sdcard_sendAppCommand(SDCARD_ACOMMAND_SEND_OP_COND, sdcard.version == 2 ? 1 << 30 /* We support high capacity cards */ : 0);
533 sdcard_deselect();
535 // When card init is complete, the idle bit in the response becomes zero.
536 return status == 0x00;
539 void sdcardSpi_preInit(const sdcardConfig_t *config)
541 spiPreinitRegister(config->chipSelectTag, IOCFG_IPU, 1);
545 * Begin the initialization process for the SD card. This must be called first before any other sdcard_ routine.
547 static void sdcardSpi_init(const sdcardConfig_t *config, const spiPinConfig_t *spiConfig)
549 UNUSED(spiConfig);
551 sdcard.enabled = config->mode;
552 if (!sdcard.enabled) {
553 sdcard.state = SDCARD_STATE_NOT_PRESENT;
554 return;
557 spiSetBusInstance(&sdcard.dev, config->device);
559 IO_t chipSelectIO;
560 if (config->chipSelectTag) {
561 chipSelectIO = IOGetByTag(config->chipSelectTag);
562 IOInit(chipSelectIO, OWNER_SDCARD_CS, 0);
563 IOConfigGPIO(chipSelectIO, SPI_IO_CS_HIGH_CFG);
564 } else {
565 chipSelectIO = IO_NONE;
567 sdcard.dev.busType_u.spi.csnPin = chipSelectIO;
569 // Set the clock phase/polarity
570 spiSetClkPhasePolarity(&sdcard.dev, true);
572 // Set the callback argument when calling back to this driver for DMA completion
573 sdcard.dev.callbackArg = (uint32_t)&sdcard;
575 // Max frequency is initially 400kHz
577 spiSetClkDivisor(&sdcard.dev, spiCalculateDivider(SDCARD_MAX_SPI_INIT_CLK_HZ));
579 // SDCard wants 1ms minimum delay after power is applied to it
580 delay(1000);
582 // Transmit at least 74 dummy clock cycles with CS high so the SD card can start up
583 IOHi(sdcard.dev.busType_u.spi.csnPin);
585 // Note that CS is not asserted for this transaction
586 busSegment_t segments[] = {
587 // Write a single 0xff
588 {.u.buffers = {NULL, NULL}, SDCARD_INIT_NUM_DUMMY_BYTES, true, NULL},
589 {.u.link = {NULL, NULL}, 0, true, NULL},
592 spiSequence(&sdcard.dev, &segments[0]);
594 // Block pending completion of SPI access
595 spiWait(&sdcard.dev);
597 // Enable the CS line
598 if (chipSelectIO != IO_NONE) {
599 IOConfigGPIO(chipSelectIO, SPI_IO_CS_CFG);
602 sdcard.operationStartTime = millis();
603 sdcard.state = SDCARD_STATE_RESET;
604 sdcard.failureCount = 0;
607 static bool sdcard_setBlockLength(uint32_t blockLen)
609 uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_SET_BLOCKLEN, blockLen);
611 sdcard_deselect();
613 return status == 0;
617 * Returns true if the card is ready to accept read/write commands.
619 static bool sdcard_isReady(void)
621 return sdcard.state == SDCARD_STATE_READY || sdcard.state == SDCARD_STATE_WRITING_MULTIPLE_BLOCKS;
625 * Send the stop-transmission token to complete a multi-block write.
627 * Returns:
628 * SDCARD_OPERATION_IN_PROGRESS - We're now waiting for that stop to complete, the card will enter
629 * the SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE state.
630 * SDCARD_OPERATION_SUCCESS - The multi-block write finished immediately, the card will enter
631 * the SDCARD_READY state.
634 static sdcardOperationStatus_e sdcard_endWriteBlocks(void)
636 uint8_t token = SDCARD_MULTIPLE_BLOCK_WRITE_STOP_TOKEN;
637 sdcard.multiWriteBlocksRemain = 0;
639 // Note that this does not release the CS at the end of the transaction
640 busSegment_t segments[] = {
641 // 8 dummy clocks to guarantee N_WR clocks between the last card response and this token
642 {.u.buffers = {NULL, NULL}, 1, false, NULL},
643 {.u.buffers = {&token, NULL}, sizeof(token), false, NULL},
644 {.u.link = {NULL, NULL}, 0, true, NULL},
648 spiSequence(&sdcard.dev, &segments[0]);
650 // Block pending completion of SPI access
651 spiWait(&sdcard.dev);
653 // Card may choose to raise a busy (non-SDCARD_IDLE_TOKEN) signal after at most N_BR (1 byte) delay
654 if (sdcard_waitForNonIdleByte(1) == SDCARD_IDLE_TOKEN) {
655 sdcard.state = SDCARD_STATE_READY;
656 return SDCARD_OPERATION_SUCCESS;
657 } else {
658 sdcard.state = SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE;
659 sdcard.operationStartTime = millis();
661 return SDCARD_OPERATION_IN_PROGRESS;
666 * Call periodically for the SD card to perform in-progress transfers.
668 * Returns true if the card is ready to accept commands.
670 static bool sdcardSpi_poll(void)
672 if (!sdcard.enabled) {
673 sdcard.state = SDCARD_STATE_NOT_PRESENT;
674 return false;
677 uint8_t initStatus;
678 bool sendComplete;
680 #ifdef SDCARD_PROFILING
681 bool profilingComplete;
682 #endif
684 doMore:
685 switch (sdcard.state) {
686 case SDCARD_STATE_RESET:
687 initStatus = sdcard_sendCommand(SDCARD_COMMAND_GO_IDLE_STATE, 0);
689 sdcard_deselect();
691 if (initStatus == SDCARD_R1_STATUS_BIT_IDLE) {
692 // Check card voltage and version
693 if (sdcard_validateInterfaceCondition()) {
695 sdcard.state = SDCARD_STATE_CARD_INIT_IN_PROGRESS;
696 goto doMore;
697 } else {
698 // Bad reply/voltage, we ought to refrain from accessing the card.
699 sdcard.state = SDCARD_STATE_NOT_PRESENT;
702 break;
704 case SDCARD_STATE_CARD_INIT_IN_PROGRESS:
705 if (sdcard_checkInitDone()) {
706 if (sdcard.version == 2) {
707 // Check for high capacity card
708 uint32_t ocr;
710 if (!sdcard_readOCRRegister(&ocr)) {
711 sdcard_reset();
712 goto doMore;
715 sdcard.highCapacity = (ocr & (1 << 30)) != 0;
716 } else {
717 // Version 1 cards are always low-capacity
718 sdcard.highCapacity = false;
721 // Now fetch the CSD and CID registers
722 if (sdcard_fetchCSD()) {
723 uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_SEND_CID, 0);
725 if (status == 0) {
726 // Keep the card selected to receive the response block
727 sdcard.state = SDCARD_STATE_INITIALIZATION_RECEIVE_CID;
728 goto doMore;
729 } else {
730 sdcard_deselect();
732 sdcard_reset();
733 goto doMore;
737 break;
738 case SDCARD_STATE_INITIALIZATION_RECEIVE_CID:
739 if (sdcard_receiveCID()) {
740 sdcard_deselect();
742 /* The spec is a little iffy on what the default block size is for Standard Size cards (it can be changed on
743 * standard size cards) so let's just set it to 512 explicitly so we don't have a problem.
745 if (!sdcard.highCapacity && !sdcard_setBlockLength(SDCARD_BLOCK_SIZE)) {
746 sdcard_reset();
747 goto doMore;
750 // Now we're done with init and we can switch to the full speed clock (<25MHz)
752 spiSetClkDivisor(&sdcard.dev, spiCalculateDivider(SDCARD_MAX_SPI_CLK_HZ));
754 sdcard.multiWriteBlocksRemain = 0;
756 sdcard.state = SDCARD_STATE_READY;
757 goto doMore;
758 } // else keep waiting for the CID to arrive
759 break;
760 case SDCARD_STATE_SENDING_WRITE:
761 // Have we finished sending the write yet?
762 sendComplete = !spiIsBusy(&sdcard.dev);
764 if (!spiUseDMA(&sdcard.dev)) {
765 // Send another chunk
766 spiReadWriteBuf(&sdcard.dev, sdcard.pendingOperation.buffer + SDCARD_NON_DMA_CHUNK_SIZE * sdcard.pendingOperation.chunkIndex, NULL, SDCARD_NON_DMA_CHUNK_SIZE);
768 sdcard.pendingOperation.chunkIndex++;
770 sendComplete = sdcard.pendingOperation.chunkIndex == SDCARD_BLOCK_SIZE / SDCARD_NON_DMA_CHUNK_SIZE;
773 if (sendComplete) {
774 // Finish up by sending the CRC and checking the SD-card's acceptance/rejectance
775 if (sdcard_sendDataBlockFinish()) {
776 // The SD card is now busy committing that write to the card
777 sdcard.state = SDCARD_STATE_WAITING_FOR_WRITE;
778 sdcard.operationStartTime = millis();
780 // Since we've transmitted the buffer we can go ahead and tell the caller their operation is complete
781 if (sdcard.pendingOperation.callback) {
782 sdcard.pendingOperation.callback(SDCARD_BLOCK_OPERATION_WRITE, sdcard.pendingOperation.blockIndex, sdcard.pendingOperation.buffer, sdcard.pendingOperation.callbackData);
784 } else {
785 /* Our write was rejected! This could be due to a bad address but we hope not to attempt that, so assume
786 * the card is broken and needs reset.
788 sdcard_reset();
790 // Announce write failure:
791 if (sdcard.pendingOperation.callback) {
792 sdcard.pendingOperation.callback(SDCARD_BLOCK_OPERATION_WRITE, sdcard.pendingOperation.blockIndex, NULL, sdcard.pendingOperation.callbackData);
795 goto doMore;
798 break;
799 case SDCARD_STATE_WAITING_FOR_WRITE:
800 if (sdcard_waitForIdle(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY)) {
801 #ifdef SDCARD_PROFILING
802 profilingComplete = true;
803 #endif
805 sdcard.failureCount = 0; // Assume the card is good if it can complete a write
807 // Still more blocks left to write in a multi-block chain?
808 if (sdcard.multiWriteBlocksRemain > 1) {
809 sdcard.multiWriteBlocksRemain--;
810 sdcard.multiWriteNextBlock++;
811 sdcard.state = SDCARD_STATE_WRITING_MULTIPLE_BLOCKS;
812 } else if (sdcard.multiWriteBlocksRemain == 1) {
813 // This function changes the sd card state for us whether immediately succesful or delayed:
814 if (sdcard_endWriteBlocks() == SDCARD_OPERATION_SUCCESS) {
815 sdcard_deselect();
816 } else {
817 #ifdef SDCARD_PROFILING
818 // Wait for the multi-block write to be terminated before finishing timing
819 profilingComplete = false;
820 #endif
822 } else {
823 sdcard.state = SDCARD_STATE_READY;
824 sdcard_deselect();
827 #ifdef SDCARD_PROFILING
828 if (profilingComplete && sdcard.profiler) {
829 sdcard.profiler(SDCARD_BLOCK_OPERATION_WRITE, sdcard.pendingOperation.blockIndex, micros() - sdcard.pendingOperation.profileStartTime);
831 #endif
832 } else if (millis() > sdcard.operationStartTime + SDCARD_TIMEOUT_WRITE_MSEC) {
834 * The caller has already been told that their write has completed, so they will have discarded
835 * their buffer and have no hope of retrying the operation. But this should be very rare and it allows
836 * them to reuse their buffer milliseconds faster than they otherwise would.
838 sdcard_reset();
839 goto doMore;
841 break;
842 case SDCARD_STATE_READING:
843 switch (sdcard_receiveDataBlock(sdcard.pendingOperation.buffer, SDCARD_BLOCK_SIZE)) {
844 case SDCARD_RECEIVE_SUCCESS:
845 sdcard_deselect();
847 sdcard.state = SDCARD_STATE_READY;
848 sdcard.failureCount = 0; // Assume the card is good if it can complete a read
850 #ifdef SDCARD_PROFILING
851 if (sdcard.profiler) {
852 sdcard.profiler(SDCARD_BLOCK_OPERATION_READ, sdcard.pendingOperation.blockIndex, micros() - sdcard.pendingOperation.profileStartTime);
854 #endif
856 if (sdcard.pendingOperation.callback) {
857 sdcard.pendingOperation.callback(
858 SDCARD_BLOCK_OPERATION_READ,
859 sdcard.pendingOperation.blockIndex,
860 sdcard.pendingOperation.buffer,
861 sdcard.pendingOperation.callbackData
864 break;
865 case SDCARD_RECEIVE_BLOCK_IN_PROGRESS:
866 if (millis() <= sdcard.operationStartTime + SDCARD_TIMEOUT_READ_MSEC) {
867 break; // Timeout not reached yet so keep waiting
869 // Timeout has expired, so fall through to convert to a fatal error
870 FALLTHROUGH;
872 case SDCARD_RECEIVE_ERROR:
873 sdcard_deselect();
875 sdcard_reset();
877 if (sdcard.pendingOperation.callback) {
878 sdcard.pendingOperation.callback(
879 SDCARD_BLOCK_OPERATION_READ,
880 sdcard.pendingOperation.blockIndex,
881 NULL,
882 sdcard.pendingOperation.callbackData
886 goto doMore;
887 break;
889 break;
890 case SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE:
891 if (sdcard_waitForIdle(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY)) {
892 sdcard_deselect();
894 sdcard.state = SDCARD_STATE_READY;
896 #ifdef SDCARD_PROFILING
897 if (sdcard.profiler) {
898 sdcard.profiler(SDCARD_BLOCK_OPERATION_WRITE, sdcard.pendingOperation.blockIndex, micros() - sdcard.pendingOperation.profileStartTime);
900 #endif
901 } else if (millis() > sdcard.operationStartTime + SDCARD_TIMEOUT_WRITE_MSEC) {
902 sdcard_reset();
903 goto doMore;
905 break;
906 case SDCARD_STATE_NOT_PRESENT:
907 default:
911 // Is the card's initialization taking too long?
912 if (sdcard.state >= SDCARD_STATE_RESET && sdcard.state < SDCARD_STATE_READY
913 && millis() - sdcard.operationStartTime > SDCARD_TIMEOUT_INIT_MILLIS) {
914 sdcard_reset();
917 return sdcard_isReady();
921 * Write the 512-byte block from the given buffer into the block with the given index.
923 * If the write does not complete immediately, your callback will be called later. If the write was successful, the
924 * buffer pointer will be the same buffer you originally passed in, otherwise the buffer will be set to NULL.
926 * Returns:
927 * SDCARD_OPERATION_IN_PROGRESS - Your buffer is currently being transmitted to the card and your callback will be
928 * called later to report the completion. The buffer pointer must remain valid until
929 * that time.
930 * SDCARD_OPERATION_SUCCESS - Your buffer has been transmitted to the card now.
931 * SDCARD_OPERATION_BUSY - The card is already busy and cannot accept your write
932 * SDCARD_OPERATION_FAILURE - Your write was rejected by the card, card will be reset
934 static sdcardOperationStatus_e sdcardSpi_writeBlock(uint32_t blockIndex, uint8_t *buffer, sdcard_operationCompleteCallback_c callback, uint32_t callbackData)
936 uint8_t status;
938 #ifdef SDCARD_PROFILING
939 sdcard.pendingOperation.profileStartTime = micros();
940 #endif
942 doMore:
943 switch (sdcard.state) {
944 case SDCARD_STATE_WRITING_MULTIPLE_BLOCKS:
945 // Do we need to cancel the previous multi-block write?
946 if (blockIndex != sdcard.multiWriteNextBlock) {
947 if (sdcard_endWriteBlocks() == SDCARD_OPERATION_SUCCESS) {
948 // Now we've entered the ready state, we can try again
949 goto doMore;
950 } else {
951 return SDCARD_OPERATION_BUSY;
955 // We're continuing a multi-block write
956 break;
957 case SDCARD_STATE_READY:
958 // We're not continuing a multi-block write so we need to send a single-block write command
959 // Standard size cards use byte addressing, high capacity cards use block addressing
960 status = sdcard_sendCommand(SDCARD_COMMAND_WRITE_BLOCK, sdcard.highCapacity ? blockIndex : blockIndex * SDCARD_BLOCK_SIZE);
962 if (status != 0) {
963 sdcard_deselect();
965 sdcard_reset();
967 return SDCARD_OPERATION_FAILURE;
969 break;
970 default:
971 return SDCARD_OPERATION_BUSY;
974 sdcard_sendDataBlockBegin(buffer, sdcard.state == SDCARD_STATE_WRITING_MULTIPLE_BLOCKS);
976 sdcard.pendingOperation.buffer = buffer;
977 sdcard.pendingOperation.blockIndex = blockIndex;
978 sdcard.pendingOperation.callback = callback;
979 sdcard.pendingOperation.callbackData = callbackData;
980 sdcard.pendingOperation.chunkIndex = 1; // (for non-DMA transfers) we've sent chunk #0 already
981 sdcard.state = SDCARD_STATE_SENDING_WRITE;
983 return SDCARD_OPERATION_IN_PROGRESS;
987 * Begin writing a series of consecutive blocks beginning at the given block index. This will allow (but not require)
988 * the SD card to pre-erase the number of blocks you specifiy, which can allow the writes to complete faster.
990 * Afterwards, just call sdcard_writeBlock() as normal to write those blocks consecutively.
992 * It's okay to abort the multi-block write at any time by writing to a non-consecutive address, or by performing a read.
994 * Returns:
995 * SDCARD_OPERATION_SUCCESS - Multi-block write has been queued
996 * SDCARD_OPERATION_BUSY - The card is already busy and cannot accept your write
997 * SDCARD_OPERATION_FAILURE - A fatal error occured, card will be reset
999 static sdcardOperationStatus_e sdcardSpi_beginWriteBlocks(uint32_t blockIndex, uint32_t blockCount)
1001 if (sdcard.state != SDCARD_STATE_READY) {
1002 if (sdcard.state == SDCARD_STATE_WRITING_MULTIPLE_BLOCKS) {
1003 if (blockIndex == sdcard.multiWriteNextBlock) {
1004 // Assume that the caller wants to continue the multi-block write they already have in progress!
1005 return SDCARD_OPERATION_SUCCESS;
1006 } else if (sdcard_endWriteBlocks() != SDCARD_OPERATION_SUCCESS) {
1007 return SDCARD_OPERATION_BUSY;
1008 } // Else we've completed the previous multi-block write and can fall through to start the new one
1009 } else {
1010 return SDCARD_OPERATION_BUSY;
1014 if (
1015 sdcard_sendAppCommand(SDCARD_ACOMMAND_SET_WR_BLOCK_ERASE_COUNT, blockCount) == 0
1016 && sdcard_sendCommand(SDCARD_COMMAND_WRITE_MULTIPLE_BLOCK, sdcard.highCapacity ? blockIndex : blockIndex * SDCARD_BLOCK_SIZE) == 0
1018 sdcard.state = SDCARD_STATE_WRITING_MULTIPLE_BLOCKS;
1019 sdcard.multiWriteBlocksRemain = blockCount;
1020 sdcard.multiWriteNextBlock = blockIndex;
1022 // Leave the card selected
1023 return SDCARD_OPERATION_SUCCESS;
1024 } else {
1025 sdcard_deselect();
1027 sdcard_reset();
1029 return SDCARD_OPERATION_FAILURE;
1034 * Read the 512-byte block with the given index into the given 512-byte buffer.
1036 * When the read completes, your callback will be called. If the read was successful, the buffer pointer will be the
1037 * same buffer you originally passed in, otherwise the buffer will be set to NULL.
1039 * You must keep the pointer to the buffer valid until the operation completes!
1041 * Returns:
1042 * true - The operation was successfully queued for later completion, your callback will be called later
1043 * false - The operation could not be started due to the card being busy (try again later).
1045 static bool sdcardSpi_readBlock(uint32_t blockIndex, uint8_t *buffer, sdcard_operationCompleteCallback_c callback, uint32_t callbackData)
1047 if (sdcard.state != SDCARD_STATE_READY) {
1048 if (sdcard.state == SDCARD_STATE_WRITING_MULTIPLE_BLOCKS) {
1049 if (sdcard_endWriteBlocks() != SDCARD_OPERATION_SUCCESS) {
1050 return false;
1052 } else {
1053 return false;
1057 #ifdef SDCARD_PROFILING
1058 sdcard.pendingOperation.profileStartTime = micros();
1059 #endif
1061 // Standard size cards use byte addressing, high capacity cards use block addressing
1062 uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_READ_SINGLE_BLOCK, sdcard.highCapacity ? blockIndex : blockIndex * SDCARD_BLOCK_SIZE);
1064 if (status == 0) {
1065 sdcard.pendingOperation.buffer = buffer;
1066 sdcard.pendingOperation.blockIndex = blockIndex;
1067 sdcard.pendingOperation.callback = callback;
1068 sdcard.pendingOperation.callbackData = callbackData;
1070 sdcard.state = SDCARD_STATE_READING;
1072 sdcard.operationStartTime = millis();
1074 // Leave the card selected for the whole transaction
1076 return true;
1077 } else {
1078 sdcard_deselect();
1080 return false;
1085 * Returns true if the SD card has successfully completed its startup procedures.
1087 static bool sdcardSpi_isInitialized(void)
1089 return sdcard.state >= SDCARD_STATE_READY;
1092 static const sdcardMetadata_t* sdcardSpi_getMetadata(void)
1094 return &sdcard.metadata;
1097 #ifdef SDCARD_PROFILING
1099 static void sdcardSpi_setProfilerCallback(sdcard_profilerCallback_c callback)
1101 sdcard.profiler = callback;
1104 #endif
1106 sdcardVTable_t sdcardSpiVTable = {
1107 sdcardSpi_preInit,
1108 sdcardSpi_init,
1109 sdcardSpi_readBlock,
1110 sdcardSpi_beginWriteBlocks,
1111 sdcardSpi_writeBlock,
1112 sdcardSpi_poll,
1113 sdcardSpi_isFunctional,
1114 sdcardSpi_isInitialized,
1115 sdcardSpi_getMetadata,
1116 #ifdef SDCARD_PROFILING
1117 sdcardSpi_setProfilerCallback,
1118 #endif
1121 #endif