ZuluSCSI.cpp 20 KB

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