duplicate emptyline removal (#14027)
[betaflight.git] / src / main / drivers / sdcard_spi.c
blobc23ded450118431d8801fff033517beffc6955b8
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 0xff
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 == 0xff) {
123 return BUS_READY;
126 if (--sdcard->idleCount == 0) {
127 dev->bus->curSegment->u.buffers.rxData[0] = 0x00;
128 return BUS_ABORT;
131 return BUS_BUSY;
134 // Called in ISR context
135 // Wait until idle is no longer indicated by a read value of 0xff
136 busStatus_e sdcard_callbackNotIdle(uint32_t arg)
138 sdcard_t *sdcard = (sdcard_t *)arg;
139 extDevice_t *dev = &sdcard->dev;
141 uint8_t idleByte = dev->bus->curSegment->u.buffers.rxData[0];
143 if (idleByte != 0xff) {
144 return BUS_READY;
147 if (sdcard->idleCount-- == 0) {
148 return BUS_ABORT;
151 return BUS_BUSY;
155 * The SD card spec requires 8 clock cycles to be sent by us on the bus after most commands so it can finish its
156 * processing of that command. The easiest way for us to do this is to just wait for the bus to become idle before
157 * we transmit a command, sending at least 8-bits onto the bus when we do so.
159 static bool sdcard_waitForIdle(int maxBytesToWait)
161 uint8_t idleByte;
163 // Note that this does not release the CS at the end of the transaction
164 busSegment_t segments[] = {
165 {.u.buffers = {NULL, &idleByte}, sizeof(idleByte), false, sdcard_callbackIdle},
166 {.u.link = {NULL, NULL}, 0, true, NULL},
170 sdcard.idleCount = maxBytesToWait;
172 spiSequence(&sdcard.dev, &segments[0]);
174 // Block pending completion of SPI access
175 spiWait(&sdcard.dev);
177 return (idleByte == 0xff);
181 * Wait for up to maxDelay 0xFF idle bytes to arrive from the card, returning the first non-idle byte found.
183 * Returns 0xFF on failure.
185 static uint8_t sdcard_waitForNonIdleByte(int maxDelay)
187 uint8_t idleByte;
189 // Note that this does not release the CS at the end of the transaction
190 busSegment_t segments[] = {
191 {.u.buffers = {NULL, &idleByte}, sizeof(idleByte), false, sdcard_callbackNotIdle},
192 {.u.link = {NULL, NULL}, 0, true, NULL},
196 sdcard.idleCount = maxDelay;
198 spiSequence(&sdcard.dev, &segments[0]);
200 // Block pending completion of SPI access
201 spiWait(&sdcard.dev);
203 return idleByte;
207 * Waits up to SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY bytes for the card to become ready, send a command to the card
208 * with the given argument, waits up to SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY bytes for a reply, and returns the
209 * first non-0xFF byte of the reply.
211 * Upon failure, 0xFF is returned.
213 static uint8_t sdcard_sendCommand(uint8_t commandCode, uint32_t commandArgument)
215 uint8_t command[6] = {
216 0x40 | commandCode,
217 commandArgument >> 24,
218 commandArgument >> 16,
219 commandArgument >> 8,
220 commandArgument,
221 0x95 /* Static CRC. This CRC is valid for CMD0 with a 0 argument, and CMD8 with 0x1AB argument, which are the only
222 commands that require a CRC */
225 uint8_t idleByte;
227 // Note that this does not release the CS at the end of the transaction
228 busSegment_t segments[] = {
229 {.u.buffers = {command, NULL}, sizeof(command), false, NULL},
230 {.u.buffers = {NULL, &idleByte}, sizeof(idleByte), false, sdcard_callbackNotIdle},
231 {.u.link = {NULL, NULL}, 0, true, NULL},
235 if (!sdcard_waitForIdle(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY) && commandCode != SDCARD_COMMAND_GO_IDLE_STATE)
236 return 0xFF;
238 sdcard.idleCount = SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY;
240 spiSequence(&sdcard.dev, &segments[0]);
242 // Block pending completion of SPI access
243 spiWait(&sdcard.dev);
245 return idleByte;
248 static uint8_t sdcard_sendAppCommand(uint8_t commandCode, uint32_t commandArgument)
250 sdcard_sendCommand(SDCARD_COMMAND_APP_CMD, 0);
252 return sdcard_sendCommand(commandCode, commandArgument);
256 * Sends an IF_COND message to the card to check its version and validate its voltage requirements. Sets the global
257 * sdCardVersion with the detected version (0, 1, or 2) and returns true if the card is compatible.
259 static bool sdcard_validateInterfaceCondition(void)
261 uint8_t ifCondReply[4];
263 sdcard.version = 0;
265 uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_SEND_IF_COND, (SDCARD_VOLTAGE_ACCEPTED_2_7_to_3_6 << 8) | SDCARD_IF_COND_CHECK_PATTERN);
267 // Don't deselect the card right away, because we'll want to read the rest of its reply if it's a V2 card
269 if (status == (SDCARD_R1_STATUS_BIT_ILLEGAL_COMMAND | SDCARD_R1_STATUS_BIT_IDLE)) {
270 // V1 cards don't support this command
271 sdcard.version = 1;
272 } else if (status == SDCARD_R1_STATUS_BIT_IDLE) {
273 // Note that this does not release the CS at the end of the transaction
274 busSegment_t segments[] = {
275 {.u.buffers = {NULL, ifCondReply}, sizeof(ifCondReply), false, NULL},
276 {.u.link = {NULL, NULL}, 0, true, NULL},
280 spiSequence(&sdcard.dev, &segments[0]);
282 // Block pending completion of SPI access
283 spiWait(&sdcard.dev);
286 * We don't bother to validate the SDCard's operating voltage range since the spec requires it to accept our
287 * 3.3V, but do check that it echoed back our check pattern properly.
289 if (ifCondReply[3] == SDCARD_IF_COND_CHECK_PATTERN) {
290 sdcard.version = 2;
294 sdcard_deselect();
296 return sdcard.version > 0;
299 static bool sdcard_readOCRRegister(uint32_t *result)
301 uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_READ_OCR, 0);
303 uint8_t response[4];
305 // Note that this does not release the CS at the end of the transaction
306 busSegment_t segments[] = {
307 {.u.buffers = {NULL, response}, sizeof(response), false, NULL},
308 {.u.link = {NULL, NULL}, 0, true, NULL},
312 spiSequence(&sdcard.dev, &segments[0]);
314 // Block pending completion of SPI access
315 spiWait(&sdcard.dev);
317 if (status == 0) {
318 sdcard_deselect();
320 *result = (response[0] << 24) | (response[1] << 16) | (response[2] << 8) | response[3];
322 return true;
323 } else {
324 sdcard_deselect();
326 return false;
330 typedef enum {
331 SDCARD_RECEIVE_SUCCESS,
332 SDCARD_RECEIVE_BLOCK_IN_PROGRESS,
333 SDCARD_RECEIVE_ERROR
334 } sdcardReceiveBlockStatus_e;
337 * Attempt to receive a data block from the SD card.
339 * Return true on success, otherwise the card has not responded yet and you should retry later.
341 static sdcardReceiveBlockStatus_e sdcard_receiveDataBlock(uint8_t *buffer, int count)
343 uint8_t dataToken = sdcard_waitForNonIdleByte(8);
345 if (dataToken == 0xFF) {
346 return SDCARD_RECEIVE_BLOCK_IN_PROGRESS;
349 if (dataToken != SDCARD_SINGLE_BLOCK_READ_START_TOKEN) {
350 return SDCARD_RECEIVE_ERROR;
353 // Note that this does not release the CS at the end of the transaction
354 busSegment_t segments[] = {
355 {.u.buffers = {NULL, buffer}, count, false, NULL},
356 // Discard trailing CRC, we don't care
357 {.u.buffers = {NULL, NULL}, 2, false, NULL},
358 {.u.link = {NULL, NULL}, 0, true, NULL},
362 spiSequence(&sdcard.dev, &segments[0]);
364 // Block pending completion of SPI access
365 spiWait(&sdcard.dev);
367 return SDCARD_RECEIVE_SUCCESS;
370 static bool sdcard_sendDataBlockFinish(void)
372 uint16_t dummyCRC = 0;
373 uint8_t dataResponseToken;
374 // Note that this does not release the CS at the end of the transaction
375 busSegment_t segments[] = {
376 {.u.buffers = {(uint8_t *)&dummyCRC, NULL}, sizeof(dummyCRC), false, NULL},
377 {.u.buffers = {NULL, &dataResponseToken}, sizeof(dataResponseToken), false, NULL},
378 {.u.link = {NULL, NULL}, 0, true, NULL},
382 spiSequence(&sdcard.dev, &segments[0]);
384 // Block pending completion of SPI access
385 spiWait(&sdcard.dev);
388 * Check if the card accepted the write (no CRC error / no address error)
390 * The lower 5 bits are structured as follows:
391 * | 0 | Status | 1 |
392 * | 0 | x x x | 1 |
394 * Statuses:
395 * 010 - Data accepted
396 * 101 - CRC error
397 * 110 - Write error
399 return (dataResponseToken & 0x1F) == 0x05;
403 * Begin sending a buffer of SDCARD_BLOCK_SIZE bytes to the SD card.
405 static void sdcard_sendDataBlockBegin(uint8_t *buffer, bool multiBlockWrite)
407 static uint8_t token;
409 token = multiBlockWrite ? SDCARD_MULTIPLE_BLOCK_WRITE_START_TOKEN : SDCARD_SINGLE_BLOCK_WRITE_START_TOKEN;
411 // Note that this does not release the CS at the end of the transaction
412 static busSegment_t segments[] = {
413 // Write a single 0xff
414 {.u.buffers = {NULL, NULL}, 1, false, NULL},
415 {.u.buffers = {&token, NULL}, sizeof(token), false, NULL},
416 {.u.buffers = {NULL, NULL}, 0, false, NULL},
417 {.u.link = {NULL, NULL}, 0, true, NULL},
421 segments[2].u.buffers.txData = buffer;
422 segments[2].len = spiUseDMA(&sdcard.dev) ? SDCARD_BLOCK_SIZE : SDCARD_NON_DMA_CHUNK_SIZE;
424 spiSequence(&sdcard.dev, &segments[0]);
426 // Don't block pending completion of SPI access
429 static bool sdcard_receiveCID(void)
431 uint8_t cid[16];
433 if (sdcard_receiveDataBlock(cid, sizeof(cid)) != SDCARD_RECEIVE_SUCCESS) {
434 return false;
437 sdcard.metadata.manufacturerID = cid[0];
438 sdcard.metadata.oemID = (cid[1] << 8) | cid[2];
439 sdcard.metadata.productName[0] = cid[3];
440 sdcard.metadata.productName[1] = cid[4];
441 sdcard.metadata.productName[2] = cid[5];
442 sdcard.metadata.productName[3] = cid[6];
443 sdcard.metadata.productName[4] = cid[7];
444 sdcard.metadata.productRevisionMajor = cid[8] >> 4;
445 sdcard.metadata.productRevisionMinor = cid[8] & 0x0F;
446 sdcard.metadata.productSerial = (cid[9] << 24) | (cid[10] << 16) | (cid[11] << 8) | cid[12];
447 sdcard.metadata.productionYear = (((cid[13] & 0x0F) << 4) | (cid[14] >> 4)) + 2000;
448 sdcard.metadata.productionMonth = cid[14] & 0x0F;
450 return true;
453 static bool sdcard_fetchCSD(void)
455 uint32_t readBlockLen, blockCount, blockCountMult;
456 uint64_t capacityBytes;
458 /* The CSD command's data block should always arrive within 8 idle clock cycles (SD card spec). This is because
459 * the information about card latency is stored in the CSD register itself, so we can't use that yet!
461 bool success =
462 sdcard_sendCommand(SDCARD_COMMAND_SEND_CSD, 0) == 0
463 && sdcard_receiveDataBlock((uint8_t*) &sdcard.csd, sizeof(sdcard.csd)) == SDCARD_RECEIVE_SUCCESS
464 && SDCARD_GET_CSD_FIELD(sdcard.csd, 1, TRAILER) == 1;
466 if (success) {
467 switch (SDCARD_GET_CSD_FIELD(sdcard.csd, 1, CSD_STRUCTURE_VER)) {
468 case SDCARD_CSD_STRUCTURE_VERSION_1:
469 // Block size in bytes (doesn't have to be 512)
470 readBlockLen = 1 << SDCARD_GET_CSD_FIELD(sdcard.csd, 1, READ_BLOCK_LEN);
471 blockCountMult = 1 << (SDCARD_GET_CSD_FIELD(sdcard.csd, 1, CSIZE_MULT) + 2);
472 blockCount = (SDCARD_GET_CSD_FIELD(sdcard.csd, 1, CSIZE) + 1) * blockCountMult;
474 // We could do this in 32 bits but it makes the 2GB case awkward
475 capacityBytes = (uint64_t) blockCount * readBlockLen;
477 // Re-express that capacity (max 2GB) in our standard 512-byte block size
478 sdcard.metadata.numBlocks = capacityBytes / SDCARD_BLOCK_SIZE;
479 break;
480 case SDCARD_CSD_STRUCTURE_VERSION_2:
481 sdcard.metadata.numBlocks = (SDCARD_GET_CSD_FIELD(sdcard.csd, 2, CSIZE) + 1) * 1024;
482 break;
483 default:
484 success = false;
488 sdcard_deselect();
490 return success;
494 * Check if the SD Card has completed its startup sequence. Must be called with sdcard.state == SDCARD_STATE_INITIALIZATION.
496 * Returns true if the card has finished its init process.
498 static bool sdcard_checkInitDone(void)
500 uint8_t status = sdcard_sendAppCommand(SDCARD_ACOMMAND_SEND_OP_COND, sdcard.version == 2 ? 1 << 30 /* We support high capacity cards */ : 0);
502 sdcard_deselect();
504 // When card init is complete, the idle bit in the response becomes zero.
505 return status == 0x00;
508 void sdcardSpi_preInit(const sdcardConfig_t *config)
510 spiPreinitRegister(config->chipSelectTag, IOCFG_IPU, 1);
514 * Begin the initialization process for the SD card. This must be called first before any other sdcard_ routine.
516 static void sdcardSpi_init(const sdcardConfig_t *config, const spiPinConfig_t *spiConfig)
518 UNUSED(spiConfig);
520 sdcard.enabled = config->mode;
521 if (!sdcard.enabled) {
522 sdcard.state = SDCARD_STATE_NOT_PRESENT;
523 return;
526 spiSetBusInstance(&sdcard.dev, config->device);
528 IO_t chipSelectIO;
529 if (config->chipSelectTag) {
530 chipSelectIO = IOGetByTag(config->chipSelectTag);
531 IOInit(chipSelectIO, OWNER_SDCARD_CS, 0);
532 IOConfigGPIO(chipSelectIO, SPI_IO_CS_CFG);
533 } else {
534 chipSelectIO = IO_NONE;
536 sdcard.dev.busType_u.spi.csnPin = chipSelectIO;
538 // Set the clock phase/polarity
539 spiSetClkPhasePolarity(&sdcard.dev, true);
541 // Set the callback argument when calling back to this driver for DMA completion
542 sdcard.dev.callbackArg = (uint32_t)&sdcard;
544 // Max frequency is initially 400kHz
546 spiSetClkDivisor(&sdcard.dev, spiCalculateDivider(SDCARD_MAX_SPI_INIT_CLK_HZ));
548 // SDCard wants 1ms minimum delay after power is applied to it
549 delay(1000);
551 // Transmit at least 74 dummy clock cycles with CS high so the SD card can start up
552 IOHi(sdcard.dev.busType_u.spi.csnPin);
554 // Note that this does not release the CS at the end of the transaction
555 busSegment_t segments[] = {
556 // Write a single 0xff
557 {.u.buffers = {NULL, NULL}, SDCARD_INIT_NUM_DUMMY_BYTES, false, NULL},
558 {.u.link = {NULL, NULL}, 0, true, NULL},
561 spiSequence(&sdcard.dev, &segments[0]);
563 // Block pending completion of SPI access
564 spiWait(&sdcard.dev);
566 sdcard.operationStartTime = millis();
567 sdcard.state = SDCARD_STATE_RESET;
568 sdcard.failureCount = 0;
571 static bool sdcard_setBlockLength(uint32_t blockLen)
573 uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_SET_BLOCKLEN, blockLen);
575 sdcard_deselect();
577 return status == 0;
581 * Returns true if the card is ready to accept read/write commands.
583 static bool sdcard_isReady(void)
585 return sdcard.state == SDCARD_STATE_READY || sdcard.state == SDCARD_STATE_WRITING_MULTIPLE_BLOCKS;
589 * Send the stop-transmission token to complete a multi-block write.
591 * Returns:
592 * SDCARD_OPERATION_IN_PROGRESS - We're now waiting for that stop to complete, the card will enter
593 * the SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE state.
594 * SDCARD_OPERATION_SUCCESS - The multi-block write finished immediately, the card will enter
595 * the SDCARD_READY state.
598 static sdcardOperationStatus_e sdcard_endWriteBlocks(void)
600 uint8_t token = SDCARD_MULTIPLE_BLOCK_WRITE_STOP_TOKEN;
601 sdcard.multiWriteBlocksRemain = 0;
603 // Note that this does not release the CS at the end of the transaction
604 busSegment_t segments[] = {
605 // 8 dummy clocks to guarantee N_WR clocks between the last card response and this token
606 {.u.buffers = {NULL, NULL}, 1, false, NULL},
607 {.u.buffers = {&token, NULL}, sizeof(token), false, NULL},
608 {.u.link = {NULL, NULL}, 0, true, NULL},
612 spiSequence(&sdcard.dev, &segments[0]);
614 // Block pending completion of SPI access
615 spiWait(&sdcard.dev);
617 // Card may choose to raise a busy (non-0xFF) signal after at most N_BR (1 byte) delay
618 if (sdcard_waitForNonIdleByte(1) == 0xFF) {
619 sdcard.state = SDCARD_STATE_READY;
620 return SDCARD_OPERATION_SUCCESS;
621 } else {
622 sdcard.state = SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE;
623 sdcard.operationStartTime = millis();
625 return SDCARD_OPERATION_IN_PROGRESS;
630 * Call periodically for the SD card to perform in-progress transfers.
632 * Returns true if the card is ready to accept commands.
634 static bool sdcardSpi_poll(void)
636 if (!sdcard.enabled) {
637 sdcard.state = SDCARD_STATE_NOT_PRESENT;
638 return false;
641 uint8_t initStatus;
642 bool sendComplete;
644 #ifdef SDCARD_PROFILING
645 bool profilingComplete;
646 #endif
648 doMore:
649 switch (sdcard.state) {
650 case SDCARD_STATE_RESET:
651 initStatus = sdcard_sendCommand(SDCARD_COMMAND_GO_IDLE_STATE, 0);
653 sdcard_deselect();
655 if (initStatus == SDCARD_R1_STATUS_BIT_IDLE) {
656 // Check card voltage and version
657 if (sdcard_validateInterfaceCondition()) {
659 sdcard.state = SDCARD_STATE_CARD_INIT_IN_PROGRESS;
660 goto doMore;
661 } else {
662 // Bad reply/voltage, we ought to refrain from accessing the card.
663 sdcard.state = SDCARD_STATE_NOT_PRESENT;
666 break;
668 case SDCARD_STATE_CARD_INIT_IN_PROGRESS:
669 if (sdcard_checkInitDone()) {
670 if (sdcard.version == 2) {
671 // Check for high capacity card
672 uint32_t ocr;
674 if (!sdcard_readOCRRegister(&ocr)) {
675 sdcard_reset();
676 goto doMore;
679 sdcard.highCapacity = (ocr & (1 << 30)) != 0;
680 } else {
681 // Version 1 cards are always low-capacity
682 sdcard.highCapacity = false;
685 // Now fetch the CSD and CID registers
686 if (sdcard_fetchCSD()) {
687 uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_SEND_CID, 0);
689 if (status == 0) {
690 // Keep the card selected to receive the response block
691 sdcard.state = SDCARD_STATE_INITIALIZATION_RECEIVE_CID;
692 goto doMore;
693 } else {
694 sdcard_deselect();
696 sdcard_reset();
697 goto doMore;
701 break;
702 case SDCARD_STATE_INITIALIZATION_RECEIVE_CID:
703 if (sdcard_receiveCID()) {
704 sdcard_deselect();
706 /* The spec is a little iffy on what the default block size is for Standard Size cards (it can be changed on
707 * standard size cards) so let's just set it to 512 explicitly so we don't have a problem.
709 if (!sdcard.highCapacity && !sdcard_setBlockLength(SDCARD_BLOCK_SIZE)) {
710 sdcard_reset();
711 goto doMore;
714 // Now we're done with init and we can switch to the full speed clock (<25MHz)
716 spiSetClkDivisor(&sdcard.dev, spiCalculateDivider(SDCARD_MAX_SPI_CLK_HZ));
718 sdcard.multiWriteBlocksRemain = 0;
720 sdcard.state = SDCARD_STATE_READY;
721 goto doMore;
722 } // else keep waiting for the CID to arrive
723 break;
724 case SDCARD_STATE_SENDING_WRITE:
725 // Have we finished sending the write yet?
726 sendComplete = !spiIsBusy(&sdcard.dev);
728 if (!spiUseDMA(&sdcard.dev)) {
729 // Send another chunk
730 spiReadWriteBuf(&sdcard.dev, sdcard.pendingOperation.buffer + SDCARD_NON_DMA_CHUNK_SIZE * sdcard.pendingOperation.chunkIndex, NULL, SDCARD_NON_DMA_CHUNK_SIZE);
732 sdcard.pendingOperation.chunkIndex++;
734 sendComplete = sdcard.pendingOperation.chunkIndex == SDCARD_BLOCK_SIZE / SDCARD_NON_DMA_CHUNK_SIZE;
737 if (sendComplete) {
738 // Finish up by sending the CRC and checking the SD-card's acceptance/rejectance
739 if (sdcard_sendDataBlockFinish()) {
740 // The SD card is now busy committing that write to the card
741 sdcard.state = SDCARD_STATE_WAITING_FOR_WRITE;
742 sdcard.operationStartTime = millis();
744 // Since we've transmitted the buffer we can go ahead and tell the caller their operation is complete
745 if (sdcard.pendingOperation.callback) {
746 sdcard.pendingOperation.callback(SDCARD_BLOCK_OPERATION_WRITE, sdcard.pendingOperation.blockIndex, sdcard.pendingOperation.buffer, sdcard.pendingOperation.callbackData);
748 } else {
749 /* Our write was rejected! This could be due to a bad address but we hope not to attempt that, so assume
750 * the card is broken and needs reset.
752 sdcard_reset();
754 // Announce write failure:
755 if (sdcard.pendingOperation.callback) {
756 sdcard.pendingOperation.callback(SDCARD_BLOCK_OPERATION_WRITE, sdcard.pendingOperation.blockIndex, NULL, sdcard.pendingOperation.callbackData);
759 goto doMore;
762 break;
763 case SDCARD_STATE_WAITING_FOR_WRITE:
764 if (sdcard_waitForIdle(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY)) {
765 #ifdef SDCARD_PROFILING
766 profilingComplete = true;
767 #endif
769 sdcard.failureCount = 0; // Assume the card is good if it can complete a write
771 // Still more blocks left to write in a multi-block chain?
772 if (sdcard.multiWriteBlocksRemain > 1) {
773 sdcard.multiWriteBlocksRemain--;
774 sdcard.multiWriteNextBlock++;
775 sdcard.state = SDCARD_STATE_WRITING_MULTIPLE_BLOCKS;
776 } else if (sdcard.multiWriteBlocksRemain == 1) {
777 // This function changes the sd card state for us whether immediately succesful or delayed:
778 if (sdcard_endWriteBlocks() == SDCARD_OPERATION_SUCCESS) {
779 sdcard_deselect();
780 } else {
781 #ifdef SDCARD_PROFILING
782 // Wait for the multi-block write to be terminated before finishing timing
783 profilingComplete = false;
784 #endif
786 } else {
787 sdcard.state = SDCARD_STATE_READY;
788 sdcard_deselect();
791 #ifdef SDCARD_PROFILING
792 if (profilingComplete && sdcard.profiler) {
793 sdcard.profiler(SDCARD_BLOCK_OPERATION_WRITE, sdcard.pendingOperation.blockIndex, micros() - sdcard.pendingOperation.profileStartTime);
795 #endif
796 } else if (millis() > sdcard.operationStartTime + SDCARD_TIMEOUT_WRITE_MSEC) {
798 * The caller has already been told that their write has completed, so they will have discarded
799 * their buffer and have no hope of retrying the operation. But this should be very rare and it allows
800 * them to reuse their buffer milliseconds faster than they otherwise would.
802 sdcard_reset();
803 goto doMore;
805 break;
806 case SDCARD_STATE_READING:
807 switch (sdcard_receiveDataBlock(sdcard.pendingOperation.buffer, SDCARD_BLOCK_SIZE)) {
808 case SDCARD_RECEIVE_SUCCESS:
809 sdcard_deselect();
811 sdcard.state = SDCARD_STATE_READY;
812 sdcard.failureCount = 0; // Assume the card is good if it can complete a read
814 #ifdef SDCARD_PROFILING
815 if (sdcard.profiler) {
816 sdcard.profiler(SDCARD_BLOCK_OPERATION_READ, sdcard.pendingOperation.blockIndex, micros() - sdcard.pendingOperation.profileStartTime);
818 #endif
820 if (sdcard.pendingOperation.callback) {
821 sdcard.pendingOperation.callback(
822 SDCARD_BLOCK_OPERATION_READ,
823 sdcard.pendingOperation.blockIndex,
824 sdcard.pendingOperation.buffer,
825 sdcard.pendingOperation.callbackData
828 break;
829 case SDCARD_RECEIVE_BLOCK_IN_PROGRESS:
830 if (millis() <= sdcard.operationStartTime + SDCARD_TIMEOUT_READ_MSEC) {
831 break; // Timeout not reached yet so keep waiting
833 // Timeout has expired, so fall through to convert to a fatal error
834 FALLTHROUGH;
836 case SDCARD_RECEIVE_ERROR:
837 sdcard_deselect();
839 sdcard_reset();
841 if (sdcard.pendingOperation.callback) {
842 sdcard.pendingOperation.callback(
843 SDCARD_BLOCK_OPERATION_READ,
844 sdcard.pendingOperation.blockIndex,
845 NULL,
846 sdcard.pendingOperation.callbackData
850 goto doMore;
851 break;
853 break;
854 case SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE:
855 if (sdcard_waitForIdle(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY)) {
856 sdcard_deselect();
858 sdcard.state = SDCARD_STATE_READY;
860 #ifdef SDCARD_PROFILING
861 if (sdcard.profiler) {
862 sdcard.profiler(SDCARD_BLOCK_OPERATION_WRITE, sdcard.pendingOperation.blockIndex, micros() - sdcard.pendingOperation.profileStartTime);
864 #endif
865 } else if (millis() > sdcard.operationStartTime + SDCARD_TIMEOUT_WRITE_MSEC) {
866 sdcard_reset();
867 goto doMore;
869 break;
870 case SDCARD_STATE_NOT_PRESENT:
871 default:
875 // Is the card's initialization taking too long?
876 if (sdcard.state >= SDCARD_STATE_RESET && sdcard.state < SDCARD_STATE_READY
877 && millis() - sdcard.operationStartTime > SDCARD_TIMEOUT_INIT_MILLIS) {
878 sdcard_reset();
881 return sdcard_isReady();
885 * Write the 512-byte block from the given buffer into the block with the given index.
887 * If the write does not complete immediately, your callback will be called later. If the write was successful, the
888 * buffer pointer will be the same buffer you originally passed in, otherwise the buffer will be set to NULL.
890 * Returns:
891 * SDCARD_OPERATION_IN_PROGRESS - Your buffer is currently being transmitted to the card and your callback will be
892 * called later to report the completion. The buffer pointer must remain valid until
893 * that time.
894 * SDCARD_OPERATION_SUCCESS - Your buffer has been transmitted to the card now.
895 * SDCARD_OPERATION_BUSY - The card is already busy and cannot accept your write
896 * SDCARD_OPERATION_FAILURE - Your write was rejected by the card, card will be reset
898 static sdcardOperationStatus_e sdcardSpi_writeBlock(uint32_t blockIndex, uint8_t *buffer, sdcard_operationCompleteCallback_c callback, uint32_t callbackData)
900 uint8_t status;
902 #ifdef SDCARD_PROFILING
903 sdcard.pendingOperation.profileStartTime = micros();
904 #endif
906 doMore:
907 switch (sdcard.state) {
908 case SDCARD_STATE_WRITING_MULTIPLE_BLOCKS:
909 // Do we need to cancel the previous multi-block write?
910 if (blockIndex != sdcard.multiWriteNextBlock) {
911 if (sdcard_endWriteBlocks() == SDCARD_OPERATION_SUCCESS) {
912 // Now we've entered the ready state, we can try again
913 goto doMore;
914 } else {
915 return SDCARD_OPERATION_BUSY;
919 // We're continuing a multi-block write
920 break;
921 case SDCARD_STATE_READY:
922 // We're not continuing a multi-block write so we need to send a single-block write command
923 // Standard size cards use byte addressing, high capacity cards use block addressing
924 status = sdcard_sendCommand(SDCARD_COMMAND_WRITE_BLOCK, sdcard.highCapacity ? blockIndex : blockIndex * SDCARD_BLOCK_SIZE);
926 if (status != 0) {
927 sdcard_deselect();
929 sdcard_reset();
931 return SDCARD_OPERATION_FAILURE;
933 break;
934 default:
935 return SDCARD_OPERATION_BUSY;
938 sdcard_sendDataBlockBegin(buffer, sdcard.state == SDCARD_STATE_WRITING_MULTIPLE_BLOCKS);
940 sdcard.pendingOperation.buffer = buffer;
941 sdcard.pendingOperation.blockIndex = blockIndex;
942 sdcard.pendingOperation.callback = callback;
943 sdcard.pendingOperation.callbackData = callbackData;
944 sdcard.pendingOperation.chunkIndex = 1; // (for non-DMA transfers) we've sent chunk #0 already
945 sdcard.state = SDCARD_STATE_SENDING_WRITE;
947 return SDCARD_OPERATION_IN_PROGRESS;
951 * Begin writing a series of consecutive blocks beginning at the given block index. This will allow (but not require)
952 * the SD card to pre-erase the number of blocks you specifiy, which can allow the writes to complete faster.
954 * Afterwards, just call sdcard_writeBlock() as normal to write those blocks consecutively.
956 * It's okay to abort the multi-block write at any time by writing to a non-consecutive address, or by performing a read.
958 * Returns:
959 * SDCARD_OPERATION_SUCCESS - Multi-block write has been queued
960 * SDCARD_OPERATION_BUSY - The card is already busy and cannot accept your write
961 * SDCARD_OPERATION_FAILURE - A fatal error occured, card will be reset
963 static sdcardOperationStatus_e sdcardSpi_beginWriteBlocks(uint32_t blockIndex, uint32_t blockCount)
965 if (sdcard.state != SDCARD_STATE_READY) {
966 if (sdcard.state == SDCARD_STATE_WRITING_MULTIPLE_BLOCKS) {
967 if (blockIndex == sdcard.multiWriteNextBlock) {
968 // Assume that the caller wants to continue the multi-block write they already have in progress!
969 return SDCARD_OPERATION_SUCCESS;
970 } else if (sdcard_endWriteBlocks() != SDCARD_OPERATION_SUCCESS) {
971 return SDCARD_OPERATION_BUSY;
972 } // Else we've completed the previous multi-block write and can fall through to start the new one
973 } else {
974 return SDCARD_OPERATION_BUSY;
978 if (
979 sdcard_sendAppCommand(SDCARD_ACOMMAND_SET_WR_BLOCK_ERASE_COUNT, blockCount) == 0
980 && sdcard_sendCommand(SDCARD_COMMAND_WRITE_MULTIPLE_BLOCK, sdcard.highCapacity ? blockIndex : blockIndex * SDCARD_BLOCK_SIZE) == 0
982 sdcard.state = SDCARD_STATE_WRITING_MULTIPLE_BLOCKS;
983 sdcard.multiWriteBlocksRemain = blockCount;
984 sdcard.multiWriteNextBlock = blockIndex;
986 // Leave the card selected
987 return SDCARD_OPERATION_SUCCESS;
988 } else {
989 sdcard_deselect();
991 sdcard_reset();
993 return SDCARD_OPERATION_FAILURE;
998 * Read the 512-byte block with the given index into the given 512-byte buffer.
1000 * When the read completes, your callback will be called. If the read was successful, the buffer pointer will be the
1001 * same buffer you originally passed in, otherwise the buffer will be set to NULL.
1003 * You must keep the pointer to the buffer valid until the operation completes!
1005 * Returns:
1006 * true - The operation was successfully queued for later completion, your callback will be called later
1007 * false - The operation could not be started due to the card being busy (try again later).
1009 static bool sdcardSpi_readBlock(uint32_t blockIndex, uint8_t *buffer, sdcard_operationCompleteCallback_c callback, uint32_t callbackData)
1011 if (sdcard.state != SDCARD_STATE_READY) {
1012 if (sdcard.state == SDCARD_STATE_WRITING_MULTIPLE_BLOCKS) {
1013 if (sdcard_endWriteBlocks() != SDCARD_OPERATION_SUCCESS) {
1014 return false;
1016 } else {
1017 return false;
1021 #ifdef SDCARD_PROFILING
1022 sdcard.pendingOperation.profileStartTime = micros();
1023 #endif
1025 // Standard size cards use byte addressing, high capacity cards use block addressing
1026 uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_READ_SINGLE_BLOCK, sdcard.highCapacity ? blockIndex : blockIndex * SDCARD_BLOCK_SIZE);
1028 if (status == 0) {
1029 sdcard.pendingOperation.buffer = buffer;
1030 sdcard.pendingOperation.blockIndex = blockIndex;
1031 sdcard.pendingOperation.callback = callback;
1032 sdcard.pendingOperation.callbackData = callbackData;
1034 sdcard.state = SDCARD_STATE_READING;
1036 sdcard.operationStartTime = millis();
1038 // Leave the card selected for the whole transaction
1040 return true;
1041 } else {
1042 sdcard_deselect();
1044 return false;
1049 * Returns true if the SD card has successfully completed its startup procedures.
1051 static bool sdcardSpi_isInitialized(void)
1053 return sdcard.state >= SDCARD_STATE_READY;
1056 static const sdcardMetadata_t* sdcardSpi_getMetadata(void)
1058 return &sdcard.metadata;
1061 #ifdef SDCARD_PROFILING
1063 static void sdcardSpi_setProfilerCallback(sdcard_profilerCallback_c callback)
1065 sdcard.profiler = callback;
1068 #endif
1070 sdcardVTable_t sdcardSpiVTable = {
1071 sdcardSpi_preInit,
1072 sdcardSpi_init,
1073 sdcardSpi_readBlock,
1074 sdcardSpi_beginWriteBlocks,
1075 sdcardSpi_writeBlock,
1076 sdcardSpi_poll,
1077 sdcardSpi_isFunctional,
1078 sdcardSpi_isInitialized,
1079 sdcardSpi_getMetadata,
1080 #ifdef SDCARD_PROFILING
1081 sdcardSpi_setProfilerCallback,
1082 #endif
1085 #endif