ZuluSCSI_disk.cpp 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491
  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-2025 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. #include "ZuluSCSI_blink.h"
  32. #ifdef ENABLE_AUDIO_OUTPUT
  33. # include "ZuluSCSI_audio.h"
  34. #endif
  35. #include "ZuluSCSI_cdrom.h"
  36. #include "ImageBackingStore.h"
  37. #include "ROMDrive.h"
  38. #include "QuirksCheck.h"
  39. #include <minIni.h>
  40. #include <string.h>
  41. #include <strings.h>
  42. #include <assert.h>
  43. #include <SdFat.h>
  44. extern "C" {
  45. #include <scsi2sd_time.h>
  46. #include <sd.h>
  47. #include <mode.h>
  48. }
  49. #ifndef PLATFORM_MAX_SCSI_SPEED
  50. #define PLATFORM_MAX_SCSI_SPEED S2S_CFG_SPEED_ASYNC_50
  51. #endif
  52. // This can be overridden in platform file to set the size of the transfers
  53. // used when reading from SCSI bus and writing to SD card.
  54. // When SD card access is fast, these are usually better increased.
  55. // If SD card access is roughly same speed as SCSI bus, these can be left at 512
  56. #ifndef PLATFORM_OPTIMAL_MIN_SD_WRITE_SIZE
  57. #define PLATFORM_OPTIMAL_MIN_SD_WRITE_SIZE 512
  58. #endif
  59. #ifndef PLATFORM_OPTIMAL_MAX_SD_WRITE_SIZE
  60. #define PLATFORM_OPTIMAL_MAX_SD_WRITE_SIZE 1024
  61. #endif
  62. // Optimal size for the last write in a write request.
  63. // This is often better a bit smaller than PLATFORM_OPTIMAL_SD_WRITE_SIZE
  64. // to reduce the dead time between end of SCSI transfer and finishing of SD write.
  65. #ifndef PLATFORM_OPTIMAL_LAST_SD_WRITE_SIZE
  66. #define PLATFORM_OPTIMAL_LAST_SD_WRITE_SIZE 512
  67. #endif
  68. // Optimal size for read block from SCSI bus
  69. // For platforms with nonblocking transfer, this can be large.
  70. // For Akai MPC60 compatibility this has to be at least 5120
  71. #ifndef PLATFORM_OPTIMAL_SCSI_READ_BLOCK_SIZE
  72. #ifdef PLATFORM_SCSIPHY_HAS_NONBLOCKING_READ
  73. #define PLATFORM_OPTIMAL_SCSI_READ_BLOCK_SIZE 65536
  74. #else
  75. #define PLATFORM_OPTIMAL_SCSI_READ_BLOCK_SIZE 8192
  76. #endif
  77. #endif
  78. #ifndef PLATFORM_SCSIPHY_HAS_NONBLOCKING_READ
  79. // For platforms that do not have non-blocking read from SCSI bus
  80. void scsiStartRead(uint8_t* data, uint32_t count, int *parityError)
  81. {
  82. scsiRead(data, count, parityError);
  83. }
  84. void scsiFinishRead(uint8_t* data, uint32_t count, int *parityError)
  85. {
  86. }
  87. bool scsiIsReadFinished(const uint8_t *data)
  88. {
  89. return true;
  90. }
  91. #endif
  92. /************************************************/
  93. /* ROM drive support (in microcontroller flash) */
  94. /************************************************/
  95. // Check if rom drive exists and activate it
  96. bool scsiDiskActivateRomDrive()
  97. {
  98. #ifndef PLATFORM_HAS_ROM_DRIVE
  99. return false;
  100. #else
  101. uint32_t maxsize = platform_get_romdrive_maxsize() - PLATFORM_ROMDRIVE_PAGE_SIZE;
  102. logmsg("-- Platform supports ROM drive up to ", (int)(maxsize / 1024), " kB");
  103. romdrive_hdr_t hdr = {};
  104. if (!romDriveCheckPresent(&hdr))
  105. {
  106. logmsg("---- ROM drive image not detected");
  107. return false;
  108. }
  109. if (ini_getbool("SCSI", "DisableROMDrive", 0, CONFIGFILE))
  110. {
  111. logmsg("---- ROM drive disabled in ini file, not enabling");
  112. return false;
  113. }
  114. long rom_scsi_id = ini_getl("SCSI", "ROMDriveSCSIID", -1, CONFIGFILE);
  115. if (rom_scsi_id >= 0 && rom_scsi_id <= 7)
  116. {
  117. hdr.scsi_id = rom_scsi_id;
  118. logmsg("---- ROM drive SCSI id overriden in ini file, changed to ", (int)hdr.scsi_id);
  119. }
  120. if (s2s_getConfigById(hdr.scsi_id))
  121. {
  122. logmsg("---- ROM drive SCSI id ", (int)hdr.scsi_id, " is already in use, not enabling");
  123. return false;
  124. }
  125. logmsg("---- Activating ROM drive, SCSI id ", (int)hdr.scsi_id, " size ", (int)(hdr.imagesize / 1024), " kB");
  126. g_scsi_settings.initDevice(hdr.scsi_id, hdr.drivetype);
  127. bool status = scsiDiskOpenHDDImage(hdr.scsi_id, "ROM:", 0, hdr.blocksize, hdr.drivetype);
  128. if (!status)
  129. {
  130. logmsg("---- ROM drive activation failed");
  131. return false;
  132. }
  133. else
  134. {
  135. return true;
  136. }
  137. #endif
  138. }
  139. /***********************/
  140. /* Image configuration */
  141. /***********************/
  142. extern SdFs SD;
  143. SdDevice sdDev = {2, 256 * 1024 * 1024 * 2}; /* For SCSI2SD */
  144. image_config_t g_DiskImages[S2S_MAX_TARGETS];
  145. void scsiDiskResetImages()
  146. {
  147. for (int i = 0; i < S2S_MAX_TARGETS; i++)
  148. {
  149. g_DiskImages[i].clear();
  150. }
  151. }
  152. void image_config_t::clear()
  153. {
  154. static const image_config_t empty; // Statically zero-initialized
  155. *this = empty;
  156. }
  157. uint32_t image_config_t::get_capacity_lba()
  158. {
  159. if (bin_container.isOpen() && cuesheetfile.isOpen())
  160. {
  161. size_t halfbufsize = sizeof(scsiDev.data) / 2;
  162. char *cuebuf = (char*)&scsiDev.data[halfbufsize];
  163. cuesheetfile.seekSet(0);
  164. int len = cuesheetfile.read(cuebuf, halfbufsize);
  165. if (len == 0)
  166. return 0;
  167. CUEParser parser(cuebuf);
  168. CUETrackInfo const *track;
  169. CUETrackInfo last_track = {0};
  170. if (bin_container.isDir())
  171. {
  172. FsFile bin_file;
  173. uint64_t prev_capacity = 0;
  174. // Find last track
  175. while((track = parser.next_track(prev_capacity)) != nullptr)
  176. {
  177. last_track = *track;
  178. if (!bin_file.open(&bin_container, track->filename, O_RDONLY | O_BINARY))
  179. {
  180. dbgmsg("Unable to open cue/multi-bin image file \"", track->filename, "\" to determine total capacity");
  181. return 0;
  182. }
  183. prev_capacity = bin_file.size();
  184. bin_file.close();
  185. }
  186. if (last_track.track_number != 0)
  187. return last_track.data_start + prev_capacity / last_track.sector_length;
  188. else
  189. return 0;
  190. }
  191. else
  192. {
  193. // Single bin file
  194. track = parser.next_track();
  195. return track->data_start + bin_container.size() / track->sector_length;
  196. }
  197. }
  198. else
  199. return file.size() / bytesPerSector;
  200. }
  201. void scsiDiskCloseSDCardImages()
  202. {
  203. for (int i = 0; i < S2S_MAX_TARGETS; i++)
  204. {
  205. if (!g_DiskImages[i].file.isRom())
  206. {
  207. g_DiskImages[i].file.close();
  208. }
  209. g_DiskImages[i].cuesheetfile.close();
  210. }
  211. }
  212. // remove path and extension from filename
  213. void extractFileName(const char* path, char* output) {
  214. const char *lastSlash, *lastDot;
  215. int fileNameLength;
  216. lastSlash = strrchr(path, '/');
  217. if (!lastSlash) lastSlash = path;
  218. else lastSlash++;
  219. lastDot = strrchr(lastSlash, '.');
  220. if (lastDot && (lastDot > lastSlash)) {
  221. fileNameLength = lastDot - lastSlash;
  222. strncpy(output, lastSlash, fileNameLength);
  223. output[fileNameLength] = '\0';
  224. } else {
  225. strcpy(output, lastSlash);
  226. }
  227. }
  228. void setNameFromImage(image_config_t &img, const char *filename) {
  229. char image_name[MAX_FILE_PATH];
  230. extractFileName(filename, image_name);
  231. memset(img.vendor, 0, 8);
  232. strncpy(img.vendor, image_name, 8);
  233. memset(img.prodId, 0, 8);
  234. strncpy(img.prodId, image_name+8, 8);
  235. }
  236. // Load values for target image configuration from given section if they exist.
  237. // Otherwise keep current settings.
  238. static void scsiDiskSetImageConfig(uint8_t target_idx)
  239. {
  240. image_config_t &img = g_DiskImages[target_idx];
  241. scsi_system_settings_t *devSys = g_scsi_settings.getSystem();
  242. scsi_device_settings_t *devCfg = g_scsi_settings.getDevice(target_idx);
  243. img.scsiId = target_idx;
  244. memset(img.vendor, 0, sizeof(img.vendor));
  245. memset(img.prodId, 0, sizeof(img.prodId));
  246. memset(img.revision, 0, sizeof(img.revision));
  247. memset(img.serial, 0, sizeof(img.serial));
  248. img.deviceType = devCfg->deviceType;
  249. img.deviceTypeModifier = devCfg->deviceTypeModifier;
  250. img.sectorsPerTrack = devCfg->sectorsPerTrack;
  251. img.headsPerCylinder = devCfg->headsPerCylinder;
  252. img.quirks = devSys->quirks;
  253. img.rightAlignStrings = devCfg->rightAlignStrings;
  254. img.name_from_image = devCfg->nameFromImage;
  255. img.prefetchbytes = devCfg->prefetchBytes;
  256. img.reinsert_on_inquiry = devCfg->reinsertOnInquiry;
  257. img.reinsert_after_eject = devCfg->reinsertAfterEject;
  258. img.ejectButton = devCfg->ejectButton;
  259. img.vendorExtensions = devCfg->vendorExtensions;
  260. #ifdef ENABLE_AUDIO_OUTPUT
  261. uint16_t vol = devCfg->vol;
  262. // Set volume on both channels
  263. audio_set_volume(target_idx, (vol << 8) | vol);
  264. #endif
  265. memcpy(img.vendor, devCfg->vendor, sizeof(img.vendor));
  266. memcpy(img.prodId, devCfg->prodId, sizeof(img.prodId));
  267. memcpy(img.revision, devCfg->revision, sizeof(img.revision));
  268. memcpy(img.serial, devCfg->serial, sizeof(img.serial));
  269. }
  270. static bool find_chs_capacity(uint64_t lba, uint16_t max_cylinders, uint8_t min_heads, uint16_t &c, uint8_t &h, uint8_t &s)
  271. {
  272. bool found_chs = false;
  273. uint32_t cylinders;
  274. for (uint8_t heads = 16 ; heads >= min_heads; heads--)
  275. {
  276. if (lba % heads != 0)
  277. continue;
  278. for (uint8_t sectors = 63; sectors >= 1; sectors--)
  279. {
  280. if (lba % (heads * sectors) == 0)
  281. {
  282. cylinders = lba / (heads * sectors);
  283. if (cylinders > max_cylinders)
  284. continue;
  285. found_chs = true;
  286. c = (uint16_t) cylinders;
  287. h = heads;
  288. s = sectors;
  289. break;
  290. }
  291. }
  292. if (found_chs)
  293. break;
  294. }
  295. return found_chs;
  296. }
  297. static void autoConfigGeometry(image_config_t &img)
  298. {
  299. const char *method = "INI config";
  300. if (img.sectorsPerTrack == 0 || img.headsPerCylinder == 0)
  301. {
  302. uint16_t cyl = 0;
  303. uint8_t head = 255;
  304. uint8_t sect = 63;
  305. bool found_chs = false;
  306. if (img.deviceType == S2S_CFG_FLOPPY_14MB && img.scsiSectors <= 2880)
  307. {
  308. method = "device type floppy";
  309. sect = 18;
  310. head = 80;
  311. }
  312. else if (img.scsiSectors <= 1032192)
  313. {
  314. found_chs = find_chs_capacity(img.scsiSectors, 1024, 1, cyl, head, sect);
  315. method = "image size";
  316. }
  317. else if (img.scsiSectors <= 16514064)
  318. {
  319. found_chs = find_chs_capacity(img.scsiSectors, 16383, 9, cyl, head, sect);
  320. if (!found_chs)
  321. found_chs = find_chs_capacity(img.scsiSectors, 32767, 5, cyl, head, sect);
  322. if (!found_chs)
  323. found_chs = find_chs_capacity(img.scsiSectors, 65535, 1, cyl, head, sect);
  324. method = "image size";
  325. }
  326. if (!found_chs)
  327. {
  328. head = 255;
  329. sect = 63;
  330. method = "defaults";
  331. }
  332. img.sectorsPerTrack = sect;
  333. img.headsPerCylinder = head;
  334. }
  335. bool divisible = (img.scsiSectors % ((uint32_t)img.sectorsPerTrack * img.headsPerCylinder)) == 0;
  336. logmsg("---- Drive geometry from ", method,
  337. ": SectorsPerTrack=", (int)img.sectorsPerTrack,
  338. " HeadsPerCylinder=", (int)img.headsPerCylinder,
  339. " total sectors ", (int)img.scsiSectors,
  340. divisible ? " (divisible)" : " (not divisible)"
  341. );
  342. }
  343. bool scsiDiskOpenHDDImage(int target_idx, const char *filename, int scsi_lun, int blocksize, S2S_CFG_TYPE type, bool use_prefix)
  344. {
  345. image_config_t &img = g_DiskImages[target_idx];
  346. img.cuesheetfile.close();
  347. img.bin_container.close();
  348. img.cdrom_binfile_index = -1;
  349. scsiDiskSetImageConfig(target_idx);
  350. img.file = ImageBackingStore(filename, blocksize);
  351. if (img.file.isOpen())
  352. {
  353. img.bytesPerSector = blocksize;
  354. img.scsiSectors = img.file.size() / blocksize;
  355. img.scsiId = target_idx | S2S_CFG_TARGET_ENABLED;
  356. img.sdSectorStart = 0;
  357. if (img.scsiSectors == 0 && type != S2S_CFG_NETWORK && !img.file.isFolder())
  358. {
  359. logmsg("---- Error: image file ", filename, " is empty");
  360. img.file.close();
  361. return false;
  362. }
  363. uint32_t sector_begin = 0, sector_end = 0;
  364. if (img.file.isRom() || type == S2S_CFG_NETWORK || img.file.isFolder())
  365. {
  366. // ROM is always contiguous, no need to log
  367. }
  368. else if (img.file.isContiguous() && img.file.contiguousRange(&sector_begin, &sector_end))
  369. {
  370. #ifdef ZULUSCSI_HARDWARE_CONFIG
  371. if (g_hw_config.is_active())
  372. {
  373. dbgmsg("---- Device spans SD card sectors ", (int)sector_begin, " to ", (int)sector_end);
  374. }
  375. else
  376. #endif // ZULUSCSI_HARDWARE_CONFIG
  377. {
  378. dbgmsg("---- Image file is contiguous, SD card sectors ", (int)sector_begin, " to ", (int)sector_end);
  379. }
  380. }
  381. else
  382. {
  383. logmsg("---- WARNING: file ", filename, " is not contiguous. This will increase read latency.");
  384. }
  385. S2S_CFG_TYPE setting_type = (S2S_CFG_TYPE) g_scsi_settings.getDevice(target_idx)->deviceType;
  386. if ( setting_type != S2S_CFG_NOT_SET)
  387. {
  388. type = setting_type;
  389. }
  390. if (type == S2S_CFG_FIXED)
  391. {
  392. logmsg("---- Configuring as disk drive drive");
  393. img.deviceType = S2S_CFG_FIXED;
  394. }
  395. else if (type == S2S_CFG_OPTICAL)
  396. {
  397. logmsg("---- Configuring as CD-ROM drive");
  398. img.deviceType = S2S_CFG_OPTICAL;
  399. if (g_scsi_settings.getDevice(target_idx)->vendorExtensions & VENDOR_EXTENSION_OPTICAL_PLEXTOR)
  400. {
  401. logmsg("---- Plextor 0xD8 vendor extension enabled");
  402. }
  403. }
  404. else if (type == S2S_CFG_FLOPPY_14MB)
  405. {
  406. logmsg("---- Configuring as floppy drive");
  407. img.deviceType = S2S_CFG_FLOPPY_14MB;
  408. }
  409. else if (type == S2S_CFG_MO)
  410. {
  411. logmsg("---- Configuring as magneto-optical");
  412. img.deviceType = S2S_CFG_MO;
  413. }
  414. #ifdef ZULUSCSI_NETWORK
  415. else if (type == S2S_CFG_NETWORK)
  416. {
  417. logmsg("---- Configuring as network based on image name");
  418. img.deviceType = S2S_CFG_NETWORK;
  419. }
  420. #endif // ZULUSCSI_NETWORK
  421. else if (type == S2S_CFG_REMOVABLE)
  422. {
  423. logmsg("---- Configuring as removable drive");
  424. img.deviceType = S2S_CFG_REMOVABLE;
  425. }
  426. else if (type == S2S_CFG_SEQUENTIAL)
  427. {
  428. logmsg("---- Configuring as tape drive");
  429. img.deviceType = S2S_CFG_SEQUENTIAL;
  430. img.tape_mark_count = 0;
  431. scsiDev.target->sense.filemark = false;
  432. scsiDev.target->sense.eom = false;
  433. }
  434. else if (type == S2S_CFG_ZIP100)
  435. {
  436. logmsg("---- Configuration as Iomega Zip100");
  437. img.deviceType = S2S_CFG_ZIP100;
  438. if(img.file.size() != ZIP100_DISK_SIZE)
  439. {
  440. logmsg("---- Zip 100 disk (", (int)img.file.size(), " bytes) is not exactly ", ZIP100_DISK_SIZE, " bytes, may not work correctly");
  441. }
  442. }
  443. if (type != S2S_CFG_OPTICAL && type != S2S_CFG_NETWORK)
  444. {
  445. autoConfigGeometry(img);
  446. }
  447. quirksCheck(&img);
  448. if (img.name_from_image)
  449. {
  450. setNameFromImage(img, filename);
  451. logmsg("---- Vendor / product id set from image file name");
  452. }
  453. if (type == S2S_CFG_NETWORK)
  454. {
  455. // prefetch not used, skip emitting log message
  456. }
  457. else if (img.prefetchbytes > 0)
  458. {
  459. logmsg("---- Read prefetch enabled: ", (int)img.prefetchbytes, " bytes");
  460. }
  461. else
  462. {
  463. logmsg("---- Read prefetch disabled");
  464. }
  465. if (img.deviceType == S2S_CFG_OPTICAL &&
  466. strncasecmp(filename + strlen(filename) - 4, ".bin", 4) == 0)
  467. {
  468. // Check for .cue sheet with single .bin file
  469. char cuesheetname[MAX_FILE_PATH + 1] = {0};
  470. strncpy(cuesheetname, filename, strlen(filename) - 4);
  471. strlcat(cuesheetname, ".cue", sizeof(cuesheetname));
  472. img.cuesheetfile = SD.open(cuesheetname, O_RDONLY);
  473. if (img.cuesheetfile.isOpen())
  474. {
  475. logmsg("---- Found CD-ROM CUE sheet at ", cuesheetname);
  476. if (!cdromValidateCueSheet(img))
  477. {
  478. logmsg("---- Failed to parse cue sheet, using as plain binary image");
  479. img.cuesheetfile.close();
  480. }
  481. else
  482. {
  483. // Set bin container to single bin file
  484. img.bin_container.open(filename);
  485. // If bin container is a directory close the file
  486. if (img.bin_container.isDir())
  487. img.bin_container.close();
  488. }
  489. }
  490. else
  491. {
  492. logmsg("---- No CUE sheet found at ", cuesheetname, ", using as plain binary image");
  493. }
  494. }
  495. else if (img.deviceType == S2S_CFG_OPTICAL && img.file.isFolder())
  496. {
  497. // The folder should contain .cue sheet and one or several .bin files
  498. char foldername[MAX_FILE_PATH + 1] = {0};
  499. char cuesheetname[MAX_FILE_PATH + 1] = {0};
  500. img.file.getFoldername(foldername, sizeof(foldername));
  501. FsFile folder = SD.open(foldername, O_RDONLY);
  502. bool valid = false;
  503. img.cuesheetfile.close();
  504. while (!valid && img.cuesheetfile.openNext(&folder, O_RDONLY))
  505. {
  506. img.cuesheetfile.getName(cuesheetname, sizeof(cuesheetname));
  507. if (strncasecmp(cuesheetname + strlen(cuesheetname) - 4, ".cue", 4) == 0)
  508. {
  509. valid = cdromValidateCueSheet(img);
  510. }
  511. }
  512. if (valid)
  513. {
  514. img.bin_container.open(foldername);
  515. }
  516. else
  517. {
  518. logmsg("No valid .cue sheet found in folder '", foldername, "'");
  519. img.cuesheetfile.close();
  520. }
  521. }
  522. else if (img.deviceType == S2S_CFG_SEQUENTIAL && img.file.isFolder())
  523. {
  524. // multi file tape that implements tape markers
  525. char name[MAX_FILE_PATH + 1] = {0};
  526. img.file.getFoldername(name, sizeof(name));
  527. img.bin_container.open(name);
  528. FsFile file;
  529. bool valid = false;
  530. while(file.openNext(&img.bin_container))
  531. {
  532. file.getName(name, sizeof(name));
  533. if(!file.isDir() && !file.isHidden() && scsiDiskFilenameValid(name))
  534. {
  535. valid = true;
  536. img.tape_mark_count++;
  537. }
  538. }
  539. if (!valid)
  540. {
  541. // if there are no valid image files, create one
  542. file.open(&img.bin_container, TAPE_DEFAULT_NAME, O_CREAT);
  543. file.close();
  544. }
  545. img.tape_mark_index = 0;
  546. img.tape_mark_block_offset = 0;
  547. img.tape_load_next_file = false;
  548. }
  549. img.use_prefix = use_prefix;
  550. img.file.getFilename(img.current_image, sizeof(img.current_image));
  551. return true;
  552. }
  553. else
  554. {
  555. logmsg("---- Failed to load image '", filename, "', ignoring");
  556. return false;
  557. }
  558. }
  559. static void checkDiskGeometryDivisible(image_config_t &img)
  560. {
  561. if (!img.geometrywarningprinted)
  562. {
  563. uint32_t sectorsPerHeadTrack = img.sectorsPerTrack * img.headsPerCylinder;
  564. if (img.scsiSectors % sectorsPerHeadTrack != 0)
  565. {
  566. logmsg("WARNING: Host used command ", scsiDev.cdb[0],
  567. " which is affected by drive geometry. Current settings are ",
  568. (int)img.sectorsPerTrack, " sectors x ", (int)img.headsPerCylinder, " heads = ",
  569. (int)sectorsPerHeadTrack, " but image size of ", (int)img.scsiSectors,
  570. " sectors is not divisible. This can cause error messages in diagnostics tools.");
  571. img.geometrywarningprinted = true;
  572. }
  573. }
  574. }
  575. bool scsiDiskFilenameValid(const char* name)
  576. {
  577. // Check file extension
  578. const char *extension = strrchr(name, '.');
  579. if (extension)
  580. {
  581. const char *ignore_exts[] = {
  582. ".rom_loaded", ".cue", ".txt", ".rtf", ".md", ".nfo", ".pdf", ".doc",
  583. ".ini", ".mid", ".midi", ".aiff", ".mp3", ".m4a",
  584. NULL
  585. };
  586. const char *archive_exts[] = {
  587. ".tar", ".tgz", ".gz", ".bz2", ".tbz2", ".xz", ".zst", ".z",
  588. ".zip", ".zipx", ".rar", ".lzh", ".lha", ".lzo", ".lz4", ".arj",
  589. ".dmg", ".hqx", ".cpt", ".7z", ".s7z", ".mid", ".wav", ".aiff",
  590. NULL
  591. };
  592. for (int i = 0; ignore_exts[i]; i++)
  593. {
  594. if (strcasecmp(extension, ignore_exts[i]) == 0)
  595. {
  596. // ignore these without log message
  597. return false;
  598. }
  599. }
  600. for (int i = 0; archive_exts[i]; i++)
  601. {
  602. if (strcasecmp(extension, archive_exts[i]) == 0)
  603. {
  604. logmsg("-- Ignoring compressed file ", name);
  605. return false;
  606. }
  607. }
  608. }
  609. // Check first character
  610. if (!isalnum(name[0]))
  611. {
  612. // ignore files that don't start with a letter or a number
  613. return false;
  614. }
  615. return true;
  616. }
  617. bool scsiDiskFolderContainsCueSheet(FsFile *dir)
  618. {
  619. FsFile file;
  620. char filename[MAX_FILE_PATH + 1];
  621. while (file.openNext(dir, O_RDONLY))
  622. {
  623. if (file.getName(filename, sizeof(filename)) &&
  624. (strncasecmp(filename + strlen(filename) - 4, ".cue", 4) == 0))
  625. {
  626. return true;
  627. }
  628. }
  629. return false;
  630. }
  631. bool scsiDiskFolderIsTapeFolder(FsFile *dir)
  632. {
  633. char filename[MAX_FILE_PATH + 1];
  634. dir->getName(filename, sizeof(filename));
  635. // string starts with 'tp', the 3rd character is a SCSI ID, and it has more 3 charters
  636. // e.g. "tp0 - tape 01"
  637. if (strlen(filename) > 3 && strncasecmp("tp", filename, 2) == 0
  638. && filename[2] >= '0' && filename[2] - '0' < NUM_SCSIID)
  639. {
  640. return true;
  641. }
  642. return false;
  643. }
  644. static void scsiDiskCheckDir(char * dir_name, int target_idx, image_config_t* img, S2S_CFG_TYPE type, const char* type_name)
  645. {
  646. if (SD.exists(dir_name))
  647. {
  648. if (img->image_directory)
  649. {
  650. logmsg("-- Already found an image directory, skipping '", dir_name, "'");
  651. }
  652. else
  653. {
  654. img->deviceType = type;
  655. img->image_directory = true;
  656. logmsg("SCSI", target_idx, " searching default ", type_name, " image directory '", dir_name, "'");
  657. }
  658. }
  659. }
  660. // Load values for target configuration from given section if they exist.
  661. // Otherwise keep current settings.
  662. static void scsiDiskSetConfig(int target_idx)
  663. {
  664. image_config_t &img = g_DiskImages[target_idx];
  665. img.scsiId = target_idx;
  666. scsiDiskSetImageConfig(target_idx);
  667. char section[6] = "SCSI0";
  668. section[4] += target_idx;
  669. char tmp[32];
  670. ini_gets(section, "ImgDir", "", tmp, sizeof(tmp), CONFIGFILE);
  671. if (tmp[0])
  672. {
  673. logmsg("SCSI", target_idx, " using image directory '", tmp, "'");
  674. img.image_directory = true;
  675. }
  676. else
  677. {
  678. strcpy(tmp, "HD0");
  679. tmp[2] += target_idx;
  680. scsiDiskCheckDir(tmp, target_idx, &img, S2S_CFG_FIXED, "disk");
  681. strcpy(tmp, "CD0");
  682. tmp[2] += target_idx;
  683. scsiDiskCheckDir(tmp, target_idx, &img, S2S_CFG_OPTICAL, "optical");
  684. strcpy(tmp, "RE0");
  685. tmp[2] += target_idx;
  686. scsiDiskCheckDir(tmp, target_idx, &img, S2S_CFG_REMOVABLE, "removable");
  687. strcpy(tmp, "MO0");
  688. tmp[2] += target_idx;
  689. scsiDiskCheckDir(tmp, target_idx, &img, S2S_CFG_MO, "magneto-optical");
  690. strcpy(tmp, "TP0");
  691. tmp[2] += target_idx;
  692. scsiDiskCheckDir(tmp, target_idx, &img, S2S_CFG_SEQUENTIAL, "tape");
  693. strcpy(tmp, "FD0");
  694. tmp[2] += target_idx;
  695. scsiDiskCheckDir(tmp, target_idx, &img, S2S_CFG_FLOPPY_14MB, "floppy");
  696. strcpy(tmp, "ZP0");
  697. tmp[2] += target_idx;
  698. scsiDiskCheckDir(tmp, target_idx, &img, S2S_CFG_ZIP100, "Iomega Zip 100");
  699. }
  700. g_scsi_settings.initDevice(target_idx, (S2S_CFG_TYPE)img.deviceType);
  701. }
  702. // Compares the prefix of both files and the scsi ID
  703. // cd3-name.iso and CD3-otherfile.bin matches, zp3.img or cd4-name.iso would not
  704. static bool compare_prefix(const char* name, const char* compare)
  705. {
  706. if (strlen(name) >= 3 && strlen(compare) >= 3)
  707. {
  708. if (tolower(name[0]) == tolower(compare[0])
  709. && tolower(name[1]) == tolower(compare[1])
  710. && tolower(name[2]) == tolower(compare[2])
  711. )
  712. return true;
  713. }
  714. return false;
  715. }
  716. /***********************/
  717. /* Start/stop commands */
  718. /***********************/
  719. static void doCloseTray(image_config_t &img)
  720. {
  721. if (img.ejected)
  722. {
  723. uint8_t target = img.scsiId & 7;
  724. dbgmsg("------ Device close tray on ID ", (int)target);
  725. img.ejected = false;
  726. if (scsiDev.boardCfg.flags & S2S_CFG_ENABLE_UNIT_ATTENTION)
  727. {
  728. dbgmsg("------ Posting UNIT ATTENTION after medium change");
  729. scsiDev.targets[target].unitAttention = NOT_READY_TO_READY_TRANSITION_MEDIUM_MAY_HAVE_CHANGED;
  730. }
  731. }
  732. }
  733. // Eject and switch image
  734. static void doPerformEject(image_config_t &img)
  735. {
  736. uint8_t target = img.scsiId & 7;
  737. if (!img.ejected)
  738. {
  739. blink_cancel();
  740. blinkStatus(g_scsi_settings.getDevice(target)->ejectBlinkTimes, g_scsi_settings.getDevice(target)->ejectBlinkPeriod);;
  741. dbgmsg("------ Device open tray on ID ", (int)target);
  742. img.ejected = true;
  743. switchNextImage(img); // Switch media for next time
  744. }
  745. else
  746. {
  747. doCloseTray(img);
  748. }
  749. }
  750. int findNextImageAfter(image_config_t &img,
  751. const char* dirname, const char* filename,
  752. char* buf, size_t buflen, bool ignore_prefix)
  753. {
  754. FsFile dir;
  755. if (dirname[0] == '\0')
  756. {
  757. logmsg("Image directory name invalid for ID", (img.scsiId & S2S_CFG_TARGET_ID_BITS));
  758. return 0;
  759. }
  760. if (!dir.open(dirname))
  761. {
  762. logmsg("Image directory '", dirname, "' couldn't be opened");
  763. return 0;
  764. }
  765. if (!dir.isDir())
  766. {
  767. logmsg("Can't find images in '", dirname, "', not a directory");
  768. dir.close();
  769. return 0;
  770. }
  771. if (dir.isHidden())
  772. {
  773. logmsg("Image directory '", dirname, "' is hidden, skipping");
  774. dir.close();
  775. return 0;
  776. }
  777. char first_name[MAX_FILE_PATH] = {'\0'};
  778. char candidate_name[MAX_FILE_PATH] = {'\0'};
  779. FsFile file;
  780. while (file.openNext(&dir, O_RDONLY))
  781. {
  782. if (file.isDir() && !scsiDiskFolderContainsCueSheet(&file)) continue;
  783. if (!file.getName(buf, MAX_FILE_PATH))
  784. {
  785. logmsg("Image directory '", dirname, "' had invalid file");
  786. continue;
  787. }
  788. if (!scsiDiskFilenameValid(buf)) continue;
  789. if (file.isHidden()) {
  790. logmsg("Image '", dirname, "/", buf, "' is hidden, skipping file");
  791. continue;
  792. }
  793. if (!ignore_prefix && img.use_prefix && !compare_prefix(filename, buf)) continue;
  794. // keep track of the first item to allow wrapping
  795. // without having to iterate again
  796. if (first_name[0] == '\0' || strcasecmp(buf, first_name) < 0)
  797. {
  798. strncpy(first_name, buf, sizeof(first_name));
  799. }
  800. // discard if no selected name, or if candidate is before (or is) selected
  801. // or prefix searching is enabled and file doesn't contain current prefix
  802. if (filename[0] == '\0' || strcasecmp(buf, filename) <= 0) continue;
  803. // if we got this far and the candidate is either 1) not set, or 2) is a
  804. // lower item than what has been encountered thus far, it is the best choice
  805. if (candidate_name[0] == '\0' || strcasecmp(buf, candidate_name) < 0)
  806. {
  807. strncpy(candidate_name, buf, sizeof(candidate_name));
  808. }
  809. }
  810. if (candidate_name[0] != '\0')
  811. {
  812. img.image_index++;
  813. strncpy(img.current_image, candidate_name, sizeof(img.current_image));
  814. strncpy(buf, candidate_name, buflen);
  815. return strlen(candidate_name);
  816. }
  817. else if (first_name[0] != '\0')
  818. {
  819. img.image_index = 0;
  820. strncpy(img.current_image, first_name, sizeof(img.current_image));
  821. strncpy(buf, first_name, buflen);
  822. return strlen(first_name);
  823. }
  824. else
  825. {
  826. logmsg("Image directory '", dirname, "' was empty");
  827. img.image_directory = false;
  828. return 0;
  829. }
  830. }
  831. int scsiDiskGetNextImageName(image_config_t &img, char *buf, size_t buflen)
  832. {
  833. int target_idx = img.scsiId & S2S_CFG_TARGET_ID_BITS;
  834. char section[6] = "SCSI0";
  835. section[4] = '0' + target_idx;
  836. // sanity check: is provided buffer is long enough to store a filename?
  837. assert(buflen >= MAX_FILE_PATH);
  838. // find the next filename
  839. char nextname[MAX_FILE_PATH];
  840. int nextlen;
  841. if (img.image_directory)
  842. {
  843. // image directory was found during startup
  844. char dirname[MAX_FILE_PATH];
  845. char key[] = "ImgDir";
  846. int dirlen = ini_gets(section, key, "", dirname, sizeof(dirname), CONFIGFILE);
  847. if (!dirlen)
  848. {
  849. switch (img.deviceType)
  850. {
  851. case S2S_CFG_FIXED:
  852. strcpy(dirname ,"HD0");
  853. break;
  854. case S2S_CFG_OPTICAL:
  855. strcpy(dirname, "CD0");
  856. break;
  857. case S2S_CFG_REMOVABLE:
  858. strcpy(dirname, "RE0");
  859. break;
  860. case S2S_CFG_MO:
  861. strcpy(dirname, "MO0");
  862. break;
  863. case S2S_CFG_SEQUENTIAL:
  864. strcpy(dirname ,"TP0");
  865. break;
  866. case S2S_CFG_FLOPPY_14MB:
  867. strcpy(dirname, "FD0");
  868. break;
  869. case S2S_CFG_ZIP100:
  870. strcpy(dirname, "ZP0");
  871. break;
  872. default:
  873. dbgmsg("No matching device type for default directory found");
  874. return 0;
  875. }
  876. dirname[2] += target_idx;
  877. if (!SD.exists(dirname))
  878. {
  879. dbgmsg("Default image directory, ", dirname, " does not exist");
  880. return 0;
  881. }
  882. }
  883. // find the next filename
  884. nextlen = findNextImageAfter(img, dirname, img.current_image, nextname, sizeof(nextname));
  885. if (nextlen == 0)
  886. {
  887. logmsg("Image directory was empty for ID", target_idx);
  888. return 0;
  889. }
  890. else if (buflen < nextlen + dirlen + 2)
  891. {
  892. logmsg("Directory '", dirname, "' and file '", nextname, "' exceed allowed length");
  893. return 0;
  894. }
  895. else
  896. {
  897. // construct a return value
  898. strncpy(buf, dirname, buflen);
  899. if (buf[strlen(buf) - 1] != '/') strcat(buf, "/");
  900. strcat(buf, nextname);
  901. return dirlen + nextlen;
  902. }
  903. }
  904. else if (img.use_prefix)
  905. {
  906. nextlen = findNextImageAfter(img, "/", img.current_image, nextname, sizeof(nextname));
  907. if (nextlen == 0)
  908. {
  909. logmsg("Next file with the same prefix as ", img.current_image," not found for ID", target_idx);
  910. }
  911. else if (buflen < nextlen + 1)
  912. {
  913. logmsg("Next file exceeds, '",nextname, "' exceed allowed length");
  914. }
  915. else
  916. {
  917. // construct a return value
  918. strncpy(buf, nextname, buflen);
  919. return nextlen;
  920. }
  921. img.image_index = -1;
  922. return 0;
  923. }
  924. else
  925. {
  926. img.image_index++;
  927. if (img.image_index > IMAGE_INDEX_MAX || img.image_index < 0)
  928. {
  929. img.image_index = 0;
  930. }
  931. char key[5] = "IMG0";
  932. key[3] = '0' + img.image_index;
  933. int ret = ini_gets(section, key, "", buf, buflen, CONFIGFILE);
  934. if (buf[0] != '\0')
  935. {
  936. img.deviceType = g_scsi_settings.getDevice(target_idx)->deviceType;
  937. return ret;
  938. }
  939. else if (img.image_index > 0)
  940. {
  941. // there may be more than one image but we've ran out of new ones
  942. // wrap back to the first image
  943. img.image_index = -1;
  944. return scsiDiskGetNextImageName(img, buf, buflen);
  945. }
  946. else
  947. {
  948. img.image_index = -1;
  949. return 0;
  950. }
  951. }
  952. }
  953. void scsiDiskLoadConfig(int target_idx)
  954. {
  955. // Then settings specific to target ID
  956. scsiDiskSetConfig(target_idx);
  957. // Check if we have image specified by name
  958. char filename[MAX_FILE_PATH];
  959. image_config_t &img = g_DiskImages[target_idx];
  960. img.image_index = IMAGE_INDEX_MAX;
  961. if (scsiDiskGetNextImageName(img, filename, sizeof(filename)))
  962. {
  963. // set the default block size now that we know the device type
  964. if (g_scsi_settings.getDevice(target_idx)->blockSize == 0)
  965. {
  966. g_scsi_settings.getDevice(target_idx)->blockSize = img.deviceType == S2S_CFG_OPTICAL ? DEFAULT_BLOCKSIZE_OPTICAL : DEFAULT_BLOCKSIZE;
  967. }
  968. int blocksize = getBlockSize(filename, target_idx);
  969. logmsg("-- Opening '", filename, "' for id: ", target_idx);
  970. scsiDiskOpenHDDImage(target_idx, filename, 0, blocksize, (S2S_CFG_TYPE) img.deviceType, img.use_prefix);
  971. }
  972. }
  973. uint32_t getBlockSize(char *filename, uint8_t scsi_id)
  974. {
  975. // Parse block size (HD00_NNNN)
  976. uint32_t block_size = g_scsi_settings.getDevice(scsi_id)->blockSize;
  977. const char *blksizestr = strchr(filename, '_');
  978. if (blksizestr)
  979. {
  980. int blktmp = strtoul(blksizestr + 1, NULL, 10);
  981. if (8 <= blktmp && blktmp <= 64 * 1024)
  982. {
  983. block_size = blktmp;
  984. logmsg("-- Using custom block size, ",(int) block_size," from filename: ", filename);
  985. }
  986. }
  987. return block_size;
  988. }
  989. uint8_t getEjectButton(uint8_t idx)
  990. {
  991. return g_DiskImages[idx].ejectButton;
  992. }
  993. void setEjectButton(uint8_t idx, int8_t eject_button)
  994. {
  995. g_DiskImages[idx].ejectButton = eject_button;
  996. g_scsi_settings.getDevice(idx)->ejectButton = eject_button;
  997. }
  998. // Check if we have multiple drive images to cycle when drive is ejected.
  999. bool switchNextImage(image_config_t &img, const char* next_filename)
  1000. {
  1001. // Check if we have a next image to load, so that drive is closed next time the host asks.
  1002. int target_idx = img.scsiId & 7;
  1003. char filename[MAX_FILE_PATH];
  1004. if (next_filename == nullptr)
  1005. {
  1006. scsiDiskGetNextImageName(img, filename, sizeof(filename));
  1007. }
  1008. else
  1009. {
  1010. strncpy(filename, next_filename, MAX_FILE_PATH);
  1011. }
  1012. #ifdef ENABLE_AUDIO_OUTPUT
  1013. // if in progress for this device, terminate audio playback immediately (Annex C)
  1014. audio_stop(target_idx);
  1015. // Reset position tracking for the new image
  1016. audio_get_status_code(target_idx); // trash audio status code
  1017. #endif
  1018. if (filename[0] != '\0')
  1019. {
  1020. logmsg("Switching to next image for id ", target_idx, ": ", filename);
  1021. img.file.close();
  1022. // set default blocksize for CDs
  1023. int block_size = getBlockSize(filename, target_idx);
  1024. bool status = scsiDiskOpenHDDImage(target_idx, filename, 0, block_size, (S2S_CFG_TYPE) img.deviceType, img.use_prefix);
  1025. if (status)
  1026. {
  1027. if (next_filename != nullptr)
  1028. {
  1029. // present the drive as ejected until the host queries it again,
  1030. // to make sure host properly detects the media change
  1031. img.ejected = true;
  1032. img.reinsert_after_eject = true;
  1033. if (img.deviceType == S2S_CFG_OPTICAL) img.cdrom_events = 2; // New Media
  1034. }
  1035. return true;
  1036. }
  1037. }
  1038. else
  1039. {
  1040. logmsg("Switch to next image failed because target filename was empty.");
  1041. }
  1042. return false;
  1043. }
  1044. bool scsiDiskCheckAnyImagesConfigured()
  1045. {
  1046. for (int i = 0; i < S2S_MAX_TARGETS; i++)
  1047. {
  1048. if (g_DiskImages[i].file.isOpen() && (g_DiskImages[i].scsiId & S2S_CFG_TARGET_ENABLED))
  1049. {
  1050. return true;
  1051. }
  1052. }
  1053. return false;
  1054. }
  1055. image_config_t &scsiDiskGetImageConfig(int target_idx)
  1056. {
  1057. assert(target_idx >= 0 && target_idx < S2S_MAX_TARGETS);
  1058. return g_DiskImages[target_idx];
  1059. }
  1060. static void diskEjectAction(uint8_t buttonId)
  1061. {
  1062. bool found = false;
  1063. for (uint8_t i = 0; i < S2S_MAX_TARGETS; i++)
  1064. {
  1065. image_config_t &img = g_DiskImages[i];
  1066. if (img.ejectButton & buttonId)
  1067. {
  1068. if (img.deviceType == S2S_CFG_OPTICAL)
  1069. {
  1070. found = true;
  1071. logmsg("Eject button ", (int)buttonId, " pressed, passing to CD drive SCSI", (int)i);
  1072. cdromPerformEject(img);
  1073. }
  1074. else if (img.deviceType == S2S_CFG_ZIP100
  1075. || img.deviceType == S2S_CFG_REMOVABLE
  1076. || img.deviceType == S2S_CFG_FLOPPY_14MB
  1077. || img.deviceType == S2S_CFG_MO
  1078. || img.deviceType == S2S_CFG_SEQUENTIAL)
  1079. {
  1080. found = true;
  1081. logmsg("Eject button ", (int)buttonId, " pressed, passing to SCSI device", (int)i);
  1082. doPerformEject(img);
  1083. }
  1084. }
  1085. }
  1086. if (!found)
  1087. {
  1088. logmsg("Eject button ", (int)buttonId, " pressed, but no drives with EjectButton=", (int)buttonId, " setting found!");
  1089. }
  1090. }
  1091. uint8_t diskEjectButtonUpdate(bool immediate)
  1092. {
  1093. // treat '1' to '0' transitions as eject actions
  1094. static uint8_t previous = 0x00;
  1095. uint8_t bitmask = platform_get_buttons() & EJECT_BTN_MASK;
  1096. uint8_t ejectors = (previous ^ bitmask) & previous;
  1097. previous = bitmask;
  1098. // defer ejection until the bus is idle
  1099. static uint8_t deferred = 0x00;
  1100. if (!immediate)
  1101. {
  1102. deferred |= ejectors;
  1103. return 0;
  1104. }
  1105. else
  1106. {
  1107. ejectors |= deferred;
  1108. deferred = 0;
  1109. if (ejectors)
  1110. {
  1111. uint8_t mask = 1;
  1112. for (uint8_t i = 0; i < 8; i++)
  1113. {
  1114. if (ejectors & mask) diskEjectAction(ejectors & mask);
  1115. mask = mask << 1;
  1116. }
  1117. }
  1118. return ejectors;
  1119. }
  1120. }
  1121. bool scsiDiskCheckAnyNetworkDevicesConfigured()
  1122. {
  1123. for (int i = 0; i < S2S_MAX_TARGETS; i++)
  1124. {
  1125. if (g_DiskImages[i].file.isOpen() && (g_DiskImages[i].scsiId & S2S_CFG_TARGET_ENABLED) && g_DiskImages[i].deviceType == S2S_CFG_NETWORK)
  1126. {
  1127. return true;
  1128. }
  1129. }
  1130. return false;
  1131. }
  1132. /*******************************/
  1133. /* Config handling for SCSI2SD */
  1134. /*******************************/
  1135. extern "C"
  1136. void s2s_configInit(S2S_BoardCfg* config)
  1137. {
  1138. char tmp[64];
  1139. if (SD.exists(CONFIGFILE))
  1140. {
  1141. logmsg("Reading configuration from " CONFIGFILE);
  1142. }
  1143. else
  1144. {
  1145. logmsg("Config file " CONFIGFILE " not found, using defaults");
  1146. }
  1147. // Get default values from system preset, if any
  1148. ini_gets("SCSI", "System", "", tmp, sizeof(tmp), CONFIGFILE);
  1149. scsi_system_settings_t *sysCfg = g_scsi_settings.initSystem(tmp);
  1150. if (g_scsi_settings.getSystemPreset() != SYS_PRESET_NONE)
  1151. {
  1152. logmsg("Active configuration (using system preset \"", g_scsi_settings.getSystemPresetName(), "\"):");
  1153. }
  1154. else
  1155. {
  1156. logmsg("Active configuration:");
  1157. }
  1158. memset(config, 0, sizeof(S2S_BoardCfg));
  1159. memcpy(config->magic, "BCFG", 4);
  1160. config->flags = 0;
  1161. config->startupDelay = 0;
  1162. config->selectionDelay = sysCfg->selectionDelay;
  1163. config->flags6 = 0;
  1164. config->scsiSpeed = PLATFORM_MAX_SCSI_SPEED;
  1165. int maxSyncSpeed = sysCfg->maxSyncSpeed;
  1166. if (maxSyncSpeed < 5 && config->scsiSpeed > S2S_CFG_SPEED_ASYNC_50)
  1167. config->scsiSpeed = S2S_CFG_SPEED_ASYNC_50;
  1168. else if (maxSyncSpeed < 10 && config->scsiSpeed > S2S_CFG_SPEED_SYNC_5)
  1169. config->scsiSpeed = S2S_CFG_SPEED_SYNC_5;
  1170. else if (maxSyncSpeed < 20 && config->scsiSpeed > S2S_CFG_SPEED_SYNC_10)
  1171. config->scsiSpeed = S2S_CFG_SPEED_SYNC_10;
  1172. logmsg("-- SelectionDelay = ", (int)config->selectionDelay);
  1173. if (sysCfg->enableUnitAttention)
  1174. {
  1175. logmsg("-- EnableUnitAttention = Yes");
  1176. config->flags |= S2S_CFG_ENABLE_UNIT_ATTENTION;
  1177. }
  1178. else
  1179. {
  1180. logmsg("-- EnableUnitAttention = No");
  1181. }
  1182. if (sysCfg->enableSCSI2)
  1183. {
  1184. logmsg("-- EnableSCSI2 = Yes");
  1185. config->flags |= S2S_CFG_ENABLE_SCSI2;
  1186. }
  1187. else
  1188. {
  1189. logmsg("-- EnableSCSI2 = No");
  1190. }
  1191. if (sysCfg->enableSelLatch)
  1192. {
  1193. logmsg("-- EnableSelLatch = Yes");
  1194. config->flags |= S2S_CFG_ENABLE_SEL_LATCH;
  1195. }
  1196. else
  1197. {
  1198. logmsg("-- EnableSelLatch = No");
  1199. }
  1200. if (sysCfg->mapLunsToIDs)
  1201. {
  1202. logmsg("-- MapLunsToIDs = Yes");
  1203. config->flags |= S2S_CFG_MAP_LUNS_TO_IDS;
  1204. }
  1205. else
  1206. {
  1207. logmsg("-- MapLunsToIDs = No");
  1208. }
  1209. #ifdef PLATFORM_HAS_PARITY_CHECK
  1210. if (sysCfg->enableParity)
  1211. {
  1212. logmsg("-- EnableParity = Yes");
  1213. config->flags |= S2S_CFG_ENABLE_PARITY;
  1214. }
  1215. else
  1216. {
  1217. logmsg("-- EnableParity = No");
  1218. }
  1219. #endif
  1220. memset(tmp, 0, sizeof(tmp));
  1221. ini_gets("SCSI", "WiFiMACAddress", "", tmp, sizeof(tmp), CONFIGFILE);
  1222. if (tmp[0])
  1223. {
  1224. // convert from "01:23:45:67:89" to { 0x01, 0x23, 0x45, 0x67, 0x89 }
  1225. int mac[6];
  1226. if (sscanf(tmp, "%x:%x:%x:%x:%x:%x", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]) == 6)
  1227. {
  1228. config->wifiMACAddress[0] = mac[0];
  1229. config->wifiMACAddress[1] = mac[1];
  1230. config->wifiMACAddress[2] = mac[2];
  1231. config->wifiMACAddress[3] = mac[3];
  1232. config->wifiMACAddress[4] = mac[4];
  1233. config->wifiMACAddress[5] = mac[5];
  1234. }
  1235. else
  1236. {
  1237. logmsg("Invalid MAC address format: \"", tmp, "\"");
  1238. memset(config->wifiMACAddress, 0, sizeof(config->wifiMACAddress));
  1239. }
  1240. }
  1241. memset(tmp, 0, sizeof(tmp));
  1242. ini_gets("SCSI", "WiFiSSID", "", tmp, sizeof(tmp), CONFIGFILE);
  1243. if (tmp[0]) memcpy(config->wifiSSID, tmp, sizeof(config->wifiSSID));
  1244. memset(tmp, 0, sizeof(tmp));
  1245. ini_gets("SCSI", "WiFiPassword", "", tmp, sizeof(tmp), CONFIGFILE);
  1246. if (tmp[0]) memcpy(config->wifiPassword, tmp, sizeof(config->wifiPassword));
  1247. }
  1248. extern "C"
  1249. void s2s_debugInit(void)
  1250. {
  1251. }
  1252. extern "C"
  1253. void s2s_configPoll(void)
  1254. {
  1255. }
  1256. extern "C"
  1257. void s2s_configSave(int scsiId, uint16_t byesPerSector)
  1258. {
  1259. // Modification of config over SCSI bus is not implemented.
  1260. }
  1261. extern "C"
  1262. const S2S_TargetCfg* s2s_getConfigByIndex(int index)
  1263. {
  1264. if (index < 0 || index >= S2S_MAX_TARGETS)
  1265. {
  1266. return NULL;
  1267. }
  1268. else
  1269. {
  1270. return &g_DiskImages[index];
  1271. }
  1272. }
  1273. extern "C"
  1274. const S2S_TargetCfg* s2s_getConfigById(int scsiId)
  1275. {
  1276. int i;
  1277. for (i = 0; i < S2S_MAX_TARGETS; ++i)
  1278. {
  1279. const S2S_TargetCfg* tgt = s2s_getConfigByIndex(i);
  1280. if ((tgt->scsiId & S2S_CFG_TARGET_ID_BITS) == scsiId &&
  1281. (tgt->scsiId & S2S_CFG_TARGET_ENABLED))
  1282. {
  1283. return tgt;
  1284. }
  1285. }
  1286. return NULL;
  1287. }
  1288. /**********************/
  1289. /* FormatUnit command */
  1290. /**********************/
  1291. // Callback once all data has been read in the data out phase.
  1292. static void doFormatUnitComplete(void)
  1293. {
  1294. scsiDev.phase = STATUS;
  1295. }
  1296. static void doFormatUnitSkipData(int bytes)
  1297. {
  1298. // We may not have enough memory to store the initialisation pattern and
  1299. // defect list data. Since we're not making use of it yet anyway, just
  1300. // discard the bytes.
  1301. scsiEnterPhase(DATA_OUT);
  1302. int i;
  1303. for (i = 0; i < bytes; ++i)
  1304. {
  1305. scsiReadByte();
  1306. }
  1307. }
  1308. // Callback from the data out phase.
  1309. static void doFormatUnitPatternHeader(void)
  1310. {
  1311. int defectLength =
  1312. ((((uint16_t)scsiDev.data[2])) << 8) +
  1313. scsiDev.data[3];
  1314. int patternLength =
  1315. ((((uint16_t)scsiDev.data[4 + 2])) << 8) +
  1316. scsiDev.data[4 + 3];
  1317. doFormatUnitSkipData(defectLength + patternLength);
  1318. doFormatUnitComplete();
  1319. }
  1320. // Callback from the data out phase.
  1321. static void doFormatUnitHeader(void)
  1322. {
  1323. int IP = (scsiDev.data[1] & 0x08) ? 1 : 0;
  1324. int DSP = (scsiDev.data[1] & 0x04) ? 1 : 0;
  1325. if (! DSP) // disable save parameters
  1326. {
  1327. // Save the "MODE SELECT savable parameters"
  1328. s2s_configSave(
  1329. scsiDev.target->targetId,
  1330. scsiDev.target->liveCfg.bytesPerSector);
  1331. }
  1332. if (IP)
  1333. {
  1334. // We need to read the initialisation pattern header first.
  1335. scsiDev.dataLen += 4;
  1336. scsiDev.phase = DATA_OUT;
  1337. scsiDev.postDataOutHook = doFormatUnitPatternHeader;
  1338. }
  1339. else
  1340. {
  1341. // Read the defect list data
  1342. int defectLength =
  1343. ((((uint16_t)scsiDev.data[2])) << 8) +
  1344. scsiDev.data[3];
  1345. doFormatUnitSkipData(defectLength);
  1346. doFormatUnitComplete();
  1347. }
  1348. }
  1349. /************************/
  1350. /* ReadCapacity command */
  1351. /************************/
  1352. static void doReadCapacity()
  1353. {
  1354. uint32_t lba = (((uint32_t) scsiDev.cdb[2]) << 24) +
  1355. (((uint32_t) scsiDev.cdb[3]) << 16) +
  1356. (((uint32_t) scsiDev.cdb[4]) << 8) +
  1357. scsiDev.cdb[5];
  1358. int pmi = scsiDev.cdb[8] & 1;
  1359. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1360. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  1361. uint32_t capacity;
  1362. if (unlikely(scsiDev.target->cfg->deviceType == S2S_CFG_NETWORK))
  1363. {
  1364. capacity = 1;
  1365. }
  1366. else
  1367. {
  1368. capacity = img.file.size() / bytesPerSector;
  1369. }
  1370. if (!pmi && lba)
  1371. {
  1372. // error.
  1373. // We don't do anything with the "partial medium indicator", and
  1374. // assume that delays are constant across each block. But the spec
  1375. // says we must return this error if pmi is specified incorrectly.
  1376. scsiDev.status = CHECK_CONDITION;
  1377. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  1378. scsiDev.target->sense.asc = INVALID_FIELD_IN_CDB;
  1379. scsiDev.phase = STATUS;
  1380. }
  1381. else if (capacity > 0)
  1382. {
  1383. uint32_t highestBlock = capacity - 1;
  1384. if (pmi && scsiDev.target->cfg->quirks == S2S_CFG_QUIRKS_EWSD)
  1385. {
  1386. highestBlock = 0x00001053;
  1387. }
  1388. scsiDev.data[0] = highestBlock >> 24;
  1389. scsiDev.data[1] = highestBlock >> 16;
  1390. scsiDev.data[2] = highestBlock >> 8;
  1391. scsiDev.data[3] = highestBlock;
  1392. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  1393. scsiDev.data[4] = bytesPerSector >> 24;
  1394. scsiDev.data[5] = bytesPerSector >> 16;
  1395. scsiDev.data[6] = bytesPerSector >> 8;
  1396. scsiDev.data[7] = bytesPerSector;
  1397. scsiDev.dataLen = 8;
  1398. scsiDev.phase = DATA_IN;
  1399. }
  1400. else
  1401. {
  1402. scsiDev.status = CHECK_CONDITION;
  1403. scsiDev.target->sense.code = NOT_READY;
  1404. scsiDev.target->sense.asc = MEDIUM_NOT_PRESENT;
  1405. scsiDev.phase = STATUS;
  1406. }
  1407. }
  1408. /*************************/
  1409. /* TestUnitReady command */
  1410. /*************************/
  1411. extern "C"
  1412. int doTestUnitReady()
  1413. {
  1414. int ready = 1;
  1415. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1416. if (unlikely(!scsiDev.target->started || !img.file.isOpen()))
  1417. {
  1418. ready = 0;
  1419. scsiDev.status = CHECK_CONDITION;
  1420. scsiDev.target->sense.code = NOT_READY;
  1421. scsiDev.target->sense.asc = LOGICAL_UNIT_NOT_READY_INITIALIZING_COMMAND_REQUIRED;
  1422. scsiDev.phase = STATUS;
  1423. }
  1424. else if (img.ejected)
  1425. {
  1426. ready = 0;
  1427. scsiDev.status = CHECK_CONDITION;
  1428. scsiDev.target->sense.code = NOT_READY;
  1429. scsiDev.target->sense.asc = MEDIUM_NOT_PRESENT;
  1430. scsiDev.phase = STATUS;
  1431. if (img.reinsert_after_eject)
  1432. {
  1433. // We are now reporting to host that the drive is open.
  1434. // Simulate a "close" for next time the host polls.
  1435. if (img.deviceType == S2S_CFG_OPTICAL) cdromCloseTray(img);
  1436. else doCloseTray(img);
  1437. }
  1438. }
  1439. else if (unlikely(!(blockDev.state & DISK_PRESENT)))
  1440. {
  1441. ready = 0;
  1442. scsiDev.status = CHECK_CONDITION;
  1443. scsiDev.target->sense.code = NOT_READY;
  1444. scsiDev.target->sense.asc = MEDIUM_NOT_PRESENT;
  1445. scsiDev.phase = STATUS;
  1446. }
  1447. else if (unlikely(!(blockDev.state & DISK_INITIALISED)))
  1448. {
  1449. ready = 0;
  1450. scsiDev.status = CHECK_CONDITION;
  1451. scsiDev.target->sense.code = NOT_READY;
  1452. scsiDev.target->sense.asc = LOGICAL_UNIT_NOT_READY_CAUSE_NOT_REPORTABLE;
  1453. scsiDev.phase = STATUS;
  1454. }
  1455. return ready;
  1456. }
  1457. /****************/
  1458. /* Seek command */
  1459. /****************/
  1460. static void doSeek(uint32_t lba)
  1461. {
  1462. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1463. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  1464. uint32_t capacity = img.get_capacity_lba();
  1465. if (lba >= capacity)
  1466. {
  1467. scsiDev.status = CHECK_CONDITION;
  1468. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  1469. scsiDev.target->sense.asc = LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
  1470. scsiDev.phase = STATUS;
  1471. }
  1472. else
  1473. {
  1474. if (unlikely(scsiDev.target->cfg->deviceType == S2S_CFG_FLOPPY_14MB) ||
  1475. scsiDev.compatMode < COMPAT_SCSI2)
  1476. {
  1477. s2s_delay_ms(10);
  1478. }
  1479. else
  1480. {
  1481. #ifdef ENABLE_AUDIO_OUTPUT
  1482. if (scsiDev.target->cfg->deviceType == S2S_CFG_OPTICAL)
  1483. {
  1484. // Uses audio play with a length of 0. CD audio won't actually play,
  1485. // but Read Subchannel will report the proper LBA location
  1486. if (!audio_play(scsiDev.target->targetId, &img, lba, 0, false))
  1487. dbgmsg("Failed to seek to audio track lba position ", (int) lba);
  1488. }
  1489. #endif
  1490. s2s_delay_us(10);
  1491. }
  1492. }
  1493. }
  1494. /********************************************/
  1495. /* Transfer state for read / write commands */
  1496. /********************************************/
  1497. BlockDevice blockDev = {DISK_PRESENT | DISK_INITIALISED};
  1498. Transfer transfer;
  1499. static struct {
  1500. uint8_t *buffer;
  1501. uint32_t bytes_sd; // Number of bytes that have been scheduled for transfer on SD card side
  1502. uint32_t bytes_scsi; // Number of bytes that have been scheduled for transfer on SCSI side
  1503. uint32_t bytes_scsi_started;
  1504. uint32_t sd_transfer_start;
  1505. int parityError;
  1506. } g_disk_transfer;
  1507. #ifdef PREFETCH_BUFFER_SIZE
  1508. static struct {
  1509. uint8_t buffer[PREFETCH_BUFFER_SIZE];
  1510. uint32_t sector;
  1511. uint32_t bytes;
  1512. uint8_t scsiId;
  1513. } g_scsi_prefetch;
  1514. #endif
  1515. /*****************/
  1516. /* Write command */
  1517. /*****************/
  1518. void scsiDiskStartWrite(uint32_t lba, uint32_t blocks)
  1519. {
  1520. if (unlikely(scsiDev.target->cfg->deviceType == S2S_CFG_FLOPPY_14MB)) {
  1521. // Floppies are supposed to be slow. Some systems can't handle a floppy
  1522. // without an access time
  1523. s2s_delay_ms(10);
  1524. }
  1525. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1526. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  1527. uint32_t capacity = img.file.size() / bytesPerSector;
  1528. dbgmsg("------ Write ", (int)blocks, "x", (int)bytesPerSector, " starting at ", (int)lba);
  1529. if (unlikely(blockDev.state & DISK_WP) ||
  1530. unlikely(scsiDev.target->cfg->deviceType == S2S_CFG_OPTICAL) ||
  1531. unlikely(!img.file.isWritable()))
  1532. {
  1533. logmsg("WARNING: Host attempted write to read-only drive ID ", (int)(img.scsiId & S2S_CFG_TARGET_ID_BITS));
  1534. scsiDev.status = CHECK_CONDITION;
  1535. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  1536. scsiDev.target->sense.asc = WRITE_PROTECTED;
  1537. scsiDev.phase = STATUS;
  1538. }
  1539. else if (unlikely(((uint64_t) lba) + blocks > capacity))
  1540. {
  1541. logmsg("WARNING: Host attempted write at sector ", (int)lba, "+", (int)blocks,
  1542. ", exceeding image size ", (int)capacity, " sectors (",
  1543. (int)bytesPerSector, "B/sector)");
  1544. scsiDev.status = CHECK_CONDITION;
  1545. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  1546. scsiDev.target->sense.asc = LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
  1547. scsiDev.phase = STATUS;
  1548. }
  1549. else
  1550. {
  1551. transfer.multiBlock = true;
  1552. transfer.lba = lba;
  1553. transfer.blocks = blocks;
  1554. transfer.currentBlock = 0;
  1555. scsiDev.phase = DATA_OUT;
  1556. scsiDev.dataLen = 0;
  1557. scsiDev.dataPtr = 0;
  1558. #ifdef PREFETCH_BUFFER_SIZE
  1559. // Invalidate prefetch buffer
  1560. g_scsi_prefetch.bytes = 0;
  1561. g_scsi_prefetch.sector = 0;
  1562. #endif
  1563. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1564. if (!img.file.seek((uint64_t)transfer.lba * bytesPerSector))
  1565. {
  1566. logmsg("Seek to ", transfer.lba, " failed for SCSI ID", (int)scsiDev.target->targetId);
  1567. scsiDev.status = CHECK_CONDITION;
  1568. scsiDev.target->sense.code = MEDIUM_ERROR;
  1569. scsiDev.target->sense.asc = NO_SEEK_COMPLETE;
  1570. scsiDev.phase = STATUS;
  1571. }
  1572. }
  1573. }
  1574. // Called to transfer next block from SCSI bus.
  1575. // Usually called from SD card driver during waiting for SD card access.
  1576. void diskDataOut_callback(uint32_t bytes_complete)
  1577. {
  1578. // For best performance, do SCSI reads in blocks of 4 or more bytes
  1579. bytes_complete &= ~3;
  1580. if (g_disk_transfer.bytes_scsi_started < g_disk_transfer.bytes_scsi)
  1581. {
  1582. // How many bytes remaining in the transfer?
  1583. uint32_t remain = g_disk_transfer.bytes_scsi - g_disk_transfer.bytes_scsi_started;
  1584. uint32_t len = remain;
  1585. // Split read so that it doesn't wrap around buffer edge
  1586. uint32_t bufsize = sizeof(scsiDev.data);
  1587. uint32_t start = (g_disk_transfer.bytes_scsi_started % bufsize);
  1588. if (start + len > bufsize)
  1589. len = bufsize - start;
  1590. // Apply platform-specific optimized transfer sizes
  1591. if (len > PLATFORM_OPTIMAL_SCSI_READ_BLOCK_SIZE)
  1592. {
  1593. len = PLATFORM_OPTIMAL_SCSI_READ_BLOCK_SIZE;
  1594. }
  1595. // Don't overwrite data that has not yet been written to SD card
  1596. uint32_t sd_ready_cnt = g_disk_transfer.bytes_sd + bytes_complete;
  1597. if (g_disk_transfer.bytes_scsi_started + len > sd_ready_cnt + bufsize)
  1598. len = sd_ready_cnt + bufsize - g_disk_transfer.bytes_scsi_started;
  1599. // Keep transfers a multiple of sector size.
  1600. // Macintosh SCSI driver seems to get confused if we have a delay
  1601. // in middle of a sector.
  1602. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  1603. if (remain >= bytesPerSector && len % bytesPerSector != 0)
  1604. {
  1605. len -= len % bytesPerSector;
  1606. }
  1607. if (len == 0)
  1608. return;
  1609. // dbgmsg("SCSI read ", (int)start, " + ", (int)len);
  1610. scsiStartRead(&scsiDev.data[start], len, &g_disk_transfer.parityError);
  1611. g_disk_transfer.bytes_scsi_started += len;
  1612. }
  1613. }
  1614. void diskDataOut()
  1615. {
  1616. scsiEnterPhase(DATA_OUT);
  1617. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1618. uint32_t blockcount = (transfer.blocks - transfer.currentBlock);
  1619. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  1620. g_disk_transfer.buffer = scsiDev.data;
  1621. g_disk_transfer.bytes_scsi = blockcount * bytesPerSector;
  1622. g_disk_transfer.bytes_sd = 0;
  1623. g_disk_transfer.bytes_scsi_started = 0;
  1624. g_disk_transfer.sd_transfer_start = 0;
  1625. g_disk_transfer.parityError = 0;
  1626. while (g_disk_transfer.bytes_sd < g_disk_transfer.bytes_scsi
  1627. && scsiDev.phase == DATA_OUT
  1628. && !scsiDev.resetFlag)
  1629. {
  1630. platform_poll();
  1631. diskEjectButtonUpdate(false);
  1632. // Figure out how many contiguous bytes are available for writing to SD card.
  1633. uint32_t bufsize = sizeof(scsiDev.data);
  1634. uint32_t start = g_disk_transfer.bytes_sd % bufsize;
  1635. uint32_t len = 0;
  1636. // How much data until buffer edge wrap?
  1637. uint32_t available = g_disk_transfer.bytes_scsi_started - g_disk_transfer.bytes_sd;
  1638. if (start + available > bufsize)
  1639. available = bufsize - start;
  1640. // Count number of finished sectors
  1641. if (scsiIsReadFinished(&scsiDev.data[start + available - 1]))
  1642. {
  1643. len = available;
  1644. }
  1645. else
  1646. {
  1647. while (len < available && scsiIsReadFinished(&scsiDev.data[start + len + SD_SECTOR_SIZE - 1]))
  1648. {
  1649. len += SD_SECTOR_SIZE;
  1650. }
  1651. }
  1652. // In case the last sector is partial (256 byte SCSI sectors)
  1653. if (len > available)
  1654. {
  1655. len = available;
  1656. }
  1657. // Apply platform-specific write size blocks for optimization
  1658. if (len > PLATFORM_OPTIMAL_MAX_SD_WRITE_SIZE)
  1659. {
  1660. len = PLATFORM_OPTIMAL_MAX_SD_WRITE_SIZE;
  1661. }
  1662. uint32_t remain_in_transfer = g_disk_transfer.bytes_scsi - g_disk_transfer.bytes_sd;
  1663. if (len < bufsize - start && len < remain_in_transfer)
  1664. {
  1665. // Use large write blocks in middle of transfer and smaller at the end of transfer.
  1666. // This improves performance for large writes and reduces latency at end of request.
  1667. uint32_t min_write_size = PLATFORM_OPTIMAL_MIN_SD_WRITE_SIZE;
  1668. if (remain_in_transfer <= PLATFORM_OPTIMAL_MAX_SD_WRITE_SIZE)
  1669. {
  1670. min_write_size = PLATFORM_OPTIMAL_LAST_SD_WRITE_SIZE;
  1671. }
  1672. if (len < min_write_size)
  1673. {
  1674. len = 0;
  1675. }
  1676. }
  1677. if (len == 0)
  1678. {
  1679. // Nothing ready to transfer, check if we can read more from SCSI bus
  1680. diskDataOut_callback(0);
  1681. }
  1682. else
  1683. {
  1684. // Finalize transfer on SCSI side
  1685. scsiFinishRead(&scsiDev.data[start], len, &g_disk_transfer.parityError);
  1686. // Check parity error status before writing to SD card
  1687. if (g_disk_transfer.parityError)
  1688. {
  1689. scsiDev.status = CHECK_CONDITION;
  1690. scsiDev.target->sense.code = ABORTED_COMMAND;
  1691. scsiDev.target->sense.asc = SCSI_PARITY_ERROR;
  1692. scsiDev.phase = STATUS;
  1693. break;
  1694. }
  1695. // Start writing to SD card and simultaneously start new SCSI transfers
  1696. // when buffer space is freed.
  1697. uint8_t *buf = &scsiDev.data[start];
  1698. g_disk_transfer.sd_transfer_start = start;
  1699. // dbgmsg("SD write ", (int)start, " + ", (int)len, " ", bytearray(buf, len));
  1700. platform_set_sd_callback(&diskDataOut_callback, buf);
  1701. if (img.file.write(buf, len) != len)
  1702. {
  1703. logmsg("SD card write failed: ", SD.sdErrorCode());
  1704. scsiDev.status = CHECK_CONDITION;
  1705. scsiDev.target->sense.code = MEDIUM_ERROR;
  1706. scsiDev.target->sense.asc = WRITE_ERROR_AUTO_REALLOCATION_FAILED;
  1707. scsiDev.phase = STATUS;
  1708. }
  1709. platform_set_sd_callback(NULL, NULL);
  1710. g_disk_transfer.bytes_sd += len;
  1711. // Reset the watchdog while the transfer is progressing.
  1712. // If the host stops transferring, the watchdog will eventually expire.
  1713. // This is needed to avoid hitting the watchdog if the host performs
  1714. // a large transfer compared to its transfer speed.
  1715. platform_reset_watchdog();
  1716. }
  1717. }
  1718. // Release SCSI bus
  1719. scsiFinishRead(NULL, 0, &g_disk_transfer.parityError);
  1720. transfer.currentBlock += blockcount;
  1721. scsiDev.dataPtr = scsiDev.dataLen = 0;
  1722. if (transfer.currentBlock == transfer.blocks)
  1723. {
  1724. // Verify that all data has been flushed to disk from SdFat cache.
  1725. // Normally does nothing as we do not change image file size and
  1726. // data writes are not cached.
  1727. img.file.flush();
  1728. }
  1729. }
  1730. /*****************/
  1731. /* Read command */
  1732. /*****************/
  1733. void scsiDiskStartRead(uint32_t lba, uint32_t blocks)
  1734. {
  1735. if (unlikely(scsiDev.target->cfg->deviceType == S2S_CFG_FLOPPY_14MB)) {
  1736. // Floppies are supposed to be slow. Some systems can't handle a floppy
  1737. // without an access time
  1738. s2s_delay_ms(10);
  1739. }
  1740. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1741. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  1742. uint32_t capacity = img.file.size() / bytesPerSector;
  1743. dbgmsg("------ Read ", (int)blocks, "x", (int)bytesPerSector, " starting at ", (int)lba);
  1744. if (unlikely(((uint64_t) lba) + blocks > capacity))
  1745. {
  1746. logmsg("WARNING: Host attempted read at sector ", (int)lba, "+", (int)blocks,
  1747. ", exceeding image size ", (int)capacity, " sectors (",
  1748. (int)bytesPerSector, "B/sector)");
  1749. scsiDev.status = CHECK_CONDITION;
  1750. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  1751. scsiDev.target->sense.asc = LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
  1752. scsiDev.phase = STATUS;
  1753. }
  1754. else
  1755. {
  1756. transfer.multiBlock = 1;
  1757. transfer.lba = lba;
  1758. transfer.blocks = blocks;
  1759. transfer.currentBlock = 0;
  1760. scsiDev.phase = DATA_IN;
  1761. scsiDev.dataLen = 0;
  1762. scsiDev.dataPtr = 0;
  1763. #ifdef PREFETCH_BUFFER_SIZE
  1764. uint32_t sectors_in_prefetch = g_scsi_prefetch.bytes / bytesPerSector;
  1765. if (img.scsiId == g_scsi_prefetch.scsiId &&
  1766. transfer.lba >= g_scsi_prefetch.sector &&
  1767. transfer.lba < g_scsi_prefetch.sector + sectors_in_prefetch)
  1768. {
  1769. // We have the some sectors already in prefetch cache
  1770. scsiEnterPhase(DATA_IN);
  1771. uint32_t start_offset = transfer.lba - g_scsi_prefetch.sector;
  1772. uint32_t count = sectors_in_prefetch - start_offset;
  1773. if (count > transfer.blocks) count = transfer.blocks;
  1774. scsiStartWrite(g_scsi_prefetch.buffer + start_offset * bytesPerSector, count * bytesPerSector);
  1775. dbgmsg("------ Found ", (int)count, " sectors in prefetch cache");
  1776. transfer.currentBlock += count;
  1777. }
  1778. if (transfer.currentBlock == transfer.blocks)
  1779. {
  1780. while (!scsiIsWriteFinished(NULL) && !scsiDev.resetFlag)
  1781. {
  1782. platform_poll();
  1783. diskEjectButtonUpdate(false);
  1784. }
  1785. scsiFinishWrite();
  1786. }
  1787. #endif
  1788. if (!img.file.seek((uint64_t)(transfer.lba + transfer.currentBlock) * bytesPerSector))
  1789. {
  1790. logmsg("Seek to ", transfer.lba, " failed for SCSI ID", (int)scsiDev.target->targetId);
  1791. scsiDev.status = CHECK_CONDITION;
  1792. scsiDev.target->sense.code = MEDIUM_ERROR;
  1793. scsiDev.target->sense.asc = NO_SEEK_COMPLETE;
  1794. scsiDev.phase = STATUS;
  1795. }
  1796. }
  1797. }
  1798. void diskDataIn_callback(uint32_t bytes_complete)
  1799. {
  1800. // On SCSI-1 devices the phase change has some extra delays.
  1801. // Doing it here lets the SD card transfer proceed in background.
  1802. scsiEnterPhase(DATA_IN);
  1803. // For best performance, do writes in blocks of 4 or more bytes
  1804. if (bytes_complete < g_disk_transfer.bytes_sd)
  1805. {
  1806. bytes_complete &= ~3;
  1807. }
  1808. // Machintosh SCSI driver can get confused if pauses occur in middle of
  1809. // a sector, so schedule the transfers in sector sized blocks.
  1810. if (bytes_complete < g_disk_transfer.bytes_sd)
  1811. {
  1812. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  1813. if (bytes_complete % bytesPerSector != 0)
  1814. {
  1815. bytes_complete -= bytes_complete % bytesPerSector;
  1816. }
  1817. }
  1818. if (bytes_complete > g_disk_transfer.bytes_scsi)
  1819. {
  1820. // DMA is reading from SD card, bytes_complete bytes have already been read.
  1821. // Send them to SCSI bus now.
  1822. uint32_t len = bytes_complete - g_disk_transfer.bytes_scsi;
  1823. scsiStartWrite(g_disk_transfer.buffer + g_disk_transfer.bytes_scsi, len);
  1824. g_disk_transfer.bytes_scsi += len;
  1825. }
  1826. // Provide a chance for polling request processing
  1827. scsiIsWriteFinished(NULL);
  1828. }
  1829. // Start a data in transfer using given temporary buffer.
  1830. // diskDataIn() below divides the scsiDev.data buffer to two halves for double buffering.
  1831. static void start_dataInTransfer(uint8_t *buffer, uint32_t count)
  1832. {
  1833. g_disk_transfer.buffer = buffer;
  1834. g_disk_transfer.bytes_scsi = 0;
  1835. g_disk_transfer.bytes_sd = count;
  1836. // Verify that previous write using this buffer has finished
  1837. uint32_t start = millis();
  1838. while (!scsiIsWriteFinished(buffer + count - 1) && !scsiDev.resetFlag)
  1839. {
  1840. if ((uint32_t)(millis() - start) > 5000)
  1841. {
  1842. logmsg("start_dataInTransfer() timeout waiting for previous to finish");
  1843. scsiDev.resetFlag = 1;
  1844. }
  1845. platform_poll();
  1846. diskEjectButtonUpdate(false);
  1847. }
  1848. if (scsiDev.resetFlag) return;
  1849. // Start transferring from SD card
  1850. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1851. platform_set_sd_callback(&diskDataIn_callback, buffer);
  1852. if (img.file.read(buffer, count) != count)
  1853. {
  1854. logmsg("SD card read failed: ", SD.sdErrorCode());
  1855. scsiDev.status = CHECK_CONDITION;
  1856. scsiDev.target->sense.code = MEDIUM_ERROR;
  1857. scsiDev.target->sense.asc = UNRECOVERED_READ_ERROR;
  1858. scsiDev.phase = STATUS;
  1859. }
  1860. diskDataIn_callback(count);
  1861. platform_set_sd_callback(NULL, NULL);
  1862. platform_poll();
  1863. diskEjectButtonUpdate(false);
  1864. // Reset the watchdog while the transfer is progressing.
  1865. // If the host stops transferring, the watchdog will eventually expire.
  1866. // This is needed to avoid hitting the watchdog if the host performs
  1867. // a large transfer compared to its transfer speed.
  1868. platform_reset_watchdog();
  1869. }
  1870. static void diskDataIn()
  1871. {
  1872. // Figure out how many blocks we can fit in buffer
  1873. uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;
  1874. uint32_t maxblocks = sizeof(scsiDev.data) / bytesPerSector;
  1875. uint32_t maxblocks_half = maxblocks / 2;
  1876. // Start transfer in first half of buffer
  1877. // Waits for the previous first half transfer to finish first.
  1878. uint32_t remain = (transfer.blocks - transfer.currentBlock);
  1879. if (remain > 0)
  1880. {
  1881. uint32_t transfer_blocks = std::min(remain, maxblocks_half);
  1882. uint32_t transfer_bytes = transfer_blocks * bytesPerSector;
  1883. start_dataInTransfer(&scsiDev.data[0], transfer_bytes);
  1884. transfer.currentBlock += transfer_blocks;
  1885. }
  1886. // Start transfer in second half of buffer
  1887. // Waits for the previous second half transfer to finish first
  1888. remain = (transfer.blocks - transfer.currentBlock);
  1889. if (remain > 0)
  1890. {
  1891. uint32_t transfer_blocks = std::min(remain, maxblocks_half);
  1892. uint32_t transfer_bytes = transfer_blocks * bytesPerSector;
  1893. start_dataInTransfer(&scsiDev.data[maxblocks_half * bytesPerSector], transfer_bytes);
  1894. transfer.currentBlock += transfer_blocks;
  1895. }
  1896. if (transfer.currentBlock == transfer.blocks)
  1897. {
  1898. // This was the last block, verify that everything finishes
  1899. #ifdef PREFETCH_BUFFER_SIZE
  1900. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1901. int prefetchbytes = img.prefetchbytes;
  1902. if (prefetchbytes > PREFETCH_BUFFER_SIZE) prefetchbytes = PREFETCH_BUFFER_SIZE;
  1903. uint32_t prefetch_sectors = prefetchbytes / bytesPerSector;
  1904. uint32_t img_sector_count = img.file.size() / bytesPerSector;
  1905. g_scsi_prefetch.sector = transfer.lba + transfer.blocks;
  1906. g_scsi_prefetch.bytes = 0;
  1907. g_scsi_prefetch.scsiId = scsiDev.target->cfg->scsiId;
  1908. if (g_scsi_prefetch.sector + prefetch_sectors > img_sector_count)
  1909. {
  1910. // Don't try to read past image end.
  1911. prefetch_sectors = img_sector_count - g_scsi_prefetch.sector;
  1912. }
  1913. while (!scsiIsWriteFinished(NULL) && prefetch_sectors > 0 && !scsiDev.resetFlag)
  1914. {
  1915. platform_poll();
  1916. diskEjectButtonUpdate(false);
  1917. // Check if prefetch buffer is free
  1918. g_disk_transfer.buffer = g_scsi_prefetch.buffer + g_scsi_prefetch.bytes;
  1919. if (!scsiIsWriteFinished(g_disk_transfer.buffer) ||
  1920. !scsiIsWriteFinished(g_disk_transfer.buffer + bytesPerSector - 1))
  1921. {
  1922. continue;
  1923. }
  1924. // We still have time, prefetch next sectors in case this SCSI request
  1925. // is part of a longer linear read.
  1926. g_disk_transfer.bytes_sd = bytesPerSector;
  1927. g_disk_transfer.bytes_scsi = bytesPerSector; // Tell callback not to send to SCSI
  1928. platform_set_sd_callback(&diskDataIn_callback, g_disk_transfer.buffer);
  1929. int status = img.file.read(g_disk_transfer.buffer, bytesPerSector);
  1930. if (status <= 0)
  1931. {
  1932. logmsg("Prefetch read failed");
  1933. prefetch_sectors = 0;
  1934. break;
  1935. }
  1936. g_scsi_prefetch.bytes += status;
  1937. platform_set_sd_callback(NULL, NULL);
  1938. prefetch_sectors--;
  1939. }
  1940. #endif
  1941. while (!scsiIsWriteFinished(NULL) && !scsiDev.resetFlag)
  1942. {
  1943. platform_poll();
  1944. diskEjectButtonUpdate(false);
  1945. }
  1946. scsiFinishWrite();
  1947. }
  1948. }
  1949. /********************/
  1950. /* Command dispatch */
  1951. /********************/
  1952. // Handle direct-access scsi device commands
  1953. extern "C"
  1954. int scsiDiskCommand()
  1955. {
  1956. int commandHandled = 1;
  1957. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  1958. uint8_t command = scsiDev.cdb[0];
  1959. if (unlikely(command == 0x1B))
  1960. {
  1961. // START STOP UNIT
  1962. // Enable or disable media access operations.
  1963. //int immed = scsiDev.cdb[1] & 1;
  1964. int start = scsiDev.cdb[4] & 1;
  1965. if ((scsiDev.cdb[4] & 2) || img.deviceType == S2S_CFG_ZIP100)
  1966. {
  1967. // Device load & eject
  1968. if (start)
  1969. {
  1970. doCloseTray(img);
  1971. }
  1972. else
  1973. {
  1974. // Eject and switch image
  1975. doPerformEject(img);
  1976. }
  1977. }
  1978. else if (start)
  1979. {
  1980. scsiDev.target->started = 1;
  1981. }
  1982. else
  1983. {
  1984. scsiDev.target->started = 0;
  1985. }
  1986. }
  1987. else if (likely(command == 0x08))
  1988. {
  1989. // READ(6)
  1990. uint32_t lba =
  1991. (((uint32_t) scsiDev.cdb[1] & 0x1F) << 16) +
  1992. (((uint32_t) scsiDev.cdb[2]) << 8) +
  1993. scsiDev.cdb[3];
  1994. uint32_t blocks = scsiDev.cdb[4];
  1995. if (unlikely(blocks == 0)) blocks = 256;
  1996. scsiDiskStartRead(lba, blocks);
  1997. }
  1998. else if (likely(command == 0x28))
  1999. {
  2000. // READ(10)
  2001. // Ignore all cache control bits - we don't support a memory cache.
  2002. uint32_t lba =
  2003. (((uint32_t) scsiDev.cdb[2]) << 24) +
  2004. (((uint32_t) scsiDev.cdb[3]) << 16) +
  2005. (((uint32_t) scsiDev.cdb[4]) << 8) +
  2006. scsiDev.cdb[5];
  2007. uint32_t blocks =
  2008. (((uint32_t) scsiDev.cdb[7]) << 8) +
  2009. scsiDev.cdb[8];
  2010. scsiDiskStartRead(lba, blocks);
  2011. }
  2012. else if (likely(command == 0x0A))
  2013. {
  2014. // WRITE(6)
  2015. uint32_t lba =
  2016. (((uint32_t) scsiDev.cdb[1] & 0x1F) << 16) +
  2017. (((uint32_t) scsiDev.cdb[2]) << 8) +
  2018. scsiDev.cdb[3];
  2019. uint32_t blocks = scsiDev.cdb[4];
  2020. if (unlikely(blocks == 0)) blocks = 256;
  2021. scsiDiskStartWrite(lba, blocks);
  2022. }
  2023. else if (likely(command == 0x2A) || // WRITE(10)
  2024. unlikely(command == 0x2E)) // WRITE AND VERIFY
  2025. {
  2026. // Ignore all cache control bits - we don't support a memory cache.
  2027. // Don't bother verifying either. The SD card likely stores ECC
  2028. // along with each flash row.
  2029. uint32_t lba =
  2030. (((uint32_t) scsiDev.cdb[2]) << 24) +
  2031. (((uint32_t) scsiDev.cdb[3]) << 16) +
  2032. (((uint32_t) scsiDev.cdb[4]) << 8) +
  2033. scsiDev.cdb[5];
  2034. uint32_t blocks =
  2035. (((uint32_t) scsiDev.cdb[7]) << 8) +
  2036. scsiDev.cdb[8];
  2037. scsiDiskStartWrite(lba, blocks);
  2038. }
  2039. else if (unlikely(command == 0x04))
  2040. {
  2041. // FORMAT UNIT
  2042. // We don't really do any formatting, but we need to read the correct
  2043. // number of bytes in the DATA_OUT phase to make the SCSI host happy.
  2044. int fmtData = (scsiDev.cdb[1] & 0x10) ? 1 : 0;
  2045. if (fmtData)
  2046. {
  2047. // We need to read the parameter list, but we don't know how
  2048. // big it is yet. Start with the header.
  2049. scsiDev.dataLen = 4;
  2050. scsiDev.phase = DATA_OUT;
  2051. scsiDev.postDataOutHook = doFormatUnitHeader;
  2052. }
  2053. else
  2054. {
  2055. // No data to read, we're already finished!
  2056. }
  2057. }
  2058. else if (unlikely(command == 0x25))
  2059. {
  2060. // READ CAPACITY
  2061. doReadCapacity();
  2062. }
  2063. else if (unlikely(command == 0x0B))
  2064. {
  2065. // SEEK(6)
  2066. uint32_t lba =
  2067. (((uint32_t) scsiDev.cdb[1] & 0x1F) << 16) +
  2068. (((uint32_t) scsiDev.cdb[2]) << 8) +
  2069. scsiDev.cdb[3];
  2070. doSeek(lba);
  2071. }
  2072. else if (unlikely(command == 0x2B))
  2073. {
  2074. // SEEK(10)
  2075. uint32_t lba =
  2076. (((uint32_t) scsiDev.cdb[2]) << 24) +
  2077. (((uint32_t) scsiDev.cdb[3]) << 16) +
  2078. (((uint32_t) scsiDev.cdb[4]) << 8) +
  2079. scsiDev.cdb[5];
  2080. doSeek(lba);
  2081. }
  2082. else if (unlikely(command == 0x36))
  2083. {
  2084. // LOCK UNLOCK CACHE
  2085. // We don't have a cache to lock data into. do nothing.
  2086. }
  2087. else if (unlikely(command == 0x34))
  2088. {
  2089. // PRE-FETCH.
  2090. // We don't have a cache to pre-fetch into. do nothing.
  2091. }
  2092. else if (unlikely(command == 0x1E))
  2093. {
  2094. // PREVENT ALLOW MEDIUM REMOVAL
  2095. // Not much we can do to prevent the user removing the SD card.
  2096. // do nothing.
  2097. }
  2098. else if (unlikely(command == 0x01))
  2099. {
  2100. // REZERO UNIT
  2101. // Set the lun to a vendor-specific state. Ignore.
  2102. }
  2103. else if (unlikely(command == 0x35))
  2104. {
  2105. // SYNCHRONIZE CACHE
  2106. // We don't have a cache. do nothing.
  2107. }
  2108. else if (unlikely(command == 0x2F))
  2109. {
  2110. // VERIFY
  2111. // TODO: When they supply data to verify, we should read the data and
  2112. // verify it. If they don't supply any data, just say success.
  2113. if ((scsiDev.cdb[1] & 0x02) == 0)
  2114. {
  2115. // They are asking us to do a medium verification with no data
  2116. // comparison. Assume success, do nothing.
  2117. }
  2118. else
  2119. {
  2120. // TODO. This means they are supplying data to verify against.
  2121. // Technically we should probably grab the data and compare it.
  2122. scsiDev.status = CHECK_CONDITION;
  2123. scsiDev.target->sense.code = ILLEGAL_REQUEST;
  2124. scsiDev.target->sense.asc = INVALID_FIELD_IN_CDB;
  2125. scsiDev.phase = STATUS;
  2126. }
  2127. }
  2128. else if (unlikely(command == 0x37))
  2129. {
  2130. // READ DEFECT DATA
  2131. uint32_t allocLength = (((uint16_t)scsiDev.cdb[7]) << 8) |
  2132. scsiDev.cdb[8];
  2133. scsiDev.data[0] = 0;
  2134. scsiDev.data[1] = scsiDev.cdb[1];
  2135. scsiDev.data[2] = 0;
  2136. scsiDev.data[3] = 0;
  2137. scsiDev.dataLen = 4;
  2138. if (scsiDev.dataLen > allocLength)
  2139. {
  2140. scsiDev.dataLen = allocLength;
  2141. }
  2142. scsiDev.phase = DATA_IN;
  2143. }
  2144. else if (!img.file.isWritable())
  2145. {
  2146. // Special handling for ROM drive to make SCSI2SD code report it as read-only
  2147. blockDev.state |= DISK_WP;
  2148. commandHandled = scsiModeCommand();
  2149. blockDev.state &= ~DISK_WP;
  2150. }
  2151. else
  2152. {
  2153. commandHandled = 0;
  2154. }
  2155. return commandHandled;
  2156. }
  2157. extern "C"
  2158. void scsiDiskPoll()
  2159. {
  2160. if (scsiDev.phase == DATA_IN &&
  2161. transfer.currentBlock != transfer.blocks)
  2162. {
  2163. diskDataIn();
  2164. }
  2165. else if (scsiDev.phase == DATA_OUT &&
  2166. transfer.currentBlock != transfer.blocks)
  2167. {
  2168. diskDataOut();
  2169. }
  2170. if (scsiDev.phase == STATUS && scsiDev.target)
  2171. {
  2172. // Check if the command is affected by drive geometry.
  2173. // Affected commands are:
  2174. // 0x1A MODE SENSE command of pages 0x03 (device format), 0x04 (disk geometry) or 0x3F (all pages)
  2175. // 0x1C RECEIVE DIAGNOSTICS RESULTS
  2176. uint8_t command = scsiDev.cdb[0];
  2177. uint8_t pageCode = scsiDev.cdb[2] & 0x3F;
  2178. if ((command == 0x1A && (pageCode == 0x03 || pageCode == 0x04 || pageCode == 0x3F)) ||
  2179. command == 0x1C)
  2180. {
  2181. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  2182. checkDiskGeometryDivisible(img);
  2183. }
  2184. // Check for Inquiry command to close CD-ROM tray on boot
  2185. if (command == 0x12)
  2186. {
  2187. image_config_t &img = *(image_config_t*)scsiDev.target->cfg;
  2188. if (img.reinsert_on_inquiry)
  2189. {
  2190. if (img.deviceType == S2S_CFG_OPTICAL) cdromCloseTray(img);
  2191. else doCloseTray(img);
  2192. }
  2193. }
  2194. }
  2195. }
  2196. extern "C"
  2197. void scsiDiskReset()
  2198. {
  2199. scsiDev.dataPtr = 0;
  2200. scsiDev.savedDataPtr = 0;
  2201. scsiDev.dataLen = 0;
  2202. // transfer.lba = 0; // Needed in Request Sense to determine failure
  2203. transfer.blocks = 0;
  2204. transfer.currentBlock = 0;
  2205. transfer.multiBlock = 0;
  2206. #ifdef PREFETCH_BUFFER_SIZE
  2207. g_scsi_prefetch.bytes = 0;
  2208. g_scsi_prefetch.sector = 0;
  2209. #endif
  2210. // Reinsert any ejected CD-ROMs on BUS RESET and restart from first image
  2211. for (int i = 0; i < S2S_MAX_TARGETS; ++i)
  2212. {
  2213. image_config_t &img = g_DiskImages[i];
  2214. if (img.deviceType == S2S_CFG_OPTICAL)
  2215. {
  2216. cdromReinsertFirstImage(img);
  2217. }
  2218. }
  2219. }
  2220. extern "C"
  2221. void scsiDiskInit()
  2222. {
  2223. scsiDiskReset();
  2224. }