ZuluSCSI_disk.cpp 62 KB

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