AzulSCSI_disk.cpp 41 KB

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