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 CY_ISR_PROTO(sdRxISR
);
71 CY_ISR_PROTO(sdTxISR
);
77 static uint8
sdCrc7(uint8
* chr
, uint8 cnt
, uint8 crc
)
80 for(a
= 0; a
< cnt
; a
++)
84 for(i
= 0; i
< 8; i
++)
87 if( (Data
& 0x80) ^ (crc
& 0x80) ) {crc
^= 0x09;}
95 // Read and write 1 byte.
96 static uint8_t sdSpiByte(uint8_t value
)
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();
105 static void sdWaitWriteBusy()
110 val
= sdSpiByte(0xFF);
111 } while (val
!= 0xFF);
114 static void sdPreCmdState(uint32_t newState
)
116 if (sdCmdState
== CMD_STATE_READ
)
120 else if (sdCmdState
== CMD_STATE_WRITE
)
124 sdCmdState
= CMD_STATE_IDLE
;
126 if (sdLastCmdState
!= newState
&& newState
!= CMD_STATE_IDLE
)
129 sdLastCmdState
= newState
;
133 static uint16_t sdDoCommand(
137 int use2byteResponse
)
139 int waitWhileBusy
= (cmd
!= SD_GO_IDLE_STATE
) && (cmd
!= SD_STOP_TRANSMISSION
);
141 // "busy" probe. We'll examine the results later.
144 SDCard_WriteTxData(0xFF);
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;
156 if (unlikely(useCRC
))
158 send
[5] = (sdCrc7(send
, 5, 0) << 1) | 1;
162 send
[5] = 1; // stop bit
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
))
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
));
180 CyDmaChSetInitialTd(sdDMARxChan
, dmaRxTd
);
181 CyDmaChSetInitialTd(sdDMATxChan
, dmaTxTd
);
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
188 trace(trace_spinSDRxFIFO
);
189 while (!(SDCard_ReadRxStatus() & SDCard_STS_RX_FIFO_NOT_EMPTY
)) {}
190 int busy
= SDCard_ReadRxData() != 0xFF;
193 trace(trace_spinSDBusy
);
194 while (sdSpiByte(0xFF) != 0xFF) {}
198 // The DMA controller is a bit trigger-happy. It will retain
199 // a drq request that was triggered while the channel was
201 CyDmaChSetRequest(sdDMATxChan
, CY_DMA_CPU_REQ
);
202 CyDmaClearPendingDrq(sdDMARxChan
);
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);
209 trace(trace_spinSDDMA
);
213 uint8_t intr
= CyEnterCriticalSection();
214 allComplete
= sdTxDMAComplete
&& sdRxDMAComplete
;
219 CyExitCriticalSection(intr
);
222 uint16_t response
= sdSpiByte(0xFF); // Result code or stuff byte
223 if (unlikely(cmd
== SD_STOP_TRANSMISSION
))
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
229 response
= sdSpiByte(0xFF);
232 uint32_t start
= getTime_ms();
234 trace(trace_spinSDBusy
);
235 while ((response
& 0x80) && likely(elapsedTime_ms(start
) <= 200))
237 response
= sdSpiByte(0xFF);
239 if (unlikely(use2byteResponse
))
241 response
= (response
<< 8) | sdSpiByte(0xFF);
247 static inline uint16_t sdCommandAndResponse(uint8_t cmd
, uint32_t param
)
249 return sdDoCommand(cmd
, param
, 0, 0);
252 static inline uint16_t sdCRCCommandAndResponse(uint8_t cmd
, uint32_t param
)
254 return sdDoCommand(cmd
, param
, 1, 0);
257 // Clear the sticky status bits on error.
258 static void sdClearStatus()
261 uint16_t r2
= sdDoCommand(SD_SEND_STATUS
, 0, 1, 1);
266 sdReadMultiSectorPrep(uint32_t sdLBA
, uint32_t sdSectors
)
268 uint32_t tmpNextLBA
= sdLBA
+ sdSectors
;
272 sdLBA
= sdLBA
* SD_SECTOR_SIZE
;
273 tmpNextLBA
= tmpNextLBA
* SD_SECTOR_SIZE
;
276 if (sdCmdState
== CMD_STATE_READ
&& sdCmdNextLBA
== sdLBA
)
278 // Well, that was lucky. We're already reading this data
279 sdCmdNextLBA
= tmpNextLBA
;
280 sdCmdTime
= getTime_ms();
284 sdPreCmdState(CMD_STATE_READ
);
286 uint8_t v
= sdCommandAndResponse(SD_READ_MULTIPLE_BLOCK
, sdLBA
);
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
;
299 sdCmdNextLBA
= tmpNextLBA
;
300 sdCmdState
= CMD_STATE_READ
;
301 sdCmdTime
= getTime_ms();
307 dmaReadSector(uint8_t* outputBuffer
)
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))
316 if (unlikely(token
&& ((token
& 0xE0) == 0)))
321 token
= sdSpiByte(0xFF);
323 if (unlikely(token
!= 0xFE))
325 if (transfer
.multiBlock
)
329 if (scsiDev
.status
!= CHECK_CONDITION
)
331 scsiDev
.status
= CHECK_CONDITION
;
332 scsiDev
.target
->sense
.code
= HARDWARE_ERROR
;
333 scsiDev
.target
->sense
.asc
= UNRECOVERED_READ_ERROR
;
334 scsiDev
.phase
= STATUS
;
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
))
344 dmaRxTd
[0] = CyDmaTdAllocate();
345 dmaRxTd
[1] = CyDmaTdAllocate();
346 dmaTxTd
= CyDmaTdAllocate();
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
));
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
));
357 CyDmaTdSetAddress(dmaRxTd
[0], LO16((uint32
)SDCard_RXDATA_PTR
), LO16((uint32
)outputBuffer
));
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
);
369 // The DMA controller is a bit trigger-happy. It will retain
370 // a drq request that was triggered while the channel was
372 CyDmaChSetRequest(sdDMATxChan
, CY_DMA_CPU_REQ
);
373 CyDmaClearPendingDrq(sdDMARxChan
);
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);
382 sdReadSectorDMAPoll()
384 if (sdRxDMAComplete
&& sdTxDMAComplete
)
386 // DMA transfer is complete
396 void sdReadSingleSectorDMA(uint32_t lba
, uint8_t* outputBuffer
)
398 sdPreCmdState(CMD_STATE_READ
);
403 lba
= lba
* SD_SECTOR_SIZE
;
405 v
= sdCommandAndResponse(SD_READ_SINGLE_BLOCK
, lba
);
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
;
418 dmaReadSector(outputBuffer
);
423 sdReadMultiSectorDMA(uint8_t* outputBuffer
)
425 // Pre: sdReadMultiSectorPrep called.
426 dmaReadSector(outputBuffer
);
429 void sdCompleteRead()
431 if (unlikely(sdIOState
!= SD_IDLE
))
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
436 trace(trace_spinSDCompleteRead
);
437 while (!sdReadSectorDMAPoll()) { /* spin */ }
441 if (sdCmdState
== CMD_STATE_READ
)
443 uint8 r1b
= sdCommandAndResponse(SD_STOP_TRANSMISSION
, 0);
445 if (unlikely(r1b
) && (scsiDev
.PHASE
== DATA_IN
))
447 scsiDev
.status
= CHECK_CONDITION
;
448 scsiDev
.target
->sense
.code
= HARDWARE_ERROR
;
449 scsiDev
.target
->sense
.asc
= UNRECOVERED_READ_ERROR
;
450 scsiDev
.phase
= STATUS
;
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
458 sdCmdState
= CMD_STATE_IDLE
;
462 sdWriteMultiSectorDMA(uint8_t* outputBuffer
)
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
))
468 dmaRxTd
[0] = CyDmaTdAllocate();
469 dmaRxTd
[1] = CyDmaTdAllocate();
470 dmaTxTd
[0] = CyDmaTdAllocate();
471 dmaTxTd
[1] = CyDmaTdAllocate();
472 dmaTxTd
[2] = CyDmaTdAllocate();
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
));
479 CyDmaTdSetConfiguration(dmaTxTd
[1], SD_SECTOR_SIZE
, dmaTxTd
[2], TD_INC_SRC_ADR
);
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
));
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
));
489 CyDmaTdSetAddress(dmaTxTd
[1], LO16((uint32
)outputBuffer
), LO16((uint32
)SDCard_TXDATA_PTR
));
493 // The DMA controller is a bit trigger-happy. It will retain
494 // a drq request that was triggered while the channel was
496 CyDmaChSetRequest(sdDMATxChan
, CY_DMA_CPU_REQ
);
497 CyDmaClearPendingDrq(sdDMARxChan
);
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]);
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);
515 sdWriteSectorDMAPoll()
517 if (sdRxDMAComplete
&& sdTxDMAComplete
)
519 if (sdIOState
== SD_DMA
)
521 // Retry a few times. The data token format is:
527 dataToken
= writeResponseBuffer
[i
]; // Response
529 } while (((dataToken
& 0x0101) != 1) && (i
< sizeof(writeResponseBuffer
)));
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.
538 sdSpiByte(0xFD); // STOP TOKEN
541 sdCmdState
= CMD_STATE_IDLE
;
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
;
552 sdIOState
= SD_ACCEPTED
;
556 if (sdIOState
== SD_ACCEPTED
)
558 // Wait while the SD card is busy
559 if (sdSpiByte(0xFF) == 0xFF)
565 return sdIOState
== SD_IDLE
;
573 void sdCompleteWrite()
575 if (unlikely(sdIOState
!= SD_IDLE
))
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
580 trace(trace_spinSDCompleteWrite
);
581 while (!sdWriteSectorDMAPoll()) { /* spin */ }
584 if (sdCmdState
== CMD_STATE_WRITE
)
588 sdSpiByte(0xFD); // STOP TOKEN
594 if (likely(scsiDev
.phase
== DATA_OUT
))
596 uint16_t r2
= sdDoCommand(SD_SEND_STATUS
, 0, 0, 1);
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
;
606 sdCmdState
= CMD_STATE_IDLE
;
609 void sdCompleteTransfer()
611 sdPreCmdState(CMD_STATE_IDLE
);
615 // SD Version 2 (SDHC) support
616 static int sendIfCond()
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);
626 if (status
== SD_R1_IDLE
)
630 // Read 32bit response. Should contain the same bytes that
631 // we sent in the command parameter.
638 else if (status
& SD_R1_ILLEGAL
)
647 } while (--retries
> 0);
652 static int sdOpCond()
654 uint32_t start
= getTime_ms();
659 sdCRCCommandAndResponse(SD_APP_CMD
, 0);
660 // Host Capacity Support = 1 (SDHC/SDXC supported)
661 status
= sdCRCCommandAndResponse(SD_APP_SEND_OP_COND
, 0x40000000);
665 // Spec says to poll for 1 second.
666 } while ((status
!= 0) && (elapsedTime_ms(start
) < 1000));
671 static int sdReadOCR()
673 uint32_t start
= getTime_ms();
682 status
= sdCRCCommandAndResponse(SD_READ_OCR
, 0);
683 if(status
) { break; }
685 for (i
= 0; i
< 4; ++i
)
687 buf
[i
] = sdSpiByte(0xFF);
690 sdDev
.ccs
= (buf
[0] & 0x40) ? 1 : 0;
691 complete
= (buf
[0] & 0x80);
695 (elapsedTime_ms(start
) < 1000));
697 return (status
== 0) && complete
;
700 static void sdReadCID()
705 uint8 status
= sdCRCCommandAndResponse(SD_SEND_CID
, 0);
711 startToken
= sdSpiByte(0xFF);
712 } while(maxWait
-- && (startToken
!= 0xFE));
713 if (startToken
!= 0xFE) { return; }
715 for (i
= 0; i
< 16; ++i
)
717 sdDev
.cid
[i
] = sdSpiByte(0xFF);
719 sdSpiByte(0xFF); // CRC
720 sdSpiByte(0xFF); // CRC
723 static int sdReadCSD()
728 uint8 status
= sdCRCCommandAndResponse(SD_SEND_CSD
, 0);
729 if(status
){goto bad
;}
734 startToken
= sdSpiByte(0xFF);
735 } while(maxWait
-- && (startToken
!= 0xFE));
736 if (startToken
!= 0xFE) { goto bad
; }
738 for (i
= 0; i
< 16; ++i
)
740 sdDev
.csd
[i
] = sdSpiByte(0xFF);
742 sdSpiByte(0xFF); // CRC
743 sdSpiByte(0xFF); // CRC
745 if ((sdDev
.csd
[0] >> 6) == 0x00)
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
;
754 else if ((sdDev
.csd
[0] >> 6) == 0x01)
757 // C_SIZE in bits [69:48]
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;
775 static void sdInitDMA()
777 // One-time init only.
778 if (sdDMATxChan
== CY_DMA_INVALID_CHANNEL
)
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
)
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
)
796 CyDmaChDisable(sdDMATxChan
);
797 CyDmaChDisable(sdDMARxChan
);
799 SD_RX_DMA_COMPLETE_StartEx(sdRxISR
);
800 SD_TX_DMA_COMPLETE_StartEx(sdTxISR
);
810 sdCmdState
= CMD_STATE_IDLE
;
814 memset(sdDev
.csd
, 0, sizeof(sdDev
.csd
));
815 memset(sdDev
.cid
, 0, sizeof(sdDev
.cid
));
819 SD_CS_SetDriveMode(SD_CS_DM_STRONG
);
820 SD_CS_Write(1); // Set CS inactive (active low)
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.
830 SDCard_Start(); // Enable SPI hardware
832 // Power on sequence. 74 clock cycles of a "1" while CS unasserted.
833 for (i
= 0; i
< 10; ++i
)
838 SD_CS_Write(0); // Set CS active (active low)
842 v
= sdDoCommand(SD_GO_IDLE_STATE
, 0, 1, 0);
843 if(v
!= 1){goto bad
;}
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.
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
854 v
= sdCRCCommandAndResponse(SD_CRC_ON_OFF
, 0); //crc off
857 // now set the sd card back to full speed.
858 // The SD Card spec says we can run SPI @ 25MHz
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
);
866 SD_Data_Clk_SetDivider(clkDiv25MHz
);
870 // Clear out rubbish data through clock change
872 SDCard_ReadRxStatus();
873 SDCard_ReadTxStatus();
876 if (!sdReadCSD()) goto bad
;
883 SD_Data_Clk_SetDivider(clkDiv25MHz
); // Restore the clock for our next retry
893 void sdWriteMultiSectorPrep(uint32_t sdLBA
, uint32_t sdSectors
)
895 uint32_t tmpNextLBA
= sdLBA
+ sdSectors
;
899 sdLBA
= sdLBA
* SD_SECTOR_SIZE
;
900 tmpNextLBA
= tmpNextLBA
* SD_SECTOR_SIZE
;
903 if (sdCmdState
== CMD_STATE_WRITE
&& sdCmdNextLBA
== sdLBA
)
905 // Well, that was lucky. We're already writing this data
906 sdCmdNextLBA
= tmpNextLBA
;
907 sdCmdTime
= getTime_ms();
911 sdPreCmdState(CMD_STATE_WRITE
);
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
);
920 uint8_t v
= sdCommandAndResponse(SD_WRITE_MULTIPLE_BLOCK
, sdLBA
);
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
;
932 sdCmdTime
= getTime_ms();
933 sdCmdNextLBA
= tmpNextLBA
;
934 sdCmdState
= CMD_STATE_WRITE
;
941 if ((scsiDev
.phase
== BUS_FREE
) &&
942 (sdCmdState
!= CMD_STATE_IDLE
) &&
943 (elapsedTime_ms(sdCmdTime
) >= 50))
945 sdPreCmdState(CMD_STATE_IDLE
);
949 void sdCheckPresent()
951 // Check if there's an SD card present.
952 if ((scsiDev
.phase
== BUS_FREE
) &&
953 (sdIOState
== SD_IDLE
) &&
954 (sdCmdState
== CMD_STATE_IDLE
))
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.
962 SD_CS_SetDriveMode(SD_CS_DM_DIG_HIZ
);
964 // Delay extended to work with 60cm cables running cards at 2.85V
966 uint8_t cs
= SD_CS_Read();
967 SD_CS_SetDriveMode(SD_CS_DM_STRONG
) ;
969 if (cs
&& !(blockDev
.state
& DISK_PRESENT
))
971 static int firstInit
= 1;
978 blockDev
.state
|= DISK_PRESENT
| DISK_INITIALISED
;
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
;
990 for (i
= 0; i
< MAX_SCSI_TARGETS
; ++i
)
992 scsiDev
.targets
[i
].unitAttention
= PARAMETERS_CHANGED
;
998 else if (!cs
&& (blockDev
.state
& DISK_PRESENT
))
1001 blockDev
.state
&= ~DISK_PRESENT
;
1002 blockDev
.state
&= ~DISK_INITIALISED
;
1004 for (i
= 0; i
< MAX_SCSI_TARGETS
; ++i
)
1006 scsiDev
.targets
[i
].unitAttention
= PARAMETERS_CHANGED
;
1012 #pragma GCC pop_options