ZuluSCSI.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. /*
  2. * ZuluSCSI
  3. * Copyright (c) 2022 Rabbit Hole Computing
  4. *
  5. * This project is based on BlueSCSI:
  6. *
  7. * BlueSCSI
  8. * Copyright (c) 2021 Eric Helgeson, Androda
  9. *
  10. * This file is free software: you may copy, redistribute and/or modify it
  11. * under the terms of the GNU General Public License as published by the
  12. * Free Software Foundation, either version 2 of the License, or (at your
  13. * option) any later version.
  14. *
  15. * This file is distributed in the hope that it will be useful, but
  16. * WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  18. * General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with this program. If not, see https://github.com/erichelgeson/bluescsi.
  22. *
  23. * This file incorporates work covered by the following copyright and
  24. * permission notice:
  25. *
  26. * Copyright (c) 2019 komatsu
  27. *
  28. * Permission to use, copy, modify, and/or distribute this software
  29. * for any purpose with or without fee is hereby granted, provided
  30. * that the above copyright notice and this permission notice appear
  31. * in all copies.
  32. *
  33. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
  34. * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
  35. * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
  36. * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
  37. * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  38. * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  39. * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  40. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  41. */
  42. #include <SdFat.h>
  43. #include <minIni.h>
  44. #include <minIni_cache.h>
  45. #include <string.h>
  46. #include <strings.h>
  47. #include <ctype.h>
  48. #include "ZuluSCSI_config.h"
  49. #include "ZuluSCSI_platform.h"
  50. #include "ZuluSCSI_log.h"
  51. #include "ZuluSCSI_log_trace.h"
  52. #include "ZuluSCSI_presets.h"
  53. #include "ZuluSCSI_disk.h"
  54. #include "ZuluSCSI_initiator.h"
  55. #include "ROMDrive.h"
  56. SdFs SD;
  57. FsFile g_logfile;
  58. static bool g_romdrive_active;
  59. static bool g_sdcard_present;
  60. /************************************/
  61. /* Status reporting by blinking led */
  62. /************************************/
  63. #define BLINK_STATUS_OK 1
  64. #define BLINK_ERROR_NO_IMAGES 3
  65. #define BLINK_ERROR_NO_SD_CARD 5
  66. void blinkStatus(int count)
  67. {
  68. for (int i = 0; i < count; i++)
  69. {
  70. LED_ON();
  71. delay(250);
  72. LED_OFF();
  73. delay(250);
  74. }
  75. }
  76. extern "C" void s2s_ledOn()
  77. {
  78. LED_ON();
  79. }
  80. extern "C" void s2s_ledOff()
  81. {
  82. LED_OFF();
  83. }
  84. /**************/
  85. /* Log saving */
  86. /**************/
  87. void save_logfile(bool always = false)
  88. {
  89. static uint32_t prev_log_pos = 0;
  90. static uint32_t prev_log_len = 0;
  91. static uint32_t prev_log_save = 0;
  92. uint32_t loglen = log_get_buffer_len();
  93. if (loglen != prev_log_len && g_sdcard_present)
  94. {
  95. // When debug is off, save log at most every LOG_SAVE_INTERVAL_MS
  96. // When debug is on, save after every SCSI command.
  97. if (always || g_log_debug || (LOG_SAVE_INTERVAL_MS > 0 && (uint32_t)(millis() - prev_log_save) > LOG_SAVE_INTERVAL_MS))
  98. {
  99. g_logfile.write(log_get_buffer(&prev_log_pos));
  100. g_logfile.flush();
  101. prev_log_len = loglen;
  102. prev_log_save = millis();
  103. }
  104. }
  105. }
  106. void init_logfile()
  107. {
  108. static bool first_open_after_boot = true;
  109. bool truncate = first_open_after_boot;
  110. int flags = O_WRONLY | O_CREAT | (truncate ? O_TRUNC : O_APPEND);
  111. g_logfile = SD.open(LOGFILE, flags);
  112. if (!g_logfile.isOpen())
  113. {
  114. logmsg("Failed to open log file: ", SD.sdErrorCode());
  115. }
  116. save_logfile(true);
  117. first_open_after_boot = false;
  118. }
  119. void print_sd_info()
  120. {
  121. uint64_t size = (uint64_t)SD.vol()->clusterCount() * SD.vol()->bytesPerCluster();
  122. logmsg("SD card detected, FAT", (int)SD.vol()->fatType(),
  123. " volume size: ", (int)(size / 1024 / 1024), " MB");
  124. cid_t sd_cid;
  125. if(SD.card()->readCID(&sd_cid))
  126. {
  127. logmsg("SD MID: ", (uint8_t)sd_cid.mid, ", OID: ", (uint8_t)sd_cid.oid[0], " ", (uint8_t)sd_cid.oid[1]);
  128. char sdname[6] = {sd_cid.pnm[0], sd_cid.pnm[1], sd_cid.pnm[2], sd_cid.pnm[3], sd_cid.pnm[4], 0};
  129. logmsg("SD Name: ", sdname);
  130. logmsg("SD Date: ", (int)sd_cid.mdtMonth(), "/", sd_cid.mdtYear());
  131. logmsg("SD Serial: ", sd_cid.psn());
  132. }
  133. }
  134. /*********************************/
  135. /* Harddisk image file handling */
  136. /*********************************/
  137. // When a file is called e.g. "Create_1024M_HD40.txt",
  138. // create image file with specified size.
  139. // Returns true if image file creation succeeded.
  140. //
  141. // Parsing rules:
  142. // - Filename must start with "Create", case-insensitive
  143. // - Separator can be either underscore, dash or space
  144. // - Size must start with a number. Unit of k, kb, m, mb, g, gb is supported,
  145. // case-insensitive, with 1024 as the base. If no unit, assume MB.
  146. // - If target filename does not have extension (just .txt), use ".bin"
  147. bool createImage(const char *cmd_filename, char imgname[MAX_FILE_PATH + 1])
  148. {
  149. if (strncasecmp(cmd_filename, CREATEFILE, strlen(CREATEFILE)) != 0)
  150. {
  151. return false;
  152. }
  153. const char *p = cmd_filename + strlen(CREATEFILE);
  154. // Skip separator if any
  155. while (isspace(*p) || *p == '-' || *p == '_')
  156. {
  157. p++;
  158. }
  159. char *unit = nullptr;
  160. uint64_t size = strtoul(p, &unit, 10);
  161. if (size <= 0 || unit <= p)
  162. {
  163. logmsg("---- Could not parse size in filename '", cmd_filename, "'");
  164. return false;
  165. }
  166. // Parse k/M/G unit
  167. char unitchar = tolower(*unit);
  168. if (unitchar == 'k')
  169. {
  170. size *= 1024;
  171. p = unit + 1;
  172. }
  173. else if (unitchar == 'm')
  174. {
  175. size *= 1024 * 1024;
  176. p = unit + 1;
  177. }
  178. else if (unitchar == 'g')
  179. {
  180. size *= 1024 * 1024 * 1024;
  181. p = unit + 1;
  182. }
  183. else
  184. {
  185. size *= 1024 * 1024;
  186. p = unit;
  187. }
  188. // Skip i and B if part of unit
  189. if (tolower(*p) == 'i') p++;
  190. if (tolower(*p) == 'b') p++;
  191. // Skip separator if any
  192. while (isspace(*p) || *p == '-' || *p == '_')
  193. {
  194. p++;
  195. }
  196. // Copy target filename to new buffer
  197. strncpy(imgname, p, MAX_FILE_PATH);
  198. imgname[MAX_FILE_PATH] = '\0';
  199. int namelen = strlen(imgname);
  200. // Strip .txt extension if any
  201. if (namelen >= 4 && strncasecmp(imgname + namelen - 4, ".txt", 4) == 0)
  202. {
  203. namelen -= 4;
  204. imgname[namelen] = '\0';
  205. }
  206. // Add .bin if no extension
  207. if (!strchr(imgname, '.') && namelen < MAX_FILE_PATH - 4)
  208. {
  209. namelen += 4;
  210. strcat(imgname, ".bin");
  211. }
  212. // Check if file exists
  213. if (namelen <= 5 || SD.exists(imgname))
  214. {
  215. logmsg("---- Image file already exists, skipping '", cmd_filename, "'");
  216. return false;
  217. }
  218. // Create file, try to preallocate contiguous sectors
  219. LED_ON();
  220. FsFile file = SD.open(imgname, O_WRONLY | O_CREAT);
  221. if (!file.preAllocate(size))
  222. {
  223. logmsg("---- Preallocation didn't find contiguous set of clusters, continuing anyway");
  224. }
  225. // Write zeros to fill the file
  226. uint32_t start = millis();
  227. memset(scsiDev.data, 0, sizeof(scsiDev.data));
  228. uint64_t remain = size;
  229. while (remain > 0)
  230. {
  231. if (millis() & 128) { LED_ON(); } else { LED_OFF(); }
  232. platform_reset_watchdog();
  233. size_t to_write = sizeof(scsiDev.data);
  234. if (to_write > remain) to_write = remain;
  235. if (file.write(scsiDev.data, to_write) != to_write)
  236. {
  237. logmsg("---- File writing to '", imgname, "' failed with ", (int)remain, " bytes remaining");
  238. file.close();
  239. LED_OFF();
  240. return false;
  241. }
  242. remain -= to_write;
  243. }
  244. file.close();
  245. uint32_t time = millis() - start;
  246. int kb_per_s = size / time;
  247. logmsg("---- Image creation successful, write speed ", kb_per_s, " kB/s, removing '", cmd_filename, "'");
  248. SD.remove(cmd_filename);
  249. LED_OFF();
  250. return true;
  251. }
  252. // Iterate over the root path in the SD card looking for candidate image files.
  253. bool findHDDImages()
  254. {
  255. char imgdir[MAX_FILE_PATH];
  256. ini_gets("SCSI", "Dir", "/", imgdir, sizeof(imgdir), CONFIGFILE);
  257. int dirindex = 0;
  258. logmsg("Finding HDD images in directory ", imgdir, ":");
  259. SdFile root;
  260. root.open(imgdir);
  261. if (!root.isOpen())
  262. {
  263. logmsg("Could not open directory: ", imgdir);
  264. }
  265. SdFile file;
  266. bool imageReady;
  267. bool foundImage = false;
  268. int usedDefaultId = 0;
  269. while (1)
  270. {
  271. if (!file.openNext(&root, O_READ))
  272. {
  273. // Check for additional directories with ini keys Dir1..Dir9
  274. while (dirindex < 10)
  275. {
  276. dirindex++;
  277. char key[5] = "Dir0";
  278. key[3] += dirindex;
  279. if (ini_gets("SCSI", key, "", imgdir, sizeof(imgdir), CONFIGFILE) != 0)
  280. {
  281. break;
  282. }
  283. }
  284. if (imgdir[0] != '\0')
  285. {
  286. logmsg("Finding HDD images in additional directory Dir", (int)dirindex, " = \"", imgdir, "\":");
  287. root.open(imgdir);
  288. if (!root.isOpen())
  289. {
  290. logmsg("-- Could not open directory: ", imgdir);
  291. }
  292. continue;
  293. }
  294. else
  295. {
  296. break;
  297. }
  298. }
  299. char name[MAX_FILE_PATH+1];
  300. if(!file.isDir()) {
  301. file.getName(name, MAX_FILE_PATH+1);
  302. file.close();
  303. // Special filename for clearing any previously programmed ROM drive
  304. if(strcasecmp(name, "CLEAR_ROM") == 0)
  305. {
  306. logmsg("-- Special filename: '", name, "'");
  307. romDriveClear();
  308. continue;
  309. }
  310. // Special filename for creating new empty image files
  311. if (strncasecmp(name, CREATEFILE, strlen(CREATEFILE)) == 0)
  312. {
  313. logmsg("-- Special filename: '", name, "'");
  314. char imgname[MAX_FILE_PATH+1];
  315. if (createImage(name, imgname))
  316. {
  317. // Created new image file, use its name instead of the name of the command file
  318. strncpy(name, imgname, MAX_FILE_PATH);
  319. name[MAX_FILE_PATH] = '\0';
  320. }
  321. }
  322. bool is_hd = (tolower(name[0]) == 'h' && tolower(name[1]) == 'd');
  323. bool is_cd = (tolower(name[0]) == 'c' && tolower(name[1]) == 'd');
  324. bool is_fd = (tolower(name[0]) == 'f' && tolower(name[1]) == 'd');
  325. bool is_mo = (tolower(name[0]) == 'm' && tolower(name[1]) == 'o');
  326. bool is_re = (tolower(name[0]) == 'r' && tolower(name[1]) == 'e');
  327. bool is_tp = (tolower(name[0]) == 't' && tolower(name[1]) == 'p');
  328. if (is_hd || is_cd || is_fd || is_mo || is_re || is_tp)
  329. {
  330. // Check if the image should be loaded to microcontroller flash ROM drive
  331. bool is_romdrive = false;
  332. const char *extension = strrchr(name, '.');
  333. if (extension && strcasecmp(extension, ".rom") == 0)
  334. {
  335. is_romdrive = true;
  336. }
  337. // skip file if the name indicates it is not a valid image container
  338. if (!is_romdrive && !scsiDiskFilenameValid(name)) continue;
  339. // Defaults for Hard Disks
  340. int id = 1; // 0 and 3 are common in Macs for physical HD and CD, so avoid them.
  341. int lun = 0;
  342. int blk = 512;
  343. if (is_cd)
  344. {
  345. // Use 2048 as the default sector size for CD-ROMs
  346. blk = 2048;
  347. }
  348. // Parse SCSI device ID
  349. int file_name_length = strlen(name);
  350. if(file_name_length > 2) { // HD[N]
  351. int tmp_id = name[HDIMG_ID_POS] - '0';
  352. if(tmp_id > -1 && tmp_id < 8)
  353. {
  354. id = tmp_id; // If valid id, set it, else use default
  355. }
  356. else
  357. {
  358. id = usedDefaultId++;
  359. }
  360. }
  361. // Parse SCSI LUN number
  362. if(file_name_length > 3) { // HD0[N]
  363. int tmp_lun = name[HDIMG_LUN_POS] - '0';
  364. if(tmp_lun > -1 && tmp_lun < NUM_SCSILUN) {
  365. lun = tmp_lun; // If valid id, set it, else use default
  366. }
  367. }
  368. // Parse block size (HD00_NNNN)
  369. const char *blksize = strchr(name, '_');
  370. if (blksize)
  371. {
  372. int blktmp = strtoul(blksize + 1, NULL, 10);
  373. if (blktmp == 256 || blktmp == 512 || blktmp == 1024 ||
  374. blktmp == 2048 || blktmp == 4096 || blktmp == 8192)
  375. {
  376. blk = blktmp;
  377. }
  378. }
  379. // Add the directory name to get the full file path
  380. char fullname[MAX_FILE_PATH * 2 + 2] = {0};
  381. strncpy(fullname, imgdir, MAX_FILE_PATH);
  382. if (fullname[strlen(fullname) - 1] != '/') strcat(fullname, "/");
  383. strcat(fullname, name);
  384. // Check whether this SCSI ID has been configured yet
  385. if (s2s_getConfigById(id))
  386. {
  387. logmsg("-- Ignoring ", fullname, ", SCSI ID ", id, " is already in use!");
  388. continue;
  389. }
  390. // Type mapping based on filename.
  391. // If type is FIXED, the type can still be overridden in .ini file.
  392. S2S_CFG_TYPE type = S2S_CFG_FIXED;
  393. if (is_cd) type = S2S_CFG_OPTICAL;
  394. if (is_fd) type = S2S_CFG_FLOPPY_14MB;
  395. if (is_mo) type = S2S_CFG_MO;
  396. if (is_re) type = S2S_CFG_REMOVEABLE;
  397. if (is_tp) type = S2S_CFG_SEQUENTIAL;
  398. // Open the image file
  399. if (id < NUM_SCSIID && is_romdrive)
  400. {
  401. logmsg("-- Loading ROM drive from ", fullname, " for id:", id);
  402. imageReady = scsiDiskProgramRomDrive(fullname, id, blk, type);
  403. if (imageReady)
  404. {
  405. foundImage = true;
  406. }
  407. }
  408. else if(id < NUM_SCSIID && lun < NUM_SCSILUN) {
  409. logmsg("-- Opening ", fullname, " for id:", id, " lun:", lun);
  410. imageReady = scsiDiskOpenHDDImage(id, fullname, id, lun, blk, type);
  411. if(imageReady)
  412. {
  413. foundImage = true;
  414. }
  415. else
  416. {
  417. logmsg("---- Failed to load image");
  418. }
  419. } else {
  420. logmsg("-- Invalid lun or id for image ", fullname);
  421. }
  422. }
  423. }
  424. }
  425. if(usedDefaultId > 0) {
  426. logmsg("Some images did not specify a SCSI ID. Last file will be used at ID ", usedDefaultId);
  427. }
  428. root.close();
  429. g_romdrive_active = scsiDiskActivateRomDrive();
  430. // Print SCSI drive map
  431. for (int i = 0; i < NUM_SCSIID; i++)
  432. {
  433. const S2S_TargetCfg* cfg = s2s_getConfigByIndex(i);
  434. if (cfg && (cfg->scsiId & S2S_CFG_TARGET_ENABLED))
  435. {
  436. int capacity_kB = ((uint64_t)cfg->scsiSectors * cfg->bytesPerSector) / 1024;
  437. logmsg("SCSI ID:", (int)(cfg->scsiId & 7),
  438. " BlockSize:", (int)cfg->bytesPerSector,
  439. " Type:", (int)cfg->deviceType,
  440. " Quirks:", (int)cfg->quirks,
  441. " ImageSize:", capacity_kB, "kB");
  442. }
  443. }
  444. return foundImage;
  445. }
  446. /************************/
  447. /* Config file loading */
  448. /************************/
  449. void readSCSIDeviceConfig()
  450. {
  451. s2s_configInit(&scsiDev.boardCfg);
  452. for (int i = 0; i < NUM_SCSIID; i++)
  453. {
  454. scsiDiskLoadConfig(i);
  455. }
  456. }
  457. /*********************************/
  458. /* Main SCSI handling loop */
  459. /*********************************/
  460. static bool mountSDCard()
  461. {
  462. // Prepare for mounting new SD card by closing all old files.
  463. // When switching between FAT and exFAT cards the pointers
  464. // are invalidated and accessing old files results in crash.
  465. invalidate_ini_cache();
  466. g_logfile.close();
  467. scsiDiskCloseSDCardImages();
  468. // Check for the common case, FAT filesystem as first partition
  469. if (SD.begin(SD_CONFIG))
  470. {
  471. reload_ini_cache(CONFIGFILE);
  472. return true;
  473. }
  474. // Do we have any kind of card?
  475. if (!SD.card() || SD.sdErrorCode() != 0)
  476. return false;
  477. // Try to mount the whole card as FAT (without partition table)
  478. if (static_cast<FsVolume*>(&SD)->begin(SD.card(), true, 0))
  479. return true;
  480. // Failed to mount FAT filesystem, but card can still be accessed as raw image
  481. return true;
  482. }
  483. static void reinitSCSI()
  484. {
  485. if (ini_getbool("SCSI", "Debug", 0, CONFIGFILE))
  486. {
  487. g_log_debug = true;
  488. }
  489. #ifdef PLATFORM_HAS_INITIATOR_MODE
  490. if (platform_is_initiator_mode_enabled())
  491. {
  492. // Initialize scsiDev to zero values even though it is not used
  493. scsiInit();
  494. // Initializer initiator mode state machine
  495. scsiInitiatorInit();
  496. blinkStatus(BLINK_STATUS_OK);
  497. return;
  498. }
  499. #endif
  500. scsiDiskResetImages();
  501. readSCSIDeviceConfig();
  502. findHDDImages();
  503. // Error if there are 0 image files
  504. if (scsiDiskCheckAnyImagesConfigured())
  505. {
  506. // Ok, there is an image, turn LED on for the time it takes to perform init
  507. LED_ON();
  508. delay(100);
  509. }
  510. else
  511. {
  512. #if RAW_FALLBACK_ENABLE
  513. logmsg("No images found, enabling RAW fallback partition");
  514. scsiDiskOpenHDDImage(RAW_FALLBACK_SCSI_ID, "RAW:0:0xFFFFFFFF", RAW_FALLBACK_SCSI_ID, 0,
  515. RAW_FALLBACK_BLOCKSIZE);
  516. #else
  517. logmsg("No valid image files found!");
  518. #endif
  519. blinkStatus(BLINK_ERROR_NO_IMAGES);
  520. }
  521. scsiPhyReset();
  522. scsiDiskInit();
  523. scsiInit();
  524. }
  525. extern "C" void zuluscsi_setup(void)
  526. {
  527. platform_init();
  528. platform_late_init();
  529. g_sdcard_present = mountSDCard();
  530. if(!g_sdcard_present)
  531. {
  532. logmsg("SD card init failed, sdErrorCode: ", (int)SD.sdErrorCode(),
  533. " sdErrorData: ", (int)SD.sdErrorData());
  534. if (romDriveCheckPresent())
  535. {
  536. reinitSCSI();
  537. if (g_romdrive_active)
  538. {
  539. logmsg("Enabled ROM drive without SD card");
  540. return;
  541. }
  542. }
  543. do
  544. {
  545. blinkStatus(BLINK_ERROR_NO_SD_CARD);
  546. delay(1000);
  547. platform_reset_watchdog();
  548. g_sdcard_present = mountSDCard();
  549. } while (!g_sdcard_present);
  550. logmsg("SD card init succeeded after retry");
  551. }
  552. if (g_sdcard_present)
  553. {
  554. if (SD.clusterCount() == 0)
  555. {
  556. logmsg("SD card without filesystem!");
  557. }
  558. print_sd_info();
  559. char presetName[32];
  560. ini_gets("SCSI", "System", "", presetName, sizeof(presetName), CONFIGFILE);
  561. preset_config_t defaults = getSystemPreset(presetName);
  562. int boot_delay_ms = ini_getl("SCSI", "InitPreDelay", defaults.initPreDelay, CONFIGFILE);
  563. if (boot_delay_ms > 0)
  564. {
  565. logmsg("Pre SCSI init boot delay in millis: ", boot_delay_ms);
  566. delay(boot_delay_ms);
  567. }
  568. reinitSCSI();
  569. boot_delay_ms = ini_getl("SCSI", "InitPostDelay", 0, CONFIGFILE);
  570. if (boot_delay_ms > 0)
  571. {
  572. logmsg("Post SCSI init boot delay in millis: ", boot_delay_ms);
  573. delay(boot_delay_ms);
  574. }
  575. }
  576. logmsg("Initialization complete!");
  577. if (g_sdcard_present)
  578. {
  579. init_logfile();
  580. if (ini_getbool("SCSI", "DisableStatusLED", false, CONFIGFILE))
  581. {
  582. platform_disable_led();
  583. }
  584. }
  585. // Counterpart for the LED_ON in reinitSCSI().
  586. LED_OFF();
  587. }
  588. extern "C" void zuluscsi_main_loop(void)
  589. {
  590. static uint32_t sd_card_check_time = 0;
  591. static uint32_t last_request_time = 0;
  592. platform_reset_watchdog();
  593. platform_poll();
  594. diskEjectButtonUpdate(true);
  595. #ifdef PLATFORM_HAS_INITIATOR_MODE
  596. if (platform_is_initiator_mode_enabled())
  597. {
  598. scsiInitiatorMainLoop();
  599. save_logfile();
  600. }
  601. else
  602. #endif
  603. {
  604. scsiPoll();
  605. scsiDiskPoll();
  606. scsiLogPhaseChange(scsiDev.phase);
  607. // Save log periodically during status phase if there are new messages.
  608. // In debug mode, also save every 2 seconds if no SCSI requests come in.
  609. // SD card writing takes a while, during which the code can't handle new
  610. // SCSI requests, so normally we only want to save during a phase where
  611. // the host is waiting for us. But for debugging issues where no requests
  612. // come through or a request hangs, it's useful to force saving of log.
  613. if (scsiDev.phase == STATUS || (g_log_debug && (uint32_t)(millis() - last_request_time) > 2000))
  614. {
  615. save_logfile();
  616. last_request_time = millis();
  617. }
  618. }
  619. if (g_sdcard_present)
  620. {
  621. // Check SD card status for hotplug
  622. if (scsiDev.phase == BUS_FREE &&
  623. (uint32_t)(millis() - sd_card_check_time) > 5000)
  624. {
  625. sd_card_check_time = millis();
  626. uint32_t ocr;
  627. if (!SD.card()->readOCR(&ocr))
  628. {
  629. if (!SD.card()->readOCR(&ocr))
  630. {
  631. g_sdcard_present = false;
  632. logmsg("SD card removed, trying to reinit");
  633. }
  634. }
  635. }
  636. }
  637. if (!g_sdcard_present)
  638. {
  639. // Try to remount SD card
  640. do
  641. {
  642. g_sdcard_present = mountSDCard();
  643. if (g_sdcard_present)
  644. {
  645. logmsg("SD card reinit succeeded");
  646. print_sd_info();
  647. reinitSCSI();
  648. init_logfile();
  649. }
  650. else if (!g_romdrive_active)
  651. {
  652. blinkStatus(BLINK_ERROR_NO_SD_CARD);
  653. delay(1000);
  654. platform_reset_watchdog();
  655. platform_poll();
  656. }
  657. } while (!g_sdcard_present && !g_romdrive_active);
  658. }
  659. else
  660. {
  661. }
  662. }