BlueSCSI_disk.cpp 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974
  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. // Finds filename with the lowest lexical order _after_ the given filename in
  481. // the given folder. If there is no file after the given one, or if there is
  482. // no current file, this will return the lowest filename encountered.
  483. static int findNextImageAfter(image_config_t &img,
  484. const char* dirname, const char* filename,
  485. char* buf, size_t buflen)
  486. {
  487. FsFile dir;
  488. if (dirname[0] == '\0')
  489. {
  490. log("Image directory name invalid for ID", (img.scsiId & 7));
  491. return 0;
  492. }
  493. if (!dir.open(dirname))
  494. {
  495. log("Image directory '", dirname, "' couldn't be opened");
  496. }
  497. if (!dir.isDir())
  498. {
  499. log("Can't find images in '", dirname, "', not a directory");
  500. dir.close();
  501. return 0;
  502. }
  503. char first_name[MAX_FILE_PATH] = {'\0'};
  504. char candidate_name[MAX_FILE_PATH] = {'\0'};
  505. FsFile file;
  506. while (file.openNext(&dir, O_RDONLY))
  507. {
  508. if (file.isDir()) continue;
  509. if (!file.getName(buf, MAX_FILE_PATH))
  510. {
  511. log("Image directory '", dirname, "'had invalid file");
  512. continue;
  513. }
  514. if (!scsiDiskFilenameValid(buf)) continue;
  515. // keep track of the first item to allow wrapping
  516. // without having to iterate again
  517. if (first_name[0] == '\0' || strcasecmp(buf, first_name) < 0)
  518. {
  519. strncpy(first_name, buf, sizeof(first_name));
  520. }
  521. // discard if no selected name, or if candidate is before (or is) selected
  522. if (filename[0] == '\0' || strcasecmp(buf, filename) <= 0) continue;
  523. // if we got this far and the candidate is either 1) not set, or 2) is a
  524. // lower item than what has been encountered thus far, it is the best choice
  525. if (candidate_name[0] == '\0' || strcasecmp(buf, candidate_name) < 0)
  526. {
  527. strncpy(candidate_name, buf, sizeof(candidate_name));
  528. }
  529. }
  530. if (candidate_name[0] != '\0')
  531. {
  532. img.image_index++;
  533. strncpy(img.current_image, candidate_name, sizeof(img.current_image));
  534. strncpy(buf, candidate_name, buflen);
  535. return strlen(candidate_name);
  536. }
  537. else if (first_name[0] != '\0')
  538. {
  539. img.image_index = 0;
  540. strncpy(img.current_image, first_name, sizeof(img.current_image));
  541. strncpy(buf, first_name, buflen);
  542. return strlen(first_name);
  543. }
  544. else
  545. {
  546. log("Image directory '", dirname, "' was empty");
  547. return 0;
  548. }
  549. }
  550. int scsiDiskGetNextImageName(image_config_t &img, char *buf, size_t buflen)
  551. {
  552. int target_idx = img.scsiId & 7;
  553. char section[6] = "SCSI0";
  554. section[4] = '0' + target_idx;
  555. // sanity check: is provided buffer is long enough to store a filename?
  556. assert(buflen >= MAX_FILE_PATH);
  557. if (img.image_directory)
  558. {
  559. // image directory was found during startup
  560. char dirname[MAX_FILE_PATH];
  561. char key[] = "ImgDir";
  562. int dirlen = ini_gets(section, key, "", dirname, sizeof(dirname), CONFIGFILE);
  563. if (!dirlen)
  564. {
  565. // If image_directory set but ImageDir is not, could be used to
  566. // indicate an image directory configured via folder structure.
  567. // Not implemented, so treat this as equivalent to missing ImageDir
  568. return 0;
  569. }
  570. // find the next filename
  571. char nextname[MAX_FILE_PATH];
  572. int nextlen = findNextImageAfter(img, dirname, img.current_image, nextname, sizeof(nextname));
  573. if (nextlen == 0)
  574. {
  575. log("Image directory was empty for ID", target_idx);
  576. return 0;
  577. }
  578. else if (buflen < nextlen + dirlen + 2)
  579. {
  580. log("Directory '", dirname, "' and file '", nextname, "' exceed allowed length");
  581. return 0;
  582. }
  583. else
  584. {
  585. // construct a return value
  586. strncpy(buf, dirname, buflen);
  587. if (buf[strlen(buf) - 1] != '/') strcat(buf, "/");
  588. strcat(buf, nextname);
  589. return dirlen + nextlen;
  590. }
  591. }
  592. else
  593. {
  594. img.image_index++;
  595. if (img.image_index > IMAGE_INDEX_MAX)
  596. {
  597. img.image_index = 0;
  598. }
  599. char key[5] = "IMG0";
  600. key[3] = '0' + img.image_index;
  601. int ret = ini_gets(section, key, "", buf, buflen, CONFIGFILE);
  602. if (buf[0] != '\0')
  603. {
  604. return ret;
  605. }
  606. else if (img.image_index > 0)
  607. {
  608. // there may be more than one image but we've ran out of new ones
  609. // wrap back to the first image
  610. img.image_index = IMAGE_INDEX_MAX;
  611. return scsiDiskGetNextImageName(img, buf, buflen);
  612. }
  613. else
  614. {
  615. // images are not defined in config
  616. img.image_index = IMAGE_INDEX_MAX;
  617. return 0;
  618. }
  619. }
  620. }
  621. void scsiDiskLoadConfig(int target_idx)
  622. {
  623. char section[6] = "SCSI0";
  624. section[4] = '0' + target_idx;
  625. // Set default settings
  626. scsiDiskConfigDefaults(target_idx);
  627. // First load global settings
  628. scsiDiskLoadConfig(target_idx, "SCSI");
  629. // Then settings specific to target ID
  630. scsiDiskLoadConfig(target_idx, section);
  631. // Check if we have image specified by name
  632. char filename[MAX_FILE_PATH];
  633. image_config_t &img = g_DiskImages[target_idx];
  634. img.image_index = IMAGE_INDEX_MAX;
  635. if (scsiDiskGetNextImageName(img, filename, sizeof(filename)))
  636. {
  637. int blocksize = (img.deviceType == S2S_CFG_OPTICAL) ? 2048 : 512;
  638. log("-- Opening '", filename, "' for id:", target_idx, ", specified in " CONFIGFILE);
  639. scsiDiskOpenHDDImage(target_idx, filename, target_idx, 0, blocksize);
  640. }
  641. }
  642. bool scsiDiskCheckAnyImagesConfigured()
  643. {
  644. for (int i = 0; i < S2S_MAX_TARGETS; i++)
  645. {
  646. if (g_DiskImages[i].file.isOpen() && (g_DiskImages[i].scsiId & S2S_CFG_TARGET_ENABLED))
  647. {
  648. return true;
  649. }
  650. }
  651. return false;
  652. }
  653. image_config_t &scsiDiskGetImageConfig(int target_idx)
  654. {
  655. assert(target_idx >= 0 && target_idx < S2S_MAX_TARGETS);
  656. return g_DiskImages[target_idx];
  657. }
  658. static void diskEjectAction(uint8_t buttonId)
  659. {
  660. bool found = false;
  661. for (uint8_t i = 0; i < S2S_MAX_TARGETS; i++)
  662. {
  663. image_config_t &img = g_DiskImages[i];
  664. if (img.ejectButton == buttonId)
  665. {
  666. if (img.deviceType == S2S_CFG_OPTICAL)
  667. {
  668. found = true;
  669. log("Eject button ", (int)buttonId, " pressed, passing to CD drive SCSI", (int)i);
  670. cdromPerformEject(img);
  671. }
  672. }
  673. }
  674. if (!found)
  675. {
  676. log("Eject button ", (int)buttonId, " pressed, but no drives with EjectButton=", (int)buttonId, " setting found!");
  677. }
  678. }
  679. uint8_t diskEjectButtonUpdate(bool immediate)
  680. {
  681. // treat '1' to '0' transitions as eject actions
  682. static uint8_t previous = 0x00;
  683. uint8_t bitmask = platform_get_buttons();
  684. uint8_t ejectors = (previous ^ bitmask) & previous;
  685. previous = bitmask;
  686. // defer ejection until the bus is idle
  687. static uint8_t deferred = 0x00;
  688. if (!immediate)
  689. {
  690. deferred |= ejectors;
  691. return 0;
  692. }
  693. else
  694. {
  695. ejectors |= deferred;
  696. deferred = 0;
  697. if (ejectors)
  698. {
  699. uint8_t mask = 1;
  700. for (uint8_t i = 0; i < 8; i++)
  701. {
  702. if (ejectors & mask) diskEjectAction(i + 1);
  703. mask = mask << 1;
  704. }
  705. }
  706. return ejectors;
  707. }
  708. }
  709. /*******************************/
  710. /* Config handling for SCSI2SD */
  711. /*******************************/
  712. extern "C"
  713. void s2s_configInit(S2S_BoardCfg* config)
  714. {
  715. if (SD.exists(CONFIGFILE))
  716. {
  717. log("Reading configuration from " CONFIGFILE);
  718. }
  719. else
  720. {
  721. log("Config file " CONFIGFILE " not found, using defaults");
  722. }
  723. // Get default values from system preset, if any
  724. char presetName[32];
  725. ini_gets("SCSI", "System", "", presetName, sizeof(presetName), CONFIGFILE);
  726. preset_config_t defaults = getSystemPreset(presetName);
  727. if (defaults.presetName)
  728. {
  729. log("Active configuration (using system preset \"", defaults.presetName, "\"):");
  730. }
  731. else
  732. {
  733. log("Active configuration:");
  734. }
  735. memset(config, 0, sizeof(S2S_BoardCfg));
  736. memcpy(config->magic, "BCFG", 4);
  737. config->flags = 0;
  738. config->startupDelay = 0;
  739. config->selectionDelay = ini_getl("SCSI", "SelectionDelay", defaults.selectionDelay, CONFIGFILE);
  740. config->flags6 = 0;
  741. config->scsiSpeed = PLATFORM_MAX_SCSI_SPEED;
  742. int maxSyncSpeed = ini_getl("SCSI", "MaxSyncSpeed", defaults.maxSyncSpeed, CONFIGFILE);
  743. if (maxSyncSpeed < 5 && config->scsiSpeed > S2S_CFG_SPEED_ASYNC_50)
  744. config->scsiSpeed = S2S_CFG_SPEED_ASYNC_50;
  745. else if (maxSyncSpeed < 10 && config->scsiSpeed > S2S_CFG_SPEED_SYNC_5)
  746. config->scsiSpeed = S2S_CFG_SPEED_SYNC_5;
  747. if ((int)config->selectionDelay == defaults.selectionDelay)
  748. {
  749. debuglog("-- SelectionDelay: ", (int)config->selectionDelay);
  750. }
  751. else
  752. {
  753. log("-- SelectionDelay: ", (int)config->selectionDelay);
  754. }
  755. if (ini_getbool("SCSI", "EnableUnitAttention", defaults.enableUnitAttention, CONFIGFILE))
  756. {
  757. log("-- EnableUnitAttention is on");
  758. config->flags |= S2S_CFG_ENABLE_UNIT_ATTENTION;
  759. }
  760. else
  761. {
  762. debuglog("-- EnableUnitAttention is off");
  763. }
  764. if (ini_getbool("SCSI", "EnableSCSI2", defaults.enableSCSI2, CONFIGFILE))
  765. {
  766. debuglog("-- EnableSCSI2 is on");
  767. config->flags |= S2S_CFG_ENABLE_SCSI2;
  768. }
  769. else
  770. {
  771. log("-- EnableSCSI2 is off");
  772. }
  773. if (ini_getbool("SCSI", "EnableSelLatch", defaults.enableSelLatch, CONFIGFILE))
  774. {
  775. log("-- EnableSelLatch is on");
  776. config->flags |= S2S_CFG_ENABLE_SEL_LATCH;
  777. }
  778. else
  779. {
  780. debuglog("-- EnableSelLatch is off");
  781. }
  782. if (ini_getbool("SCSI", "MapLunsToIDs", defaults.mapLunsToIDs, CONFIGFILE))
  783. {
  784. log("-- MapLunsToIDs is on");
  785. config->flags |= S2S_CFG_MAP_LUNS_TO_IDS;
  786. }
  787. else
  788. {
  789. debuglog("-- MapLunsToIDs is off");
  790. }
  791. if (ini_getbool("SCSI", "Debug", 0, CONFIGFILE))
  792. {
  793. log("-- Debug is enabled");
  794. }
  795. if (ini_getbool("SCSI", "EnableParity", defaults.enableParity, CONFIGFILE))
  796. {
  797. debuglog("-- Parity is enabled");
  798. config->flags |= S2S_CFG_ENABLE_PARITY;
  799. }
  800. else
  801. {
  802. log("-- Parity is disabled");
  803. }
  804. if (ini_getbool("SCSI", "ReinsertCDOnInquiry", defaults.reinsertOnInquiry, CONFIGFILE))
  805. {
  806. log("-- ReinsertCDOnInquiry is enabled");
  807. }
  808. else
  809. {
  810. debuglog("-- ReinsertCDOnInquiry is disabled");
  811. }
  812. }
  813. extern "C"
  814. void s2s_debugInit(void)
  815. {
  816. }
  817. extern "C"
  818. void s2s_configPoll(void)
  819. {
  820. }
  821. extern "C"
  822. void s2s_configSave(int scsiId, uint16_t byesPerSector)
  823. {
  824. // Modification of config over SCSI bus is not implemented.
  825. }
  826. extern "C"
  827. const S2S_TargetCfg* s2s_getConfigByIndex(int index)
  828. {
  829. if (index < 0 || index >= S2S_MAX_TARGETS)
  830. {
  831. return NULL;
  832. }
  833. else
  834. {
  835. return &g_DiskImages[index];
  836. }
  837. }
  838. extern "C"
  839. const S2S_TargetCfg* s2s_getConfigById(int scsiId)
  840. {
  841. int i;
  842. for (i = 0; i < S2S_MAX_TARGETS; ++i)
  843. {
  844. const S2S_TargetCfg* tgt = s2s_getConfigByIndex(i);
  845. if ((tgt->scsiId & S2S_CFG_TARGET_ID_BITS) == scsiId &&
  846. (tgt->scsiId & S2S_CFG_TARGET_ENABLED))
  847. {
  848. return tgt;
  849. }
  850. }
  851. return NULL;
  852. }
  853. /**********************/
  854. /* FormatUnit command */
  855. /**********************/
  856. // Callback once all data has been read in the data out phase.
  857. static void doFormatUnitComplete(void)
  858. {
  859. scsiDev.phase = STATUS;
  860. }
  861. static void doFormatUnitSkipData(int bytes)
  862. {
  863. // We may not have enough memory to store the initialisation pattern and
  864. // defect list data. Since we're not making use of it yet anyway, just
  865. // discard the bytes.
  866. scsiEnterPhase(DATA_OUT);
  867. int i;
  868. for (i = 0; i < bytes; ++i)
  869. {
  870. scsiReadByte();
  871. }
  872. }
  873. // Callback from the data out phase.
  874. static void doFormatUnitPatternHeader(void)
  875. {
  876. int defectLength =
  877. ((((uint16_t)scsiDev.data[2])) << 8) +
  878. scsiDev.data[3];
  879. int patternLength =
  880. ((((uint16_t)scsiDev.data[4 + 2])) << 8) +
  881. scsiDev.data[4 + 3];
  882. doFormatUnitSkipData(defectLength + patternLength);
  883. doFormatUnitComplete();
  884. }
  885. // Callback from the data out phase.
  886. static void doFormatUnitHeader(void)
  887. {
  888. int IP = (scsiDev.data[1] & 0x08) ? 1 : 0;
  889. int DSP = (scsiDev.data[1] & 0x04) ? 1 : 0;
  890. if (! DSP) // disable save parameters
  891. {
  892. // Save the "MODE SELECT savable parameters"
  893. s2s_configSave(
  894. scsiDev.target->targetId,
  895. scsiDev.target->liveCfg.bytesPerSector);
  896. }
  897. if (IP)
  898. {
  899. // We need to read the initialisation pattern header first.
  900. scsiDev.dataLen += 4;
  901. scsiDev.phase = DATA_OUT;
  902. scsiDev.postDataOutHook = doFormatUnitPatternHeader;
  903. }
  904. else
  905. {
  906. // Read the defect list data
  907. int defectLength =
  908. ((((uint16_t)scsiDev.data[2])) << 8) +
  909. scsiDev.data[3];
  910. doFormatUnitSkipData(defectLength);
  911. doFormatUnitComplete();
  912. }
  913. }
  914. /************************/
  915. /* ReadCapacity command */
  916. /************************/
  917. static void doReadCapacity()
  918. {
  919. uint32_t lba = (((uint32_t) scsiDev.cdb[2]) << 24) +
  920. (((uint32_t) scsiDev.cdb[3]) << 16) +
  921. (((uint32_t) scsiDev.cdb[4]) << 8) +
  922. scsiDev.cdb[5];
  923. int pmi = scsiDev.cdb[8] & 1;
  924. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  925. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  926. uint32_t capacity = img.file.size() / bytesPerSector;
  927. if (!pmi && lba)
  928. {
  929. // error.
  930. // We don't do anything with the "partial medium indicator", and
  931. // assume that delays are constant across each block. But the spec
  932. // says we must return this error if pmi is specified incorrectly.
  933. scsiDev.status = CHECK_CONDITION;
  934. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  935. scsiDev.target->sense.asc = INVALID_FIELD_IN_CDB;
  936. scsiDev.phase = STATUS;
  937. }
  938. else if (capacity > 0)
  939. {
  940. uint32_t highestBlock = capacity - 1;
  941. scsiDev.data[0] = highestBlock >> 24;
  942. scsiDev.data[1] = highestBlock >> 16;
  943. scsiDev.data[2] = highestBlock >> 8;
  944. scsiDev.data[3] = highestBlock;
  945. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  946. scsiDev.data[4] = bytesPerSector >> 24;
  947. scsiDev.data[5] = bytesPerSector >> 16;
  948. scsiDev.data[6] = bytesPerSector >> 8;
  949. scsiDev.data[7] = bytesPerSector;
  950. scsiDev.dataLen = 8;
  951. scsiDev.phase = DATA_IN;
  952. }
  953. else
  954. {
  955. scsiDev.status = CHECK_CONDITION;
  956. scsiDev.target->sense.code = NOT_READY;
  957. scsiDev.target->sense.asc = MEDIUM_NOT_PRESENT;
  958. scsiDev.phase = STATUS;
  959. }
  960. }
  961. /*************************/
  962. /* TestUnitReady command */
  963. /*************************/
  964. static int doTestUnitReady()
  965. {
  966. int ready = 1;
  967. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  968. if (unlikely(!scsiDev.target->started || !img.file.isOpen()))
  969. {
  970. ready = 0;
  971. scsiDev.status = CHECK_CONDITION;
  972. scsiDev.target->sense.code = NOT_READY;
  973. scsiDev.target->sense.asc = LOGICAL_UNIT_NOT_READY_INITIALIZING_COMMAND_REQUIRED;
  974. scsiDev.phase = STATUS;
  975. }
  976. else if (img.ejected)
  977. {
  978. ready = 0;
  979. scsiDev.status = CHECK_CONDITION;
  980. scsiDev.target->sense.code = NOT_READY;
  981. scsiDev.target->sense.asc = MEDIUM_NOT_PRESENT;
  982. scsiDev.phase = STATUS;
  983. if (img.reinsert_after_eject)
  984. {
  985. // We are now reporting to host that the drive is open.
  986. // Simulate a "close" for next time the host polls.
  987. cdromSwitchNextImage(img);
  988. }
  989. }
  990. else if (unlikely(!(blockDev.state & DISK_PRESENT)))
  991. {
  992. ready = 0;
  993. scsiDev.status = CHECK_CONDITION;
  994. scsiDev.target->sense.code = NOT_READY;
  995. scsiDev.target->sense.asc = MEDIUM_NOT_PRESENT;
  996. scsiDev.phase = STATUS;
  997. }
  998. else if (unlikely(!(blockDev.state & DISK_INITIALISED)))
  999. {
  1000. ready = 0;
  1001. scsiDev.status = CHECK_CONDITION;
  1002. scsiDev.target->sense.code = NOT_READY;
  1003. scsiDev.target->sense.asc = LOGICAL_UNIT_NOT_READY_CAUSE_NOT_REPORTABLE;
  1004. scsiDev.phase = STATUS;
  1005. }
  1006. return ready;
  1007. }
  1008. /****************/
  1009. /* Seek command */
  1010. /****************/
  1011. static void doSeek(uint32_t lba)
  1012. {
  1013. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1014. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  1015. uint32_t capacity = img.file.size() / bytesPerSector;
  1016. if (lba >= capacity)
  1017. {
  1018. scsiDev.status = CHECK_CONDITION;
  1019. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  1020. scsiDev.target->sense.asc = LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
  1021. scsiDev.phase = STATUS;
  1022. }
  1023. else
  1024. {
  1025. if (unlikely(scsiDev.target->cfg->deviceType == S2S_CFG_FLOPPY_14MB) ||
  1026. scsiDev.compatMode < COMPAT_SCSI2)
  1027. {
  1028. s2s_delay_ms(10);
  1029. }
  1030. else
  1031. {
  1032. s2s_delay_us(10);
  1033. }
  1034. }
  1035. }
  1036. /********************************************/
  1037. /* Transfer state for read / write commands */
  1038. /********************************************/
  1039. BlockDevice blockDev = {DISK_PRESENT | DISK_INITIALISED};
  1040. Transfer transfer;
  1041. static struct {
  1042. uint8_t *buffer;
  1043. uint32_t bytes_sd; // Number of bytes that have been scheduled for transfer on SD card side
  1044. uint32_t bytes_scsi; // Number of bytes that have been scheduled for transfer on SCSI side
  1045. uint32_t bytes_scsi_started;
  1046. uint32_t sd_transfer_start;
  1047. int parityError;
  1048. } g_disk_transfer;
  1049. #ifdef PREFETCH_BUFFER_SIZE
  1050. static struct {
  1051. uint8_t buffer[PREFETCH_BUFFER_SIZE];
  1052. uint32_t sector;
  1053. uint32_t bytes;
  1054. uint8_t scsiId;
  1055. } g_scsi_prefetch;
  1056. #endif
  1057. /*****************/
  1058. /* Write command */
  1059. /*****************/
  1060. void scsiDiskStartWrite(uint32_t lba, uint32_t blocks)
  1061. {
  1062. if (unlikely(scsiDev.target->cfg->deviceType == S2S_CFG_FLOPPY_14MB)) {
  1063. // Floppies are supposed to be slow. Some systems can't handle a floppy
  1064. // without an access time
  1065. s2s_delay_ms(10);
  1066. }
  1067. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1068. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  1069. uint32_t capacity = img.file.size() / bytesPerSector;
  1070. debuglog("------ Write ", (int)blocks, "x", (int)bytesPerSector, " starting at ", (int)lba);
  1071. if (unlikely(blockDev.state & DISK_WP) ||
  1072. unlikely(scsiDev.target->cfg->deviceType == S2S_CFG_OPTICAL) ||
  1073. unlikely(!img.file.isWritable()))
  1074. {
  1075. log("WARNING: Host attempted write to read-only drive ID ", (int)(img.scsiId & S2S_CFG_TARGET_ID_BITS));
  1076. scsiDev.status = CHECK_CONDITION;
  1077. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  1078. scsiDev.target->sense.asc = WRITE_PROTECTED;
  1079. scsiDev.phase = STATUS;
  1080. }
  1081. else if (unlikely(((uint64_t) lba) + blocks > capacity))
  1082. {
  1083. log("WARNING: Host attempted write at sector ", (int)lba, "+", (int)blocks,
  1084. ", exceeding image size ", (int)capacity, " sectors (",
  1085. (int)bytesPerSector, "B/sector)");
  1086. scsiDev.status = CHECK_CONDITION;
  1087. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  1088. scsiDev.target->sense.asc = LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
  1089. scsiDev.phase = STATUS;
  1090. }
  1091. else
  1092. {
  1093. transfer.multiBlock = true;
  1094. transfer.lba = lba;
  1095. transfer.blocks = blocks;
  1096. transfer.currentBlock = 0;
  1097. scsiDev.phase = DATA_OUT;
  1098. scsiDev.dataLen = 0;
  1099. scsiDev.dataPtr = 0;
  1100. #ifdef PREFETCH_BUFFER_SIZE
  1101. // Invalidate prefetch buffer
  1102. g_scsi_prefetch.bytes = 0;
  1103. g_scsi_prefetch.sector = 0;
  1104. #endif
  1105. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1106. if (!img.file.seek((uint64_t)transfer.lba * bytesPerSector))
  1107. {
  1108. log("Seek to ", transfer.lba, " failed for SCSI ID", (int)scsiDev.target->targetId);
  1109. scsiDev.status = CHECK_CONDITION;
  1110. scsiDev.target->sense.code = MEDIUM_ERROR;
  1111. scsiDev.target->sense.asc = NO_SEEK_COMPLETE;
  1112. scsiDev.phase = STATUS;
  1113. }
  1114. }
  1115. }
  1116. // Called to transfer next block from SCSI bus.
  1117. // Usually called from SD card driver during waiting for SD card access.
  1118. void diskDataOut_callback(uint32_t bytes_complete)
  1119. {
  1120. // For best performance, do SCSI reads in blocks of 4 or more bytes
  1121. bytes_complete &= ~3;
  1122. if (g_disk_transfer.bytes_scsi_started < g_disk_transfer.bytes_scsi)
  1123. {
  1124. // How many bytes remaining in the transfer?
  1125. uint32_t remain = g_disk_transfer.bytes_scsi - g_disk_transfer.bytes_scsi_started;
  1126. uint32_t len = remain;
  1127. // Split read so that it doesn't wrap around buffer edge
  1128. uint32_t bufsize = sizeof(scsiDev.data);
  1129. uint32_t start = (g_disk_transfer.bytes_scsi_started % bufsize);
  1130. if (start + len > bufsize)
  1131. len = bufsize - start;
  1132. // Apply platform-specific optimized transfer sizes
  1133. if (len > PLATFORM_OPTIMAL_SCSI_READ_BLOCK_SIZE)
  1134. {
  1135. len = PLATFORM_OPTIMAL_SCSI_READ_BLOCK_SIZE;
  1136. }
  1137. // Don't overwrite data that has not yet been written to SD card
  1138. uint32_t sd_ready_cnt = g_disk_transfer.bytes_sd + bytes_complete;
  1139. if (g_disk_transfer.bytes_scsi_started + len > sd_ready_cnt + bufsize)
  1140. len = sd_ready_cnt + bufsize - g_disk_transfer.bytes_scsi_started;
  1141. // Keep transfers a multiple of sector size.
  1142. // Macintosh SCSI driver seems to get confused if we have a delay
  1143. // in middle of a sector.
  1144. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  1145. if (remain >= bytesPerSector && len % bytesPerSector != 0)
  1146. {
  1147. len -= len % bytesPerSector;
  1148. }
  1149. if (len == 0)
  1150. return;
  1151. // debuglog("SCSI read ", (int)start, " + ", (int)len);
  1152. scsiStartRead(&scsiDev.data[start], len, &g_disk_transfer.parityError);
  1153. g_disk_transfer.bytes_scsi_started += len;
  1154. }
  1155. }
  1156. void diskDataOut()
  1157. {
  1158. scsiEnterPhase(DATA_OUT);
  1159. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1160. uint32_t blockcount = (transfer.blocks - transfer.currentBlock);
  1161. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  1162. g_disk_transfer.buffer = scsiDev.data;
  1163. g_disk_transfer.bytes_scsi = blockcount * bytesPerSector;
  1164. g_disk_transfer.bytes_sd = 0;
  1165. g_disk_transfer.bytes_scsi_started = 0;
  1166. g_disk_transfer.sd_transfer_start = 0;
  1167. g_disk_transfer.parityError = 0;
  1168. while (g_disk_transfer.bytes_sd < g_disk_transfer.bytes_scsi
  1169. && scsiDev.phase == DATA_OUT
  1170. && !scsiDev.resetFlag)
  1171. {
  1172. platform_poll();
  1173. diskEjectButtonUpdate(false);
  1174. // Figure out how many contiguous bytes are available for writing to SD card.
  1175. uint32_t bufsize = sizeof(scsiDev.data);
  1176. uint32_t start = g_disk_transfer.bytes_sd % bufsize;
  1177. uint32_t len = 0;
  1178. // How much data until buffer edge wrap?
  1179. uint32_t available = g_disk_transfer.bytes_scsi_started - g_disk_transfer.bytes_sd;
  1180. if (start + available > bufsize)
  1181. available = bufsize - start;
  1182. // Count number of finished sectors
  1183. if (scsiIsReadFinished(&scsiDev.data[start + available - 1]))
  1184. {
  1185. len = available;
  1186. }
  1187. else
  1188. {
  1189. while (len < available && scsiIsReadFinished(&scsiDev.data[start + len + SD_SECTOR_SIZE - 1]))
  1190. {
  1191. len += SD_SECTOR_SIZE;
  1192. }
  1193. }
  1194. // In case the last sector is partial (256 byte SCSI sectors)
  1195. if (len > available)
  1196. {
  1197. len = available;
  1198. }
  1199. // Apply platform-specific write size blocks for optimization
  1200. if (len > PLATFORM_OPTIMAL_MAX_SD_WRITE_SIZE)
  1201. {
  1202. len = PLATFORM_OPTIMAL_MAX_SD_WRITE_SIZE;
  1203. }
  1204. uint32_t remain_in_transfer = g_disk_transfer.bytes_scsi - g_disk_transfer.bytes_sd;
  1205. if (len < bufsize - start && len < remain_in_transfer)
  1206. {
  1207. // Use large write blocks in middle of transfer and smaller at the end of transfer.
  1208. // This improves performance for large writes and reduces latency at end of request.
  1209. uint32_t min_write_size = PLATFORM_OPTIMAL_MIN_SD_WRITE_SIZE;
  1210. if (remain_in_transfer <= PLATFORM_OPTIMAL_MAX_SD_WRITE_SIZE)
  1211. {
  1212. min_write_size = PLATFORM_OPTIMAL_LAST_SD_WRITE_SIZE;
  1213. }
  1214. if (len < min_write_size)
  1215. {
  1216. len = 0;
  1217. }
  1218. }
  1219. if (len == 0)
  1220. {
  1221. // Nothing ready to transfer, check if we can read more from SCSI bus
  1222. diskDataOut_callback(0);
  1223. }
  1224. else
  1225. {
  1226. // Finalize transfer on SCSI side
  1227. scsiFinishRead(&scsiDev.data[start], len, &g_disk_transfer.parityError);
  1228. // Check parity error status before writing to SD card
  1229. if (g_disk_transfer.parityError && (scsiDev.boardCfg.flags & S2S_CFG_ENABLE_PARITY))
  1230. {
  1231. scsiDev.status = CHECK_CONDITION;
  1232. scsiDev.target->sense.code = ABORTED_COMMAND;
  1233. scsiDev.target->sense.asc = SCSI_PARITY_ERROR;
  1234. scsiDev.phase = STATUS;
  1235. break;
  1236. }
  1237. // Start writing to SD card and simultaneously start new SCSI transfers
  1238. // when buffer space is freed.
  1239. uint8_t *buf = &scsiDev.data[start];
  1240. g_disk_transfer.sd_transfer_start = start;
  1241. // debuglog("SD write ", (int)start, " + ", (int)len, " ", bytearray(buf, len));
  1242. platform_set_sd_callback(&diskDataOut_callback, buf);
  1243. if (img.file.write(buf, len) != len)
  1244. {
  1245. log("SD card write failed: ", SD.sdErrorCode());
  1246. scsiDev.status = CHECK_CONDITION;
  1247. scsiDev.target->sense.code = MEDIUM_ERROR;
  1248. scsiDev.target->sense.asc = WRITE_ERROR_AUTO_REALLOCATION_FAILED;
  1249. scsiDev.phase = STATUS;
  1250. }
  1251. platform_set_sd_callback(NULL, NULL);
  1252. g_disk_transfer.bytes_sd += len;
  1253. }
  1254. }
  1255. // Release SCSI bus
  1256. scsiFinishRead(NULL, 0, &g_disk_transfer.parityError);
  1257. transfer.currentBlock += blockcount;
  1258. scsiDev.dataPtr = scsiDev.dataLen = 0;
  1259. if (transfer.currentBlock == transfer.blocks)
  1260. {
  1261. // Verify that all data has been flushed to disk from SdFat cache.
  1262. // Normally does nothing as we do not change image file size and
  1263. // data writes are not cached.
  1264. img.file.flush();
  1265. }
  1266. }
  1267. /*****************/
  1268. /* Read command */
  1269. /*****************/
  1270. void scsiDiskStartRead(uint32_t lba, uint32_t blocks)
  1271. {
  1272. if (unlikely(scsiDev.target->cfg->deviceType == S2S_CFG_FLOPPY_14MB)) {
  1273. // Floppies are supposed to be slow. Some systems can't handle a floppy
  1274. // without an access time
  1275. s2s_delay_ms(10);
  1276. }
  1277. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1278. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  1279. uint32_t capacity = img.file.size() / bytesPerSector;
  1280. debuglog("------ Read ", (int)blocks, "x", (int)bytesPerSector, " starting at ", (int)lba);
  1281. if (unlikely(((uint64_t) lba) + blocks > capacity))
  1282. {
  1283. log("WARNING: Host attempted read at sector ", (int)lba, "+", (int)blocks,
  1284. ", exceeding image size ", (int)capacity, " sectors (",
  1285. (int)bytesPerSector, "B/sector)");
  1286. scsiDev.status = CHECK_CONDITION;
  1287. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  1288. scsiDev.target->sense.asc = LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
  1289. scsiDev.phase = STATUS;
  1290. }
  1291. else
  1292. {
  1293. transfer.multiBlock = 1;
  1294. transfer.lba = lba;
  1295. transfer.blocks = blocks;
  1296. transfer.currentBlock = 0;
  1297. scsiDev.phase = DATA_IN;
  1298. scsiDev.dataLen = 0;
  1299. scsiDev.dataPtr = 0;
  1300. #ifdef PREFETCH_BUFFER_SIZE
  1301. uint32_t sectors_in_prefetch = g_scsi_prefetch.bytes / bytesPerSector;
  1302. if (img.scsiId == g_scsi_prefetch.scsiId &&
  1303. transfer.lba >= g_scsi_prefetch.sector &&
  1304. transfer.lba < g_scsi_prefetch.sector + sectors_in_prefetch)
  1305. {
  1306. // We have the some sectors already in prefetch cache
  1307. scsiEnterPhase(DATA_IN);
  1308. uint32_t start_offset = transfer.lba - g_scsi_prefetch.sector;
  1309. uint32_t count = sectors_in_prefetch - start_offset;
  1310. if (count > transfer.blocks) count = transfer.blocks;
  1311. scsiStartWrite(g_scsi_prefetch.buffer + start_offset * bytesPerSector, count * bytesPerSector);
  1312. debuglog("------ Found ", (int)count, " sectors in prefetch cache");
  1313. transfer.currentBlock += count;
  1314. }
  1315. if (transfer.currentBlock == transfer.blocks)
  1316. {
  1317. while (!scsiIsWriteFinished(NULL))
  1318. {
  1319. platform_poll();
  1320. diskEjectButtonUpdate(false);
  1321. }
  1322. scsiFinishWrite();
  1323. }
  1324. #endif
  1325. if (!img.file.seek((uint64_t)(transfer.lba + transfer.currentBlock) * bytesPerSector))
  1326. {
  1327. log("Seek to ", transfer.lba, " failed for SCSI ID", (int)scsiDev.target->targetId);
  1328. scsiDev.status = CHECK_CONDITION;
  1329. scsiDev.target->sense.code = MEDIUM_ERROR;
  1330. scsiDev.target->sense.asc = NO_SEEK_COMPLETE;
  1331. scsiDev.phase = STATUS;
  1332. }
  1333. }
  1334. }
  1335. void diskDataIn_callback(uint32_t bytes_complete)
  1336. {
  1337. // On SCSI-1 devices the phase change has some extra delays.
  1338. // Doing it here lets the SD card transfer proceed in background.
  1339. scsiEnterPhase(DATA_IN);
  1340. // For best performance, do writes in blocks of 4 or more bytes
  1341. if (bytes_complete < g_disk_transfer.bytes_sd)
  1342. {
  1343. bytes_complete &= ~3;
  1344. }
  1345. // Machintosh SCSI driver can get confused if pauses occur in middle of
  1346. // a sector, so schedule the transfers in sector sized blocks.
  1347. if (bytes_complete < g_disk_transfer.bytes_sd)
  1348. {
  1349. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  1350. if (bytes_complete % bytesPerSector != 0)
  1351. {
  1352. bytes_complete -= bytes_complete % bytesPerSector;
  1353. }
  1354. }
  1355. if (bytes_complete > g_disk_transfer.bytes_scsi)
  1356. {
  1357. // DMA is reading from SD card, bytes_complete bytes have already been read.
  1358. // Send them to SCSI bus now.
  1359. uint32_t len = bytes_complete - g_disk_transfer.bytes_scsi;
  1360. scsiStartWrite(g_disk_transfer.buffer + g_disk_transfer.bytes_scsi, len);
  1361. g_disk_transfer.bytes_scsi += len;
  1362. }
  1363. // Provide a chance for polling request processing
  1364. scsiIsWriteFinished(NULL);
  1365. }
  1366. // Start a data in transfer using given temporary buffer.
  1367. // diskDataIn() below divides the scsiDev.data buffer to two halves for double buffering.
  1368. static void start_dataInTransfer(uint8_t *buffer, uint32_t count)
  1369. {
  1370. g_disk_transfer.buffer = buffer;
  1371. g_disk_transfer.bytes_scsi = 0;
  1372. g_disk_transfer.bytes_sd = count;
  1373. // Verify that previous write using this buffer has finished
  1374. uint32_t start = millis();
  1375. while (!scsiIsWriteFinished(buffer + count - 1) && !scsiDev.resetFlag)
  1376. {
  1377. if ((uint32_t)(millis() - start) > 5000)
  1378. {
  1379. log("start_dataInTransfer() timeout waiting for previous to finish");
  1380. scsiDev.resetFlag = 1;
  1381. }
  1382. platform_poll();
  1383. diskEjectButtonUpdate(false);
  1384. }
  1385. if (scsiDev.resetFlag) return;
  1386. // Start transferring from SD card
  1387. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1388. platform_set_sd_callback(&diskDataIn_callback, buffer);
  1389. if (img.file.read(buffer, count) != count)
  1390. {
  1391. log("SD card read failed: ", SD.sdErrorCode());
  1392. scsiDev.status = CHECK_CONDITION;
  1393. scsiDev.target->sense.code = MEDIUM_ERROR;
  1394. scsiDev.target->sense.asc = UNRECOVERED_READ_ERROR;
  1395. scsiDev.phase = STATUS;
  1396. }
  1397. diskDataIn_callback(count);
  1398. platform_set_sd_callback(NULL, NULL);
  1399. platform_poll();
  1400. diskEjectButtonUpdate(false);
  1401. }
  1402. static void diskDataIn()
  1403. {
  1404. // Figure out how many blocks we can fit in buffer
  1405. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  1406. uint32_t maxblocks = sizeof(scsiDev.data) / bytesPerSector;
  1407. uint32_t maxblocks_half = maxblocks / 2;
  1408. // Start transfer in first half of buffer
  1409. // Waits for the previous first half transfer to finish first.
  1410. uint32_t remain = (transfer.blocks - transfer.currentBlock);
  1411. if (remain > 0)
  1412. {
  1413. uint32_t transfer_blocks = std::min(remain, maxblocks_half);
  1414. uint32_t transfer_bytes = transfer_blocks * bytesPerSector;
  1415. start_dataInTransfer(&scsiDev.data[0], transfer_bytes);
  1416. transfer.currentBlock += transfer_blocks;
  1417. }
  1418. // Start transfer in second half of buffer
  1419. // Waits for the previous second half transfer to finish first
  1420. remain = (transfer.blocks - transfer.currentBlock);
  1421. if (remain > 0)
  1422. {
  1423. uint32_t transfer_blocks = std::min(remain, maxblocks_half);
  1424. uint32_t transfer_bytes = transfer_blocks * bytesPerSector;
  1425. start_dataInTransfer(&scsiDev.data[maxblocks_half * bytesPerSector], transfer_bytes);
  1426. transfer.currentBlock += transfer_blocks;
  1427. }
  1428. if (transfer.currentBlock == transfer.blocks)
  1429. {
  1430. // This was the last block, verify that everything finishes
  1431. #ifdef PREFETCH_BUFFER_SIZE
  1432. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1433. int prefetchbytes = img.prefetchbytes;
  1434. if (prefetchbytes > PREFETCH_BUFFER_SIZE) prefetchbytes = PREFETCH_BUFFER_SIZE;
  1435. uint32_t prefetch_sectors = prefetchbytes / bytesPerSector;
  1436. uint32_t img_sector_count = img.file.size() / bytesPerSector;
  1437. g_scsi_prefetch.sector = transfer.lba + transfer.blocks;
  1438. g_scsi_prefetch.bytes = 0;
  1439. g_scsi_prefetch.scsiId = scsiDev.target->cfg->scsiId;
  1440. if (g_scsi_prefetch.sector + prefetch_sectors > img_sector_count)
  1441. {
  1442. // Don't try to read past image end.
  1443. prefetch_sectors = img_sector_count - g_scsi_prefetch.sector;
  1444. }
  1445. while (!scsiIsWriteFinished(NULL) && prefetch_sectors > 0 && !scsiDev.resetFlag)
  1446. {
  1447. platform_poll();
  1448. diskEjectButtonUpdate(false);
  1449. // Check if prefetch buffer is free
  1450. g_disk_transfer.buffer = g_scsi_prefetch.buffer + g_scsi_prefetch.bytes;
  1451. if (!scsiIsWriteFinished(g_disk_transfer.buffer) ||
  1452. !scsiIsWriteFinished(g_disk_transfer.buffer + bytesPerSector - 1))
  1453. {
  1454. continue;
  1455. }
  1456. // We still have time, prefetch next sectors in case this SCSI request
  1457. // is part of a longer linear read.
  1458. g_disk_transfer.bytes_sd = bytesPerSector;
  1459. g_disk_transfer.bytes_scsi = bytesPerSector; // Tell callback not to send to SCSI
  1460. platform_set_sd_callback(&diskDataIn_callback, g_disk_transfer.buffer);
  1461. int status = img.file.read(g_disk_transfer.buffer, bytesPerSector);
  1462. if (status <= 0)
  1463. {
  1464. log("Prefetch read failed");
  1465. prefetch_sectors = 0;
  1466. break;
  1467. }
  1468. g_scsi_prefetch.bytes += status;
  1469. platform_set_sd_callback(NULL, NULL);
  1470. prefetch_sectors--;
  1471. }
  1472. #endif
  1473. while (!scsiIsWriteFinished(NULL))
  1474. {
  1475. platform_poll();
  1476. diskEjectButtonUpdate(false);
  1477. }
  1478. scsiFinishWrite();
  1479. }
  1480. }
  1481. /********************/
  1482. /* Command dispatch */
  1483. /********************/
  1484. // Handle direct-access scsi device commands
  1485. extern "C"
  1486. int scsiDiskCommand()
  1487. {
  1488. int commandHandled = 1;
  1489. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1490. uint8_t command = scsiDev.cdb[0];
  1491. if (unlikely(command == 0x1B))
  1492. {
  1493. // START STOP UNIT
  1494. // Enable or disable media access operations.
  1495. //int immed = scsiDev.cdb[1] & 1;
  1496. int start = scsiDev.cdb[4] & 1;
  1497. if (start)
  1498. {
  1499. scsiDev.target->started = 1;
  1500. }
  1501. else
  1502. {
  1503. scsiDev.target->started = 0;
  1504. }
  1505. }
  1506. else if (unlikely(command == 0x00))
  1507. {
  1508. // TEST UNIT READY
  1509. doTestUnitReady();
  1510. }
  1511. else if (unlikely(!doTestUnitReady()))
  1512. {
  1513. // Status and sense codes already set by doTestUnitReady
  1514. }
  1515. else if (likely(command == 0x08))
  1516. {
  1517. // READ(6)
  1518. uint32_t lba =
  1519. (((uint32_t) scsiDev.cdb[1] & 0x1F) << 16) +
  1520. (((uint32_t) scsiDev.cdb[2]) << 8) +
  1521. scsiDev.cdb[3];
  1522. uint32_t blocks = scsiDev.cdb[4];
  1523. if (unlikely(blocks == 0)) blocks = 256;
  1524. scsiDiskStartRead(lba, blocks);
  1525. }
  1526. else if (likely(command == 0x28))
  1527. {
  1528. // READ(10)
  1529. // Ignore all cache control bits - we don't support a memory cache.
  1530. uint32_t lba =
  1531. (((uint32_t) scsiDev.cdb[2]) << 24) +
  1532. (((uint32_t) scsiDev.cdb[3]) << 16) +
  1533. (((uint32_t) scsiDev.cdb[4]) << 8) +
  1534. scsiDev.cdb[5];
  1535. uint32_t blocks =
  1536. (((uint32_t) scsiDev.cdb[7]) << 8) +
  1537. scsiDev.cdb[8];
  1538. scsiDiskStartRead(lba, blocks);
  1539. }
  1540. else if (likely(command == 0x0A))
  1541. {
  1542. // WRITE(6)
  1543. uint32_t lba =
  1544. (((uint32_t) scsiDev.cdb[1] & 0x1F) << 16) +
  1545. (((uint32_t) scsiDev.cdb[2]) << 8) +
  1546. scsiDev.cdb[3];
  1547. uint32_t blocks = scsiDev.cdb[4];
  1548. if (unlikely(blocks == 0)) blocks = 256;
  1549. scsiDiskStartWrite(lba, blocks);
  1550. }
  1551. else if (likely(command == 0x2A) || // WRITE(10)
  1552. unlikely(command == 0x2E)) // WRITE AND VERIFY
  1553. {
  1554. // Ignore all cache control bits - we don't support a memory cache.
  1555. // Don't bother verifying either. The SD card likely stores ECC
  1556. // along with each flash row.
  1557. uint32_t lba =
  1558. (((uint32_t) scsiDev.cdb[2]) << 24) +
  1559. (((uint32_t) scsiDev.cdb[3]) << 16) +
  1560. (((uint32_t) scsiDev.cdb[4]) << 8) +
  1561. scsiDev.cdb[5];
  1562. uint32_t blocks =
  1563. (((uint32_t) scsiDev.cdb[7]) << 8) +
  1564. scsiDev.cdb[8];
  1565. scsiDiskStartWrite(lba, blocks);
  1566. }
  1567. else if (unlikely(command == 0x04))
  1568. {
  1569. // FORMAT UNIT
  1570. // We don't really do any formatting, but we need to read the correct
  1571. // number of bytes in the DATA_OUT phase to make the SCSI host happy.
  1572. int fmtData = (scsiDev.cdb[1] & 0x10) ? 1 : 0;
  1573. if (fmtData)
  1574. {
  1575. // We need to read the parameter list, but we don't know how
  1576. // big it is yet. Start with the header.
  1577. scsiDev.dataLen = 4;
  1578. scsiDev.phase = DATA_OUT;
  1579. scsiDev.postDataOutHook = doFormatUnitHeader;
  1580. }
  1581. else
  1582. {
  1583. // No data to read, we're already finished!
  1584. }
  1585. }
  1586. else if (unlikely(command == 0x25))
  1587. {
  1588. // READ CAPACITY
  1589. doReadCapacity();
  1590. }
  1591. else if (unlikely(command == 0x0B))
  1592. {
  1593. // SEEK(6)
  1594. uint32_t lba =
  1595. (((uint32_t) scsiDev.cdb[1] & 0x1F) << 16) +
  1596. (((uint32_t) scsiDev.cdb[2]) << 8) +
  1597. scsiDev.cdb[3];
  1598. doSeek(lba);
  1599. }
  1600. else if (unlikely(command == 0x2B))
  1601. {
  1602. // SEEK(10)
  1603. uint32_t lba =
  1604. (((uint32_t) scsiDev.cdb[2]) << 24) +
  1605. (((uint32_t) scsiDev.cdb[3]) << 16) +
  1606. (((uint32_t) scsiDev.cdb[4]) << 8) +
  1607. scsiDev.cdb[5];
  1608. doSeek(lba);
  1609. }
  1610. else if (unlikely(command == 0x36))
  1611. {
  1612. // LOCK UNLOCK CACHE
  1613. // We don't have a cache to lock data into. do nothing.
  1614. }
  1615. else if (unlikely(command == 0x34))
  1616. {
  1617. // PRE-FETCH.
  1618. // We don't have a cache to pre-fetch into. do nothing.
  1619. }
  1620. else if (unlikely(command == 0x1E))
  1621. {
  1622. // PREVENT ALLOW MEDIUM REMOVAL
  1623. // Not much we can do to prevent the user removing the SD card.
  1624. // do nothing.
  1625. }
  1626. else if (unlikely(command == 0x01))
  1627. {
  1628. // REZERO UNIT
  1629. // Set the lun to a vendor-specific state. Ignore.
  1630. }
  1631. else if (unlikely(command == 0x35))
  1632. {
  1633. // SYNCHRONIZE CACHE
  1634. // We don't have a cache. do nothing.
  1635. }
  1636. else if (unlikely(command == 0x2F))
  1637. {
  1638. // VERIFY
  1639. // TODO: When they supply data to verify, we should read the data and
  1640. // verify it. If they don't supply any data, just say success.
  1641. if ((scsiDev.cdb[1] & 0x02) == 0)
  1642. {
  1643. // They are asking us to do a medium verification with no data
  1644. // comparison. Assume success, do nothing.
  1645. }
  1646. else
  1647. {
  1648. // TODO. This means they are supplying data to verify against.
  1649. // Technically we should probably grab the data and compare it.
  1650. scsiDev.status = CHECK_CONDITION;
  1651. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  1652. scsiDev.target->sense.asc = INVALID_FIELD_IN_CDB;
  1653. scsiDev.phase = STATUS;
  1654. }
  1655. }
  1656. else if (unlikely(command == 0x37))
  1657. {
  1658. // READ DEFECT DATA
  1659. uint32_t allocLength = (((uint16_t)scsiDev.cdb[7]) << 8) |
  1660. scsiDev.cdb[8];
  1661. scsiDev.data[0] = 0;
  1662. scsiDev.data[1] = scsiDev.cdb[1];
  1663. scsiDev.data[2] = 0;
  1664. scsiDev.data[3] = 0;
  1665. scsiDev.dataLen = 4;
  1666. if (scsiDev.dataLen > allocLength)
  1667. {
  1668. scsiDev.dataLen = allocLength;
  1669. }
  1670. scsiDev.phase = DATA_IN;
  1671. }
  1672. else if (img.file.isRom())
  1673. {
  1674. // Special handling for ROM drive to make SCSI2SD code report it as read-only
  1675. blockDev.state |= DISK_WP;
  1676. commandHandled = scsiModeCommand();
  1677. blockDev.state &= ~DISK_WP;
  1678. }
  1679. else
  1680. {
  1681. commandHandled = 0;
  1682. }
  1683. return commandHandled;
  1684. }
  1685. extern "C"
  1686. void scsiDiskPoll()
  1687. {
  1688. if (scsiDev.phase == DATA_IN &&
  1689. transfer.currentBlock != transfer.blocks)
  1690. {
  1691. diskDataIn();
  1692. }
  1693. else if (scsiDev.phase == DATA_OUT &&
  1694. transfer.currentBlock != transfer.blocks)
  1695. {
  1696. diskDataOut();
  1697. }
  1698. if (scsiDev.phase == STATUS && scsiDev.target)
  1699. {
  1700. // Check if the command is affected by drive geometry.
  1701. // Affected commands are:
  1702. // 0x1A MODE SENSE command of pages 0x03 (device format), 0x04 (disk geometry) or 0x3F (all pages)
  1703. // 0x1C RECEIVE DIAGNOSTICS RESULTS
  1704. uint8_t command = scsiDev.cdb[0];
  1705. uint8_t pageCode = scsiDev.cdb[2] & 0x3F;
  1706. if ((command == 0x1A && (pageCode == 0x03 || pageCode == 0x04 || pageCode == 0x3F)) ||
  1707. command == 0x1C)
  1708. {
  1709. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1710. checkDiskGeometryDivisible(img);
  1711. }
  1712. // Check for Inquiry command to reinsert CD-ROMs on boot
  1713. if (command == 0x12)
  1714. {
  1715. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1716. if (img.deviceType == S2S_CFG_OPTICAL && img.reinsert_on_inquiry)
  1717. {
  1718. cdromReinsertFirstImage(img);
  1719. }
  1720. }
  1721. }
  1722. }
  1723. extern "C"
  1724. void scsiDiskReset()
  1725. {
  1726. scsiDev.dataPtr = 0;
  1727. scsiDev.savedDataPtr = 0;
  1728. scsiDev.dataLen = 0;
  1729. // transfer.lba = 0; // Needed in Request Sense to determine failure
  1730. transfer.blocks = 0;
  1731. transfer.currentBlock = 0;
  1732. transfer.multiBlock = 0;
  1733. #ifdef PREFETCH_BUFFER_SIZE
  1734. g_scsi_prefetch.bytes = 0;
  1735. g_scsi_prefetch.sector = 0;
  1736. #endif
  1737. // Reinsert any ejected CD-ROMs
  1738. for (int i = 0; i < S2S_MAX_TARGETS; ++i)
  1739. {
  1740. image_config_t &img = g_DiskImages[i];
  1741. if (img.deviceType == S2S_CFG_OPTICAL)
  1742. {
  1743. cdromReinsertFirstImage(img);
  1744. }
  1745. }
  1746. }
  1747. extern "C"
  1748. void scsiDiskInit()
  1749. {
  1750. scsiDiskReset();
  1751. }