bf1adc23e671a280996b262a12e75a494933d1a3
[SCSI2SD-V6.git] / software / SCSI2SD / src / sd.c
1 // Copyright (C) 2013 Michael McMaster <michael@codesrc.com>
2 //
3 // This file is part of SCSI2SD.
4 //
5 // SCSI2SD is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // SCSI2SD is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with SCSI2SD. If not, see <http://www.gnu.org/licenses/>.
17 #pragma GCC push_options
18 #pragma GCC optimize("-flto")
19
20 #include "device.h"
21 #include "scsi.h"
22 #include "config.h"
23 #include "disk.h"
24 #include "sd.h"
25 #include "led.h"
26 #include "time.h"
27 #include "trace.h"
28
29 #include "scsiPhy.h"
30
31 #include <string.h>
32
33 // Global
34 SdDevice sdDev;
35
36 enum SD_CMD_STATE { CMD_STATE_IDLE, CMD_STATE_READ, CMD_STATE_WRITE };
37 static int sdCmdState = CMD_STATE_IDLE;
38 static uint32_t sdCmdNextLBA; // Only valid in CMD_STATE_READ or CMD_STATE_WRITE
39 static uint32_t sdCmdTime;
40 static uint32_t sdLastCmdState = CMD_STATE_IDLE;
41
42 enum SD_IO_STATE { SD_DMA, SD_ACCEPTED, SD_IDLE };
43 static int sdIOState = SD_IDLE;
44
45 // Private DMA variables.
46 static uint8 sdDMARxChan = CY_DMA_INVALID_CHANNEL;
47 static uint8 sdDMATxChan = CY_DMA_INVALID_CHANNEL;
48
49 // Dummy location for DMA to send unchecked CRC bytes to
50 static uint8 discardBuffer __attribute__((aligned(4)));
51
52 // 2 bytes CRC, response, 8bits to close the clock..
53 // "NCR" time is up to 8 bytes.
54 static uint8_t writeResponseBuffer[8] __attribute__((aligned(4)));
55
56 // Padded with a dummy byte just to allow the tx DMA channel to
57 // use 2-byte bursts for performance.
58 static uint8_t writeStartToken[2] __attribute__((aligned(4))) = {0xFF, 0xFC};
59
60 // Source of dummy SPI bytes for DMA
61 static uint8_t dummyBuffer[2] __attribute__((aligned(4))) = {0xFF, 0xFF};
62
63 volatile uint8_t sdRxDMAComplete;
64 volatile uint8_t sdTxDMAComplete;
65
66 CY_ISR_PROTO(sdRxISR);
67 CY_ISR(sdRxISR)
68 {
69 sdRxDMAComplete = 1;
70 }
71 CY_ISR_PROTO(sdTxISR);
72 CY_ISR(sdTxISR)
73 {
74 sdTxDMAComplete = 1;
75 }
76
77 static uint8 sdCrc7(uint8* chr, uint8 cnt, uint8 crc)
78 {
79 uint8 a;
80 for(a = 0; a < cnt; a++)
81 {
82 uint8 Data = chr[a];
83 uint8 i;
84 for(i = 0; i < 8; i++)
85 {
86 crc <<= 1;
87 if( (Data & 0x80) ^ (crc & 0x80) ) {crc ^= 0x09;}
88 Data <<= 1;
89 }
90 }
91 return crc & 0x7F;
92 }
93
94
95 // Read and write 1 byte.
96 static uint8_t sdSpiByte(uint8_t value)
97 {
98 SDCard_WriteTxData(value);
99 trace(trace_spinSpiByte);
100 while (!(SDCard_ReadRxStatus() & SDCard_STS_RX_FIFO_NOT_EMPTY)) {}
101 trace(trace_sdSpiByte);
102 return SDCard_ReadRxData();
103 }
104
105 static void sdWaitWriteBusy()
106 {
107 uint8 val;
108 do
109 {
110 val = sdSpiByte(0xFF);
111 } while (val != 0xFF);
112 }
113
114 static void sdPreCmdState(uint32_t newState)
115 {
116 if (sdCmdState == CMD_STATE_READ)
117 {
118 sdCompleteRead();
119 }
120 else if (sdCmdState == CMD_STATE_WRITE)
121 {
122 sdCompleteWrite();
123 }
124 sdCmdState = CMD_STATE_IDLE;
125
126 if (sdLastCmdState != newState && newState != CMD_STATE_IDLE)
127 {
128 sdWaitWriteBusy();
129 sdLastCmdState = newState;
130 }
131 }
132
133 static uint16_t sdDoCommand(
134 uint8_t cmd,
135 uint32_t param,
136 int useCRC,
137 int use2byteResponse)
138 {
139 int waitWhileBusy = (cmd != SD_GO_IDLE_STATE) && (cmd != SD_STOP_TRANSMISSION);
140
141 // "busy" probe. We'll examine the results later.
142 if (waitWhileBusy)
143 {
144 SDCard_WriteTxData(0xFF);
145 }
146
147 // send is static as the address must remain consistent for the static
148 // DMA descriptors to work.
149 // Size must be divisible by 2 to suit 2-byte-burst TX DMA channel.
150 static uint8_t send[6] __attribute__((aligned(4)));
151 send[0] = cmd | 0x40;
152 send[1] = param >> 24;
153 send[2] = param >> 16;
154 send[3] = param >> 8;
155 send[4] = param;
156 if (unlikely(useCRC))
157 {
158 send[5] = (sdCrc7(send, 5, 0) << 1) | 1;
159 }
160 else
161 {
162 send[5] = 1; // stop bit
163 }
164
165 static uint8_t dmaRxTd = CY_DMA_INVALID_TD;
166 static uint8_t dmaTxTd = CY_DMA_INVALID_TD;
167 if (unlikely(dmaRxTd == CY_DMA_INVALID_TD))
168 {
169 dmaRxTd = CyDmaTdAllocate();
170 dmaTxTd = CyDmaTdAllocate();
171 CyDmaTdSetConfiguration(dmaTxTd, sizeof(send), CY_DMA_DISABLE_TD, TD_INC_SRC_ADR|SD_TX_DMA__TD_TERMOUT_EN);
172 CyDmaTdSetAddress(dmaTxTd, LO16((uint32)&send), LO16((uint32)SDCard_TXDATA_PTR));
173 CyDmaTdSetConfiguration(dmaRxTd, sizeof(send), CY_DMA_DISABLE_TD, SD_RX_DMA__TD_TERMOUT_EN);
174 CyDmaTdSetAddress(dmaRxTd, LO16((uint32)SDCard_RXDATA_PTR), LO16((uint32)&discardBuffer));
175 }
176
177 sdTxDMAComplete = 0;
178 sdRxDMAComplete = 0;
179
180 CyDmaChSetInitialTd(sdDMARxChan, dmaRxTd);
181 CyDmaChSetInitialTd(sdDMATxChan, dmaTxTd);
182
183 // Some Samsung cards enter a busy-state after single-sector reads.
184 // But we also need to wait for R1B to complete from the multi-sector
185 // reads.
186 if (waitWhileBusy)
187 {
188 trace(trace_spinSDRxFIFO);
189 while (!(SDCard_ReadRxStatus() & SDCard_STS_RX_FIFO_NOT_EMPTY)) {}
190 int busy = SDCard_ReadRxData() != 0xFF;
191 if (unlikely(busy))
192 {
193 trace(trace_spinSDBusy);
194 while (sdSpiByte(0xFF) != 0xFF) {}
195 }
196 }
197
198 // The DMA controller is a bit trigger-happy. It will retain
199 // a drq request that was triggered while the channel was
200 // disabled.
201 CyDmaChSetRequest(sdDMATxChan, CY_DMA_CPU_REQ);
202 CyDmaClearPendingDrq(sdDMARxChan);
203
204 // There is no flow control, so we must ensure we can read the bytes
205 // before we start transmitting
206 CyDmaChEnable(sdDMARxChan, 1);
207 CyDmaChEnable(sdDMATxChan, 1);
208
209 trace(trace_spinSDDMA);
210 int allComplete = 0;
211 while (!allComplete)
212 {
213 uint8_t intr = CyEnterCriticalSection();
214 allComplete = sdTxDMAComplete && sdRxDMAComplete;
215 if (!allComplete)
216 {
217 __WFI();
218 }
219 CyExitCriticalSection(intr);
220 }
221
222 uint16_t response = sdSpiByte(0xFF); // Result code or stuff byte
223 if (unlikely(cmd == SD_STOP_TRANSMISSION))
224 {
225 // Stuff byte is required for this command only.
226 // Part 1 Simplified standard 3.01
227 // "The stop command has an execution delay due to the serial command
228 // transmission."
229 response = sdSpiByte(0xFF);
230 }
231
232 uint32_t start = getTime_ms();
233
234 trace(trace_spinSDBusy);
235 while ((response & 0x80) && likely(elapsedTime_ms(start) <= 200))
236 {
237 response = sdSpiByte(0xFF);
238 }
239 if (unlikely(use2byteResponse))
240 {
241 response = (response << 8) | sdSpiByte(0xFF);
242 }
243 return response;
244 }
245
246
247 static inline uint16_t sdCommandAndResponse(uint8_t cmd, uint32_t param)
248 {
249 return sdDoCommand(cmd, param, 0, 0);
250 }
251
252 static inline uint16_t sdCRCCommandAndResponse(uint8_t cmd, uint32_t param)
253 {
254 return sdDoCommand(cmd, param, 1, 0);
255 }
256
257 // Clear the sticky status bits on error.
258 static void sdClearStatus()
259 {
260 sdSpiByte(0xFF);
261 uint16_t r2 = sdDoCommand(SD_SEND_STATUS, 0, 1, 1);
262 (void) r2;
263 }
264
265 void
266 sdReadMultiSectorPrep(uint32_t sdLBA, uint32_t sdSectors)
267 {
268 uint32_t tmpNextLBA = sdLBA + sdSectors;
269
270 if (!sdDev.ccs)
271 {
272 sdLBA = sdLBA * SD_SECTOR_SIZE;
273 tmpNextLBA = tmpNextLBA * SD_SECTOR_SIZE;
274 }
275
276 if (sdCmdState == CMD_STATE_READ && sdCmdNextLBA == sdLBA)
277 {
278 // Well, that was lucky. We're already reading this data
279 sdCmdNextLBA = tmpNextLBA;
280 sdCmdTime = getTime_ms();
281 }
282 else
283 {
284 sdPreCmdState(CMD_STATE_READ);
285
286 uint8_t v = sdCommandAndResponse(SD_READ_MULTIPLE_BLOCK, sdLBA);
287 if (unlikely(v))
288 {
289 scsiDiskReset();
290 sdClearStatus();
291
292 scsiDev.status = CHECK_CONDITION;
293 scsiDev.target->sense.code = HARDWARE_ERROR;
294 scsiDev.target->sense.asc = LOGICAL_UNIT_COMMUNICATION_FAILURE;
295 scsiDev.phase = STATUS;
296 }
297 else
298 {
299 sdCmdNextLBA = tmpNextLBA;
300 sdCmdState = CMD_STATE_READ;
301 sdCmdTime = getTime_ms();
302 }
303 }
304 }
305
306 static void
307 dmaReadSector(uint8_t* outputBuffer)
308 {
309 // Wait for a start-block token.
310 // Don't wait more than 200ms. The standard recommends 100ms.
311 uint32_t start = getTime_ms();
312 uint8_t token = sdSpiByte(0xFF);
313 trace(trace_spinSDBusy);
314 while (token != 0xFE && likely(elapsedTime_ms(start) <= 200))
315 {
316 if (unlikely(token && ((token & 0xE0) == 0)))
317 {
318 // Error token!
319 break;
320 }
321 token = sdSpiByte(0xFF);
322 }
323 if (unlikely(token != 0xFE))
324 {
325 if (transfer.multiBlock)
326 {
327 sdCompleteRead();
328 }
329 if (scsiDev.status != CHECK_CONDITION)
330 {
331 scsiDev.status = CHECK_CONDITION;
332 scsiDev.target->sense.code = HARDWARE_ERROR;
333 scsiDev.target->sense.asc = UNRECOVERED_READ_ERROR;
334 scsiDev.phase = STATUS;
335 }
336 sdClearStatus();
337 return;
338 }
339
340 static uint8_t dmaRxTd[2] = { CY_DMA_INVALID_TD, CY_DMA_INVALID_TD};
341 static uint8_t dmaTxTd = CY_DMA_INVALID_TD;
342 if (unlikely(dmaRxTd[0] == CY_DMA_INVALID_TD))
343 {
344 dmaRxTd[0] = CyDmaTdAllocate();
345 dmaRxTd[1] = CyDmaTdAllocate();
346 dmaTxTd = CyDmaTdAllocate();
347
348 // Receive 512 bytes of data and then 2 bytes CRC.
349 CyDmaTdSetConfiguration(dmaRxTd[0], SD_SECTOR_SIZE, dmaRxTd[1], TD_INC_DST_ADR);
350 CyDmaTdSetConfiguration(dmaRxTd[1], 2, CY_DMA_DISABLE_TD, SD_RX_DMA__TD_TERMOUT_EN);
351 CyDmaTdSetAddress(dmaRxTd[1], LO16((uint32)SDCard_RXDATA_PTR), LO16((uint32)&discardBuffer));
352
353 CyDmaTdSetConfiguration(dmaTxTd, SD_SECTOR_SIZE + 2, CY_DMA_DISABLE_TD, SD_TX_DMA__TD_TERMOUT_EN);
354 CyDmaTdSetAddress(dmaTxTd, LO16((uint32)&dummyBuffer), LO16((uint32)SDCard_TXDATA_PTR));
355
356 }
357 CyDmaTdSetAddress(dmaRxTd[0], LO16((uint32)SDCard_RXDATA_PTR), LO16((uint32)outputBuffer));
358
359 sdIOState = SD_DMA;
360 sdTxDMAComplete = 0;
361 sdRxDMAComplete = 0;
362
363 // Re-loading the initial TD's here is very important, or else
364 // we'll be re-using the last-used TD, which would be the last
365 // in the chain (ie. CRC TD)
366 CyDmaChSetInitialTd(sdDMARxChan, dmaRxTd[0]);
367 CyDmaChSetInitialTd(sdDMATxChan, dmaTxTd);
368
369 // The DMA controller is a bit trigger-happy. It will retain
370 // a drq request that was triggered while the channel was
371 // disabled.
372 CyDmaChSetRequest(sdDMATxChan, CY_DMA_CPU_REQ);
373 CyDmaClearPendingDrq(sdDMARxChan);
374
375 // There is no flow control, so we must ensure we can read the bytes
376 // before we start transmitting
377 CyDmaChEnable(sdDMARxChan, 1);
378 CyDmaChEnable(sdDMATxChan, 1);
379 }
380
381 int
382 sdReadSectorDMAPoll()
383 {
384 if (sdRxDMAComplete && sdTxDMAComplete)
385 {
386 // DMA transfer is complete
387 sdIOState = SD_IDLE;
388 return 1;
389 }
390 else
391 {
392 return 0;
393 }
394 }
395
396 void sdReadSingleSectorDMA(uint32_t lba, uint8_t* outputBuffer)
397 {
398 sdPreCmdState(CMD_STATE_READ);
399
400 uint8 v;
401 if (!sdDev.ccs)
402 {
403 lba = lba * SD_SECTOR_SIZE;
404 }
405 v = sdCommandAndResponse(SD_READ_SINGLE_BLOCK, lba);
406 if (unlikely(v))
407 {
408 scsiDiskReset();
409 sdClearStatus();
410
411 scsiDev.status = CHECK_CONDITION;
412 scsiDev.target->sense.code = HARDWARE_ERROR;
413 scsiDev.target->sense.asc = LOGICAL_UNIT_COMMUNICATION_FAILURE;
414 scsiDev.phase = STATUS;
415 }
416 else
417 {
418 dmaReadSector(outputBuffer);
419 }
420 }
421
422 void
423 sdReadMultiSectorDMA(uint8_t* outputBuffer)
424 {
425 // Pre: sdReadMultiSectorPrep called.
426 dmaReadSector(outputBuffer);
427 }
428
429 void sdCompleteRead()
430 {
431 if (unlikely(sdIOState != SD_IDLE))
432 {
433 // Not much choice but to wait until we've completed the transfer.
434 // Cancelling the transfer can't be done as we have no way to reset
435 // the SD card.
436 trace(trace_spinSDCompleteRead);
437 while (!sdReadSectorDMAPoll()) { /* spin */ }
438 }
439
440
441 if (sdCmdState == CMD_STATE_READ)
442 {
443 uint8 r1b = sdCommandAndResponse(SD_STOP_TRANSMISSION, 0);
444
445 if (unlikely(r1b) && (scsiDev.PHASE == DATA_IN))
446 {
447 scsiDev.status = CHECK_CONDITION;
448 scsiDev.target->sense.code = HARDWARE_ERROR;
449 scsiDev.target->sense.asc = UNRECOVERED_READ_ERROR;
450 scsiDev.phase = STATUS;
451 }
452 }
453
454 // R1b has an optional trailing "busy" signal, but we defer waiting on this.
455 // The next call so sdCommandAndResponse will wait for the busy state to
456 // clear.
457
458 sdCmdState = CMD_STATE_IDLE;
459 }
460
461 void
462 sdWriteMultiSectorDMA(uint8_t* outputBuffer)
463 {
464 static uint8_t dmaRxTd[2] = { CY_DMA_INVALID_TD, CY_DMA_INVALID_TD};
465 static uint8_t dmaTxTd[3] = { CY_DMA_INVALID_TD, CY_DMA_INVALID_TD, CY_DMA_INVALID_TD};
466 if (unlikely(dmaRxTd[0] == CY_DMA_INVALID_TD))
467 {
468 dmaRxTd[0] = CyDmaTdAllocate();
469 dmaRxTd[1] = CyDmaTdAllocate();
470 dmaTxTd[0] = CyDmaTdAllocate();
471 dmaTxTd[1] = CyDmaTdAllocate();
472 dmaTxTd[2] = CyDmaTdAllocate();
473
474 // Transmit 512 bytes of data and then 2 bytes CRC, and then get the response byte
475 // We need to do this without stopping the clock
476 CyDmaTdSetConfiguration(dmaTxTd[0], 2, dmaTxTd[1], TD_INC_SRC_ADR);
477 CyDmaTdSetAddress(dmaTxTd[0], LO16((uint32)&writeStartToken), LO16((uint32)SDCard_TXDATA_PTR));
478
479 CyDmaTdSetConfiguration(dmaTxTd[1], SD_SECTOR_SIZE, dmaTxTd[2], TD_INC_SRC_ADR);
480
481 CyDmaTdSetConfiguration(dmaTxTd[2], 2 + sizeof(writeResponseBuffer), CY_DMA_DISABLE_TD, SD_TX_DMA__TD_TERMOUT_EN);
482 CyDmaTdSetAddress(dmaTxTd[2], LO16((uint32)&dummyBuffer), LO16((uint32)SDCard_TXDATA_PTR));
483
484 CyDmaTdSetConfiguration(dmaRxTd[0], SD_SECTOR_SIZE + 4, dmaRxTd[1], 0);
485 CyDmaTdSetAddress(dmaRxTd[0], LO16((uint32)SDCard_RXDATA_PTR), LO16((uint32)&discardBuffer));
486 CyDmaTdSetConfiguration(dmaRxTd[1], sizeof(writeResponseBuffer), CY_DMA_DISABLE_TD, SD_RX_DMA__TD_TERMOUT_EN|TD_INC_DST_ADR);
487 CyDmaTdSetAddress(dmaRxTd[1], LO16((uint32)SDCard_RXDATA_PTR), LO16((uint32)&writeResponseBuffer));
488 }
489 CyDmaTdSetAddress(dmaTxTd[1], LO16((uint32)outputBuffer), LO16((uint32)SDCard_TXDATA_PTR));
490
491
492 sdIOState = SD_DMA;
493 // The DMA controller is a bit trigger-happy. It will retain
494 // a drq request that was triggered while the channel was
495 // disabled.
496 CyDmaChSetRequest(sdDMATxChan, CY_DMA_CPU_REQ);
497 CyDmaClearPendingDrq(sdDMARxChan);
498
499 sdTxDMAComplete = 0;
500 sdRxDMAComplete = 0;
501
502 // Re-loading the initial TD's here is very important, or else
503 // we'll be re-using the last-used TD, which would be the last
504 // in the chain (ie. CRC TD)
505 CyDmaChSetInitialTd(sdDMARxChan, dmaRxTd[0]);
506 CyDmaChSetInitialTd(sdDMATxChan, dmaTxTd[0]);
507
508 // There is no flow control, so we must ensure we can read the bytes
509 // before we start transmitting
510 CyDmaChEnable(sdDMARxChan, 1);
511 CyDmaChEnable(sdDMATxChan, 1);
512 }
513
514 int
515 sdWriteSectorDMAPoll()
516 {
517 if (sdRxDMAComplete && sdTxDMAComplete)
518 {
519 if (sdIOState == SD_DMA)
520 {
521 // Retry a few times. The data token format is:
522 // XXX0AAA1
523 int i = 0;
524 uint8_t dataToken;
525 do
526 {
527 dataToken = writeResponseBuffer[i]; // Response
528 ++i;
529 } while (((dataToken & 0x0101) != 1) && (i < sizeof(writeResponseBuffer)));
530
531 // At this point we should either have an accepted token, or we'll
532 // timeout and proceed into the error case below.
533 if (unlikely(((dataToken & 0x1F) >> 1) != 0x2)) // Accepted.
534 {
535 sdIOState = SD_IDLE;
536
537 sdWaitWriteBusy();
538 sdSpiByte(0xFD); // STOP TOKEN
539 sdWaitWriteBusy();
540
541 sdCmdState = CMD_STATE_IDLE;
542 scsiDiskReset();
543 sdClearStatus();
544
545 scsiDev.status = CHECK_CONDITION;
546 scsiDev.target->sense.code = HARDWARE_ERROR;
547 scsiDev.target->sense.asc = LOGICAL_UNIT_COMMUNICATION_FAILURE;
548 scsiDev.phase = STATUS;
549 }
550 else
551 {
552 sdIOState = SD_ACCEPTED;
553 }
554 }
555
556 if (sdIOState == SD_ACCEPTED)
557 {
558 // Wait while the SD card is busy
559 if (sdSpiByte(0xFF) == 0xFF)
560 {
561 sdIOState = SD_IDLE;
562 }
563 }
564
565 return sdIOState == SD_IDLE;
566 }
567 else
568 {
569 return 0;
570 }
571 }
572
573 void sdCompleteWrite()
574 {
575 if (unlikely(sdIOState != SD_IDLE))
576 {
577 // Not much choice but to wait until we've completed the transfer.
578 // Cancelling the transfer can't be done as we have no way to reset
579 // the SD card.
580 trace(trace_spinSDCompleteWrite);
581 while (!sdWriteSectorDMAPoll()) { /* spin */ }
582 }
583
584 if (sdCmdState == CMD_STATE_WRITE)
585 {
586 sdWaitWriteBusy();
587
588 sdSpiByte(0xFD); // STOP TOKEN
589
590 sdWaitWriteBusy();
591 }
592
593
594 if (likely(scsiDev.phase == DATA_OUT))
595 {
596 uint16_t r2 = sdDoCommand(SD_SEND_STATUS, 0, 0, 1);
597 if (unlikely(r2))
598 {
599 sdClearStatus();
600 scsiDev.status = CHECK_CONDITION;
601 scsiDev.target->sense.code = HARDWARE_ERROR;
602 scsiDev.target->sense.asc = WRITE_ERROR_AUTO_REALLOCATION_FAILED;
603 scsiDev.phase = STATUS;
604 }
605 }
606 sdCmdState = CMD_STATE_IDLE;
607 }
608
609 void sdCompleteTransfer()
610 {
611 sdPreCmdState(CMD_STATE_IDLE);
612 }
613
614
615 // SD Version 2 (SDHC) support
616 static int sendIfCond()
617 {
618 int retries = 50;
619
620 do
621 {
622 // 11:8 Host voltage. 1 = 2.7-3.6V
623 // 7:0 Echo bits. Ignore.
624 uint8 status = sdCRCCommandAndResponse(SD_SEND_IF_COND, 0x000001AA);
625
626 if (status == SD_R1_IDLE)
627 {
628 // Version 2 card.
629 sdDev.version = 2;
630 // Read 32bit response. Should contain the same bytes that
631 // we sent in the command parameter.
632 sdSpiByte(0xFF);
633 sdSpiByte(0xFF);
634 sdSpiByte(0xFF);
635 sdSpiByte(0xFF);
636 break;
637 }
638 else if (status & SD_R1_ILLEGAL)
639 {
640 // Version 1 card.
641 sdDev.version = 1;
642 sdClearStatus();
643 break;
644 }
645
646 sdClearStatus();
647 } while (--retries > 0);
648
649 return retries > 0;
650 }
651
652 static int sdOpCond()
653 {
654 uint32_t start = getTime_ms();
655
656 uint8 status;
657 do
658 {
659 sdCRCCommandAndResponse(SD_APP_CMD, 0);
660 // Host Capacity Support = 1 (SDHC/SDXC supported)
661 status = sdCRCCommandAndResponse(SD_APP_SEND_OP_COND, 0x40000000);
662
663 sdClearStatus();
664
665 // Spec says to poll for 1 second.
666 } while ((status != 0) && (elapsedTime_ms(start) < 1000));
667
668 return status == 0;
669 }
670
671 static int sdReadOCR()
672 {
673 uint32_t start = getTime_ms();
674 int complete;
675 uint8 status;
676
677 do
678 {
679 uint8 buf[4];
680 int i;
681
682 status = sdCRCCommandAndResponse(SD_READ_OCR, 0);
683 if(status) { break; }
684
685 for (i = 0; i < 4; ++i)
686 {
687 buf[i] = sdSpiByte(0xFF);
688 }
689
690 sdDev.ccs = (buf[0] & 0x40) ? 1 : 0;
691 complete = (buf[0] & 0x80);
692
693 } while (!status &&
694 !complete &&
695 (elapsedTime_ms(start) < 1000));
696
697 return (status == 0) && complete;
698 }
699
700 static void sdReadCID()
701 {
702 uint8 startToken;
703 int maxWait, i;
704
705 uint8 status = sdCRCCommandAndResponse(SD_SEND_CID, 0);
706 if(status){return;}
707
708 maxWait = 1023;
709 do
710 {
711 startToken = sdSpiByte(0xFF);
712 } while(maxWait-- && (startToken != 0xFE));
713 if (startToken != 0xFE) { return; }
714
715 for (i = 0; i < 16; ++i)
716 {
717 sdDev.cid[i] = sdSpiByte(0xFF);
718 }
719 sdSpiByte(0xFF); // CRC
720 sdSpiByte(0xFF); // CRC
721 }
722
723 static int sdReadCSD()
724 {
725 uint8 startToken;
726 int maxWait, i;
727
728 uint8 status = sdCRCCommandAndResponse(SD_SEND_CSD, 0);
729 if(status){goto bad;}
730
731 maxWait = 1023;
732 do
733 {
734 startToken = sdSpiByte(0xFF);
735 } while(maxWait-- && (startToken != 0xFE));
736 if (startToken != 0xFE) { goto bad; }
737
738 for (i = 0; i < 16; ++i)
739 {
740 sdDev.csd[i] = sdSpiByte(0xFF);
741 }
742 sdSpiByte(0xFF); // CRC
743 sdSpiByte(0xFF); // CRC
744
745 if ((sdDev.csd[0] >> 6) == 0x00)
746 {
747 // CSD version 1
748 // C_SIZE in bits [73:62]
749 uint32 c_size = (((((uint32)sdDev.csd[6]) & 0x3) << 16) | (((uint32)sdDev.csd[7]) << 8) | sdDev.csd[8]) >> 6;
750 uint32 c_mult = (((((uint32)sdDev.csd[9]) & 0x3) << 8) | ((uint32)sdDev.csd[0xa])) >> 7;
751 uint32 sectorSize = sdDev.csd[5] & 0x0F;
752 sdDev.capacity = ((c_size+1) * ((uint64)1 << (c_mult+2)) * ((uint64)1 << sectorSize)) / SD_SECTOR_SIZE;
753 }
754 else if ((sdDev.csd[0] >> 6) == 0x01)
755 {
756 // CSD version 2
757 // C_SIZE in bits [69:48]
758
759 uint32 c_size =
760 ((((uint32)sdDev.csd[7]) & 0x3F) << 16) |
761 (((uint32)sdDev.csd[8]) << 8) |
762 ((uint32)sdDev.csd[7]);
763 sdDev.capacity = (c_size + 1) * 1024;
764 }
765 else
766 {
767 goto bad;
768 }
769
770 return 1;
771 bad:
772 return 0;
773 }
774
775 static void sdInitDMA()
776 {
777 // One-time init only.
778 if (sdDMATxChan == CY_DMA_INVALID_CHANNEL)
779 {
780 sdDMATxChan =
781 SD_TX_DMA_DmaInitialize(
782 2, // Bytes per burst
783 1, // request per burst
784 HI16(CYDEV_SRAM_BASE),
785 HI16(CYDEV_PERIPH_BASE)
786 );
787
788 sdDMARxChan =
789 SD_RX_DMA_DmaInitialize(
790 1, // Bytes per burst
791 1, // request per burst
792 HI16(CYDEV_PERIPH_BASE),
793 HI16(CYDEV_SRAM_BASE)
794 );
795
796 CyDmaChDisable(sdDMATxChan);
797 CyDmaChDisable(sdDMARxChan);
798
799 SD_RX_DMA_COMPLETE_StartEx(sdRxISR);
800 SD_TX_DMA_COMPLETE_StartEx(sdTxISR);
801 }
802 }
803
804 int sdInit()
805 {
806 int result = 0;
807 int i;
808 uint8 v;
809
810 sdCmdState = CMD_STATE_IDLE;
811 sdDev.version = 0;
812 sdDev.ccs = 0;
813 sdDev.capacity = 0;
814 memset(sdDev.csd, 0, sizeof(sdDev.csd));
815 memset(sdDev.cid, 0, sizeof(sdDev.cid));
816
817 sdInitDMA();
818
819 SD_CS_SetDriveMode(SD_CS_DM_STRONG);
820 SD_CS_Write(1); // Set CS inactive (active low)
821
822 // Set the SPI clock for 400kHz transfers
823 // 25MHz / 400kHz approx factor of 63.
824 // The register contains (divider - 1)
825 uint16_t clkDiv25MHz = SD_Data_Clk_GetDividerRegister();
826 SD_Data_Clk_SetDivider(((clkDiv25MHz + 1) * 63) - 1);
827 // Wait for the clock to settle.
828 CyDelayUs(1);
829
830 SDCard_Start(); // Enable SPI hardware
831
832 // Power on sequence. 74 clock cycles of a "1" while CS unasserted.
833 for (i = 0; i < 10; ++i)
834 {
835 sdSpiByte(0xFF);
836 }
837
838 SD_CS_Write(0); // Set CS active (active low)
839 CyDelayUs(1);
840
841 sdSpiByte(0xFF);
842 v = sdDoCommand(SD_GO_IDLE_STATE, 0, 1, 0);
843 if(v != 1){goto bad;}
844
845 ledOn();
846 if (!sendIfCond()) goto bad; // Sets V1 or V2 flag CMD8
847 if (!sdOpCond()) goto bad; // ACMD41. Wait for init completes.
848 if (!sdReadOCR()) goto bad; // CMD58. Get CCS flag. Only valid after init.
849
850 // This command will be ignored if sdDev.ccs is set.
851 // SDHC and SDXC are always 512bytes.
852 v = sdCRCCommandAndResponse(SD_SET_BLOCKLEN, SD_SECTOR_SIZE); //Force sector size
853 if(v){goto bad;}
854 v = sdCRCCommandAndResponse(SD_CRC_ON_OFF, 0); //crc off
855 if(v){goto bad;}
856
857 // now set the sd card back to full speed.
858 // The SD Card spec says we can run SPI @ 25MHz
859 SDCard_Stop();
860
861 // We can't run at full-speed with the pullup resistors enabled.
862 SD_MISO_SetDriveMode(SD_MISO_DM_DIG_HIZ);
863 SD_MOSI_SetDriveMode(SD_MOSI_DM_STRONG);
864 SD_SCK_SetDriveMode(SD_SCK_DM_STRONG);
865
866 SD_Data_Clk_SetDivider(clkDiv25MHz);
867 CyDelayUs(1);
868 SDCard_Start();
869
870 // Clear out rubbish data through clock change
871 CyDelayUs(1);
872 SDCard_ReadRxStatus();
873 SDCard_ReadTxStatus();
874 SDCard_ClearFIFO();
875
876 if (!sdReadCSD()) goto bad;
877 sdReadCID();
878
879 result = 1;
880 goto out;
881
882 bad:
883 SD_Data_Clk_SetDivider(clkDiv25MHz); // Restore the clock for our next retry
884 sdDev.capacity = 0;
885
886 out:
887 sdClearStatus();
888 ledOff();
889 return result;
890
891 }
892
893 void sdWriteMultiSectorPrep(uint32_t sdLBA, uint32_t sdSectors)
894 {
895 uint32_t tmpNextLBA = sdLBA + sdSectors;
896
897 if (!sdDev.ccs)
898 {
899 sdLBA = sdLBA * SD_SECTOR_SIZE;
900 tmpNextLBA = tmpNextLBA * SD_SECTOR_SIZE;
901 }
902
903 if (sdCmdState == CMD_STATE_WRITE && sdCmdNextLBA == sdLBA)
904 {
905 // Well, that was lucky. We're already writing this data
906 sdCmdNextLBA = tmpNextLBA;
907 sdCmdTime = getTime_ms();
908 }
909 else
910 {
911 sdPreCmdState(CMD_STATE_WRITE);
912
913 // Set the number of blocks to pre-erase by the multiple block write
914 // command. We don't care about the response - if the command is not
915 // accepted, writes will just be a bit slower. Max 22bit parameter.
916 uint32 blocks = sdSectors > 0x7FFFFF ? 0x7FFFFF : sdSectors;
917 sdCommandAndResponse(SD_APP_CMD, 0);
918 sdCommandAndResponse(SD_APP_SET_WR_BLK_ERASE_COUNT, blocks);
919
920 uint8_t v = sdCommandAndResponse(SD_WRITE_MULTIPLE_BLOCK, sdLBA);
921 if (unlikely(v))
922 {
923 scsiDiskReset();
924 sdClearStatus();
925 scsiDev.status = CHECK_CONDITION;
926 scsiDev.target->sense.code = HARDWARE_ERROR;
927 scsiDev.target->sense.asc = LOGICAL_UNIT_COMMUNICATION_FAILURE;
928 scsiDev.phase = STATUS;
929 }
930 else
931 {
932 sdCmdTime = getTime_ms();
933 sdCmdNextLBA = tmpNextLBA;
934 sdCmdState = CMD_STATE_WRITE;
935 }
936 }
937 }
938
939 void sdPoll()
940 {
941 if ((scsiDev.phase == BUS_FREE) &&
942 (sdCmdState != CMD_STATE_IDLE) &&
943 (elapsedTime_ms(sdCmdTime) >= 50))
944 {
945 sdPreCmdState(CMD_STATE_IDLE);
946 }
947 }
948
949 void sdCheckPresent()
950 {
951 // Check if there's an SD card present.
952 if ((scsiDev.phase == BUS_FREE) &&
953 (sdIOState == SD_IDLE) &&
954 (sdCmdState == CMD_STATE_IDLE))
955 {
956 // The CS line is pulled high by the SD card.
957 // De-assert the line, and check if it's high.
958 // This isn't foolproof as it'll be left floating without
959 // an SD card. We can't use the built-in pull-down resistor as it will
960 // overpower the SD pullup resistor.
961 SD_CS_Write(0);
962 SD_CS_SetDriveMode(SD_CS_DM_DIG_HIZ);
963
964 // Delay extended to work with 60cm cables running cards at 2.85V
965 CyDelayCycles(128);
966 uint8_t cs = SD_CS_Read();
967 SD_CS_SetDriveMode(SD_CS_DM_STRONG) ;
968
969 if (cs && !(blockDev.state & DISK_PRESENT))
970 {
971 static int firstInit = 1;
972
973 // Debounce
974 CyDelay(250);
975
976 if (sdInit())
977 {
978 blockDev.state |= DISK_PRESENT | DISK_INITIALISED;
979
980 // Always "start" the device. Many systems (eg. Apple System 7)
981 // won't respond properly to
982 // LOGICAL_UNIT_NOT_READY_INITIALIZING_COMMAND_REQUIRED sense
983 // code, even if they stopped it first with
984 // START STOP UNIT command.
985 blockDev.state |= DISK_STARTED;
986
987 if (!firstInit)
988 {
989 int i;
990 for (i = 0; i < MAX_SCSI_TARGETS; ++i)
991 {
992 scsiDev.targets[i].unitAttention = PARAMETERS_CHANGED;
993 }
994 }
995 firstInit = 0;
996 }
997 }
998 else if (!cs && (blockDev.state & DISK_PRESENT))
999 {
1000 sdDev.capacity = 0;
1001 blockDev.state &= ~DISK_PRESENT;
1002 blockDev.state &= ~DISK_INITIALISED;
1003 int i;
1004 for (i = 0; i < MAX_SCSI_TARGETS; ++i)
1005 {
1006 scsiDev.targets[i].unitAttention = PARAMETERS_CHANGED;
1007 }
1008 }
1009 }
1010 }
1011
1012 #pragma GCC pop_options