ZuluSCSI_disk.cpp 66 KB

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