disk.c 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  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. #ifdef STM32F2xx
  19. #include "stm32f2xx.h"
  20. #endif
  21. #ifdef STM32F4xx
  22. #include "stm32f4xx.h"
  23. #endif
  24. #include <assert.h>
  25. // For SD write direct routines
  26. #include "sdio.h"
  27. #include "bsp_driver_sd.h"
  28. #include "scsi.h"
  29. #include "scsiPhy.h"
  30. #include "config.h"
  31. #include "disk.h"
  32. #include "sd.h"
  33. #include "time.h"
  34. #include "bsp.h"
  35. #include <string.h>
  36. // Global
  37. BlockDevice blockDev;
  38. Transfer transfer;
  39. static int doSdInit()
  40. {
  41. int result = 0;
  42. if (blockDev.state & DISK_PRESENT)
  43. {
  44. blockDev.state = blockDev.state | DISK_INITIALISED;
  45. }
  46. return result;
  47. }
  48. // Callback once all data has been read in the data out phase.
  49. static void doFormatUnitComplete(void)
  50. {
  51. // TODO start writing the initialisation pattern to the SD
  52. // card
  53. scsiDev.phase = STATUS;
  54. }
  55. static void doFormatUnitSkipData(int bytes)
  56. {
  57. // We may not have enough memory to store the initialisation pattern and
  58. // defect list data. Since we're not making use of it yet anyway, just
  59. // discard the bytes.
  60. scsiEnterPhase(DATA_OUT);
  61. int i;
  62. for (i = 0; i < bytes; ++i)
  63. {
  64. scsiReadByte();
  65. }
  66. }
  67. // Callback from the data out phase.
  68. static void doFormatUnitPatternHeader(void)
  69. {
  70. int defectLength =
  71. ((((uint16_t)scsiDev.data[2])) << 8) +
  72. scsiDev.data[3];
  73. int patternLength =
  74. ((((uint16_t)scsiDev.data[4 + 2])) << 8) +
  75. scsiDev.data[4 + 3];
  76. doFormatUnitSkipData(defectLength + patternLength);
  77. doFormatUnitComplete();
  78. }
  79. // Callback from the data out phase.
  80. static void doFormatUnitHeader(void)
  81. {
  82. int IP = (scsiDev.data[1] & 0x08) ? 1 : 0;
  83. int DSP = (scsiDev.data[1] & 0x04) ? 1 : 0;
  84. if (! DSP) // disable save parameters
  85. {
  86. // Save the "MODE SELECT savable parameters"
  87. s2s_configSave(
  88. scsiDev.target->targetId,
  89. scsiDev.target->liveCfg.bytesPerSector);
  90. }
  91. if (IP)
  92. {
  93. // We need to read the initialisation pattern header first.
  94. scsiDev.dataLen += 4;
  95. scsiDev.phase = DATA_OUT;
  96. scsiDev.postDataOutHook = doFormatUnitPatternHeader;
  97. }
  98. else
  99. {
  100. // Read the defect list data
  101. int defectLength =
  102. ((((uint16_t)scsiDev.data[2])) << 8) +
  103. scsiDev.data[3];
  104. doFormatUnitSkipData(defectLength);
  105. doFormatUnitComplete();
  106. }
  107. }
  108. static void doReadCapacity()
  109. {
  110. uint32_t lba = (((uint32_t) scsiDev.cdb[2]) << 24) +
  111. (((uint32_t) scsiDev.cdb[3]) << 16) +
  112. (((uint32_t) scsiDev.cdb[4]) << 8) +
  113. scsiDev.cdb[5];
  114. int pmi = scsiDev.cdb[8] & 1;
  115. uint32_t capacity = getScsiCapacity(
  116. scsiDev.target->cfg->sdSectorStart,
  117. scsiDev.target->liveCfg.bytesPerSector,
  118. scsiDev.target->cfg->scsiSectors);
  119. if (!pmi && lba)
  120. {
  121. // error.
  122. // We don't do anything with the "partial medium indicator", and
  123. // assume that delays are constant across each block. But the spec
  124. // says we must return this error if pmi is specified incorrectly.
  125. scsiDev.status = CHECK_CONDITION;
  126. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  127. scsiDev.target->sense.asc = INVALID_FIELD_IN_CDB;
  128. scsiDev.phase = STATUS;
  129. }
  130. else if (capacity > 0)
  131. {
  132. uint32_t highestBlock = capacity - 1;
  133. scsiDev.data[0] = highestBlock >> 24;
  134. scsiDev.data[1] = highestBlock >> 16;
  135. scsiDev.data[2] = highestBlock >> 8;
  136. scsiDev.data[3] = highestBlock;
  137. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  138. scsiDev.data[4] = bytesPerSector >> 24;
  139. scsiDev.data[5] = bytesPerSector >> 16;
  140. scsiDev.data[6] = bytesPerSector >> 8;
  141. scsiDev.data[7] = bytesPerSector;
  142. scsiDev.dataLen = 8;
  143. scsiDev.phase = DATA_IN;
  144. }
  145. else
  146. {
  147. scsiDev.status = CHECK_CONDITION;
  148. scsiDev.target->sense.code = NOT_READY;
  149. scsiDev.target->sense.asc = MEDIUM_NOT_PRESENT;
  150. scsiDev.phase = STATUS;
  151. }
  152. }
  153. static void doWrite(uint32_t lba, uint32_t blocks)
  154. {
  155. if (unlikely(scsiDev.target->cfg->deviceType == S2S_CFG_FLOPPY_14MB)) {
  156. // Floppies are supposed to be slow. Some systems can't handle a floppy
  157. // without an access time
  158. s2s_delay_ms(10);
  159. }
  160. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  161. if (unlikely(blockDev.state & DISK_WP) ||
  162. unlikely(scsiDev.target->cfg->deviceType == S2S_CFG_OPTICAL))
  163. {
  164. scsiDev.status = CHECK_CONDITION;
  165. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  166. scsiDev.target->sense.asc = WRITE_PROTECTED;
  167. scsiDev.phase = STATUS;
  168. }
  169. else if (unlikely(((uint64_t) lba) + blocks >
  170. getScsiCapacity(
  171. scsiDev.target->cfg->sdSectorStart,
  172. bytesPerSector,
  173. scsiDev.target->cfg->scsiSectors
  174. )
  175. ))
  176. {
  177. scsiDev.status = CHECK_CONDITION;
  178. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  179. scsiDev.target->sense.asc = LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
  180. scsiDev.phase = STATUS;
  181. }
  182. else
  183. {
  184. transfer.lba = lba;
  185. transfer.blocks = blocks;
  186. transfer.currentBlock = 0;
  187. scsiDev.phase = DATA_OUT;
  188. scsiDev.dataLen = bytesPerSector;
  189. scsiDev.dataPtr = bytesPerSector;
  190. // No need for single-block writes atm. Overhead of the
  191. // multi-block write is minimal.
  192. transfer.multiBlock = 1;
  193. }
  194. }
  195. static void doRead(uint32_t lba, uint32_t blocks)
  196. {
  197. if (unlikely(scsiDev.target->cfg->deviceType == S2S_CFG_FLOPPY_14MB)) {
  198. // Floppies are supposed to be slow. Some systems can't handle a floppy
  199. // without an access time
  200. s2s_delay_ms(10);
  201. }
  202. uint32_t capacity = getScsiCapacity(
  203. scsiDev.target->cfg->sdSectorStart,
  204. scsiDev.target->liveCfg.bytesPerSector,
  205. scsiDev.target->cfg->scsiSectors);
  206. if (unlikely(((uint64_t) lba) + blocks > capacity))
  207. {
  208. scsiDev.status = CHECK_CONDITION;
  209. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  210. scsiDev.target->sense.asc = LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
  211. scsiDev.phase = STATUS;
  212. }
  213. else
  214. {
  215. transfer.lba = lba;
  216. transfer.blocks = blocks;
  217. transfer.currentBlock = 0;
  218. scsiDev.phase = DATA_IN;
  219. scsiDev.dataLen = 0; // No data yet
  220. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  221. uint32_t sdSectorPerSCSISector = SDSectorsPerSCSISector(bytesPerSector);
  222. uint32_t sdSectors =
  223. blocks * sdSectorPerSCSISector;
  224. if ((
  225. (sdSectors == 1) &&
  226. !(scsiDev.boardCfg.flags & S2S_CFG_ENABLE_CACHE)
  227. ) ||
  228. unlikely(((uint64_t) lba) + blocks == capacity)
  229. )
  230. {
  231. // We get errors on reading the last sector using a multi-sector
  232. // read :-(
  233. transfer.multiBlock = 0;
  234. }
  235. else
  236. {
  237. transfer.multiBlock = 1;
  238. // uint32_t sdLBA =
  239. // SCSISector2SD(
  240. // scsiDev.target->cfg->sdSectorStart,
  241. // bytesPerSector,
  242. // lba);
  243. // TODO sdReadMultiSectorPrep(sdLBA, sdSectors);
  244. }
  245. }
  246. }
  247. static void doSeek(uint32_t lba)
  248. {
  249. if (lba >=
  250. getScsiCapacity(
  251. scsiDev.target->cfg->sdSectorStart,
  252. scsiDev.target->liveCfg.bytesPerSector,
  253. scsiDev.target->cfg->scsiSectors)
  254. )
  255. {
  256. scsiDev.status = CHECK_CONDITION;
  257. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  258. scsiDev.target->sense.asc = LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
  259. scsiDev.phase = STATUS;
  260. }
  261. else
  262. {
  263. if (unlikely(scsiDev.target->cfg->deviceType == S2S_CFG_FLOPPY_14MB) ||
  264. scsiDev.compatMode < COMPAT_SCSI2)
  265. {
  266. s2s_delay_ms(10);
  267. }
  268. else
  269. {
  270. s2s_delay_us(10);
  271. }
  272. }
  273. }
  274. static int doTestUnitReady()
  275. {
  276. int ready = 1;
  277. if (likely(blockDev.state == (DISK_PRESENT | DISK_INITIALISED) &&
  278. scsiDev.target->started))
  279. {
  280. // nothing to do.
  281. }
  282. else if (unlikely(!scsiDev.target->started))
  283. {
  284. ready = 0;
  285. scsiDev.status = CHECK_CONDITION;
  286. scsiDev.target->sense.code = NOT_READY;
  287. scsiDev.target->sense.asc = LOGICAL_UNIT_NOT_READY_INITIALIZING_COMMAND_REQUIRED;
  288. scsiDev.phase = STATUS;
  289. }
  290. else if (unlikely(!(blockDev.state & DISK_PRESENT)))
  291. {
  292. ready = 0;
  293. scsiDev.status = CHECK_CONDITION;
  294. scsiDev.target->sense.code = NOT_READY;
  295. scsiDev.target->sense.asc = MEDIUM_NOT_PRESENT;
  296. scsiDev.phase = STATUS;
  297. }
  298. else if (unlikely(!(blockDev.state & DISK_INITIALISED)))
  299. {
  300. ready = 0;
  301. scsiDev.status = CHECK_CONDITION;
  302. scsiDev.target->sense.code = NOT_READY;
  303. scsiDev.target->sense.asc = LOGICAL_UNIT_NOT_READY_CAUSE_NOT_REPORTABLE;
  304. scsiDev.phase = STATUS;
  305. }
  306. return ready;
  307. }
  308. // Handle direct-access scsi device commands
  309. int scsiDiskCommand()
  310. {
  311. int commandHandled = 1;
  312. uint8_t command = scsiDev.cdb[0];
  313. if (unlikely(command == 0x1B))
  314. {
  315. // START STOP UNIT
  316. // Enable or disable media access operations.
  317. //int immed = scsiDev.cdb[1] & 1;
  318. int start = scsiDev.cdb[4] & 1;
  319. int loadEject = scsiDev.cdb[4] & 2;
  320. if (loadEject)
  321. {
  322. // Ignore load/eject requests. We can't do that.
  323. }
  324. else if (start)
  325. {
  326. scsiDev.target->started = 1;
  327. if (!(blockDev.state & DISK_INITIALISED))
  328. {
  329. doSdInit();
  330. }
  331. }
  332. else
  333. {
  334. scsiDev.target->started = 0;
  335. }
  336. }
  337. else if (unlikely(command == 0x00))
  338. {
  339. // TEST UNIT READY
  340. doTestUnitReady();
  341. }
  342. else if (unlikely(!doTestUnitReady()))
  343. {
  344. // Status and sense codes already set by doTestUnitReady
  345. }
  346. else if (likely(command == 0x08))
  347. {
  348. // READ(6)
  349. uint32_t lba =
  350. (((uint32_t) scsiDev.cdb[1] & 0x1F) << 16) +
  351. (((uint32_t) scsiDev.cdb[2]) << 8) +
  352. scsiDev.cdb[3];
  353. uint32_t blocks = scsiDev.cdb[4];
  354. if (unlikely(blocks == 0)) blocks = 256;
  355. doRead(lba, blocks);
  356. }
  357. else if (likely(command == 0x28))
  358. {
  359. // READ(10)
  360. // Ignore all cache control bits - we don't support a memory cache.
  361. uint32_t lba =
  362. (((uint32_t) scsiDev.cdb[2]) << 24) +
  363. (((uint32_t) scsiDev.cdb[3]) << 16) +
  364. (((uint32_t) scsiDev.cdb[4]) << 8) +
  365. scsiDev.cdb[5];
  366. uint32_t blocks =
  367. (((uint32_t) scsiDev.cdb[7]) << 8) +
  368. scsiDev.cdb[8];
  369. doRead(lba, blocks);
  370. }
  371. else if (likely(command == 0x0A))
  372. {
  373. // WRITE(6)
  374. uint32_t lba =
  375. (((uint32_t) scsiDev.cdb[1] & 0x1F) << 16) +
  376. (((uint32_t) scsiDev.cdb[2]) << 8) +
  377. scsiDev.cdb[3];
  378. uint32_t blocks = scsiDev.cdb[4];
  379. if (unlikely(blocks == 0)) blocks = 256;
  380. doWrite(lba, blocks);
  381. }
  382. else if (likely(command == 0x2A) || // WRITE(10)
  383. unlikely(command == 0x2E)) // WRITE AND VERIFY
  384. {
  385. // Ignore all cache control bits - we don't support a memory cache.
  386. // Don't bother verifying either. The SD card likely stores ECC
  387. // along with each flash row.
  388. uint32_t lba =
  389. (((uint32_t) scsiDev.cdb[2]) << 24) +
  390. (((uint32_t) scsiDev.cdb[3]) << 16) +
  391. (((uint32_t) scsiDev.cdb[4]) << 8) +
  392. scsiDev.cdb[5];
  393. uint32_t blocks =
  394. (((uint32_t) scsiDev.cdb[7]) << 8) +
  395. scsiDev.cdb[8];
  396. doWrite(lba, blocks);
  397. }
  398. else if (unlikely(command == 0x04))
  399. {
  400. // FORMAT UNIT
  401. // We don't really do any formatting, but we need to read the correct
  402. // number of bytes in the DATA_OUT phase to make the SCSI host happy.
  403. int fmtData = (scsiDev.cdb[1] & 0x10) ? 1 : 0;
  404. if (fmtData)
  405. {
  406. // We need to read the parameter list, but we don't know how
  407. // big it is yet. Start with the header.
  408. scsiDev.dataLen = 4;
  409. scsiDev.phase = DATA_OUT;
  410. scsiDev.postDataOutHook = doFormatUnitHeader;
  411. }
  412. else
  413. {
  414. // No data to read, we're already finished!
  415. }
  416. }
  417. else if (unlikely(command == 0x25))
  418. {
  419. // READ CAPACITY
  420. doReadCapacity();
  421. }
  422. else if (unlikely(command == 0x0B))
  423. {
  424. // SEEK(6)
  425. uint32_t lba =
  426. (((uint32_t) scsiDev.cdb[1] & 0x1F) << 16) +
  427. (((uint32_t) scsiDev.cdb[2]) << 8) +
  428. scsiDev.cdb[3];
  429. doSeek(lba);
  430. }
  431. else if (unlikely(command == 0x2B))
  432. {
  433. // SEEK(10)
  434. uint32_t lba =
  435. (((uint32_t) scsiDev.cdb[2]) << 24) +
  436. (((uint32_t) scsiDev.cdb[3]) << 16) +
  437. (((uint32_t) scsiDev.cdb[4]) << 8) +
  438. scsiDev.cdb[5];
  439. doSeek(lba);
  440. }
  441. else if (unlikely(command == 0x36))
  442. {
  443. // LOCK UNLOCK CACHE
  444. // We don't have a cache to lock data into. do nothing.
  445. }
  446. else if (unlikely(command == 0x34))
  447. {
  448. // PRE-FETCH.
  449. // We don't have a cache to pre-fetch into. do nothing.
  450. }
  451. else if (unlikely(command == 0x1E))
  452. {
  453. // PREVENT ALLOW MEDIUM REMOVAL
  454. // Not much we can do to prevent the user removing the SD card.
  455. // do nothing.
  456. }
  457. else if (unlikely(command == 0x01))
  458. {
  459. // REZERO UNIT
  460. // Set the lun to a vendor-specific state. Ignore.
  461. }
  462. else if (unlikely(command == 0x35))
  463. {
  464. // SYNCHRONIZE CACHE
  465. // We don't have a cache. do nothing.
  466. }
  467. else if (unlikely(command == 0x2F))
  468. {
  469. // VERIFY
  470. // TODO: When they supply data to verify, we should read the data and
  471. // verify it. If they don't supply any data, just say success.
  472. if ((scsiDev.cdb[1] & 0x02) == 0)
  473. {
  474. // They are asking us to do a medium verification with no data
  475. // comparison. Assume success, do nothing.
  476. }
  477. else
  478. {
  479. // TODO. This means they are supplying data to verify against.
  480. // Technically we should probably grab the data and compare it.
  481. scsiDev.status = CHECK_CONDITION;
  482. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  483. scsiDev.target->sense.asc = INVALID_FIELD_IN_CDB;
  484. scsiDev.phase = STATUS;
  485. }
  486. }
  487. else if (unlikely(command == 0x37))
  488. {
  489. // READ DEFECT DATA
  490. uint32_t allocLength = (((uint16_t)scsiDev.cdb[7]) << 8) |
  491. scsiDev.cdb[8];
  492. scsiDev.data[0] = 0;
  493. scsiDev.data[1] = scsiDev.cdb[1];
  494. scsiDev.data[2] = 0;
  495. scsiDev.data[3] = 0;
  496. scsiDev.dataLen = 4;
  497. if (scsiDev.dataLen > allocLength)
  498. {
  499. scsiDev.dataLen = allocLength;
  500. }
  501. scsiDev.phase = DATA_IN;
  502. }
  503. else
  504. {
  505. commandHandled = 0;
  506. }
  507. return commandHandled;
  508. }
  509. static void diskDataInBuffered(int totalSDSectors, uint32_t sdLBA, int useSlowDataCount, uint32_t* phaseChangeDelayNs)
  510. {
  511. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  512. const int sdPerScsi = SDSectorsPerSCSISector(bytesPerSector);
  513. const int buffers = sizeof(scsiDev.data) / SD_SECTOR_SIZE;
  514. int prep = 0;
  515. int i = 0;
  516. int scsiActive __attribute__((unused)) = 0; // unused if DMA disabled
  517. int sdActive = 0;
  518. int gotHalf = 0;
  519. int sentHalf = 0;
  520. while ((i < totalSDSectors) &&
  521. likely(scsiDev.phase == DATA_IN) &&
  522. likely(!scsiDev.resetFlag))
  523. {
  524. int completedDmaSectors;
  525. if (sdActive && (completedDmaSectors = sdReadDMAPoll(sdActive)))
  526. {
  527. prep += completedDmaSectors;
  528. sdActive -= completedDmaSectors;
  529. gotHalf = 0;
  530. }
  531. else if (sdActive > 1)
  532. {
  533. if ((scsiDev.data[SD_SECTOR_SIZE * (prep % buffers) + 510] != 0xAA) ||
  534. (scsiDev.data[SD_SECTOR_SIZE * (prep % buffers) + 511] != 0x33))
  535. {
  536. prep += 1;
  537. sdActive -= 1;
  538. gotHalf = 0;
  539. }
  540. else if (scsiDev.data[SD_SECTOR_SIZE * (prep % buffers) + 127] != 0xAA)
  541. {
  542. // Half-block
  543. gotHalf = 1;
  544. }
  545. }
  546. if (!sdActive &&
  547. (prep - i < buffers) &&
  548. (prep < totalSDSectors) &&
  549. ((totalSDSectors - prep) >= sdPerScsi) &&
  550. (likely(!useSlowDataCount) || scsiPhyComplete()) &&
  551. (HAL_SD_GetState(&hsd) != HAL_SD_STATE_BUSY)) // rx complete but IRQ not fired yet.
  552. {
  553. // Start an SD transfer if we have space.
  554. uint32_t startBuffer = prep % buffers;
  555. uint32_t sectors = totalSDSectors - prep;
  556. uint32_t freeBuffers = buffers - (prep - i);
  557. uint32_t contiguousBuffers = buffers - startBuffer;
  558. freeBuffers = freeBuffers < contiguousBuffers
  559. ? freeBuffers : contiguousBuffers;
  560. sectors = sectors < freeBuffers ? sectors : freeBuffers;
  561. if (sectors > 128) sectors = 128; // 65536 DMA limit !!
  562. // Round-down when we have odd sector sizes.
  563. if (sdPerScsi != 1)
  564. {
  565. sectors = (sectors / sdPerScsi) * sdPerScsi;
  566. }
  567. for (int dodgy = 0; dodgy < sectors; dodgy++)
  568. {
  569. scsiDev.data[SD_SECTOR_SIZE * (startBuffer + dodgy) + 127] = 0xAA;
  570. scsiDev.data[SD_SECTOR_SIZE * (startBuffer + dodgy) + 510] = 0xAA;
  571. scsiDev.data[SD_SECTOR_SIZE * (startBuffer + dodgy) + 511] = 0x33;
  572. }
  573. sdReadDMA(sdLBA + prep, sectors, &scsiDev.data[SD_SECTOR_SIZE * startBuffer]);
  574. sdActive = sectors;
  575. if (useSlowDataCount)
  576. {
  577. scsiSetDataCount((sectors / sdPerScsi) * bytesPerSector);
  578. }
  579. // Wait now that the SD card is busy
  580. // Chances are we've probably already waited sufficient time,
  581. // but it's hard to measure microseconds cheaply. So just wait
  582. // extra just-in-case. Hopefully it's in parallel with dma.
  583. if (*phaseChangeDelayNs > 0)
  584. {
  585. s2s_delay_ns(*phaseChangeDelayNs);
  586. *phaseChangeDelayNs = 0;
  587. }
  588. }
  589. int fifoReady = scsiFifoReady();
  590. if (((prep - i) > 0) && fifoReady)
  591. {
  592. int dmaBytes = SD_SECTOR_SIZE;
  593. if ((i % sdPerScsi) == (sdPerScsi - 1))
  594. {
  595. dmaBytes = bytesPerSector % SD_SECTOR_SIZE;
  596. if (dmaBytes == 0) dmaBytes = SD_SECTOR_SIZE;
  597. }
  598. uint8_t* scsiDmaData = &(scsiDev.data[SD_SECTOR_SIZE * (i % buffers)]);
  599. if (sentHalf)
  600. {
  601. scsiDmaData += SD_SECTOR_SIZE / 2;
  602. dmaBytes -= (SD_SECTOR_SIZE / 2);
  603. }
  604. scsiWritePIO(scsiDmaData, dmaBytes);
  605. ++i;
  606. sentHalf = 0;
  607. gotHalf = 0;
  608. }
  609. else if (gotHalf && !sentHalf && fifoReady && bytesPerSector == SD_SECTOR_SIZE)
  610. {
  611. uint8_t* scsiDmaData = &(scsiDev.data[SD_SECTOR_SIZE * (i % buffers)]);
  612. scsiWritePIO(scsiDmaData, SD_SECTOR_SIZE / 2);
  613. sentHalf = 1;
  614. }
  615. }
  616. }
  617. // Transfer from the SD card straight to the SCSI Fifo without storing in memory first for lower latency
  618. // This requires hardware flow control on the SD device (broken on stm32f205)
  619. // Only functional for 512 byte sectors.
  620. static void diskDataInDirect(uint32_t totalSDSectors, uint32_t sdLBA, int useSlowDataCount, uint32_t* phaseChangeDelayNs)
  621. {
  622. sdReadCmd(sdLBA, totalSDSectors);
  623. // Wait while the SD card starts buffering data
  624. if (*phaseChangeDelayNs > 0)
  625. {
  626. s2s_delay_ns(*phaseChangeDelayNs);
  627. *phaseChangeDelayNs = 0;
  628. }
  629. for (int i = 0; i < totalSDSectors && !scsiDev.resetFlag; ++i)
  630. {
  631. if (i % 128 == 0)
  632. {
  633. // SD DPSM has 24 bit limit. Re-use 128 (DMA limit)
  634. uint32_t chunk = totalSDSectors - i > 128 ? 128 : totalSDSectors - i;
  635. sdReadPIOData(chunk);
  636. if (useSlowDataCount)
  637. {
  638. while (!scsiDev.resetFlag && !scsiPhyComplete())
  639. {}
  640. scsiSetDataCount(chunk * SD_SECTOR_SIZE); // SCSI_XFER_MAX > 65536
  641. }
  642. }
  643. // The SCSI fifo is a full sector so we only need to check once.
  644. while (!scsiFifoReady() && !scsiDev.resetFlag)
  645. {}
  646. int byteCount = 0;
  647. while(byteCount < SD_SECTOR_SIZE &&
  648. likely(!scsiDev.resetFlag) &&
  649. likely(scsiDev.phase == DATA_IN) &&
  650. !__HAL_SD_GET_FLAG(&hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT))
  651. {
  652. if(__HAL_SD_GET_FLAG(&hsd, SDIO_FLAG_RXFIFOHF))
  653. {
  654. // The SDIO fifo is 32 x 32bits. As we're using the "half full" flag we must
  655. // always read half the FIFO.
  656. for (int j = 0; j < 4; ++j)
  657. {
  658. uint32_t data[4];
  659. data[0] = SDIO_ReadFIFO(hsd.Instance);
  660. data[1] = SDIO_ReadFIFO(hsd.Instance);
  661. data[2] = SDIO_ReadFIFO(hsd.Instance);
  662. data[3] = SDIO_ReadFIFO(hsd.Instance);
  663. *((volatile uint32_t*)SCSI_FIFO_DATA) = data[0];
  664. *((volatile uint32_t*)SCSI_FIFO_DATA) = data[1];
  665. *((volatile uint32_t*)SCSI_FIFO_DATA) = data[2];
  666. *((volatile uint32_t*)SCSI_FIFO_DATA) = data[3];
  667. }
  668. byteCount += 64;
  669. }
  670. }
  671. int error = 0;
  672. if (__HAL_SD_GET_FLAG(&hsd, SDIO_FLAG_DTIMEOUT))
  673. {
  674. __HAL_SD_CLEAR_FLAG(&hsd, SDIO_FLAG_DTIMEOUT);
  675. error = 1;
  676. }
  677. else if (__HAL_SD_GET_FLAG(&hsd, SDIO_FLAG_DCRCFAIL))
  678. {
  679. __HAL_SD_CLEAR_FLAG(&hsd, SDIO_FLAG_DCRCFAIL);
  680. error = 1;
  681. }
  682. else if (__HAL_SD_GET_FLAG(&hsd, SDIO_FLAG_RXOVERR))
  683. {
  684. __HAL_SD_CLEAR_FLAG(&hsd, SDIO_FLAG_RXOVERR);
  685. error = 1;
  686. }
  687. if (error && scsiDev.phase == DATA_IN)
  688. {
  689. __HAL_SD_CLEAR_FLAG(&hsd, SDIO_STATIC_FLAGS);
  690. scsiDiskReset();
  691. scsiDev.status = CHECK_CONDITION;
  692. scsiDev.target->sense.code = HARDWARE_ERROR;
  693. scsiDev.target->sense.asc = LOGICAL_UNIT_COMMUNICATION_FAILURE;
  694. scsiDev.phase = STATUS;
  695. }
  696. // We need the SCSI FIFO count to complete even after the SD read has failed
  697. while (byteCount < SD_SECTOR_SIZE &&
  698. likely(!scsiDev.resetFlag))
  699. {
  700. scsiPhyTx32(0, 0);
  701. byteCount += 4;
  702. }
  703. }
  704. /* Send stop transmission command in case of multiblock read */
  705. if(totalSDSectors > 1U)
  706. {
  707. SDMMC_CmdStopTransfer(hsd.Instance);
  708. }
  709. // Read remaining data
  710. uint32_t extraCount = SD_DATATIMEOUT;
  711. while ((__HAL_SD_GET_FLAG(&hsd, SDIO_FLAG_RXDAVL)) && (extraCount > 0))
  712. {
  713. SDIO_ReadFIFO(hsd.Instance);
  714. extraCount--;
  715. }
  716. __HAL_SD_CLEAR_FLAG(&hsd, SDIO_STATIC_DATA_FLAGS);
  717. hsd.State = HAL_SD_STATE_READY;
  718. sdCompleteTransfer(); // Probably overkill
  719. }
  720. static void diskDataIn()
  721. {
  722. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  723. // Take responsibility for waiting for the phase delays
  724. uint32_t phaseChangeDelayNs = scsiEnterPhaseImmediate(DATA_IN);
  725. int totalSDSectors =
  726. transfer.blocks * SDSectorsPerSCSISector(bytesPerSector);
  727. uint32_t sdLBA =
  728. SCSISector2SD(
  729. scsiDev.target->cfg->sdSectorStart,
  730. bytesPerSector,
  731. transfer.lba);
  732. // It's highly unlikely that someone is going to use huge transfers
  733. // per scsi command, but if they do it'll be slower than usual.
  734. uint32_t totalScsiBytes = transfer.blocks * bytesPerSector;
  735. int useSlowDataCount = totalScsiBytes >= SCSI_XFER_MAX;
  736. if (!useSlowDataCount)
  737. {
  738. scsiSetDataCount(totalScsiBytes);
  739. }
  740. #ifdef STM32F4xx
  741. // Direct mode requires hardware flow control to be working on the SD peripheral
  742. // Code isn't currently working above 128 sectors. TODO investigate
  743. if (totalSDSectors < 128 && bytesPerSector == SD_SECTOR_SIZE)
  744. {
  745. diskDataInDirect(totalSDSectors, sdLBA, useSlowDataCount, &phaseChangeDelayNs);
  746. }
  747. else
  748. #endif
  749. {
  750. diskDataInBuffered(totalSDSectors, sdLBA, useSlowDataCount, &phaseChangeDelayNs);
  751. }
  752. if (phaseChangeDelayNs > 0 && !scsiDev.resetFlag) // zero bytes ?
  753. {
  754. s2s_delay_ns(phaseChangeDelayNs);
  755. phaseChangeDelayNs = 0;
  756. }
  757. if (scsiDev.resetFlag)
  758. {
  759. HAL_SD_Abort(&hsd);
  760. }
  761. else
  762. {
  763. // Wait for the SD transfer to complete before we disable IRQs.
  764. // (Otherwise some cards will cause an error if we don't sent the
  765. // stop transfer command via the DMA complete handler in time)
  766. while (HAL_SD_GetState(&hsd) == HAL_SD_STATE_BUSY)
  767. {
  768. // Wait while keeping BSY.
  769. }
  770. }
  771. HAL_SD_CardStateTypeDef cardState = HAL_SD_GetCardState(&hsd);
  772. while (cardState == HAL_SD_CARD_PROGRAMMING || cardState == HAL_SD_CARD_SENDING)
  773. {
  774. cardState = HAL_SD_GetCardState(&hsd);
  775. }
  776. // We've finished transferring the data to the FPGA, now wait until it's
  777. // written to he SCSI bus.
  778. while (!scsiPhyComplete() &&
  779. likely(scsiDev.phase == DATA_IN) &&
  780. likely(!scsiDev.resetFlag))
  781. {
  782. // spin
  783. }
  784. if (scsiDev.phase == DATA_IN)
  785. {
  786. scsiDev.phase = STATUS;
  787. }
  788. scsiDiskReset();
  789. }
  790. void diskDataOut_512(int totalSDSectors, uint32_t sdLBA, int useSlowDataCount, int* clearBSY, int* parityError)
  791. {
  792. int i = 0;
  793. int disconnected = 0;
  794. int enableParity = scsiDev.boardCfg.flags & S2S_CFG_ENABLE_PARITY;
  795. uint32_t maxSectors = sizeof(scsiDev.data) / SD_SECTOR_SIZE;
  796. int lastWriteSize = 0;
  797. while ((i < totalSDSectors) &&
  798. likely(scsiDev.phase == DATA_OUT) &&
  799. likely(!scsiDev.resetFlag))
  800. // KEEP GOING to ensure FIFOs are in a good state.
  801. // likely(!parityError || !enableParity))
  802. {
  803. uint32_t maxXferSectors = SCSI_XFER_MAX / SD_SECTOR_SIZE;
  804. uint32_t rem = totalSDSectors - i;
  805. uint32_t sectors = rem < maxXferSectors ? rem : maxXferSectors;
  806. uint32_t totalBytes = sectors * SD_SECTOR_SIZE;
  807. if (useSlowDataCount)
  808. {
  809. scsiSetDataCount(totalBytes);
  810. }
  811. lastWriteSize = sectors;
  812. HAL_SD_WriteBlocks_DMA(&hsd, i + sdLBA, sectors);
  813. int j = 0;
  814. int prep = 0;
  815. int sdActive = 0;
  816. uint32_t dmaFinishTime = 0;
  817. while (j < sectors && !scsiDev.resetFlag)
  818. {
  819. if (sdActive &&
  820. HAL_SD_GetState(&hsd) != HAL_SD_STATE_BUSY &&
  821. !sdIsBusy())
  822. {
  823. j += sdActive;
  824. sdActive = 0;
  825. }
  826. if (!sdActive && ((prep - j) > 0))
  827. {
  828. // Start an SD transfer if we have space.
  829. HAL_SD_WriteBlocks_Data(&hsd, &scsiDev.data[SD_SECTOR_SIZE * (j % maxSectors)]);
  830. sdActive = 1;
  831. }
  832. if (((prep - j) < maxSectors) &&
  833. (prep < sectors) &&
  834. scsiFifoReady())
  835. {
  836. scsiReadPIO(
  837. &scsiDev.data[(prep % maxSectors) * SD_SECTOR_SIZE],
  838. SD_SECTOR_SIZE,
  839. parityError);
  840. prep++;
  841. if (prep == sectors)
  842. {
  843. dmaFinishTime = s2s_getTime_ms();
  844. }
  845. }
  846. if (i + prep >= totalSDSectors &&
  847. !disconnected &&
  848. (!(*parityError) || !enableParity) &&
  849. s2s_elapsedTime_ms(dmaFinishTime) >= 180)
  850. {
  851. // We're transferring over the SCSI bus faster than the SD card
  852. // can write. All data is buffered, and we're just waiting for
  853. // the SD card to complete. The host won't let us disconnect.
  854. // Some drivers set a 250ms timeout on transfers to complete.
  855. // SD card writes are supposed to complete
  856. // within 200ms, but sometimes they don't.
  857. // Just pretend we're finished.
  858. process_Status();
  859. *clearBSY = process_MessageIn(0); // Will go to BUS_FREE state but keep BSY asserted.
  860. disconnected = 1;
  861. }
  862. }
  863. if (scsiDev.resetFlag)
  864. {
  865. HAL_SD_Abort(&hsd);
  866. }
  867. else
  868. {
  869. while (HAL_SD_GetState(&hsd) == HAL_SD_STATE_BUSY) {} // Waits for DMA to complete
  870. if (lastWriteSize > 1)
  871. {
  872. SDMMC_CmdStopTransfer(hsd.Instance);
  873. }
  874. }
  875. while (sdIsBusy() &&
  876. s2s_elapsedTime_ms(dmaFinishTime) < 180)
  877. {
  878. // Wait while the SD card is writing buffer to flash
  879. // The card may remain in the RECEIVING state (even though it's programming) if
  880. // it has buffer space to receive more data available.
  881. }
  882. if (!disconnected &&
  883. i + sectors >= totalSDSectors &&
  884. (!parityError || !enableParity))
  885. {
  886. // We're transferring over the SCSI bus faster than the SD card
  887. // can write. All data is buffered, and we're just waiting for
  888. // the SD card to complete. The host won't let us disconnect.
  889. // Some drivers set a 250ms timeout on transfers to complete.
  890. // SD card writes are supposed to complete
  891. // within 200ms, but sometimes they don't.
  892. // Just pretend we're finished.
  893. process_Status();
  894. *clearBSY = process_MessageIn(0); // Will go to BUS_FREE state but keep BSY asserted.
  895. }
  896. // Wait while the SD card is writing buffer to flash
  897. // The card may remain in the RECEIVING state (even though it's programming) if
  898. // it has buffer space to receive more data available.
  899. while (sdIsBusy()) {}
  900. HAL_SD_CardStateTypeDef cardState = HAL_SD_GetCardState(&hsd);
  901. while (cardState == HAL_SD_CARD_PROGRAMMING || cardState == HAL_SD_CARD_RECEIVING)
  902. {
  903. // Wait while the SD card is writing buffer to flash
  904. // The card may remain in the RECEIVING state (even though it's programming) if
  905. // it has buffer space to receive more data available.
  906. cardState = HAL_SD_GetCardState(&hsd);
  907. }
  908. i += sectors;
  909. }
  910. }
  911. void diskDataOut_variableSectorSize(int sdPerScsi, int totalSDSectors, uint32_t sdLBA, int useSlowDataCount, int* parityError)
  912. {
  913. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  914. int i = 0;
  915. int enableParity = scsiDev.boardCfg.flags & S2S_CFG_ENABLE_PARITY;
  916. uint32_t maxSectors = sizeof(scsiDev.data) / SD_SECTOR_SIZE;
  917. while ((i < totalSDSectors) &&
  918. likely(scsiDev.phase == DATA_OUT) &&
  919. likely(!scsiDev.resetFlag))
  920. // KEEP GOING to ensure FIFOs are in a good state.
  921. // likely(!parityError || !enableParity))
  922. {
  923. // Well, until we have some proper non-blocking SD code, we must
  924. // do this in a half-duplex fashion. We need to write as much as
  925. // possible in each SD card transaction.
  926. // use sg_dd from sg_utils3 tools to test.
  927. uint32_t rem = totalSDSectors - i;
  928. uint32_t sectors;
  929. if (rem <= maxSectors)
  930. {
  931. sectors = rem;
  932. }
  933. else
  934. {
  935. sectors = maxSectors;
  936. while (sectors % sdPerScsi) sectors--;
  937. }
  938. if (useSlowDataCount)
  939. {
  940. scsiSetDataCount((sectors / sdPerScsi) * bytesPerSector);
  941. }
  942. for (int scsiSector = i; scsiSector < i + sectors; ++scsiSector)
  943. {
  944. int dmaBytes = SD_SECTOR_SIZE;
  945. if ((scsiSector % sdPerScsi) == (sdPerScsi - 1))
  946. {
  947. dmaBytes = bytesPerSector % SD_SECTOR_SIZE;
  948. if (dmaBytes == 0) dmaBytes = SD_SECTOR_SIZE;
  949. }
  950. scsiReadPIO(&scsiDev.data[SD_SECTOR_SIZE * (scsiSector - i)], dmaBytes, parityError);
  951. }
  952. if (!(*parityError) || !enableParity)
  953. {
  954. BSP_SD_WriteBlocks_DMA(&scsiDev.data[0], i + sdLBA, sectors);
  955. }
  956. i += sectors;
  957. }
  958. }
  959. void diskDataOut()
  960. {
  961. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  962. scsiEnterPhase(DATA_OUT);
  963. const int sdPerScsi = SDSectorsPerSCSISector(bytesPerSector);
  964. int totalSDSectors = transfer.blocks * sdPerScsi;
  965. uint32_t sdLBA =
  966. SCSISector2SD(
  967. scsiDev.target->cfg->sdSectorStart,
  968. bytesPerSector,
  969. transfer.lba);
  970. int clearBSY = 0;
  971. int parityError = 0;
  972. static_assert(SCSI_XFER_MAX >= sizeof(scsiDev.data), "Assumes SCSI_XFER_MAX >= sizeof(scsiDev.data)");
  973. // Start reading and filling fifos as soon as possible.
  974. // It's highly unlikely that someone is going to use huge transfers
  975. // per scsi command, but if they do it'll be slower than usual.
  976. // Note: Happens in Macintosh FWB HDD Toolkit benchmarks which default
  977. // to 768kb
  978. uint32_t totalTransferBytes = transfer.blocks * bytesPerSector;
  979. int useSlowDataCount = totalTransferBytes >= SCSI_XFER_MAX;
  980. if (!useSlowDataCount)
  981. {
  982. DWT->CYCCNT = 0; // Start counting cycles
  983. scsiSetDataCount(totalTransferBytes);
  984. }
  985. if (bytesPerSector == SD_SECTOR_SIZE)
  986. {
  987. diskDataOut_512(totalSDSectors, sdLBA, useSlowDataCount, &clearBSY, &parityError);
  988. }
  989. else
  990. {
  991. diskDataOut_variableSectorSize(sdPerScsi, totalSDSectors, sdLBA, useSlowDataCount, &parityError);
  992. }
  993. // Should already be complete here as we've ready the FIFOs
  994. // by now. Check anyway.
  995. while (!scsiPhyComplete() && likely(!scsiDev.resetFlag))
  996. {
  997. // spin
  998. }
  999. if (clearBSY)
  1000. {
  1001. enter_BusFree();
  1002. }
  1003. if (scsiDev.phase == DATA_OUT)
  1004. {
  1005. if (parityError &&
  1006. (scsiDev.boardCfg.flags & S2S_CFG_ENABLE_PARITY))
  1007. {
  1008. scsiDev.target->sense.code = ABORTED_COMMAND;
  1009. scsiDev.target->sense.asc = SCSI_PARITY_ERROR;
  1010. scsiDev.status = CHECK_CONDITION;;
  1011. }
  1012. scsiDev.phase = STATUS;
  1013. }
  1014. scsiDiskReset();
  1015. }
  1016. void scsiDiskPoll()
  1017. {
  1018. if (scsiDev.phase == DATA_IN &&
  1019. transfer.currentBlock != transfer.blocks)
  1020. {
  1021. diskDataIn();
  1022. }
  1023. else if (scsiDev.phase == DATA_OUT &&
  1024. transfer.currentBlock != transfer.blocks)
  1025. {
  1026. diskDataOut();
  1027. }
  1028. }
  1029. void scsiDiskReset()
  1030. {
  1031. scsiDev.dataPtr = 0;
  1032. scsiDev.savedDataPtr = 0;
  1033. scsiDev.dataLen = 0;
  1034. // transfer.lba = 0; // Needed in Request Sense to determine failure
  1035. transfer.blocks = 0;
  1036. transfer.currentBlock = 0;
  1037. // Cancel long running commands!
  1038. #if 0
  1039. if (
  1040. ((scsiDev.boardCfg.flags & S2S_CFG_ENABLE_CACHE) == 0) ||
  1041. (transfer.multiBlock == 0)
  1042. )
  1043. #endif
  1044. {
  1045. sdCompleteTransfer();
  1046. }
  1047. transfer.multiBlock = 0;
  1048. }
  1049. void scsiDiskInit()
  1050. {
  1051. scsiDiskReset();
  1052. }