ZuluSCSI_initiator.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  1. /**
  2. * ZuluSCSI™ - Copyright (c) 2022 Rabbit Hole Computing™
  3. *
  4. * ZuluSCSI™ firmware is licensed under the GPL version 3 or any later version. 
  5. *
  6. * https://www.gnu.org/licenses/gpl-3.0.html
  7. * ----
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version. 
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16. * GNU General Public License for more details. 
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program.  If not, see <https://www.gnu.org/licenses/>.
  20. **/
  21. /*
  22. * Main program for initiator mode.
  23. */
  24. #include "ZuluSCSI_config.h"
  25. #include "ZuluSCSI_log.h"
  26. #include "ZuluSCSI_log_trace.h"
  27. #include "ZuluSCSI_initiator.h"
  28. #include <ZuluSCSI_platform.h>
  29. #include <minIni.h>
  30. #include "SdFat.h"
  31. #include <scsi2sd.h>
  32. extern "C" {
  33. #include <scsi.h>
  34. }
  35. #ifndef PLATFORM_HAS_INITIATOR_MODE
  36. void scsiInitiatorInit()
  37. {
  38. }
  39. void scsiInitiatorMainLoop()
  40. {
  41. }
  42. int scsiInitiatorRunCommand(const uint8_t *command, size_t cmdlen,
  43. uint8_t *bufIn, size_t bufInLen,
  44. const uint8_t *bufOut, size_t bufOutLen)
  45. {
  46. return -1;
  47. }
  48. bool scsiInitiatorReadCapacity(int target_id, uint32_t *sectorcount, uint32_t *sectorsize)
  49. {
  50. return false;
  51. }
  52. #else
  53. /*************************************
  54. * High level initiator mode logic *
  55. *************************************/
  56. static struct {
  57. // Bitmap of all drives that have been imaged
  58. uint32_t drives_imaged;
  59. uint8_t initiator_id;
  60. // Is imaging a drive in progress, or are we scanning?
  61. bool imaging;
  62. // Information about currently selected drive
  63. int target_id;
  64. uint32_t sectorsize;
  65. uint32_t sectorcount;
  66. uint32_t sectorcount_all;
  67. uint32_t sectors_done;
  68. uint32_t max_sector_per_transfer;
  69. uint32_t bad_sector_count;
  70. uint8_t ansi_version;
  71. uint8_t max_retry_count;
  72. uint8_t device_type;
  73. // Retry information for sector reads.
  74. // If a large read fails, retry is done sector-by-sector.
  75. int retrycount;
  76. uint32_t failposition;
  77. bool eject_when_done;
  78. bool removable;
  79. uint32_t removable_count[8];
  80. FsFile target_file;
  81. } g_initiator_state;
  82. extern SdFs SD;
  83. // Initialization of initiator mode
  84. void scsiInitiatorInit()
  85. {
  86. scsiHostPhyReset();
  87. g_initiator_state.initiator_id = ini_getl("SCSI", "InitiatorID", 7, CONFIGFILE);
  88. if (g_initiator_state.initiator_id > 7)
  89. {
  90. logmsg("InitiatorID set to illegal value in, ", CONFIGFILE, ", defaulting to 7");
  91. g_initiator_state.initiator_id = 7;
  92. }
  93. else
  94. {
  95. logmsg("InitiatorID set to ID ", g_initiator_state.initiator_id);
  96. }
  97. g_initiator_state.max_retry_count = ini_getl("SCSI", "InitiatorMaxRetry", 5, CONFIGFILE);
  98. // treat initiator id as already imaged drive so it gets skipped
  99. g_initiator_state.drives_imaged = 1 << g_initiator_state.initiator_id;
  100. g_initiator_state.imaging = false;
  101. g_initiator_state.target_id = -1;
  102. g_initiator_state.sectorsize = 0;
  103. g_initiator_state.sectorcount = 0;
  104. g_initiator_state.sectors_done = 0;
  105. g_initiator_state.retrycount = 0;
  106. g_initiator_state.failposition = 0;
  107. g_initiator_state.max_sector_per_transfer = 512;
  108. g_initiator_state.ansi_version = 0;
  109. g_initiator_state.bad_sector_count = 0;
  110. g_initiator_state.device_type = SCSI_DEVICE_TYPE_DIRECT_ACCESS;
  111. g_initiator_state.removable = false;
  112. g_initiator_state.eject_when_done = false;
  113. memset(g_initiator_state.removable_count, 0, sizeof(g_initiator_state.removable_count));
  114. }
  115. // Update progress bar LED during transfers
  116. static void scsiInitiatorUpdateLed()
  117. {
  118. // Update status indicator, the led blinks every 5 seconds and is on the longer the more data has been transferred
  119. const int period = 256;
  120. int phase = (millis() % period);
  121. int duty = (int64_t)g_initiator_state.sectors_done * period / g_initiator_state.sectorcount;
  122. // Minimum and maximum time to verify that the blink is visible
  123. if (duty < 50) duty = 50;
  124. if (duty > period - 50) duty = period - 50;
  125. if (phase <= duty)
  126. {
  127. LED_ON();
  128. }
  129. else
  130. {
  131. LED_OFF();
  132. }
  133. }
  134. void delay_with_poll(uint32_t ms)
  135. {
  136. uint32_t start = millis();
  137. while ((uint32_t)(millis() - start) < ms)
  138. {
  139. platform_poll();
  140. delay(1);
  141. }
  142. }
  143. static int scsiTypeToIniType(int scsi_type, bool removable)
  144. {
  145. int ini_type = -1;
  146. switch (scsi_type)
  147. {
  148. case SCSI_DEVICE_TYPE_DIRECT_ACCESS:
  149. ini_type = removable ? S2S_CFG_REMOVABLE : S2S_CFG_FIXED;
  150. break;
  151. case 1:
  152. ini_type = -1; // S2S_CFG_SEQUENTIAL
  153. break;
  154. case SCSI_DEVICE_TYPE_CD:
  155. ini_type = S2S_CFG_OPTICAL;
  156. break;
  157. case SCSI_DEVICE_TYPE_MO:
  158. ini_type = S2S_CFG_MO;
  159. break;
  160. default:
  161. ini_type = -1;
  162. break;
  163. }
  164. return ini_type;
  165. }
  166. // High level logic of the initiator mode
  167. void scsiInitiatorMainLoop()
  168. {
  169. if (g_scsiHostPhyReset)
  170. {
  171. logmsg("Executing BUS RESET after aborted command");
  172. scsiHostPhyReset();
  173. }
  174. if (!g_initiator_state.imaging)
  175. {
  176. // Scan for SCSI drives one at a time
  177. g_initiator_state.target_id = (g_initiator_state.target_id + 1) % 8;
  178. g_initiator_state.sectors_done = 0;
  179. g_initiator_state.retrycount = 0;
  180. g_initiator_state.max_sector_per_transfer = 512;
  181. g_initiator_state.bad_sector_count = 0;
  182. g_initiator_state.eject_when_done = false;
  183. if (!(g_initiator_state.drives_imaged & (1 << g_initiator_state.target_id)))
  184. {
  185. delay_with_poll(1000);
  186. uint8_t inquiry_data[36] = {0};
  187. LED_ON();
  188. bool startstopok =
  189. scsiTestUnitReady(g_initiator_state.target_id) &&
  190. scsiStartStopUnit(g_initiator_state.target_id, true);
  191. bool readcapok = startstopok &&
  192. scsiInitiatorReadCapacity(g_initiator_state.target_id,
  193. &g_initiator_state.sectorcount,
  194. &g_initiator_state.sectorsize);
  195. bool inquiryok = startstopok &&
  196. scsiInquiry(g_initiator_state.target_id, inquiry_data);
  197. LED_OFF();
  198. uint64_t total_bytes = 0;
  199. if (readcapok)
  200. {
  201. logmsg("SCSI ID ", g_initiator_state.target_id,
  202. " capacity ", (int)g_initiator_state.sectorcount,
  203. " sectors x ", (int)g_initiator_state.sectorsize, " bytes");
  204. g_initiator_state.sectorcount_all = g_initiator_state.sectorcount;
  205. total_bytes = (uint64_t)g_initiator_state.sectorcount * g_initiator_state.sectorsize;
  206. logmsg("Drive total size is ", (int)(total_bytes / (1024 * 1024)), " MiB");
  207. if (total_bytes >= 0xFFFFFFFF && SD.fatType() != FAT_TYPE_EXFAT)
  208. {
  209. // Note: the FAT32 limit is 4 GiB - 1 byte
  210. logmsg("Target SCSI ID ", g_initiator_state.target_id, " image size is equal or larger than 4 GiB.");
  211. logmsg("This is larger than the max filesize supported by SD card's filesystem");
  212. logmsg("Please reformat the SD card with exFAT format to image this target");
  213. g_initiator_state.drives_imaged |= 1 << g_initiator_state.target_id;
  214. return;
  215. }
  216. }
  217. else if (startstopok)
  218. {
  219. logmsg("SCSI ID ", g_initiator_state.target_id, " responds but ReadCapacity command failed");
  220. logmsg("Possibly SCSI-1 drive? Attempting to read up to 1 GB.");
  221. g_initiator_state.sectorsize = 512;
  222. g_initiator_state.sectorcount = g_initiator_state.sectorcount_all = 2097152;
  223. g_initiator_state.max_sector_per_transfer = 128;
  224. }
  225. else
  226. {
  227. #ifndef ZULUSCSI_NETWORK
  228. dbgmsg("Failed to connect to SCSI ID ", g_initiator_state.target_id);
  229. #endif
  230. g_initiator_state.sectorsize = 0;
  231. g_initiator_state.sectorcount = g_initiator_state.sectorcount_all = 0;
  232. }
  233. char filename_base[12];
  234. strncpy(filename_base, "HD00_imaged", sizeof(filename_base));
  235. const char *filename_extension = ".hda";
  236. if (inquiryok)
  237. {
  238. char vendor[9], product[17], revision[5];
  239. g_initiator_state.device_type=inquiry_data[0] & 0x1f;
  240. g_initiator_state.ansi_version = inquiry_data[2] & 0x7;
  241. g_initiator_state.removable = !!(inquiry_data[1] & 0x80);
  242. g_initiator_state.eject_when_done = g_initiator_state.removable;
  243. memcpy(vendor, &inquiry_data[8], 8);
  244. vendor[8]=0;
  245. memcpy(product, &inquiry_data[16], 16);
  246. product[16]=0;
  247. memcpy(revision, &inquiry_data[32], 4);
  248. revision[4]=0;
  249. if(g_initiator_state.ansi_version < 0x02)
  250. {
  251. // this is a SCSI-1 drive, use READ6 and 256 bytes to be safe.
  252. g_initiator_state.max_sector_per_transfer = 256;
  253. }
  254. int ini_type = scsiTypeToIniType(g_initiator_state.device_type, g_initiator_state.removable);
  255. logmsg("SCSI Version ", (int) g_initiator_state.ansi_version);
  256. logmsg("[SCSI", g_initiator_state.target_id,"]");
  257. logmsg(" Vendor = \"", vendor,"\"");
  258. logmsg(" Product = \"", product,"\"");
  259. logmsg(" Version = \"", revision,"\"");
  260. if (ini_type == -1)
  261. logmsg("Type = Not Supported, trying direct access");
  262. else
  263. logmsg(" Type = ", ini_type);
  264. if (g_initiator_state.device_type == SCSI_DEVICE_TYPE_CD)
  265. {
  266. strncpy(filename_base, "CD00_imaged", sizeof(filename_base));
  267. filename_extension = ".iso";
  268. }
  269. else if (g_initiator_state.device_type == SCSI_DEVICE_TYPE_MO)
  270. {
  271. strncpy(filename_base, "MO00_imaged", sizeof(filename_base));
  272. filename_extension = ".img";
  273. }
  274. else if (g_initiator_state.device_type != SCSI_DEVICE_TYPE_DIRECT_ACCESS)
  275. {
  276. logmsg("Unhandled scsi device type: ", g_initiator_state.device_type, ". Handling it as Direct Access Device.");
  277. g_initiator_state.device_type = SCSI_DEVICE_TYPE_DIRECT_ACCESS;
  278. }
  279. if (g_initiator_state.device_type == SCSI_DEVICE_TYPE_DIRECT_ACCESS && g_initiator_state.removable)
  280. {
  281. strncpy(filename_base, "RM00_imaged", sizeof(filename_base));
  282. filename_extension = ".img";
  283. }
  284. }
  285. if (g_initiator_state.eject_when_done && g_initiator_state.removable_count[g_initiator_state.target_id] == 0)
  286. {
  287. g_initiator_state.removable_count[g_initiator_state.target_id] = 1;
  288. }
  289. if (g_initiator_state.sectorcount > 0)
  290. {
  291. char filename[32] = {0};
  292. filename_base[2] += g_initiator_state.target_id;
  293. if (g_initiator_state.eject_when_done)
  294. {
  295. auto removable_count = g_initiator_state.removable_count[g_initiator_state.target_id];
  296. snprintf(filename, sizeof(filename), "%s(%lu)%s",filename_base, removable_count, filename_extension);
  297. }
  298. else
  299. {
  300. snprintf(filename, sizeof(filename), "%s%s", filename_base, filename_extension);
  301. }
  302. static int handling = -1;
  303. if (handling == -1)
  304. {
  305. handling = ini_getl("SCSI", "InitiatorImageHandling", 0, CONFIGFILE);
  306. }
  307. // Stop if a file already exists
  308. if (handling == 0)
  309. {
  310. if (SD.exists(filename))
  311. {
  312. logmsg("File, ", filename, ", already exists, InitiatorImageHandling set to stop if file exists.");
  313. g_initiator_state.drives_imaged |= (1 << g_initiator_state.target_id);
  314. return;
  315. }
  316. }
  317. // Create a new copy to the file 002-999
  318. else if (handling == 1)
  319. {
  320. for (uint32_t i = 1; i <= 1000; i++)
  321. {
  322. if (i == 1)
  323. {
  324. if (SD.exists(filename))
  325. continue;
  326. break;
  327. }
  328. else if(i >= 1000)
  329. {
  330. logmsg("Max images created from SCSI ID ", g_initiator_state.target_id, ", skipping image creation");
  331. g_initiator_state.drives_imaged |= (1 << g_initiator_state.target_id);
  332. return;
  333. }
  334. char filename_copy[6] = {0};
  335. if (g_initiator_state.eject_when_done)
  336. {
  337. auto removable_count = g_initiator_state.removable_count[g_initiator_state.target_id];
  338. snprintf(filename, sizeof(filename), "%s(%lu)-%03lu%s", filename_base, removable_count, i, filename_extension);
  339. }
  340. else
  341. {
  342. snprintf(filename, sizeof(filename), "%s-%03lu%s", filename_base, i, filename_extension);
  343. }
  344. snprintf(filename_copy, sizeof(filename_copy), "-%03lu", i);
  345. if (SD.exists(filename))
  346. continue;
  347. break;
  348. }
  349. }
  350. // overwrite file if it exists
  351. else if (handling == 2)
  352. {
  353. if (SD.exists(filename))
  354. {
  355. logmsg("File, ",filename, " already exists, InitiatorImageHandling set to overwrite file");
  356. SD.remove(filename);
  357. }
  358. }
  359. // InitiatorImageHandling invalid setting
  360. else
  361. {
  362. static bool invalid_logged_once = false;
  363. if (!invalid_logged_once)
  364. {
  365. logmsg("InitiatorImageHandling is set to, ", handling, ", which is invalid");
  366. invalid_logged_once = true;
  367. }
  368. return;
  369. }
  370. uint64_t sd_card_free_bytes = (uint64_t)SD.vol()->freeClusterCount() * SD.vol()->bytesPerCluster();
  371. if (sd_card_free_bytes < total_bytes)
  372. {
  373. logmsg("SD Card only has ", (int)(sd_card_free_bytes / (1024 * 1024)),
  374. " MiB - not enough free space to image SCSI ID ", g_initiator_state.target_id);
  375. g_initiator_state.drives_imaged |= 1 << g_initiator_state.target_id;
  376. return;
  377. }
  378. g_initiator_state.target_file = SD.open(filename, O_WRONLY | O_CREAT | O_TRUNC);
  379. if (!g_initiator_state.target_file.isOpen())
  380. {
  381. logmsg("Failed to open file for writing: ", filename);
  382. return;
  383. }
  384. if (SD.fatType() == FAT_TYPE_EXFAT)
  385. {
  386. // Only preallocate on exFAT, on FAT32 preallocating can result in false garbage data in the
  387. // file if write is interrupted.
  388. logmsg("Preallocating image file");
  389. g_initiator_state.target_file.preAllocate((uint64_t)g_initiator_state.sectorcount * g_initiator_state.sectorsize);
  390. }
  391. logmsg("Starting to copy drive data to ", filename);
  392. g_initiator_state.imaging = true;
  393. }
  394. }
  395. }
  396. else
  397. {
  398. // Copy sectors from SCSI drive to file
  399. if (g_initiator_state.sectors_done >= g_initiator_state.sectorcount)
  400. {
  401. scsiStartStopUnit(g_initiator_state.target_id, false);
  402. logmsg("Finished imaging drive with id ", g_initiator_state.target_id);
  403. LED_OFF();
  404. if (g_initiator_state.sectorcount != g_initiator_state.sectorcount_all)
  405. {
  406. logmsg("NOTE: Image size was limited to first 4 GiB due to SD card filesystem limit");
  407. logmsg("Please reformat the SD card with exFAT format to image this drive fully");
  408. }
  409. if(g_initiator_state.bad_sector_count != 0)
  410. {
  411. logmsg("NOTE: There were ", (int) g_initiator_state.bad_sector_count, " bad sectors that could not be read off this drive.");
  412. }
  413. if (!g_initiator_state.eject_when_done)
  414. {
  415. logmsg("Marking SCSI ID, ", g_initiator_state.target_id, ", as imaged, wont ask it again.");
  416. g_initiator_state.drives_imaged |= (1 << g_initiator_state.target_id);
  417. }
  418. g_initiator_state.imaging = false;
  419. g_initiator_state.target_file.close();
  420. return;
  421. }
  422. scsiInitiatorUpdateLed();
  423. // How many sectors to read in one batch?
  424. int numtoread = g_initiator_state.sectorcount - g_initiator_state.sectors_done;
  425. if (numtoread > g_initiator_state.max_sector_per_transfer)
  426. numtoread = g_initiator_state.max_sector_per_transfer;
  427. // Retry sector-by-sector after failure
  428. if (g_initiator_state.sectors_done < g_initiator_state.failposition)
  429. numtoread = 1;
  430. uint32_t time_start = millis();
  431. bool status = scsiInitiatorReadDataToFile(g_initiator_state.target_id,
  432. g_initiator_state.sectors_done, numtoread, g_initiator_state.sectorsize,
  433. g_initiator_state.target_file);
  434. if (!status)
  435. {
  436. logmsg("Failed to transfer ", numtoread, " sectors starting at ", (int)g_initiator_state.sectors_done);
  437. if (g_initiator_state.retrycount < g_initiator_state.max_retry_count)
  438. {
  439. logmsg("Retrying.. ", g_initiator_state.retrycount + 1, "/", (int) g_initiator_state.max_retry_count);
  440. delay_with_poll(200);
  441. // This reset causes some drives to hang and seems to have no effect if left off.
  442. // scsiHostPhyReset();
  443. delay_with_poll(200);
  444. g_initiator_state.retrycount++;
  445. g_initiator_state.target_file.seek((uint64_t)g_initiator_state.sectors_done * g_initiator_state.sectorsize);
  446. if (g_initiator_state.retrycount > 1 && numtoread > 1)
  447. {
  448. logmsg("Multiple failures, retrying sector-by-sector");
  449. g_initiator_state.failposition = g_initiator_state.sectors_done + numtoread;
  450. }
  451. }
  452. else
  453. {
  454. logmsg("Retry limit exceeded, skipping one sector");
  455. g_initiator_state.retrycount = 0;
  456. g_initiator_state.sectors_done++;
  457. g_initiator_state.bad_sector_count++;
  458. g_initiator_state.target_file.seek((uint64_t)g_initiator_state.sectors_done * g_initiator_state.sectorsize);
  459. }
  460. }
  461. else
  462. {
  463. g_initiator_state.retrycount = 0;
  464. g_initiator_state.sectors_done += numtoread;
  465. g_initiator_state.target_file.flush();
  466. int speed_kbps = numtoread * g_initiator_state.sectorsize / (millis() - time_start);
  467. logmsg("SCSI read succeeded, sectors done: ",
  468. (int)g_initiator_state.sectors_done, " / ", (int)g_initiator_state.sectorcount,
  469. " speed ", speed_kbps, " kB/s - ",
  470. (int)(100 * (int64_t)g_initiator_state.sectors_done / g_initiator_state.sectorcount), "%");
  471. }
  472. }
  473. }
  474. /*************************************
  475. * Low level command implementations *
  476. *************************************/
  477. int scsiInitiatorRunCommand(int target_id,
  478. const uint8_t *command, size_t cmdLen,
  479. uint8_t *bufIn, size_t bufInLen,
  480. const uint8_t *bufOut, size_t bufOutLen,
  481. bool returnDataPhase)
  482. {
  483. if (!scsiHostPhySelect(target_id, g_initiator_state.initiator_id))
  484. {
  485. #ifndef ZULUSCSI_NETWORK
  486. dbgmsg("------ Target ", target_id, " did not respond");
  487. #endif
  488. scsiHostPhyRelease();
  489. return -1;
  490. }
  491. SCSI_PHASE phase;
  492. int status = -1;
  493. while ((phase = (SCSI_PHASE)scsiHostPhyGetPhase()) != BUS_FREE)
  494. {
  495. platform_poll();
  496. if (phase == MESSAGE_IN)
  497. {
  498. uint8_t dummy = 0;
  499. scsiHostRead(&dummy, 1);
  500. }
  501. else if (phase == MESSAGE_OUT)
  502. {
  503. uint8_t identify_msg = 0x80;
  504. scsiHostWrite(&identify_msg, 1);
  505. }
  506. else if (phase == COMMAND)
  507. {
  508. scsiHostWrite(command, cmdLen);
  509. }
  510. else if (phase == DATA_IN)
  511. {
  512. if (returnDataPhase) return 0;
  513. if (bufInLen == 0)
  514. {
  515. logmsg("DATA_IN phase but no data to receive!");
  516. status = -3;
  517. break;
  518. }
  519. if (scsiHostRead(bufIn, bufInLen) == 0)
  520. {
  521. logmsg("scsiHostRead failed, tried to read ", (int)bufInLen, " bytes");
  522. status = -2;
  523. break;
  524. }
  525. }
  526. else if (phase == DATA_OUT)
  527. {
  528. if (returnDataPhase) return 0;
  529. if (bufOutLen == 0)
  530. {
  531. logmsg("DATA_OUT phase but no data to send!");
  532. status = -3;
  533. break;
  534. }
  535. if (scsiHostWrite(bufOut, bufOutLen) < bufOutLen)
  536. {
  537. logmsg("scsiHostWrite failed, was writing ", bytearray(bufOut, bufOutLen));
  538. status = -2;
  539. break;
  540. }
  541. }
  542. else if (phase == STATUS)
  543. {
  544. uint8_t tmp = -1;
  545. scsiHostRead(&tmp, 1);
  546. status = tmp;
  547. #ifndef ZULUSCSI_NETWORK
  548. dbgmsg("------ STATUS: ", tmp);
  549. #endif
  550. }
  551. }
  552. scsiHostPhyRelease();
  553. return status;
  554. }
  555. bool scsiInitiatorReadCapacity(int target_id, uint32_t *sectorcount, uint32_t *sectorsize)
  556. {
  557. uint8_t command[10] = {0x25, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  558. uint8_t response[8] = {0};
  559. int status = scsiInitiatorRunCommand(target_id,
  560. command, sizeof(command),
  561. response, sizeof(response),
  562. NULL, 0);
  563. if (status == 0)
  564. {
  565. *sectorcount = ((uint32_t)response[0] << 24)
  566. | ((uint32_t)response[1] << 16)
  567. | ((uint32_t)response[2] << 8)
  568. | ((uint32_t)response[3] << 0);
  569. *sectorcount += 1; // SCSI reports last sector address
  570. *sectorsize = ((uint32_t)response[4] << 24)
  571. | ((uint32_t)response[5] << 16)
  572. | ((uint32_t)response[6] << 8)
  573. | ((uint32_t)response[7] << 0);
  574. return true;
  575. }
  576. else if (status == 2)
  577. {
  578. uint8_t sense_key;
  579. scsiRequestSense(target_id, &sense_key);
  580. logmsg("READ CAPACITY on target ", target_id, " failed, sense key ", sense_key);
  581. return false;
  582. }
  583. else
  584. {
  585. *sectorcount = *sectorsize = 0;
  586. return false;
  587. }
  588. }
  589. // Execute REQUEST SENSE command to get more information about error status
  590. bool scsiRequestSense(int target_id, uint8_t *sense_key)
  591. {
  592. uint8_t command[6] = {0x03, 0, 0, 0, 18, 0};
  593. uint8_t response[18] = {0};
  594. int status = scsiInitiatorRunCommand(target_id,
  595. command, sizeof(command),
  596. response, sizeof(response),
  597. NULL, 0);
  598. dbgmsg("RequestSense response: ", bytearray(response, 18));
  599. *sense_key = response[2] % 0xF;
  600. return status == 0;
  601. }
  602. // Execute UNIT START STOP command to load/unload media
  603. bool scsiStartStopUnit(int target_id, bool start)
  604. {
  605. uint8_t command[6] = {0x1B, 0x1, 0, 0, 0, 0};
  606. uint8_t response[4] = {0};
  607. if (start)
  608. {
  609. command[4] |= 1; // Start
  610. command[1] = 0; // Immediate
  611. }
  612. else // stop
  613. {
  614. if(g_initiator_state.eject_when_done)
  615. {
  616. logmsg("Ejecting media on SCSI ID: ", target_id);
  617. g_initiator_state.removable_count[g_initiator_state.target_id]++;
  618. command[4] = 0b00000010; // eject(6), stop(7).
  619. }
  620. }
  621. int status = scsiInitiatorRunCommand(target_id,
  622. command, sizeof(command),
  623. response, sizeof(response),
  624. NULL, 0);
  625. if (status == 2)
  626. {
  627. uint8_t sense_key;
  628. scsiRequestSense(target_id, &sense_key);
  629. dbgmsg("START STOP UNIT on target ", target_id, " failed, sense key ", sense_key);
  630. }
  631. return status == 0;
  632. }
  633. // Execute INQUIRY command
  634. bool scsiInquiry(int target_id, uint8_t inquiry_data[36])
  635. {
  636. uint8_t command[6] = {0x12, 0, 0, 0, 36, 0};
  637. int status = scsiInitiatorRunCommand(target_id,
  638. command, sizeof(command),
  639. inquiry_data, 36,
  640. NULL, 0);
  641. return status == 0;
  642. }
  643. // Execute TEST UNIT READY command and handle unit attention state
  644. bool scsiTestUnitReady(int target_id)
  645. {
  646. for (int retries = 0; retries < 2; retries++)
  647. {
  648. uint8_t command[6] = {0x00, 0, 0, 0, 0, 0};
  649. int status = scsiInitiatorRunCommand(target_id,
  650. command, sizeof(command),
  651. NULL, 0,
  652. NULL, 0);
  653. if (status == 0)
  654. {
  655. return true;
  656. }
  657. else if (status == -1)
  658. {
  659. // No response to select
  660. return false;
  661. }
  662. else if (status == 2)
  663. {
  664. uint8_t sense_key;
  665. scsiRequestSense(target_id, &sense_key);
  666. if (sense_key == 6)
  667. {
  668. uint8_t inquiry[36];
  669. dbgmsg("Target ", target_id, " reports UNIT_ATTENTION, running INQUIRY");
  670. scsiInquiry(target_id, inquiry);
  671. }
  672. else if (sense_key == 2)
  673. {
  674. dbgmsg("Target ", target_id, " reports NOT_READY, running STARTSTOPUNIT");
  675. scsiStartStopUnit(target_id, true);
  676. }
  677. }
  678. else
  679. {
  680. dbgmsg("Target ", target_id, " TEST UNIT READY response: ", status);
  681. }
  682. }
  683. return false;
  684. }
  685. // This uses callbacks to run SD and SCSI transfers in parallel
  686. static struct {
  687. uint32_t bytes_sd; // Number of bytes that have been transferred on SD card side
  688. uint32_t bytes_sd_scheduled; // Number of bytes scheduled for transfer on SD card side
  689. uint32_t bytes_scsi; // Number of bytes that have been scheduled for transfer on SCSI side
  690. uint32_t bytes_scsi_done; // Number of bytes that have been transferred on SCSI side
  691. uint32_t bytes_per_sector;
  692. bool all_ok;
  693. } g_initiator_transfer;
  694. static void initiatorReadSDCallback(uint32_t bytes_complete)
  695. {
  696. if (g_initiator_transfer.bytes_scsi_done < g_initiator_transfer.bytes_scsi)
  697. {
  698. // How many bytes remaining in the transfer?
  699. uint32_t remain = g_initiator_transfer.bytes_scsi - g_initiator_transfer.bytes_scsi_done;
  700. uint32_t len = remain;
  701. // Limit maximum amount of data transferred at one go, to give enough callbacks to SD driver.
  702. // Select the limit based on total bytes in the transfer.
  703. // Transfer size is reduced towards the end of transfer to reduce the dead time between
  704. // end of SCSI transfer and the SD write completing.
  705. uint32_t limit = g_initiator_transfer.bytes_scsi / 8;
  706. uint32_t bytesPerSector = g_initiator_transfer.bytes_per_sector;
  707. if (limit < PLATFORM_OPTIMAL_MIN_SD_WRITE_SIZE) limit = PLATFORM_OPTIMAL_MIN_SD_WRITE_SIZE;
  708. if (limit > PLATFORM_OPTIMAL_MAX_SD_WRITE_SIZE) limit = PLATFORM_OPTIMAL_MAX_SD_WRITE_SIZE;
  709. if (limit > len) limit = PLATFORM_OPTIMAL_LAST_SD_WRITE_SIZE;
  710. if (limit < bytesPerSector) limit = bytesPerSector;
  711. if (len > limit)
  712. {
  713. len = limit;
  714. }
  715. // Split read so that it doesn't wrap around buffer edge
  716. uint32_t bufsize = sizeof(scsiDev.data);
  717. uint32_t start = (g_initiator_transfer.bytes_scsi_done % bufsize);
  718. if (start + len > bufsize)
  719. len = bufsize - start;
  720. // Don't overwrite data that has not yet been written to SD card
  721. uint32_t sd_ready_cnt = g_initiator_transfer.bytes_sd + bytes_complete;
  722. if (g_initiator_transfer.bytes_scsi_done + len > sd_ready_cnt + bufsize)
  723. len = sd_ready_cnt + bufsize - g_initiator_transfer.bytes_scsi_done;
  724. if (sd_ready_cnt == g_initiator_transfer.bytes_sd_scheduled &&
  725. g_initiator_transfer.bytes_sd_scheduled + bytesPerSector <= g_initiator_transfer.bytes_scsi_done)
  726. {
  727. // Current SD transfer is complete, it is better we return now and offer a chance for the next
  728. // transfer to begin.
  729. return;
  730. }
  731. // Keep transfers a multiple of sector size.
  732. if (remain >= bytesPerSector && len % bytesPerSector != 0)
  733. {
  734. len -= len % bytesPerSector;
  735. }
  736. if (len == 0)
  737. return;
  738. // dbgmsg("SCSI read ", (int)start, " + ", (int)len, ", sd ready cnt ", (int)sd_ready_cnt, " ", (int)bytes_complete, ", scsi done ", (int)g_initiator_transfer.bytes_scsi_done);
  739. if (scsiHostRead(&scsiDev.data[start], len) != len)
  740. {
  741. logmsg("Read failed at byte ", (int)g_initiator_transfer.bytes_scsi_done);
  742. g_initiator_transfer.all_ok = false;
  743. }
  744. g_initiator_transfer.bytes_scsi_done += len;
  745. }
  746. }
  747. static void scsiInitiatorWriteDataToSd(FsFile &file, bool use_callback)
  748. {
  749. // Figure out longest continuous block in buffer
  750. uint32_t bufsize = sizeof(scsiDev.data);
  751. uint32_t start = g_initiator_transfer.bytes_sd % bufsize;
  752. uint32_t len = g_initiator_transfer.bytes_scsi_done - g_initiator_transfer.bytes_sd;
  753. if (start + len > bufsize) len = bufsize - start;
  754. // Try to do writes in multiple of 512 bytes
  755. // This allows better performance for SD card access.
  756. if (len >= 512) len &= ~511;
  757. // Start writing to SD card and simultaneously reading more from SCSI bus
  758. uint8_t *buf = &scsiDev.data[start];
  759. // dbgmsg("SD write ", (int)start, " + ", (int)len);
  760. if (use_callback)
  761. {
  762. platform_set_sd_callback(&initiatorReadSDCallback, buf);
  763. }
  764. g_initiator_transfer.bytes_sd_scheduled = g_initiator_transfer.bytes_sd + len;
  765. if (file.write(buf, len) != len)
  766. {
  767. logmsg("scsiInitiatorReadDataToFile: SD card write failed");
  768. g_initiator_transfer.all_ok = false;
  769. }
  770. platform_set_sd_callback(NULL, NULL);
  771. g_initiator_transfer.bytes_sd += len;
  772. }
  773. bool scsiInitiatorReadDataToFile(int target_id, uint32_t start_sector, uint32_t sectorcount, uint32_t sectorsize,
  774. FsFile &file)
  775. {
  776. int status = -1;
  777. // Read6 command supports 21 bit LBA - max of 0x1FFFFF
  778. // ref: https://www.seagate.com/files/staticfiles/support/docs/manual/Interface%20manuals/100293068j.pdf pg 134
  779. if (g_initiator_state.ansi_version < 0x02 || (start_sector < 0x1FFFFF && sectorcount <= 256))
  780. {
  781. // Use READ6 command for compatibility with old SCSI1 drives
  782. uint8_t command[6] = {0x08,
  783. (uint8_t)(start_sector >> 16),
  784. (uint8_t)(start_sector >> 8),
  785. (uint8_t)start_sector,
  786. (uint8_t)sectorcount,
  787. 0x00
  788. };
  789. // Start executing command, return in data phase
  790. status = scsiInitiatorRunCommand(target_id, command, sizeof(command), NULL, 0, NULL, 0, true);
  791. }
  792. else
  793. {
  794. // Use READ10 command for larger number of blocks
  795. uint8_t command[10] = {0x28, 0x00,
  796. (uint8_t)(start_sector >> 24), (uint8_t)(start_sector >> 16),
  797. (uint8_t)(start_sector >> 8), (uint8_t)start_sector,
  798. 0x00,
  799. (uint8_t)(sectorcount >> 8), (uint8_t)(sectorcount),
  800. 0x00
  801. };
  802. // Start executing command, return in data phase
  803. status = scsiInitiatorRunCommand(target_id, command, sizeof(command), NULL, 0, NULL, 0, true);
  804. }
  805. if (status != 0)
  806. {
  807. uint8_t sense_key;
  808. scsiRequestSense(target_id, &sense_key);
  809. logmsg("scsiInitiatorReadDataToFile: READ failed: ", status, " sense key ", sense_key);
  810. scsiHostPhyRelease();
  811. return false;
  812. }
  813. SCSI_PHASE phase;
  814. g_initiator_transfer.bytes_scsi = sectorcount * sectorsize;
  815. g_initiator_transfer.bytes_per_sector = sectorsize;
  816. g_initiator_transfer.bytes_sd = 0;
  817. g_initiator_transfer.bytes_sd_scheduled = 0;
  818. g_initiator_transfer.bytes_scsi_done = 0;
  819. g_initiator_transfer.all_ok = true;
  820. while (true)
  821. {
  822. platform_poll();
  823. phase = (SCSI_PHASE)scsiHostPhyGetPhase();
  824. if (phase != DATA_IN && phase != BUS_BUSY)
  825. {
  826. break;
  827. }
  828. // Read next block from SCSI bus if buffer empty
  829. if (g_initiator_transfer.bytes_sd == g_initiator_transfer.bytes_scsi_done)
  830. {
  831. initiatorReadSDCallback(0);
  832. }
  833. else
  834. {
  835. // Write data to SD card and simultaneously read more from SCSI
  836. scsiInitiatorUpdateLed();
  837. scsiInitiatorWriteDataToSd(file, true);
  838. }
  839. }
  840. // Write any remaining buffered data
  841. while (g_initiator_transfer.bytes_sd < g_initiator_transfer.bytes_scsi_done)
  842. {
  843. platform_poll();
  844. scsiInitiatorWriteDataToSd(file, false);
  845. }
  846. if (g_initiator_transfer.bytes_sd != g_initiator_transfer.bytes_scsi)
  847. {
  848. logmsg("SCSI read from sector ", (int)start_sector, " was incomplete: expected ",
  849. (int)g_initiator_transfer.bytes_scsi, " got ", (int)g_initiator_transfer.bytes_sd, " bytes");
  850. g_initiator_transfer.all_ok = false;
  851. }
  852. while ((phase = (SCSI_PHASE)scsiHostPhyGetPhase()) != BUS_FREE)
  853. {
  854. platform_poll();
  855. if (phase == MESSAGE_IN)
  856. {
  857. uint8_t dummy = 0;
  858. scsiHostRead(&dummy, 1);
  859. }
  860. else if (phase == MESSAGE_OUT)
  861. {
  862. uint8_t identify_msg = 0x80;
  863. scsiHostWrite(&identify_msg, 1);
  864. }
  865. else if (phase == STATUS)
  866. {
  867. uint8_t tmp = 0;
  868. scsiHostRead(&tmp, 1);
  869. status = tmp;
  870. dbgmsg("------ STATUS: ", tmp);
  871. }
  872. }
  873. scsiHostPhyRelease();
  874. return status == 0 && g_initiator_transfer.all_ok;
  875. }
  876. #endif