ZuluSCSI.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  1. /*
  2. * ZuluSCSI™
  3. * Copyright (c) 2022-2025 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 <zip_parser.h>
  53. #include "ZuluSCSI_config.h"
  54. #include "ZuluSCSI_platform.h"
  55. #include "ZuluSCSI_log.h"
  56. #include "ZuluSCSI_log_trace.h"
  57. #include "ZuluSCSI_settings.h"
  58. #include "ZuluSCSI_disk.h"
  59. #include "ZuluSCSI_initiator.h"
  60. #include "ZuluSCSI_msc_initiator.h"
  61. #include "ZuluSCSI_msc.h"
  62. #include "ZuluSCSI_blink.h"
  63. #include "ROMDrive.h"
  64. SdFs SD;
  65. FsFile g_logfile;
  66. bool g_rawdrive_active;
  67. static bool g_romdrive_active;
  68. bool g_sdcard_present;
  69. #ifndef SD_SPEED_CLASS_WARN_BELOW
  70. #define SD_SPEED_CLASS_WARN_BELOW 10
  71. #endif
  72. /**************/
  73. /* Log saving */
  74. /**************/
  75. void save_logfile(bool always = false)
  76. {
  77. #ifdef ZULUSCSI_HARDWARE_CONFIG
  78. // Disable logging to the SD card when in direct mode
  79. if (g_hw_config.is_active())
  80. return;
  81. #endif
  82. static uint32_t prev_log_pos = 0;
  83. static uint32_t prev_log_len = 0;
  84. static uint32_t prev_log_save = 0;
  85. uint32_t loglen = log_get_buffer_len();
  86. if (loglen != prev_log_len && g_sdcard_present)
  87. {
  88. // When debug is off, save log at most every LOG_SAVE_INTERVAL_MS
  89. // When debug is on, save after every SCSI command.
  90. if (always || g_log_debug || (LOG_SAVE_INTERVAL_MS > 0 && (uint32_t)(millis() - prev_log_save) > LOG_SAVE_INTERVAL_MS))
  91. {
  92. g_logfile.write(log_get_buffer(&prev_log_pos));
  93. g_logfile.flush();
  94. prev_log_len = loglen;
  95. prev_log_save = millis();
  96. }
  97. }
  98. }
  99. void init_logfile()
  100. {
  101. #ifdef ZULUSCSI_HARDWARE_CONFIG
  102. // Disable logging to the SD card when in direct mode
  103. if (g_hw_config.is_active())
  104. return;
  105. #endif
  106. if (g_rawdrive_active)
  107. return;
  108. static bool first_open_after_boot = true;
  109. bool truncate = first_open_after_boot;
  110. int flags = O_WRONLY | O_CREAT | (truncate ? O_TRUNC : O_APPEND);
  111. g_logfile = SD.open(LOGFILE, flags);
  112. if (!g_logfile.isOpen())
  113. {
  114. logmsg("Failed to open log file: ", SD.sdErrorCode());
  115. }
  116. save_logfile(true);
  117. first_open_after_boot = false;
  118. }
  119. void print_sd_info()
  120. {
  121. uint64_t size = (uint64_t)SD.vol()->clusterCount() * SD.vol()->bytesPerCluster();
  122. logmsg("SD card detected, FAT", (int)SD.vol()->fatType(),
  123. " volume size: ", (int)(size / 1024 / 1024), " MB");
  124. cid_t sd_cid;
  125. if(SD.card()->readCID(&sd_cid))
  126. {
  127. logmsg("SD MID: ", (uint8_t)sd_cid.mid, ", OID: ", (uint8_t)sd_cid.oid[0], " ", (uint8_t)sd_cid.oid[1]);
  128. char sdname[6] = {sd_cid.pnm[0], sd_cid.pnm[1], sd_cid.pnm[2], sd_cid.pnm[3], sd_cid.pnm[4], 0};
  129. logmsg("SD Name: ", sdname);
  130. logmsg("SD Date: ", (int)sd_cid.mdtMonth(), "/", sd_cid.mdtYear());
  131. logmsg("SD Serial: ", sd_cid.psn());
  132. }
  133. sds_t sds = {0};
  134. if (SD.card()->readSDS(&sds) && sds.speedClass() < SD_SPEED_CLASS_WARN_BELOW)
  135. {
  136. logmsg("-- WARNING: Your SD Card Speed Class is ", (int)sds.speedClass(), ". Class ", (int) SD_SPEED_CLASS_WARN_BELOW," or better is recommended for best performance.");
  137. }
  138. }
  139. /*********************************/
  140. /* Harddisk image file handling */
  141. /*********************************/
  142. // When a file is called e.g. "Create_1024M_HD40.txt",
  143. // create image file with specified size.
  144. // Returns true if image file creation succeeded.
  145. //
  146. // Parsing rules:
  147. // - Filename must start with "Create", case-insensitive
  148. // - Separator can be either underscore, dash or space
  149. // - Size must start with a number. Unit of k, kb, m, mb, g, gb is supported,
  150. // case-insensitive, with 1024 as the base. If no unit, assume MB.
  151. // - If target filename does not have extension (just .txt), use ".bin"
  152. bool createImage(const char *cmd_filename, char imgname[MAX_FILE_PATH + 1])
  153. {
  154. if (strncasecmp(cmd_filename, CREATEFILE, strlen(CREATEFILE)) != 0)
  155. {
  156. return false;
  157. }
  158. const char *p = cmd_filename + strlen(CREATEFILE);
  159. // Skip separator if any
  160. while (isspace(*p) || *p == '-' || *p == '_')
  161. {
  162. p++;
  163. }
  164. char *unit = nullptr;
  165. uint64_t size = strtoul(p, &unit, 10);
  166. if (size <= 0 || unit <= p)
  167. {
  168. logmsg("---- Could not parse size in filename '", cmd_filename, "'");
  169. return false;
  170. }
  171. // Parse k/M/G unit
  172. char unitchar = tolower(*unit);
  173. if (unitchar == 'k')
  174. {
  175. size *= 1024;
  176. p = unit + 1;
  177. }
  178. else if (unitchar == 'm')
  179. {
  180. size *= 1024 * 1024;
  181. p = unit + 1;
  182. }
  183. else if (unitchar == 'g')
  184. {
  185. size *= 1024 * 1024 * 1024;
  186. p = unit + 1;
  187. }
  188. else
  189. {
  190. size *= 1024 * 1024;
  191. p = unit;
  192. }
  193. // Skip i and B if part of unit
  194. if (tolower(*p) == 'i') p++;
  195. if (tolower(*p) == 'b') p++;
  196. // Skip separator if any
  197. while (isspace(*p) || *p == '-' || *p == '_')
  198. {
  199. p++;
  200. }
  201. // Copy target filename to new buffer
  202. strncpy(imgname, p, MAX_FILE_PATH);
  203. imgname[MAX_FILE_PATH] = '\0';
  204. int namelen = strlen(imgname);
  205. // Strip .txt extension if any
  206. if (namelen >= 4 && strncasecmp(imgname + namelen - 4, ".txt", 4) == 0)
  207. {
  208. namelen -= 4;
  209. imgname[namelen] = '\0';
  210. }
  211. // Add .bin if no extension
  212. if (!strchr(imgname, '.') && namelen < MAX_FILE_PATH - 4)
  213. {
  214. namelen += 4;
  215. strcat(imgname, ".bin");
  216. }
  217. // Check if file exists
  218. if (namelen <= 5 || SD.exists(imgname))
  219. {
  220. logmsg("---- Image file already exists, skipping '", cmd_filename, "'");
  221. return false;
  222. }
  223. // Create file, try to preallocate contiguous sectors
  224. LED_ON();
  225. FsFile file = SD.open(imgname, O_WRONLY | O_CREAT);
  226. if (!file.preAllocate(size))
  227. {
  228. logmsg("---- Preallocation didn't find contiguous set of clusters, continuing anyway");
  229. }
  230. // Write zeros to fill the file
  231. uint32_t start = millis();
  232. memset(scsiDev.data, 0, sizeof(scsiDev.data));
  233. uint64_t remain = size;
  234. while (remain > 0)
  235. {
  236. if (millis() & 128) { LED_ON(); } else { LED_OFF(); }
  237. platform_reset_watchdog();
  238. size_t to_write = sizeof(scsiDev.data);
  239. if (to_write > remain) to_write = remain;
  240. if (file.write(scsiDev.data, to_write) != to_write)
  241. {
  242. logmsg("---- File writing to '", imgname, "' failed with ", (int)remain, " bytes remaining");
  243. file.close();
  244. LED_OFF();
  245. return false;
  246. }
  247. remain -= to_write;
  248. }
  249. file.close();
  250. uint32_t time = millis() - start;
  251. int kb_per_s = size / time;
  252. logmsg("---- Image creation successful, write speed ", kb_per_s, " kB/s, removing '", cmd_filename, "'");
  253. SD.remove(cmd_filename);
  254. LED_OFF();
  255. return true;
  256. }
  257. static bool typeIsRemovable(S2S_CFG_TYPE type)
  258. {
  259. switch (type)
  260. {
  261. case S2S_CFG_OPTICAL:
  262. case S2S_CFG_MO:
  263. case S2S_CFG_FLOPPY_14MB:
  264. case S2S_CFG_ZIP100:
  265. case S2S_CFG_REMOVABLE:
  266. case S2S_CFG_SEQUENTIAL:
  267. return true;
  268. default:
  269. return false;
  270. }
  271. }
  272. // Iterate over the root path in the SD card looking for candidate image files.
  273. bool findHDDImages()
  274. {
  275. #ifdef ZULUSCSI_HARDWARE_CONFIG
  276. if (g_hw_config.is_active())
  277. {
  278. return false;
  279. }
  280. #endif // ZULUSCSI_HARDWARE_CONFIG
  281. char imgdir[MAX_FILE_PATH];
  282. ini_gets("SCSI", "Dir", "/", imgdir, sizeof(imgdir), CONFIGFILE);
  283. int dirindex = 0;
  284. logmsg("Finding images in directory ", imgdir, ":");
  285. FsFile root;
  286. root.open(imgdir);
  287. if (!root.isOpen())
  288. {
  289. logmsg("Could not open directory: ", imgdir);
  290. }
  291. FsFile file;
  292. bool imageReady;
  293. bool foundImage = false;
  294. int usedDefaultId = 0;
  295. uint8_t removable_count = 0;
  296. uint8_t eject_btn_set = 0;
  297. uint8_t last_removable_device = 255;
  298. while (1)
  299. {
  300. if (!file.openNext(&root, O_READ))
  301. {
  302. // Check for additional directories with ini keys Dir1..Dir9
  303. while (dirindex < 10)
  304. {
  305. dirindex++;
  306. char key[5] = "Dir0";
  307. key[3] += dirindex;
  308. if (ini_gets("SCSI", key, "", imgdir, sizeof(imgdir), CONFIGFILE) != 0)
  309. {
  310. break;
  311. }
  312. }
  313. if (imgdir[0] != '\0')
  314. {
  315. logmsg("Finding images in additional directory Dir", (int)dirindex, " = \"", imgdir, "\":");
  316. root.open(imgdir);
  317. if (!root.isOpen())
  318. {
  319. logmsg("-- Could not open directory: ", imgdir);
  320. }
  321. continue;
  322. }
  323. else
  324. {
  325. break;
  326. }
  327. }
  328. char name[MAX_FILE_PATH+1];
  329. if(!file.isDir() || scsiDiskFolderContainsCueSheet(&file) || scsiDiskFolderIsTapeFolder(&file)) {
  330. file.getName(name, MAX_FILE_PATH+1);
  331. file.close();
  332. // Special filename for clearing any previously programmed ROM drive
  333. if(strcasecmp(name, "CLEAR_ROM") == 0)
  334. {
  335. logmsg("-- Special filename: '", name, "'");
  336. romDriveClear();
  337. continue;
  338. }
  339. // Special filename for creating new empty image files
  340. if (strncasecmp(name, CREATEFILE, strlen(CREATEFILE)) == 0)
  341. {
  342. logmsg("-- Special filename: '", name, "'");
  343. char imgname[MAX_FILE_PATH+1];
  344. if (createImage(name, imgname))
  345. {
  346. // Created new image file, use its name instead of the name of the command file
  347. strncpy(name, imgname, MAX_FILE_PATH);
  348. name[MAX_FILE_PATH] = '\0';
  349. }
  350. }
  351. bool use_prefix = false;
  352. bool is_hd = (tolower(name[0]) == 'h' && tolower(name[1]) == 'd');
  353. bool is_cd = (tolower(name[0]) == 'c' && tolower(name[1]) == 'd');
  354. bool is_fd = (tolower(name[0]) == 'f' && tolower(name[1]) == 'd');
  355. bool is_mo = (tolower(name[0]) == 'm' && tolower(name[1]) == 'o');
  356. bool is_re = (tolower(name[0]) == 'r' && tolower(name[1]) == 'e');
  357. bool is_tp = (tolower(name[0]) == 't' && tolower(name[1]) == 'p');
  358. bool is_zp = (tolower(name[0]) == 'z' && tolower(name[1]) == 'p');
  359. #ifdef ZULUSCSI_NETWORK
  360. bool is_ne = (tolower(name[0]) == 'n' && tolower(name[1]) == 'e');
  361. #endif // ZULUSCSI_NETWORK
  362. if (is_hd || is_cd || is_fd || is_mo || is_re || is_tp || is_zp
  363. #ifdef ZULUSCSI_NETWORK
  364. || is_ne
  365. #endif // ZULUSCSI_NETWORK
  366. )
  367. {
  368. // Check if the image should be loaded to microcontroller flash ROM drive
  369. bool is_romdrive = false;
  370. const char *extension = strrchr(name, '.');
  371. if (extension && strcasecmp(extension, ".rom") == 0)
  372. {
  373. is_romdrive = true;
  374. }
  375. // skip file if the name indicates it is not a valid image container
  376. if (!is_romdrive && !scsiDiskFilenameValid(name)) continue;
  377. // Defaults for Hard Disks
  378. int id = 1; // 0 and 3 are common in Macs for physical HD and CD, so avoid them.
  379. int lun = 0;
  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. use_prefix = true;
  388. }
  389. else
  390. {
  391. id = usedDefaultId++;
  392. }
  393. }
  394. // Parse SCSI LUN number
  395. if(file_name_length > 3) { // HD0[N]
  396. int tmp_lun = name[HDIMG_LUN_POS] - '0';
  397. if(tmp_lun > -1 && tmp_lun < NUM_SCSILUN) {
  398. lun = tmp_lun; // If valid id, set it, else use default
  399. }
  400. }
  401. // Add the directory name to get the full file path
  402. char fullname[MAX_FILE_PATH * 2 + 2] = {0};
  403. strncpy(fullname, imgdir, MAX_FILE_PATH);
  404. if (fullname[strlen(fullname) - 1] != '/') strcat(fullname, "/");
  405. strcat(fullname, name);
  406. // Check whether this SCSI ID has been configured yet
  407. if (s2s_getConfigById(id))
  408. {
  409. logmsg("-- Ignoring ", fullname, ", SCSI ID ", id, " is already in use!");
  410. continue;
  411. }
  412. // set the default block size now that we know the device type
  413. if (g_scsi_settings.getDevice(id)->blockSize == 0)
  414. {
  415. g_scsi_settings.getDevice(id)->blockSize = is_cd ? DEFAULT_BLOCKSIZE_OPTICAL : DEFAULT_BLOCKSIZE;
  416. }
  417. int blk = getBlockSize(name, id);
  418. #ifdef ZULUSCSI_NETWORK
  419. if (is_ne && !platform_network_supported())
  420. {
  421. logmsg("-- Ignoring ", fullname, ", networking is not supported on this hardware");
  422. continue;
  423. }
  424. #endif // ZULUSCSI_NETWORK
  425. // Type mapping based on filename.
  426. // If type is FIXED, the type can still be overridden in .ini file.
  427. S2S_CFG_TYPE type = S2S_CFG_FIXED;
  428. if (is_cd) type = S2S_CFG_OPTICAL;
  429. if (is_fd) type = S2S_CFG_FLOPPY_14MB;
  430. if (is_mo) type = S2S_CFG_MO;
  431. #ifdef ZULUSCSI_NETWORK
  432. if (is_ne) type = S2S_CFG_NETWORK;
  433. #endif // ZULUSCSI_NETWORK
  434. if (is_re) type = S2S_CFG_REMOVABLE;
  435. if (is_tp) type = S2S_CFG_SEQUENTIAL;
  436. if (is_zp) type = S2S_CFG_ZIP100;
  437. g_scsi_settings.initDevice(id & 7, type);
  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. if (g_scsi_settings.getDevicePreset(id) != DEV_PRESET_NONE)
  451. {
  452. logmsg("---- Using device preset: ", g_scsi_settings.getDevicePresetName(id));
  453. }
  454. imageReady = scsiDiskOpenHDDImage(id, fullname, lun, blk, type, use_prefix);
  455. if(imageReady)
  456. {
  457. foundImage = true;
  458. }
  459. else
  460. {
  461. logmsg("---- Failed to load image");
  462. }
  463. } else {
  464. logmsg("-- Invalid lun or id for image ", fullname);
  465. }
  466. }
  467. }
  468. }
  469. if(usedDefaultId > 0) {
  470. logmsg("Some images did not specify a SCSI ID. Last file will be used at ID ", usedDefaultId);
  471. }
  472. root.close();
  473. g_romdrive_active = scsiDiskActivateRomDrive();
  474. // Print SCSI drive map
  475. for (int i = 0; i < NUM_SCSIID; i++)
  476. {
  477. const S2S_TargetCfg* cfg = s2s_getConfigByIndex(i);
  478. if (cfg && (cfg->scsiId & S2S_CFG_TARGET_ENABLED))
  479. {
  480. int capacity_kB = ((uint64_t)cfg->scsiSectors * cfg->bytesPerSector) / 1024;
  481. if (cfg->deviceType == S2S_CFG_NETWORK)
  482. {
  483. logmsg("SCSI ID: ", (int)(cfg->scsiId & 7),
  484. ", Type: ", (int)cfg->deviceType,
  485. ", Quirks: ", (int)cfg->quirks);
  486. }
  487. else
  488. {
  489. logmsg("SCSI ID: ", (int)(cfg->scsiId & S2S_CFG_TARGET_ID_BITS),
  490. ", BlockSize: ", (int)cfg->bytesPerSector,
  491. ", Type: ", (int)cfg->deviceType,
  492. ", Quirks: ", (int)cfg->quirks,
  493. ", Size: ", capacity_kB, "kB",
  494. typeIsRemovable((S2S_CFG_TYPE)cfg->deviceType) ? ", Removable" : ""
  495. );
  496. }
  497. }
  498. }
  499. // count the removable drives and drive with eject enabled
  500. for (uint8_t id = 0; id < S2S_MAX_TARGETS; id++)
  501. {
  502. const S2S_TargetCfg* cfg = s2s_getConfigByIndex(id);
  503. if (cfg && (cfg->scsiId & S2S_CFG_TARGET_ENABLED ))
  504. {
  505. if (typeIsRemovable((S2S_CFG_TYPE)cfg->deviceType))
  506. {
  507. removable_count++;
  508. last_removable_device = id;
  509. if ( getEjectButton(id) !=0 )
  510. {
  511. eject_btn_set++;
  512. }
  513. }
  514. }
  515. }
  516. if (removable_count == 1)
  517. {
  518. // If there is a removable device
  519. if (eject_btn_set == 1)
  520. logmsg("Eject set to device with ID: ", last_removable_device);
  521. else if (eject_btn_set == 0)
  522. {
  523. logmsg("Found 1 removable device, to set an eject button see EjectButton in the '", CONFIGFILE,"', or the http://zuluscsi.com/manual");
  524. }
  525. }
  526. else if (removable_count > 1)
  527. {
  528. if (removable_count >= eject_btn_set && eject_btn_set > 0)
  529. {
  530. if (eject_btn_set == removable_count)
  531. logmsg("Eject set on all removable devices:");
  532. else
  533. logmsg("Eject set on the following SCSI IDs:");
  534. for (uint8_t id = 0; id < S2S_MAX_TARGETS; id++)
  535. {
  536. if( getEjectButton(id) != 0)
  537. {
  538. logmsg("-- SCSI ID: ", (int)id, " type: ", (int) s2s_getConfigById(id)->deviceType, " button mask: ", getEjectButton(id));
  539. }
  540. }
  541. }
  542. else
  543. {
  544. logmsg("Multiple removable devices, to set an eject button see EjectButton in the '", CONFIGFILE,"', or the http://zuluscsi.com/manual");
  545. }
  546. }
  547. return foundImage;
  548. }
  549. /************************/
  550. /* Config file loading */
  551. /************************/
  552. void readSCSIDeviceConfig()
  553. {
  554. s2s_configInit(&scsiDev.boardCfg);
  555. for (int i = 0; i < NUM_SCSIID; i++)
  556. {
  557. scsiDiskLoadConfig(i);
  558. }
  559. }
  560. /*********************************/
  561. /* Main SCSI handling loop */
  562. /*********************************/
  563. static bool mountSDCard()
  564. {
  565. // Prepare for mounting new SD card by closing all old files.
  566. // When switching between FAT and exFAT cards the pointers
  567. // are invalidated and accessing old files results in crash.
  568. invalidate_ini_cache();
  569. g_logfile.close();
  570. scsiDiskCloseSDCardImages();
  571. // Check for the common case, FAT filesystem as first partition
  572. if (SD.begin(SD_CONFIG))
  573. {
  574. #if defined(HAS_SDIO_CLASS) && HAS_SDIO_CLASS
  575. int speed = ((SdioCard*)SD.card())->kHzSdClk();
  576. if (speed > 0)
  577. {
  578. logmsg("SD card communication speed: ",
  579. (int)((speed + 500) / 1000), " MHz, ",
  580. (int)((speed + 1000) / 2000), " MB/s");
  581. }
  582. #endif
  583. reload_ini_cache(CONFIGFILE);
  584. return true;
  585. }
  586. // Do we have any kind of card?
  587. if (!SD.card() || SD.sdErrorCode() != 0)
  588. return false;
  589. // Try to mount the whole card as FAT (without partition table)
  590. if (static_cast<FsVolume*>(&SD)->begin(SD.card(), true, 0))
  591. return true;
  592. // Failed to mount FAT filesystem, but card can still be accessed as raw image
  593. return true;
  594. }
  595. static void reinitSCSI()
  596. {
  597. #if defined(ZULUSCSI_HARDWARE_CONFIG)
  598. if (!g_hw_config.is_active() && ini_getbool("SCSI", "Debug", 0, CONFIGFILE))
  599. {
  600. g_log_debug = true;
  601. }
  602. #else
  603. if (ini_getbool("SCSI", "Debug", 0, CONFIGFILE))
  604. {
  605. g_log_debug = true;
  606. }
  607. #endif
  608. if (g_log_debug)
  609. {
  610. g_scsi_log_mask = ini_getl("SCSI", "DebugLogMask", 0xFF, CONFIGFILE) & 0xFF;
  611. if (g_scsi_log_mask == 0)
  612. {
  613. dbgmsg("DebugLogMask set to 0x00, this will silence all debug messages when a SCSI ID has been selected");
  614. }
  615. else if (g_scsi_log_mask != 0xFF)
  616. {
  617. dbgmsg("DebugLogMask set to ", (uint8_t) g_scsi_log_mask, " only SCSI ID's matching the bit mask will be logged");
  618. }
  619. g_log_ignore_busy_free = ini_getbool("SCSI", "DebugIgnoreBusyFree", 0, CONFIGFILE);
  620. if (g_log_ignore_busy_free)
  621. {
  622. dbgmsg("DebugIgnoreBusyFree enabled, BUS_FREE/BUS_BUSY messages suppressed");
  623. }
  624. }
  625. #ifdef PLATFORM_HAS_INITIATOR_MODE
  626. if (platform_is_initiator_mode_enabled())
  627. {
  628. // Initialize scsiDev to zero values even though it is not used
  629. scsiInit();
  630. // Initializer initiator mode state machine
  631. scsiInitiatorInit();
  632. blinkStatus(BLINK_STATUS_OK);
  633. return;
  634. }
  635. #endif
  636. scsiDiskResetImages();
  637. #if defined(ZULUSCSI_HARDWARE_CONFIG)
  638. if (g_hw_config.is_active())
  639. {
  640. bool success;
  641. uint8_t scsiId = g_hw_config.scsi_id();
  642. g_scsi_settings.initDevice(scsiId, g_hw_config.device_type());
  643. logmsg("Direct/Raw mode enabled, using hardware switches for configuration");
  644. logmsg("-- SCSI ID set via DIP switch to ", (int) g_hw_config.scsi_id());
  645. char raw_filename[32];
  646. uint32_t start = g_scsi_settings.getDevice(scsiId)->sectorSDBegin;
  647. uint32_t end = g_scsi_settings.getDevice(scsiId)->sectorSDEnd;
  648. if (start == end && end == 0)
  649. {
  650. strcpy(raw_filename, "RAW:0:0xFFFFFFFF");
  651. }
  652. else
  653. {
  654. snprintf(raw_filename, sizeof(raw_filename), "RAW:0x%X:0x%X", start, end);
  655. }
  656. success = scsiDiskOpenHDDImage(scsiId, raw_filename, 0,
  657. g_hw_config.blocksize(), g_hw_config.device_type());
  658. if (success)
  659. {
  660. if (g_scsi_settings.getDevicePreset(scsiId) != DEV_PRESET_NONE)
  661. {
  662. logmsg("---- Using device preset: ", g_scsi_settings.getDevicePresetName(scsiId));
  663. }
  664. }
  665. blinkStatus(BLINK_DIRECT_MODE);
  666. }
  667. else
  668. #endif // ZULUSCSI_HARDWARE_CONFIG
  669. {
  670. readSCSIDeviceConfig();
  671. findHDDImages();
  672. // Error if there are 0 image files
  673. if (!scsiDiskCheckAnyImagesConfigured())
  674. {
  675. #ifdef RAW_FALLBACK_ENABLE
  676. logmsg("No images found, enabling RAW fallback partition");
  677. g_scsi_settings.initDevice(RAW_FALLBACK_SCSI_ID, S2S_CFG_FIXED);
  678. scsiDiskOpenHDDImage(RAW_FALLBACK_SCSI_ID, "RAW:0:0xFFFFFFFF", 0,
  679. RAW_FALLBACK_BLOCKSIZE);
  680. #else
  681. logmsg("No valid image files found!");
  682. #endif // RAW_FALLBACK_ENABLE
  683. blinkStatus(BLINK_ERROR_NO_IMAGES);
  684. }
  685. }
  686. scsiPhyReset();
  687. scsiDiskInit();
  688. scsiInit();
  689. #ifdef ZULUSCSI_NETWORK
  690. if (scsiDiskCheckAnyNetworkDevicesConfigured())
  691. {
  692. platform_network_init(scsiDev.boardCfg.wifiMACAddress);
  693. if (scsiDev.boardCfg.wifiSSID[0] != '\0')
  694. platform_network_wifi_join(scsiDev.boardCfg.wifiSSID, scsiDev.boardCfg.wifiPassword);
  695. }
  696. #endif // ZULUSCSI_NETWORK
  697. }
  698. // Alert user that update bin file not used
  699. static void check_for_unused_update_files()
  700. {
  701. FsFile root = SD.open("/");
  702. FsFile file;
  703. char filename[MAX_FILE_PATH + 1];
  704. bool bin_files_found = false;
  705. while (file.openNext(&root, O_RDONLY))
  706. {
  707. if (!file.isDir())
  708. {
  709. size_t filename_len = file.getName(filename, sizeof(filename));
  710. if (strncasecmp(filename, "zuluscsi", sizeof("zuluscsi" - 1)) == 0 &&
  711. strncasecmp(filename + filename_len - 4, ".bin", 4) == 0)
  712. {
  713. bin_files_found = true;
  714. logmsg("Firmware update file \"", filename, "\" does not contain the board model string \"", FIRMWARE_NAME_PREFIX, "\"");
  715. }
  716. }
  717. }
  718. if (bin_files_found)
  719. {
  720. logmsg("Please use the ", FIRMWARE_PREFIX ,"*.zip firmware bundle, or the proper .bin or .uf2 file to update the firmware.");
  721. logmsg("See http://zuluscsi.com/manual for more information");
  722. }
  723. }
  724. // Update firmware by unzipping the firmware package
  725. static void firmware_update()
  726. {
  727. const char firmware_prefix[] = FIRMWARE_PREFIX;
  728. FsFile root = SD.open("/");
  729. FsFile file;
  730. char name[MAX_FILE_PATH + 1];
  731. while (1)
  732. {
  733. if (!file.openNext(&root, O_RDONLY))
  734. {
  735. file.close();
  736. root.close();
  737. return;
  738. }
  739. if (file.isDir())
  740. continue;
  741. file.getName(name, sizeof(name));
  742. if (strlen(name) + 1 < sizeof(firmware_prefix))
  743. continue;
  744. if ( strncasecmp(firmware_prefix, name, sizeof(firmware_prefix) -1) == 0)
  745. {
  746. break;
  747. }
  748. }
  749. logmsg("Found firmware package ", name);
  750. // example fixed length at the end of the filename
  751. const uint32_t postfix_filename_length = sizeof("_2025-02-21_e4be9ed.bin") - 1;
  752. const uint32_t target_filename_length = sizeof(FIRMWARE_NAME_PREFIX) - 1 + postfix_filename_length;
  753. zipparser::Parser parser = zipparser::Parser(FIRMWARE_NAME_PREFIX, sizeof(FIRMWARE_NAME_PREFIX) - 1, target_filename_length);
  754. uint8_t buf[512];
  755. int32_t parsed_length;
  756. int bytes_read = 0;
  757. while ((bytes_read = file.read(buf, sizeof(buf))) > 0)
  758. {
  759. parsed_length = parser.Parse(buf, bytes_read);
  760. if (parsed_length == sizeof(buf))
  761. continue;
  762. if (parsed_length >= 0)
  763. {
  764. if (!parser.FoundMatch())
  765. {
  766. parser.Reset();
  767. file.seekSet(file.position() - (sizeof(buf) - parsed_length) + parser.GetCompressedSize());
  768. }
  769. else
  770. {
  771. // seek to start of data in matching file
  772. file.seekSet(file.position() - (sizeof(buf) - parsed_length));
  773. break;
  774. }
  775. }
  776. if (parsed_length < 0)
  777. {
  778. logmsg("Filename character length of ", (int)target_filename_length , " with a prefix of ", FIRMWARE_NAME_PREFIX, " not found in ", name);
  779. file.close();
  780. root.close();
  781. return;
  782. }
  783. }
  784. if (parser.FoundMatch())
  785. {
  786. logmsg("Unzipping matching firmware with prefix: ", FIRMWARE_NAME_PREFIX);
  787. FsFile target_firmware;
  788. char firmware_name[64] = {0};
  789. memcpy(firmware_name, FIRMWARE_NAME_PREFIX, sizeof(FIRMWARE_NAME_PREFIX) - 1);
  790. memcpy(firmware_name + sizeof(FIRMWARE_NAME_PREFIX) - 1, ".bin", sizeof(".bin"));
  791. target_firmware.open(&root, firmware_name, O_BINARY | O_WRONLY | O_CREAT | O_TRUNC);
  792. uint32_t position = 0;
  793. while ((bytes_read = file.read(buf, sizeof(buf))) > 0)
  794. {
  795. if (bytes_read > parser.GetCompressedSize() - position)
  796. bytes_read = parser.GetCompressedSize() - position;
  797. target_firmware.write(buf, bytes_read);
  798. position += bytes_read;
  799. if (position >= parser.GetCompressedSize())
  800. {
  801. break;
  802. }
  803. }
  804. // zip file has a central directory at the end of the file,
  805. // so the compressed data should never hit the end of the file
  806. // so bytes read should always be greater than 0 for a valid datastream
  807. if (bytes_read > 0)
  808. {
  809. target_firmware.close();
  810. file.close();
  811. root.remove(name);
  812. root.close();
  813. logmsg("Update extracted from package, rebooting MCU");
  814. platform_reset_mcu();
  815. }
  816. else
  817. {
  818. target_firmware.close();
  819. logmsg("Error reading firmware package file");
  820. root.remove(firmware_name);
  821. }
  822. }
  823. file.close();
  824. root.close();
  825. }
  826. // Checks if SD card is still present
  827. static bool poll_sd_card()
  828. {
  829. #ifdef SD_USE_SDIO
  830. return SD.card()->status() != 0 && SD.card()->errorCode() == 0;
  831. #else
  832. uint32_t ocr;
  833. return SD.card()->readOCR(&ocr);
  834. #endif
  835. }
  836. // Place all the setup code that requires the SD card to be initialized here
  837. // Which is pretty much everything after platform_init and and platform_late_init
  838. static void zuluscsi_setup_sd_card(bool wait_for_card = true)
  839. {
  840. g_sdcard_present = mountSDCard();
  841. if(!g_sdcard_present)
  842. {
  843. if (SD.sdErrorCode() == platform_no_sd_card_on_init_error_code())
  844. {
  845. #ifdef PLATFORM_HAS_INITIATOR_MODE
  846. if (platform_is_initiator_mode_enabled())
  847. {
  848. logmsg("No SD card detected, imaging to SD card not possible");
  849. }
  850. else
  851. #endif
  852. {
  853. logmsg("No SD card detected, please check SD card slot to make sure it is in correctly");
  854. }
  855. }
  856. dbgmsg("SD card init failed, sdErrorCode: ", (int)SD.sdErrorCode(),
  857. " sdErrorData: ", (int)SD.sdErrorData());
  858. if (romDriveCheckPresent())
  859. {
  860. reinitSCSI();
  861. if (g_romdrive_active)
  862. {
  863. logmsg("Enabled ROM drive without SD card");
  864. return;
  865. }
  866. }
  867. do
  868. {
  869. blinkStatus(BLINK_ERROR_NO_SD_CARD);
  870. platform_reset_watchdog();
  871. g_sdcard_present = mountSDCard();
  872. } while (!g_sdcard_present && wait_for_card);
  873. blink_cancel();
  874. LED_OFF();
  875. if (g_sdcard_present)
  876. {
  877. logmsg("SD card init succeeded after retry");
  878. }
  879. else
  880. {
  881. logmsg("Continuing without SD card");
  882. }
  883. }
  884. check_for_unused_update_files();
  885. firmware_update();
  886. if (g_sdcard_present)
  887. {
  888. if (SD.clusterCount() == 0)
  889. {
  890. logmsg("SD card without filesystem!");
  891. }
  892. print_sd_info();
  893. char presetName[32];
  894. ini_gets("SCSI", "System", "", presetName, sizeof(presetName), CONFIGFILE);
  895. scsi_system_settings_t *cfg = g_scsi_settings.initSystem(presetName);
  896. #ifdef RECLOCKING_SUPPORTED
  897. zuluscsi_speed_grade_t speed_grade = (zuluscsi_speed_grade_t) g_scsi_settings.getSystem()->speedGrade;
  898. if (speed_grade != zuluscsi_speed_grade_t::SPEED_GRADE_DEFAULT)
  899. {
  900. logmsg("Speed grade set to ", g_scsi_settings.getSpeedGradeString(), " reclocking system");
  901. if (platform_reclock(speed_grade))
  902. {
  903. logmsg("======== Reinitializing ZuluSCSI after reclock ========");
  904. g_sdcard_present = mountSDCard();
  905. }
  906. }
  907. else
  908. {
  909. #ifndef ENABLE_AUDIO_OUTPUT // if audio is enabled, skip message because reclocking ocurred earlier
  910. logmsg("Speed grade set to Default, skipping reclocking");
  911. #endif
  912. }
  913. #endif
  914. int boot_delay_ms = cfg->initPreDelay;
  915. if (boot_delay_ms > 0)
  916. {
  917. logmsg("Pre SCSI init boot delay in millis: ", boot_delay_ms);
  918. delay(boot_delay_ms);
  919. }
  920. platform_post_sd_card_init();
  921. reinitSCSI();
  922. boot_delay_ms = cfg->initPostDelay;
  923. if (boot_delay_ms > 0)
  924. {
  925. logmsg("Post SCSI init boot delay in millis: ", boot_delay_ms);
  926. delay(boot_delay_ms);
  927. }
  928. }
  929. if (g_sdcard_present)
  930. {
  931. init_logfile();
  932. if (ini_getbool("SCSI", "DisableStatusLED", false, CONFIGFILE))
  933. {
  934. platform_disable_led();
  935. }
  936. }
  937. blinkStatus(BLINK_STATUS_OK);
  938. }
  939. extern "C" void zuluscsi_setup(void)
  940. {
  941. platform_init();
  942. platform_late_init();
  943. bool is_initiator = false;
  944. #ifdef PLATFORM_HAS_INITIATOR_MODE
  945. is_initiator = platform_is_initiator_mode_enabled();
  946. #endif
  947. zuluscsi_setup_sd_card(!is_initiator);
  948. #ifdef PLATFORM_MASS_STORAGE
  949. static bool check_mass_storage = true;
  950. if (((check_mass_storage && g_scsi_settings.getSystem()->enableUSBMassStorage)
  951. || platform_rebooted_into_mass_storage()) && !is_initiator)
  952. {
  953. check_mass_storage = false;
  954. // perform checks to see if a computer is attached and return true if we should enter MSC mode.
  955. if (platform_sense_msc())
  956. {
  957. zuluscsi_msc_loop();
  958. logmsg("Re-processing filenames and zuluscsi.ini config parameters");
  959. zuluscsi_setup_sd_card();
  960. }
  961. }
  962. #endif
  963. logmsg("Clock set to: ", (int) platform_sys_clock_in_hz(), "Hz");
  964. logmsg("Initialization complete!");
  965. }
  966. extern "C" void zuluscsi_main_loop(void)
  967. {
  968. static uint32_t sd_card_check_time = 0;
  969. static uint32_t last_request_time = 0;
  970. bool is_initiator = false;
  971. #ifdef PLATFORM_HAS_INITIATOR_MODE
  972. is_initiator = platform_is_initiator_mode_enabled();
  973. #endif
  974. platform_reset_watchdog();
  975. platform_poll();
  976. diskEjectButtonUpdate(true);
  977. blink_poll();
  978. #ifdef ZULUSCSI_NETWORK
  979. platform_network_poll();
  980. #endif // ZULUSCSI_NETWORK
  981. #ifdef PLATFORM_HAS_INITIATOR_MODE
  982. if (is_initiator)
  983. {
  984. scsiInitiatorMainLoop();
  985. save_logfile();
  986. }
  987. else
  988. #endif
  989. {
  990. scsiPoll();
  991. scsiDiskPoll();
  992. scsiLogPhaseChange(scsiDev.phase);
  993. // Save log periodically during status phase if there are new messages.
  994. // In debug mode, also save every 2 seconds if no SCSI requests come in.
  995. // SD card writing takes a while, during which the code can't handle new
  996. // SCSI requests, so normally we only want to save during a phase where
  997. // the host is waiting for us. But for debugging issues where no requests
  998. // come through or a request hangs, it's useful to force saving of log.
  999. if (scsiDev.phase == STATUS || (g_log_debug && (uint32_t)(millis() - last_request_time) > 2000))
  1000. {
  1001. save_logfile();
  1002. last_request_time = millis();
  1003. }
  1004. }
  1005. if (g_sdcard_present)
  1006. {
  1007. // Check SD card status for hotplug
  1008. if (scsiDev.phase == BUS_FREE &&
  1009. (uint32_t)(millis() - sd_card_check_time) > SDCARD_POLL_INTERVAL)
  1010. {
  1011. sd_card_check_time = millis();
  1012. if (!poll_sd_card())
  1013. {
  1014. if (!poll_sd_card())
  1015. {
  1016. g_sdcard_present = false;
  1017. logmsg("SD card removed, trying to reinit");
  1018. }
  1019. }
  1020. }
  1021. }
  1022. if (!g_sdcard_present && (uint32_t)(millis() - sd_card_check_time) > SDCARD_POLL_INTERVAL
  1023. && !g_msc_initiator)
  1024. {
  1025. sd_card_check_time = millis();
  1026. // Try to remount SD card
  1027. do
  1028. {
  1029. g_sdcard_present = mountSDCard();
  1030. if (g_sdcard_present)
  1031. {
  1032. blink_cancel();
  1033. LED_OFF();
  1034. logmsg("SD card reinit succeeded");
  1035. print_sd_info();
  1036. reinitSCSI();
  1037. init_logfile();
  1038. blinkStatus(BLINK_STATUS_OK);
  1039. }
  1040. else if (!g_romdrive_active)
  1041. {
  1042. blinkStatus(BLINK_ERROR_NO_SD_CARD);
  1043. platform_reset_watchdog();
  1044. platform_poll();
  1045. }
  1046. } while (!g_sdcard_present && !g_romdrive_active && !is_initiator);
  1047. }
  1048. }