BlueSCSI_disk.cpp 72 KB

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