BlueSCSI_disk.cpp 67 KB

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