1 // Copyright (C) 2013 Michael McMaster <michael@codesrc.com>
\r
3 // This file is part of SCSI2SD.
\r
5 // SCSI2SD is free software: you can redistribute it and/or modify
\r
6 // it under the terms of the GNU General Public License as published by
\r
7 // the Free Software Foundation, either version 3 of the License, or
\r
8 // (at your option) any later version.
\r
10 // SCSI2SD is distributed in the hope that it will be useful,
\r
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
\r
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
\r
13 // GNU General Public License for more details.
\r
15 // You should have received a copy of the GNU General Public License
\r
16 // along with SCSI2SD. If not, see <http://www.gnu.org/licenses/>.
\r
17 #pragma GCC push_options
\r
18 #pragma GCC optimize("-flto")
\r
29 #include "scsiPhy.h"
\r
36 enum SD_CMD_STATE { CMD_STATE_IDLE, CMD_STATE_READ, CMD_STATE_WRITE };
\r
37 static int sdCmdState = CMD_STATE_IDLE;
\r
38 static uint32_t sdCmdNextLBA; // Only valid in CMD_STATE_READ or CMD_STATE_WRITE
\r
39 static uint32_t sdCmdTime;
\r
40 static uint32_t sdLastCmdState = CMD_STATE_IDLE;
\r
42 enum SD_IO_STATE { SD_DMA, SD_ACCEPTED, SD_IDLE };
\r
43 static int sdIOState = SD_IDLE;
\r
45 // Private DMA variables.
\r
46 static uint8 sdDMARxChan = CY_DMA_INVALID_CHANNEL;
\r
47 static uint8 sdDMATxChan = CY_DMA_INVALID_CHANNEL;
\r
49 // Dummy location for DMA to send unchecked CRC bytes to
\r
50 static uint8 discardBuffer __attribute__((aligned(4)));
\r
52 // 2 bytes CRC, response, 8bits to close the clock..
\r
53 // "NCR" time is up to 8 bytes.
\r
54 static uint8_t writeResponseBuffer[8] __attribute__((aligned(4)));
\r
56 // Padded with a dummy byte just to allow the tx DMA channel to
\r
57 // use 2-byte bursts for performance.
\r
58 static uint8_t writeStartToken[2] __attribute__((aligned(4))) = {0xFF, 0xFC};
\r
60 // Source of dummy SPI bytes for DMA
\r
61 static uint8_t dummyBuffer[2] __attribute__((aligned(4))) = {0xFF, 0xFF};
\r
63 volatile uint8_t sdRxDMAComplete;
\r
64 volatile uint8_t sdTxDMAComplete;
\r
66 static void sdCompleteRead();
\r
67 static void sdCompleteWrite();
\r
69 CY_ISR_PROTO(sdRxISR);
\r
72 sdRxDMAComplete = 1;
\r
74 CY_ISR_PROTO(sdTxISR);
\r
77 sdTxDMAComplete = 1;
\r
80 static uint8 sdCrc7(uint8* chr, uint8 cnt, uint8 crc)
\r
83 for(a = 0; a < cnt; a++)
\r
85 uint8 Data = chr[a];
\r
87 for(i = 0; i < 8; i++)
\r
90 if( (Data & 0x80) ^ (crc & 0x80) ) {crc ^= 0x09;}
\r
98 // Read and write 1 byte.
\r
99 static uint8_t sdSpiByte(uint8_t value)
\r
101 SDCard_WriteTxData(value);
\r
102 trace(trace_spinSpiByte);
\r
103 while (!(SDCard_ReadRxStatus() & SDCard_STS_RX_FIFO_NOT_EMPTY)) {}
\r
104 trace(trace_sdSpiByte);
\r
105 return SDCard_ReadRxData();
\r
108 static void sdWaitWriteBusy()
\r
113 val = sdSpiByte(0xFF);
\r
114 } while (val != 0xFF);
\r
117 static void sdPreCmdState(uint32_t newState)
\r
119 if (sdCmdState == CMD_STATE_READ)
\r
123 else if (sdCmdState == CMD_STATE_WRITE)
\r
127 sdCmdState = CMD_STATE_IDLE;
\r
129 if (sdLastCmdState != newState && newState != CMD_STATE_IDLE)
\r
132 sdLastCmdState = newState;
\r
136 static uint16_t sdDoCommand(
\r
140 int use2byteResponse)
\r
142 int waitWhileBusy = (cmd != SD_GO_IDLE_STATE) && (cmd != SD_STOP_TRANSMISSION);
\r
144 // "busy" probe. We'll examine the results later.
\r
147 SDCard_WriteTxData(0xFF);
\r
150 // send is static as the address must remain consistent for the static
\r
151 // DMA descriptors to work.
\r
152 // Size must be divisible by 2 to suit 2-byte-burst TX DMA channel.
\r
153 static uint8_t send[6] __attribute__((aligned(4)));
\r
154 send[0] = cmd | 0x40;
\r
155 send[1] = param >> 24;
\r
156 send[2] = param >> 16;
\r
157 send[3] = param >> 8;
\r
159 if (unlikely(useCRC))
\r
161 send[5] = (sdCrc7(send, 5, 0) << 1) | 1;
\r
165 send[5] = 1; // stop bit
\r
168 static uint8_t dmaRxTd = CY_DMA_INVALID_TD;
\r
169 static uint8_t dmaTxTd = CY_DMA_INVALID_TD;
\r
170 if (unlikely(dmaRxTd == CY_DMA_INVALID_TD))
\r
172 dmaRxTd = CyDmaTdAllocate();
\r
173 dmaTxTd = CyDmaTdAllocate();
\r
174 CyDmaTdSetConfiguration(dmaTxTd, sizeof(send), CY_DMA_DISABLE_TD, TD_INC_SRC_ADR|SD_TX_DMA__TD_TERMOUT_EN);
\r
175 CyDmaTdSetAddress(dmaTxTd, LO16((uint32)&send), LO16((uint32)SDCard_TXDATA_PTR));
\r
176 CyDmaTdSetConfiguration(dmaRxTd, sizeof(send), CY_DMA_DISABLE_TD, SD_RX_DMA__TD_TERMOUT_EN);
\r
177 CyDmaTdSetAddress(dmaRxTd, LO16((uint32)SDCard_RXDATA_PTR), LO16((uint32)&discardBuffer));
\r
180 sdTxDMAComplete = 0;
\r
181 sdRxDMAComplete = 0;
\r
183 CyDmaChSetInitialTd(sdDMARxChan, dmaRxTd);
\r
184 CyDmaChSetInitialTd(sdDMATxChan, dmaTxTd);
\r
186 // Some Samsung cards enter a busy-state after single-sector reads.
\r
187 // But we also need to wait for R1B to complete from the multi-sector
\r
191 trace(trace_spinSDRxFIFO);
\r
192 while (!(SDCard_ReadRxStatus() & SDCard_STS_RX_FIFO_NOT_EMPTY)) {}
\r
193 int busy = SDCard_ReadRxData() != 0xFF;
\r
194 if (unlikely(busy))
\r
196 trace(trace_spinSDBusy);
\r
197 while (sdSpiByte(0xFF) != 0xFF) {}
\r
201 // The DMA controller is a bit trigger-happy. It will retain
\r
202 // a drq request that was triggered while the channel was
\r
204 CyDmaChSetRequest(sdDMATxChan, CY_DMA_CPU_REQ);
\r
205 CyDmaClearPendingDrq(sdDMARxChan);
\r
207 // There is no flow control, so we must ensure we can read the bytes
\r
208 // before we start transmitting
\r
209 CyDmaChEnable(sdDMARxChan, 1);
\r
210 CyDmaChEnable(sdDMATxChan, 1);
\r
212 trace(trace_spinSDDMA);
\r
213 int allComplete = 0;
\r
214 while (!allComplete)
\r
216 uint8_t intr = CyEnterCriticalSection();
\r
217 allComplete = sdTxDMAComplete && sdRxDMAComplete;
\r
222 CyExitCriticalSection(intr);
\r
225 uint16_t response = sdSpiByte(0xFF); // Result code or stuff byte
\r
226 if (unlikely(cmd == SD_STOP_TRANSMISSION))
\r
228 // Stuff byte is required for this command only.
\r
229 // Part 1 Simplified standard 3.01
\r
230 // "The stop command has an execution delay due to the serial command
\r
232 response = sdSpiByte(0xFF);
\r
235 uint32_t start = getTime_ms();
\r
237 trace(trace_spinSDBusy);
\r
238 while ((response & 0x80) && likely(elapsedTime_ms(start) <= 200))
\r
240 response = sdSpiByte(0xFF);
\r
242 if (unlikely(use2byteResponse))
\r
244 response = (response << 8) | sdSpiByte(0xFF);
\r
250 static inline uint16_t sdCommandAndResponse(uint8_t cmd, uint32_t param)
\r
252 return sdDoCommand(cmd, param, 0, 0);
\r
255 static inline uint16_t sdCRCCommandAndResponse(uint8_t cmd, uint32_t param)
\r
257 return sdDoCommand(cmd, param, 1, 0);
\r
260 // Clear the sticky status bits on error.
\r
261 static void sdClearStatus()
\r
264 uint16_t r2 = sdDoCommand(SD_SEND_STATUS, 0, 1, 1);
\r
269 sdReadMultiSectorPrep(uint32_t sdLBA, uint32_t sdSectors)
\r
271 uint32_t tmpNextLBA = sdLBA + sdSectors;
\r
275 sdLBA = sdLBA * SD_SECTOR_SIZE;
\r
276 tmpNextLBA = tmpNextLBA * SD_SECTOR_SIZE;
\r
279 if (sdCmdState == CMD_STATE_READ && sdCmdNextLBA == sdLBA)
\r
281 // Well, that was lucky. We're already reading this data
\r
282 sdCmdNextLBA = tmpNextLBA;
\r
283 sdCmdTime = getTime_ms();
\r
287 sdPreCmdState(CMD_STATE_READ);
\r
289 uint8_t v = sdCommandAndResponse(SD_READ_MULTIPLE_BLOCK, sdLBA);
\r
295 scsiDev.status = CHECK_CONDITION;
\r
296 scsiDev.target->sense.code = HARDWARE_ERROR;
\r
297 scsiDev.target->sense.asc = LOGICAL_UNIT_COMMUNICATION_FAILURE;
\r
298 scsiDev.phase = STATUS;
\r
302 sdCmdNextLBA = tmpNextLBA;
\r
303 sdCmdState = CMD_STATE_READ;
\r
304 sdCmdTime = getTime_ms();
\r
310 dmaReadSector(uint8_t* outputBuffer)
\r
312 // Wait for a start-block token.
\r
313 // Don't wait more than 200ms. The standard recommends 100ms.
\r
314 uint32_t start = getTime_ms();
\r
315 uint8_t token = sdSpiByte(0xFF);
\r
316 trace(trace_spinSDBusy);
\r
317 while (token != 0xFE && likely(elapsedTime_ms(start) <= 200))
\r
319 if (unlikely(token && ((token & 0xE0) == 0)))
\r
324 token = sdSpiByte(0xFF);
\r
326 if (unlikely(token != 0xFE))
\r
328 if (transfer.multiBlock)
\r
332 if (scsiDev.status != CHECK_CONDITION)
\r
334 scsiDev.status = CHECK_CONDITION;
\r
335 scsiDev.target->sense.code = HARDWARE_ERROR;
\r
336 scsiDev.target->sense.asc = UNRECOVERED_READ_ERROR;
\r
337 scsiDev.phase = STATUS;
\r
343 static uint8_t dmaRxTd[2] = { CY_DMA_INVALID_TD, CY_DMA_INVALID_TD};
\r
344 static uint8_t dmaTxTd = CY_DMA_INVALID_TD;
\r
345 if (unlikely(dmaRxTd[0] == CY_DMA_INVALID_TD))
\r
347 dmaRxTd[0] = CyDmaTdAllocate();
\r
348 dmaRxTd[1] = CyDmaTdAllocate();
\r
349 dmaTxTd = CyDmaTdAllocate();
\r
351 // Receive 512 bytes of data and then 2 bytes CRC.
\r
352 CyDmaTdSetConfiguration(dmaRxTd[0], SD_SECTOR_SIZE, dmaRxTd[1], TD_INC_DST_ADR);
\r
353 CyDmaTdSetConfiguration(dmaRxTd[1], 2, CY_DMA_DISABLE_TD, SD_RX_DMA__TD_TERMOUT_EN);
\r
354 CyDmaTdSetAddress(dmaRxTd[1], LO16((uint32)SDCard_RXDATA_PTR), LO16((uint32)&discardBuffer));
\r
356 CyDmaTdSetConfiguration(dmaTxTd, SD_SECTOR_SIZE + 2, CY_DMA_DISABLE_TD, SD_TX_DMA__TD_TERMOUT_EN);
\r
357 CyDmaTdSetAddress(dmaTxTd, LO16((uint32)&dummyBuffer), LO16((uint32)SDCard_TXDATA_PTR));
\r
360 CyDmaTdSetAddress(dmaRxTd[0], LO16((uint32)SDCard_RXDATA_PTR), LO16((uint32)outputBuffer));
\r
362 sdIOState = SD_DMA;
\r
363 sdTxDMAComplete = 0;
\r
364 sdRxDMAComplete = 0;
\r
366 // Re-loading the initial TD's here is very important, or else
\r
367 // we'll be re-using the last-used TD, which would be the last
\r
368 // in the chain (ie. CRC TD)
\r
369 CyDmaChSetInitialTd(sdDMARxChan, dmaRxTd[0]);
\r
370 CyDmaChSetInitialTd(sdDMATxChan, dmaTxTd);
\r
372 // The DMA controller is a bit trigger-happy. It will retain
\r
373 // a drq request that was triggered while the channel was
\r
375 CyDmaChSetRequest(sdDMATxChan, CY_DMA_CPU_REQ);
\r
376 CyDmaClearPendingDrq(sdDMARxChan);
\r
378 // There is no flow control, so we must ensure we can read the bytes
\r
379 // before we start transmitting
\r
380 CyDmaChEnable(sdDMARxChan, 1);
\r
381 CyDmaChEnable(sdDMATxChan, 1);
\r
385 sdReadSectorDMAPoll()
\r
387 if (sdRxDMAComplete && sdTxDMAComplete)
\r
389 // DMA transfer is complete
\r
390 sdIOState = SD_IDLE;
\r
399 void sdReadSingleSectorDMA(uint32_t lba, uint8_t* outputBuffer)
\r
401 sdPreCmdState(CMD_STATE_READ);
\r
406 lba = lba * SD_SECTOR_SIZE;
\r
408 v = sdCommandAndResponse(SD_READ_SINGLE_BLOCK, lba);
\r
414 scsiDev.status = CHECK_CONDITION;
\r
415 scsiDev.target->sense.code = HARDWARE_ERROR;
\r
416 scsiDev.target->sense.asc = LOGICAL_UNIT_COMMUNICATION_FAILURE;
\r
417 scsiDev.phase = STATUS;
\r
421 dmaReadSector(outputBuffer);
\r
426 sdReadMultiSectorDMA(uint8_t* outputBuffer)
\r
428 // Pre: sdReadMultiSectorPrep called.
\r
429 dmaReadSector(outputBuffer);
\r
432 static void sdCompleteRead()
\r
434 if (unlikely(sdIOState != SD_IDLE))
\r
436 // Not much choice but to wait until we've completed the transfer.
\r
437 // Cancelling the transfer can't be done as we have no way to reset
\r
439 trace(trace_spinSDCompleteRead);
\r
440 while (!sdReadSectorDMAPoll()) { /* spin */ }
\r
444 if (sdCmdState == CMD_STATE_READ)
\r
446 uint8 r1b = sdCommandAndResponse(SD_STOP_TRANSMISSION, 0);
\r
448 if (unlikely(r1b) && (scsiDev.phase == DATA_IN))
\r
450 scsiDev.status = CHECK_CONDITION;
\r
451 scsiDev.target->sense.code = HARDWARE_ERROR;
\r
452 scsiDev.target->sense.asc = UNRECOVERED_READ_ERROR;
\r
453 scsiDev.phase = STATUS;
\r
457 // R1b has an optional trailing "busy" signal, but we defer waiting on this.
\r
458 // The next call so sdCommandAndResponse will wait for the busy state to
\r
461 sdCmdState = CMD_STATE_IDLE;
\r
465 sdWriteMultiSectorDMA(uint8_t* outputBuffer)
\r
467 static uint8_t dmaRxTd[2] = { CY_DMA_INVALID_TD, CY_DMA_INVALID_TD};
\r
468 static uint8_t dmaTxTd[3] = { CY_DMA_INVALID_TD, CY_DMA_INVALID_TD, CY_DMA_INVALID_TD};
\r
469 if (unlikely(dmaRxTd[0] == CY_DMA_INVALID_TD))
\r
471 dmaRxTd[0] = CyDmaTdAllocate();
\r
472 dmaRxTd[1] = CyDmaTdAllocate();
\r
473 dmaTxTd[0] = CyDmaTdAllocate();
\r
474 dmaTxTd[1] = CyDmaTdAllocate();
\r
475 dmaTxTd[2] = CyDmaTdAllocate();
\r
477 // Transmit 512 bytes of data and then 2 bytes CRC, and then get the response byte
\r
478 // We need to do this without stopping the clock
\r
479 CyDmaTdSetConfiguration(dmaTxTd[0], 2, dmaTxTd[1], TD_INC_SRC_ADR);
\r
480 CyDmaTdSetAddress(dmaTxTd[0], LO16((uint32)&writeStartToken), LO16((uint32)SDCard_TXDATA_PTR));
\r
482 CyDmaTdSetConfiguration(dmaTxTd[1], SD_SECTOR_SIZE, dmaTxTd[2], TD_INC_SRC_ADR);
\r
484 CyDmaTdSetConfiguration(dmaTxTd[2], 2 + sizeof(writeResponseBuffer), CY_DMA_DISABLE_TD, SD_TX_DMA__TD_TERMOUT_EN);
\r
485 CyDmaTdSetAddress(dmaTxTd[2], LO16((uint32)&dummyBuffer), LO16((uint32)SDCard_TXDATA_PTR));
\r
487 CyDmaTdSetConfiguration(dmaRxTd[0], SD_SECTOR_SIZE + 4, dmaRxTd[1], 0);
\r
488 CyDmaTdSetAddress(dmaRxTd[0], LO16((uint32)SDCard_RXDATA_PTR), LO16((uint32)&discardBuffer));
\r
489 CyDmaTdSetConfiguration(dmaRxTd[1], sizeof(writeResponseBuffer), CY_DMA_DISABLE_TD, SD_RX_DMA__TD_TERMOUT_EN|TD_INC_DST_ADR);
\r
490 CyDmaTdSetAddress(dmaRxTd[1], LO16((uint32)SDCard_RXDATA_PTR), LO16((uint32)&writeResponseBuffer));
\r
492 CyDmaTdSetAddress(dmaTxTd[1], LO16((uint32)outputBuffer), LO16((uint32)SDCard_TXDATA_PTR));
\r
495 sdIOState = SD_DMA;
\r
496 // The DMA controller is a bit trigger-happy. It will retain
\r
497 // a drq request that was triggered while the channel was
\r
499 CyDmaChSetRequest(sdDMATxChan, CY_DMA_CPU_REQ);
\r
500 CyDmaClearPendingDrq(sdDMARxChan);
\r
502 sdTxDMAComplete = 0;
\r
503 sdRxDMAComplete = 0;
\r
505 // Re-loading the initial TD's here is very important, or else
\r
506 // we'll be re-using the last-used TD, which would be the last
\r
507 // in the chain (ie. CRC TD)
\r
508 CyDmaChSetInitialTd(sdDMARxChan, dmaRxTd[0]);
\r
509 CyDmaChSetInitialTd(sdDMATxChan, dmaTxTd[0]);
\r
511 // There is no flow control, so we must ensure we can read the bytes
\r
512 // before we start transmitting
\r
513 CyDmaChEnable(sdDMARxChan, 1);
\r
514 CyDmaChEnable(sdDMATxChan, 1);
\r
518 sdWriteSectorDMAPoll()
\r
520 if (sdRxDMAComplete && sdTxDMAComplete)
\r
522 if (sdIOState == SD_DMA)
\r
524 // Retry a few times. The data token format is:
\r
530 dataToken = writeResponseBuffer[i]; // Response
\r
532 } while (((dataToken & 0x0101) != 1) && (i < sizeof(writeResponseBuffer)));
\r
534 // At this point we should either have an accepted token, or we'll
\r
535 // timeout and proceed into the error case below.
\r
536 if (unlikely(((dataToken & 0x1F) >> 1) != 0x2)) // Accepted.
\r
538 sdIOState = SD_IDLE;
\r
541 sdSpiByte(0xFD); // STOP TOKEN
\r
544 sdCmdState = CMD_STATE_IDLE;
\r
548 scsiDev.status = CHECK_CONDITION;
\r
549 scsiDev.target->sense.code = HARDWARE_ERROR;
\r
550 scsiDev.target->sense.asc = LOGICAL_UNIT_COMMUNICATION_FAILURE;
\r
551 scsiDev.phase = STATUS;
\r
555 sdIOState = SD_ACCEPTED;
\r
559 if (sdIOState == SD_ACCEPTED)
\r
561 // Wait while the SD card is busy
\r
562 if (sdSpiByte(0xFF) == 0xFF)
\r
564 sdIOState = SD_IDLE;
\r
568 return sdIOState == SD_IDLE;
\r
576 static void sdCompleteWrite()
\r
578 if (unlikely(sdIOState != SD_IDLE))
\r
580 // Not much choice but to wait until we've completed the transfer.
\r
581 // Cancelling the transfer can't be done as we have no way to reset
\r
583 trace(trace_spinSDCompleteWrite);
\r
584 while (!sdWriteSectorDMAPoll()) { /* spin */ }
\r
587 if (sdCmdState == CMD_STATE_WRITE)
\r
591 sdSpiByte(0xFD); // STOP TOKEN
\r
597 if (likely(scsiDev.phase == DATA_OUT))
\r
599 uint16_t r2 = sdDoCommand(SD_SEND_STATUS, 0, 0, 1);
\r
603 scsiDev.status = CHECK_CONDITION;
\r
604 scsiDev.target->sense.code = HARDWARE_ERROR;
\r
605 scsiDev.target->sense.asc = WRITE_ERROR_AUTO_REALLOCATION_FAILED;
\r
606 scsiDev.phase = STATUS;
\r
609 sdCmdState = CMD_STATE_IDLE;
\r
612 void sdCompleteTransfer()
\r
614 sdPreCmdState(CMD_STATE_IDLE);
\r
618 // SD Version 2 (SDHC) support
\r
619 static int sendIfCond()
\r
625 // 11:8 Host voltage. 1 = 2.7-3.6V
\r
626 // 7:0 Echo bits. Ignore.
\r
627 uint8 status = sdCRCCommandAndResponse(SD_SEND_IF_COND, 0x000001AA);
\r
629 if (status == SD_R1_IDLE)
\r
633 // Read 32bit response. Should contain the same bytes that
\r
634 // we sent in the command parameter.
\r
641 else if (status & SD_R1_ILLEGAL)
\r
650 } while (--retries > 0);
\r
652 return retries > 0;
\r
655 static int sdOpCond()
\r
657 uint32_t start = getTime_ms();
\r
662 sdCRCCommandAndResponse(SD_APP_CMD, 0);
\r
663 // Host Capacity Support = 1 (SDHC/SDXC supported)
\r
664 status = sdCRCCommandAndResponse(SD_APP_SEND_OP_COND, 0x40000000);
\r
668 // Spec says to poll for 1 second.
\r
669 } while ((status != 0) && (elapsedTime_ms(start) < 1000));
\r
671 return status == 0;
\r
674 static int sdReadOCR()
\r
676 uint32_t start = getTime_ms();
\r
685 status = sdCRCCommandAndResponse(SD_READ_OCR, 0);
\r
686 if(status) { break; }
\r
688 for (i = 0; i < 4; ++i)
\r
690 buf[i] = sdSpiByte(0xFF);
\r
693 sdDev.ccs = (buf[0] & 0x40) ? 1 : 0;
\r
694 complete = (buf[0] & 0x80);
\r
696 } while (!status &&
\r
698 (elapsedTime_ms(start) < 1000));
\r
700 return (status == 0) && complete;
\r
703 static void sdReadCID()
\r
708 uint8 status = sdCRCCommandAndResponse(SD_SEND_CID, 0);
\r
709 if(status){return;}
\r
714 startToken = sdSpiByte(0xFF);
\r
715 } while(maxWait-- && (startToken != 0xFE));
\r
716 if (startToken != 0xFE) { return; }
\r
718 for (i = 0; i < 16; ++i)
\r
720 sdDev.cid[i] = sdSpiByte(0xFF);
\r
722 sdSpiByte(0xFF); // CRC
\r
723 sdSpiByte(0xFF); // CRC
\r
726 static int sdReadCSD()
\r
731 uint8 status = sdCRCCommandAndResponse(SD_SEND_CSD, 0);
\r
732 if(status){goto bad;}
\r
737 startToken = sdSpiByte(0xFF);
\r
738 } while(maxWait-- && (startToken != 0xFE));
\r
739 if (startToken != 0xFE) { goto bad; }
\r
741 for (i = 0; i < 16; ++i)
\r
743 sdDev.csd[i] = sdSpiByte(0xFF);
\r
745 sdSpiByte(0xFF); // CRC
\r
746 sdSpiByte(0xFF); // CRC
\r
748 if ((sdDev.csd[0] >> 6) == 0x00)
\r
751 // C_SIZE in bits [73:62]
\r
752 uint32 c_size = (((((uint32)sdDev.csd[6]) & 0x3) << 16) | (((uint32)sdDev.csd[7]) << 8) | sdDev.csd[8]) >> 6;
\r
753 uint32 c_mult = (((((uint32)sdDev.csd[9]) & 0x3) << 8) | ((uint32)sdDev.csd[0xa])) >> 7;
\r
754 uint32 sectorSize = sdDev.csd[5] & 0x0F;
\r
755 sdDev.capacity = ((c_size+1) * ((uint64)1 << (c_mult+2)) * ((uint64)1 << sectorSize)) / SD_SECTOR_SIZE;
\r
757 else if ((sdDev.csd[0] >> 6) == 0x01)
\r
760 // C_SIZE in bits [69:48]
\r
763 ((((uint32)sdDev.csd[7]) & 0x3F) << 16) |
\r
764 (((uint32)sdDev.csd[8]) << 8) |
\r
765 ((uint32)sdDev.csd[7]);
\r
766 sdDev.capacity = (c_size + 1) * 1024;
\r
778 static void sdInitDMA()
\r
780 // One-time init only.
\r
781 if (sdDMATxChan == CY_DMA_INVALID_CHANNEL)
\r
784 SD_TX_DMA_DmaInitialize(
\r
785 2, // Bytes per burst
\r
786 1, // request per burst
\r
787 HI16(CYDEV_SRAM_BASE),
\r
788 HI16(CYDEV_PERIPH_BASE)
\r
792 SD_RX_DMA_DmaInitialize(
\r
793 1, // Bytes per burst
\r
794 1, // request per burst
\r
795 HI16(CYDEV_PERIPH_BASE),
\r
796 HI16(CYDEV_SRAM_BASE)
\r
799 CyDmaChDisable(sdDMATxChan);
\r
800 CyDmaChDisable(sdDMARxChan);
\r
802 SD_RX_DMA_COMPLETE_StartEx(sdRxISR);
\r
803 SD_TX_DMA_COMPLETE_StartEx(sdTxISR);
\r
813 sdCmdState = CMD_STATE_IDLE;
\r
816 sdDev.capacity = 0;
\r
817 memset(sdDev.csd, 0, sizeof(sdDev.csd));
\r
818 memset(sdDev.cid, 0, sizeof(sdDev.cid));
\r
822 SD_CS_SetDriveMode(SD_CS_DM_STRONG);
\r
823 SD_CS_Write(1); // Set CS inactive (active low)
\r
825 // Set the SPI clock for 400kHz transfers
\r
826 // 25MHz / 400kHz approx factor of 63.
\r
827 // The register contains (divider - 1)
\r
828 uint16_t clkDiv25MHz = SD_Data_Clk_GetDividerRegister();
\r
829 SD_Data_Clk_SetDivider(((clkDiv25MHz + 1) * 63) - 1);
\r
830 // Wait for the clock to settle.
\r
833 SDCard_Start(); // Enable SPI hardware
\r
835 // Power on sequence. 74 clock cycles of a "1" while CS unasserted.
\r
836 for (i = 0; i < 10; ++i)
\r
841 SD_CS_Write(0); // Set CS active (active low)
\r
845 v = sdDoCommand(SD_GO_IDLE_STATE, 0, 1, 0);
\r
846 if(v != 1){goto bad;}
\r
849 if (!sendIfCond()) goto bad; // Sets V1 or V2 flag CMD8
\r
850 if (!sdOpCond()) goto bad; // ACMD41. Wait for init completes.
\r
851 if (!sdReadOCR()) goto bad; // CMD58. Get CCS flag. Only valid after init.
\r
853 // This command will be ignored if sdDev.ccs is set.
\r
854 // SDHC and SDXC are always 512bytes.
\r
855 v = sdCRCCommandAndResponse(SD_SET_BLOCKLEN, SD_SECTOR_SIZE); //Force sector size
\r
857 v = sdCRCCommandAndResponse(SD_CRC_ON_OFF, 0); //crc off
\r
860 // now set the sd card back to full speed.
\r
861 // The SD Card spec says we can run SPI @ 25MHz
\r
864 // We can't run at full-speed with the pullup resistors enabled.
\r
865 SD_MISO_SetDriveMode(SD_MISO_DM_DIG_HIZ);
\r
866 SD_MOSI_SetDriveMode(SD_MOSI_DM_STRONG);
\r
867 SD_SCK_SetDriveMode(SD_SCK_DM_STRONG);
\r
869 SD_Data_Clk_SetDivider(clkDiv25MHz);
\r
873 // Clear out rubbish data through clock change
\r
875 SDCard_ReadRxStatus();
\r
876 SDCard_ReadTxStatus();
\r
877 SDCard_ClearFIFO();
\r
879 if (!sdReadCSD()) goto bad;
\r
886 SD_Data_Clk_SetDivider(clkDiv25MHz); // Restore the clock for our next retry
\r
887 sdDev.capacity = 0;
\r
896 void sdWriteMultiSectorPrep(uint32_t sdLBA, uint32_t sdSectors)
\r
898 uint32_t tmpNextLBA = sdLBA + sdSectors;
\r
902 sdLBA = sdLBA * SD_SECTOR_SIZE;
\r
903 tmpNextLBA = tmpNextLBA * SD_SECTOR_SIZE;
\r
906 if (sdCmdState == CMD_STATE_WRITE && sdCmdNextLBA == sdLBA)
\r
908 // Well, that was lucky. We're already writing this data
\r
909 sdCmdNextLBA = tmpNextLBA;
\r
910 sdCmdTime = getTime_ms();
\r
914 sdPreCmdState(CMD_STATE_WRITE);
\r
916 // Set the number of blocks to pre-erase by the multiple block write
\r
917 // command. We don't care about the response - if the command is not
\r
918 // accepted, writes will just be a bit slower. Max 22bit parameter.
\r
919 uint32 blocks = sdSectors > 0x7FFFFF ? 0x7FFFFF : sdSectors;
\r
920 sdCommandAndResponse(SD_APP_CMD, 0);
\r
921 sdCommandAndResponse(SD_APP_SET_WR_BLK_ERASE_COUNT, blocks);
\r
923 uint8_t v = sdCommandAndResponse(SD_WRITE_MULTIPLE_BLOCK, sdLBA);
\r
928 scsiDev.status = CHECK_CONDITION;
\r
929 scsiDev.target->sense.code = HARDWARE_ERROR;
\r
930 scsiDev.target->sense.asc = LOGICAL_UNIT_COMMUNICATION_FAILURE;
\r
931 scsiDev.phase = STATUS;
\r
935 sdCmdTime = getTime_ms();
\r
936 sdCmdNextLBA = tmpNextLBA;
\r
937 sdCmdState = CMD_STATE_WRITE;
\r
944 if ((scsiDev.phase == BUS_FREE) &&
\r
945 (sdCmdState != CMD_STATE_IDLE) &&
\r
946 (elapsedTime_ms(sdCmdTime) >= 50))
\r
948 sdPreCmdState(CMD_STATE_IDLE);
\r
952 void sdCheckPresent()
\r
954 // Check if there's an SD card present.
\r
955 if ((scsiDev.phase == BUS_FREE) &&
\r
956 (sdIOState == SD_IDLE) &&
\r
957 (sdCmdState == CMD_STATE_IDLE))
\r
959 // The CS line is pulled high by the SD card.
\r
960 // De-assert the line, and check if it's high.
\r
961 // This isn't foolproof as it'll be left floating without
\r
962 // an SD card. We can't use the built-in pull-down resistor as it will
\r
963 // overpower the SD pullup resistor.
\r
965 SD_CS_SetDriveMode(SD_CS_DM_DIG_HIZ);
\r
967 // Delay extended to work with 60cm cables running cards at 2.85V
\r
968 CyDelayCycles(128);
\r
969 uint8_t cs = SD_CS_Read();
\r
970 SD_CS_SetDriveMode(SD_CS_DM_STRONG) ;
\r
972 if (cs && !(blockDev.state & DISK_PRESENT))
\r
974 static int firstInit = 1;
\r
981 blockDev.state |= DISK_PRESENT | DISK_INITIALISED;
\r
983 // Always "start" the device. Many systems (eg. Apple System 7)
\r
984 // won't respond properly to
\r
985 // LOGICAL_UNIT_NOT_READY_INITIALIZING_COMMAND_REQUIRED sense
\r
986 // code, even if they stopped it first with
\r
987 // START STOP UNIT command.
\r
988 blockDev.state |= DISK_STARTED;
\r
993 for (i = 0; i < MAX_SCSI_TARGETS; ++i)
\r
995 scsiDev.targets[i].unitAttention = PARAMETERS_CHANGED;
\r
1001 else if (!cs && (blockDev.state & DISK_PRESENT))
\r
1003 sdDev.capacity = 0;
\r
1004 blockDev.state &= ~DISK_PRESENT;
\r
1005 blockDev.state &= ~DISK_INITIALISED;
\r
1007 for (i = 0; i < MAX_SCSI_TARGETS; ++i)
\r
1009 scsiDev.targets[i].unitAttention = PARAMETERS_CHANGED;
\r
1015 #pragma GCC pop_options
\r