ZuluSCSI_disk.cpp 66 KB

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