ZuluSCSI_disk.cpp 63 KB

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