ZuluSCSI_disk.cpp 68 KB

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