BlueSCSI_disk.cpp 62 KB

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