ZuluSCSI_disk.cpp 61 KB

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