ZuluSCSI_disk.cpp 62 KB

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