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)
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/>.
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"
39 #include "sdcard_impl.h"
40 #include "sdcard_standard.h"
42 #ifdef AFATFS_USE_INTROSPECTIVE_LOGGING
43 #define SDCARD_PROFILING
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
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);
81 delayMicroseconds(10);
84 spiRelease(&sdcard
.dev
);
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
;
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
;
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
;
128 if (--sdcard
->idleCount
<= 0) {
129 dev
->bus
->curSegment
->u
.buffers
.rxData
[0] = 0x00;
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
) {
149 if (sdcard
->idleCount
-- <= 0) {
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
)
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
)
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
);
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] = {
219 commandArgument
>> 24,
220 commandArgument
>> 16,
221 commandArgument
>> 8,
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 */
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
) {
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];
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
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
) {
301 return sdcard
.version
> 0;
304 static bool sdcard_readOCRRegister(uint32_t *result
)
306 uint8_t status
= sdcard_sendCommand(SDCARD_COMMAND_READ_OCR
, 0);
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
);
325 *result
= (response
[0] << 24) | (response
[1] << 16) | (response
[2] << 8) | response
[3];
336 SDCARD_RECEIVE_SUCCESS
,
337 SDCARD_RECEIVE_BLOCK_IN_PROGRESS
,
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
) {
354 if (idleByte
!= SDCARD_IDLE_TOKEN
) {
358 if (sdcard
->idleCount
-- <= 0) {
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
)
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
);
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
;
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:
426 * 010 - Data accepted
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)
464 if (sdcard_receiveDataBlock(cid
, sizeof(cid
)) != SDCARD_RECEIVE_SUCCESS
) {
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;
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!
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;
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
;
511 case SDCARD_CSD_STRUCTURE_VERSION_2
:
512 sdcard
.metadata
.numBlocks
= (SDCARD_GET_CSD_FIELD(sdcard
.csd
, 2, CSIZE
) + 1) * 1024;
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);
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
)
551 sdcard
.enabled
= config
->mode
;
552 if (!sdcard
.enabled
) {
553 sdcard
.state
= SDCARD_STATE_NOT_PRESENT
;
557 spiSetBusInstance(&sdcard
.dev
, config
->device
);
560 if (config
->chipSelectTag
) {
561 chipSelectIO
= IOGetByTag(config
->chipSelectTag
);
562 IOInit(chipSelectIO
, OWNER_SDCARD_CS
, 0);
563 IOConfigGPIO(chipSelectIO
, SPI_IO_CS_HIGH_CFG
);
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
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
);
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.
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
;
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
;
680 #ifdef SDCARD_PROFILING
681 bool profilingComplete
;
685 switch (sdcard
.state
) {
686 case SDCARD_STATE_RESET
:
687 initStatus
= sdcard_sendCommand(SDCARD_COMMAND_GO_IDLE_STATE
, 0);
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
;
698 // Bad reply/voltage, we ought to refrain from accessing the card.
699 sdcard
.state
= SDCARD_STATE_NOT_PRESENT
;
704 case SDCARD_STATE_CARD_INIT_IN_PROGRESS
:
705 if (sdcard_checkInitDone()) {
706 if (sdcard
.version
== 2) {
707 // Check for high capacity card
710 if (!sdcard_readOCRRegister(&ocr
)) {
715 sdcard
.highCapacity
= (ocr
& (1 << 30)) != 0;
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);
726 // Keep the card selected to receive the response block
727 sdcard
.state
= SDCARD_STATE_INITIALIZATION_RECEIVE_CID
;
738 case SDCARD_STATE_INITIALIZATION_RECEIVE_CID
:
739 if (sdcard_receiveCID()) {
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
)) {
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
;
758 } // else keep waiting for the CID to arrive
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
;
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
);
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.
790 // Announce write failure:
791 if (sdcard
.pendingOperation
.callback
) {
792 sdcard
.pendingOperation
.callback(SDCARD_BLOCK_OPERATION_WRITE
, sdcard
.pendingOperation
.blockIndex
, NULL
, sdcard
.pendingOperation
.callbackData
);
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;
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
) {
817 #ifdef SDCARD_PROFILING
818 // Wait for the multi-block write to be terminated before finishing timing
819 profilingComplete
= false;
823 sdcard
.state
= SDCARD_STATE_READY
;
827 #ifdef SDCARD_PROFILING
828 if (profilingComplete
&& sdcard
.profiler
) {
829 sdcard
.profiler(SDCARD_BLOCK_OPERATION_WRITE
, sdcard
.pendingOperation
.blockIndex
, micros() - sdcard
.pendingOperation
.profileStartTime
);
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.
842 case SDCARD_STATE_READING
:
843 switch (sdcard_receiveDataBlock(sdcard
.pendingOperation
.buffer
, SDCARD_BLOCK_SIZE
)) {
844 case SDCARD_RECEIVE_SUCCESS
:
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
);
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
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
872 case SDCARD_RECEIVE_ERROR
:
877 if (sdcard
.pendingOperation
.callback
) {
878 sdcard
.pendingOperation
.callback(
879 SDCARD_BLOCK_OPERATION_READ
,
880 sdcard
.pendingOperation
.blockIndex
,
882 sdcard
.pendingOperation
.callbackData
890 case SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE
:
891 if (sdcard_waitForIdle(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY
)) {
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
);
901 } else if (millis() > sdcard
.operationStartTime
+ SDCARD_TIMEOUT_WRITE_MSEC
) {
906 case SDCARD_STATE_NOT_PRESENT
:
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
) {
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.
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
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
)
938 #ifdef SDCARD_PROFILING
939 sdcard
.pendingOperation
.profileStartTime
= micros();
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
951 return SDCARD_OPERATION_BUSY
;
955 // We're continuing a multi-block write
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
);
967 return SDCARD_OPERATION_FAILURE
;
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.
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
1010 return SDCARD_OPERATION_BUSY
;
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
;
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!
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
) {
1057 #ifdef SDCARD_PROFILING
1058 sdcard
.pendingOperation
.profileStartTime
= micros();
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
);
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
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
;
1106 sdcardVTable_t sdcardSpiVTable
= {
1109 sdcardSpi_readBlock
,
1110 sdcardSpi_beginWriteBlocks
,
1111 sdcardSpi_writeBlock
,
1113 sdcardSpi_isFunctional
,
1114 sdcardSpi_isInitialized
,
1115 sdcardSpi_getMetadata
,
1116 #ifdef SDCARD_PROFILING
1117 sdcardSpi_setProfilerCallback
,