ZuluSCSI_disk.cpp 56 KB

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