BlueSCSI_disk.cpp 70 KB

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