ZuluSCSI_disk.cpp 53 KB

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