ZuluSCSI_disk.cpp 44 KB

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