disk.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  1. // Copyright (C) 2013 Michael McMaster <michael@codesrc.com>
  2. // Copyright (C) 2014 Doug Brown <doug@downtowndougbrown.com>
  3. //
  4. // This file is part of SCSI2SD.
  5. //
  6. // SCSI2SD is free software: you can redistribute it and/or modify
  7. // it under the terms of the GNU General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // SCSI2SD is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU General Public License
  17. // along with SCSI2SD. If not, see <http://www.gnu.org/licenses/>.
  18. #include "stm32f2xx.h"
  19. #include <assert.h>
  20. // For SD write direct routines
  21. #include "sdio.h"
  22. #include "bsp_driver_sd.h"
  23. #include "scsi.h"
  24. #include "scsiPhy.h"
  25. #include "config.h"
  26. #include "disk.h"
  27. #include "sd.h"
  28. #include "time.h"
  29. #include "bsp.h"
  30. #include <string.h>
  31. // Global
  32. BlockDevice blockDev;
  33. Transfer transfer;
  34. static int doSdInit()
  35. {
  36. int result = 0;
  37. if (blockDev.state & DISK_PRESENT)
  38. {
  39. blockDev.state = blockDev.state | DISK_INITIALISED;
  40. }
  41. return result;
  42. }
  43. // Callback once all data has been read in the data out phase.
  44. static void doFormatUnitComplete(void)
  45. {
  46. // TODO start writing the initialisation pattern to the SD
  47. // card
  48. scsiDev.phase = STATUS;
  49. }
  50. static void doFormatUnitSkipData(int bytes)
  51. {
  52. // We may not have enough memory to store the initialisation pattern and
  53. // defect list data. Since we're not making use of it yet anyway, just
  54. // discard the bytes.
  55. scsiEnterPhase(DATA_OUT);
  56. int i;
  57. for (i = 0; i < bytes; ++i)
  58. {
  59. scsiReadByte();
  60. }
  61. }
  62. // Callback from the data out phase.
  63. static void doFormatUnitPatternHeader(void)
  64. {
  65. int defectLength =
  66. ((((uint16_t)scsiDev.data[2])) << 8) +
  67. scsiDev.data[3];
  68. int patternLength =
  69. ((((uint16_t)scsiDev.data[4 + 2])) << 8) +
  70. scsiDev.data[4 + 3];
  71. doFormatUnitSkipData(defectLength + patternLength);
  72. doFormatUnitComplete();
  73. }
  74. // Callback from the data out phase.
  75. static void doFormatUnitHeader(void)
  76. {
  77. int IP = (scsiDev.data[1] & 0x08) ? 1 : 0;
  78. int DSP = (scsiDev.data[1] & 0x04) ? 1 : 0;
  79. if (! DSP) // disable save parameters
  80. {
  81. // Save the "MODE SELECT savable parameters"
  82. s2s_configSave(
  83. scsiDev.target->targetId,
  84. scsiDev.target->liveCfg.bytesPerSector);
  85. }
  86. if (IP)
  87. {
  88. // We need to read the initialisation pattern header first.
  89. scsiDev.dataLen += 4;
  90. scsiDev.phase = DATA_OUT;
  91. scsiDev.postDataOutHook = doFormatUnitPatternHeader;
  92. }
  93. else
  94. {
  95. // Read the defect list data
  96. int defectLength =
  97. ((((uint16_t)scsiDev.data[2])) << 8) +
  98. scsiDev.data[3];
  99. doFormatUnitSkipData(defectLength);
  100. doFormatUnitComplete();
  101. }
  102. }
  103. static void doReadCapacity()
  104. {
  105. uint32_t lba = (((uint32_t) scsiDev.cdb[2]) << 24) +
  106. (((uint32_t) scsiDev.cdb[3]) << 16) +
  107. (((uint32_t) scsiDev.cdb[4]) << 8) +
  108. scsiDev.cdb[5];
  109. int pmi = scsiDev.cdb[8] & 1;
  110. uint32_t capacity = getScsiCapacity(
  111. scsiDev.target->cfg->sdSectorStart,
  112. scsiDev.target->liveCfg.bytesPerSector,
  113. scsiDev.target->cfg->scsiSectors);
  114. if (!pmi && lba)
  115. {
  116. // error.
  117. // We don't do anything with the "partial medium indicator", and
  118. // assume that delays are constant across each block. But the spec
  119. // says we must return this error if pmi is specified incorrectly.
  120. scsiDev.status = CHECK_CONDITION;
  121. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  122. scsiDev.target->sense.asc = INVALID_FIELD_IN_CDB;
  123. scsiDev.phase = STATUS;
  124. }
  125. else if (capacity > 0)
  126. {
  127. uint32_t highestBlock = capacity - 1;
  128. scsiDev.data[0] = highestBlock >> 24;
  129. scsiDev.data[1] = highestBlock >> 16;
  130. scsiDev.data[2] = highestBlock >> 8;
  131. scsiDev.data[3] = highestBlock;
  132. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  133. scsiDev.data[4] = bytesPerSector >> 24;
  134. scsiDev.data[5] = bytesPerSector >> 16;
  135. scsiDev.data[6] = bytesPerSector >> 8;
  136. scsiDev.data[7] = bytesPerSector;
  137. scsiDev.dataLen = 8;
  138. scsiDev.phase = DATA_IN;
  139. }
  140. else
  141. {
  142. scsiDev.status = CHECK_CONDITION;
  143. scsiDev.target->sense.code = NOT_READY;
  144. scsiDev.target->sense.asc = MEDIUM_NOT_PRESENT;
  145. scsiDev.phase = STATUS;
  146. }
  147. }
  148. static void doWrite(uint32_t lba, uint32_t blocks)
  149. {
  150. if (unlikely(scsiDev.target->cfg->deviceType == S2S_CFG_FLOPPY_14MB)) {
  151. // Floppies are supposed to be slow. Some systems can't handle a floppy
  152. // without an access time
  153. s2s_delay_ms(10);
  154. }
  155. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  156. if (unlikely(blockDev.state & DISK_WP) ||
  157. unlikely(scsiDev.target->cfg->deviceType == S2S_CFG_OPTICAL))
  158. {
  159. scsiDev.status = CHECK_CONDITION;
  160. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  161. scsiDev.target->sense.asc = WRITE_PROTECTED;
  162. scsiDev.phase = STATUS;
  163. }
  164. else if (unlikely(((uint64_t) lba) + blocks >
  165. getScsiCapacity(
  166. scsiDev.target->cfg->sdSectorStart,
  167. bytesPerSector,
  168. scsiDev.target->cfg->scsiSectors
  169. )
  170. ))
  171. {
  172. scsiDev.status = CHECK_CONDITION;
  173. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  174. scsiDev.target->sense.asc = LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
  175. scsiDev.phase = STATUS;
  176. }
  177. else
  178. {
  179. transfer.lba = lba;
  180. transfer.blocks = blocks;
  181. transfer.currentBlock = 0;
  182. scsiDev.phase = DATA_OUT;
  183. scsiDev.dataLen = bytesPerSector;
  184. scsiDev.dataPtr = bytesPerSector;
  185. // No need for single-block writes atm. Overhead of the
  186. // multi-block write is minimal.
  187. transfer.multiBlock = 1;
  188. // TODO uint32_t sdLBA =
  189. // TODO SCSISector2SD(
  190. // TODO scsiDev.target->cfg->sdSectorStart,
  191. // TODO bytesPerSector,
  192. // TODO lba);
  193. // TODO uint32_t sdBlocks = blocks * SDSectorsPerSCSISector(bytesPerSector);
  194. // TODO sdWriteMultiSectorPrep(sdLBA, sdBlocks);
  195. }
  196. }
  197. static void doRead(uint32_t lba, uint32_t blocks)
  198. {
  199. if (unlikely(scsiDev.target->cfg->deviceType == S2S_CFG_FLOPPY_14MB)) {
  200. // Floppies are supposed to be slow. Some systems can't handle a floppy
  201. // without an access time
  202. s2s_delay_ms(10);
  203. }
  204. uint32_t capacity = getScsiCapacity(
  205. scsiDev.target->cfg->sdSectorStart,
  206. scsiDev.target->liveCfg.bytesPerSector,
  207. scsiDev.target->cfg->scsiSectors);
  208. if (unlikely(((uint64_t) lba) + blocks > capacity))
  209. {
  210. scsiDev.status = CHECK_CONDITION;
  211. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  212. scsiDev.target->sense.asc = LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
  213. scsiDev.phase = STATUS;
  214. }
  215. else
  216. {
  217. transfer.lba = lba;
  218. transfer.blocks = blocks;
  219. transfer.currentBlock = 0;
  220. scsiDev.phase = DATA_IN;
  221. scsiDev.dataLen = 0; // No data yet
  222. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  223. uint32_t sdSectorPerSCSISector = SDSectorsPerSCSISector(bytesPerSector);
  224. uint32_t sdSectors =
  225. blocks * sdSectorPerSCSISector;
  226. if ((
  227. (sdSectors == 1) &&
  228. !(scsiDev.boardCfg.flags & S2S_CFG_ENABLE_CACHE)
  229. ) ||
  230. unlikely(((uint64_t) lba) + blocks == capacity)
  231. )
  232. {
  233. // We get errors on reading the last sector using a multi-sector
  234. // read :-(
  235. transfer.multiBlock = 0;
  236. }
  237. else
  238. {
  239. transfer.multiBlock = 1;
  240. // uint32_t sdLBA =
  241. // SCSISector2SD(
  242. // scsiDev.target->cfg->sdSectorStart,
  243. // bytesPerSector,
  244. // lba);
  245. // TODO sdReadMultiSectorPrep(sdLBA, sdSectors);
  246. }
  247. }
  248. }
  249. static void doSeek(uint32_t lba)
  250. {
  251. if (lba >=
  252. getScsiCapacity(
  253. scsiDev.target->cfg->sdSectorStart,
  254. scsiDev.target->liveCfg.bytesPerSector,
  255. scsiDev.target->cfg->scsiSectors)
  256. )
  257. {
  258. scsiDev.status = CHECK_CONDITION;
  259. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  260. scsiDev.target->sense.asc = LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
  261. scsiDev.phase = STATUS;
  262. }
  263. else
  264. {
  265. s2s_delay_ms(10);
  266. }
  267. }
  268. static int doTestUnitReady()
  269. {
  270. int ready = 1;
  271. if (likely(blockDev.state == (DISK_STARTED | DISK_PRESENT | DISK_INITIALISED)))
  272. {
  273. // nothing to do.
  274. }
  275. else if (unlikely(!(blockDev.state & DISK_STARTED)))
  276. {
  277. ready = 0;
  278. scsiDev.status = CHECK_CONDITION;
  279. scsiDev.target->sense.code = NOT_READY;
  280. scsiDev.target->sense.asc = LOGICAL_UNIT_NOT_READY_INITIALIZING_COMMAND_REQUIRED;
  281. scsiDev.phase = STATUS;
  282. }
  283. else if (unlikely(!(blockDev.state & DISK_PRESENT)))
  284. {
  285. ready = 0;
  286. scsiDev.status = CHECK_CONDITION;
  287. scsiDev.target->sense.code = NOT_READY;
  288. scsiDev.target->sense.asc = MEDIUM_NOT_PRESENT;
  289. scsiDev.phase = STATUS;
  290. }
  291. else if (unlikely(!(blockDev.state & DISK_INITIALISED)))
  292. {
  293. ready = 0;
  294. scsiDev.status = CHECK_CONDITION;
  295. scsiDev.target->sense.code = NOT_READY;
  296. scsiDev.target->sense.asc = LOGICAL_UNIT_NOT_READY_CAUSE_NOT_REPORTABLE;
  297. scsiDev.phase = STATUS;
  298. }
  299. return ready;
  300. }
  301. // Handle direct-access scsi device commands
  302. int scsiDiskCommand()
  303. {
  304. int commandHandled = 1;
  305. uint8_t command = scsiDev.cdb[0];
  306. if (unlikely(command == 0x1B))
  307. {
  308. // START STOP UNIT
  309. // Enable or disable media access operations.
  310. // Ignore load/eject requests. We can't do that.
  311. //int immed = scsiDev.cdb[1] & 1;
  312. int start = scsiDev.cdb[4] & 1;
  313. if (start)
  314. {
  315. blockDev.state = blockDev.state | DISK_STARTED;
  316. if (!(blockDev.state & DISK_INITIALISED))
  317. {
  318. doSdInit();
  319. }
  320. }
  321. else
  322. {
  323. blockDev.state &= ~DISK_STARTED;
  324. }
  325. }
  326. else if (unlikely(command == 0x00))
  327. {
  328. // TEST UNIT READY
  329. doTestUnitReady();
  330. }
  331. else if (unlikely(!doTestUnitReady()))
  332. {
  333. // Status and sense codes already set by doTestUnitReady
  334. }
  335. else if (likely(command == 0x08))
  336. {
  337. // READ(6)
  338. uint32_t lba =
  339. (((uint32_t) scsiDev.cdb[1] & 0x1F) << 16) +
  340. (((uint32_t) scsiDev.cdb[2]) << 8) +
  341. scsiDev.cdb[3];
  342. uint32_t blocks = scsiDev.cdb[4];
  343. if (unlikely(blocks == 0)) blocks = 256;
  344. doRead(lba, blocks);
  345. }
  346. else if (likely(command == 0x28))
  347. {
  348. // READ(10)
  349. // Ignore all cache control bits - we don't support a memory cache.
  350. uint32_t lba =
  351. (((uint32_t) scsiDev.cdb[2]) << 24) +
  352. (((uint32_t) scsiDev.cdb[3]) << 16) +
  353. (((uint32_t) scsiDev.cdb[4]) << 8) +
  354. scsiDev.cdb[5];
  355. uint32_t blocks =
  356. (((uint32_t) scsiDev.cdb[7]) << 8) +
  357. scsiDev.cdb[8];
  358. doRead(lba, blocks);
  359. }
  360. else if (likely(command == 0x0A))
  361. {
  362. // WRITE(6)
  363. uint32_t lba =
  364. (((uint32_t) scsiDev.cdb[1] & 0x1F) << 16) +
  365. (((uint32_t) scsiDev.cdb[2]) << 8) +
  366. scsiDev.cdb[3];
  367. uint32_t blocks = scsiDev.cdb[4];
  368. if (unlikely(blocks == 0)) blocks = 256;
  369. doWrite(lba, blocks);
  370. }
  371. else if (likely(command == 0x2A) || // WRITE(10)
  372. unlikely(command == 0x2E)) // WRITE AND VERIFY
  373. {
  374. // Ignore all cache control bits - we don't support a memory cache.
  375. // Don't bother verifying either. The SD card likely stores ECC
  376. // along with each flash row.
  377. uint32_t lba =
  378. (((uint32_t) scsiDev.cdb[2]) << 24) +
  379. (((uint32_t) scsiDev.cdb[3]) << 16) +
  380. (((uint32_t) scsiDev.cdb[4]) << 8) +
  381. scsiDev.cdb[5];
  382. uint32_t blocks =
  383. (((uint32_t) scsiDev.cdb[7]) << 8) +
  384. scsiDev.cdb[8];
  385. doWrite(lba, blocks);
  386. }
  387. else if (unlikely(command == 0x04))
  388. {
  389. // FORMAT UNIT
  390. // We don't really do any formatting, but we need to read the correct
  391. // number of bytes in the DATA_OUT phase to make the SCSI host happy.
  392. int fmtData = (scsiDev.cdb[1] & 0x10) ? 1 : 0;
  393. if (fmtData)
  394. {
  395. // We need to read the parameter list, but we don't know how
  396. // big it is yet. Start with the header.
  397. scsiDev.dataLen = 4;
  398. scsiDev.phase = DATA_OUT;
  399. scsiDev.postDataOutHook = doFormatUnitHeader;
  400. }
  401. else
  402. {
  403. // No data to read, we're already finished!
  404. }
  405. }
  406. else if (unlikely(command == 0x25))
  407. {
  408. // READ CAPACITY
  409. doReadCapacity();
  410. }
  411. else if (unlikely(command == 0x0B))
  412. {
  413. // SEEK(6)
  414. uint32_t lba =
  415. (((uint32_t) scsiDev.cdb[1] & 0x1F) << 16) +
  416. (((uint32_t) scsiDev.cdb[2]) << 8) +
  417. scsiDev.cdb[3];
  418. doSeek(lba);
  419. }
  420. else if (unlikely(command == 0x2B))
  421. {
  422. // SEEK(10)
  423. uint32_t lba =
  424. (((uint32_t) scsiDev.cdb[2]) << 24) +
  425. (((uint32_t) scsiDev.cdb[3]) << 16) +
  426. (((uint32_t) scsiDev.cdb[4]) << 8) +
  427. scsiDev.cdb[5];
  428. doSeek(lba);
  429. }
  430. else if (unlikely(command == 0x36))
  431. {
  432. // LOCK UNLOCK CACHE
  433. // We don't have a cache to lock data into. do nothing.
  434. }
  435. else if (unlikely(command == 0x34))
  436. {
  437. // PRE-FETCH.
  438. // We don't have a cache to pre-fetch into. do nothing.
  439. }
  440. else if (unlikely(command == 0x1E))
  441. {
  442. // PREVENT ALLOW MEDIUM REMOVAL
  443. // Not much we can do to prevent the user removing the SD card.
  444. // do nothing.
  445. }
  446. else if (unlikely(command == 0x01))
  447. {
  448. // REZERO UNIT
  449. // Set the lun to a vendor-specific state. Ignore.
  450. }
  451. else if (unlikely(command == 0x35))
  452. {
  453. // SYNCHRONIZE CACHE
  454. // We don't have a cache. do nothing.
  455. }
  456. else if (unlikely(command == 0x2F))
  457. {
  458. // VERIFY
  459. // TODO: When they supply data to verify, we should read the data and
  460. // verify it. If they don't supply any data, just say success.
  461. if ((scsiDev.cdb[1] & 0x02) == 0)
  462. {
  463. // They are asking us to do a medium verification with no data
  464. // comparison. Assume success, do nothing.
  465. }
  466. else
  467. {
  468. // TODO. This means they are supplying data to verify against.
  469. // Technically we should probably grab the data and compare it.
  470. scsiDev.status = CHECK_CONDITION;
  471. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  472. scsiDev.target->sense.asc = INVALID_FIELD_IN_CDB;
  473. scsiDev.phase = STATUS;
  474. }
  475. }
  476. else if (unlikely(command == 0x37))
  477. {
  478. // READ DEFECT DATA
  479. uint32_t allocLength = (((uint16_t)scsiDev.cdb[7]) << 8) |
  480. scsiDev.cdb[8];
  481. scsiDev.data[0] = 0;
  482. scsiDev.data[1] = scsiDev.cdb[1];
  483. scsiDev.data[2] = 0;
  484. scsiDev.data[3] = 0;
  485. scsiDev.dataLen = 4;
  486. if (scsiDev.dataLen > allocLength)
  487. {
  488. scsiDev.dataLen = allocLength;
  489. }
  490. scsiDev.phase = DATA_IN;
  491. }
  492. else
  493. {
  494. commandHandled = 0;
  495. }
  496. return commandHandled;
  497. }
  498. static uint32_t
  499. calcReadahead(uint32_t totalBytes, uint32_t sdSpeedKBs, uint32_t scsiSpeedKBs)
  500. {
  501. if (!(scsiDev.boardCfg.flags6 & S2S_CFG_ENABLE_BLIND_WRITES) ||
  502. (scsiSpeedKBs == 0) ||
  503. (scsiDev.hostSpeedMeasured == 0))
  504. {
  505. return totalBytes;
  506. }
  507. // uint32_t readAheadBytes = totalBytes * (1 - scsiSpeedKBs / sdSpeedKBs);
  508. // Won't overflow with 65536 max bytes, 20000 max scsi speed.
  509. uint32_t readAheadBytes = totalBytes - totalBytes * scsiSpeedKBs / sdSpeedKBs;
  510. // Round up to nearest FIFO size (* 4 for safety)
  511. readAheadBytes = ((readAheadBytes / SCSI_FIFO_DEPTH) + 4) * SCSI_FIFO_DEPTH;
  512. if (readAheadBytes > totalBytes)
  513. {
  514. readAheadBytes = totalBytes;
  515. }
  516. return readAheadBytes;
  517. }
  518. void scsiDiskPoll()
  519. {
  520. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  521. if (scsiDev.phase == DATA_IN &&
  522. transfer.currentBlock != transfer.blocks)
  523. {
  524. // Take responsibility for waiting for the phase delays
  525. uint32_t phaseChangeDelayUs = scsiEnterPhaseImmediate(DATA_IN);
  526. int totalSDSectors =
  527. transfer.blocks * SDSectorsPerSCSISector(bytesPerSector);
  528. uint32_t sdLBA =
  529. SCSISector2SD(
  530. scsiDev.target->cfg->sdSectorStart,
  531. bytesPerSector,
  532. transfer.lba);
  533. const int sdPerScsi = SDSectorsPerSCSISector(bytesPerSector);
  534. const int buffers = sizeof(scsiDev.data) / SD_SECTOR_SIZE;
  535. int prep = 0;
  536. int i = 0;
  537. int scsiActive __attribute__((unused)) = 0; // unused if DMA disabled
  538. int sdActive = 0;
  539. // It's highly unlikely that someone is going to use huge transfers
  540. // per scsi command, but if they do it'll be slower than usual.
  541. uint32_t totalScsiBytes = transfer.blocks * bytesPerSector;
  542. int useSlowDataCount = totalScsiBytes >= SCSI_XFER_MAX;
  543. if (!useSlowDataCount)
  544. {
  545. scsiSetDataCount(totalScsiBytes);
  546. }
  547. while ((i < totalSDSectors) &&
  548. likely(scsiDev.phase == DATA_IN) &&
  549. likely(!scsiDev.resetFlag))
  550. {
  551. int completedDmaSectors;
  552. if (sdActive && (completedDmaSectors = sdReadDMAPoll(sdActive)))
  553. {
  554. prep += completedDmaSectors;
  555. sdActive -= completedDmaSectors;
  556. } else if (sdActive > 1)
  557. {
  558. if ((scsiDev.data[SD_SECTOR_SIZE * (prep % buffers) + 510] != 0xAA) ||
  559. (scsiDev.data[SD_SECTOR_SIZE * (prep % buffers) + 511] != 0x33))
  560. {
  561. prep += 1;
  562. sdActive -= 1;
  563. }
  564. }
  565. if (!sdActive &&
  566. (prep - i < buffers) &&
  567. (prep < totalSDSectors) &&
  568. ((totalSDSectors - prep) >= sdPerScsi) &&
  569. (likely(!useSlowDataCount) || scsiPhyComplete()))
  570. {
  571. // Start an SD transfer if we have space.
  572. uint32_t startBuffer = prep % buffers;
  573. uint32_t sectors = totalSDSectors - prep;
  574. uint32_t freeBuffers = buffers - (prep - i);
  575. uint32_t contiguousBuffers = buffers - startBuffer;
  576. freeBuffers = freeBuffers < contiguousBuffers
  577. ? freeBuffers : contiguousBuffers;
  578. sectors = sectors < freeBuffers ? sectors : freeBuffers;
  579. if (sectors > 128) sectors = 128; // 65536 DMA limit !!
  580. // Round-down when we have odd sector sizes.
  581. if (sdPerScsi != 1)
  582. {
  583. sectors = (sectors / sdPerScsi) * sdPerScsi;
  584. }
  585. for (int dodgy = 0; dodgy < sectors; dodgy++)
  586. {
  587. scsiDev.data[SD_SECTOR_SIZE * (startBuffer + dodgy) + 510] = 0xAA;
  588. scsiDev.data[SD_SECTOR_SIZE * (startBuffer + dodgy) + 511] = 0x33;
  589. }
  590. sdReadDMA(sdLBA + prep, sectors, &scsiDev.data[SD_SECTOR_SIZE * startBuffer]);
  591. sdActive = sectors;
  592. if (useSlowDataCount)
  593. {
  594. scsiSetDataCount((sectors / sdPerScsi) * bytesPerSector);
  595. }
  596. // Wait now that the SD card is busy
  597. // Chances are we've probably already waited sufficient time,
  598. // but it's hard to measure microseconds cheaply. So just wait
  599. // extra just-in-case. Hopefully it's in parallel with dma.
  600. if (phaseChangeDelayUs > 0)
  601. {
  602. s2s_delay_us(phaseChangeDelayUs);
  603. phaseChangeDelayUs = 0;
  604. }
  605. }
  606. if ((prep - i) > 0)
  607. {
  608. int dmaBytes = SD_SECTOR_SIZE;
  609. if ((i % sdPerScsi) == (sdPerScsi - 1))
  610. {
  611. dmaBytes = bytesPerSector % SD_SECTOR_SIZE;
  612. if (dmaBytes == 0) dmaBytes = SD_SECTOR_SIZE;
  613. }
  614. uint8_t* scsiDmaData = &(scsiDev.data[SD_SECTOR_SIZE * (i % buffers)]);
  615. scsiWritePIO(scsiDmaData, dmaBytes);
  616. ++i;
  617. }
  618. }
  619. if (phaseChangeDelayUs > 0 && !scsiDev.resetFlag) // zero bytes ?
  620. {
  621. s2s_delay_us(phaseChangeDelayUs);
  622. phaseChangeDelayUs = 0;
  623. }
  624. // We've finished transferring the data to the FPGA, now wait until it's
  625. // written to he SCSI bus.
  626. __disable_irq();
  627. while (!scsiPhyComplete() &&
  628. likely(scsiDev.phase == DATA_IN) &&
  629. likely(!scsiDev.resetFlag))
  630. {
  631. __WFI();
  632. }
  633. __enable_irq();
  634. if (scsiDev.phase == DATA_IN)
  635. {
  636. scsiDev.phase = STATUS;
  637. }
  638. scsiDiskReset();
  639. }
  640. else if (scsiDev.phase == DATA_OUT &&
  641. transfer.currentBlock != transfer.blocks)
  642. {
  643. scsiEnterPhase(DATA_OUT);
  644. const int sdPerScsi = SDSectorsPerSCSISector(bytesPerSector);
  645. int totalSDSectors = transfer.blocks * sdPerScsi;
  646. uint32_t sdLBA =
  647. SCSISector2SD(
  648. scsiDev.target->cfg->sdSectorStart,
  649. bytesPerSector,
  650. transfer.lba);
  651. int i = 0;
  652. int clearBSY = 0;
  653. int parityError = 0;
  654. int enableParity = scsiDev.boardCfg.flags & S2S_CFG_ENABLE_PARITY;
  655. uint32_t maxSectors = sizeof(scsiDev.data) / SD_SECTOR_SIZE;
  656. static_assert(SCSI_XFER_MAX >= sizeof(scsiDev.data), "Assumes SCSI_XFER_MAX >= sizeof(scsiDev.data)");
  657. // Start reading and filling fifos as soon as possible.
  658. // It's highly unlikely that someone is going to use huge transfers
  659. // per scsi command, but if they do it'll be slower than usual.
  660. // Note: Happens in Macintosh FWB HDD Toolkit benchmarks which default
  661. // to 768kb
  662. uint32_t totalTransferBytes = transfer.blocks * bytesPerSector;
  663. int useSlowDataCount = totalTransferBytes >= SCSI_XFER_MAX;
  664. if (!useSlowDataCount)
  665. {
  666. DWT->CYCCNT = 0; // Start counting cycles
  667. scsiSetDataCount(totalTransferBytes);
  668. }
  669. while ((i < totalSDSectors) &&
  670. likely(scsiDev.phase == DATA_OUT) &&
  671. likely(!scsiDev.resetFlag))
  672. // KEEP GOING to ensure FIFOs are in a good state.
  673. // likely(!parityError || !enableParity))
  674. {
  675. uint32_t rem = totalSDSectors - i;
  676. uint32_t sectors = rem < maxSectors ? rem : maxSectors;
  677. if (bytesPerSector == SD_SECTOR_SIZE)
  678. {
  679. // We assume the SD card is faster than the SCSI interface, but has
  680. // no flow control. This can be handled if a) the scsi interface
  681. // doesn't block and b) we read enough SCSI sectors first so that
  682. // the SD interface cannot catch up.
  683. uint32_t totalBytes = sectors * SD_SECTOR_SIZE;
  684. uint32_t sdSpeedKBs = s2s_getSdRateKBs() + (scsiDev.sdUnderrunCount * 256);
  685. uint32_t readAheadBytes = calcReadahead(
  686. totalBytes,
  687. sdSpeedKBs,
  688. scsiDev.hostSpeedKBs);
  689. if (useSlowDataCount)
  690. {
  691. DWT->CYCCNT = 0; // Start counting cycles
  692. scsiSetDataCount(totalBytes);
  693. }
  694. uint32_t scsiBytesRead = 0;
  695. if (readAheadBytes > 0)
  696. {
  697. scsiReadPIO(
  698. &scsiDev.data[scsiBytesRead],
  699. readAheadBytes,
  700. &parityError);
  701. scsiBytesRead += readAheadBytes;
  702. if (i == 0 && !useSlowDataCount)
  703. {
  704. uint32_t elapsedCycles = DWT->CYCCNT;
  705. // uint32_t rateKBs = (readAheadBytes / 1000) / (elapsedCycles / HAL_RCC_GetHCLKFreq());
  706. // Scaled by 4 to avoid overflow w/ max 65536 at 108MHz.
  707. uint32_t rateKBs = ((readAheadBytes / 4) * (HAL_RCC_GetHCLKFreq() / 1000) / elapsedCycles) * 4;
  708. scsiDev.hostSpeedKBs = (scsiDev.hostSpeedKBs + rateKBs) / 2;
  709. scsiDev.hostSpeedMeasured = 1;
  710. if (rateKBs < scsiDev.hostSpeedKBs)
  711. {
  712. // Our readahead was too slow; assume remaining bytes
  713. // will be as well.
  714. if (readAheadBytes < totalBytes)
  715. {
  716. uint32_t properReadahead = calcReadahead(
  717. totalBytes,
  718. sdSpeedKBs,
  719. rateKBs);
  720. if (properReadahead > readAheadBytes)
  721. {
  722. uint32_t diff = properReadahead - readAheadBytes;
  723. readAheadBytes = properReadahead;
  724. scsiReadPIO(
  725. &scsiDev.data[scsiBytesRead],
  726. diff,
  727. &parityError);
  728. scsiBytesRead += diff;
  729. }
  730. }
  731. }
  732. }
  733. }
  734. HAL_SD_WriteBlocks_DMA(&hsd, (uint32_t*) (&scsiDev.data[0]), (i + sdLBA) * 512ll, SD_SECTOR_SIZE, sectors);
  735. int underrun = 0;
  736. if (scsiBytesRead < totalBytes && !scsiDev.resetFlag)
  737. {
  738. scsiReadPIO(
  739. &scsiDev.data[scsiBytesRead],
  740. totalBytes - readAheadBytes,
  741. &parityError);
  742. // Oh dear, SD finished first.
  743. underrun = hsd.DmaTransferCplt;
  744. scsiBytesRead += (totalBytes - readAheadBytes);
  745. }
  746. uint32_t dmaFinishTime = s2s_getTime_ms();
  747. while ((!hsd.SdTransferCplt ||
  748. __HAL_SD_SDIO_GET_FLAG(&hsd, SDIO_FLAG_TXACT)) &&
  749. s2s_elapsedTime_ms(dmaFinishTime) < 180)
  750. {
  751. // Wait while keeping BSY.
  752. }
  753. if (i + sectors >= totalSDSectors &&
  754. !underrun &&
  755. (!parityError || !enableParity))
  756. {
  757. // We're transferring over the SCSI bus faster than the SD card
  758. // can write. All data is buffered, and we're just waiting for
  759. // the SD card to complete. The host won't let us disconnect.
  760. // Some drivers set a 250ms timeout on transfers to complete.
  761. // SD card writes are supposed to complete
  762. // within 200ms, but sometimes they don't.
  763. // Just pretend we're finished.
  764. process_Status();
  765. clearBSY = process_MessageIn(0); // Will go to BUS_FREE state but keep BSY asserted.
  766. }
  767. HAL_SD_CheckWriteOperation(&hsd, (uint32_t)SD_DATATIMEOUT);
  768. if (underrun && (!parityError || !enableParity))
  769. {
  770. // Try again. Data is still in memory.
  771. sdTmpWrite(&scsiDev.data[0], i + sdLBA, sectors);
  772. scsiDev.sdUnderrunCount++;
  773. }
  774. i += sectors;
  775. }
  776. else
  777. {
  778. // Well, until we have some proper non-blocking SD code, we must
  779. // do this in a half-duplex fashion. We need to write as much as
  780. // possible in each SD card transaction.
  781. // use sg_dd from sg_utils3 tools to test.
  782. if (useSlowDataCount)
  783. {
  784. scsiSetDataCount(sectors * bytesPerSector);
  785. }
  786. for (int scsiSector = i; scsiSector < i + sectors; ++scsiSector)
  787. {
  788. int dmaBytes = SD_SECTOR_SIZE;
  789. if ((scsiSector % sdPerScsi) == (sdPerScsi - 1))
  790. {
  791. dmaBytes = bytesPerSector % SD_SECTOR_SIZE;
  792. if (dmaBytes == 0) dmaBytes = SD_SECTOR_SIZE;
  793. }
  794. scsiReadPIO(&scsiDev.data[SD_SECTOR_SIZE * (scsiSector - i)], dmaBytes, &parityError);
  795. }
  796. if (!parityError || !enableParity)
  797. {
  798. sdTmpWrite(&scsiDev.data[0], i + sdLBA, sectors);
  799. }
  800. i += sectors;
  801. }
  802. }
  803. // Should already be complete here as we've ready the FIFOs
  804. // by now. Check anyway.
  805. __disable_irq();
  806. while (!scsiPhyComplete() && likely(!scsiDev.resetFlag))
  807. {
  808. __WFI();
  809. }
  810. __enable_irq();
  811. if (clearBSY)
  812. {
  813. enter_BusFree();
  814. }
  815. if (scsiDev.phase == DATA_OUT)
  816. {
  817. if (parityError &&
  818. (scsiDev.boardCfg.flags & S2S_CFG_ENABLE_PARITY))
  819. {
  820. scsiDev.target->sense.code = ABORTED_COMMAND;
  821. scsiDev.target->sense.asc = SCSI_PARITY_ERROR;
  822. scsiDev.status = CHECK_CONDITION;;
  823. }
  824. scsiDev.phase = STATUS;
  825. }
  826. scsiDiskReset();
  827. }
  828. }
  829. void scsiDiskReset()
  830. {
  831. scsiDev.dataPtr = 0;
  832. scsiDev.savedDataPtr = 0;
  833. scsiDev.dataLen = 0;
  834. // transfer.lba = 0; // Needed in Request Sense to determine failure
  835. transfer.blocks = 0;
  836. transfer.currentBlock = 0;
  837. // Cancel long running commands!
  838. #if 0
  839. if (
  840. ((scsiDev.boardCfg.flags & S2S_CFG_ENABLE_CACHE) == 0) ||
  841. (transfer.multiBlock == 0)
  842. )
  843. #endif
  844. {
  845. sdCompleteTransfer();
  846. }
  847. transfer.multiBlock = 0;
  848. }
  849. void scsiDiskInit()
  850. {
  851. scsiDiskReset();
  852. // Don't require the host to send us a START STOP UNIT command
  853. blockDev.state = DISK_STARTED;
  854. }