ZuluSCSI_disk.cpp 71 KB

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