BlueSCSI_initiator.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  1. /*
  2. * ZuluSCSI
  3. * Copyright (c) 2022 Rabbit Hole Computing
  4. *
  5. * Main program for initiator mode.
  6. */
  7. #include "BlueSCSI_config.h"
  8. #include "BlueSCSI_log.h"
  9. #include "BlueSCSI_log_trace.h"
  10. #include "BlueSCSI_initiator.h"
  11. #include <BlueSCSI_platform.h>
  12. #include <minIni.h>
  13. #include "SdFat.h"
  14. #include <scsi2sd.h>
  15. extern "C" {
  16. #include <scsi.h>
  17. }
  18. #ifndef PLATFORM_HAS_INITIATOR_MODE
  19. void scsiInitiatorInit()
  20. {
  21. }
  22. void scsiInitiatorMainLoop()
  23. {
  24. }
  25. int scsiInitiatorRunCommand(const uint8_t *command, size_t cmdlen,
  26. uint8_t *bufIn, size_t bufInLen,
  27. const uint8_t *bufOut, size_t bufOutLen)
  28. {
  29. return -1;
  30. }
  31. bool scsiInitiatorReadCapacity(int target_id, uint32_t *sectorcount, uint32_t *sectorsize)
  32. {
  33. return false;
  34. }
  35. #else
  36. /*************************************
  37. * High level initiator mode logic *
  38. *************************************/
  39. static struct {
  40. // Bitmap of all drives that have been imaged
  41. uint32_t drives_imaged;
  42. uint8_t initiator_id;
  43. // Is imaging a drive in progress, or are we scanning?
  44. bool imaging;
  45. // Information about currently selected drive
  46. int target_id;
  47. uint32_t sectorsize;
  48. uint32_t sectorcount;
  49. uint32_t sectorcount_all;
  50. uint32_t sectors_done;
  51. uint32_t max_sector_per_transfer;
  52. uint32_t badSectorCount;
  53. uint8_t ansiVersion;
  54. uint8_t maxRetryCount;
  55. // Retry information for sector reads.
  56. // If a large read fails, retry is done sector-by-sector.
  57. int retrycount;
  58. uint32_t failposition;
  59. FsFile target_file;
  60. } g_initiator_state;
  61. extern SdFs SD;
  62. // Initialization of initiator mode
  63. void scsiInitiatorInit()
  64. {
  65. scsiHostPhyReset();
  66. g_initiator_state.initiator_id = ini_getl("SCSI", "InitiatorID", 7, CONFIGFILE);
  67. if (g_initiator_state.initiator_id > 7)
  68. {
  69. log("InitiatorID set to illegal value in, ", CONFIGFILE, ", defaulting to 7");
  70. g_initiator_state.initiator_id = 7;
  71. } else
  72. {
  73. log_f("InitiatorID set to ID %d", g_initiator_state.initiator_id);
  74. }
  75. g_initiator_state.maxRetryCount = ini_getl("SCSI", "InitiatorMaxRetry", 5, CONFIGFILE);
  76. // treat initiator id as already imaged drive so it gets skipped
  77. g_initiator_state.drives_imaged = 1 << g_initiator_state.initiator_id;
  78. g_initiator_state.imaging = false;
  79. g_initiator_state.target_id = -1;
  80. g_initiator_state.sectorsize = 0;
  81. g_initiator_state.sectorcount = 0;
  82. g_initiator_state.sectors_done = 0;
  83. g_initiator_state.retrycount = 0;
  84. g_initiator_state.failposition = 0;
  85. g_initiator_state.max_sector_per_transfer = 512;
  86. g_initiator_state.ansiVersion = 0;
  87. g_initiator_state.badSectorCount = 0;
  88. }
  89. // Update progress bar LED during transfers
  90. static void scsiInitiatorUpdateLed()
  91. {
  92. // Update status indicator, the led blinks every 5 seconds and is on the longer the more data has been transferred
  93. const int period = 256;
  94. int phase = (millis() % period);
  95. int duty = g_initiator_state.sectors_done * period / g_initiator_state.sectorcount;
  96. // Minimum and maximum time to verify that the blink is visible
  97. if (duty < 50) duty = 50;
  98. if (duty > period - 50) duty = period - 50;
  99. if (phase <= duty)
  100. {
  101. LED_ON();
  102. }
  103. else
  104. {
  105. LED_OFF();
  106. }
  107. }
  108. void delay_with_poll(uint32_t ms)
  109. {
  110. uint32_t start = millis();
  111. while ((uint32_t)(millis() - start) < ms)
  112. {
  113. platform_poll();
  114. delay(1);
  115. }
  116. }
  117. // High level logic of the initiator mode
  118. void scsiInitiatorMainLoop()
  119. {
  120. SCSI_RELEASE_OUTPUTS();
  121. SCSI_ENABLE_INITIATOR();
  122. if (g_scsiHostPhyReset)
  123. {
  124. log("Executing BUS RESET after aborted command");
  125. scsiHostPhyReset();
  126. }
  127. if (!g_initiator_state.imaging)
  128. {
  129. // Scan for SCSI drives one at a time
  130. g_initiator_state.target_id = (g_initiator_state.target_id + 1) % 8;
  131. g_initiator_state.sectors_done = 0;
  132. g_initiator_state.retrycount = 0;
  133. g_initiator_state.max_sector_per_transfer = 512;
  134. g_initiator_state.badSectorCount = 0;
  135. if (!(g_initiator_state.drives_imaged & (1 << g_initiator_state.target_id)))
  136. {
  137. delay_with_poll(1000);
  138. uint8_t inquiry_data[36] = {0};
  139. LED_ON();
  140. bool startstopok =
  141. scsiTestUnitReady(g_initiator_state.target_id) &&
  142. scsiStartStopUnit(g_initiator_state.target_id, true);
  143. bool readcapok = startstopok &&
  144. scsiInitiatorReadCapacity(g_initiator_state.target_id,
  145. &g_initiator_state.sectorcount,
  146. &g_initiator_state.sectorsize);
  147. bool inquiryok = startstopok &&
  148. scsiInquiry(g_initiator_state.target_id, inquiry_data);
  149. g_initiator_state.ansiVersion = inquiry_data[2] & 0x7;
  150. LED_OFF();
  151. uint64_t total_bytes = 0;
  152. if (readcapok)
  153. {
  154. log("SCSI ID ", g_initiator_state.target_id,
  155. " capacity ", (int)g_initiator_state.sectorcount,
  156. " sectors x ", (int)g_initiator_state.sectorsize, " bytes");
  157. log_f("SCSI-%d: Vendor: %.8s, Product: %.16s, Version: %.4s",
  158. g_initiator_state.ansiVersion,
  159. &inquiry_data[8],
  160. &inquiry_data[16],
  161. &inquiry_data[32]);
  162. g_initiator_state.sectorcount_all = g_initiator_state.sectorcount;
  163. total_bytes = (uint64_t)g_initiator_state.sectorcount * g_initiator_state.sectorsize;
  164. log("Drive total size is ", (int)(total_bytes / (1024 * 1024)), " MiB");
  165. if (total_bytes >= 0xFFFFFFFF && SD.fatType() != FAT_TYPE_EXFAT)
  166. {
  167. // Note: the FAT32 limit is 4 GiB - 1 byte
  168. log("Image files equal or larger than 4 GiB are only possible on exFAT filesystem");
  169. log("Please reformat the SD card with exFAT format to image this drive.");
  170. g_initiator_state.sectorsize = 0;
  171. g_initiator_state.sectorcount = g_initiator_state.sectorcount_all = 0;
  172. }
  173. if(g_initiator_state.ansiVersion != 0x02)
  174. {
  175. // this is a SCSI-1 drive, use READ6 and 256 bytes to be safe.
  176. g_initiator_state.max_sector_per_transfer = 256;
  177. }
  178. }
  179. else if (startstopok)
  180. {
  181. log("SCSI ID ", g_initiator_state.target_id, " responds but ReadCapacity command failed");
  182. log("Possibly SCSI-1 drive? Attempting to read up to 1 GB.");
  183. g_initiator_state.sectorsize = 512;
  184. g_initiator_state.sectorcount = g_initiator_state.sectorcount_all = 2097152;
  185. g_initiator_state.max_sector_per_transfer = 128;
  186. }
  187. else
  188. {
  189. log("* No response from SCSI ID ", g_initiator_state.target_id);
  190. g_initiator_state.sectorsize = 0;
  191. g_initiator_state.sectorcount = g_initiator_state.sectorcount_all = 0;
  192. }
  193. const char *filename_format = "HD00_imaged.hda";
  194. if (inquiryok)
  195. {
  196. if ((inquiry_data[0] & 0x1F) == 5)
  197. {
  198. filename_format = "CD00_imaged.iso";
  199. }
  200. }
  201. if (g_initiator_state.sectorcount > 0)
  202. {
  203. char filename[32] = {0};
  204. int lun = 0;
  205. strncpy(filename, filename_format, sizeof(filename) - 1);
  206. filename[2] += g_initiator_state.target_id;
  207. uint64_t sd_card_free_bytes = (uint64_t)SD.vol()->freeClusterCount() * SD.vol()->bytesPerCluster();
  208. if(sd_card_free_bytes < total_bytes)
  209. {
  210. log("SD Card only has ", (int)(sd_card_free_bytes / (1024 * 1024)), " MiB - not enough free space to image this drive!");
  211. g_initiator_state.imaging = false;
  212. return;
  213. }
  214. while(SD.exists(filename))
  215. {
  216. filename[3] = lun++ + '0';
  217. }
  218. if(lun != 0)
  219. {
  220. log("Using filename: ", filename, " to avoid overwriting existing file.");
  221. }
  222. g_initiator_state.target_file = SD.open(filename, O_WRONLY | O_CREAT | O_TRUNC);
  223. if (!g_initiator_state.target_file.isOpen())
  224. {
  225. log("Failed to open file for writing: ", filename);
  226. return;
  227. }
  228. if (SD.fatType() == FAT_TYPE_EXFAT)
  229. {
  230. // Only preallocate on exFAT, on FAT32 preallocating can result in false garbage data in the
  231. // file if write is interrupted.
  232. log("Preallocating image file");
  233. g_initiator_state.target_file.preAllocate((uint64_t)g_initiator_state.sectorcount * g_initiator_state.sectorsize);
  234. }
  235. log("Starting to copy drive data to ", filename);
  236. g_initiator_state.imaging = true;
  237. }
  238. }
  239. }
  240. else
  241. {
  242. // Copy sectors from SCSI drive to file
  243. if (g_initiator_state.sectors_done >= g_initiator_state.sectorcount)
  244. {
  245. scsiStartStopUnit(g_initiator_state.target_id, false);
  246. log("Finished imaging drive with id ", g_initiator_state.target_id);
  247. LED_OFF();
  248. if (g_initiator_state.sectorcount != g_initiator_state.sectorcount_all)
  249. {
  250. log("NOTE: Image size was limited to first 4 GiB due to SD card filesystem limit");
  251. log("Please reformat the SD card with exFAT format to image this drive fully");
  252. }
  253. if(g_initiator_state.badSectorCount != 0)
  254. {
  255. log_f("NOTE: There were %d bad sectors that could not be read off this drive.", g_initiator_state.badSectorCount);
  256. }
  257. g_initiator_state.drives_imaged |= (1 << g_initiator_state.target_id);
  258. g_initiator_state.imaging = false;
  259. g_initiator_state.target_file.close();
  260. return;
  261. }
  262. scsiInitiatorUpdateLed();
  263. // How many sectors to read in one batch?
  264. int numtoread = g_initiator_state.sectorcount - g_initiator_state.sectors_done;
  265. if (numtoread > g_initiator_state.max_sector_per_transfer)
  266. numtoread = g_initiator_state.max_sector_per_transfer;
  267. // Retry sector-by-sector after failure
  268. if (g_initiator_state.sectors_done < g_initiator_state.failposition)
  269. numtoread = 1;
  270. uint32_t time_start = millis();
  271. bool status = scsiInitiatorReadDataToFile(g_initiator_state.target_id,
  272. g_initiator_state.sectors_done, numtoread, g_initiator_state.sectorsize,
  273. g_initiator_state.target_file);
  274. if (!status)
  275. {
  276. log("Failed to transfer ", numtoread, " sectors starting at ", (int)g_initiator_state.sectors_done);
  277. if (g_initiator_state.retrycount < g_initiator_state.maxRetryCount)
  278. {
  279. log("Retrying.. ", g_initiator_state.retrycount + 1, "/", (int)g_initiator_state.maxRetryCount);
  280. delay_with_poll(200);
  281. // This reset causes some drives to hang and seems to have no effect if left off.
  282. // scsiHostPhyReset();
  283. delay_with_poll(200);
  284. g_initiator_state.retrycount++;
  285. g_initiator_state.target_file.seek((uint64_t)g_initiator_state.sectors_done * g_initiator_state.sectorsize);
  286. if (g_initiator_state.retrycount > 1 && numtoread > 1)
  287. {
  288. log("Multiple failures, retrying sector-by-sector");
  289. g_initiator_state.failposition = g_initiator_state.sectors_done + numtoread;
  290. }
  291. }
  292. else
  293. {
  294. log("Retry limit exceeded, skipping one sector");
  295. g_initiator_state.retrycount = 0;
  296. g_initiator_state.sectors_done++;
  297. g_initiator_state.badSectorCount++;
  298. g_initiator_state.target_file.seek((uint64_t)g_initiator_state.sectors_done * g_initiator_state.sectorsize);
  299. }
  300. }
  301. else
  302. {
  303. g_initiator_state.retrycount = 0;
  304. g_initiator_state.sectors_done += numtoread;
  305. g_initiator_state.target_file.flush();
  306. int speed_kbps = numtoread * g_initiator_state.sectorsize / (millis() - time_start);
  307. log_f("SCSI read succeeded, sectors done: %d / %d speed %d kB/s - %.2f%%",
  308. g_initiator_state.sectors_done, g_initiator_state.sectorcount, speed_kbps,
  309. (float)(((float)g_initiator_state.sectors_done / (float)g_initiator_state.sectorcount) * 100.0));
  310. }
  311. }
  312. }
  313. /*************************************
  314. * Low level command implementations *
  315. *************************************/
  316. int scsiInitiatorRunCommand(int target_id,
  317. const uint8_t *command, size_t cmdLen,
  318. uint8_t *bufIn, size_t bufInLen,
  319. const uint8_t *bufOut, size_t bufOutLen,
  320. bool returnDataPhase)
  321. {
  322. if (!scsiHostPhySelect(target_id, g_initiator_state.initiator_id))
  323. {
  324. debuglog("------ Target ", target_id, " did not respond");
  325. scsiHostPhyRelease();
  326. return -1;
  327. }
  328. SCSI_PHASE phase;
  329. int status = -1;
  330. while ((phase = (SCSI_PHASE)scsiHostPhyGetPhase()) != BUS_FREE)
  331. {
  332. platform_poll();
  333. if (phase == MESSAGE_IN)
  334. {
  335. uint8_t dummy = 0;
  336. scsiHostRead(&dummy, 1);
  337. }
  338. else if (phase == MESSAGE_OUT)
  339. {
  340. uint8_t identify_msg = 0x80;
  341. scsiHostWrite(&identify_msg, 1);
  342. }
  343. else if (phase == COMMAND)
  344. {
  345. scsiHostWrite(command, cmdLen);
  346. }
  347. else if (phase == DATA_IN)
  348. {
  349. if (returnDataPhase) return 0;
  350. if (bufInLen == 0)
  351. {
  352. log("DATA_IN phase but no data to receive!");
  353. status = -3;
  354. break;
  355. }
  356. if (scsiHostRead(bufIn, bufInLen) == 0)
  357. {
  358. log("scsiHostRead failed, tried to read ", (int)bufInLen, " bytes");
  359. status = -2;
  360. break;
  361. }
  362. }
  363. else if (phase == DATA_OUT)
  364. {
  365. if (returnDataPhase) return 0;
  366. if (bufOutLen == 0)
  367. {
  368. log("DATA_OUT phase but no data to send!");
  369. status = -3;
  370. break;
  371. }
  372. if (scsiHostWrite(bufOut, bufOutLen) < bufOutLen)
  373. {
  374. log("scsiHostWrite failed, was writing ", bytearray(bufOut, bufOutLen));
  375. status = -2;
  376. break;
  377. }
  378. }
  379. else if (phase == STATUS)
  380. {
  381. uint8_t tmp = -1;
  382. scsiHostRead(&tmp, 1);
  383. status = tmp;
  384. debuglog("------ STATUS: ", tmp);
  385. }
  386. }
  387. scsiHostPhyRelease();
  388. return status;
  389. }
  390. bool scsiInitiatorReadCapacity(int target_id, uint32_t *sectorcount, uint32_t *sectorsize)
  391. {
  392. uint8_t command[10] = {0x25, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  393. uint8_t response[8] = {0};
  394. int status = scsiInitiatorRunCommand(target_id,
  395. command, sizeof(command),
  396. response, sizeof(response),
  397. NULL, 0);
  398. if (status == 0)
  399. {
  400. *sectorcount = ((uint32_t)response[0] << 24)
  401. | ((uint32_t)response[1] << 16)
  402. | ((uint32_t)response[2] << 8)
  403. | ((uint32_t)response[3] << 0);
  404. *sectorcount += 1; // SCSI reports last sector address
  405. *sectorsize = ((uint32_t)response[4] << 24)
  406. | ((uint32_t)response[5] << 16)
  407. | ((uint32_t)response[6] << 8)
  408. | ((uint32_t)response[7] << 0);
  409. return true;
  410. }
  411. else if (status == 2)
  412. {
  413. uint8_t sense_key;
  414. scsiRequestSense(target_id, &sense_key);
  415. log("READ CAPACITY on target ", target_id, " failed, sense key ", sense_key);
  416. return false;
  417. }
  418. else
  419. {
  420. *sectorcount = *sectorsize = 0;
  421. return false;
  422. }
  423. }
  424. // Execute REQUEST SENSE command to get more information about error status
  425. bool scsiRequestSense(int target_id, uint8_t *sense_key)
  426. {
  427. uint8_t command[6] = {0x03, 0, 0, 0, 18, 0};
  428. uint8_t response[18] = {0};
  429. int status = scsiInitiatorRunCommand(target_id,
  430. command, sizeof(command),
  431. response, sizeof(response),
  432. NULL, 0);
  433. log("RequestSense response: ", bytearray(response, 18));
  434. *sense_key = response[2];
  435. return status == 0;
  436. }
  437. // Execute UNIT START STOP command to load/unload media
  438. bool scsiStartStopUnit(int target_id, bool start)
  439. {
  440. uint8_t command[6] = {0x1B, 0x1, 0, 0, 0, 0};
  441. uint8_t response[4] = {0};
  442. if (start)
  443. {
  444. command[4] |= 1; // Start
  445. command[1] = 0; // Immediate
  446. }
  447. int status = scsiInitiatorRunCommand(target_id,
  448. command, sizeof(command),
  449. response, sizeof(response),
  450. NULL, 0);
  451. if (status == 2)
  452. {
  453. uint8_t sense_key;
  454. scsiRequestSense(target_id, &sense_key);
  455. log("START STOP UNIT on target ", target_id, " failed, sense key ", sense_key);
  456. }
  457. return status == 0;
  458. }
  459. // Execute INQUIRY command
  460. bool scsiInquiry(int target_id, uint8_t inquiry_data[36])
  461. {
  462. uint8_t command[6] = {0x12, 0, 0, 0, 36, 0};
  463. int status = scsiInitiatorRunCommand(target_id,
  464. command, sizeof(command),
  465. inquiry_data, 36,
  466. NULL, 0);
  467. return status == 0;
  468. }
  469. // Execute TEST UNIT READY command and handle unit attention state
  470. bool scsiTestUnitReady(int target_id)
  471. {
  472. for (int retries = 0; retries < 2; retries++)
  473. {
  474. uint8_t command[6] = {0x00, 0, 0, 0, 0, 0};
  475. int status = scsiInitiatorRunCommand(target_id,
  476. command, sizeof(command),
  477. NULL, 0,
  478. NULL, 0);
  479. if (status == 0)
  480. {
  481. return true;
  482. }
  483. else if (status == -1)
  484. {
  485. // No response to select
  486. return false;
  487. }
  488. else if (status == 2)
  489. {
  490. uint8_t sense_key;
  491. scsiRequestSense(target_id, &sense_key);
  492. if (sense_key == 6)
  493. {
  494. uint8_t inquiry[36];
  495. log("Target ", target_id, " reports UNIT_ATTENTION, running INQUIRY");
  496. scsiInquiry(target_id, inquiry);
  497. }
  498. else if (sense_key == 2)
  499. {
  500. log("Target ", target_id, " reports NOT_READY, running STARTSTOPUNIT");
  501. scsiStartStopUnit(target_id, true);
  502. }
  503. }
  504. else
  505. {
  506. log("Target ", target_id, " TEST UNIT READY response: ", status);
  507. }
  508. }
  509. return false;
  510. }
  511. // This uses callbacks to run SD and SCSI transfers in parallel
  512. static struct {
  513. uint32_t bytes_sd; // Number of bytes that have been transferred on SD card side
  514. uint32_t bytes_sd_scheduled; // Number of bytes scheduled for transfer on SD card side
  515. uint32_t bytes_scsi; // Number of bytes that have been scheduled for transfer on SCSI side
  516. uint32_t bytes_scsi_done; // Number of bytes that have been transferred on SCSI side
  517. uint32_t bytes_per_sector;
  518. bool all_ok;
  519. } g_initiator_transfer;
  520. static void initiatorReadSDCallback(uint32_t bytes_complete)
  521. {
  522. if (g_initiator_transfer.bytes_scsi_done < g_initiator_transfer.bytes_scsi)
  523. {
  524. // How many bytes remaining in the transfer?
  525. uint32_t remain = g_initiator_transfer.bytes_scsi - g_initiator_transfer.bytes_scsi_done;
  526. uint32_t len = remain;
  527. // Limit maximum amount of data transferred at one go, to give enough callbacks to SD driver.
  528. // Select the limit based on total bytes in the transfer.
  529. // Transfer size is reduced towards the end of transfer to reduce the dead time between
  530. // end of SCSI transfer and the SD write completing.
  531. uint32_t limit = g_initiator_transfer.bytes_scsi / 8;
  532. uint32_t bytesPerSector = g_initiator_transfer.bytes_per_sector;
  533. if (limit < PLATFORM_OPTIMAL_MIN_SD_WRITE_SIZE) limit = PLATFORM_OPTIMAL_MIN_SD_WRITE_SIZE;
  534. if (limit > PLATFORM_OPTIMAL_MAX_SD_WRITE_SIZE) limit = PLATFORM_OPTIMAL_MAX_SD_WRITE_SIZE;
  535. if (limit > len) limit = PLATFORM_OPTIMAL_LAST_SD_WRITE_SIZE;
  536. if (limit < bytesPerSector) limit = bytesPerSector;
  537. if (len > limit)
  538. {
  539. len = limit;
  540. }
  541. // Split read so that it doesn't wrap around buffer edge
  542. uint32_t bufsize = sizeof(scsiDev.data);
  543. uint32_t start = (g_initiator_transfer.bytes_scsi_done % bufsize);
  544. if (start + len > bufsize)
  545. len = bufsize - start;
  546. // Don't overwrite data that has not yet been written to SD card
  547. uint32_t sd_ready_cnt = g_initiator_transfer.bytes_sd + bytes_complete;
  548. if (g_initiator_transfer.bytes_scsi_done + len > sd_ready_cnt + bufsize)
  549. len = sd_ready_cnt + bufsize - g_initiator_transfer.bytes_scsi_done;
  550. if (sd_ready_cnt == g_initiator_transfer.bytes_sd_scheduled &&
  551. g_initiator_transfer.bytes_sd_scheduled + bytesPerSector <= g_initiator_transfer.bytes_scsi_done)
  552. {
  553. // Current SD transfer is complete, it is better we return now and offer a chance for the next
  554. // transfer to begin.
  555. return;
  556. }
  557. // Keep transfers a multiple of sector size.
  558. if (remain >= bytesPerSector && len % bytesPerSector != 0)
  559. {
  560. len -= len % bytesPerSector;
  561. }
  562. if (len == 0)
  563. return;
  564. // debuglog("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);
  565. if (scsiHostRead(&scsiDev.data[start], len) != len)
  566. {
  567. log("Read failed at byte ", (int)g_initiator_transfer.bytes_scsi_done);
  568. g_initiator_transfer.all_ok = false;
  569. }
  570. g_initiator_transfer.bytes_scsi_done += len;
  571. }
  572. }
  573. static void scsiInitiatorWriteDataToSd(FsFile &file, bool use_callback)
  574. {
  575. // Figure out longest continuous block in buffer
  576. uint32_t bufsize = sizeof(scsiDev.data);
  577. uint32_t start = g_initiator_transfer.bytes_sd % bufsize;
  578. uint32_t len = g_initiator_transfer.bytes_scsi_done - g_initiator_transfer.bytes_sd;
  579. if (start + len > bufsize) len = bufsize - start;
  580. // Try to do writes in multiple of 512 bytes
  581. // This allows better performance for SD card access.
  582. if (len >= 512) len &= ~511;
  583. // Start writing to SD card and simultaneously reading more from SCSI bus
  584. uint8_t *buf = &scsiDev.data[start];
  585. // debuglog("SD write ", (int)start, " + ", (int)len);
  586. if (use_callback)
  587. {
  588. platform_set_sd_callback(&initiatorReadSDCallback, buf);
  589. }
  590. g_initiator_transfer.bytes_sd_scheduled = g_initiator_transfer.bytes_sd + len;
  591. if (file.write(buf, len) != len)
  592. {
  593. log("scsiInitiatorReadDataToFile: SD card write failed");
  594. g_initiator_transfer.all_ok = false;
  595. }
  596. platform_set_sd_callback(NULL, NULL);
  597. g_initiator_transfer.bytes_sd += len;
  598. }
  599. bool scsiInitiatorReadDataToFile(int target_id, uint32_t start_sector, uint32_t sectorcount, uint32_t sectorsize,
  600. FsFile &file)
  601. {
  602. int status = -1;
  603. // Read6 command supports 21 bit LBA - max of 0x1FFFFF
  604. // ref: https://www.seagate.com/files/staticfiles/support/docs/manual/Interface%20manuals/100293068j.pdf pg 134
  605. if (g_initiator_state.ansiVersion != 0x02 || (start_sector < 0x1FFFFF && sectorcount <= 256))
  606. {
  607. // Use READ6 command for compatibility with old SCSI1 drives
  608. uint8_t command[6] = {0x08,
  609. (uint8_t)(start_sector >> 16),
  610. (uint8_t)(start_sector >> 8),
  611. (uint8_t)start_sector,
  612. (uint8_t)sectorcount,
  613. 0x00
  614. };
  615. // Start executing command, return in data phase
  616. status = scsiInitiatorRunCommand(target_id, command, sizeof(command), NULL, 0, NULL, 0, true);
  617. }
  618. else
  619. {
  620. // Use READ10 command for larger number of blocks
  621. uint8_t command[10] = {0x28, 0x00,
  622. (uint8_t)(start_sector >> 24), (uint8_t)(start_sector >> 16),
  623. (uint8_t)(start_sector >> 8), (uint8_t)start_sector,
  624. 0x00,
  625. (uint8_t)(sectorcount >> 8), (uint8_t)(sectorcount),
  626. 0x00
  627. };
  628. // Start executing command, return in data phase
  629. status = scsiInitiatorRunCommand(target_id, command, sizeof(command), NULL, 0, NULL, 0, true);
  630. }
  631. if (status != 0)
  632. {
  633. uint8_t sense_key;
  634. scsiRequestSense(target_id, &sense_key);
  635. log("scsiInitiatorReadDataToFile: READ failed: ", status, " sense key ", sense_key);
  636. scsiHostPhyRelease();
  637. return false;
  638. }
  639. SCSI_PHASE phase;
  640. g_initiator_transfer.bytes_scsi = sectorcount * sectorsize;
  641. g_initiator_transfer.bytes_per_sector = sectorsize;
  642. g_initiator_transfer.bytes_sd = 0;
  643. g_initiator_transfer.bytes_sd_scheduled = 0;
  644. g_initiator_transfer.bytes_scsi_done = 0;
  645. g_initiator_transfer.all_ok = true;
  646. while (true)
  647. {
  648. platform_poll();
  649. phase = (SCSI_PHASE)scsiHostPhyGetPhase();
  650. if (phase != DATA_IN && phase != BUS_BUSY)
  651. {
  652. break;
  653. }
  654. // Read next block from SCSI bus if buffer empty
  655. if (g_initiator_transfer.bytes_sd == g_initiator_transfer.bytes_scsi_done)
  656. {
  657. initiatorReadSDCallback(0);
  658. }
  659. else
  660. {
  661. // Write data to SD card and simultaneously read more from SCSI
  662. scsiInitiatorUpdateLed();
  663. scsiInitiatorWriteDataToSd(file, true);
  664. }
  665. }
  666. // Write any remaining buffered data
  667. while (g_initiator_transfer.bytes_sd < g_initiator_transfer.bytes_scsi_done)
  668. {
  669. platform_poll();
  670. scsiInitiatorWriteDataToSd(file, false);
  671. }
  672. if (g_initiator_transfer.bytes_sd != g_initiator_transfer.bytes_scsi)
  673. {
  674. log("SCSI read from sector ", (int)start_sector, " was incomplete: expected ",
  675. (int)g_initiator_transfer.bytes_scsi, " got ", (int)g_initiator_transfer.bytes_sd, " bytes");
  676. g_initiator_transfer.all_ok = false;
  677. }
  678. while ((phase = (SCSI_PHASE)scsiHostPhyGetPhase()) != BUS_FREE)
  679. {
  680. platform_poll();
  681. if (phase == MESSAGE_IN)
  682. {
  683. uint8_t dummy = 0;
  684. scsiHostRead(&dummy, 1);
  685. }
  686. else if (phase == MESSAGE_OUT)
  687. {
  688. uint8_t identify_msg = 0x80;
  689. scsiHostWrite(&identify_msg, 1);
  690. }
  691. else if (phase == STATUS)
  692. {
  693. uint8_t tmp = 0;
  694. scsiHostRead(&tmp, 1);
  695. status = tmp;
  696. debuglog("------ STATUS: ", tmp);
  697. }
  698. }
  699. scsiHostPhyRelease();
  700. return status == 0 && g_initiator_transfer.all_ok;
  701. }
  702. #endif