BlueSCSI_disk.cpp 67 KB

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