BlueSCSI.cpp 36 KB

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