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_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);
86 delayMicroseconds(10);
87 IOHi(sdcard
.dev
.busType_u
.spi
.csnPin
);
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
;
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
;
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) {
130 if (--sdcard
->idleCount
== 0) {
131 dev
->bus
->curSegment
->u
.buffers
.rxData
[0] = 0x00;
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) {
152 if (sdcard
->idleCount
-- == 0) {
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
)
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
.link
= {NULL
, NULL
}, 0, true, NULL
},
176 sdcard
.idleCount
= maxBytesToWait
;
178 spiSequence(&sdcard
.dev
, &segments
[0]);
180 // Block pending completion of SPI access
181 spiWait(&sdcard
.dev
);
183 return (idleByte
== 0xff);
187 * Wait for up to maxDelay 0xFF idle bytes to arrive from the card, returning the first non-idle byte found.
189 * Returns 0xFF on failure.
191 static uint8_t sdcard_waitForNonIdleByte(int maxDelay
)
195 // Note that this does not release the CS at the end of the transaction
196 busSegment_t segments
[] = {
197 {.u
.buffers
= {NULL
, &idleByte
}, sizeof(idleByte
), false, sdcard_callbackNotIdle
},
198 {.u
.link
= {NULL
, NULL
}, 0, true, NULL
},
202 sdcard
.idleCount
= maxDelay
;
204 spiSequence(&sdcard
.dev
, &segments
[0]);
206 // Block pending completion of SPI access
207 spiWait(&sdcard
.dev
);
213 * Waits up to SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY bytes for the card to become ready, send a command to the card
214 * with the given argument, waits up to SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY bytes for a reply, and returns the
215 * first non-0xFF byte of the reply.
217 * You must select the card first with sdcard_select() and deselect it afterwards with sdcard_deselect().
219 * Upon failure, 0xFF is returned.
221 static uint8_t sdcard_sendCommand(uint8_t commandCode
, uint32_t commandArgument
)
223 uint8_t command
[6] = {
225 commandArgument
>> 24,
226 commandArgument
>> 16,
227 commandArgument
>> 8,
229 0x95 /* Static CRC. This CRC is valid for CMD0 with a 0 argument, and CMD8 with 0x1AB argument, which are the only
230 commands that require a CRC */
235 // Note that this does not release the CS at the end of the transaction
236 busSegment_t segments
[] = {
237 {.u
.buffers
= {command
, NULL
}, sizeof(command
), false, NULL
},
238 {.u
.buffers
= {NULL
, &idleByte
}, sizeof(idleByte
), false, sdcard_callbackNotIdle
},
239 {.u
.link
= {NULL
, NULL
}, 0, true, NULL
},
243 if (!sdcard_waitForIdle(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY
) && commandCode
!= SDCARD_COMMAND_GO_IDLE_STATE
)
246 sdcard
.idleCount
= SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY
;
248 spiSequence(&sdcard
.dev
, &segments
[0]);
250 // Block pending completion of SPI access
251 spiWait(&sdcard
.dev
);
256 static uint8_t sdcard_sendAppCommand(uint8_t commandCode
, uint32_t commandArgument
)
258 sdcard_sendCommand(SDCARD_COMMAND_APP_CMD
, 0);
260 return sdcard_sendCommand(commandCode
, commandArgument
);
264 * Sends an IF_COND message to the card to check its version and validate its voltage requirements. Sets the global
265 * sdCardVersion with the detected version (0, 1, or 2) and returns true if the card is compatible.
267 static bool sdcard_validateInterfaceCondition(void)
269 uint8_t ifCondReply
[4];
275 uint8_t status
= sdcard_sendCommand(SDCARD_COMMAND_SEND_IF_COND
, (SDCARD_VOLTAGE_ACCEPTED_2_7_to_3_6
<< 8) | SDCARD_IF_COND_CHECK_PATTERN
);
277 // Don't deselect the card right away, because we'll want to read the rest of its reply if it's a V2 card
279 if (status
== (SDCARD_R1_STATUS_BIT_ILLEGAL_COMMAND
| SDCARD_R1_STATUS_BIT_IDLE
)) {
280 // V1 cards don't support this command
282 } else if (status
== SDCARD_R1_STATUS_BIT_IDLE
) {
283 // Note that this does not release the CS at the end of the transaction
284 busSegment_t segments
[] = {
285 {.u
.buffers
= {NULL
, ifCondReply
}, sizeof(ifCondReply
), false, NULL
},
286 {.u
.link
= {NULL
, NULL
}, 0, true, NULL
},
290 spiSequence(&sdcard
.dev
, &segments
[0]);
292 // Block pending completion of SPI access
293 spiWait(&sdcard
.dev
);
296 * We don't bother to validate the SDCard's operating voltage range since the spec requires it to accept our
297 * 3.3V, but do check that it echoed back our check pattern properly.
299 if (ifCondReply
[3] == SDCARD_IF_COND_CHECK_PATTERN
) {
306 return sdcard
.version
> 0;
309 static bool sdcard_readOCRRegister(uint32_t *result
)
313 uint8_t status
= sdcard_sendCommand(SDCARD_COMMAND_READ_OCR
, 0);
317 // Note that this does not release the CS at the end of the transaction
318 busSegment_t segments
[] = {
319 {.u
.buffers
= {NULL
, response
}, sizeof(response
), false, NULL
},
320 {.u
.link
= {NULL
, NULL
}, 0, true, NULL
},
324 spiSequence(&sdcard
.dev
, &segments
[0]);
326 // Block pending completion of SPI access
327 spiWait(&sdcard
.dev
);
332 *result
= (response
[0] << 24) | (response
[1] << 16) | (response
[2] << 8) | response
[3];
343 SDCARD_RECEIVE_SUCCESS
,
344 SDCARD_RECEIVE_BLOCK_IN_PROGRESS
,
346 } sdcardReceiveBlockStatus_e
;
349 * Attempt to receive a data block from the SD card.
351 * Return true on success, otherwise the card has not responded yet and you should retry later.
353 static sdcardReceiveBlockStatus_e
sdcard_receiveDataBlock(uint8_t *buffer
, int count
)
355 uint8_t dataToken
= sdcard_waitForNonIdleByte(8);
357 if (dataToken
== 0xFF) {
358 return SDCARD_RECEIVE_BLOCK_IN_PROGRESS
;
361 if (dataToken
!= SDCARD_SINGLE_BLOCK_READ_START_TOKEN
) {
362 return SDCARD_RECEIVE_ERROR
;
365 // Note that this does not release the CS at the end of the transaction
366 busSegment_t segments
[] = {
367 {.u
.buffers
= {NULL
, buffer
}, count
, false, NULL
},
368 // Discard trailing CRC, we don't care
369 {.u
.buffers
= {NULL
, NULL
}, 2, false, NULL
},
370 {.u
.link
= {NULL
, NULL
}, 0, true, NULL
},
374 spiSequence(&sdcard
.dev
, &segments
[0]);
376 // Block pending completion of SPI access
377 spiWait(&sdcard
.dev
);
379 return SDCARD_RECEIVE_SUCCESS
;
382 static bool sdcard_sendDataBlockFinish(void)
384 uint16_t dummyCRC
= 0;
385 uint8_t dataResponseToken
;
386 // Note that this does not release the CS at the end of the transaction
387 busSegment_t segments
[] = {
388 {.u
.buffers
= {(uint8_t *)&dummyCRC
, NULL
}, sizeof(dummyCRC
), false, NULL
},
389 {.u
.buffers
= {NULL
, &dataResponseToken
}, sizeof(dataResponseToken
), false, NULL
},
390 {.u
.link
= {NULL
, NULL
}, 0, true, NULL
},
394 spiSequence(&sdcard
.dev
, &segments
[0]);
396 // Block pending completion of SPI access
397 spiWait(&sdcard
.dev
);
400 * Check if the card accepted the write (no CRC error / no address error)
402 * The lower 5 bits are structured as follows:
407 * 010 - Data accepted
411 return (dataResponseToken
& 0x1F) == 0x05;
415 * Begin sending a buffer of SDCARD_BLOCK_SIZE bytes to the SD card.
417 static void sdcard_sendDataBlockBegin(uint8_t *buffer
, bool multiBlockWrite
)
419 static uint8_t token
;
421 token
= multiBlockWrite
? SDCARD_MULTIPLE_BLOCK_WRITE_START_TOKEN
: SDCARD_SINGLE_BLOCK_WRITE_START_TOKEN
;
423 // Note that this does not release the CS at the end of the transaction
424 static busSegment_t segments
[] = {
425 // Write a single 0xff
426 {.u
.buffers
= {NULL
, NULL
}, 1, false, NULL
},
427 {.u
.buffers
= {&token
, NULL
}, sizeof(token
), false, NULL
},
428 {.u
.buffers
= {NULL
, NULL
}, 0, false, NULL
},
429 {.u
.link
= {NULL
, NULL
}, 0, true, NULL
},
433 segments
[2].u
.buffers
.txData
= buffer
;
434 segments
[2].len
= spiUseDMA(&sdcard
.dev
) ? SDCARD_BLOCK_SIZE
: SDCARD_NON_DMA_CHUNK_SIZE
;
436 spiSequence(&sdcard
.dev
, &segments
[0]);
438 // Don't block pending completion of SPI access
441 static bool sdcard_receiveCID(void)
445 if (sdcard_receiveDataBlock(cid
, sizeof(cid
)) != SDCARD_RECEIVE_SUCCESS
) {
449 sdcard
.metadata
.manufacturerID
= cid
[0];
450 sdcard
.metadata
.oemID
= (cid
[1] << 8) | cid
[2];
451 sdcard
.metadata
.productName
[0] = cid
[3];
452 sdcard
.metadata
.productName
[1] = cid
[4];
453 sdcard
.metadata
.productName
[2] = cid
[5];
454 sdcard
.metadata
.productName
[3] = cid
[6];
455 sdcard
.metadata
.productName
[4] = cid
[7];
456 sdcard
.metadata
.productRevisionMajor
= cid
[8] >> 4;
457 sdcard
.metadata
.productRevisionMinor
= cid
[8] & 0x0F;
458 sdcard
.metadata
.productSerial
= (cid
[9] << 24) | (cid
[10] << 16) | (cid
[11] << 8) | cid
[12];
459 sdcard
.metadata
.productionYear
= (((cid
[13] & 0x0F) << 4) | (cid
[14] >> 4)) + 2000;
460 sdcard
.metadata
.productionMonth
= cid
[14] & 0x0F;
465 static bool sdcard_fetchCSD(void)
467 uint32_t readBlockLen
, blockCount
, blockCountMult
;
468 uint64_t capacityBytes
;
472 /* The CSD command's data block should always arrive within 8 idle clock cycles (SD card spec). This is because
473 * the information about card latency is stored in the CSD register itself, so we can't use that yet!
476 sdcard_sendCommand(SDCARD_COMMAND_SEND_CSD
, 0) == 0
477 && sdcard_receiveDataBlock((uint8_t*) &sdcard
.csd
, sizeof(sdcard
.csd
)) == SDCARD_RECEIVE_SUCCESS
478 && SDCARD_GET_CSD_FIELD(sdcard
.csd
, 1, TRAILER
) == 1;
481 switch (SDCARD_GET_CSD_FIELD(sdcard
.csd
, 1, CSD_STRUCTURE_VER
)) {
482 case SDCARD_CSD_STRUCTURE_VERSION_1
:
483 // Block size in bytes (doesn't have to be 512)
484 readBlockLen
= 1 << SDCARD_GET_CSD_FIELD(sdcard
.csd
, 1, READ_BLOCK_LEN
);
485 blockCountMult
= 1 << (SDCARD_GET_CSD_FIELD(sdcard
.csd
, 1, CSIZE_MULT
) + 2);
486 blockCount
= (SDCARD_GET_CSD_FIELD(sdcard
.csd
, 1, CSIZE
) + 1) * blockCountMult
;
488 // We could do this in 32 bits but it makes the 2GB case awkward
489 capacityBytes
= (uint64_t) blockCount
* readBlockLen
;
491 // Re-express that capacity (max 2GB) in our standard 512-byte block size
492 sdcard
.metadata
.numBlocks
= capacityBytes
/ SDCARD_BLOCK_SIZE
;
494 case SDCARD_CSD_STRUCTURE_VERSION_2
:
495 sdcard
.metadata
.numBlocks
= (SDCARD_GET_CSD_FIELD(sdcard
.csd
, 2, CSIZE
) + 1) * 1024;
508 * Check if the SD Card has completed its startup sequence. Must be called with sdcard.state == SDCARD_STATE_INITIALIZATION.
510 * Returns true if the card has finished its init process.
512 static bool sdcard_checkInitDone(void)
516 uint8_t status
= sdcard_sendAppCommand(SDCARD_ACOMMAND_SEND_OP_COND
, sdcard
.version
== 2 ? 1 << 30 /* We support high capacity cards */ : 0);
520 // When card init is complete, the idle bit in the response becomes zero.
521 return status
== 0x00;
524 void sdcardSpi_preInit(const sdcardConfig_t
*config
)
526 spiPreinitRegister(config
->chipSelectTag
, IOCFG_IPU
, 1);
530 * Begin the initialization process for the SD card. This must be called first before any other sdcard_ routine.
532 static void sdcardSpi_init(const sdcardConfig_t
*config
, const spiPinConfig_t
*spiConfig
)
536 sdcard
.enabled
= config
->mode
;
537 if (!sdcard
.enabled
) {
538 sdcard
.state
= SDCARD_STATE_NOT_PRESENT
;
542 spiSetBusInstance(&sdcard
.dev
, config
->device
);
545 if (config
->chipSelectTag
) {
546 chipSelectIO
= IOGetByTag(config
->chipSelectTag
);
547 IOInit(chipSelectIO
, OWNER_SDCARD_CS
, 0);
548 IOConfigGPIO(chipSelectIO
, SPI_IO_CS_CFG
);
550 chipSelectIO
= IO_NONE
;
552 sdcard
.dev
.busType_u
.spi
.csnPin
= chipSelectIO
;
554 // Set the clock phase/polarity
555 spiSetClkPhasePolarity(&sdcard
.dev
, true);
557 // Set the callback argument when calling back to this driver for DMA completion
558 sdcard
.dev
.callbackArg
= (uint32_t)&sdcard
;
560 // Max frequency is initially 400kHz
562 spiSetClkDivisor(&sdcard
.dev
, spiCalculateDivider(SDCARD_MAX_SPI_INIT_CLK_HZ
));
564 // SDCard wants 1ms minimum delay after power is applied to it
567 // Transmit at least 74 dummy clock cycles with CS high so the SD card can start up
568 IOHi(sdcard
.dev
.busType_u
.spi
.csnPin
);
570 // Note that this does not release the CS at the end of the transaction
571 busSegment_t segments
[] = {
572 // Write a single 0xff
573 {.u
.buffers
= {NULL
, NULL
}, SDCARD_INIT_NUM_DUMMY_BYTES
, false, NULL
},
574 {.u
.link
= {NULL
, NULL
}, 0, true, NULL
},
577 spiSequence(&sdcard
.dev
, &segments
[0]);
579 // Block pending completion of SPI access
580 spiWait(&sdcard
.dev
);
582 sdcard
.operationStartTime
= millis();
583 sdcard
.state
= SDCARD_STATE_RESET
;
584 sdcard
.failureCount
= 0;
587 static bool sdcard_setBlockLength(uint32_t blockLen
)
591 uint8_t status
= sdcard_sendCommand(SDCARD_COMMAND_SET_BLOCKLEN
, blockLen
);
599 * Returns true if the card is ready to accept read/write commands.
601 static bool sdcard_isReady(void)
603 return sdcard
.state
== SDCARD_STATE_READY
|| sdcard
.state
== SDCARD_STATE_WRITING_MULTIPLE_BLOCKS
;
607 * Send the stop-transmission token to complete a multi-block write.
610 * SDCARD_OPERATION_IN_PROGRESS - We're now waiting for that stop to complete, the card will enter
611 * the SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE state.
612 * SDCARD_OPERATION_SUCCESS - The multi-block write finished immediately, the card will enter
613 * the SDCARD_READY state.
616 static sdcardOperationStatus_e
sdcard_endWriteBlocks(void)
618 uint8_t token
= SDCARD_MULTIPLE_BLOCK_WRITE_STOP_TOKEN
;
619 sdcard
.multiWriteBlocksRemain
= 0;
621 // Note that this does not release the CS at the end of the transaction
622 busSegment_t segments
[] = {
623 // 8 dummy clocks to guarantee N_WR clocks between the last card response and this token
624 {.u
.buffers
= {NULL
, NULL
}, 1, false, NULL
},
625 {.u
.buffers
= {&token
, NULL
}, sizeof(token
), false, NULL
},
626 {.u
.link
= {NULL
, NULL
}, 0, true, NULL
},
630 spiSequence(&sdcard
.dev
, &segments
[0]);
632 // Block pending completion of SPI access
633 spiWait(&sdcard
.dev
);
635 // Card may choose to raise a busy (non-0xFF) signal after at most N_BR (1 byte) delay
636 if (sdcard_waitForNonIdleByte(1) == 0xFF) {
637 sdcard
.state
= SDCARD_STATE_READY
;
638 return SDCARD_OPERATION_SUCCESS
;
640 sdcard
.state
= SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE
;
641 sdcard
.operationStartTime
= millis();
643 return SDCARD_OPERATION_IN_PROGRESS
;
648 * Call periodically for the SD card to perform in-progress transfers.
650 * Returns true if the card is ready to accept commands.
652 static bool sdcardSpi_poll(void)
654 if (!sdcard
.enabled
) {
655 sdcard
.state
= SDCARD_STATE_NOT_PRESENT
;
662 #ifdef SDCARD_PROFILING
663 bool profilingComplete
;
667 switch (sdcard
.state
) {
668 case SDCARD_STATE_RESET
:
671 initStatus
= sdcard_sendCommand(SDCARD_COMMAND_GO_IDLE_STATE
, 0);
675 if (initStatus
== SDCARD_R1_STATUS_BIT_IDLE
) {
676 // Check card voltage and version
677 if (sdcard_validateInterfaceCondition()) {
679 sdcard
.state
= SDCARD_STATE_CARD_INIT_IN_PROGRESS
;
682 // Bad reply/voltage, we ought to refrain from accessing the card.
683 sdcard
.state
= SDCARD_STATE_NOT_PRESENT
;
688 case SDCARD_STATE_CARD_INIT_IN_PROGRESS
:
689 if (sdcard_checkInitDone()) {
690 if (sdcard
.version
== 2) {
691 // Check for high capacity card
694 if (!sdcard_readOCRRegister(&ocr
)) {
699 sdcard
.highCapacity
= (ocr
& (1 << 30)) != 0;
701 // Version 1 cards are always low-capacity
702 sdcard
.highCapacity
= false;
705 // Now fetch the CSD and CID registers
706 if (sdcard_fetchCSD()) {
709 uint8_t status
= sdcard_sendCommand(SDCARD_COMMAND_SEND_CID
, 0);
712 // Keep the card selected to receive the response block
713 sdcard
.state
= SDCARD_STATE_INITIALIZATION_RECEIVE_CID
;
724 case SDCARD_STATE_INITIALIZATION_RECEIVE_CID
:
725 if (sdcard_receiveCID()) {
728 /* The spec is a little iffy on what the default block size is for Standard Size cards (it can be changed on
729 * standard size cards) so let's just set it to 512 explicitly so we don't have a problem.
731 if (!sdcard
.highCapacity
&& !sdcard_setBlockLength(SDCARD_BLOCK_SIZE
)) {
736 // Now we're done with init and we can switch to the full speed clock (<25MHz)
738 spiSetClkDivisor(&sdcard
.dev
, spiCalculateDivider(SDCARD_MAX_SPI_CLK_HZ
));
740 sdcard
.multiWriteBlocksRemain
= 0;
742 sdcard
.state
= SDCARD_STATE_READY
;
744 } // else keep waiting for the CID to arrive
746 case SDCARD_STATE_SENDING_WRITE
:
747 // Have we finished sending the write yet?
748 sendComplete
= !spiIsBusy(&sdcard
.dev
);
750 if (!spiUseDMA(&sdcard
.dev
)) {
751 // Send another chunk
752 spiReadWriteBuf(&sdcard
.dev
, sdcard
.pendingOperation
.buffer
+ SDCARD_NON_DMA_CHUNK_SIZE
* sdcard
.pendingOperation
.chunkIndex
, NULL
, SDCARD_NON_DMA_CHUNK_SIZE
);
754 sdcard
.pendingOperation
.chunkIndex
++;
756 sendComplete
= sdcard
.pendingOperation
.chunkIndex
== SDCARD_BLOCK_SIZE
/ SDCARD_NON_DMA_CHUNK_SIZE
;
760 // Finish up by sending the CRC and checking the SD-card's acceptance/rejectance
761 if (sdcard_sendDataBlockFinish()) {
762 // The SD card is now busy committing that write to the card
763 sdcard
.state
= SDCARD_STATE_WAITING_FOR_WRITE
;
764 sdcard
.operationStartTime
= millis();
766 // Since we've transmitted the buffer we can go ahead and tell the caller their operation is complete
767 if (sdcard
.pendingOperation
.callback
) {
768 sdcard
.pendingOperation
.callback(SDCARD_BLOCK_OPERATION_WRITE
, sdcard
.pendingOperation
.blockIndex
, sdcard
.pendingOperation
.buffer
, sdcard
.pendingOperation
.callbackData
);
771 /* Our write was rejected! This could be due to a bad address but we hope not to attempt that, so assume
772 * the card is broken and needs reset.
776 // Announce write failure:
777 if (sdcard
.pendingOperation
.callback
) {
778 sdcard
.pendingOperation
.callback(SDCARD_BLOCK_OPERATION_WRITE
, sdcard
.pendingOperation
.blockIndex
, NULL
, sdcard
.pendingOperation
.callbackData
);
785 case SDCARD_STATE_WAITING_FOR_WRITE
:
786 if (sdcard_waitForIdle(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY
)) {
787 #ifdef SDCARD_PROFILING
788 profilingComplete
= true;
791 sdcard
.failureCount
= 0; // Assume the card is good if it can complete a write
793 // Still more blocks left to write in a multi-block chain?
794 if (sdcard
.multiWriteBlocksRemain
> 1) {
795 sdcard
.multiWriteBlocksRemain
--;
796 sdcard
.multiWriteNextBlock
++;
797 sdcard
.state
= SDCARD_STATE_WRITING_MULTIPLE_BLOCKS
;
798 } else if (sdcard
.multiWriteBlocksRemain
== 1) {
799 // This function changes the sd card state for us whether immediately succesful or delayed:
800 if (sdcard_endWriteBlocks() == SDCARD_OPERATION_SUCCESS
) {
803 #ifdef SDCARD_PROFILING
804 // Wait for the multi-block write to be terminated before finishing timing
805 profilingComplete
= false;
809 sdcard
.state
= SDCARD_STATE_READY
;
813 #ifdef SDCARD_PROFILING
814 if (profilingComplete
&& sdcard
.profiler
) {
815 sdcard
.profiler(SDCARD_BLOCK_OPERATION_WRITE
, sdcard
.pendingOperation
.blockIndex
, micros() - sdcard
.pendingOperation
.profileStartTime
);
818 } else if (millis() > sdcard
.operationStartTime
+ SDCARD_TIMEOUT_WRITE_MSEC
) {
820 * The caller has already been told that their write has completed, so they will have discarded
821 * their buffer and have no hope of retrying the operation. But this should be very rare and it allows
822 * them to reuse their buffer milliseconds faster than they otherwise would.
828 case SDCARD_STATE_READING
:
829 switch (sdcard_receiveDataBlock(sdcard
.pendingOperation
.buffer
, SDCARD_BLOCK_SIZE
)) {
830 case SDCARD_RECEIVE_SUCCESS
:
833 sdcard
.state
= SDCARD_STATE_READY
;
834 sdcard
.failureCount
= 0; // Assume the card is good if it can complete a read
836 #ifdef SDCARD_PROFILING
837 if (sdcard
.profiler
) {
838 sdcard
.profiler(SDCARD_BLOCK_OPERATION_READ
, sdcard
.pendingOperation
.blockIndex
, micros() - sdcard
.pendingOperation
.profileStartTime
);
842 if (sdcard
.pendingOperation
.callback
) {
843 sdcard
.pendingOperation
.callback(
844 SDCARD_BLOCK_OPERATION_READ
,
845 sdcard
.pendingOperation
.blockIndex
,
846 sdcard
.pendingOperation
.buffer
,
847 sdcard
.pendingOperation
.callbackData
851 case SDCARD_RECEIVE_BLOCK_IN_PROGRESS
:
852 if (millis() <= sdcard
.operationStartTime
+ SDCARD_TIMEOUT_READ_MSEC
) {
853 break; // Timeout not reached yet so keep waiting
855 // Timeout has expired, so fall through to convert to a fatal error
858 case SDCARD_RECEIVE_ERROR
:
863 if (sdcard
.pendingOperation
.callback
) {
864 sdcard
.pendingOperation
.callback(
865 SDCARD_BLOCK_OPERATION_READ
,
866 sdcard
.pendingOperation
.blockIndex
,
868 sdcard
.pendingOperation
.callbackData
876 case SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE
:
877 if (sdcard_waitForIdle(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY
)) {
880 sdcard
.state
= SDCARD_STATE_READY
;
882 #ifdef SDCARD_PROFILING
883 if (sdcard
.profiler
) {
884 sdcard
.profiler(SDCARD_BLOCK_OPERATION_WRITE
, sdcard
.pendingOperation
.blockIndex
, micros() - sdcard
.pendingOperation
.profileStartTime
);
887 } else if (millis() > sdcard
.operationStartTime
+ SDCARD_TIMEOUT_WRITE_MSEC
) {
892 case SDCARD_STATE_NOT_PRESENT
:
897 // Is the card's initialization taking too long?
898 if (sdcard
.state
>= SDCARD_STATE_RESET
&& sdcard
.state
< SDCARD_STATE_READY
899 && millis() - sdcard
.operationStartTime
> SDCARD_TIMEOUT_INIT_MILLIS
) {
903 return sdcard_isReady();
907 * Write the 512-byte block from the given buffer into the block with the given index.
909 * If the write does not complete immediately, your callback will be called later. If the write was successful, the
910 * buffer pointer will be the same buffer you originally passed in, otherwise the buffer will be set to NULL.
913 * SDCARD_OPERATION_IN_PROGRESS - Your buffer is currently being transmitted to the card and your callback will be
914 * called later to report the completion. The buffer pointer must remain valid until
916 * SDCARD_OPERATION_SUCCESS - Your buffer has been transmitted to the card now.
917 * SDCARD_OPERATION_BUSY - The card is already busy and cannot accept your write
918 * SDCARD_OPERATION_FAILURE - Your write was rejected by the card, card will be reset
920 static sdcardOperationStatus_e
sdcardSpi_writeBlock(uint32_t blockIndex
, uint8_t *buffer
, sdcard_operationCompleteCallback_c callback
, uint32_t callbackData
)
924 #ifdef SDCARD_PROFILING
925 sdcard
.pendingOperation
.profileStartTime
= micros();
929 switch (sdcard
.state
) {
930 case SDCARD_STATE_WRITING_MULTIPLE_BLOCKS
:
931 // Do we need to cancel the previous multi-block write?
932 if (blockIndex
!= sdcard
.multiWriteNextBlock
) {
933 if (sdcard_endWriteBlocks() == SDCARD_OPERATION_SUCCESS
) {
934 // Now we've entered the ready state, we can try again
937 return SDCARD_OPERATION_BUSY
;
941 // We're continuing a multi-block write
943 case SDCARD_STATE_READY
:
944 // We're not continuing a multi-block write so we need to send a single-block write command
947 // Standard size cards use byte addressing, high capacity cards use block addressing
948 status
= sdcard_sendCommand(SDCARD_COMMAND_WRITE_BLOCK
, sdcard
.highCapacity
? blockIndex
: blockIndex
* SDCARD_BLOCK_SIZE
);
955 return SDCARD_OPERATION_FAILURE
;
959 return SDCARD_OPERATION_BUSY
;
962 sdcard_sendDataBlockBegin(buffer
, sdcard
.state
== SDCARD_STATE_WRITING_MULTIPLE_BLOCKS
);
964 sdcard
.pendingOperation
.buffer
= buffer
;
965 sdcard
.pendingOperation
.blockIndex
= blockIndex
;
966 sdcard
.pendingOperation
.callback
= callback
;
967 sdcard
.pendingOperation
.callbackData
= callbackData
;
968 sdcard
.pendingOperation
.chunkIndex
= 1; // (for non-DMA transfers) we've sent chunk #0 already
969 sdcard
.state
= SDCARD_STATE_SENDING_WRITE
;
971 return SDCARD_OPERATION_IN_PROGRESS
;
975 * Begin writing a series of consecutive blocks beginning at the given block index. This will allow (but not require)
976 * the SD card to pre-erase the number of blocks you specifiy, which can allow the writes to complete faster.
978 * Afterwards, just call sdcard_writeBlock() as normal to write those blocks consecutively.
980 * It's okay to abort the multi-block write at any time by writing to a non-consecutive address, or by performing a read.
983 * SDCARD_OPERATION_SUCCESS - Multi-block write has been queued
984 * SDCARD_OPERATION_BUSY - The card is already busy and cannot accept your write
985 * SDCARD_OPERATION_FAILURE - A fatal error occured, card will be reset
987 static sdcardOperationStatus_e
sdcardSpi_beginWriteBlocks(uint32_t blockIndex
, uint32_t blockCount
)
989 if (sdcard
.state
!= SDCARD_STATE_READY
) {
990 if (sdcard
.state
== SDCARD_STATE_WRITING_MULTIPLE_BLOCKS
) {
991 if (blockIndex
== sdcard
.multiWriteNextBlock
) {
992 // Assume that the caller wants to continue the multi-block write they already have in progress!
993 return SDCARD_OPERATION_SUCCESS
;
994 } else if (sdcard_endWriteBlocks() != SDCARD_OPERATION_SUCCESS
) {
995 return SDCARD_OPERATION_BUSY
;
996 } // Else we've completed the previous multi-block write and can fall through to start the new one
998 return SDCARD_OPERATION_BUSY
;
1005 sdcard_sendAppCommand(SDCARD_ACOMMAND_SET_WR_BLOCK_ERASE_COUNT
, blockCount
) == 0
1006 && sdcard_sendCommand(SDCARD_COMMAND_WRITE_MULTIPLE_BLOCK
, sdcard
.highCapacity
? blockIndex
: blockIndex
* SDCARD_BLOCK_SIZE
) == 0
1008 sdcard
.state
= SDCARD_STATE_WRITING_MULTIPLE_BLOCKS
;
1009 sdcard
.multiWriteBlocksRemain
= blockCount
;
1010 sdcard
.multiWriteNextBlock
= blockIndex
;
1012 // Leave the card selected
1013 return SDCARD_OPERATION_SUCCESS
;
1019 return SDCARD_OPERATION_FAILURE
;
1024 * Read the 512-byte block with the given index into the given 512-byte buffer.
1026 * When the read completes, your callback will be called. If the read was successful, the buffer pointer will be the
1027 * same buffer you originally passed in, otherwise the buffer will be set to NULL.
1029 * You must keep the pointer to the buffer valid until the operation completes!
1032 * true - The operation was successfully queued for later completion, your callback will be called later
1033 * false - The operation could not be started due to the card being busy (try again later).
1035 static bool sdcardSpi_readBlock(uint32_t blockIndex
, uint8_t *buffer
, sdcard_operationCompleteCallback_c callback
, uint32_t callbackData
)
1037 if (sdcard
.state
!= SDCARD_STATE_READY
) {
1038 if (sdcard
.state
== SDCARD_STATE_WRITING_MULTIPLE_BLOCKS
) {
1039 if (sdcard_endWriteBlocks() != SDCARD_OPERATION_SUCCESS
) {
1047 #ifdef SDCARD_PROFILING
1048 sdcard
.pendingOperation
.profileStartTime
= micros();
1053 // Standard size cards use byte addressing, high capacity cards use block addressing
1054 uint8_t status
= sdcard_sendCommand(SDCARD_COMMAND_READ_SINGLE_BLOCK
, sdcard
.highCapacity
? blockIndex
: blockIndex
* SDCARD_BLOCK_SIZE
);
1057 sdcard
.pendingOperation
.buffer
= buffer
;
1058 sdcard
.pendingOperation
.blockIndex
= blockIndex
;
1059 sdcard
.pendingOperation
.callback
= callback
;
1060 sdcard
.pendingOperation
.callbackData
= callbackData
;
1062 sdcard
.state
= SDCARD_STATE_READING
;
1064 sdcard
.operationStartTime
= millis();
1066 // Leave the card selected for the whole transaction
1077 * Returns true if the SD card has successfully completed its startup procedures.
1079 static bool sdcardSpi_isInitialized(void)
1081 return sdcard
.state
>= SDCARD_STATE_READY
;
1084 static const sdcardMetadata_t
* sdcardSpi_getMetadata(void)
1086 return &sdcard
.metadata
;
1089 #ifdef SDCARD_PROFILING
1091 static void sdcardSpi_setProfilerCallback(sdcard_profilerCallback_c callback
)
1093 sdcard
.profiler
= callback
;
1098 sdcardVTable_t sdcardSpiVTable
= {
1101 sdcardSpi_readBlock
,
1102 sdcardSpi_beginWriteBlocks
,
1103 sdcardSpi_writeBlock
,
1105 sdcardSpi_isFunctional
,
1106 sdcardSpi_isInitialized
,
1107 sdcardSpi_getMetadata
,
1108 #ifdef SDCARD_PROFILING
1109 sdcardSpi_setProfilerCallback
,