ZuluSCSI_disk.cpp 61 KB

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