BlueSCSI_disk.cpp 78 KB

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