ZuluSCSI_disk.cpp 62 KB

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