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