1 // Copyright (C) 2013 Michael McMaster <michael@codesrc.com>
\r
2 // Copyright (C) 2014 Doug Brown <doug@downtowndougbrown.com>
\r
4 // This file is part of SCSI2SD.
\r
6 // SCSI2SD is free software: you can redistribute it and/or modify
\r
7 // it under the terms of the GNU General Public License as published by
\r
8 // the Free Software Foundation, either version 3 of the License, or
\r
9 // (at your option) any later version.
\r
11 // SCSI2SD is distributed in the hope that it will be useful,
\r
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
\r
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
\r
14 // GNU General Public License for more details.
\r
16 // You should have received a copy of the GNU General Public License
\r
17 // along with SCSI2SD. If not, see <http://www.gnu.org/licenses/>.
\r
20 #include "stm32f2xx.h"
\r
23 #include "stm32f4xx.h"
\r
28 // For SD write direct routines
\r
30 #include "bsp_driver_sd.h"
\r
34 #include "scsiPhy.h"
\r
44 BlockDevice blockDev;
\r
47 static int doSdInit()
\r
50 if (blockDev.state & DISK_PRESENT)
\r
52 blockDev.state = blockDev.state | DISK_INITIALISED;
\r
57 // Callback once all data has been read in the data out phase.
\r
58 static void doFormatUnitComplete(void)
\r
60 // TODO start writing the initialisation pattern to the SD
\r
62 scsiDev.phase = STATUS;
\r
65 static void doFormatUnitSkipData(int bytes)
\r
67 // We may not have enough memory to store the initialisation pattern and
\r
68 // defect list data. Since we're not making use of it yet anyway, just
\r
69 // discard the bytes.
\r
70 scsiEnterPhase(DATA_OUT);
\r
72 for (i = 0; i < bytes; ++i)
\r
78 // Callback from the data out phase.
\r
79 static void doFormatUnitPatternHeader(void)
\r
82 ((((uint16_t)scsiDev.data[2])) << 8) +
\r
86 ((((uint16_t)scsiDev.data[4 + 2])) << 8) +
\r
87 scsiDev.data[4 + 3];
\r
89 doFormatUnitSkipData(defectLength + patternLength);
\r
90 doFormatUnitComplete();
\r
93 // Callback from the data out phase.
\r
94 static void doFormatUnitHeader(void)
\r
96 int IP = (scsiDev.data[1] & 0x08) ? 1 : 0;
\r
97 int DSP = (scsiDev.data[1] & 0x04) ? 1 : 0;
\r
99 if (! DSP) // disable save parameters
\r
101 // Save the "MODE SELECT savable parameters"
\r
103 scsiDev.target->targetId,
\r
104 scsiDev.target->liveCfg.bytesPerSector);
\r
109 // We need to read the initialisation pattern header first.
\r
110 scsiDev.dataLen += 4;
\r
111 scsiDev.phase = DATA_OUT;
\r
112 scsiDev.postDataOutHook = doFormatUnitPatternHeader;
\r
116 // Read the defect list data
\r
118 ((((uint16_t)scsiDev.data[2])) << 8) +
\r
120 doFormatUnitSkipData(defectLength);
\r
121 doFormatUnitComplete();
\r
125 static void doReadCapacity()
\r
127 uint32_t lba = (((uint32_t) scsiDev.cdb[2]) << 24) +
\r
128 (((uint32_t) scsiDev.cdb[3]) << 16) +
\r
129 (((uint32_t) scsiDev.cdb[4]) << 8) +
\r
131 int pmi = scsiDev.cdb[8] & 1;
\r
133 uint32_t capacity = getScsiCapacity(
\r
134 scsiDev.target->cfg->sdSectorStart,
\r
135 scsiDev.target->liveCfg.bytesPerSector,
\r
136 scsiDev.target->cfg->scsiSectors);
\r
141 // We don't do anything with the "partial medium indicator", and
\r
142 // assume that delays are constant across each block. But the spec
\r
143 // says we must return this error if pmi is specified incorrectly.
\r
144 scsiDev.status = CHECK_CONDITION;
\r
145 scsiDev.target->sense.code = ILLEGAL_REQUEST;
\r
146 scsiDev.target->sense.asc = INVALID_FIELD_IN_CDB;
\r
147 scsiDev.phase = STATUS;
\r
149 else if (capacity > 0)
\r
151 uint32_t highestBlock = capacity - 1;
\r
153 scsiDev.data[0] = highestBlock >> 24;
\r
154 scsiDev.data[1] = highestBlock >> 16;
\r
155 scsiDev.data[2] = highestBlock >> 8;
\r
156 scsiDev.data[3] = highestBlock;
\r
158 uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
\r
159 scsiDev.data[4] = bytesPerSector >> 24;
\r
160 scsiDev.data[5] = bytesPerSector >> 16;
\r
161 scsiDev.data[6] = bytesPerSector >> 8;
\r
162 scsiDev.data[7] = bytesPerSector;
\r
163 scsiDev.dataLen = 8;
\r
164 scsiDev.phase = DATA_IN;
\r
168 scsiDev.status = CHECK_CONDITION;
\r
169 scsiDev.target->sense.code = NOT_READY;
\r
170 scsiDev.target->sense.asc = MEDIUM_NOT_PRESENT;
\r
171 scsiDev.phase = STATUS;
\r
175 static void doWrite(uint32_t lba, uint32_t blocks)
\r
177 if (unlikely(scsiDev.target->cfg->deviceType == S2S_CFG_FLOPPY_14MB)) {
\r
178 // Floppies are supposed to be slow. Some systems can't handle a floppy
\r
179 // without an access time
\r
183 uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
\r
185 if (unlikely(blockDev.state & DISK_WP) ||
\r
186 unlikely(scsiDev.target->cfg->deviceType == S2S_CFG_OPTICAL))
\r
189 scsiDev.status = CHECK_CONDITION;
\r
190 scsiDev.target->sense.code = ILLEGAL_REQUEST;
\r
191 scsiDev.target->sense.asc = WRITE_PROTECTED;
\r
192 scsiDev.phase = STATUS;
\r
194 else if (unlikely(((uint64_t) lba) + blocks >
\r
196 scsiDev.target->cfg->sdSectorStart,
\r
198 scsiDev.target->cfg->scsiSectors
\r
202 scsiDev.status = CHECK_CONDITION;
\r
203 scsiDev.target->sense.code = ILLEGAL_REQUEST;
\r
204 scsiDev.target->sense.asc = LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
\r
205 scsiDev.phase = STATUS;
\r
209 transfer.lba = lba;
\r
210 transfer.blocks = blocks;
\r
211 transfer.currentBlock = 0;
\r
212 scsiDev.phase = DATA_OUT;
\r
213 scsiDev.dataLen = bytesPerSector;
\r
214 scsiDev.dataPtr = bytesPerSector;
\r
216 // No need for single-block writes atm. Overhead of the
\r
217 // multi-block write is minimal.
\r
218 transfer.multiBlock = 1;
\r
221 // TODO uint32_t sdLBA =
\r
222 // TODO SCSISector2SD(
\r
223 // TODO scsiDev.target->cfg->sdSectorStart,
\r
224 // TODO bytesPerSector,
\r
226 // TODO uint32_t sdBlocks = blocks * SDSectorsPerSCSISector(bytesPerSector);
\r
227 // TODO sdWriteMultiSectorPrep(sdLBA, sdBlocks);
\r
232 static void doRead(uint32_t lba, uint32_t blocks)
\r
234 if (unlikely(scsiDev.target->cfg->deviceType == S2S_CFG_FLOPPY_14MB)) {
\r
235 // Floppies are supposed to be slow. Some systems can't handle a floppy
\r
236 // without an access time
\r
240 uint32_t capacity = getScsiCapacity(
\r
241 scsiDev.target->cfg->sdSectorStart,
\r
242 scsiDev.target->liveCfg.bytesPerSector,
\r
243 scsiDev.target->cfg->scsiSectors);
\r
244 if (unlikely(((uint64_t) lba) + blocks > capacity))
\r
246 scsiDev.status = CHECK_CONDITION;
\r
247 scsiDev.target->sense.code = ILLEGAL_REQUEST;
\r
248 scsiDev.target->sense.asc = LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
\r
249 scsiDev.phase = STATUS;
\r
253 transfer.lba = lba;
\r
254 transfer.blocks = blocks;
\r
255 transfer.currentBlock = 0;
\r
256 scsiDev.phase = DATA_IN;
\r
257 scsiDev.dataLen = 0; // No data yet
\r
259 uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
\r
260 uint32_t sdSectorPerSCSISector = SDSectorsPerSCSISector(bytesPerSector);
\r
261 uint32_t sdSectors =
\r
262 blocks * sdSectorPerSCSISector;
\r
265 (sdSectors == 1) &&
\r
266 !(scsiDev.boardCfg.flags & S2S_CFG_ENABLE_CACHE)
\r
268 unlikely(((uint64_t) lba) + blocks == capacity)
\r
271 // We get errors on reading the last sector using a multi-sector
\r
273 transfer.multiBlock = 0;
\r
277 transfer.multiBlock = 1;
\r
279 // uint32_t sdLBA =
\r
281 // scsiDev.target->cfg->sdSectorStart,
\r
285 // TODO sdReadMultiSectorPrep(sdLBA, sdSectors);
\r
290 static void doSeek(uint32_t lba)
\r
294 scsiDev.target->cfg->sdSectorStart,
\r
295 scsiDev.target->liveCfg.bytesPerSector,
\r
296 scsiDev.target->cfg->scsiSectors)
\r
299 scsiDev.status = CHECK_CONDITION;
\r
300 scsiDev.target->sense.code = ILLEGAL_REQUEST;
\r
301 scsiDev.target->sense.asc = LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
\r
302 scsiDev.phase = STATUS;
\r
310 static int doTestUnitReady()
\r
313 if (likely(blockDev.state == (DISK_STARTED | DISK_PRESENT | DISK_INITIALISED)))
\r
317 else if (unlikely(!(blockDev.state & DISK_STARTED)))
\r
320 scsiDev.status = CHECK_CONDITION;
\r
321 scsiDev.target->sense.code = NOT_READY;
\r
322 scsiDev.target->sense.asc = LOGICAL_UNIT_NOT_READY_INITIALIZING_COMMAND_REQUIRED;
\r
323 scsiDev.phase = STATUS;
\r
325 else if (unlikely(!(blockDev.state & DISK_PRESENT)))
\r
328 scsiDev.status = CHECK_CONDITION;
\r
329 scsiDev.target->sense.code = NOT_READY;
\r
330 scsiDev.target->sense.asc = MEDIUM_NOT_PRESENT;
\r
331 scsiDev.phase = STATUS;
\r
333 else if (unlikely(!(blockDev.state & DISK_INITIALISED)))
\r
336 scsiDev.status = CHECK_CONDITION;
\r
337 scsiDev.target->sense.code = NOT_READY;
\r
338 scsiDev.target->sense.asc = LOGICAL_UNIT_NOT_READY_CAUSE_NOT_REPORTABLE;
\r
339 scsiDev.phase = STATUS;
\r
344 // Handle direct-access scsi device commands
\r
345 int scsiDiskCommand()
\r
347 int commandHandled = 1;
\r
349 uint8_t command = scsiDev.cdb[0];
\r
350 if (unlikely(command == 0x1B))
\r
353 // Enable or disable media access operations.
\r
354 // Ignore load/eject requests. We can't do that.
\r
355 //int immed = scsiDev.cdb[1] & 1;
\r
356 int start = scsiDev.cdb[4] & 1;
\r
360 blockDev.state = blockDev.state | DISK_STARTED;
\r
361 if (!(blockDev.state & DISK_INITIALISED))
\r
368 blockDev.state &= ~DISK_STARTED;
\r
371 else if (unlikely(command == 0x00))
\r
376 else if (unlikely(!doTestUnitReady()))
\r
378 // Status and sense codes already set by doTestUnitReady
\r
380 else if (likely(command == 0x08))
\r
384 (((uint32_t) scsiDev.cdb[1] & 0x1F) << 16) +
\r
385 (((uint32_t) scsiDev.cdb[2]) << 8) +
\r
387 uint32_t blocks = scsiDev.cdb[4];
\r
388 if (unlikely(blocks == 0)) blocks = 256;
\r
389 doRead(lba, blocks);
\r
391 else if (likely(command == 0x28))
\r
394 // Ignore all cache control bits - we don't support a memory cache.
\r
397 (((uint32_t) scsiDev.cdb[2]) << 24) +
\r
398 (((uint32_t) scsiDev.cdb[3]) << 16) +
\r
399 (((uint32_t) scsiDev.cdb[4]) << 8) +
\r
402 (((uint32_t) scsiDev.cdb[7]) << 8) +
\r
405 doRead(lba, blocks);
\r
407 else if (likely(command == 0x0A))
\r
411 (((uint32_t) scsiDev.cdb[1] & 0x1F) << 16) +
\r
412 (((uint32_t) scsiDev.cdb[2]) << 8) +
\r
414 uint32_t blocks = scsiDev.cdb[4];
\r
415 if (unlikely(blocks == 0)) blocks = 256;
\r
416 doWrite(lba, blocks);
\r
418 else if (likely(command == 0x2A) || // WRITE(10)
\r
419 unlikely(command == 0x2E)) // WRITE AND VERIFY
\r
421 // Ignore all cache control bits - we don't support a memory cache.
\r
422 // Don't bother verifying either. The SD card likely stores ECC
\r
423 // along with each flash row.
\r
426 (((uint32_t) scsiDev.cdb[2]) << 24) +
\r
427 (((uint32_t) scsiDev.cdb[3]) << 16) +
\r
428 (((uint32_t) scsiDev.cdb[4]) << 8) +
\r
431 (((uint32_t) scsiDev.cdb[7]) << 8) +
\r
434 doWrite(lba, blocks);
\r
436 else if (unlikely(command == 0x04))
\r
439 // We don't really do any formatting, but we need to read the correct
\r
440 // number of bytes in the DATA_OUT phase to make the SCSI host happy.
\r
442 int fmtData = (scsiDev.cdb[1] & 0x10) ? 1 : 0;
\r
445 // We need to read the parameter list, but we don't know how
\r
446 // big it is yet. Start with the header.
\r
447 scsiDev.dataLen = 4;
\r
448 scsiDev.phase = DATA_OUT;
\r
449 scsiDev.postDataOutHook = doFormatUnitHeader;
\r
453 // No data to read, we're already finished!
\r
456 else if (unlikely(command == 0x25))
\r
461 else if (unlikely(command == 0x0B))
\r
465 (((uint32_t) scsiDev.cdb[1] & 0x1F) << 16) +
\r
466 (((uint32_t) scsiDev.cdb[2]) << 8) +
\r
472 else if (unlikely(command == 0x2B))
\r
476 (((uint32_t) scsiDev.cdb[2]) << 24) +
\r
477 (((uint32_t) scsiDev.cdb[3]) << 16) +
\r
478 (((uint32_t) scsiDev.cdb[4]) << 8) +
\r
483 else if (unlikely(command == 0x36))
\r
485 // LOCK UNLOCK CACHE
\r
486 // We don't have a cache to lock data into. do nothing.
\r
488 else if (unlikely(command == 0x34))
\r
491 // We don't have a cache to pre-fetch into. do nothing.
\r
493 else if (unlikely(command == 0x1E))
\r
495 // PREVENT ALLOW MEDIUM REMOVAL
\r
496 // Not much we can do to prevent the user removing the SD card.
\r
499 else if (unlikely(command == 0x01))
\r
502 // Set the lun to a vendor-specific state. Ignore.
\r
504 else if (unlikely(command == 0x35))
\r
506 // SYNCHRONIZE CACHE
\r
507 // We don't have a cache. do nothing.
\r
509 else if (unlikely(command == 0x2F))
\r
512 // TODO: When they supply data to verify, we should read the data and
\r
513 // verify it. If they don't supply any data, just say success.
\r
514 if ((scsiDev.cdb[1] & 0x02) == 0)
\r
516 // They are asking us to do a medium verification with no data
\r
517 // comparison. Assume success, do nothing.
\r
521 // TODO. This means they are supplying data to verify against.
\r
522 // Technically we should probably grab the data and compare it.
\r
523 scsiDev.status = CHECK_CONDITION;
\r
524 scsiDev.target->sense.code = ILLEGAL_REQUEST;
\r
525 scsiDev.target->sense.asc = INVALID_FIELD_IN_CDB;
\r
526 scsiDev.phase = STATUS;
\r
529 else if (unlikely(command == 0x37))
\r
531 // READ DEFECT DATA
\r
532 uint32_t allocLength = (((uint16_t)scsiDev.cdb[7]) << 8) |
\r
535 scsiDev.data[0] = 0;
\r
536 scsiDev.data[1] = scsiDev.cdb[1];
\r
537 scsiDev.data[2] = 0;
\r
538 scsiDev.data[3] = 0;
\r
539 scsiDev.dataLen = 4;
\r
541 if (scsiDev.dataLen > allocLength)
\r
543 scsiDev.dataLen = allocLength;
\r
546 scsiDev.phase = DATA_IN;
\r
550 commandHandled = 0;
\r
553 return commandHandled;
\r
557 calcReadahead(uint32_t totalBytes, uint32_t sdSpeedKBs, uint32_t scsiSpeedKBs)
\r
559 if (!(scsiDev.boardCfg.flags6 & S2S_CFG_ENABLE_BLIND_WRITES) ||
\r
560 (scsiSpeedKBs == 0) ||
\r
561 (scsiDev.hostSpeedMeasured == 0))
\r
566 // uint32_t readAheadBytes = totalBytes * (1 - scsiSpeedKBs / sdSpeedKBs);
\r
567 // Won't overflow with 65536 max bytes, 20000 max scsi speed.
\r
568 uint32_t readAheadBytes = totalBytes - totalBytes * scsiSpeedKBs / sdSpeedKBs;
\r
570 // Round up to nearest FIFO size (* 4 for safety)
\r
571 readAheadBytes = ((readAheadBytes / SCSI_FIFO_DEPTH) + 4) * SCSI_FIFO_DEPTH;
\r
573 if (readAheadBytes > totalBytes)
\r
575 readAheadBytes = totalBytes;
\r
578 return readAheadBytes;
\r
581 void scsiDiskPoll()
\r
583 uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
\r
585 if (scsiDev.phase == DATA_IN &&
\r
586 transfer.currentBlock != transfer.blocks)
\r
588 // Take responsibility for waiting for the phase delays
\r
589 uint32_t phaseChangeDelayUs = scsiEnterPhaseImmediate(DATA_IN);
\r
591 int totalSDSectors =
\r
592 transfer.blocks * SDSectorsPerSCSISector(bytesPerSector);
\r
595 scsiDev.target->cfg->sdSectorStart,
\r
599 const int sdPerScsi = SDSectorsPerSCSISector(bytesPerSector);
\r
600 const int buffers = sizeof(scsiDev.data) / SD_SECTOR_SIZE;
\r
603 int scsiActive __attribute__((unused)) = 0; // unused if DMA disabled
\r
606 // It's highly unlikely that someone is going to use huge transfers
\r
607 // per scsi command, but if they do it'll be slower than usual.
\r
608 uint32_t totalScsiBytes = transfer.blocks * bytesPerSector;
\r
609 int useSlowDataCount = totalScsiBytes >= SCSI_XFER_MAX;
\r
610 if (!useSlowDataCount)
\r
612 scsiSetDataCount(totalScsiBytes);
\r
615 while ((i < totalSDSectors) &&
\r
616 likely(scsiDev.phase == DATA_IN) &&
\r
617 likely(!scsiDev.resetFlag))
\r
619 int completedDmaSectors;
\r
620 if (sdActive && (completedDmaSectors = sdReadDMAPoll(sdActive)))
\r
622 prep += completedDmaSectors;
\r
623 sdActive -= completedDmaSectors;
\r
624 } else if (sdActive > 1)
\r
626 if ((scsiDev.data[SD_SECTOR_SIZE * (prep % buffers) + 510] != 0xAA) ||
\r
627 (scsiDev.data[SD_SECTOR_SIZE * (prep % buffers) + 511] != 0x33))
\r
635 (prep - i < buffers) &&
\r
636 (prep < totalSDSectors) &&
\r
637 ((totalSDSectors - prep) >= sdPerScsi) &&
\r
638 (likely(!useSlowDataCount) || scsiPhyComplete()) &&
\r
639 (HAL_SD_GetState(&hsd) != HAL_SD_STATE_BUSY)) // rx complete but IRQ not fired yet.
\r
641 // Start an SD transfer if we have space.
\r
642 uint32_t startBuffer = prep % buffers;
\r
643 uint32_t sectors = totalSDSectors - prep;
\r
644 uint32_t freeBuffers = buffers - (prep - i);
\r
646 uint32_t contiguousBuffers = buffers - startBuffer;
\r
647 freeBuffers = freeBuffers < contiguousBuffers
\r
648 ? freeBuffers : contiguousBuffers;
\r
649 sectors = sectors < freeBuffers ? sectors : freeBuffers;
\r
651 if (sectors > 128) sectors = 128; // 65536 DMA limit !!
\r
653 // Round-down when we have odd sector sizes.
\r
654 if (sdPerScsi != 1)
\r
656 sectors = (sectors / sdPerScsi) * sdPerScsi;
\r
659 for (int dodgy = 0; dodgy < sectors; dodgy++)
\r
661 scsiDev.data[SD_SECTOR_SIZE * (startBuffer + dodgy) + 510] = 0xAA;
\r
662 scsiDev.data[SD_SECTOR_SIZE * (startBuffer + dodgy) + 511] = 0x33;
\r
665 sdReadDMA(sdLBA + prep, sectors, &scsiDev.data[SD_SECTOR_SIZE * startBuffer]);
\r
667 sdActive = sectors;
\r
669 if (useSlowDataCount)
\r
671 scsiSetDataCount((sectors / sdPerScsi) * bytesPerSector);
\r
674 // Wait now that the SD card is busy
\r
675 // Chances are we've probably already waited sufficient time,
\r
676 // but it's hard to measure microseconds cheaply. So just wait
\r
677 // extra just-in-case. Hopefully it's in parallel with dma.
\r
678 if (phaseChangeDelayUs > 0)
\r
680 s2s_delay_us(phaseChangeDelayUs);
\r
681 phaseChangeDelayUs = 0;
\r
685 if ((prep - i) > 0)
\r
687 int dmaBytes = SD_SECTOR_SIZE;
\r
688 if ((i % sdPerScsi) == (sdPerScsi - 1))
\r
690 dmaBytes = bytesPerSector % SD_SECTOR_SIZE;
\r
691 if (dmaBytes == 0) dmaBytes = SD_SECTOR_SIZE;
\r
694 uint8_t* scsiDmaData = &(scsiDev.data[SD_SECTOR_SIZE * (i % buffers)]);
\r
695 scsiWritePIO(scsiDmaData, dmaBytes);
\r
701 if (phaseChangeDelayUs > 0 && !scsiDev.resetFlag) // zero bytes ?
\r
703 s2s_delay_us(phaseChangeDelayUs);
\r
704 phaseChangeDelayUs = 0;
\r
707 // We've finished transferring the data to the FPGA, now wait until it's
\r
708 // written to he SCSI bus.
\r
710 while (!scsiPhyComplete() &&
\r
711 likely(scsiDev.phase == DATA_IN) &&
\r
712 likely(!scsiDev.resetFlag))
\r
718 while (HAL_SD_GetState(&hsd) == HAL_SD_STATE_BUSY)
\r
720 // Wait while keeping BSY.
\r
723 if (scsiDev.phase == DATA_IN)
\r
725 scsiDev.phase = STATUS;
\r
729 else if (scsiDev.phase == DATA_OUT &&
\r
730 transfer.currentBlock != transfer.blocks)
\r
732 scsiEnterPhase(DATA_OUT);
\r
734 const int sdPerScsi = SDSectorsPerSCSISector(bytesPerSector);
\r
735 int totalSDSectors = transfer.blocks * sdPerScsi;
\r
738 scsiDev.target->cfg->sdSectorStart,
\r
744 int parityError = 0;
\r
745 int enableParity = scsiDev.boardCfg.flags & S2S_CFG_ENABLE_PARITY;
\r
747 uint32_t maxSectors = sizeof(scsiDev.data) / SD_SECTOR_SIZE;
\r
749 static_assert(SCSI_XFER_MAX >= sizeof(scsiDev.data), "Assumes SCSI_XFER_MAX >= sizeof(scsiDev.data)");
\r
751 // Start reading and filling fifos as soon as possible.
\r
752 // It's highly unlikely that someone is going to use huge transfers
\r
753 // per scsi command, but if they do it'll be slower than usual.
\r
754 // Note: Happens in Macintosh FWB HDD Toolkit benchmarks which default
\r
756 uint32_t totalTransferBytes = transfer.blocks * bytesPerSector;
\r
757 int useSlowDataCount = totalTransferBytes >= SCSI_XFER_MAX;
\r
758 if (!useSlowDataCount)
\r
760 DWT->CYCCNT = 0; // Start counting cycles
\r
761 scsiSetDataCount(totalTransferBytes);
\r
764 while ((i < totalSDSectors) &&
\r
765 likely(scsiDev.phase == DATA_OUT) &&
\r
766 likely(!scsiDev.resetFlag))
\r
767 // KEEP GOING to ensure FIFOs are in a good state.
\r
768 // likely(!parityError || !enableParity))
\r
770 uint32_t rem = totalSDSectors - i;
\r
771 uint32_t sectors = rem < maxSectors ? rem : maxSectors;
\r
773 if (bytesPerSector == SD_SECTOR_SIZE)
\r
775 // We assume the SD card is faster than the SCSI interface, but has
\r
776 // no flow control. This can be handled if a) the scsi interface
\r
777 // doesn't block and b) we read enough SCSI sectors first so that
\r
778 // the SD interface cannot catch up.
\r
779 uint32_t totalBytes = sectors * SD_SECTOR_SIZE;
\r
781 uint32_t sdSpeedKBs = s2s_getSdRateKBs() + (scsiDev.sdUnderrunCount * 256);
\r
782 uint32_t readAheadBytes = calcReadahead(
\r
785 scsiDev.hostSpeedKBs);
\r
787 if (useSlowDataCount)
\r
789 DWT->CYCCNT = 0; // Start counting cycles
\r
790 scsiSetDataCount(totalBytes);
\r
793 uint32_t scsiBytesRead = 0;
\r
794 if (readAheadBytes > 0)
\r
797 &scsiDev.data[scsiBytesRead],
\r
800 scsiBytesRead += readAheadBytes;
\r
802 if (i == 0 && !useSlowDataCount)
\r
804 uint32_t elapsedCycles = DWT->CYCCNT;
\r
806 // uint32_t rateKBs = (readAheadBytes / 1000) / (elapsedCycles / HAL_RCC_GetHCLKFreq());
\r
807 // Scaled by 4 to avoid overflow w/ max 65536 at 108MHz.
\r
808 uint32_t rateKBs = ((readAheadBytes / 4) * (HAL_RCC_GetHCLKFreq() / 1000) / elapsedCycles) * 4;
\r
810 scsiDev.hostSpeedKBs = (scsiDev.hostSpeedKBs + rateKBs) / 2;
\r
811 scsiDev.hostSpeedMeasured = 1;
\r
813 if (rateKBs < scsiDev.hostSpeedKBs)
\r
815 // Our readahead was too slow; assume remaining bytes
\r
816 // will be as well.
\r
817 if (readAheadBytes < totalBytes)
\r
819 uint32_t properReadahead = calcReadahead(
\r
824 if (properReadahead > readAheadBytes)
\r
826 uint32_t diff = properReadahead - readAheadBytes;
\r
827 readAheadBytes = properReadahead;
\r
829 &scsiDev.data[scsiBytesRead],
\r
832 scsiBytesRead += diff;
\r
839 HAL_SD_WriteBlocks_DMA(&hsd, (&scsiDev.data[0]), i + sdLBA, sectors);
\r
842 if (scsiBytesRead < totalBytes && !scsiDev.resetFlag)
\r
845 &scsiDev.data[scsiBytesRead],
\r
846 totalBytes - readAheadBytes,
\r
849 // Oh dear, SD finished first.
\r
850 underrun = HAL_DMA_GetState(hsd.hdmatx) == HAL_DMA_STATE_BUSY;
\r
852 scsiBytesRead += (totalBytes - readAheadBytes);
\r
855 uint32_t dmaFinishTime = s2s_getTime_ms();
\r
856 while ((HAL_SD_GetState(&hsd) == HAL_SD_STATE_BUSY) &&
\r
857 s2s_elapsedTime_ms(dmaFinishTime) < 180)
\r
859 // Wait while keeping BSY.
\r
862 HAL_SD_CardStateTypeDef cardState = HAL_SD_GetCardState(&hsd);
\r
863 while ((cardState == HAL_SD_CARD_PROGRAMMING || cardState == HAL_SD_CARD_RECEIVING) &&
\r
864 s2s_elapsedTime_ms(dmaFinishTime) < 180)
\r
866 // Wait while the SD card is writing buffer to flash
\r
867 // The card may remain in the RECEIVING state (even though it's programming) if
\r
868 // it has buffer space to receive more data available.
\r
869 cardState = HAL_SD_GetCardState(&hsd);
\r
872 if (i + sectors >= totalSDSectors &&
\r
874 (!parityError || !enableParity))
\r
876 // We're transferring over the SCSI bus faster than the SD card
\r
877 // can write. All data is buffered, and we're just waiting for
\r
878 // the SD card to complete. The host won't let us disconnect.
\r
879 // Some drivers set a 250ms timeout on transfers to complete.
\r
880 // SD card writes are supposed to complete
\r
881 // within 200ms, but sometimes they don't.
\r
882 // Just pretend we're finished.
\r
884 clearBSY = process_MessageIn(0); // Will go to BUS_FREE state but keep BSY asserted.
\r
887 while (HAL_SD_GetState(&hsd) == HAL_SD_STATE_BUSY)
\r
889 // Wait while keeping BSY.
\r
892 cardState = HAL_SD_GetCardState(&hsd);
\r
893 while (cardState == HAL_SD_CARD_PROGRAMMING || cardState == HAL_SD_CARD_RECEIVING)
\r
895 // Wait while the SD card is writing buffer to flash
\r
896 // The card may remain in the RECEIVING state (even though it's programming) if
\r
897 // it has buffer space to receive more data available.
\r
898 cardState = HAL_SD_GetCardState(&hsd);
\r
901 if (underrun && (!parityError || !enableParity))
\r
903 // Try again. Data is still in memory.
\r
904 BSP_SD_WriteBlocks_DMA(&scsiDev.data[0], i + sdLBA, sectors);
\r
905 scsiDev.sdUnderrunCount++;
\r
912 // Well, until we have some proper non-blocking SD code, we must
\r
913 // do this in a half-duplex fashion. We need to write as much as
\r
914 // possible in each SD card transaction.
\r
915 // use sg_dd from sg_utils3 tools to test.
\r
917 if (useSlowDataCount)
\r
919 scsiSetDataCount(sectors * bytesPerSector);
\r
922 for (int scsiSector = i; scsiSector < i + sectors; ++scsiSector)
\r
924 int dmaBytes = SD_SECTOR_SIZE;
\r
925 if ((scsiSector % sdPerScsi) == (sdPerScsi - 1))
\r
927 dmaBytes = bytesPerSector % SD_SECTOR_SIZE;
\r
928 if (dmaBytes == 0) dmaBytes = SD_SECTOR_SIZE;
\r
931 scsiReadPIO(&scsiDev.data[SD_SECTOR_SIZE * (scsiSector - i)], dmaBytes, &parityError);
\r
933 if (!parityError || !enableParity)
\r
935 BSP_SD_WriteBlocks_DMA(&scsiDev.data[0], i + sdLBA, sectors);
\r
941 // Should already be complete here as we've ready the FIFOs
\r
942 // by now. Check anyway.
\r
944 while (!scsiPhyComplete() && likely(!scsiDev.resetFlag))
\r
955 if (scsiDev.phase == DATA_OUT)
\r
958 (scsiDev.boardCfg.flags & S2S_CFG_ENABLE_PARITY))
\r
960 scsiDev.target->sense.code = ABORTED_COMMAND;
\r
961 scsiDev.target->sense.asc = SCSI_PARITY_ERROR;
\r
962 scsiDev.status = CHECK_CONDITION;;
\r
964 scsiDev.phase = STATUS;
\r
970 void scsiDiskReset()
\r
972 scsiDev.dataPtr = 0;
\r
973 scsiDev.savedDataPtr = 0;
\r
974 scsiDev.dataLen = 0;
\r
975 // transfer.lba = 0; // Needed in Request Sense to determine failure
\r
976 transfer.blocks = 0;
\r
977 transfer.currentBlock = 0;
\r
979 // Cancel long running commands!
\r
982 ((scsiDev.boardCfg.flags & S2S_CFG_ENABLE_CACHE) == 0) ||
\r
983 (transfer.multiBlock == 0)
\r
987 sdCompleteTransfer();
\r
990 transfer.multiBlock = 0;
\r
993 void scsiDiskInit()
\r
997 // Don't require the host to send us a START STOP UNIT command
\r
998 blockDev.state = DISK_STARTED;
\r