BlueSCSI_disk.cpp 57 KB

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