ZuluSCSI_disk.cpp 61 KB

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