ZuluSCSI_disk.cpp 62 KB

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