BlueSCSI_disk.cpp 55 KB

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