BlueSCSI.cpp 37 KB

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