-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
sdcard_spi.c
1088 lines (878 loc) · 36.8 KB
/
sdcard_spi.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of Cleanflight and Betaflight.
*
* Cleanflight and Betaflight are free software. You can redistribute
* this software and/or modify this software under the terms of the
* GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* Cleanflight and Betaflight are distributed in the hope that they
* will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software.
*
* If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdbool.h>
#include <stdint.h>
#include "platform.h"
#ifdef USE_SDCARD_SPI
#include "drivers/bus_spi.h"
#include "drivers/dma.h"
#include "drivers/dma_reqmap.h"
#include "drivers/io.h"
#include "drivers/nvic.h"
#include "drivers/time.h"
#include "pg/bus_spi.h"
#include "pg/sdcard.h"
#include "sdcard.h"
#include "sdcard_impl.h"
#include "sdcard_standard.h"
#ifdef AFATFS_USE_INTROSPECTIVE_LOGGING
#define SDCARD_PROFILING
#endif
#define SDCARD_INIT_NUM_DUMMY_BYTES 10
#define SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY 8
// Chosen so that CMD8 will have the same CRC as CMD0:
#define SDCARD_IF_COND_CHECK_PATTERN 0xAB
/* Spec calls for under 400KHz */
#define SDCARD_MAX_SPI_INIT_CLK_HZ 400000
/* Operational speed <= 25MHz */
#define SDCARD_MAX_SPI_CLK_HZ 25000000
#define SDCARD_SPI_MODE SPI_MODE0_POL_LOW_EDGE_1ST
//#define SDCARD_SPI_MODE SPI_MODE3_POL_HIGH_EDGE_2ND
/* Break up 512-byte SD card sectors into chunks of this size when writing without DMA to reduce the peak overhead
* per call to sdcard_poll().
*/
#define SDCARD_NON_DMA_CHUNK_SIZE 256
/**
* Returns true if the card has already been, or is currently, initializing and hasn't encountered enough errors to
* trip our error threshold and be disabled (i.e. our card is in and working!)
*/
static bool sdcardSpi_isFunctional(void)
{
return sdcard.state != SDCARD_STATE_NOT_PRESENT;
}
static void sdcard_deselect(void)
{
// As per the SD-card spec, give the card 8 dummy clocks so it can finish its operation
//spiReadWrite(&sdcard.dev, 0xFF);
spiWait(&sdcard.dev);
delayMicroseconds(10);
// Negate CS
spiRelease(&sdcard.dev);
}
/**
* Handle a failure of an SD card operation by resetting the card back to its initialization phase.
*
* Increments the failure counter, and when the failure threshold is reached, disables the card until
* the next call to sdcard_init().
*/
static void sdcard_reset(void)
{
if (!sdcard_isInserted()) {
sdcard.state = SDCARD_STATE_NOT_PRESENT;
return;
}
if (sdcard.state >= SDCARD_STATE_READY) {
spiSetClkDivisor(&sdcard.dev, spiCalculateDivider(SDCARD_MAX_SPI_INIT_CLK_HZ));
}
sdcard.failureCount++;
if (sdcard.failureCount >= SDCARD_MAX_CONSECUTIVE_FAILURES) {
sdcard.state = SDCARD_STATE_NOT_PRESENT;
} else {
sdcard.operationStartTime = millis();
sdcard.state = SDCARD_STATE_RESET;
}
}
// Called in ISR context
// Wait until idle indicated by a read value of 0xff
busStatus_e sdcard_callbackIdle(uint32_t arg)
{
sdcard_t *sdcard = (sdcard_t *)arg;
extDevice_t *dev = &sdcard->dev;
uint8_t idleByte = dev->bus->curSegment->u.buffers.rxData[0];
if (idleByte == 0xff) {
return BUS_READY;
}
if (--sdcard->idleCount == 0) {
dev->bus->curSegment->u.buffers.rxData[0] = 0x00;
return BUS_ABORT;
}
return BUS_BUSY;
}
// Called in ISR context
// Wait until idle is no longer indicated by a read value of 0xff
busStatus_e sdcard_callbackNotIdle(uint32_t arg)
{
sdcard_t *sdcard = (sdcard_t *)arg;
extDevice_t *dev = &sdcard->dev;
uint8_t idleByte = dev->bus->curSegment->u.buffers.rxData[0];
if (idleByte != 0xff) {
return BUS_READY;
}
if (sdcard->idleCount-- == 0) {
return BUS_ABORT;
}
return BUS_BUSY;
}
/**
* The SD card spec requires 8 clock cycles to be sent by us on the bus after most commands so it can finish its
* processing of that command. The easiest way for us to do this is to just wait for the bus to become idle before
* we transmit a command, sending at least 8-bits onto the bus when we do so.
*/
static bool sdcard_waitForIdle(int maxBytesToWait)
{
uint8_t idleByte;
// Note that this does not release the CS at the end of the transaction
busSegment_t segments[] = {
{.u.buffers = {NULL, &idleByte}, sizeof(idleByte), false, sdcard_callbackIdle},
{.u.link = {NULL, NULL}, 0, true, NULL},
};
sdcard.idleCount = maxBytesToWait;
spiSequence(&sdcard.dev, &segments[0]);
// Block pending completion of SPI access
spiWait(&sdcard.dev);
return (idleByte == 0xff);
}
/**
* Wait for up to maxDelay 0xFF idle bytes to arrive from the card, returning the first non-idle byte found.
*
* Returns 0xFF on failure.
*/
static uint8_t sdcard_waitForNonIdleByte(int maxDelay)
{
uint8_t idleByte;
// Note that this does not release the CS at the end of the transaction
busSegment_t segments[] = {
{.u.buffers = {NULL, &idleByte}, sizeof(idleByte), false, sdcard_callbackNotIdle},
{.u.link = {NULL, NULL}, 0, true, NULL},
};
sdcard.idleCount = maxDelay;
spiSequence(&sdcard.dev, &segments[0]);
// Block pending completion of SPI access
spiWait(&sdcard.dev);
return idleByte;
}
/**
* Waits up to SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY bytes for the card to become ready, send a command to the card
* with the given argument, waits up to SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY bytes for a reply, and returns the
* first non-0xFF byte of the reply.
*
* Upon failure, 0xFF is returned.
*/
static uint8_t sdcard_sendCommand(uint8_t commandCode, uint32_t commandArgument)
{
uint8_t command[6] = {
0x40 | commandCode,
commandArgument >> 24,
commandArgument >> 16,
commandArgument >> 8,
commandArgument,
0x95 /* Static CRC. This CRC is valid for CMD0 with a 0 argument, and CMD8 with 0x1AB argument, which are the only
commands that require a CRC */
};
uint8_t idleByte;
// Note that this does not release the CS at the end of the transaction
busSegment_t segments[] = {
{.u.buffers = {command, NULL}, sizeof(command), false, NULL},
{.u.buffers = {NULL, &idleByte}, sizeof(idleByte), false, sdcard_callbackNotIdle},
{.u.link = {NULL, NULL}, 0, true, NULL},
};
if (!sdcard_waitForIdle(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY) && commandCode != SDCARD_COMMAND_GO_IDLE_STATE)
return 0xFF;
sdcard.idleCount = SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY;
spiSequence(&sdcard.dev, &segments[0]);
// Block pending completion of SPI access
spiWait(&sdcard.dev);
return idleByte;
}
static uint8_t sdcard_sendAppCommand(uint8_t commandCode, uint32_t commandArgument)
{
sdcard_sendCommand(SDCARD_COMMAND_APP_CMD, 0);
return sdcard_sendCommand(commandCode, commandArgument);
}
/**
* Sends an IF_COND message to the card to check its version and validate its voltage requirements. Sets the global
* sdCardVersion with the detected version (0, 1, or 2) and returns true if the card is compatible.
*/
static bool sdcard_validateInterfaceCondition(void)
{
uint8_t ifCondReply[4];
sdcard.version = 0;
uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_SEND_IF_COND, (SDCARD_VOLTAGE_ACCEPTED_2_7_to_3_6 << 8) | SDCARD_IF_COND_CHECK_PATTERN);
// Don't deselect the card right away, because we'll want to read the rest of its reply if it's a V2 card
if (status == (SDCARD_R1_STATUS_BIT_ILLEGAL_COMMAND | SDCARD_R1_STATUS_BIT_IDLE)) {
// V1 cards don't support this command
sdcard.version = 1;
} else if (status == SDCARD_R1_STATUS_BIT_IDLE) {
// Note that this does not release the CS at the end of the transaction
busSegment_t segments[] = {
{.u.buffers = {NULL, ifCondReply}, sizeof(ifCondReply), false, NULL},
{.u.link = {NULL, NULL}, 0, true, NULL},
};
spiSequence(&sdcard.dev, &segments[0]);
// Block pending completion of SPI access
spiWait(&sdcard.dev);
/*
* We don't bother to validate the SDCard's operating voltage range since the spec requires it to accept our
* 3.3V, but do check that it echoed back our check pattern properly.
*/
if (ifCondReply[3] == SDCARD_IF_COND_CHECK_PATTERN) {
sdcard.version = 2;
}
}
sdcard_deselect();
return sdcard.version > 0;
}
static bool sdcard_readOCRRegister(uint32_t *result)
{
uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_READ_OCR, 0);
uint8_t response[4];
// Note that this does not release the CS at the end of the transaction
busSegment_t segments[] = {
{.u.buffers = {NULL, response}, sizeof(response), false, NULL},
{.u.link = {NULL, NULL}, 0, true, NULL},
};
spiSequence(&sdcard.dev, &segments[0]);
// Block pending completion of SPI access
spiWait(&sdcard.dev);
if (status == 0) {
sdcard_deselect();
*result = (response[0] << 24) | (response[1] << 16) | (response[2] << 8) | response[3];
return true;
} else {
sdcard_deselect();
return false;
}
}
typedef enum {
SDCARD_RECEIVE_SUCCESS,
SDCARD_RECEIVE_BLOCK_IN_PROGRESS,
SDCARD_RECEIVE_ERROR
} sdcardReceiveBlockStatus_e;
/**
* Attempt to receive a data block from the SD card.
*
* Return true on success, otherwise the card has not responded yet and you should retry later.
*/
static sdcardReceiveBlockStatus_e sdcard_receiveDataBlock(uint8_t *buffer, int count)
{
uint8_t dataToken = sdcard_waitForNonIdleByte(8);
if (dataToken == 0xFF) {
return SDCARD_RECEIVE_BLOCK_IN_PROGRESS;
}
if (dataToken != SDCARD_SINGLE_BLOCK_READ_START_TOKEN) {
return SDCARD_RECEIVE_ERROR;
}
// Note that this does not release the CS at the end of the transaction
busSegment_t segments[] = {
{.u.buffers = {NULL, buffer}, count, false, NULL},
// Discard trailing CRC, we don't care
{.u.buffers = {NULL, NULL}, 2, false, NULL},
{.u.link = {NULL, NULL}, 0, true, NULL},
};
spiSequence(&sdcard.dev, &segments[0]);
// Block pending completion of SPI access
spiWait(&sdcard.dev);
return SDCARD_RECEIVE_SUCCESS;
}
static bool sdcard_sendDataBlockFinish(void)
{
uint16_t dummyCRC = 0;
uint8_t dataResponseToken;
// Note that this does not release the CS at the end of the transaction
busSegment_t segments[] = {
{.u.buffers = {(uint8_t *)&dummyCRC, NULL}, sizeof(dummyCRC), false, NULL},
{.u.buffers = {NULL, &dataResponseToken}, sizeof(dataResponseToken), false, NULL},
{.u.link = {NULL, NULL}, 0, true, NULL},
};
spiSequence(&sdcard.dev, &segments[0]);
// Block pending completion of SPI access
spiWait(&sdcard.dev);
/*
* Check if the card accepted the write (no CRC error / no address error)
*
* The lower 5 bits are structured as follows:
* | 0 | Status | 1 |
* | 0 | x x x | 1 |
*
* Statuses:
* 010 - Data accepted
* 101 - CRC error
* 110 - Write error
*/
return (dataResponseToken & 0x1F) == 0x05;
}
/**
* Begin sending a buffer of SDCARD_BLOCK_SIZE bytes to the SD card.
*/
static void sdcard_sendDataBlockBegin(uint8_t *buffer, bool multiBlockWrite)
{
static uint8_t token;
token = multiBlockWrite ? SDCARD_MULTIPLE_BLOCK_WRITE_START_TOKEN : SDCARD_SINGLE_BLOCK_WRITE_START_TOKEN;
// Note that this does not release the CS at the end of the transaction
static busSegment_t segments[] = {
// Write a single 0xff
{.u.buffers = {NULL, NULL}, 1, false, NULL},
{.u.buffers = {&token, NULL}, sizeof(token), false, NULL},
{.u.buffers = {NULL, NULL}, 0, false, NULL},
{.u.link = {NULL, NULL}, 0, true, NULL},
};
segments[2].u.buffers.txData = buffer;
segments[2].len = spiUseDMA(&sdcard.dev) ? SDCARD_BLOCK_SIZE : SDCARD_NON_DMA_CHUNK_SIZE;
spiSequence(&sdcard.dev, &segments[0]);
// Don't block pending completion of SPI access
}
static bool sdcard_receiveCID(void)
{
uint8_t cid[16];
if (sdcard_receiveDataBlock(cid, sizeof(cid)) != SDCARD_RECEIVE_SUCCESS) {
return false;
}
sdcard.metadata.manufacturerID = cid[0];
sdcard.metadata.oemID = (cid[1] << 8) | cid[2];
sdcard.metadata.productName[0] = cid[3];
sdcard.metadata.productName[1] = cid[4];
sdcard.metadata.productName[2] = cid[5];
sdcard.metadata.productName[3] = cid[6];
sdcard.metadata.productName[4] = cid[7];
sdcard.metadata.productRevisionMajor = cid[8] >> 4;
sdcard.metadata.productRevisionMinor = cid[8] & 0x0F;
sdcard.metadata.productSerial = (cid[9] << 24) | (cid[10] << 16) | (cid[11] << 8) | cid[12];
sdcard.metadata.productionYear = (((cid[13] & 0x0F) << 4) | (cid[14] >> 4)) + 2000;
sdcard.metadata.productionMonth = cid[14] & 0x0F;
return true;
}
static bool sdcard_fetchCSD(void)
{
uint32_t readBlockLen, blockCount, blockCountMult;
uint64_t capacityBytes;
/* The CSD command's data block should always arrive within 8 idle clock cycles (SD card spec). This is because
* the information about card latency is stored in the CSD register itself, so we can't use that yet!
*/
bool success =
sdcard_sendCommand(SDCARD_COMMAND_SEND_CSD, 0) == 0
&& sdcard_receiveDataBlock((uint8_t*) &sdcard.csd, sizeof(sdcard.csd)) == SDCARD_RECEIVE_SUCCESS
&& SDCARD_GET_CSD_FIELD(sdcard.csd, 1, TRAILER) == 1;
if (success) {
switch (SDCARD_GET_CSD_FIELD(sdcard.csd, 1, CSD_STRUCTURE_VER)) {
case SDCARD_CSD_STRUCTURE_VERSION_1:
// Block size in bytes (doesn't have to be 512)
readBlockLen = 1 << SDCARD_GET_CSD_FIELD(sdcard.csd, 1, READ_BLOCK_LEN);
blockCountMult = 1 << (SDCARD_GET_CSD_FIELD(sdcard.csd, 1, CSIZE_MULT) + 2);
blockCount = (SDCARD_GET_CSD_FIELD(sdcard.csd, 1, CSIZE) + 1) * blockCountMult;
// We could do this in 32 bits but it makes the 2GB case awkward
capacityBytes = (uint64_t) blockCount * readBlockLen;
// Re-express that capacity (max 2GB) in our standard 512-byte block size
sdcard.metadata.numBlocks = capacityBytes / SDCARD_BLOCK_SIZE;
break;
case SDCARD_CSD_STRUCTURE_VERSION_2:
sdcard.metadata.numBlocks = (SDCARD_GET_CSD_FIELD(sdcard.csd, 2, CSIZE) + 1) * 1024;
break;
default:
success = false;
}
}
sdcard_deselect();
return success;
}
/**
* Check if the SD Card has completed its startup sequence. Must be called with sdcard.state == SDCARD_STATE_INITIALIZATION.
*
* Returns true if the card has finished its init process.
*/
static bool sdcard_checkInitDone(void)
{
uint8_t status = sdcard_sendAppCommand(SDCARD_ACOMMAND_SEND_OP_COND, sdcard.version == 2 ? 1 << 30 /* We support high capacity cards */ : 0);
sdcard_deselect();
// When card init is complete, the idle bit in the response becomes zero.
return status == 0x00;
}
void sdcardSpi_preInit(const sdcardConfig_t *config)
{
spiPreinitRegister(config->chipSelectTag, IOCFG_IPU, 1);
}
/**
* Begin the initialization process for the SD card. This must be called first before any other sdcard_ routine.
*/
static void sdcardSpi_init(const sdcardConfig_t *config, const spiPinConfig_t *spiConfig)
{
UNUSED(spiConfig);
sdcard.enabled = config->mode;
if (!sdcard.enabled) {
sdcard.state = SDCARD_STATE_NOT_PRESENT;
return;
}
spiSetBusInstance(&sdcard.dev, config->device);
IO_t chipSelectIO;
if (config->chipSelectTag) {
chipSelectIO = IOGetByTag(config->chipSelectTag);
IOInit(chipSelectIO, OWNER_SDCARD_CS, 0);
IOConfigGPIO(chipSelectIO, SPI_IO_CS_CFG);
} else {
chipSelectIO = IO_NONE;
}
sdcard.dev.busType_u.spi.csnPin = chipSelectIO;
// Set the clock phase/polarity
spiSetClkPhasePolarity(&sdcard.dev, true);
// Set the callback argument when calling back to this driver for DMA completion
sdcard.dev.callbackArg = (uint32_t)&sdcard;
// Max frequency is initially 400kHz
spiSetClkDivisor(&sdcard.dev, spiCalculateDivider(SDCARD_MAX_SPI_INIT_CLK_HZ));
// SDCard wants 1ms minimum delay after power is applied to it
delay(1000);
// Transmit at least 74 dummy clock cycles with CS high so the SD card can start up
IOHi(sdcard.dev.busType_u.spi.csnPin);
// Note that this does not release the CS at the end of the transaction
busSegment_t segments[] = {
// Write a single 0xff
{.u.buffers = {NULL, NULL}, SDCARD_INIT_NUM_DUMMY_BYTES, false, NULL},
{.u.link = {NULL, NULL}, 0, true, NULL},
};
spiSequence(&sdcard.dev, &segments[0]);
// Block pending completion of SPI access
spiWait(&sdcard.dev);
sdcard.operationStartTime = millis();
sdcard.state = SDCARD_STATE_RESET;
sdcard.failureCount = 0;
}
static bool sdcard_setBlockLength(uint32_t blockLen)
{
uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_SET_BLOCKLEN, blockLen);
sdcard_deselect();
return status == 0;
}
/*
* Returns true if the card is ready to accept read/write commands.
*/
static bool sdcard_isReady(void)
{
return sdcard.state == SDCARD_STATE_READY || sdcard.state == SDCARD_STATE_WRITING_MULTIPLE_BLOCKS;
}
/**
* Send the stop-transmission token to complete a multi-block write.
*
* Returns:
* SDCARD_OPERATION_IN_PROGRESS - We're now waiting for that stop to complete, the card will enter
* the SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE state.
* SDCARD_OPERATION_SUCCESS - The multi-block write finished immediately, the card will enter
* the SDCARD_READY state.
*
*/
static sdcardOperationStatus_e sdcard_endWriteBlocks(void)
{
uint8_t token = SDCARD_MULTIPLE_BLOCK_WRITE_STOP_TOKEN;
sdcard.multiWriteBlocksRemain = 0;
// Note that this does not release the CS at the end of the transaction
busSegment_t segments[] = {
// 8 dummy clocks to guarantee N_WR clocks between the last card response and this token
{.u.buffers = {NULL, NULL}, 1, false, NULL},
{.u.buffers = {&token, NULL}, sizeof(token), false, NULL},
{.u.link = {NULL, NULL}, 0, true, NULL},
};
spiSequence(&sdcard.dev, &segments[0]);
// Block pending completion of SPI access
spiWait(&sdcard.dev);
// Card may choose to raise a busy (non-0xFF) signal after at most N_BR (1 byte) delay
if (sdcard_waitForNonIdleByte(1) == 0xFF) {
sdcard.state = SDCARD_STATE_READY;
return SDCARD_OPERATION_SUCCESS;
} else {
sdcard.state = SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE;
sdcard.operationStartTime = millis();
return SDCARD_OPERATION_IN_PROGRESS;
}
}
/**
* Call periodically for the SD card to perform in-progress transfers.
*
* Returns true if the card is ready to accept commands.
*/
static bool sdcardSpi_poll(void)
{
if (!sdcard.enabled) {
sdcard.state = SDCARD_STATE_NOT_PRESENT;
return false;
}
uint8_t initStatus;
bool sendComplete;
#ifdef SDCARD_PROFILING
bool profilingComplete;
#endif
doMore:
switch (sdcard.state) {
case SDCARD_STATE_RESET:
initStatus = sdcard_sendCommand(SDCARD_COMMAND_GO_IDLE_STATE, 0);
sdcard_deselect();
if (initStatus == SDCARD_R1_STATUS_BIT_IDLE) {
// Check card voltage and version
if (sdcard_validateInterfaceCondition()) {
sdcard.state = SDCARD_STATE_CARD_INIT_IN_PROGRESS;
goto doMore;
} else {
// Bad reply/voltage, we ought to refrain from accessing the card.
sdcard.state = SDCARD_STATE_NOT_PRESENT;
}
}
break;
case SDCARD_STATE_CARD_INIT_IN_PROGRESS:
if (sdcard_checkInitDone()) {
if (sdcard.version == 2) {
// Check for high capacity card
uint32_t ocr;
if (!sdcard_readOCRRegister(&ocr)) {
sdcard_reset();
goto doMore;
}
sdcard.highCapacity = (ocr & (1 << 30)) != 0;
} else {
// Version 1 cards are always low-capacity
sdcard.highCapacity = false;
}
// Now fetch the CSD and CID registers
if (sdcard_fetchCSD()) {
uint8_t status = sdcard_sendCommand(SDCARD_COMMAND_SEND_CID, 0);
if (status == 0) {
// Keep the card selected to receive the response block
sdcard.state = SDCARD_STATE_INITIALIZATION_RECEIVE_CID;
goto doMore;
} else {
sdcard_deselect();
sdcard_reset();
goto doMore;
}
}
}
break;
case SDCARD_STATE_INITIALIZATION_RECEIVE_CID:
if (sdcard_receiveCID()) {
sdcard_deselect();
/* The spec is a little iffy on what the default block size is for Standard Size cards (it can be changed on
* standard size cards) so let's just set it to 512 explicitly so we don't have a problem.
*/
if (!sdcard.highCapacity && !sdcard_setBlockLength(SDCARD_BLOCK_SIZE)) {
sdcard_reset();
goto doMore;
}
// Now we're done with init and we can switch to the full speed clock (<25MHz)
spiSetClkDivisor(&sdcard.dev, spiCalculateDivider(SDCARD_MAX_SPI_CLK_HZ));
sdcard.multiWriteBlocksRemain = 0;
sdcard.state = SDCARD_STATE_READY;
goto doMore;
} // else keep waiting for the CID to arrive
break;
case SDCARD_STATE_SENDING_WRITE:
// Have we finished sending the write yet?
sendComplete = !spiIsBusy(&sdcard.dev);
if (!spiUseDMA(&sdcard.dev)) {
// Send another chunk
spiReadWriteBuf(&sdcard.dev, sdcard.pendingOperation.buffer + SDCARD_NON_DMA_CHUNK_SIZE * sdcard.pendingOperation.chunkIndex, NULL, SDCARD_NON_DMA_CHUNK_SIZE);
sdcard.pendingOperation.chunkIndex++;
sendComplete = sdcard.pendingOperation.chunkIndex == SDCARD_BLOCK_SIZE / SDCARD_NON_DMA_CHUNK_SIZE;
}
if (sendComplete) {
// Finish up by sending the CRC and checking the SD-card's acceptance/rejectance
if (sdcard_sendDataBlockFinish()) {
// The SD card is now busy committing that write to the card
sdcard.state = SDCARD_STATE_WAITING_FOR_WRITE;
sdcard.operationStartTime = millis();
// Since we've transmitted the buffer we can go ahead and tell the caller their operation is complete
if (sdcard.pendingOperation.callback) {
sdcard.pendingOperation.callback(SDCARD_BLOCK_OPERATION_WRITE, sdcard.pendingOperation.blockIndex, sdcard.pendingOperation.buffer, sdcard.pendingOperation.callbackData);
}
} else {
/* Our write was rejected! This could be due to a bad address but we hope not to attempt that, so assume
* the card is broken and needs reset.
*/
sdcard_reset();
// Announce write failure:
if (sdcard.pendingOperation.callback) {
sdcard.pendingOperation.callback(SDCARD_BLOCK_OPERATION_WRITE, sdcard.pendingOperation.blockIndex, NULL, sdcard.pendingOperation.callbackData);
}
goto doMore;
}
}
break;
case SDCARD_STATE_WAITING_FOR_WRITE:
if (sdcard_waitForIdle(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY)) {
#ifdef SDCARD_PROFILING
profilingComplete = true;
#endif
sdcard.failureCount = 0; // Assume the card is good if it can complete a write
// Still more blocks left to write in a multi-block chain?
if (sdcard.multiWriteBlocksRemain > 1) {
sdcard.multiWriteBlocksRemain--;
sdcard.multiWriteNextBlock++;
sdcard.state = SDCARD_STATE_WRITING_MULTIPLE_BLOCKS;
} else if (sdcard.multiWriteBlocksRemain == 1) {
// This function changes the sd card state for us whether immediately succesful or delayed:
if (sdcard_endWriteBlocks() == SDCARD_OPERATION_SUCCESS) {
sdcard_deselect();
} else {
#ifdef SDCARD_PROFILING
// Wait for the multi-block write to be terminated before finishing timing
profilingComplete = false;
#endif
}
} else {
sdcard.state = SDCARD_STATE_READY;
sdcard_deselect();
}
#ifdef SDCARD_PROFILING
if (profilingComplete && sdcard.profiler) {
sdcard.profiler(SDCARD_BLOCK_OPERATION_WRITE, sdcard.pendingOperation.blockIndex, micros() - sdcard.pendingOperation.profileStartTime);
}
#endif
} else if (millis() > sdcard.operationStartTime + SDCARD_TIMEOUT_WRITE_MSEC) {
/*
* The caller has already been told that their write has completed, so they will have discarded
* their buffer and have no hope of retrying the operation. But this should be very rare and it allows
* them to reuse their buffer milliseconds faster than they otherwise would.
*/
sdcard_reset();
goto doMore;
}
break;
case SDCARD_STATE_READING:
switch (sdcard_receiveDataBlock(sdcard.pendingOperation.buffer, SDCARD_BLOCK_SIZE)) {
case SDCARD_RECEIVE_SUCCESS:
sdcard_deselect();
sdcard.state = SDCARD_STATE_READY;
sdcard.failureCount = 0; // Assume the card is good if it can complete a read
#ifdef SDCARD_PROFILING
if (sdcard.profiler) {
sdcard.profiler(SDCARD_BLOCK_OPERATION_READ, sdcard.pendingOperation.blockIndex, micros() - sdcard.pendingOperation.profileStartTime);
}
#endif
if (sdcard.pendingOperation.callback) {
sdcard.pendingOperation.callback(
SDCARD_BLOCK_OPERATION_READ,
sdcard.pendingOperation.blockIndex,
sdcard.pendingOperation.buffer,
sdcard.pendingOperation.callbackData
);
}
break;
case SDCARD_RECEIVE_BLOCK_IN_PROGRESS:
if (millis() <= sdcard.operationStartTime + SDCARD_TIMEOUT_READ_MSEC) {
break; // Timeout not reached yet so keep waiting
}
// Timeout has expired, so fall through to convert to a fatal error
FALLTHROUGH;
case SDCARD_RECEIVE_ERROR:
sdcard_deselect();
sdcard_reset();
if (sdcard.pendingOperation.callback) {
sdcard.pendingOperation.callback(
SDCARD_BLOCK_OPERATION_READ,
sdcard.pendingOperation.blockIndex,
NULL,
sdcard.pendingOperation.callbackData
);
}
goto doMore;
break;
}
break;
case SDCARD_STATE_STOPPING_MULTIPLE_BLOCK_WRITE:
if (sdcard_waitForIdle(SDCARD_MAXIMUM_BYTE_DELAY_FOR_CMD_REPLY)) {
sdcard_deselect();
sdcard.state = SDCARD_STATE_READY;
#ifdef SDCARD_PROFILING
if (sdcard.profiler) {
sdcard.profiler(SDCARD_BLOCK_OPERATION_WRITE, sdcard.pendingOperation.blockIndex, micros() - sdcard.pendingOperation.profileStartTime);
}
#endif
} else if (millis() > sdcard.operationStartTime + SDCARD_TIMEOUT_WRITE_MSEC) {
sdcard_reset();
goto doMore;
}
break;
case SDCARD_STATE_NOT_PRESENT:
default:
;
}
// Is the card's initialization taking too long?
if (sdcard.state >= SDCARD_STATE_RESET && sdcard.state < SDCARD_STATE_READY
&& millis() - sdcard.operationStartTime > SDCARD_TIMEOUT_INIT_MILLIS) {
sdcard_reset();
}
return sdcard_isReady();
}
/**
* Write the 512-byte block from the given buffer into the block with the given index.
*
* If the write does not complete immediately, your callback will be called later. If the write was successful, the
* buffer pointer will be the same buffer you originally passed in, otherwise the buffer will be set to NULL.
*
* Returns:
* SDCARD_OPERATION_IN_PROGRESS - Your buffer is currently being transmitted to the card and your callback will be
* called later to report the completion. The buffer pointer must remain valid until
* that time.
* SDCARD_OPERATION_SUCCESS - Your buffer has been transmitted to the card now.
* SDCARD_OPERATION_BUSY - The card is already busy and cannot accept your write
* SDCARD_OPERATION_FAILURE - Your write was rejected by the card, card will be reset
*/
static sdcardOperationStatus_e sdcardSpi_writeBlock(uint32_t blockIndex, uint8_t *buffer, sdcard_operationCompleteCallback_c callback, uint32_t callbackData)
{
uint8_t status;
#ifdef SDCARD_PROFILING
sdcard.pendingOperation.profileStartTime = micros();
#endif
doMore:
switch (sdcard.state) {
case SDCARD_STATE_WRITING_MULTIPLE_BLOCKS:
// Do we need to cancel the previous multi-block write?
if (blockIndex != sdcard.multiWriteNextBlock) {
if (sdcard_endWriteBlocks() == SDCARD_OPERATION_SUCCESS) {
// Now we've entered the ready state, we can try again
goto doMore;
} else {
return SDCARD_OPERATION_BUSY;
}
}
// We're continuing a multi-block write
break;
case SDCARD_STATE_READY:
// We're not continuing a multi-block write so we need to send a single-block write command
// Standard size cards use byte addressing, high capacity cards use block addressing
status = sdcard_sendCommand(SDCARD_COMMAND_WRITE_BLOCK, sdcard.highCapacity ? blockIndex : blockIndex * SDCARD_BLOCK_SIZE);
if (status != 0) {
sdcard_deselect();
sdcard_reset();
return SDCARD_OPERATION_FAILURE;
}
break;
default:
return SDCARD_OPERATION_BUSY;
}
sdcard_sendDataBlockBegin(buffer, sdcard.state == SDCARD_STATE_WRITING_MULTIPLE_BLOCKS);
sdcard.pendingOperation.buffer = buffer;
sdcard.pendingOperation.blockIndex = blockIndex;
sdcard.pendingOperation.callback = callback;
sdcard.pendingOperation.callbackData = callbackData;
sdcard.pendingOperation.chunkIndex = 1; // (for non-DMA transfers) we've sent chunk #0 already
sdcard.state = SDCARD_STATE_SENDING_WRITE;
return SDCARD_OPERATION_IN_PROGRESS;
}
/**
* Begin writing a series of consecutive blocks beginning at the given block index. This will allow (but not require)
* the SD card to pre-erase the number of blocks you specifiy, which can allow the writes to complete faster.
*
* Afterwards, just call sdcard_writeBlock() as normal to write those blocks consecutively.
*
* It's okay to abort the multi-block write at any time by writing to a non-consecutive address, or by performing a read.
*
* Returns:
* SDCARD_OPERATION_SUCCESS - Multi-block write has been queued
* SDCARD_OPERATION_BUSY - The card is already busy and cannot accept your write
* SDCARD_OPERATION_FAILURE - A fatal error occured, card will be reset
*/
static sdcardOperationStatus_e sdcardSpi_beginWriteBlocks(uint32_t blockIndex, uint32_t blockCount)
{
if (sdcard.state != SDCARD_STATE_READY) {
if (sdcard.state == SDCARD_STATE_WRITING_MULTIPLE_BLOCKS) {
if (blockIndex == sdcard.multiWriteNextBlock) {
// Assume that the caller wants to continue the multi-block write they already have in progress!
return SDCARD_OPERATION_SUCCESS;
} else if (sdcard_endWriteBlocks() != SDCARD_OPERATION_SUCCESS) {
return SDCARD_OPERATION_BUSY;
} // Else we've completed the previous multi-block write and can fall through to start the new one
} else {
return SDCARD_OPERATION_BUSY;
}
}
if (
sdcard_sendAppCommand(SDCARD_ACOMMAND_SET_WR_BLOCK_ERASE_COUNT, blockCount) == 0
&& sdcard_sendCommand(SDCARD_COMMAND_WRITE_MULTIPLE_BLOCK, sdcard.highCapacity ? blockIndex : blockIndex * SDCARD_BLOCK_SIZE) == 0
) {
sdcard.state = SDCARD_STATE_WRITING_MULTIPLE_BLOCKS;
sdcard.multiWriteBlocksRemain = blockCount;
sdcard.multiWriteNextBlock = blockIndex;
// Leave the card selected
return SDCARD_OPERATION_SUCCESS;
} else {
sdcard_deselect();
sdcard_reset();
return SDCARD_OPERATION_FAILURE;
}
}
/**