ZuluSCSI_disk.cpp 63 KB

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