ZuluSCSI_disk.cpp 63 KB

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