disk.c 25 KB

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