BlueSCSI_disk.cpp 64 KB

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