ZuluSCSI.cpp 21 KB

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