disk.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  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. else
  263. {
  264. s2s_delay_ms(10);
  265. }
  266. }
  267. static int doTestUnitReady()
  268. {
  269. int ready = 1;
  270. if (likely(blockDev.state == (DISK_STARTED | DISK_PRESENT | DISK_INITIALISED)))
  271. {
  272. // nothing to do.
  273. }
  274. else if (unlikely(!(blockDev.state & DISK_STARTED)))
  275. {
  276. ready = 0;
  277. scsiDev.status = CHECK_CONDITION;
  278. scsiDev.target->sense.code = NOT_READY;
  279. scsiDev.target->sense.asc = LOGICAL_UNIT_NOT_READY_INITIALIZING_COMMAND_REQUIRED;
  280. scsiDev.phase = STATUS;
  281. }
  282. else if (unlikely(!(blockDev.state & DISK_PRESENT)))
  283. {
  284. ready = 0;
  285. scsiDev.status = CHECK_CONDITION;
  286. scsiDev.target->sense.code = NOT_READY;
  287. scsiDev.target->sense.asc = MEDIUM_NOT_PRESENT;
  288. scsiDev.phase = STATUS;
  289. }
  290. else if (unlikely(!(blockDev.state & DISK_INITIALISED)))
  291. {
  292. ready = 0;
  293. scsiDev.status = CHECK_CONDITION;
  294. scsiDev.target->sense.code = NOT_READY;
  295. scsiDev.target->sense.asc = LOGICAL_UNIT_NOT_READY_CAUSE_NOT_REPORTABLE;
  296. scsiDev.phase = STATUS;
  297. }
  298. return ready;
  299. }
  300. // Handle direct-access scsi device commands
  301. int scsiDiskCommand()
  302. {
  303. int commandHandled = 1;
  304. uint8_t command = scsiDev.cdb[0];
  305. if (unlikely(command == 0x1B))
  306. {
  307. // START STOP UNIT
  308. // Enable or disable media access operations.
  309. // Ignore load/eject requests. We can't do that.
  310. //int immed = scsiDev.cdb[1] & 1;
  311. int start = scsiDev.cdb[4] & 1;
  312. if (start)
  313. {
  314. blockDev.state = blockDev.state | DISK_STARTED;
  315. if (!(blockDev.state & DISK_INITIALISED))
  316. {
  317. doSdInit();
  318. }
  319. }
  320. else
  321. {
  322. blockDev.state &= ~DISK_STARTED;
  323. }
  324. }
  325. else if (unlikely(command == 0x00))
  326. {
  327. // TEST UNIT READY
  328. doTestUnitReady();
  329. }
  330. else if (unlikely(!doTestUnitReady()))
  331. {
  332. // Status and sense codes already set by doTestUnitReady
  333. }
  334. else if (likely(command == 0x08))
  335. {
  336. // READ(6)
  337. uint32_t lba =
  338. (((uint32_t) scsiDev.cdb[1] & 0x1F) << 16) +
  339. (((uint32_t) scsiDev.cdb[2]) << 8) +
  340. scsiDev.cdb[3];
  341. uint32_t blocks = scsiDev.cdb[4];
  342. if (unlikely(blocks == 0)) blocks = 256;
  343. doRead(lba, blocks);
  344. }
  345. else if (likely(command == 0x28))
  346. {
  347. // READ(10)
  348. // Ignore all cache control bits - we don't support a memory cache.
  349. uint32_t lba =
  350. (((uint32_t) scsiDev.cdb[2]) << 24) +
  351. (((uint32_t) scsiDev.cdb[3]) << 16) +
  352. (((uint32_t) scsiDev.cdb[4]) << 8) +
  353. scsiDev.cdb[5];
  354. uint32_t blocks =
  355. (((uint32_t) scsiDev.cdb[7]) << 8) +
  356. scsiDev.cdb[8];
  357. doRead(lba, blocks);
  358. }
  359. else if (likely(command == 0x0A))
  360. {
  361. // WRITE(6)
  362. uint32_t lba =
  363. (((uint32_t) scsiDev.cdb[1] & 0x1F) << 16) +
  364. (((uint32_t) scsiDev.cdb[2]) << 8) +
  365. scsiDev.cdb[3];
  366. uint32_t blocks = scsiDev.cdb[4];
  367. if (unlikely(blocks == 0)) blocks = 256;
  368. doWrite(lba, blocks);
  369. }
  370. else if (likely(command == 0x2A) || // WRITE(10)
  371. unlikely(command == 0x2E)) // WRITE AND VERIFY
  372. {
  373. // Ignore all cache control bits - we don't support a memory cache.
  374. // Don't bother verifying either. The SD card likely stores ECC
  375. // along with each flash row.
  376. uint32_t lba =
  377. (((uint32_t) scsiDev.cdb[2]) << 24) +
  378. (((uint32_t) scsiDev.cdb[3]) << 16) +
  379. (((uint32_t) scsiDev.cdb[4]) << 8) +
  380. scsiDev.cdb[5];
  381. uint32_t blocks =
  382. (((uint32_t) scsiDev.cdb[7]) << 8) +
  383. scsiDev.cdb[8];
  384. doWrite(lba, blocks);
  385. }
  386. else if (unlikely(command == 0x04))
  387. {
  388. // FORMAT UNIT
  389. // We don't really do any formatting, but we need to read the correct
  390. // number of bytes in the DATA_OUT phase to make the SCSI host happy.
  391. int fmtData = (scsiDev.cdb[1] & 0x10) ? 1 : 0;
  392. if (fmtData)
  393. {
  394. // We need to read the parameter list, but we don't know how
  395. // big it is yet. Start with the header.
  396. scsiDev.dataLen = 4;
  397. scsiDev.phase = DATA_OUT;
  398. scsiDev.postDataOutHook = doFormatUnitHeader;
  399. }
  400. else
  401. {
  402. // No data to read, we're already finished!
  403. }
  404. }
  405. else if (unlikely(command == 0x25))
  406. {
  407. // READ CAPACITY
  408. doReadCapacity();
  409. }
  410. else if (unlikely(command == 0x0B))
  411. {
  412. // SEEK(6)
  413. uint32_t lba =
  414. (((uint32_t) scsiDev.cdb[1] & 0x1F) << 16) +
  415. (((uint32_t) scsiDev.cdb[2]) << 8) +
  416. scsiDev.cdb[3];
  417. doSeek(lba);
  418. }
  419. else if (unlikely(command == 0x2B))
  420. {
  421. // SEEK(10)
  422. uint32_t lba =
  423. (((uint32_t) scsiDev.cdb[2]) << 24) +
  424. (((uint32_t) scsiDev.cdb[3]) << 16) +
  425. (((uint32_t) scsiDev.cdb[4]) << 8) +
  426. scsiDev.cdb[5];
  427. doSeek(lba);
  428. }
  429. else if (unlikely(command == 0x36))
  430. {
  431. // LOCK UNLOCK CACHE
  432. // We don't have a cache to lock data into. do nothing.
  433. }
  434. else if (unlikely(command == 0x34))
  435. {
  436. // PRE-FETCH.
  437. // We don't have a cache to pre-fetch into. do nothing.
  438. }
  439. else if (unlikely(command == 0x1E))
  440. {
  441. // PREVENT ALLOW MEDIUM REMOVAL
  442. // Not much we can do to prevent the user removing the SD card.
  443. // do nothing.
  444. }
  445. else if (unlikely(command == 0x01))
  446. {
  447. // REZERO UNIT
  448. // Set the lun to a vendor-specific state. Ignore.
  449. }
  450. else if (unlikely(command == 0x35))
  451. {
  452. // SYNCHRONIZE CACHE
  453. // We don't have a cache. do nothing.
  454. }
  455. else if (unlikely(command == 0x2F))
  456. {
  457. // VERIFY
  458. // TODO: When they supply data to verify, we should read the data and
  459. // verify it. If they don't supply any data, just say success.
  460. if ((scsiDev.cdb[1] & 0x02) == 0)
  461. {
  462. // They are asking us to do a medium verification with no data
  463. // comparison. Assume success, do nothing.
  464. }
  465. else
  466. {
  467. // TODO. This means they are supplying data to verify against.
  468. // Technically we should probably grab the data and compare it.
  469. scsiDev.status = CHECK_CONDITION;
  470. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  471. scsiDev.target->sense.asc = INVALID_FIELD_IN_CDB;
  472. scsiDev.phase = STATUS;
  473. }
  474. }
  475. else if (unlikely(command == 0x37))
  476. {
  477. // READ DEFECT DATA
  478. scsiDev.status = CHECK_CONDITION;
  479. scsiDev.target->sense.code = NO_SENSE;
  480. scsiDev.target->sense.asc = DEFECT_LIST_NOT_FOUND;
  481. scsiDev.phase = STATUS;
  482. }
  483. else
  484. {
  485. commandHandled = 0;
  486. }
  487. return commandHandled;
  488. }
  489. void scsiDiskPoll()
  490. {
  491. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  492. if (scsiDev.phase == DATA_IN &&
  493. transfer.currentBlock != transfer.blocks)
  494. {
  495. int totalSDSectors =
  496. transfer.blocks * SDSectorsPerSCSISector(bytesPerSector);
  497. uint32_t sdLBA =
  498. SCSISector2SD(
  499. scsiDev.target->cfg->sdSectorStart,
  500. bytesPerSector,
  501. transfer.lba);
  502. const int sdPerScsi = SDSectorsPerSCSISector(bytesPerSector);
  503. const int buffers = sizeof(scsiDev.data) / SD_SECTOR_SIZE;
  504. int prep = 0;
  505. int i = 0;
  506. int scsiActive __attribute__((unused)) = 0; // unused if DMA disabled
  507. int sdActive = 0;
  508. uint32_t partialScsiChunk = 0;
  509. // Start reading from the SD card FIRST, because we change state and
  510. // wai for SCSI signals
  511. int dataInStarted = 0;
  512. while ((i < totalSDSectors) &&
  513. (!dataInStarted || likely(scsiDev.phase == DATA_IN)) &&
  514. likely(!scsiDev.resetFlag))
  515. {
  516. int completedDmaSectors;
  517. if (sdActive && (completedDmaSectors = sdReadDMAPoll(sdActive)))
  518. {
  519. prep += completedDmaSectors;
  520. sdActive -= completedDmaSectors;
  521. } else if (sdActive > 1)
  522. {
  523. if ((scsiDev.data[SD_SECTOR_SIZE * (prep % buffers) + 510] != 0xAA) ||
  524. (scsiDev.data[SD_SECTOR_SIZE * (prep % buffers) + 511] != 0x33))
  525. {
  526. prep += 1;
  527. sdActive -= 1;
  528. }
  529. }
  530. if (!sdActive &&
  531. (prep - i < buffers) &&
  532. (prep < totalSDSectors))
  533. {
  534. // Start an SD transfer if we have space.
  535. uint32_t startBuffer = prep % buffers;
  536. uint32_t sectors = totalSDSectors - prep;
  537. uint32_t freeBuffers = buffers - (prep - i);
  538. uint32_t contiguousBuffers = buffers - startBuffer;
  539. freeBuffers = freeBuffers < contiguousBuffers
  540. ? freeBuffers : contiguousBuffers;
  541. sectors = sectors < freeBuffers ? sectors : freeBuffers;
  542. if (sectors > 128) sectors = 128; // 65536 DMA limit !!
  543. for (int dodgy = 0; dodgy < sectors; dodgy++)
  544. {
  545. scsiDev.data[SD_SECTOR_SIZE * (startBuffer + dodgy) + 510] = 0xAA;
  546. scsiDev.data[SD_SECTOR_SIZE * (startBuffer + dodgy) + 511] = 0x33;
  547. }
  548. sdReadDMA(sdLBA + prep, sectors, &scsiDev.data[SD_SECTOR_SIZE * startBuffer]);
  549. sdActive = sectors;
  550. if (!dataInStarted)
  551. {
  552. dataInStarted = 1;
  553. scsiEnterPhase(DATA_IN); // Will wait a few microseconds.
  554. }
  555. }
  556. #ifdef SCSI_FSMC_DMA
  557. #error this code not updated for 256 max bytes in scsi fifo
  558. if (scsiActive && scsiPhyComplete() && scsiWriteDMAPoll())
  559. {
  560. scsiActive = 0;
  561. i++;
  562. scsiPhyFifoFlip();
  563. }
  564. if (!scsiActive && ((prep - i) > 0))
  565. {
  566. int dmaBytes = SD_SECTOR_SIZE;
  567. if ((i % sdPerScsi) == (sdPerScsi - 1))
  568. {
  569. dmaBytes = bytesPerSector % SD_SECTOR_SIZE;
  570. if (dmaBytes == 0) dmaBytes = SD_SECTOR_SIZE;
  571. }
  572. scsiWriteDMA(&scsiDev.data[SD_SECTOR_SIZE * (i % buffers)], dmaBytes);
  573. scsiActive = 1;
  574. }
  575. #else
  576. if ((prep - i) > 0)
  577. {
  578. int dmaBytes = SD_SECTOR_SIZE;
  579. if ((i % sdPerScsi) == (sdPerScsi - 1))
  580. {
  581. dmaBytes = bytesPerSector % SD_SECTOR_SIZE;
  582. if (dmaBytes == 0) dmaBytes = SD_SECTOR_SIZE;
  583. }
  584. // Manually unrolled loop for performance.
  585. // -Os won't unroll this for us automatically,
  586. // especially since scsiPhyTx does volatile stuff.
  587. // Reduces bus utilisation by making the fsmc split
  588. // 32bits into 2 16 bit writes.
  589. uint16_t* scsiDmaData = (uint16_t*) &(scsiDev.data[SD_SECTOR_SIZE * (i % buffers) + partialScsiChunk]);
  590. uint32_t chunk = ((dmaBytes - partialScsiChunk) > SCSI_FIFO_DEPTH)
  591. ? SCSI_FIFO_DEPTH : (dmaBytes - partialScsiChunk);
  592. int k = 0;
  593. for (; k + 4 < (chunk + 1) / 2; k += 4)
  594. {
  595. scsiPhyTx32(scsiDmaData[k], scsiDmaData[k+1]);
  596. scsiPhyTx32(scsiDmaData[k+2], scsiDmaData[k+3]);
  597. }
  598. for (; k < (chunk + 1) / 2; ++k)
  599. {
  600. scsiPhyTx(scsiDmaData[k]);
  601. }
  602. while (!scsiPhyComplete() && !scsiDev.resetFlag)
  603. {
  604. __WFE(); // Wait for event
  605. }
  606. scsiPhyFifoFlip();
  607. scsiSetDataCount(chunk);
  608. partialScsiChunk += chunk;
  609. if (partialScsiChunk == dmaBytes)
  610. {
  611. partialScsiChunk = 0;
  612. ++i;
  613. }
  614. }
  615. #endif
  616. }
  617. if (!dataInStarted && !scsiDev.resetFlag) // zero bytes ?
  618. {
  619. scsiEnterPhase(DATA_IN); // Will wait a few microseconds.
  620. }
  621. // We've finished transferring the data to the FPGA, now wait until it's
  622. // written to he SCSI bus.
  623. while (!scsiPhyComplete() &&
  624. likely(scsiDev.phase == DATA_IN) &&
  625. likely(!scsiDev.resetFlag))
  626. {
  627. __WFE(); // Wait for event
  628. }
  629. if (scsiDev.phase == DATA_IN)
  630. {
  631. scsiDev.phase = STATUS;
  632. }
  633. scsiDiskReset();
  634. }
  635. else if (scsiDev.phase == DATA_OUT &&
  636. transfer.currentBlock != transfer.blocks)
  637. {
  638. scsiEnterPhase(DATA_OUT);
  639. const int sdPerScsi = SDSectorsPerSCSISector(bytesPerSector);
  640. int totalSDSectors = transfer.blocks * sdPerScsi;
  641. uint32_t sdLBA =
  642. SCSISector2SD(
  643. scsiDev.target->cfg->sdSectorStart,
  644. bytesPerSector,
  645. transfer.lba);
  646. int i = 0;
  647. int clearBSY = 0;
  648. int parityError = 0;
  649. int enableParity = scsiDev.boardCfg.flags & S2S_CFG_ENABLE_PARITY;
  650. while ((i < totalSDSectors) &&
  651. likely(scsiDev.phase == DATA_OUT) &&
  652. likely(!scsiDev.resetFlag) &&
  653. likely(!parityError || !enableParity))
  654. {
  655. // Well, until we have some proper non-blocking SD code, we must
  656. // do this in a half-duplex fashion. We need to write as much as
  657. // possible in each SD card transaction.
  658. uint32_t maxSectors = sizeof(scsiDev.data) / SD_SECTOR_SIZE;
  659. uint32_t rem = totalSDSectors - i;
  660. uint32_t sectors =
  661. rem < maxSectors ? rem : maxSectors;
  662. if (bytesPerSector == SD_SECTOR_SIZE)
  663. {
  664. // We assume the SD card is faster than the SCSI interface, but has
  665. // no flow control. This can be handled if a) the scsi interface
  666. // doesn't block and b) we read enough SCSI sectors first so that
  667. // the SD interface cannot catch up.
  668. uint32_t totalBytes = sectors * SD_SECTOR_SIZE;
  669. uint32_t readAheadBytes = sectors * SD_SECTOR_SIZE;
  670. uint32_t sdSpeed = s2s_getSdRateMBs() + (scsiDev.sdUnderrunCount / 2);
  671. uint32_t scsiSpeed = s2s_getScsiRateMBs();
  672. // if (have blind writes)
  673. if (scsiSpeed > 0 && scsiDev.sdUnderrunCount < 16)
  674. {
  675. // readAhead = sectors * (sd / scsi - 1 + 0.1);
  676. readAheadBytes = totalBytes * sdSpeed / scsiSpeed - totalBytes + SCSI_FIFO_DEPTH;
  677. if (readAheadBytes < SCSI_FIFO_DEPTH)
  678. {
  679. readAheadBytes = SCSI_FIFO_DEPTH;
  680. }
  681. if (readAheadBytes > totalBytes)
  682. {
  683. readAheadBytes = totalBytes;
  684. }
  685. }
  686. uint32_t chunk = (readAheadBytes > SCSI_FIFO_DEPTH) ? SCSI_FIFO_DEPTH : readAheadBytes;
  687. scsiSetDataCount(chunk);
  688. uint32_t scsiBytesRead = 0;
  689. while (scsiBytesRead < readAheadBytes)
  690. {
  691. while (!scsiPhyComplete() && likely(!scsiDev.resetFlag))
  692. {
  693. __WFE(); // Wait for event
  694. }
  695. parityError |= scsiParityError();
  696. scsiPhyFifoFlip();
  697. uint32_t nextChunk = ((totalBytes - scsiBytesRead - chunk) > SCSI_FIFO_DEPTH)
  698. ? SCSI_FIFO_DEPTH : (totalBytes - scsiBytesRead - chunk);
  699. if (nextChunk > 0) scsiSetDataCount(nextChunk);
  700. scsiReadPIO(&scsiDev.data[scsiBytesRead], chunk);
  701. scsiBytesRead += chunk;
  702. chunk = nextChunk;
  703. }
  704. HAL_SD_WriteBlocks_DMA(&hsd, (uint32_t*) (&scsiDev.data[0]), (i + sdLBA) * 512ll, SD_SECTOR_SIZE, sectors);
  705. while (scsiBytesRead < totalBytes)
  706. {
  707. while (!scsiPhyComplete() && likely(!scsiDev.resetFlag))
  708. {
  709. __WFE(); // Wait for event
  710. }
  711. parityError |= scsiParityError();
  712. scsiPhyFifoFlip();
  713. uint32_t nextChunk = ((totalBytes - scsiBytesRead - chunk) > SCSI_FIFO_DEPTH)
  714. ? SCSI_FIFO_DEPTH : (totalBytes - scsiBytesRead - chunk);
  715. if (nextChunk > 0) scsiSetDataCount(nextChunk);
  716. scsiReadPIO(&scsiDev.data[scsiBytesRead], chunk);
  717. scsiBytesRead += chunk;
  718. chunk = nextChunk;
  719. }
  720. // Oh dear, SD finished first.
  721. int underrun = totalBytes > readAheadBytes && hsd.DmaTransferCplt;
  722. uint32_t dmaFinishTime = s2s_getTime_ms();
  723. while (!hsd.SdTransferCplt &&
  724. s2s_elapsedTime_ms(dmaFinishTime) < 180)
  725. {
  726. // Wait while keeping BSY.
  727. }
  728. while((__HAL_SD_SDIO_GET_FLAG(&hsd, SDIO_FLAG_TXACT)) &&
  729. s2s_elapsedTime_ms(dmaFinishTime) < 180)
  730. {
  731. // Wait for SD card while keeping BSY.
  732. }
  733. if (i + sectors >= totalSDSectors &&
  734. !underrun &&
  735. (!parityError || !enableParity))
  736. {
  737. // We're transferring over the SCSI bus faster than the SD card
  738. // can write. All data is buffered, and we're just waiting for
  739. // the SD card to complete. The host won't let us disconnect.
  740. // Some drivers set a 250ms timeout on transfers to complete.
  741. // SD card writes are supposed to complete
  742. // within 200ms, but sometimes they don't.
  743. // Just pretend we're finished.
  744. process_Status();
  745. clearBSY = process_MessageIn(0); // Will go to BUS_FREE state but keep BSY asserted.
  746. }
  747. HAL_SD_CheckWriteOperation(&hsd, (uint32_t)SD_DATATIMEOUT);
  748. if (underrun)
  749. {
  750. // Try again. Data is still in memory.
  751. sdTmpWrite(&scsiDev.data[0], i + sdLBA, sectors);
  752. scsiDev.sdUnderrunCount++;
  753. }
  754. i += sectors;
  755. }
  756. else
  757. {
  758. // Well, until we have some proper non-blocking SD code, we must
  759. // do this in a half-duplex fashion. We need to write as much as
  760. // possible in each SD card transaction.
  761. // use sg_dd from sg_utils3 tools to test.
  762. uint32_t maxSectors = sizeof(scsiDev.data) / SD_SECTOR_SIZE;
  763. uint32_t rem = totalSDSectors - i;
  764. uint32_t sectors = rem < maxSectors ? rem : maxSectors;
  765. int scsiSector;
  766. for (scsiSector = i; scsiSector < i + sectors; ++scsiSector)
  767. {
  768. int dmaBytes = SD_SECTOR_SIZE;
  769. if ((scsiSector % sdPerScsi) == (sdPerScsi - 1))
  770. {
  771. dmaBytes = bytesPerSector % SD_SECTOR_SIZE;
  772. if (dmaBytes == 0) dmaBytes = SD_SECTOR_SIZE;
  773. }
  774. scsiRead(&scsiDev.data[SD_SECTOR_SIZE * (scsiSector - i)], dmaBytes, &parityError);
  775. }
  776. if (!parityError)
  777. {
  778. sdTmpWrite(&scsiDev.data[0], i + sdLBA, sectors);
  779. }
  780. i += sectors;
  781. }
  782. }
  783. if (clearBSY)
  784. {
  785. enter_BusFree();
  786. }
  787. if (scsiDev.phase == DATA_OUT)
  788. {
  789. if (parityError &&
  790. (scsiDev.boardCfg.flags & S2S_CFG_ENABLE_PARITY))
  791. {
  792. scsiDev.target->sense.code = ABORTED_COMMAND;
  793. scsiDev.target->sense.asc = SCSI_PARITY_ERROR;
  794. scsiDev.status = CHECK_CONDITION;;
  795. }
  796. scsiDev.phase = STATUS;
  797. }
  798. scsiDiskReset();
  799. }
  800. }
  801. void scsiDiskReset()
  802. {
  803. scsiDev.dataPtr = 0;
  804. scsiDev.savedDataPtr = 0;
  805. scsiDev.dataLen = 0;
  806. // transfer.lba = 0; // Needed in Request Sense to determine failure
  807. transfer.blocks = 0;
  808. transfer.currentBlock = 0;
  809. // Cancel long running commands!
  810. #if 0
  811. if (
  812. ((scsiDev.boardCfg.flags & S2S_CFG_ENABLE_CACHE) == 0) ||
  813. (transfer.multiBlock == 0)
  814. )
  815. #endif
  816. {
  817. sdCompleteTransfer();
  818. }
  819. transfer.multiBlock = 0;
  820. }
  821. void scsiDiskInit()
  822. {
  823. scsiDiskReset();
  824. // Don't require the host to send us a START STOP UNIT command
  825. blockDev.state = DISK_STARTED;
  826. }