Merge pull request #11198 from SteveCEvans/sce_rc2
[betaflight.git] / src / main / drivers / sdcard_spi.c
blobe66fabffef2d6706e939628e26d8e3dab850114e
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_select(void)
76 IOLo(sdcard.dev.busType_u.spi.csnPin);
79 static void sdcard_deselect(void)
81 // As per the SD-card spec, give the card 8 dummy clocks so it can finish its operation
82 //spiReadWrite(&sdcard.dev, 0xFF);
84 spiWait(&sdcard.dev);
86 delayMicroseconds(10);
87 IOHi(sdcard.dev.busType_u.spi.csnPin);
90 /**
91 * Handle a failure of an SD card operation by resetting the card back to its initialization phase.
93 * Increments the failure counter, and when the failure threshold is reached, disables the card until
94 * the next call to sdcard_init().
96 static void sdcard_reset(void)
98 if (!sdcard_isInserted()) {
99 sdcard.state = SDCARD_STATE_NOT_PRESENT;
100 return;
103 if (sdcard.state >= SDCARD_STATE_READY) {
104 spiSetClkDivisor(&sdcard.dev, spiCalculateDivider(SDCARD_MAX_SPI_INIT_CLK_HZ));
107 sdcard.failureCount++;
108 if (sdcard.failureCount >= SDCARD_MAX_CONSECUTIVE_FAILURES) {
109 sdcard.state = SDCARD_STATE_NOT_PRESENT;
110 } else {
111 sdcard.operationStartTime = millis();
112 sdcard.state = SDCARD_STATE_RESET;
117 // Called in ISR context
118 // Wait until idle indicated by a read value of 0xff
119 busStatus_e sdcard_callbackIdle(uint32_t arg)
121 sdcard_t *sdcard = (sdcard_t *)arg;
122 extDevice_t *dev = &sdcard->dev;
124 uint8_t idleByte = dev->bus->curSegment->u.buffers.rxData[0];
126 if (idleByte == 0xff) {
127 return BUS_READY;
130 if (--sdcard->idleCount == 0) {
131 dev->bus->curSegment->u.buffers.rxData[0] = 0x00;
132 return BUS_ABORT;
135 return BUS_BUSY;
139 // Called in ISR context
140 // Wait until idle is no longer indicated by a read value of 0xff
141 busStatus_e sdcard_callbackNotIdle(uint32_t arg)
143 sdcard_t *sdcard = (sdcard_t *)arg;
144 extDevice_t *dev = &sdcard->dev;
146 uint8_t idleByte = dev->bus->curSegment->u.buffers.rxData[0];
148 if (idleByte != 0xff) {
149 return BUS_READY;
152 if (sdcard->idleCount-- == 0) {
153 return BUS_ABORT;
156 return BUS_BUSY;
161 * The SD card spec requires 8 clock cycles to be sent by us on the bus after most commands so it can finish its
162 * processing of that command. The easiest way for us to do this is to just wait for the bus to become idle before
163 * we transmit a command, sending at least 8-bits onto the bus when we do so.
165 static bool sdcard_waitForIdle(int maxBytesToWait)
167 uint8_t idleByte;
169 // Note that this does not release the CS at the end of the transaction
170 busSegment_t segments[] = {
171 {.u.buffers = {NULL, &idleByte}, sizeof(idleByte), false, sdcard_callbackIdle},
172 {.u.buffers = {NULL, NULL}, 0, false, NULL},
175 sdcard.idleCount = maxBytesToWait;
177 spiSequence(&sdcard.dev, &segments[0]);
179 // Block pending completion of SPI access
180 spiWait(&sdcard.dev);
182 return (idleByte == 0xff);
186 * Wait for up to maxDelay 0xFF idle bytes to arrive from the card, returning the first non-idle byte found.
188 * Returns 0xFF on failure.
190 static uint8_t sdcard_waitForNonIdleByte(int maxDelay)
192 uint8_t idleByte;
194 // Note that this does not release the CS at the end of the transaction
195 busSegment_t segments[] = {
196 {.u.buffers = {NULL, &idleByte}, sizeof(idleByte), false, sdcard_callbackNotIdle},
197 {.u.buffers = {NULL, NULL}, 0, false, NULL},
200 sdcard.idleCount = maxDelay;
202 spiSequence(&sdcard.dev, &segments[0]);
204 // Block pending completion of SPI access
205 spiWait(&sdcard.dev);
207 return idleByte;
211 * Waits up to SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY bytes for the card to become ready, send a command to the card
212 * with the given argument, waits up to SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY bytes for a reply, and returns the
213 * first non-0xFF byte of the reply.
215 * You must select the card first with sdcard_select() and deselect it afterwards with sdcard_deselect().
217 * Upon failure, 0xFF is returned.
219 static uint8_t sdcard_sendCommand(uint8_t commandCode, uint32_t commandArgument)
221 uint8_t command[6] = {
222 0x40 | commandCode,
223 commandArgument >> 24,
224 commandArgument >> 16,
225 commandArgument >> 8,
226 commandArgument,
227 0x95 /* Static CRC. This CRC is valid for CMD0 with a 0 argument, and CMD8 with 0x1AB argument, which are the only
228 commands that require a CRC */
231 uint8_t idleByte;
233 // Note that this does not release the CS at the end of the transaction
234 busSegment_t segments[] = {
235 {.u.buffers = {command, NULL}, sizeof(command), false, NULL},
236 {.u.buffers = {NULL, &idleByte}, sizeof(idleByte), false, sdcard_callbackNotIdle},
237 {.u.buffers = {NULL, NULL}, 0, false, NULL},
240 if (!sdcard_waitForIdle(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY) && commandCode != SDCARD_COMMAND_GO_IDLE_STATE)
241 return 0xFF;
243 sdcard.idleCount = SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY;
245 spiSequence(&sdcard.dev, &segments[0]);
247 // Block pending completion of SPI access
248 spiWait(&sdcard.dev);
250 return idleByte;
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 sdcard_select();
272 uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_SEND_IF_COND, (SDCARD_VOLTAGE_ACCEPTED_2_7_to_3_6 << 8) | SDCARD_IF_COND_CHECK_PATTERN);
274 // Don't deselect the card right away, because we'll want to read the rest of its reply if it's a V2 card
276 if (status == (SDCARD_R1_STATUS_BIT_ILLEGAL_COMMAND | SDCARD_R1_STATUS_BIT_IDLE)) {
277 // V1 cards don't support this command
278 sdcard.version = 1;
279 } else if (status == SDCARD_R1_STATUS_BIT_IDLE) {
280 // Note that this does not release the CS at the end of the transaction
281 busSegment_t segments[] = {
282 {.u.buffers = {NULL, ifCondReply}, sizeof(ifCondReply), false, NULL},
283 {.u.buffers = {NULL, NULL}, 0, false, NULL},
286 spiSequence(&sdcard.dev, &segments[0]);
288 // Block pending completion of SPI access
289 spiWait(&sdcard.dev);
292 * We don't bother to validate the SDCard's operating voltage range since the spec requires it to accept our
293 * 3.3V, but do check that it echoed back our check pattern properly.
295 if (ifCondReply[3] == SDCARD_IF_COND_CHECK_PATTERN) {
296 sdcard.version = 2;
300 sdcard_deselect();
302 return sdcard.version > 0;
305 static bool sdcard_readOCRRegister(uint32_t *result)
307 sdcard_select();
309 uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_READ_OCR, 0);
311 uint8_t response[4];
313 // Note that this does not release the CS at the end of the transaction
314 busSegment_t segments[] = {
315 {.u.buffers = {NULL, response}, sizeof(response), false, NULL},
316 {.u.buffers = {NULL, NULL}, 0, false, NULL},
319 spiSequence(&sdcard.dev, &segments[0]);
321 // Block pending completion of SPI access
322 spiWait(&sdcard.dev);
324 if (status == 0) {
325 sdcard_deselect();
327 *result = (response[0] << 24) | (response[1] << 16) | (response[2] << 8) | response[3];
329 return true;
330 } else {
331 sdcard_deselect();
333 return false;
337 typedef enum {
338 SDCARD_RECEIVE_SUCCESS,
339 SDCARD_RECEIVE_BLOCK_IN_PROGRESS,
340 SDCARD_RECEIVE_ERROR
341 } sdcardReceiveBlockStatus_e;
344 * Attempt to receive a data block from the SD card.
346 * Return true on success, otherwise the card has not responded yet and you should retry later.
348 static sdcardReceiveBlockStatus_e sdcard_receiveDataBlock(uint8_t *buffer, int count)
350 uint8_t dataToken = sdcard_waitForNonIdleByte(8);
352 if (dataToken == 0xFF) {
353 return SDCARD_RECEIVE_BLOCK_IN_PROGRESS;
356 if (dataToken != SDCARD_SINGLE_BLOCK_READ_START_TOKEN) {
357 return SDCARD_RECEIVE_ERROR;
360 // Note that this does not release the CS at the end of the transaction
361 busSegment_t segments[] = {
362 {.u.buffers = {NULL, buffer}, count, false, NULL},
363 // Discard trailing CRC, we don't care
364 {.u.buffers = {NULL, NULL}, 2, false, NULL},
365 {.u.buffers = {NULL, NULL}, 0, false, NULL},
368 spiSequence(&sdcard.dev, &segments[0]);
370 // Block pending completion of SPI access
371 spiWait(&sdcard.dev);
373 return SDCARD_RECEIVE_SUCCESS;
376 static bool sdcard_sendDataBlockFinish(void)
378 uint16_t dummyCRC = 0;
379 uint8_t dataResponseToken;
380 // Note that this does not release the CS at the end of the transaction
381 busSegment_t segments[] = {
382 {.u.buffers = {(uint8_t *)&dummyCRC, NULL}, sizeof(dummyCRC), false, NULL},
383 {.u.buffers = {NULL, &dataResponseToken}, sizeof(dataResponseToken), false, NULL},
384 {.u.buffers = {NULL, NULL}, 0, false, NULL},
387 spiSequence(&sdcard.dev, &segments[0]);
389 // Block pending completion of SPI access
390 spiWait(&sdcard.dev);
393 * Check if the card accepted the write (no CRC error / no address error)
395 * The lower 5 bits are structured as follows:
396 * | 0 | Status | 1 |
397 * | 0 | x x x | 1 |
399 * Statuses:
400 * 010 - Data accepted
401 * 101 - CRC error
402 * 110 - Write error
404 return (dataResponseToken & 0x1F) == 0x05;
408 * Begin sending a buffer of SDCARD_BLOCK_SIZE bytes to the SD card.
410 static void sdcard_sendDataBlockBegin(uint8_t *buffer, bool multiBlockWrite)
412 static uint8_t token;
414 token = multiBlockWrite ? SDCARD_MULTIPLE_BLOCK_WRITE_START_TOKEN : SDCARD_SINGLE_BLOCK_WRITE_START_TOKEN;
416 // Note that this does not release the CS at the end of the transaction
417 static busSegment_t segments[] = {
418 // Write a single 0xff
419 {.u.buffers = {NULL, NULL}, 1, false, NULL},
420 {.u.buffers = {&token, NULL}, sizeof(token), false, NULL},
421 {.u.buffers = {NULL, NULL}, 0, false, NULL},
422 {.u.buffers = {NULL, NULL}, 0, false, NULL},
425 segments[2].u.buffers.txData = buffer;
426 segments[2].len = spiUseDMA(&sdcard.dev) ? SDCARD_BLOCK_SIZE : SDCARD_NON_DMA_CHUNK_SIZE;
428 spiSequence(&sdcard.dev, &segments[0]);
430 // Don't block pending completion of SPI access
433 static bool sdcard_receiveCID(void)
435 uint8_t cid[16];
437 if (sdcard_receiveDataBlock(cid, sizeof(cid)) != SDCARD_RECEIVE_SUCCESS) {
438 return false;
441 sdcard.metadata.manufacturerID = cid[0];
442 sdcard.metadata.oemID = (cid[1] << 8) | cid[2];
443 sdcard.metadata.productName[0] = cid[3];
444 sdcard.metadata.productName[1] = cid[4];
445 sdcard.metadata.productName[2] = cid[5];
446 sdcard.metadata.productName[3] = cid[6];
447 sdcard.metadata.productName[4] = cid[7];
448 sdcard.metadata.productRevisionMajor = cid[8] >> 4;
449 sdcard.metadata.productRevisionMinor = cid[8] & 0x0F;
450 sdcard.metadata.productSerial = (cid[9] << 24) | (cid[10] << 16) | (cid[11] << 8) | cid[12];
451 sdcard.metadata.productionYear = (((cid[13] & 0x0F) << 4) | (cid[14] >> 4)) + 2000;
452 sdcard.metadata.productionMonth = cid[14] & 0x0F;
454 return true;
457 static bool sdcard_fetchCSD(void)
459 uint32_t readBlockLen, blockCount, blockCountMult;
460 uint64_t capacityBytes;
462 sdcard_select();
464 /* The CSD command's data block should always arrive within 8 idle clock cycles (SD card spec). This is because
465 * the information about card latency is stored in the CSD register itself, so we can't use that yet!
467 bool success =
468 sdcard_sendCommand(SDCARD_COMMAND_SEND_CSD, 0) == 0
469 && sdcard_receiveDataBlock((uint8_t*) &sdcard.csd, sizeof(sdcard.csd)) == SDCARD_RECEIVE_SUCCESS
470 && SDCARD_GET_CSD_FIELD(sdcard.csd, 1, TRAILER) == 1;
472 if (success) {
473 switch (SDCARD_GET_CSD_FIELD(sdcard.csd, 1, CSD_STRUCTURE_VER)) {
474 case SDCARD_CSD_STRUCTURE_VERSION_1:
475 // Block size in bytes (doesn't have to be 512)
476 readBlockLen = 1 << SDCARD_GET_CSD_FIELD(sdcard.csd, 1, READ_BLOCK_LEN);
477 blockCountMult = 1 << (SDCARD_GET_CSD_FIELD(sdcard.csd, 1, CSIZE_MULT) + 2);
478 blockCount = (SDCARD_GET_CSD_FIELD(sdcard.csd, 1, CSIZE) + 1) * blockCountMult;
480 // We could do this in 32 bits but it makes the 2GB case awkward
481 capacityBytes = (uint64_t) blockCount * readBlockLen;
483 // Re-express that capacity (max 2GB) in our standard 512-byte block size
484 sdcard.metadata.numBlocks = capacityBytes / SDCARD_BLOCK_SIZE;
485 break;
486 case SDCARD_CSD_STRUCTURE_VERSION_2:
487 sdcard.metadata.numBlocks = (SDCARD_GET_CSD_FIELD(sdcard.csd, 2, CSIZE) + 1) * 1024;
488 break;
489 default:
490 success = false;
494 sdcard_deselect();
496 return success;
500 * Check if the SD Card has completed its startup sequence. Must be called with sdcard.state == SDCARD_STATE_INITIALIZATION.
502 * Returns true if the card has finished its init process.
504 static bool sdcard_checkInitDone(void)
506 sdcard_select();
508 uint8_t status = sdcard_sendAppCommand(SDCARD_ACOMMAND_SEND_OP_COND, sdcard.version == 2 ? 1 << 30 /* We support high capacity cards */ : 0);
510 sdcard_deselect();
512 // When card init is complete, the idle bit in the response becomes zero.
513 return status == 0x00;
516 void sdcardSpi_preInit(const sdcardConfig_t *config)
518 spiPreinitRegister(config->chipSelectTag, IOCFG_IPU, 1);
522 * Begin the initialization process for the SD card. This must be called first before any other sdcard_ routine.
524 static void sdcardSpi_init(const sdcardConfig_t *config, const spiPinConfig_t *spiConfig)
526 UNUSED(spiConfig);
528 sdcard.enabled = config->mode;
529 if (!sdcard.enabled) {
530 sdcard.state = SDCARD_STATE_NOT_PRESENT;
531 return;
534 spiSetBusInstance(&sdcard.dev, config->device);
536 IO_t chipSelectIO;
537 if (config->chipSelectTag) {
538 chipSelectIO = IOGetByTag(config->chipSelectTag);
539 IOInit(chipSelectIO, OWNER_SDCARD_CS, 0);
540 IOConfigGPIO(chipSelectIO, SPI_IO_CS_CFG);
541 } else {
542 chipSelectIO = IO_NONE;
544 sdcard.dev.busType_u.spi.csnPin = chipSelectIO;
546 // Set the clock phase/polarity
547 spiSetClkPhasePolarity(&sdcard.dev, true);
549 // Set the callback argument when calling back to this driver for DMA completion
550 sdcard.dev.callbackArg = (uint32_t)&sdcard;
552 // Max frequency is initially 400kHz
554 spiSetClkDivisor(&sdcard.dev, spiCalculateDivider(SDCARD_MAX_SPI_INIT_CLK_HZ));
556 // SDCard wants 1ms minimum delay after power is applied to it
557 delay(1000);
559 // Transmit at least 74 dummy clock cycles with CS high so the SD card can start up
560 IOHi(sdcard.dev.busType_u.spi.csnPin);
562 // Note that this does not release the CS at the end of the transaction
563 busSegment_t segments[] = {
564 // Write a single 0xff
565 {.u.buffers = {NULL, NULL}, SDCARD_INIT_NUM_DUMMY_BYTES, false, NULL},
566 {.u.buffers = {NULL, NULL}, 0, false, NULL},
569 spiSequence(&sdcard.dev, &segments[0]);
571 // Block pending completion of SPI access
572 spiWait(&sdcard.dev);
574 sdcard.operationStartTime = millis();
575 sdcard.state = SDCARD_STATE_RESET;
576 sdcard.failureCount = 0;
579 static bool sdcard_setBlockLength(uint32_t blockLen)
581 sdcard_select();
583 uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_SET_BLOCKLEN, blockLen);
585 sdcard_deselect();
587 return status == 0;
591 * Returns true if the card is ready to accept read/write commands.
593 static bool sdcard_isReady(void)
595 return sdcard.state == SDCARD_STATE_READY || sdcard.state == SDCARD_STATE_WRITING_MULTIPLE_BLOCKS;
599 * Send the stop-transmission token to complete a multi-block write.
601 * Returns:
602 * SDCARD_OPERATION_IN_PROGRESS - We're now waiting for that stop to complete, the card will enter
603 * the SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE state.
604 * SDCARD_OPERATION_SUCCESS - The multi-block write finished immediately, the card will enter
605 * the SDCARD_READY state.
608 static sdcardOperationStatus_e sdcard_endWriteBlocks(void)
610 uint8_t token = SDCARD_MULTIPLE_BLOCK_WRITE_STOP_TOKEN;
611 sdcard.multiWriteBlocksRemain = 0;
613 // Note that this does not release the CS at the end of the transaction
614 busSegment_t segments[] = {
615 // 8 dummy clocks to guarantee N_WR clocks between the last card response and this token
616 {.u.buffers = {NULL, NULL}, 1, false, NULL},
617 {.u.buffers = {&token, NULL}, sizeof(token), false, NULL},
618 {.u.buffers = {NULL, NULL}, 0, false, NULL},
621 spiSequence(&sdcard.dev, &segments[0]);
623 // Block pending completion of SPI access
624 spiWait(&sdcard.dev);
626 // Card may choose to raise a busy (non-0xFF) signal after at most N_BR (1 byte) delay
627 if (sdcard_waitForNonIdleByte(1) == 0xFF) {
628 sdcard.state = SDCARD_STATE_READY;
629 return SDCARD_OPERATION_SUCCESS;
630 } else {
631 sdcard.state = SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE;
632 sdcard.operationStartTime = millis();
634 return SDCARD_OPERATION_IN_PROGRESS;
639 * Call periodically for the SD card to perform in-progress transfers.
641 * Returns true if the card is ready to accept commands.
643 static bool sdcardSpi_poll(void)
645 if (!sdcard.enabled) {
646 sdcard.state = SDCARD_STATE_NOT_PRESENT;
647 return false;
650 uint8_t initStatus;
651 bool sendComplete;
653 #ifdef SDCARD_PROFILING
654 bool profilingComplete;
655 #endif
657 doMore:
658 switch (sdcard.state) {
659 case SDCARD_STATE_RESET:
660 sdcard_select();
662 initStatus = sdcard_sendCommand(SDCARD_COMMAND_GO_IDLE_STATE, 0);
664 sdcard_deselect();
666 if (initStatus == SDCARD_R1_STATUS_BIT_IDLE) {
667 // Check card voltage and version
668 if (sdcard_validateInterfaceCondition()) {
670 sdcard.state = SDCARD_STATE_CARD_INIT_IN_PROGRESS;
671 goto doMore;
672 } else {
673 // Bad reply/voltage, we ought to refrain from accessing the card.
674 sdcard.state = SDCARD_STATE_NOT_PRESENT;
677 break;
679 case SDCARD_STATE_CARD_INIT_IN_PROGRESS:
680 if (sdcard_checkInitDone()) {
681 if (sdcard.version == 2) {
682 // Check for high capacity card
683 uint32_t ocr;
685 if (!sdcard_readOCRRegister(&ocr)) {
686 sdcard_reset();
687 goto doMore;
690 sdcard.highCapacity = (ocr & (1 << 30)) != 0;
691 } else {
692 // Version 1 cards are always low-capacity
693 sdcard.highCapacity = false;
696 // Now fetch the CSD and CID registers
697 if (sdcard_fetchCSD()) {
698 sdcard_select();
700 uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_SEND_CID, 0);
702 if (status == 0) {
703 // Keep the card selected to receive the response block
704 sdcard.state = SDCARD_STATE_INITIALIZATION_RECEIVE_CID;
705 goto doMore;
706 } else {
707 sdcard_deselect();
709 sdcard_reset();
710 goto doMore;
714 break;
715 case SDCARD_STATE_INITIALIZATION_RECEIVE_CID:
716 if (sdcard_receiveCID()) {
717 sdcard_deselect();
719 /* The spec is a little iffy on what the default block size is for Standard Size cards (it can be changed on
720 * standard size cards) so let's just set it to 512 explicitly so we don't have a problem.
722 if (!sdcard.highCapacity && !sdcard_setBlockLength(SDCARD_BLOCK_SIZE)) {
723 sdcard_reset();
724 goto doMore;
727 // Now we're done with init and we can switch to the full speed clock (<25MHz)
729 spiSetClkDivisor(&sdcard.dev, spiCalculateDivider(SDCARD_MAX_SPI_CLK_HZ));
731 sdcard.multiWriteBlocksRemain = 0;
733 sdcard.state = SDCARD_STATE_READY;
734 goto doMore;
735 } // else keep waiting for the CID to arrive
736 break;
737 case SDCARD_STATE_SENDING_WRITE:
738 // Have we finished sending the write yet?
739 sendComplete = !spiIsBusy(&sdcard.dev);
741 if (!spiUseDMA(&sdcard.dev)) {
742 // Send another chunk
743 spiReadWriteBuf(&sdcard.dev, sdcard.pendingOperation.buffer + SDCARD_NON_DMA_CHUNK_SIZE * sdcard.pendingOperation.chunkIndex, NULL, SDCARD_NON_DMA_CHUNK_SIZE);
745 sdcard.pendingOperation.chunkIndex++;
747 sendComplete = sdcard.pendingOperation.chunkIndex == SDCARD_BLOCK_SIZE / SDCARD_NON_DMA_CHUNK_SIZE;
750 if (sendComplete) {
751 // Finish up by sending the CRC and checking the SD-card's acceptance/rejectance
752 if (sdcard_sendDataBlockFinish()) {
753 // The SD card is now busy committing that write to the card
754 sdcard.state = SDCARD_STATE_WAITING_FOR_WRITE;
755 sdcard.operationStartTime = millis();
757 // Since we've transmitted the buffer we can go ahead and tell the caller their operation is complete
758 if (sdcard.pendingOperation.callback) {
759 sdcard.pendingOperation.callback(SDCARD_BLOCK_OPERATION_WRITE, sdcard.pendingOperation.blockIndex, sdcard.pendingOperation.buffer, sdcard.pendingOperation.callbackData);
761 } else {
762 /* Our write was rejected! This could be due to a bad address but we hope not to attempt that, so assume
763 * the card is broken and needs reset.
765 sdcard_reset();
767 // Announce write failure:
768 if (sdcard.pendingOperation.callback) {
769 sdcard.pendingOperation.callback(SDCARD_BLOCK_OPERATION_WRITE, sdcard.pendingOperation.blockIndex, NULL, sdcard.pendingOperation.callbackData);
772 goto doMore;
775 break;
776 case SDCARD_STATE_WAITING_FOR_WRITE:
777 if (sdcard_waitForIdle(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY)) {
778 #ifdef SDCARD_PROFILING
779 profilingComplete = true;
780 #endif
782 sdcard.failureCount = 0; // Assume the card is good if it can complete a write
784 // Still more blocks left to write in a multi-block chain?
785 if (sdcard.multiWriteBlocksRemain > 1) {
786 sdcard.multiWriteBlocksRemain--;
787 sdcard.multiWriteNextBlock++;
788 sdcard.state = SDCARD_STATE_WRITING_MULTIPLE_BLOCKS;
789 } else if (sdcard.multiWriteBlocksRemain == 1) {
790 // This function changes the sd card state for us whether immediately succesful or delayed:
791 if (sdcard_endWriteBlocks() == SDCARD_OPERATION_SUCCESS) {
792 sdcard_deselect();
793 } else {
794 #ifdef SDCARD_PROFILING
795 // Wait for the multi-block write to be terminated before finishing timing
796 profilingComplete = false;
797 #endif
799 } else {
800 sdcard.state = SDCARD_STATE_READY;
801 sdcard_deselect();
804 #ifdef SDCARD_PROFILING
805 if (profilingComplete && sdcard.profiler) {
806 sdcard.profiler(SDCARD_BLOCK_OPERATION_WRITE, sdcard.pendingOperation.blockIndex, micros() - sdcard.pendingOperation.profileStartTime);
808 #endif
809 } else if (millis() > sdcard.operationStartTime + SDCARD_TIMEOUT_WRITE_MSEC) {
811 * The caller has already been told that their write has completed, so they will have discarded
812 * their buffer and have no hope of retrying the operation. But this should be very rare and it allows
813 * them to reuse their buffer milliseconds faster than they otherwise would.
815 sdcard_reset();
816 goto doMore;
818 break;
819 case SDCARD_STATE_READING:
820 switch (sdcard_receiveDataBlock(sdcard.pendingOperation.buffer, SDCARD_BLOCK_SIZE)) {
821 case SDCARD_RECEIVE_SUCCESS:
822 sdcard_deselect();
824 sdcard.state = SDCARD_STATE_READY;
825 sdcard.failureCount = 0; // Assume the card is good if it can complete a read
827 #ifdef SDCARD_PROFILING
828 if (sdcard.profiler) {
829 sdcard.profiler(SDCARD_BLOCK_OPERATION_READ, sdcard.pendingOperation.blockIndex, micros() - sdcard.pendingOperation.profileStartTime);
831 #endif
833 if (sdcard.pendingOperation.callback) {
834 sdcard.pendingOperation.callback(
835 SDCARD_BLOCK_OPERATION_READ,
836 sdcard.pendingOperation.blockIndex,
837 sdcard.pendingOperation.buffer,
838 sdcard.pendingOperation.callbackData
841 break;
842 case SDCARD_RECEIVE_BLOCK_IN_PROGRESS:
843 if (millis() <= sdcard.operationStartTime + SDCARD_TIMEOUT_READ_MSEC) {
844 break; // Timeout not reached yet so keep waiting
846 // Timeout has expired, so fall through to convert to a fatal error
847 FALLTHROUGH;
849 case SDCARD_RECEIVE_ERROR:
850 sdcard_deselect();
852 sdcard_reset();
854 if (sdcard.pendingOperation.callback) {
855 sdcard.pendingOperation.callback(
856 SDCARD_BLOCK_OPERATION_READ,
857 sdcard.pendingOperation.blockIndex,
858 NULL,
859 sdcard.pendingOperation.callbackData
863 goto doMore;
864 break;
866 break;
867 case SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE:
868 if (sdcard_waitForIdle(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY)) {
869 sdcard_deselect();
871 sdcard.state = SDCARD_STATE_READY;
873 #ifdef SDCARD_PROFILING
874 if (sdcard.profiler) {
875 sdcard.profiler(SDCARD_BLOCK_OPERATION_WRITE, sdcard.pendingOperation.blockIndex, micros() - sdcard.pendingOperation.profileStartTime);
877 #endif
878 } else if (millis() > sdcard.operationStartTime + SDCARD_TIMEOUT_WRITE_MSEC) {
879 sdcard_reset();
880 goto doMore;
882 break;
883 case SDCARD_STATE_NOT_PRESENT:
884 default:
888 // Is the card's initialization taking too long?
889 if (sdcard.state >= SDCARD_STATE_RESET && sdcard.state < SDCARD_STATE_READY
890 && millis() - sdcard.operationStartTime > SDCARD_TIMEOUT_INIT_MILLIS) {
891 sdcard_reset();
894 return sdcard_isReady();
898 * Write the 512-byte block from the given buffer into the block with the given index.
900 * If the write does not complete immediately, your callback will be called later. If the write was successful, the
901 * buffer pointer will be the same buffer you originally passed in, otherwise the buffer will be set to NULL.
903 * Returns:
904 * SDCARD_OPERATION_IN_PROGRESS - Your buffer is currently being transmitted to the card and your callback will be
905 * called later to report the completion. The buffer pointer must remain valid until
906 * that time.
907 * SDCARD_OPERATION_SUCCESS - Your buffer has been transmitted to the card now.
908 * SDCARD_OPERATION_BUSY - The card is already busy and cannot accept your write
909 * SDCARD_OPERATION_FAILURE - Your write was rejected by the card, card will be reset
911 static sdcardOperationStatus_e sdcardSpi_writeBlock(uint32_t blockIndex, uint8_t *buffer, sdcard_operationCompleteCallback_c callback, uint32_t callbackData)
913 uint8_t status;
915 #ifdef SDCARD_PROFILING
916 sdcard.pendingOperation.profileStartTime = micros();
917 #endif
919 doMore:
920 switch (sdcard.state) {
921 case SDCARD_STATE_WRITING_MULTIPLE_BLOCKS:
922 // Do we need to cancel the previous multi-block write?
923 if (blockIndex != sdcard.multiWriteNextBlock) {
924 if (sdcard_endWriteBlocks() == SDCARD_OPERATION_SUCCESS) {
925 // Now we've entered the ready state, we can try again
926 goto doMore;
927 } else {
928 return SDCARD_OPERATION_BUSY;
932 // We're continuing a multi-block write
933 break;
934 case SDCARD_STATE_READY:
935 // We're not continuing a multi-block write so we need to send a single-block write command
936 sdcard_select();
938 // Standard size cards use byte addressing, high capacity cards use block addressing
939 status = sdcard_sendCommand(SDCARD_COMMAND_WRITE_BLOCK, sdcard.highCapacity ? blockIndex : blockIndex * SDCARD_BLOCK_SIZE);
941 if (status != 0) {
942 sdcard_deselect();
944 sdcard_reset();
946 return SDCARD_OPERATION_FAILURE;
948 break;
949 default:
950 return SDCARD_OPERATION_BUSY;
953 sdcard_sendDataBlockBegin(buffer, sdcard.state == SDCARD_STATE_WRITING_MULTIPLE_BLOCKS);
955 sdcard.pendingOperation.buffer = buffer;
956 sdcard.pendingOperation.blockIndex = blockIndex;
957 sdcard.pendingOperation.callback = callback;
958 sdcard.pendingOperation.callbackData = callbackData;
959 sdcard.pendingOperation.chunkIndex = 1; // (for non-DMA transfers) we've sent chunk #0 already
960 sdcard.state = SDCARD_STATE_SENDING_WRITE;
962 return SDCARD_OPERATION_IN_PROGRESS;
966 * Begin writing a series of consecutive blocks beginning at the given block index. This will allow (but not require)
967 * the SD card to pre-erase the number of blocks you specifiy, which can allow the writes to complete faster.
969 * Afterwards, just call sdcard_writeBlock() as normal to write those blocks consecutively.
971 * It's okay to abort the multi-block write at any time by writing to a non-consecutive address, or by performing a read.
973 * Returns:
974 * SDCARD_OPERATION_SUCCESS - Multi-block write has been queued
975 * SDCARD_OPERATION_BUSY - The card is already busy and cannot accept your write
976 * SDCARD_OPERATION_FAILURE - A fatal error occured, card will be reset
978 static sdcardOperationStatus_e sdcardSpi_beginWriteBlocks(uint32_t blockIndex, uint32_t blockCount)
980 if (sdcard.state != SDCARD_STATE_READY) {
981 if (sdcard.state == SDCARD_STATE_WRITING_MULTIPLE_BLOCKS) {
982 if (blockIndex == sdcard.multiWriteNextBlock) {
983 // Assume that the caller wants to continue the multi-block write they already have in progress!
984 return SDCARD_OPERATION_SUCCESS;
985 } else if (sdcard_endWriteBlocks() != SDCARD_OPERATION_SUCCESS) {
986 return SDCARD_OPERATION_BUSY;
987 } // Else we've completed the previous multi-block write and can fall through to start the new one
988 } else {
989 return SDCARD_OPERATION_BUSY;
993 sdcard_select();
995 if (
996 sdcard_sendAppCommand(SDCARD_ACOMMAND_SET_WR_BLOCK_ERASE_COUNT, blockCount) == 0
997 && sdcard_sendCommand(SDCARD_COMMAND_WRITE_MULTIPLE_BLOCK, sdcard.highCapacity ? blockIndex : blockIndex * SDCARD_BLOCK_SIZE) == 0
999 sdcard.state = SDCARD_STATE_WRITING_MULTIPLE_BLOCKS;
1000 sdcard.multiWriteBlocksRemain = blockCount;
1001 sdcard.multiWriteNextBlock = blockIndex;
1003 // Leave the card selected
1004 return SDCARD_OPERATION_SUCCESS;
1005 } else {
1006 sdcard_deselect();
1008 sdcard_reset();
1010 return SDCARD_OPERATION_FAILURE;
1015 * Read the 512-byte block with the given index into the given 512-byte buffer.
1017 * When the read completes, your callback will be called. If the read was successful, the buffer pointer will be the
1018 * same buffer you originally passed in, otherwise the buffer will be set to NULL.
1020 * You must keep the pointer to the buffer valid until the operation completes!
1022 * Returns:
1023 * true - The operation was successfully queued for later completion, your callback will be called later
1024 * false - The operation could not be started due to the card being busy (try again later).
1026 static bool sdcardSpi_readBlock(uint32_t blockIndex, uint8_t *buffer, sdcard_operationCompleteCallback_c callback, uint32_t callbackData)
1028 if (sdcard.state != SDCARD_STATE_READY) {
1029 if (sdcard.state == SDCARD_STATE_WRITING_MULTIPLE_BLOCKS) {
1030 if (sdcard_endWriteBlocks() != SDCARD_OPERATION_SUCCESS) {
1031 return false;
1033 } else {
1034 return false;
1038 #ifdef SDCARD_PROFILING
1039 sdcard.pendingOperation.profileStartTime = micros();
1040 #endif
1042 sdcard_select();
1044 // Standard size cards use byte addressing, high capacity cards use block addressing
1045 uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_READ_SINGLE_BLOCK, sdcard.highCapacity ? blockIndex : blockIndex * SDCARD_BLOCK_SIZE);
1047 if (status == 0) {
1048 sdcard.pendingOperation.buffer = buffer;
1049 sdcard.pendingOperation.blockIndex = blockIndex;
1050 sdcard.pendingOperation.callback = callback;
1051 sdcard.pendingOperation.callbackData = callbackData;
1053 sdcard.state = SDCARD_STATE_READING;
1055 sdcard.operationStartTime = millis();
1057 // Leave the card selected for the whole transaction
1059 return true;
1060 } else {
1061 sdcard_deselect();
1063 return false;
1068 * Returns true if the SD card has successfully completed its startup procedures.
1070 static bool sdcardSpi_isInitialized(void)
1072 return sdcard.state >= SDCARD_STATE_READY;
1075 static const sdcardMetadata_t* sdcardSpi_getMetadata(void)
1077 return &sdcard.metadata;
1080 #ifdef SDCARD_PROFILING
1082 static void sdcardSpi_setProfilerCallback(sdcard_profilerCallback_c callback)
1084 sdcard.profiler = callback;
1087 #endif
1089 sdcardVTable_t sdcardSpiVTable = {
1090 sdcardSpi_preInit,
1091 sdcardSpi_init,
1092 sdcardSpi_readBlock,
1093 sdcardSpi_beginWriteBlocks,
1094 sdcardSpi_writeBlock,
1095 sdcardSpi_poll,
1096 sdcardSpi_isFunctional,
1097 sdcardSpi_isInitialized,
1098 sdcardSpi_getMetadata,
1099 #ifdef SDCARD_PROFILING
1100 sdcardSpi_setProfilerCallback,
1101 #endif
1104 #endif