ZuluSCSI.cpp 24 KB

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