BlueSCSI_disk.cpp 58 KB

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