ZuluSCSI_disk.cpp 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234
  1. /**
  2. * SCSI2SD V6 - Copyright (C) 2013 Michael McMaster <michael@codesrc.com>
  3. * Copyright (C) 2014 Doug Brown <doug@downtowndougbrown.com
  4. * ZuluSCSI™ - Copyright (c) 2022 Rabbit Hole Computing™
  5. *
  6. * This file is licensed under the GPL version 3 or any later version. 
  7. * It is derived from disk.c in SCSI2SD V6
  8. *
  9. * https://www.gnu.org/licenses/gpl-3.0.html
  10. * ----
  11. * This program is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU General Public License as published by
  13. * the Free Software Foundation, either version 3 of the License, or
  14. * (at your option) any later version. 
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  19. * GNU General Public License for more details. 
  20. *
  21. * You should have received a copy of the GNU General Public License
  22. * along with this program.  If not, see <https://www.gnu.org/licenses/>.
  23. **/
  24. // This file implements the main SCSI disk emulation and data streaming.
  25. // It is derived from disk.c in SCSI2SD V6.
  26. #include "ZuluSCSI_disk.h"
  27. #include "ZuluSCSI_log.h"
  28. #include "ZuluSCSI_config.h"
  29. #include "ZuluSCSI_presets.h"
  30. #include <minIni.h>
  31. #include <string.h>
  32. #include <strings.h>
  33. #include <assert.h>
  34. #include <SdFat.h>
  35. extern "C" {
  36. #include <scsi2sd_time.h>
  37. #include <sd.h>
  38. #include <mode.h>
  39. }
  40. #ifndef PLATFORM_MAX_SCSI_SPEED
  41. #define PLATFORM_MAX_SCSI_SPEED S2S_CFG_SPEED_ASYNC_50
  42. #endif
  43. // This can be overridden in platform file to set the size of the transfers
  44. // used when reading from SCSI bus and writing to SD card.
  45. // When SD card access is fast, these are usually better increased.
  46. // If SD card access is roughly same speed as SCSI bus, these can be left at 512
  47. #ifndef PLATFORM_OPTIMAL_MIN_SD_WRITE_SIZE
  48. #define PLATFORM_OPTIMAL_MIN_SD_WRITE_SIZE 512
  49. #endif
  50. #ifndef PLATFORM_OPTIMAL_MAX_SD_WRITE_SIZE
  51. #define PLATFORM_OPTIMAL_MAX_SD_WRITE_SIZE 1024
  52. #endif
  53. // Optimal size for the last write in a write request.
  54. // This is often better a bit smaller than PLATFORM_OPTIMAL_SD_WRITE_SIZE
  55. // to reduce the dead time between end of SCSI transfer and finishing of SD write.
  56. #ifndef PLATFORM_OPTIMAL_LAST_SD_WRITE_SIZE
  57. #define PLATFORM_OPTIMAL_LAST_SD_WRITE_SIZE 512
  58. #endif
  59. // Optimal size for read block from SCSI bus
  60. // For platforms with nonblocking transfer, this can be large.
  61. // For Akai MPC60 compatibility this has to be at least 5120
  62. #ifndef PLATFORM_OPTIMAL_SCSI_READ_BLOCK_SIZE
  63. #ifdef PLATFORM_SCSIPHY_HAS_NONBLOCKING_READ
  64. #define PLATFORM_OPTIMAL_SCSI_READ_BLOCK_SIZE 65536
  65. #else
  66. #define PLATFORM_OPTIMAL_SCSI_READ_BLOCK_SIZE 8192
  67. #endif
  68. #endif
  69. #ifndef PLATFORM_HAS_ROM_DRIVE
  70. // Dummy defines for platforms without ROM drive support
  71. #define PLATFORM_ROMDRIVE_PAGE_SIZE 1024
  72. uint32_t platform_get_romdrive_maxsize() { return 0; }
  73. bool platform_read_romdrive(uint8_t *dest, uint32_t start, uint32_t count) { return false; }
  74. bool platform_write_romdrive(const uint8_t *data, uint32_t start, uint32_t count) { return false; }
  75. #endif
  76. #ifndef PLATFORM_SCSIPHY_HAS_NONBLOCKING_READ
  77. // For platforms that do not have non-blocking read from SCSI bus
  78. void scsiStartRead(uint8_t* data, uint32_t count, int *parityError)
  79. {
  80. scsiRead(data, count, parityError);
  81. }
  82. void scsiFinishRead(uint8_t* data, uint32_t count, int *parityError)
  83. {
  84. }
  85. bool scsiIsReadFinished(const uint8_t *data)
  86. {
  87. return true;
  88. }
  89. #endif
  90. // SD card sector size is always 512 bytes
  91. extern SdFs SD;
  92. #define SD_SECTOR_SIZE 512
  93. /************************************************/
  94. /* ROM drive support (in microcontroller flash) */
  95. /************************************************/
  96. struct romdrive_hdr_t {
  97. char magic[8]; // "ROMDRIVE"
  98. int scsi_id;
  99. uint32_t imagesize;
  100. uint32_t blocksize;
  101. S2S_CFG_TYPE drivetype;
  102. uint32_t reserved[32];
  103. };
  104. // Check if the romdrive is present
  105. static bool check_romdrive(romdrive_hdr_t *hdr)
  106. {
  107. if (!platform_read_romdrive((uint8_t*)hdr, 0, sizeof(romdrive_hdr_t)))
  108. {
  109. return false;
  110. }
  111. if (memcmp(hdr->magic, "ROMDRIVE", 8) != 0)
  112. {
  113. return false;
  114. }
  115. if (hdr->imagesize <= 0 || hdr->scsi_id < 0 || hdr->scsi_id > 8)
  116. {
  117. return false;
  118. }
  119. return true;
  120. }
  121. // Clear the drive metadata header
  122. bool scsiDiskClearRomDrive()
  123. {
  124. #ifndef PLATFORM_HAS_ROM_DRIVE
  125. logmsg("---- Platform does not support ROM drive");
  126. return false;
  127. #else
  128. romdrive_hdr_t hdr = {0x0};
  129. if (!platform_write_romdrive((const uint8_t*)&hdr, 0, PLATFORM_ROMDRIVE_PAGE_SIZE))
  130. {
  131. logmsg("-- Failed to clear ROM drive");
  132. return false;
  133. }
  134. logmsg("-- Cleared ROM drive");
  135. SD.remove("CLEAR_ROM");
  136. return true;
  137. #endif
  138. }
  139. // Load an image file to romdrive
  140. bool scsiDiskProgramRomDrive(const char *filename, int scsi_id, int blocksize, S2S_CFG_TYPE type)
  141. {
  142. #ifndef PLATFORM_HAS_ROM_DRIVE
  143. logmsg("---- Platform does not support ROM drive");
  144. return false;
  145. #endif
  146. FsFile file = SD.open(filename, O_RDONLY);
  147. if (!file.isOpen())
  148. {
  149. logmsg("---- Failed to open: ", filename);
  150. return false;
  151. }
  152. uint64_t filesize = file.size();
  153. uint32_t maxsize = platform_get_romdrive_maxsize() - PLATFORM_ROMDRIVE_PAGE_SIZE;
  154. logmsg("---- SCSI ID: ", scsi_id, " blocksize ", blocksize, " type ", (int)type);
  155. logmsg("---- ROM drive maximum size is ", (int)maxsize,
  156. " bytes, image file is ", (int)filesize, " bytes");
  157. if (filesize > maxsize)
  158. {
  159. logmsg("---- Image size exceeds ROM space, not loading");
  160. file.close();
  161. return false;
  162. }
  163. romdrive_hdr_t hdr = {};
  164. memcpy(hdr.magic, "ROMDRIVE", 8);
  165. hdr.scsi_id = scsi_id;
  166. hdr.imagesize = filesize;
  167. hdr.blocksize = blocksize;
  168. hdr.drivetype = type;
  169. // Program the drive metadata header
  170. if (!platform_write_romdrive((const uint8_t*)&hdr, 0, PLATFORM_ROMDRIVE_PAGE_SIZE))
  171. {
  172. logmsg("---- Failed to program ROM drive header");
  173. file.close();
  174. return false;
  175. }
  176. // Program the drive contents
  177. uint32_t pages = (filesize + PLATFORM_ROMDRIVE_PAGE_SIZE - 1) / PLATFORM_ROMDRIVE_PAGE_SIZE;
  178. for (uint32_t i = 0; i < pages; i++)
  179. {
  180. if (i % 2)
  181. LED_ON();
  182. else
  183. LED_OFF();
  184. if (file.read(scsiDev.data, PLATFORM_ROMDRIVE_PAGE_SIZE) <= 0 ||
  185. !platform_write_romdrive(scsiDev.data, (i + 1) * PLATFORM_ROMDRIVE_PAGE_SIZE, PLATFORM_ROMDRIVE_PAGE_SIZE))
  186. {
  187. logmsg("---- Failed to program ROM drive page ", (int)i);
  188. file.close();
  189. return false;
  190. }
  191. }
  192. LED_OFF();
  193. file.close();
  194. char newname[MAX_FILE_PATH * 2] = "";
  195. strlcat(newname, filename, sizeof(newname));
  196. strlcat(newname, "_loaded", sizeof(newname));
  197. SD.rename(filename, newname);
  198. logmsg("---- ROM drive programming successful, image file renamed to ", newname);
  199. return true;
  200. }
  201. bool scsiDiskCheckRomDrive()
  202. {
  203. romdrive_hdr_t hdr = {};
  204. return check_romdrive(&hdr);
  205. }
  206. // Check if rom drive exists and activate it
  207. bool scsiDiskActivateRomDrive()
  208. {
  209. #ifndef PLATFORM_HAS_ROM_DRIVE
  210. return false;
  211. #endif
  212. uint32_t maxsize = platform_get_romdrive_maxsize() - PLATFORM_ROMDRIVE_PAGE_SIZE;
  213. logmsg("-- Platform supports ROM drive up to ", (int)(maxsize / 1024), " kB");
  214. romdrive_hdr_t hdr = {};
  215. if (!check_romdrive(&hdr))
  216. {
  217. logmsg("---- ROM drive image not detected");
  218. return false;
  219. }
  220. if (ini_getbool("SCSI", "DisableROMDrive", 0, CONFIGFILE))
  221. {
  222. logmsg("---- ROM drive disabled in ini file, not enabling");
  223. return false;
  224. }
  225. long rom_scsi_id = ini_getl("SCSI", "ROMDriveSCSIID", -1, CONFIGFILE);
  226. if (rom_scsi_id >= 0 && rom_scsi_id <= 7)
  227. {
  228. hdr.scsi_id = rom_scsi_id;
  229. logmsg("---- ROM drive SCSI id overriden in ini file, changed to ", (int)hdr.scsi_id);
  230. }
  231. if (s2s_getConfigById(hdr.scsi_id))
  232. {
  233. logmsg("---- ROM drive SCSI id ", (int)hdr.scsi_id, " is already in use, not enabling");
  234. return false;
  235. }
  236. logmsg("---- Activating ROM drive, SCSI id ", (int)hdr.scsi_id, " size ", (int)(hdr.imagesize / 1024), " kB");
  237. bool status = scsiDiskOpenHDDImage(hdr.scsi_id, "ROM:", hdr.scsi_id, 0, hdr.blocksize, hdr.drivetype);
  238. if (!status)
  239. {
  240. logmsg("---- ROM drive activation failed");
  241. return false;
  242. }
  243. else
  244. {
  245. return true;
  246. }
  247. }
  248. /***********************/
  249. /* Backing image files */
  250. /***********************/
  251. extern SdFs SD;
  252. SdDevice sdDev = {2, 256 * 1024 * 1024 * 2}; /* For SCSI2SD */
  253. // This class wraps SdFat library FsFile to allow access
  254. // through either FAT filesystem or as a raw sector range.
  255. //
  256. // Raw access is activated by using filename like "RAW:0:12345"
  257. // where the numbers are the first and last sector.
  258. //
  259. // If the platform supports a ROM drive, it is activated by using
  260. // filename "ROM:".
  261. class ImageBackingStore
  262. {
  263. public:
  264. ImageBackingStore()
  265. {
  266. m_israw = false;
  267. m_isrom = false;
  268. m_isreadonly_attr = false;
  269. m_blockdev = nullptr;
  270. m_bgnsector = m_endsector = m_cursector = 0;
  271. }
  272. ImageBackingStore(const char *filename, uint32_t scsi_block_size): ImageBackingStore()
  273. {
  274. if (strncasecmp(filename, "RAW:", 4) == 0)
  275. {
  276. char *endptr, *endptr2;
  277. m_bgnsector = strtoul(filename + 4, &endptr, 0);
  278. m_endsector = strtoul(endptr + 1, &endptr2, 0);
  279. if (*endptr != ':' || *endptr2 != '\0')
  280. {
  281. logmsg("Invalid format for raw filename: ", filename);
  282. return;
  283. }
  284. if ((scsi_block_size % SD_SECTOR_SIZE) != 0)
  285. {
  286. logmsg("SCSI block size ", (int)scsi_block_size, " is not supported for RAW partitions (must be divisible by 512 bytes)");
  287. return;
  288. }
  289. m_israw = true;
  290. m_blockdev = SD.card();
  291. uint32_t sectorCount = SD.card()->sectorCount();
  292. if (m_endsector >= sectorCount)
  293. {
  294. logmsg("Limiting RAW image mapping to SD card sector count: ", (int)sectorCount);
  295. m_endsector = sectorCount - 1;
  296. }
  297. }
  298. else if (strncasecmp(filename, "ROM:", 4) == 0)
  299. {
  300. if (!check_romdrive(&m_romhdr))
  301. {
  302. m_romhdr.imagesize = 0;
  303. }
  304. else
  305. {
  306. m_isrom = true;
  307. }
  308. }
  309. else
  310. {
  311. m_isreadonly_attr = !!(FS_ATTRIB_READ_ONLY & SD.attrib(filename));
  312. if (m_isreadonly_attr)
  313. {
  314. m_fsfile = SD.open(filename, O_RDONLY);
  315. logmsg("---- Image file is read-only, writes disabled");
  316. }
  317. else
  318. {
  319. m_fsfile = SD.open(filename, O_RDWR);
  320. }
  321. uint32_t sectorcount = m_fsfile.size() / SD_SECTOR_SIZE;
  322. uint32_t begin = 0, end = 0;
  323. if (m_fsfile.contiguousRange(&begin, &end) && end >= begin + sectorcount
  324. && (scsi_block_size % SD_SECTOR_SIZE) == 0)
  325. {
  326. // Convert to raw mapping, this avoids some unnecessary
  327. // access overhead in SdFat library.
  328. m_israw = true;
  329. m_blockdev = SD.card();
  330. m_bgnsector = begin;
  331. if (end != begin + sectorcount)
  332. {
  333. uint32_t allocsize = end - begin + 1;
  334. // Due to issue #80 in ZuluSCSI version 1.0.8 and 1.0.9 the allocated size was mistakenly reported to SCSI controller.
  335. // If the drive was formatted using those versions, you may have problems accessing it with newer firmware.
  336. // The old behavior can be restored with setting [SCSI] UseFATAllocSize = 1 in config file.
  337. if (ini_getbool("SCSI", "UseFATAllocSize", 0, CONFIGFILE))
  338. {
  339. sectorcount = allocsize;
  340. }
  341. }
  342. m_endsector = begin + sectorcount - 1;
  343. m_fsfile.close();
  344. }
  345. }
  346. }
  347. bool isWritable()
  348. {
  349. return !m_isrom && !m_isreadonly_attr;
  350. }
  351. bool isRom()
  352. {
  353. return m_isrom;
  354. }
  355. bool isOpen()
  356. {
  357. if (m_israw)
  358. return (m_blockdev != NULL);
  359. else if (m_isrom)
  360. return (m_romhdr.imagesize > 0);
  361. else
  362. return m_fsfile.isOpen();
  363. }
  364. bool close()
  365. {
  366. if (m_israw)
  367. {
  368. m_blockdev = nullptr;
  369. return true;
  370. }
  371. else if (m_isrom)
  372. {
  373. m_romhdr.imagesize = 0;
  374. return true;
  375. }
  376. else
  377. {
  378. return m_fsfile.close();
  379. }
  380. }
  381. uint64_t size()
  382. {
  383. if (m_israw && m_blockdev)
  384. {
  385. return (uint64_t)(m_endsector - m_bgnsector + 1) * SD_SECTOR_SIZE;
  386. }
  387. else if (m_isrom)
  388. {
  389. return m_romhdr.imagesize;
  390. }
  391. else
  392. {
  393. return m_fsfile.size();
  394. }
  395. }
  396. bool contiguousRange(uint32_t* bgnSector, uint32_t* endSector)
  397. {
  398. if (m_israw && m_blockdev)
  399. {
  400. *bgnSector = m_bgnsector;
  401. *endSector = m_endsector;
  402. return true;
  403. }
  404. else if (m_isrom)
  405. {
  406. *bgnSector = 0;
  407. *endSector = 0;
  408. return true;
  409. }
  410. else
  411. {
  412. return m_fsfile.contiguousRange(bgnSector, endSector);
  413. }
  414. }
  415. bool seek(uint64_t pos)
  416. {
  417. if (m_israw)
  418. {
  419. uint32_t sectornum = pos / SD_SECTOR_SIZE;
  420. assert((uint64_t)sectornum * SD_SECTOR_SIZE == pos);
  421. m_cursector = m_bgnsector + sectornum;
  422. return (m_cursector <= m_endsector);
  423. }
  424. else if (m_isrom)
  425. {
  426. uint32_t sectornum = pos / SD_SECTOR_SIZE;
  427. assert((uint64_t)sectornum * SD_SECTOR_SIZE == pos);
  428. m_cursector = sectornum;
  429. return m_cursector * SD_SECTOR_SIZE < m_romhdr.imagesize;
  430. }
  431. else
  432. {
  433. return m_fsfile.seek(pos);
  434. }
  435. }
  436. int read(void* buf, size_t count)
  437. {
  438. if (m_israw && m_blockdev)
  439. {
  440. uint32_t sectorcount = count / SD_SECTOR_SIZE;
  441. assert((uint64_t)sectorcount * SD_SECTOR_SIZE == count);
  442. if (m_blockdev->readSectors(m_cursector, (uint8_t*)buf, sectorcount))
  443. {
  444. m_cursector += sectorcount;
  445. return count;
  446. }
  447. else
  448. {
  449. return -1;
  450. }
  451. }
  452. else if (m_isrom)
  453. {
  454. uint32_t sectorcount = count / SD_SECTOR_SIZE;
  455. assert((uint64_t)sectorcount * SD_SECTOR_SIZE == count);
  456. uint32_t start = m_cursector * SD_SECTOR_SIZE + PLATFORM_ROMDRIVE_PAGE_SIZE;
  457. if (platform_read_romdrive((uint8_t*)buf, start, count))
  458. {
  459. m_cursector += sectorcount;
  460. return count;
  461. }
  462. else
  463. {
  464. return -1;
  465. }
  466. }
  467. else
  468. {
  469. return m_fsfile.read(buf, count);
  470. }
  471. }
  472. size_t write(const void* buf, size_t count)
  473. {
  474. if (m_israw && m_blockdev)
  475. {
  476. uint32_t sectorcount = count / SD_SECTOR_SIZE;
  477. assert((uint64_t)sectorcount * SD_SECTOR_SIZE == count);
  478. if (m_blockdev->writeSectors(m_cursector, (const uint8_t*)buf, sectorcount))
  479. {
  480. m_cursector += sectorcount;
  481. return count;
  482. }
  483. else
  484. {
  485. return 0;
  486. }
  487. }
  488. else if (m_isrom)
  489. {
  490. logmsg("ERROR: attempted to write to ROM drive");
  491. return 0;
  492. }
  493. else if (m_isreadonly_attr)
  494. {
  495. logmsg("ERROR: attempted to write to a read only image");
  496. return 0;
  497. }
  498. else
  499. {
  500. return m_fsfile.write(buf, count);
  501. }
  502. }
  503. void flush()
  504. {
  505. if (!m_israw && !m_isrom && !m_isreadonly_attr)
  506. {
  507. m_fsfile.flush();
  508. }
  509. }
  510. private:
  511. bool m_israw;
  512. bool m_isrom;
  513. bool m_isreadonly_attr;
  514. romdrive_hdr_t m_romhdr;
  515. FsFile m_fsfile;
  516. SdCard *m_blockdev;
  517. uint32_t m_bgnsector;
  518. uint32_t m_endsector;
  519. uint32_t m_cursector;
  520. };
  521. struct image_config_t: public S2S_TargetCfg
  522. {
  523. ImageBackingStore file;
  524. // For CD-ROM drive ejection
  525. bool ejected;
  526. uint8_t cdrom_events;
  527. bool reinsert_on_inquiry;
  528. // Index of image, for when image on-the-fly switching is used for CD drives
  529. int image_index;
  530. // Right-align vendor / product type strings (for Apple)
  531. // Standard SCSI uses left alignment
  532. // This field uses -1 for default when field is not set in .ini
  533. int rightAlignStrings;
  534. // Maximum amount of bytes to prefetch
  535. int prefetchbytes;
  536. // Warning about geometry settings
  537. bool geometrywarningprinted;
  538. };
  539. static image_config_t g_DiskImages[S2S_MAX_TARGETS];
  540. void scsiDiskResetImages()
  541. {
  542. memset(g_DiskImages, 0, sizeof(g_DiskImages));
  543. }
  544. // Verify format conformance to SCSI spec:
  545. // - Empty bytes filled with 0x20 (space)
  546. // - Only values 0x20 to 0x7E
  547. // - Left alignment for vendor/product/revision, right alignment for serial.
  548. static void formatDriveInfoField(char *field, int fieldsize, bool align_right)
  549. {
  550. if (align_right)
  551. {
  552. // Right align and trim spaces on either side
  553. int dst = fieldsize - 1;
  554. for (int src = fieldsize - 1; src >= 0; src--)
  555. {
  556. char c = field[src];
  557. if (c < 0x20 || c > 0x7E) c = 0x20;
  558. if (c != 0x20 || dst != fieldsize - 1)
  559. {
  560. field[dst--] = c;
  561. }
  562. }
  563. while (dst >= 0)
  564. {
  565. field[dst--] = 0x20;
  566. }
  567. }
  568. else
  569. {
  570. // Left align, preserve spaces in case config tries to manually right-align
  571. int dst = 0;
  572. for (int src = 0; src < fieldsize; src++)
  573. {
  574. char c = field[src];
  575. if (c < 0x20 || c > 0x7E) c = 0x20;
  576. field[dst++] = c;
  577. }
  578. while (dst < fieldsize)
  579. {
  580. field[dst++] = 0x20;
  581. }
  582. }
  583. }
  584. // Set default drive vendor / product info after the image file
  585. // is loaded and the device type is known.
  586. static void setDefaultDriveInfo(int target_idx)
  587. {
  588. image_config_t &img = g_DiskImages[target_idx];
  589. static const char *driveinfo_fixed[4] = DRIVEINFO_FIXED;
  590. static const char *driveinfo_removable[4] = DRIVEINFO_REMOVABLE;
  591. static const char *driveinfo_optical[4] = DRIVEINFO_OPTICAL;
  592. static const char *driveinfo_floppy[4] = DRIVEINFO_FLOPPY;
  593. static const char *driveinfo_magopt[4] = DRIVEINFO_MAGOPT;
  594. static const char *driveinfo_tape[4] = DRIVEINFO_TAPE;
  595. static const char *apl_driveinfo_fixed[4] = APPLE_DRIVEINFO_FIXED;
  596. static const char *apl_driveinfo_removable[4] = APPLE_DRIVEINFO_REMOVABLE;
  597. static const char *apl_driveinfo_optical[4] = APPLE_DRIVEINFO_OPTICAL;
  598. static const char *apl_driveinfo_floppy[4] = APPLE_DRIVEINFO_FLOPPY;
  599. static const char *apl_driveinfo_magopt[4] = APPLE_DRIVEINFO_MAGOPT;
  600. static const char *apl_driveinfo_tape[4] = APPLE_DRIVEINFO_TAPE;
  601. const char **driveinfo = NULL;
  602. if (img.quirks == S2S_CFG_QUIRKS_APPLE)
  603. {
  604. // Use default drive IDs that are recognized by Apple machines
  605. switch (img.deviceType)
  606. {
  607. case S2S_CFG_FIXED: driveinfo = apl_driveinfo_fixed; break;
  608. case S2S_CFG_REMOVEABLE: driveinfo = apl_driveinfo_removable; break;
  609. case S2S_CFG_OPTICAL: driveinfo = apl_driveinfo_optical; break;
  610. case S2S_CFG_FLOPPY_14MB: driveinfo = apl_driveinfo_floppy; break;
  611. case S2S_CFG_MO: driveinfo = apl_driveinfo_magopt; break;
  612. case S2S_CFG_SEQUENTIAL: driveinfo = apl_driveinfo_tape; break;
  613. default: driveinfo = apl_driveinfo_fixed; break;
  614. }
  615. }
  616. else
  617. {
  618. // Generic IDs
  619. switch (img.deviceType)
  620. {
  621. case S2S_CFG_FIXED: driveinfo = driveinfo_fixed; break;
  622. case S2S_CFG_REMOVEABLE: driveinfo = driveinfo_removable; break;
  623. case S2S_CFG_OPTICAL: driveinfo = driveinfo_optical; break;
  624. case S2S_CFG_FLOPPY_14MB: driveinfo = driveinfo_floppy; break;
  625. case S2S_CFG_MO: driveinfo = driveinfo_magopt; break;
  626. case S2S_CFG_SEQUENTIAL: driveinfo = driveinfo_tape; break;
  627. default: driveinfo = driveinfo_fixed; break;
  628. }
  629. }
  630. if (img.vendor[0] == '\0')
  631. {
  632. memset(img.vendor, 0, sizeof(img.vendor));
  633. strncpy(img.vendor, driveinfo[0], sizeof(img.vendor));
  634. }
  635. if (img.prodId[0] == '\0')
  636. {
  637. memset(img.prodId, 0, sizeof(img.prodId));
  638. strncpy(img.prodId, driveinfo[1], sizeof(img.prodId));
  639. }
  640. if (img.revision[0] == '\0')
  641. {
  642. memset(img.revision, 0, sizeof(img.revision));
  643. strncpy(img.revision, driveinfo[2], sizeof(img.revision));
  644. }
  645. if (img.serial[0] == '\0')
  646. {
  647. memset(img.serial, 0, sizeof(img.serial));
  648. strncpy(img.serial, driveinfo[3], sizeof(img.serial));
  649. }
  650. if (img.serial[0] == '\0')
  651. {
  652. // Use SD card serial number
  653. cid_t sd_cid;
  654. uint32_t sd_sn = 0;
  655. if (SD.card()->readCID(&sd_cid))
  656. {
  657. sd_sn = sd_cid.psn();
  658. }
  659. memset(img.serial, 0, sizeof(img.serial));
  660. const char *nibble = "0123456789ABCDEF";
  661. img.serial[0] = nibble[(sd_sn >> 28) & 0xF];
  662. img.serial[1] = nibble[(sd_sn >> 24) & 0xF];
  663. img.serial[2] = nibble[(sd_sn >> 20) & 0xF];
  664. img.serial[3] = nibble[(sd_sn >> 16) & 0xF];
  665. img.serial[4] = nibble[(sd_sn >> 12) & 0xF];
  666. img.serial[5] = nibble[(sd_sn >> 8) & 0xF];
  667. img.serial[6] = nibble[(sd_sn >> 4) & 0xF];
  668. img.serial[7] = nibble[(sd_sn >> 0) & 0xF];
  669. }
  670. int rightAlign = img.rightAlignStrings;
  671. formatDriveInfoField(img.vendor, sizeof(img.vendor), rightAlign);
  672. formatDriveInfoField(img.prodId, sizeof(img.prodId), rightAlign);
  673. formatDriveInfoField(img.revision, sizeof(img.revision), rightAlign);
  674. formatDriveInfoField(img.serial, sizeof(img.serial), true);
  675. }
  676. bool scsiDiskOpenHDDImage(int target_idx, const char *filename, int scsi_id, int scsi_lun, int blocksize, S2S_CFG_TYPE type)
  677. {
  678. image_config_t &img = g_DiskImages[target_idx];
  679. img.file = ImageBackingStore(filename, blocksize);
  680. if (img.file.isOpen())
  681. {
  682. img.bytesPerSector = blocksize;
  683. img.scsiSectors = img.file.size() / blocksize;
  684. img.scsiId = scsi_id | S2S_CFG_TARGET_ENABLED;
  685. img.sdSectorStart = 0;
  686. if (img.scsiSectors == 0)
  687. {
  688. logmsg("---- Error: image file ", filename, " is empty");
  689. img.file.close();
  690. return false;
  691. }
  692. uint32_t sector_begin = 0, sector_end = 0;
  693. if (img.file.isRom())
  694. {
  695. // ROM is always contiguous, no need to log
  696. }
  697. else if (img.file.contiguousRange(&sector_begin, &sector_end))
  698. {
  699. dbgmsg("---- Image file is contiguous, SD card sectors ", (int)sector_begin, " to ", (int)sector_end);
  700. }
  701. else
  702. {
  703. logmsg("---- WARNING: file ", filename, " is not contiguous. This will increase read latency.");
  704. }
  705. if (type == S2S_CFG_OPTICAL)
  706. {
  707. logmsg("---- Configuring as CD-ROM drive based on image name");
  708. img.deviceType = S2S_CFG_OPTICAL;
  709. }
  710. else if (type == S2S_CFG_FLOPPY_14MB)
  711. {
  712. logmsg("---- Configuring as floppy drive based on image name");
  713. img.deviceType = S2S_CFG_FLOPPY_14MB;
  714. }
  715. else if (type == S2S_CFG_MO)
  716. {
  717. logmsg("---- Configuring as magneto-optical based on image name");
  718. img.deviceType = S2S_CFG_MO;
  719. }
  720. else if (type == S2S_CFG_REMOVEABLE)
  721. {
  722. logmsg("---- Configuring as removable drive based on image name");
  723. img.deviceType = S2S_CFG_REMOVEABLE;
  724. }
  725. else if (type == S2S_CFG_SEQUENTIAL)
  726. {
  727. logmsg("---- Configuring as tape drive based on image name");
  728. img.deviceType = S2S_CFG_SEQUENTIAL;
  729. }
  730. #ifdef PLATFORM_CONFIG_HOOK
  731. PLATFORM_CONFIG_HOOK(&img);
  732. #endif
  733. setDefaultDriveInfo(target_idx);
  734. if (img.prefetchbytes > 0)
  735. {
  736. logmsg("---- Read prefetch enabled: ", (int)img.prefetchbytes, " bytes");
  737. }
  738. else
  739. {
  740. logmsg("---- Read prefetch disabled");
  741. }
  742. return true;
  743. }
  744. return false;
  745. }
  746. static void checkDiskGeometryDivisible(image_config_t &img)
  747. {
  748. if (!img.geometrywarningprinted)
  749. {
  750. uint32_t sectorsPerHeadTrack = img.sectorsPerTrack * img.headsPerCylinder;
  751. if (img.scsiSectors % sectorsPerHeadTrack != 0)
  752. {
  753. logmsg("WARNING: Host used command ", scsiDev.cdb[0],
  754. " which is affected by drive geometry. Current settings are ",
  755. (int)img.sectorsPerTrack, " sectors x ", (int)img.headsPerCylinder, " heads = ",
  756. (int)sectorsPerHeadTrack, " but image size of ", (int)img.scsiSectors,
  757. " sectors is not divisible. This can cause error messages in diagnostics tools.");
  758. img.geometrywarningprinted = true;
  759. }
  760. }
  761. }
  762. // Set target configuration to default values
  763. static void scsiDiskConfigDefaults(int target_idx)
  764. {
  765. // Get default values from system preset, if any
  766. char presetName[32];
  767. ini_gets("SCSI", "System", "", presetName, sizeof(presetName), CONFIGFILE);
  768. preset_config_t defaults = getSystemPreset(presetName);
  769. image_config_t &img = g_DiskImages[target_idx];
  770. img.deviceType = S2S_CFG_FIXED;
  771. img.deviceTypeModifier = defaults.deviceTypeModifier;
  772. img.sectorsPerTrack = defaults.sectorsPerTrack;
  773. img.headsPerCylinder = defaults.headsPerCylinder;
  774. img.quirks = defaults.quirks;
  775. img.prefetchbytes = defaults.prefetchBytes;
  776. memset(img.vendor, 0, sizeof(img.vendor));
  777. memset(img.prodId, 0, sizeof(img.prodId));
  778. memset(img.revision, 0, sizeof(img.revision));
  779. memset(img.serial, 0, sizeof(img.serial));
  780. }
  781. // Load values for target configuration from given section if they exist.
  782. // Otherwise keep current settings.
  783. static void scsiDiskLoadConfig(int target_idx, const char *section)
  784. {
  785. image_config_t &img = g_DiskImages[target_idx];
  786. img.deviceType = ini_getl(section, "Type", img.deviceType, CONFIGFILE);
  787. img.deviceTypeModifier = ini_getl(section, "TypeModifier", img.deviceTypeModifier, CONFIGFILE);
  788. img.sectorsPerTrack = ini_getl(section, "SectorsPerTrack", img.sectorsPerTrack, CONFIGFILE);
  789. img.headsPerCylinder = ini_getl(section, "HeadsPerCylinder", img.headsPerCylinder, CONFIGFILE);
  790. img.quirks = ini_getl(section, "Quirks", img.quirks, CONFIGFILE);
  791. img.rightAlignStrings = ini_getbool(section, "RightAlignStrings", 0, CONFIGFILE);
  792. img.prefetchbytes = ini_getl(section, "PrefetchBytes", img.prefetchbytes, CONFIGFILE);
  793. img.reinsert_on_inquiry = ini_getbool(section, "ReinsertCDOnInquiry", 1, CONFIGFILE);
  794. char tmp[32];
  795. memset(tmp, 0, sizeof(tmp));
  796. ini_gets(section, "Vendor", "", tmp, sizeof(tmp), CONFIGFILE);
  797. if (tmp[0]) memcpy(img.vendor, tmp, sizeof(img.vendor));
  798. memset(tmp, 0, sizeof(tmp));
  799. ini_gets(section, "Product", "", tmp, sizeof(tmp), CONFIGFILE);
  800. if (tmp[0]) memcpy(img.prodId, tmp, sizeof(img.prodId));
  801. memset(tmp, 0, sizeof(tmp));
  802. ini_gets(section, "Version", "", tmp, sizeof(tmp), CONFIGFILE);
  803. if (tmp[0]) memcpy(img.revision, tmp, sizeof(img.revision));
  804. memset(tmp, 0, sizeof(tmp));
  805. ini_gets(section, "Serial", "", tmp, sizeof(tmp), CONFIGFILE);
  806. if (tmp[0]) memcpy(img.serial, tmp, sizeof(img.serial));
  807. }
  808. // Check if image file name is overridden in config
  809. static bool get_image_name(int target_idx, char *buf, size_t buflen)
  810. {
  811. image_config_t &img = g_DiskImages[target_idx];
  812. char section[6] = "SCSI0";
  813. section[4] = '0' + target_idx;
  814. char key[5] = "IMG0";
  815. key[3] = '0' + img.image_index;
  816. ini_gets(section, key, "", buf, buflen, CONFIGFILE);
  817. return buf[0] != '\0';
  818. }
  819. void scsiDiskLoadConfig(int target_idx)
  820. {
  821. char section[6] = "SCSI0";
  822. section[4] = '0' + target_idx;
  823. // Set default settings
  824. scsiDiskConfigDefaults(target_idx);
  825. // First load global settings
  826. scsiDiskLoadConfig(target_idx, "SCSI");
  827. // Then settings specific to target ID
  828. scsiDiskLoadConfig(target_idx, section);
  829. // Check if we have image specified by name
  830. char filename[MAX_FILE_PATH];
  831. if (get_image_name(target_idx, filename, sizeof(filename)))
  832. {
  833. image_config_t &img = g_DiskImages[target_idx];
  834. int blocksize = (img.deviceType == S2S_CFG_OPTICAL) ? 2048 : 512;
  835. logmsg("-- Opening ", filename, " for id:", target_idx, ", specified in " CONFIGFILE);
  836. scsiDiskOpenHDDImage(target_idx, filename, target_idx, 0, blocksize);
  837. }
  838. }
  839. bool scsiDiskCheckAnyImagesConfigured()
  840. {
  841. for (int i = 0; i < S2S_MAX_TARGETS; i++)
  842. {
  843. if (g_DiskImages[i].file.isOpen() && (g_DiskImages[i].scsiId & S2S_CFG_TARGET_ENABLED))
  844. {
  845. return true;
  846. }
  847. }
  848. return false;
  849. }
  850. /*******************************/
  851. /* Config handling for SCSI2SD */
  852. /*******************************/
  853. extern "C"
  854. void s2s_configInit(S2S_BoardCfg* config)
  855. {
  856. if (SD.exists(CONFIGFILE))
  857. {
  858. logmsg("Reading configuration from " CONFIGFILE);
  859. }
  860. else
  861. {
  862. logmsg("Config file " CONFIGFILE " not found, using defaults");
  863. }
  864. // Get default values from system preset, if any
  865. char presetName[32];
  866. ini_gets("SCSI", "System", "", presetName, sizeof(presetName), CONFIGFILE);
  867. preset_config_t defaults = getSystemPreset(presetName);
  868. if (defaults.presetName)
  869. {
  870. logmsg("Active configuration (using system preset \"", defaults.presetName, "\"):");
  871. }
  872. else
  873. {
  874. logmsg("Active configuration:");
  875. }
  876. memset(config, 0, sizeof(S2S_BoardCfg));
  877. memcpy(config->magic, "BCFG", 4);
  878. config->flags = 0;
  879. config->startupDelay = 0;
  880. config->selectionDelay = ini_getl("SCSI", "SelectionDelay", defaults.selectionDelay, CONFIGFILE);
  881. config->flags6 = 0;
  882. config->scsiSpeed = PLATFORM_MAX_SCSI_SPEED;
  883. int maxSyncSpeed = ini_getl("SCSI", "MaxSyncSpeed", defaults.maxSyncSpeed, CONFIGFILE);
  884. if (maxSyncSpeed < 5 && config->scsiSpeed > S2S_CFG_SPEED_ASYNC_50)
  885. config->scsiSpeed = S2S_CFG_SPEED_ASYNC_50;
  886. else if (maxSyncSpeed < 10 && config->scsiSpeed > S2S_CFG_SPEED_SYNC_5)
  887. config->scsiSpeed = S2S_CFG_SPEED_SYNC_5;
  888. logmsg("-- SelectionDelay = ", (int)config->selectionDelay);
  889. if (ini_getbool("SCSI", "EnableUnitAttention", defaults.enableUnitAttention, CONFIGFILE))
  890. {
  891. logmsg("-- EnableUnitAttention = Yes");
  892. config->flags |= S2S_CFG_ENABLE_UNIT_ATTENTION;
  893. }
  894. else
  895. {
  896. logmsg("-- EnableUnitAttention = No");
  897. }
  898. if (ini_getbool("SCSI", "EnableSCSI2", defaults.enableSCSI2, CONFIGFILE))
  899. {
  900. logmsg("-- EnableSCSI2 = Yes");
  901. config->flags |= S2S_CFG_ENABLE_SCSI2;
  902. }
  903. else
  904. {
  905. logmsg("-- EnableSCSI2 = No");
  906. }
  907. if (ini_getbool("SCSI", "EnableSelLatch", defaults.enableSelLatch, CONFIGFILE))
  908. {
  909. logmsg("-- EnableSelLatch = Yes");
  910. config->flags |= S2S_CFG_ENABLE_SEL_LATCH;
  911. }
  912. else
  913. {
  914. logmsg("-- EnableSelLatch = No");
  915. }
  916. if (ini_getbool("SCSI", "MapLunsToIDs", defaults.mapLunsToIDs, CONFIGFILE))
  917. {
  918. logmsg("-- MapLunsToIDs = Yes");
  919. config->flags |= S2S_CFG_MAP_LUNS_TO_IDS;
  920. }
  921. else
  922. {
  923. logmsg("-- MapLunsToIDs = No");
  924. }
  925. #ifdef PLATFORM_HAS_PARITY_CHECK
  926. if (ini_getbool("SCSI", "EnableParity", defaults.enableParity, CONFIGFILE))
  927. {
  928. logmsg("-- EnableParity = Yes");
  929. config->flags |= S2S_CFG_ENABLE_PARITY;
  930. }
  931. else
  932. {
  933. logmsg("-- EnableParity = No");
  934. }
  935. #endif
  936. }
  937. extern "C"
  938. void s2s_debugInit(void)
  939. {
  940. }
  941. extern "C"
  942. void s2s_configPoll(void)
  943. {
  944. }
  945. extern "C"
  946. void s2s_configSave(int scsiId, uint16_t byesPerSector)
  947. {
  948. // Modification of config over SCSI bus is not implemented.
  949. }
  950. extern "C"
  951. const S2S_TargetCfg* s2s_getConfigByIndex(int index)
  952. {
  953. if (index < 0 || index >= S2S_MAX_TARGETS)
  954. {
  955. return NULL;
  956. }
  957. else
  958. {
  959. return &g_DiskImages[index];
  960. }
  961. }
  962. extern "C"
  963. const S2S_TargetCfg* s2s_getConfigById(int scsiId)
  964. {
  965. int i;
  966. for (i = 0; i < S2S_MAX_TARGETS; ++i)
  967. {
  968. const S2S_TargetCfg* tgt = s2s_getConfigByIndex(i);
  969. if ((tgt->scsiId & S2S_CFG_TARGET_ID_BITS) == scsiId &&
  970. (tgt->scsiId & S2S_CFG_TARGET_ENABLED))
  971. {
  972. return tgt;
  973. }
  974. }
  975. return NULL;
  976. }
  977. /**********************/
  978. /* FormatUnit command */
  979. /**********************/
  980. // Callback once all data has been read in the data out phase.
  981. static void doFormatUnitComplete(void)
  982. {
  983. scsiDev.phase = STATUS;
  984. }
  985. static void doFormatUnitSkipData(int bytes)
  986. {
  987. // We may not have enough memory to store the initialisation pattern and
  988. // defect list data. Since we're not making use of it yet anyway, just
  989. // discard the bytes.
  990. scsiEnterPhase(DATA_OUT);
  991. int i;
  992. for (i = 0; i < bytes; ++i)
  993. {
  994. scsiReadByte();
  995. }
  996. }
  997. // Callback from the data out phase.
  998. static void doFormatUnitPatternHeader(void)
  999. {
  1000. int defectLength =
  1001. ((((uint16_t)scsiDev.data[2])) << 8) +
  1002. scsiDev.data[3];
  1003. int patternLength =
  1004. ((((uint16_t)scsiDev.data[4 + 2])) << 8) +
  1005. scsiDev.data[4 + 3];
  1006. doFormatUnitSkipData(defectLength + patternLength);
  1007. doFormatUnitComplete();
  1008. }
  1009. // Callback from the data out phase.
  1010. static void doFormatUnitHeader(void)
  1011. {
  1012. int IP = (scsiDev.data[1] & 0x08) ? 1 : 0;
  1013. int DSP = (scsiDev.data[1] & 0x04) ? 1 : 0;
  1014. if (! DSP) // disable save parameters
  1015. {
  1016. // Save the "MODE SELECT savable parameters"
  1017. s2s_configSave(
  1018. scsiDev.target->targetId,
  1019. scsiDev.target->liveCfg.bytesPerSector);
  1020. }
  1021. if (IP)
  1022. {
  1023. // We need to read the initialisation pattern header first.
  1024. scsiDev.dataLen += 4;
  1025. scsiDev.phase = DATA_OUT;
  1026. scsiDev.postDataOutHook = doFormatUnitPatternHeader;
  1027. }
  1028. else
  1029. {
  1030. // Read the defect list data
  1031. int defectLength =
  1032. ((((uint16_t)scsiDev.data[2])) << 8) +
  1033. scsiDev.data[3];
  1034. doFormatUnitSkipData(defectLength);
  1035. doFormatUnitComplete();
  1036. }
  1037. }
  1038. /************************/
  1039. /* ReadCapacity command */
  1040. /************************/
  1041. static void doReadCapacity()
  1042. {
  1043. uint32_t lba = (((uint32_t) scsiDev.cdb[2]) << 24) +
  1044. (((uint32_t) scsiDev.cdb[3]) << 16) +
  1045. (((uint32_t) scsiDev.cdb[4]) << 8) +
  1046. scsiDev.cdb[5];
  1047. int pmi = scsiDev.cdb[8] & 1;
  1048. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1049. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  1050. uint32_t capacity = img.file.size() / bytesPerSector;
  1051. if (!pmi && lba)
  1052. {
  1053. // error.
  1054. // We don't do anything with the "partial medium indicator", and
  1055. // assume that delays are constant across each block. But the spec
  1056. // says we must return this error if pmi is specified incorrectly.
  1057. scsiDev.status = CHECK_CONDITION;
  1058. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  1059. scsiDev.target->sense.asc = INVALID_FIELD_IN_CDB;
  1060. scsiDev.phase = STATUS;
  1061. }
  1062. else if (capacity > 0)
  1063. {
  1064. uint32_t highestBlock = capacity - 1;
  1065. scsiDev.data[0] = highestBlock >> 24;
  1066. scsiDev.data[1] = highestBlock >> 16;
  1067. scsiDev.data[2] = highestBlock >> 8;
  1068. scsiDev.data[3] = highestBlock;
  1069. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  1070. scsiDev.data[4] = bytesPerSector >> 24;
  1071. scsiDev.data[5] = bytesPerSector >> 16;
  1072. scsiDev.data[6] = bytesPerSector >> 8;
  1073. scsiDev.data[7] = bytesPerSector;
  1074. scsiDev.dataLen = 8;
  1075. scsiDev.phase = DATA_IN;
  1076. }
  1077. else
  1078. {
  1079. scsiDev.status = CHECK_CONDITION;
  1080. scsiDev.target->sense.code = NOT_READY;
  1081. scsiDev.target->sense.asc = MEDIUM_NOT_PRESENT;
  1082. scsiDev.phase = STATUS;
  1083. }
  1084. }
  1085. /*************************/
  1086. /* TestUnitReady command */
  1087. /*************************/
  1088. // Check if we have multiple CD-ROM images to cycle when drive is ejected.
  1089. static bool checkNextCDImage()
  1090. {
  1091. // Check if we have a next image to load, so that drive is closed next time the host asks.
  1092. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1093. img.image_index++;
  1094. char filename[MAX_FILE_PATH];
  1095. int target_idx = img.scsiId & 7;
  1096. if (!get_image_name(target_idx, filename, sizeof(filename)))
  1097. {
  1098. img.image_index = 0;
  1099. get_image_name(target_idx, filename, sizeof(filename));
  1100. }
  1101. if (filename[0] != '\0')
  1102. {
  1103. logmsg("Switching to next CD-ROM image for ", target_idx, ": ", filename);
  1104. image_config_t &img = g_DiskImages[target_idx];
  1105. img.file.close();
  1106. bool status = scsiDiskOpenHDDImage(target_idx, filename, target_idx, 0, 2048);
  1107. if (status)
  1108. {
  1109. img.ejected = false;
  1110. img.cdrom_events = 2; // New media
  1111. return true;
  1112. }
  1113. }
  1114. return false;
  1115. }
  1116. // Reinsert any ejected CDROMs on reboot
  1117. static void reinsertCDROM(image_config_t &img)
  1118. {
  1119. if (img.image_index > 0)
  1120. {
  1121. // Multiple images for this drive, force restart from first one
  1122. dbgmsg("---- Restarting from first CD-ROM image");
  1123. img.image_index = 9;
  1124. checkNextCDImage();
  1125. }
  1126. else if (img.ejected)
  1127. {
  1128. // Reinsert the single image
  1129. dbgmsg("---- Closing CD-ROM tray");
  1130. img.ejected = false;
  1131. img.cdrom_events = 2; // New media
  1132. }
  1133. }
  1134. static int doTestUnitReady()
  1135. {
  1136. int ready = 1;
  1137. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1138. if (unlikely(!scsiDev.target->started || !img.file.isOpen()))
  1139. {
  1140. ready = 0;
  1141. scsiDev.status = CHECK_CONDITION;
  1142. scsiDev.target->sense.code = NOT_READY;
  1143. scsiDev.target->sense.asc = LOGICAL_UNIT_NOT_READY_INITIALIZING_COMMAND_REQUIRED;
  1144. scsiDev.phase = STATUS;
  1145. }
  1146. else if (img.ejected)
  1147. {
  1148. ready = 0;
  1149. scsiDev.status = CHECK_CONDITION;
  1150. scsiDev.target->sense.code = NOT_READY;
  1151. scsiDev.target->sense.asc = MEDIUM_NOT_PRESENT;
  1152. scsiDev.phase = STATUS;
  1153. // We are now reporting to host that the drive is open.
  1154. // Simulate a "close" for next time the host polls.
  1155. checkNextCDImage();
  1156. }
  1157. else if (unlikely(!(blockDev.state & DISK_PRESENT)))
  1158. {
  1159. ready = 0;
  1160. scsiDev.status = CHECK_CONDITION;
  1161. scsiDev.target->sense.code = NOT_READY;
  1162. scsiDev.target->sense.asc = MEDIUM_NOT_PRESENT;
  1163. scsiDev.phase = STATUS;
  1164. }
  1165. else if (unlikely(!(blockDev.state & DISK_INITIALISED)))
  1166. {
  1167. ready = 0;
  1168. scsiDev.status = CHECK_CONDITION;
  1169. scsiDev.target->sense.code = NOT_READY;
  1170. scsiDev.target->sense.asc = LOGICAL_UNIT_NOT_READY_CAUSE_NOT_REPORTABLE;
  1171. scsiDev.phase = STATUS;
  1172. }
  1173. return ready;
  1174. }
  1175. static void doGetEventStatusNotification(bool immed)
  1176. {
  1177. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1178. if (!immed)
  1179. {
  1180. // Asynchronous notification not supported
  1181. scsiDev.status = CHECK_CONDITION;
  1182. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  1183. scsiDev.target->sense.asc = INVALID_FIELD_IN_CDB;
  1184. scsiDev.phase = STATUS;
  1185. }
  1186. else if (img.cdrom_events)
  1187. {
  1188. scsiDev.data[0] = 0;
  1189. scsiDev.data[1] = 6; // EventDataLength
  1190. scsiDev.data[2] = 0x04; // Media status events
  1191. scsiDev.data[3] = 0x04; // Supported events
  1192. scsiDev.data[4] = img.cdrom_events;
  1193. scsiDev.data[5] = 0x01; // Power status
  1194. scsiDev.data[6] = 0; // Start slot
  1195. scsiDev.data[7] = 0; // End slot
  1196. scsiDev.dataLen = 8;
  1197. scsiDev.phase = DATA_IN;
  1198. img.cdrom_events = 0;
  1199. if (img.ejected)
  1200. {
  1201. // We are now reporting to host that the drive is open.
  1202. // Simulate a "close" for next time the host polls.
  1203. checkNextCDImage();
  1204. }
  1205. }
  1206. else
  1207. {
  1208. scsiDev.data[0] = 0;
  1209. scsiDev.data[1] = 2; // EventDataLength
  1210. scsiDev.data[2] = 0x00; // Media status events
  1211. scsiDev.data[3] = 0x04; // Supported events
  1212. scsiDev.dataLen = 4;
  1213. scsiDev.phase = DATA_IN;
  1214. }
  1215. }
  1216. /****************/
  1217. /* Seek command */
  1218. /****************/
  1219. static void doSeek(uint32_t lba)
  1220. {
  1221. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1222. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  1223. uint32_t capacity = img.file.size() / bytesPerSector;
  1224. if (lba >= capacity)
  1225. {
  1226. scsiDev.status = CHECK_CONDITION;
  1227. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  1228. scsiDev.target->sense.asc = LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
  1229. scsiDev.phase = STATUS;
  1230. }
  1231. else
  1232. {
  1233. if (unlikely(scsiDev.target->cfg->deviceType == S2S_CFG_FLOPPY_14MB) ||
  1234. scsiDev.compatMode < COMPAT_SCSI2)
  1235. {
  1236. s2s_delay_ms(10);
  1237. }
  1238. else
  1239. {
  1240. s2s_delay_us(10);
  1241. }
  1242. }
  1243. }
  1244. /********************************************/
  1245. /* Transfer state for read / write commands */
  1246. /********************************************/
  1247. BlockDevice blockDev = {DISK_PRESENT | DISK_INITIALISED};
  1248. Transfer transfer;
  1249. static struct {
  1250. uint8_t *buffer;
  1251. uint32_t bytes_sd; // Number of bytes that have been scheduled for transfer on SD card side
  1252. uint32_t bytes_scsi; // Number of bytes that have been scheduled for transfer on SCSI side
  1253. uint32_t bytes_scsi_started;
  1254. uint32_t sd_transfer_start;
  1255. int parityError;
  1256. } g_disk_transfer;
  1257. #ifdef PREFETCH_BUFFER_SIZE
  1258. static struct {
  1259. uint8_t buffer[PREFETCH_BUFFER_SIZE];
  1260. uint32_t sector;
  1261. uint32_t bytes;
  1262. uint8_t scsiId;
  1263. } g_scsi_prefetch;
  1264. #endif
  1265. /*****************/
  1266. /* Write command */
  1267. /*****************/
  1268. static void doWrite(uint32_t lba, uint32_t blocks)
  1269. {
  1270. if (unlikely(scsiDev.target->cfg->deviceType == S2S_CFG_FLOPPY_14MB)) {
  1271. // Floppies are supposed to be slow. Some systems can't handle a floppy
  1272. // without an access time
  1273. s2s_delay_ms(10);
  1274. }
  1275. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1276. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  1277. uint32_t capacity = img.file.size() / bytesPerSector;
  1278. dbgmsg("------ Write ", (int)blocks, "x", (int)bytesPerSector, " starting at ", (int)lba);
  1279. if (unlikely(blockDev.state & DISK_WP) ||
  1280. unlikely(scsiDev.target->cfg->deviceType == S2S_CFG_OPTICAL) ||
  1281. unlikely(!img.file.isWritable()))
  1282. {
  1283. logmsg("WARNING: Host attempted write to read-only drive ID ", (int)(img.scsiId & S2S_CFG_TARGET_ID_BITS));
  1284. scsiDev.status = CHECK_CONDITION;
  1285. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  1286. scsiDev.target->sense.asc = WRITE_PROTECTED;
  1287. scsiDev.phase = STATUS;
  1288. }
  1289. else if (unlikely(((uint64_t) lba) + blocks > capacity))
  1290. {
  1291. logmsg("WARNING: Host attempted write at sector ", (int)lba, "+", (int)blocks,
  1292. ", exceeding image size ", (int)capacity, " sectors (",
  1293. (int)bytesPerSector, "B/sector)");
  1294. scsiDev.status = CHECK_CONDITION;
  1295. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  1296. scsiDev.target->sense.asc = LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
  1297. scsiDev.phase = STATUS;
  1298. }
  1299. else
  1300. {
  1301. transfer.multiBlock = true;
  1302. transfer.lba = lba;
  1303. transfer.blocks = blocks;
  1304. transfer.currentBlock = 0;
  1305. scsiDev.phase = DATA_OUT;
  1306. scsiDev.dataLen = 0;
  1307. scsiDev.dataPtr = 0;
  1308. #ifdef PREFETCH_BUFFER_SIZE
  1309. // Invalidate prefetch buffer
  1310. g_scsi_prefetch.bytes = 0;
  1311. g_scsi_prefetch.sector = 0;
  1312. #endif
  1313. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1314. if (!img.file.seek((uint64_t)transfer.lba * bytesPerSector))
  1315. {
  1316. logmsg("Seek to ", transfer.lba, " failed for SCSI ID", (int)scsiDev.target->targetId);
  1317. scsiDev.status = CHECK_CONDITION;
  1318. scsiDev.target->sense.code = MEDIUM_ERROR;
  1319. scsiDev.target->sense.asc = NO_SEEK_COMPLETE;
  1320. scsiDev.phase = STATUS;
  1321. }
  1322. }
  1323. }
  1324. // Called to transfer next block from SCSI bus.
  1325. // Usually called from SD card driver during waiting for SD card access.
  1326. void diskDataOut_callback(uint32_t bytes_complete)
  1327. {
  1328. // For best performance, do SCSI reads in blocks of 4 or more bytes
  1329. bytes_complete &= ~3;
  1330. if (g_disk_transfer.bytes_scsi_started < g_disk_transfer.bytes_scsi)
  1331. {
  1332. // How many bytes remaining in the transfer?
  1333. uint32_t remain = g_disk_transfer.bytes_scsi - g_disk_transfer.bytes_scsi_started;
  1334. uint32_t len = remain;
  1335. // Split read so that it doesn't wrap around buffer edge
  1336. uint32_t bufsize = sizeof(scsiDev.data);
  1337. uint32_t start = (g_disk_transfer.bytes_scsi_started % bufsize);
  1338. if (start + len > bufsize)
  1339. len = bufsize - start;
  1340. // Apply platform-specific optimized transfer sizes
  1341. if (len > PLATFORM_OPTIMAL_SCSI_READ_BLOCK_SIZE)
  1342. {
  1343. len = PLATFORM_OPTIMAL_SCSI_READ_BLOCK_SIZE;
  1344. }
  1345. // Don't overwrite data that has not yet been written to SD card
  1346. uint32_t sd_ready_cnt = g_disk_transfer.bytes_sd + bytes_complete;
  1347. if (g_disk_transfer.bytes_scsi_started + len > sd_ready_cnt + bufsize)
  1348. len = sd_ready_cnt + bufsize - g_disk_transfer.bytes_scsi_started;
  1349. // Keep transfers a multiple of sector size.
  1350. // Macintosh SCSI driver seems to get confused if we have a delay
  1351. // in middle of a sector.
  1352. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  1353. if (remain >= bytesPerSector && len % bytesPerSector != 0)
  1354. {
  1355. len -= len % bytesPerSector;
  1356. }
  1357. if (len == 0)
  1358. return;
  1359. // dbgmsg("SCSI read ", (int)start, " + ", (int)len);
  1360. scsiStartRead(&scsiDev.data[start], len, &g_disk_transfer.parityError);
  1361. g_disk_transfer.bytes_scsi_started += len;
  1362. }
  1363. }
  1364. void diskDataOut()
  1365. {
  1366. scsiEnterPhase(DATA_OUT);
  1367. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1368. uint32_t blockcount = (transfer.blocks - transfer.currentBlock);
  1369. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  1370. g_disk_transfer.buffer = scsiDev.data;
  1371. g_disk_transfer.bytes_scsi = blockcount * bytesPerSector;
  1372. g_disk_transfer.bytes_sd = 0;
  1373. g_disk_transfer.bytes_scsi_started = 0;
  1374. g_disk_transfer.sd_transfer_start = 0;
  1375. g_disk_transfer.parityError = 0;
  1376. while (g_disk_transfer.bytes_sd < g_disk_transfer.bytes_scsi
  1377. && scsiDev.phase == DATA_OUT
  1378. && !scsiDev.resetFlag)
  1379. {
  1380. platform_poll();
  1381. // Figure out how many contiguous bytes are available for writing to SD card.
  1382. uint32_t bufsize = sizeof(scsiDev.data);
  1383. uint32_t start = g_disk_transfer.bytes_sd % bufsize;
  1384. uint32_t len = 0;
  1385. // How much data until buffer edge wrap?
  1386. uint32_t available = g_disk_transfer.bytes_scsi_started - g_disk_transfer.bytes_sd;
  1387. if (start + available > bufsize)
  1388. available = bufsize - start;
  1389. // Count number of finished sectors
  1390. if (scsiIsReadFinished(&scsiDev.data[start + available - 1]))
  1391. {
  1392. len = available;
  1393. }
  1394. else
  1395. {
  1396. while (len < available && scsiIsReadFinished(&scsiDev.data[start + len + SD_SECTOR_SIZE - 1]))
  1397. {
  1398. len += SD_SECTOR_SIZE;
  1399. }
  1400. }
  1401. // In case the last sector is partial (256 byte SCSI sectors)
  1402. if (len > available)
  1403. {
  1404. len = available;
  1405. }
  1406. // Apply platform-specific write size blocks for optimization
  1407. if (len > PLATFORM_OPTIMAL_MAX_SD_WRITE_SIZE)
  1408. {
  1409. len = PLATFORM_OPTIMAL_MAX_SD_WRITE_SIZE;
  1410. }
  1411. uint32_t remain_in_transfer = g_disk_transfer.bytes_scsi - g_disk_transfer.bytes_sd;
  1412. if (len < bufsize - start && len < remain_in_transfer)
  1413. {
  1414. // Use large write blocks in middle of transfer and smaller at the end of transfer.
  1415. // This improves performance for large writes and reduces latency at end of request.
  1416. uint32_t min_write_size = PLATFORM_OPTIMAL_MIN_SD_WRITE_SIZE;
  1417. if (remain_in_transfer <= PLATFORM_OPTIMAL_MAX_SD_WRITE_SIZE)
  1418. {
  1419. min_write_size = PLATFORM_OPTIMAL_LAST_SD_WRITE_SIZE;
  1420. }
  1421. if (len < min_write_size)
  1422. {
  1423. len = 0;
  1424. }
  1425. }
  1426. if (len == 0)
  1427. {
  1428. // Nothing ready to transfer, check if we can read more from SCSI bus
  1429. diskDataOut_callback(0);
  1430. }
  1431. else
  1432. {
  1433. // Finalize transfer on SCSI side
  1434. scsiFinishRead(&scsiDev.data[start], len, &g_disk_transfer.parityError);
  1435. // Check parity error status before writing to SD card
  1436. if (g_disk_transfer.parityError)
  1437. {
  1438. scsiDev.status = CHECK_CONDITION;
  1439. scsiDev.target->sense.code = ABORTED_COMMAND;
  1440. scsiDev.target->sense.asc = SCSI_PARITY_ERROR;
  1441. scsiDev.phase = STATUS;
  1442. break;
  1443. }
  1444. // Start writing to SD card and simultaneously start new SCSI transfers
  1445. // when buffer space is freed.
  1446. uint8_t *buf = &scsiDev.data[start];
  1447. g_disk_transfer.sd_transfer_start = start;
  1448. // dbgmsg("SD write ", (int)start, " + ", (int)len, " ", bytearray(buf, len));
  1449. platform_set_sd_callback(&diskDataOut_callback, buf);
  1450. if (img.file.write(buf, len) != len)
  1451. {
  1452. logmsg("SD card write failed: ", SD.sdErrorCode());
  1453. scsiDev.status = CHECK_CONDITION;
  1454. scsiDev.target->sense.code = MEDIUM_ERROR;
  1455. scsiDev.target->sense.asc = WRITE_ERROR_AUTO_REALLOCATION_FAILED;
  1456. scsiDev.phase = STATUS;
  1457. }
  1458. platform_set_sd_callback(NULL, NULL);
  1459. g_disk_transfer.bytes_sd += len;
  1460. }
  1461. }
  1462. // Release SCSI bus
  1463. scsiFinishRead(NULL, 0, &g_disk_transfer.parityError);
  1464. transfer.currentBlock += blockcount;
  1465. scsiDev.dataPtr = scsiDev.dataLen = 0;
  1466. if (transfer.currentBlock == transfer.blocks)
  1467. {
  1468. // Verify that all data has been flushed to disk from SdFat cache.
  1469. // Normally does nothing as we do not change image file size and
  1470. // data writes are not cached.
  1471. img.file.flush();
  1472. }
  1473. }
  1474. /*****************/
  1475. /* Read command */
  1476. /*****************/
  1477. static void doRead(uint32_t lba, uint32_t blocks)
  1478. {
  1479. if (unlikely(scsiDev.target->cfg->deviceType == S2S_CFG_FLOPPY_14MB)) {
  1480. // Floppies are supposed to be slow. Some systems can't handle a floppy
  1481. // without an access time
  1482. s2s_delay_ms(10);
  1483. }
  1484. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1485. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  1486. uint32_t capacity = img.file.size() / bytesPerSector;
  1487. dbgmsg("------ Read ", (int)blocks, "x", (int)bytesPerSector, " starting at ", (int)lba);
  1488. if (unlikely(((uint64_t) lba) + blocks > capacity))
  1489. {
  1490. logmsg("WARNING: Host attempted read at sector ", (int)lba, "+", (int)blocks,
  1491. ", exceeding image size ", (int)capacity, " sectors (",
  1492. (int)bytesPerSector, "B/sector)");
  1493. scsiDev.status = CHECK_CONDITION;
  1494. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  1495. scsiDev.target->sense.asc = LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
  1496. scsiDev.phase = STATUS;
  1497. }
  1498. else
  1499. {
  1500. transfer.multiBlock = 1;
  1501. transfer.lba = lba;
  1502. transfer.blocks = blocks;
  1503. transfer.currentBlock = 0;
  1504. scsiDev.phase = DATA_IN;
  1505. scsiDev.dataLen = 0;
  1506. scsiDev.dataPtr = 0;
  1507. #ifdef PREFETCH_BUFFER_SIZE
  1508. uint32_t sectors_in_prefetch = g_scsi_prefetch.bytes / bytesPerSector;
  1509. if (img.scsiId == g_scsi_prefetch.scsiId &&
  1510. transfer.lba >= g_scsi_prefetch.sector &&
  1511. transfer.lba < g_scsi_prefetch.sector + sectors_in_prefetch)
  1512. {
  1513. // We have the some sectors already in prefetch cache
  1514. scsiEnterPhase(DATA_IN);
  1515. uint32_t start_offset = transfer.lba - g_scsi_prefetch.sector;
  1516. uint32_t count = sectors_in_prefetch - start_offset;
  1517. if (count > transfer.blocks) count = transfer.blocks;
  1518. scsiStartWrite(g_scsi_prefetch.buffer + start_offset * bytesPerSector, count * bytesPerSector);
  1519. dbgmsg("------ Found ", (int)count, " sectors in prefetch cache");
  1520. transfer.currentBlock += count;
  1521. }
  1522. if (transfer.currentBlock == transfer.blocks)
  1523. {
  1524. while (!scsiIsWriteFinished(NULL))
  1525. {
  1526. platform_poll();
  1527. }
  1528. scsiFinishWrite();
  1529. }
  1530. #endif
  1531. if (!img.file.seek((uint64_t)(transfer.lba + transfer.currentBlock) * bytesPerSector))
  1532. {
  1533. logmsg("Seek to ", transfer.lba, " failed for SCSI ID", (int)scsiDev.target->targetId);
  1534. scsiDev.status = CHECK_CONDITION;
  1535. scsiDev.target->sense.code = MEDIUM_ERROR;
  1536. scsiDev.target->sense.asc = NO_SEEK_COMPLETE;
  1537. scsiDev.phase = STATUS;
  1538. }
  1539. }
  1540. }
  1541. void diskDataIn_callback(uint32_t bytes_complete)
  1542. {
  1543. // On SCSI-1 devices the phase change has some extra delays.
  1544. // Doing it here lets the SD card transfer proceed in background.
  1545. scsiEnterPhase(DATA_IN);
  1546. // For best performance, do writes in blocks of 4 or more bytes
  1547. if (bytes_complete < g_disk_transfer.bytes_sd)
  1548. {
  1549. bytes_complete &= ~3;
  1550. }
  1551. // Machintosh SCSI driver can get confused if pauses occur in middle of
  1552. // a sector, so schedule the transfers in sector sized blocks.
  1553. if (bytes_complete < g_disk_transfer.bytes_sd)
  1554. {
  1555. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  1556. if (bytes_complete % bytesPerSector != 0)
  1557. {
  1558. bytes_complete -= bytes_complete % bytesPerSector;
  1559. }
  1560. }
  1561. if (bytes_complete > g_disk_transfer.bytes_scsi)
  1562. {
  1563. // DMA is reading from SD card, bytes_complete bytes have already been read.
  1564. // Send them to SCSI bus now.
  1565. uint32_t len = bytes_complete - g_disk_transfer.bytes_scsi;
  1566. scsiStartWrite(g_disk_transfer.buffer + g_disk_transfer.bytes_scsi, len);
  1567. g_disk_transfer.bytes_scsi += len;
  1568. }
  1569. // Provide a chance for polling request processing
  1570. scsiIsWriteFinished(NULL);
  1571. }
  1572. // Start a data in transfer using given temporary buffer.
  1573. // diskDataIn() below divides the scsiDev.data buffer to two halves for double buffering.
  1574. static void start_dataInTransfer(uint8_t *buffer, uint32_t count)
  1575. {
  1576. g_disk_transfer.buffer = buffer;
  1577. g_disk_transfer.bytes_scsi = 0;
  1578. g_disk_transfer.bytes_sd = count;
  1579. // Verify that previous write using this buffer has finished
  1580. uint32_t start = millis();
  1581. while (!scsiIsWriteFinished(buffer + count - 1) && !scsiDev.resetFlag)
  1582. {
  1583. if ((uint32_t)(millis() - start) > 5000)
  1584. {
  1585. logmsg("start_dataInTransfer() timeout waiting for previous to finish");
  1586. scsiDev.resetFlag = 1;
  1587. }
  1588. platform_poll();
  1589. }
  1590. if (scsiDev.resetFlag) return;
  1591. // Start transferring from SD card
  1592. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1593. platform_set_sd_callback(&diskDataIn_callback, buffer);
  1594. if (img.file.read(buffer, count) != count)
  1595. {
  1596. logmsg("SD card read failed: ", SD.sdErrorCode());
  1597. scsiDev.status = CHECK_CONDITION;
  1598. scsiDev.target->sense.code = MEDIUM_ERROR;
  1599. scsiDev.target->sense.asc = UNRECOVERED_READ_ERROR;
  1600. scsiDev.phase = STATUS;
  1601. }
  1602. diskDataIn_callback(count);
  1603. platform_set_sd_callback(NULL, NULL);
  1604. platform_poll();
  1605. }
  1606. static void diskDataIn()
  1607. {
  1608. // Figure out how many blocks we can fit in buffer
  1609. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  1610. uint32_t maxblocks = sizeof(scsiDev.data) / bytesPerSector;
  1611. uint32_t maxblocks_half = maxblocks / 2;
  1612. // Start transfer in first half of buffer
  1613. // Waits for the previous first half transfer to finish first.
  1614. uint32_t remain = (transfer.blocks - transfer.currentBlock);
  1615. if (remain > 0)
  1616. {
  1617. uint32_t transfer_blocks = std::min(remain, maxblocks_half);
  1618. uint32_t transfer_bytes = transfer_blocks * bytesPerSector;
  1619. start_dataInTransfer(&scsiDev.data[0], transfer_bytes);
  1620. transfer.currentBlock += transfer_blocks;
  1621. }
  1622. // Start transfer in second half of buffer
  1623. // Waits for the previous second half transfer to finish first
  1624. remain = (transfer.blocks - transfer.currentBlock);
  1625. if (remain > 0)
  1626. {
  1627. uint32_t transfer_blocks = std::min(remain, maxblocks_half);
  1628. uint32_t transfer_bytes = transfer_blocks * bytesPerSector;
  1629. start_dataInTransfer(&scsiDev.data[maxblocks_half * bytesPerSector], transfer_bytes);
  1630. transfer.currentBlock += transfer_blocks;
  1631. }
  1632. if (transfer.currentBlock == transfer.blocks)
  1633. {
  1634. // This was the last block, verify that everything finishes
  1635. #ifdef PREFETCH_BUFFER_SIZE
  1636. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1637. int prefetchbytes = img.prefetchbytes;
  1638. if (prefetchbytes > PREFETCH_BUFFER_SIZE) prefetchbytes = PREFETCH_BUFFER_SIZE;
  1639. uint32_t prefetch_sectors = prefetchbytes / bytesPerSector;
  1640. uint32_t img_sector_count = img.file.size() / bytesPerSector;
  1641. g_scsi_prefetch.sector = transfer.lba + transfer.blocks;
  1642. g_scsi_prefetch.bytes = 0;
  1643. g_scsi_prefetch.scsiId = scsiDev.target->cfg->scsiId;
  1644. if (g_scsi_prefetch.sector + prefetch_sectors > img_sector_count)
  1645. {
  1646. // Don't try to read past image end.
  1647. prefetch_sectors = img_sector_count - g_scsi_prefetch.sector;
  1648. }
  1649. while (!scsiIsWriteFinished(NULL) && prefetch_sectors > 0 && !scsiDev.resetFlag)
  1650. {
  1651. platform_poll();
  1652. // Check if prefetch buffer is free
  1653. g_disk_transfer.buffer = g_scsi_prefetch.buffer + g_scsi_prefetch.bytes;
  1654. if (!scsiIsWriteFinished(g_disk_transfer.buffer) ||
  1655. !scsiIsWriteFinished(g_disk_transfer.buffer + bytesPerSector - 1))
  1656. {
  1657. continue;
  1658. }
  1659. // We still have time, prefetch next sectors in case this SCSI request
  1660. // is part of a longer linear read.
  1661. g_disk_transfer.bytes_sd = bytesPerSector;
  1662. g_disk_transfer.bytes_scsi = bytesPerSector; // Tell callback not to send to SCSI
  1663. platform_set_sd_callback(&diskDataIn_callback, g_disk_transfer.buffer);
  1664. int status = img.file.read(g_disk_transfer.buffer, bytesPerSector);
  1665. if (status <= 0)
  1666. {
  1667. logmsg("Prefetch read failed");
  1668. prefetch_sectors = 0;
  1669. break;
  1670. }
  1671. g_scsi_prefetch.bytes += status;
  1672. platform_set_sd_callback(NULL, NULL);
  1673. prefetch_sectors--;
  1674. }
  1675. #endif
  1676. while (!scsiIsWriteFinished(NULL))
  1677. {
  1678. platform_poll();
  1679. }
  1680. scsiFinishWrite();
  1681. }
  1682. }
  1683. /********************/
  1684. /* Command dispatch */
  1685. /********************/
  1686. // Handle direct-access scsi device commands
  1687. extern "C"
  1688. int scsiDiskCommand()
  1689. {
  1690. int commandHandled = 1;
  1691. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1692. uint8_t command = scsiDev.cdb[0];
  1693. if (unlikely(command == 0x1B))
  1694. {
  1695. // START STOP UNIT
  1696. // Enable or disable media access operations.
  1697. //int immed = scsiDev.cdb[1] & 1;
  1698. int start = scsiDev.cdb[4] & 1;
  1699. int loadEject = scsiDev.cdb[4] & 2;
  1700. if (loadEject && img.deviceType == S2S_CFG_OPTICAL)
  1701. {
  1702. if (start)
  1703. {
  1704. dbgmsg("------ CDROM close tray");
  1705. img.ejected = false;
  1706. img.cdrom_events = 2; // New media
  1707. }
  1708. else
  1709. {
  1710. dbgmsg("------ CDROM open tray");
  1711. img.ejected = true;
  1712. img.cdrom_events = 3; // Media removal
  1713. }
  1714. }
  1715. else if (start)
  1716. {
  1717. scsiDev.target->started = 1;
  1718. }
  1719. else
  1720. {
  1721. scsiDev.target->started = 0;
  1722. }
  1723. }
  1724. else if (unlikely(command == 0x00))
  1725. {
  1726. // TEST UNIT READY
  1727. doTestUnitReady();
  1728. }
  1729. else if (command == 0x4A)
  1730. {
  1731. bool immed = scsiDev.cdb[1] & 1;
  1732. doGetEventStatusNotification(immed);
  1733. }
  1734. else if (unlikely(!doTestUnitReady()))
  1735. {
  1736. // Status and sense codes already set by doTestUnitReady
  1737. }
  1738. else if (likely(command == 0x08))
  1739. {
  1740. // READ(6)
  1741. uint32_t lba =
  1742. (((uint32_t) scsiDev.cdb[1] & 0x1F) << 16) +
  1743. (((uint32_t) scsiDev.cdb[2]) << 8) +
  1744. scsiDev.cdb[3];
  1745. uint32_t blocks = scsiDev.cdb[4];
  1746. if (unlikely(blocks == 0)) blocks = 256;
  1747. doRead(lba, blocks);
  1748. }
  1749. else if (likely(command == 0x28))
  1750. {
  1751. // READ(10)
  1752. // Ignore all cache control bits - we don't support a memory cache.
  1753. uint32_t lba =
  1754. (((uint32_t) scsiDev.cdb[2]) << 24) +
  1755. (((uint32_t) scsiDev.cdb[3]) << 16) +
  1756. (((uint32_t) scsiDev.cdb[4]) << 8) +
  1757. scsiDev.cdb[5];
  1758. uint32_t blocks =
  1759. (((uint32_t) scsiDev.cdb[7]) << 8) +
  1760. scsiDev.cdb[8];
  1761. doRead(lba, blocks);
  1762. }
  1763. else if (likely(command == 0x0A))
  1764. {
  1765. // WRITE(6)
  1766. uint32_t lba =
  1767. (((uint32_t) scsiDev.cdb[1] & 0x1F) << 16) +
  1768. (((uint32_t) scsiDev.cdb[2]) << 8) +
  1769. scsiDev.cdb[3];
  1770. uint32_t blocks = scsiDev.cdb[4];
  1771. if (unlikely(blocks == 0)) blocks = 256;
  1772. doWrite(lba, blocks);
  1773. }
  1774. else if (likely(command == 0x2A) || // WRITE(10)
  1775. unlikely(command == 0x2E)) // WRITE AND VERIFY
  1776. {
  1777. // Ignore all cache control bits - we don't support a memory cache.
  1778. // Don't bother verifying either. The SD card likely stores ECC
  1779. // along with each flash row.
  1780. uint32_t lba =
  1781. (((uint32_t) scsiDev.cdb[2]) << 24) +
  1782. (((uint32_t) scsiDev.cdb[3]) << 16) +
  1783. (((uint32_t) scsiDev.cdb[4]) << 8) +
  1784. scsiDev.cdb[5];
  1785. uint32_t blocks =
  1786. (((uint32_t) scsiDev.cdb[7]) << 8) +
  1787. scsiDev.cdb[8];
  1788. doWrite(lba, blocks);
  1789. }
  1790. else if (unlikely(command == 0x04))
  1791. {
  1792. // FORMAT UNIT
  1793. // We don't really do any formatting, but we need to read the correct
  1794. // number of bytes in the DATA_OUT phase to make the SCSI host happy.
  1795. int fmtData = (scsiDev.cdb[1] & 0x10) ? 1 : 0;
  1796. if (fmtData)
  1797. {
  1798. // We need to read the parameter list, but we don't know how
  1799. // big it is yet. Start with the header.
  1800. scsiDev.dataLen = 4;
  1801. scsiDev.phase = DATA_OUT;
  1802. scsiDev.postDataOutHook = doFormatUnitHeader;
  1803. }
  1804. else
  1805. {
  1806. // No data to read, we're already finished!
  1807. }
  1808. }
  1809. else if (unlikely(command == 0x25))
  1810. {
  1811. // READ CAPACITY
  1812. doReadCapacity();
  1813. }
  1814. else if (unlikely(command == 0x0B))
  1815. {
  1816. // SEEK(6)
  1817. uint32_t lba =
  1818. (((uint32_t) scsiDev.cdb[1] & 0x1F) << 16) +
  1819. (((uint32_t) scsiDev.cdb[2]) << 8) +
  1820. scsiDev.cdb[3];
  1821. doSeek(lba);
  1822. }
  1823. else if (unlikely(command == 0x2B))
  1824. {
  1825. // SEEK(10)
  1826. uint32_t lba =
  1827. (((uint32_t) scsiDev.cdb[2]) << 24) +
  1828. (((uint32_t) scsiDev.cdb[3]) << 16) +
  1829. (((uint32_t) scsiDev.cdb[4]) << 8) +
  1830. scsiDev.cdb[5];
  1831. doSeek(lba);
  1832. }
  1833. else if (unlikely(command == 0x36))
  1834. {
  1835. // LOCK UNLOCK CACHE
  1836. // We don't have a cache to lock data into. do nothing.
  1837. }
  1838. else if (unlikely(command == 0x34))
  1839. {
  1840. // PRE-FETCH.
  1841. // We don't have a cache to pre-fetch into. do nothing.
  1842. }
  1843. else if (unlikely(command == 0x1E))
  1844. {
  1845. // PREVENT ALLOW MEDIUM REMOVAL
  1846. // Not much we can do to prevent the user removing the SD card.
  1847. // do nothing.
  1848. }
  1849. else if (unlikely(command == 0x01))
  1850. {
  1851. // REZERO UNIT
  1852. // Set the lun to a vendor-specific state. Ignore.
  1853. }
  1854. else if (unlikely(command == 0x35))
  1855. {
  1856. // SYNCHRONIZE CACHE
  1857. // We don't have a cache. do nothing.
  1858. }
  1859. else if (unlikely(command == 0x2F))
  1860. {
  1861. // VERIFY
  1862. // TODO: When they supply data to verify, we should read the data and
  1863. // verify it. If they don't supply any data, just say success.
  1864. if ((scsiDev.cdb[1] & 0x02) == 0)
  1865. {
  1866. // They are asking us to do a medium verification with no data
  1867. // comparison. Assume success, do nothing.
  1868. }
  1869. else
  1870. {
  1871. // TODO. This means they are supplying data to verify against.
  1872. // Technically we should probably grab the data and compare it.
  1873. scsiDev.status = CHECK_CONDITION;
  1874. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  1875. scsiDev.target->sense.asc = INVALID_FIELD_IN_CDB;
  1876. scsiDev.phase = STATUS;
  1877. }
  1878. }
  1879. else if (unlikely(command == 0x37))
  1880. {
  1881. // READ DEFECT DATA
  1882. uint32_t allocLength = (((uint16_t)scsiDev.cdb[7]) << 8) |
  1883. scsiDev.cdb[8];
  1884. scsiDev.data[0] = 0;
  1885. scsiDev.data[1] = scsiDev.cdb[1];
  1886. scsiDev.data[2] = 0;
  1887. scsiDev.data[3] = 0;
  1888. scsiDev.dataLen = 4;
  1889. if (scsiDev.dataLen > allocLength)
  1890. {
  1891. scsiDev.dataLen = allocLength;
  1892. }
  1893. scsiDev.phase = DATA_IN;
  1894. }
  1895. else if (img.file.isRom())
  1896. {
  1897. // Special handling for ROM drive to make SCSI2SD code report it as read-only
  1898. blockDev.state |= DISK_WP;
  1899. commandHandled = scsiModeCommand();
  1900. blockDev.state &= ~DISK_WP;
  1901. }
  1902. else
  1903. {
  1904. commandHandled = 0;
  1905. }
  1906. return commandHandled;
  1907. }
  1908. extern "C"
  1909. void scsiDiskPoll()
  1910. {
  1911. if (scsiDev.phase == DATA_IN &&
  1912. transfer.currentBlock != transfer.blocks)
  1913. {
  1914. diskDataIn();
  1915. }
  1916. else if (scsiDev.phase == DATA_OUT &&
  1917. transfer.currentBlock != transfer.blocks)
  1918. {
  1919. diskDataOut();
  1920. }
  1921. if (scsiDev.phase == STATUS && scsiDev.target)
  1922. {
  1923. // Check if the command is affected by drive geometry.
  1924. // Affected commands are:
  1925. // 0x1A MODE SENSE command of pages 0x03 (device format), 0x04 (disk geometry) or 0x3F (all pages)
  1926. // 0x1C RECEIVE DIAGNOSTICS RESULTS
  1927. uint8_t command = scsiDev.cdb[0];
  1928. uint8_t pageCode = scsiDev.cdb[2] & 0x3F;
  1929. if ((command == 0x1A && (pageCode == 0x03 || pageCode == 0x04 || pageCode == 0x3F)) ||
  1930. command == 0x1C)
  1931. {
  1932. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1933. checkDiskGeometryDivisible(img);
  1934. }
  1935. // Check for Inquiry command to reinsert CD-ROMs on boot
  1936. if (command == 0x12)
  1937. {
  1938. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1939. if (img.deviceType == S2S_CFG_OPTICAL && img.reinsert_on_inquiry)
  1940. {
  1941. reinsertCDROM(img);
  1942. }
  1943. }
  1944. }
  1945. }
  1946. extern "C"
  1947. void scsiDiskReset()
  1948. {
  1949. scsiDev.dataPtr = 0;
  1950. scsiDev.savedDataPtr = 0;
  1951. scsiDev.dataLen = 0;
  1952. // transfer.lba = 0; // Needed in Request Sense to determine failure
  1953. transfer.blocks = 0;
  1954. transfer.currentBlock = 0;
  1955. transfer.multiBlock = 0;
  1956. #ifdef PREFETCH_BUFFER_SIZE
  1957. g_scsi_prefetch.bytes = 0;
  1958. g_scsi_prefetch.sector = 0;
  1959. #endif
  1960. // Reinsert any ejected CD-ROMs
  1961. for (int i = 0; i < S2S_MAX_TARGETS; ++i)
  1962. {
  1963. image_config_t &img = g_DiskImages[i];
  1964. if (img.deviceType == S2S_CFG_OPTICAL)
  1965. {
  1966. reinsertCDROM(img);
  1967. }
  1968. }
  1969. }
  1970. extern "C"
  1971. void scsiDiskInit()
  1972. {
  1973. scsiDiskReset();
  1974. }