ZuluSCSI_disk.cpp 71 KB

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