ZuluSCSI_disk.cpp 62 KB

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