BlueSCSI_initiator.cpp 26 KB

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