1 // Copyright (C) 2013 Michael McMaster <michael@codesrc.com>
3 // This file is part of SCSI2SD.
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.
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.
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")
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
;
42 enum SD_IO_STATE
{ SD_DMA
, SD_ACCEPTED
, SD_IDLE
};
43 static int sdIOState
= SD_IDLE
;
45 // Private DMA variables.
46 static uint8 sdDMARxChan
= CY_DMA_INVALID_CHANNEL
;
47 static uint8 sdDMATxChan
= CY_DMA_INVALID_CHANNEL
;
49 // Dummy location for DMA to send unchecked CRC bytes to
50 static uint8 discardBuffer
__attribute__((aligned(4)));
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)));
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};
60 // Source of dummy SPI bytes for DMA
61 static uint8_t dummyBuffer
[2] __attribute__((aligned(4))) = {0xFF, 0xFF};
63 volatile uint8_t sdRxDMAComplete
;
64 volatile uint8_t sdTxDMAComplete
;
66 static void sdCompleteRead();
67 static void sdCompleteWrite();
69 CY_ISR_PROTO(sdRxISR
);
74 CY_ISR_PROTO(sdTxISR
);
80 static uint8
sdCrc7(uint8
* chr
, uint8 cnt
, uint8 crc
)
83 for(a
= 0; a
< cnt
; a
++)
87 for(i
= 0; i
< 8; i
++)
90 if( (Data
& 0x80) ^ (crc
& 0x80) ) {crc
^= 0x09;}
98 // Read and write 1 byte.
99 static uint8_t sdSpiByte(uint8_t value
)
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();
108 static void sdWaitWriteBusy()
113 val
= sdSpiByte(0xFF);
114 } while (val
!= 0xFF);
117 static void sdPreCmdState(uint32_t newState
)
119 if (sdCmdState
== CMD_STATE_READ
)
123 else if (sdCmdState
== CMD_STATE_WRITE
)
127 sdCmdState
= CMD_STATE_IDLE
;
129 if (sdLastCmdState
!= newState
&& newState
!= CMD_STATE_IDLE
)
132 sdLastCmdState
= newState
;
136 static uint16_t sdDoCommand(
140 int use2byteResponse
)
142 int waitWhileBusy
= (cmd
!= SD_GO_IDLE_STATE
) && (cmd
!= SD_STOP_TRANSMISSION
);
144 // "busy" probe. We'll examine the results later.
147 SDCard_WriteTxData(0xFF);
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;
159 if (unlikely(useCRC
))
161 send
[5] = (sdCrc7(send
, 5, 0) << 1) | 1;
165 send
[5] = 1; // stop bit
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
))
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
));
183 CyDmaChSetInitialTd(sdDMARxChan
, dmaRxTd
);
184 CyDmaChSetInitialTd(sdDMATxChan
, dmaTxTd
);
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
191 trace(trace_spinSDRxFIFO
);
192 while (!(SDCard_ReadRxStatus() & SDCard_STS_RX_FIFO_NOT_EMPTY
)) {}
193 int busy
= SDCard_ReadRxData() != 0xFF;
196 trace(trace_spinSDBusy
);
197 while (sdSpiByte(0xFF) != 0xFF) {}
201 // The DMA controller is a bit trigger-happy. It will retain
202 // a drq request that was triggered while the channel was
204 CyDmaChSetRequest(sdDMATxChan
, CY_DMA_CPU_REQ
);
205 CyDmaClearPendingDrq(sdDMARxChan
);
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);
212 trace(trace_spinSDDMA
);
216 uint8_t intr
= CyEnterCriticalSection();
217 allComplete
= sdTxDMAComplete
&& sdRxDMAComplete
;
222 CyExitCriticalSection(intr
);
225 uint16_t response
= sdSpiByte(0xFF); // Result code or stuff byte
226 if (unlikely(cmd
== SD_STOP_TRANSMISSION
))
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
232 response
= sdSpiByte(0xFF);
235 uint32_t start
= getTime_ms();
237 trace(trace_spinSDBusy
);
238 while ((response
& 0x80) && likely(elapsedTime_ms(start
) <= 200))
240 response
= sdSpiByte(0xFF);
242 if (unlikely(use2byteResponse
))
244 response
= (response
<< 8) | sdSpiByte(0xFF);
250 static inline uint16_t sdCommandAndResponse(uint8_t cmd
, uint32_t param
)
252 return sdDoCommand(cmd
, param
, 0, 0);
255 static inline uint16_t sdCRCCommandAndResponse(uint8_t cmd
, uint32_t param
)
257 return sdDoCommand(cmd
, param
, 1, 0);
260 // Clear the sticky status bits on error.
261 static void sdClearStatus()
264 uint16_t r2
= sdDoCommand(SD_SEND_STATUS
, 0, 1, 1);
269 sdReadMultiSectorPrep(uint32_t sdLBA
, uint32_t sdSectors
)
271 uint32_t tmpNextLBA
= sdLBA
+ sdSectors
;
275 sdLBA
= sdLBA
* SD_SECTOR_SIZE
;
276 tmpNextLBA
= tmpNextLBA
* SD_SECTOR_SIZE
;
279 if (sdCmdState
== CMD_STATE_READ
&& sdCmdNextLBA
== sdLBA
)
281 // Well, that was lucky. We're already reading this data
282 sdCmdNextLBA
= tmpNextLBA
;
283 sdCmdTime
= getTime_ms();
287 sdPreCmdState(CMD_STATE_READ
);
289 uint8_t v
= sdCommandAndResponse(SD_READ_MULTIPLE_BLOCK
, sdLBA
);
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
;
302 sdCmdNextLBA
= tmpNextLBA
;
303 sdCmdState
= CMD_STATE_READ
;
304 sdCmdTime
= getTime_ms();
310 dmaReadSector(uint8_t* outputBuffer
)
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))
319 if (unlikely(token
&& ((token
& 0xE0) == 0)))
324 token
= sdSpiByte(0xFF);
326 if (unlikely(token
!= 0xFE))
328 if (transfer
.multiBlock
)
332 if (scsiDev
.status
!= CHECK_CONDITION
)
334 scsiDev
.status
= CHECK_CONDITION
;
335 scsiDev
.target
->sense
.code
= HARDWARE_ERROR
;
336 scsiDev
.target
->sense
.asc
= UNRECOVERED_READ_ERROR
;
337 scsiDev
.phase
= STATUS
;
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
))
347 dmaRxTd
[0] = CyDmaTdAllocate();
348 dmaRxTd
[1] = CyDmaTdAllocate();
349 dmaTxTd
= CyDmaTdAllocate();
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
));
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
));
360 CyDmaTdSetAddress(dmaRxTd
[0], LO16((uint32
)SDCard_RXDATA_PTR
), LO16((uint32
)outputBuffer
));
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
);
372 // The DMA controller is a bit trigger-happy. It will retain
373 // a drq request that was triggered while the channel was
375 CyDmaChSetRequest(sdDMATxChan
, CY_DMA_CPU_REQ
);
376 CyDmaClearPendingDrq(sdDMARxChan
);
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);
385 sdReadSectorDMAPoll()
387 if (sdRxDMAComplete
&& sdTxDMAComplete
)
389 // DMA transfer is complete
399 void sdReadSingleSectorDMA(uint32_t lba
, uint8_t* outputBuffer
)
401 sdPreCmdState(CMD_STATE_READ
);
406 lba
= lba
* SD_SECTOR_SIZE
;
408 v
= sdCommandAndResponse(SD_READ_SINGLE_BLOCK
, lba
);
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
;
421 dmaReadSector(outputBuffer
);
426 sdReadMultiSectorDMA(uint8_t* outputBuffer
)
428 // Pre: sdReadMultiSectorPrep called.
429 dmaReadSector(outputBuffer
);
432 static void sdCompleteRead()
434 if (unlikely(sdIOState
!= SD_IDLE
))
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
439 trace(trace_spinSDCompleteRead
);
440 while (!sdReadSectorDMAPoll()) { /* spin */ }
444 if (sdCmdState
== CMD_STATE_READ
)
446 uint8 r1b
= sdCommandAndResponse(SD_STOP_TRANSMISSION
, 0);
448 if (unlikely(r1b
) && (scsiDev
.phase
== DATA_IN
))
450 scsiDev
.status
= CHECK_CONDITION
;
451 scsiDev
.target
->sense
.code
= HARDWARE_ERROR
;
452 scsiDev
.target
->sense
.asc
= UNRECOVERED_READ_ERROR
;
453 scsiDev
.phase
= STATUS
;
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
461 sdCmdState
= CMD_STATE_IDLE
;
465 sdWriteMultiSectorDMA(uint8_t* outputBuffer
)
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
))
471 dmaRxTd
[0] = CyDmaTdAllocate();
472 dmaRxTd
[1] = CyDmaTdAllocate();
473 dmaTxTd
[0] = CyDmaTdAllocate();
474 dmaTxTd
[1] = CyDmaTdAllocate();
475 dmaTxTd
[2] = CyDmaTdAllocate();
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
));
482 CyDmaTdSetConfiguration(dmaTxTd
[1], SD_SECTOR_SIZE
, dmaTxTd
[2], TD_INC_SRC_ADR
);
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
));
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
));
492 CyDmaTdSetAddress(dmaTxTd
[1], LO16((uint32
)outputBuffer
), LO16((uint32
)SDCard_TXDATA_PTR
));
496 // The DMA controller is a bit trigger-happy. It will retain
497 // a drq request that was triggered while the channel was
499 CyDmaChSetRequest(sdDMATxChan
, CY_DMA_CPU_REQ
);
500 CyDmaClearPendingDrq(sdDMARxChan
);
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]);
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);
518 sdWriteSectorDMAPoll()
520 if (sdRxDMAComplete
&& sdTxDMAComplete
)
522 if (sdIOState
== SD_DMA
)
524 // Retry a few times. The data token format is:
530 dataToken
= writeResponseBuffer
[i
]; // Response
532 } while (((dataToken
& 0x0101) != 1) && (i
< sizeof(writeResponseBuffer
)));
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.
541 sdSpiByte(0xFD); // STOP TOKEN
544 sdCmdState
= CMD_STATE_IDLE
;
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
;
555 sdIOState
= SD_ACCEPTED
;
559 if (sdIOState
== SD_ACCEPTED
)
561 // Wait while the SD card is busy
562 if (sdSpiByte(0xFF) == 0xFF)
568 return sdIOState
== SD_IDLE
;
576 static void sdCompleteWrite()
578 if (unlikely(sdIOState
!= SD_IDLE
))
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
583 trace(trace_spinSDCompleteWrite
);
584 while (!sdWriteSectorDMAPoll()) { /* spin */ }
587 if (sdCmdState
== CMD_STATE_WRITE
)
591 sdSpiByte(0xFD); // STOP TOKEN
597 if (likely(scsiDev
.phase
== DATA_OUT
))
599 uint16_t r2
= sdDoCommand(SD_SEND_STATUS
, 0, 0, 1);
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
;
609 sdCmdState
= CMD_STATE_IDLE
;
612 void sdCompleteTransfer()
614 sdPreCmdState(CMD_STATE_IDLE
);
618 // SD Version 2 (SDHC) support
619 static int sendIfCond()
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);
629 if (status
== SD_R1_IDLE
)
633 // Read 32bit response. Should contain the same bytes that
634 // we sent in the command parameter.
641 else if (status
& SD_R1_ILLEGAL
)
650 } while (--retries
> 0);
655 static int sdOpCond()
657 uint32_t start
= getTime_ms();
662 sdCRCCommandAndResponse(SD_APP_CMD
, 0);
663 // Host Capacity Support = 1 (SDHC/SDXC supported)
664 status
= sdCRCCommandAndResponse(SD_APP_SEND_OP_COND
, 0x40000000);
668 // Spec says to poll for 1 second.
669 } while ((status
!= 0) && (elapsedTime_ms(start
) < 1000));
674 static int sdReadOCR()
676 uint32_t start
= getTime_ms();
685 status
= sdCRCCommandAndResponse(SD_READ_OCR
, 0);
686 if(status
) { break; }
688 for (i
= 0; i
< 4; ++i
)
690 buf
[i
] = sdSpiByte(0xFF);
693 sdDev
.ccs
= (buf
[0] & 0x40) ? 1 : 0;
694 complete
= (buf
[0] & 0x80);
698 (elapsedTime_ms(start
) < 1000));
700 return (status
== 0) && complete
;
703 static void sdReadCID()
708 uint8 status
= sdCRCCommandAndResponse(SD_SEND_CID
, 0);
714 startToken
= sdSpiByte(0xFF);
715 } while(maxWait
-- && (startToken
!= 0xFE));
716 if (startToken
!= 0xFE) { return; }
718 for (i
= 0; i
< 16; ++i
)
720 sdDev
.cid
[i
] = sdSpiByte(0xFF);
722 sdSpiByte(0xFF); // CRC
723 sdSpiByte(0xFF); // CRC
726 static int sdReadCSD()
731 uint8 status
= sdCRCCommandAndResponse(SD_SEND_CSD
, 0);
732 if(status
){goto bad
;}
737 startToken
= sdSpiByte(0xFF);
738 } while(maxWait
-- && (startToken
!= 0xFE));
739 if (startToken
!= 0xFE) { goto bad
; }
741 for (i
= 0; i
< 16; ++i
)
743 sdDev
.csd
[i
] = sdSpiByte(0xFF);
745 sdSpiByte(0xFF); // CRC
746 sdSpiByte(0xFF); // CRC
748 if ((sdDev
.csd
[0] >> 6) == 0x00)
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
;
757 else if ((sdDev
.csd
[0] >> 6) == 0x01)
760 // C_SIZE in bits [69:48]
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;
778 static void sdInitDMA()
780 // One-time init only.
781 if (sdDMATxChan
== CY_DMA_INVALID_CHANNEL
)
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
)
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
)
799 CyDmaChDisable(sdDMATxChan
);
800 CyDmaChDisable(sdDMARxChan
);
802 SD_RX_DMA_COMPLETE_StartEx(sdRxISR
);
803 SD_TX_DMA_COMPLETE_StartEx(sdTxISR
);
813 sdCmdState
= CMD_STATE_IDLE
;
817 memset(sdDev
.csd
, 0, sizeof(sdDev
.csd
));
818 memset(sdDev
.cid
, 0, sizeof(sdDev
.cid
));
822 SD_CS_SetDriveMode(SD_CS_DM_STRONG
);
823 SD_CS_Write(1); // Set CS inactive (active low)
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.
833 SDCard_Start(); // Enable SPI hardware
835 // Power on sequence. 74 clock cycles of a "1" while CS unasserted.
836 for (i
= 0; i
< 10; ++i
)
841 SD_CS_Write(0); // Set CS active (active low)
845 v
= sdDoCommand(SD_GO_IDLE_STATE
, 0, 1, 0);
846 if(v
!= 1){goto bad
;}
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.
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
857 v
= sdCRCCommandAndResponse(SD_CRC_ON_OFF
, 0); //crc off
860 // now set the sd card back to full speed.
861 // The SD Card spec says we can run SPI @ 25MHz
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
);
869 SD_Data_Clk_SetDivider(clkDiv25MHz
);
873 // Clear out rubbish data through clock change
875 SDCard_ReadRxStatus();
876 SDCard_ReadTxStatus();
879 if (!sdReadCSD()) goto bad
;
886 SD_Data_Clk_SetDivider(clkDiv25MHz
); // Restore the clock for our next retry
896 void sdWriteMultiSectorPrep(uint32_t sdLBA
, uint32_t sdSectors
)
898 uint32_t tmpNextLBA
= sdLBA
+ sdSectors
;
902 sdLBA
= sdLBA
* SD_SECTOR_SIZE
;
903 tmpNextLBA
= tmpNextLBA
* SD_SECTOR_SIZE
;
906 if (sdCmdState
== CMD_STATE_WRITE
&& sdCmdNextLBA
== sdLBA
)
908 // Well, that was lucky. We're already writing this data
909 sdCmdNextLBA
= tmpNextLBA
;
910 sdCmdTime
= getTime_ms();
914 sdPreCmdState(CMD_STATE_WRITE
);
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
);
923 uint8_t v
= sdCommandAndResponse(SD_WRITE_MULTIPLE_BLOCK
, sdLBA
);
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
;
935 sdCmdTime
= getTime_ms();
936 sdCmdNextLBA
= tmpNextLBA
;
937 sdCmdState
= CMD_STATE_WRITE
;
944 if ((scsiDev
.phase
== BUS_FREE
) &&
945 (sdCmdState
!= CMD_STATE_IDLE
) &&
946 (elapsedTime_ms(sdCmdTime
) >= 50))
948 sdPreCmdState(CMD_STATE_IDLE
);
952 void sdCheckPresent()
954 // Check if there's an SD card present.
955 if ((scsiDev
.phase
== BUS_FREE
) &&
956 (sdIOState
== SD_IDLE
) &&
957 (sdCmdState
== CMD_STATE_IDLE
))
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.
965 SD_CS_SetDriveMode(SD_CS_DM_DIG_HIZ
);
967 // Delay extended to work with 60cm cables running cards at 2.85V
969 uint8_t cs
= SD_CS_Read();
970 SD_CS_SetDriveMode(SD_CS_DM_STRONG
) ;
972 if (cs
&& !(blockDev
.state
& DISK_PRESENT
))
974 static int firstInit
= 1;
981 blockDev
.state
|= DISK_PRESENT
| DISK_INITIALISED
;
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
;
993 for (i
= 0; i
< MAX_SCSI_TARGETS
; ++i
)
995 scsiDev
.targets
[i
].unitAttention
= PARAMETERS_CHANGED
;
1001 else if (!cs
&& (blockDev
.state
& DISK_PRESENT
))
1004 blockDev
.state
&= ~DISK_PRESENT
;
1005 blockDev
.state
&= ~DISK_INITIALISED
;
1007 for (i
= 0; i
< MAX_SCSI_TARGETS
; ++i
)
1009 scsiDev
.targets
[i
].unitAttention
= PARAMETERS_CHANGED
;
1015 #pragma GCC pop_options