ZuluSCSI.cpp 23 KB

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