BlueSCSI.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319
  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. // Setup GPIO pins for initiator mode
  699. platform_initiator_gpio_setup();
  700. // Initializer initiator mode state machine
  701. scsiInitiatorInit();
  702. blinkStatus(BLINK_STATUS_OK);
  703. return;
  704. }
  705. #endif
  706. scsiDiskResetImages();
  707. #if defined(BLUESCSI_HARDWARE_CONFIG)
  708. if (g_hw_config.is_active())
  709. {
  710. bool success;
  711. uint8_t scsiId = g_hw_config.scsi_id();
  712. g_scsi_settings.initDevice(scsiId, g_hw_config.device_type());
  713. logmsg("Direct/Raw mode enabled, using hardware switches for configuration");
  714. logmsg("-- SCSI ID set via DIP switch to ", (int) g_hw_config.scsi_id());
  715. char raw_filename[32];
  716. uint32_t start = g_scsi_settings.getDevice(scsiId)->sectorSDBegin;
  717. uint32_t end = g_scsi_settings.getDevice(scsiId)->sectorSDEnd;
  718. if (start == end && end == 0)
  719. {
  720. strcpy(raw_filename, "RAW:0:0xFFFFFFFF");
  721. }
  722. else
  723. {
  724. snprintf(raw_filename, sizeof(raw_filename), "RAW:0x%X:0x%X", start, end);
  725. }
  726. success = scsiDiskOpenHDDImage(scsiId, raw_filename, 0,
  727. g_hw_config.blocksize(), g_hw_config.device_type());
  728. if (success)
  729. {
  730. if (g_scsi_settings.getDevicePreset(scsiId) != DEV_PRESET_NONE)
  731. {
  732. logmsg("---- Using device preset: ", g_scsi_settings.getDevicePresetName(scsiId));
  733. }
  734. }
  735. blinkStatus(BLINK_DIRECT_MODE);
  736. }
  737. else
  738. #endif // BLUESCSI_HARDWARE_CONFIG
  739. {
  740. readSCSIDeviceConfig();
  741. findHDDImages();
  742. // Error if there are 0 image files
  743. if (!scsiDiskCheckAnyImagesConfigured())
  744. {
  745. #ifdef RAW_FALLBACK_ENABLE
  746. logmsg("No images found, enabling RAW fallback partition");
  747. g_scsi_settings.initDevice(RAW_FALLBACK_SCSI_ID, S2S_CFG_FIXED);
  748. scsiDiskOpenHDDImage(RAW_FALLBACK_SCSI_ID, "RAW:0:0xFFFFFFFF", 0,
  749. RAW_FALLBACK_BLOCKSIZE);
  750. #else
  751. logmsg("No valid image files found!");
  752. #endif // RAW_FALLBACK_ENABLE
  753. blinkStatus(BLINK_ERROR_NO_IMAGES);
  754. }
  755. }
  756. scsiPhyReset();
  757. scsiDiskInit();
  758. scsiInit();
  759. #ifdef BLUESCSI_NETWORK
  760. if (platform_network_supported()) {
  761. if (scsiDiskCheckAnyNetworkDevicesConfigured())
  762. {
  763. platform_network_init(scsiDev.boardCfg.wifiMACAddress);
  764. if (scsiDev.boardCfg.wifiSSID[0] != '\0')
  765. platform_network_wifi_join(scsiDev.boardCfg.wifiSSID, scsiDev.boardCfg.wifiPassword);
  766. else
  767. logmsg("No Wi-Fi SSID or Password found. Use the BlueSCSI Wi-Fi DA to configure the network.");
  768. }
  769. else
  770. {
  771. platform_network_deinit();
  772. }
  773. }
  774. #endif // BLUESCSI_NETWORK
  775. logmsg("");
  776. }
  777. // Alert user that update bin file not used
  778. static void check_for_unused_update_files()
  779. {
  780. FsFile root = SD.open("/");
  781. FsFile file;
  782. char filename[MAX_FILE_PATH + 1];
  783. bool bin_files_found = false;
  784. while (file.openNext(&root, O_RDONLY))
  785. {
  786. if (!file.isDir())
  787. {
  788. size_t filename_len = file.getName(filename, sizeof(filename));
  789. if (strncasecmp(filename, "bluescsi", sizeof("bluescsi" - 1)) == 0 &&
  790. strncasecmp(filename + filename_len - 4, ".bin", 4) == 0)
  791. {
  792. bin_files_found = true;
  793. logmsg("Firmware update file \"", filename, "\" does not contain the board model string \"", FIRMWARE_NAME_PREFIX, "\"");
  794. }
  795. }
  796. }
  797. if (bin_files_found)
  798. {
  799. logmsg("Please use the ", FIRMWARE_PREFIX ,"*.zip firmware bundle, or the proper .bin or .uf2 file to update the firmware.");
  800. logmsg("See https://github.com/blueSCSI/BlueSCSI-v2/wiki/Updating-Firmware for more information");
  801. }
  802. }
  803. // Update firmware by unzipping the firmware package
  804. static void firmware_update()
  805. {
  806. const char firmware_prefix[] = FIRMWARE_PREFIX;
  807. FsFile root = SD.open("/");
  808. FsFile file;
  809. char name[MAX_FILE_PATH + 1];
  810. while (1)
  811. {
  812. if (!file.openNext(&root, O_RDONLY))
  813. {
  814. file.close();
  815. root.close();
  816. return;
  817. }
  818. if (file.isDir())
  819. continue;
  820. file.getName(name, sizeof(name));
  821. if (strlen(name) + 1 < sizeof(firmware_prefix))
  822. continue;
  823. if ( strncasecmp(firmware_prefix, name, sizeof(firmware_prefix) -1) == 0)
  824. {
  825. break;
  826. }
  827. }
  828. logmsg("Found firmware package ", name);
  829. // example fixed length at the end of the filename
  830. const uint32_t postfix_filename_length = sizeof("_2025-02-21_e4be9ed.bin") - 1;
  831. const uint32_t target_filename_length = sizeof(FIRMWARE_NAME_PREFIX) - 1 + postfix_filename_length;
  832. zipparser::Parser parser = zipparser::Parser(FIRMWARE_NAME_PREFIX, sizeof(FIRMWARE_NAME_PREFIX) - 1, target_filename_length);
  833. uint8_t buf[512];
  834. int32_t parsed_length;
  835. int bytes_read = 0;
  836. while ((bytes_read = file.read(buf, sizeof(buf))) > 0)
  837. {
  838. parsed_length = parser.Parse(buf, bytes_read);
  839. if (parsed_length == sizeof(buf))
  840. continue;
  841. if (parsed_length >= 0)
  842. {
  843. if (!parser.FoundMatch())
  844. {
  845. parser.Reset();
  846. file.seekSet(file.position() - (sizeof(buf) - parsed_length) + parser.GetCompressedSize());
  847. }
  848. else
  849. {
  850. // seek to start of data in matching file
  851. file.seekSet(file.position() - (sizeof(buf) - parsed_length));
  852. break;
  853. }
  854. }
  855. if (parsed_length < 0)
  856. {
  857. logmsg("Filename character length of ", (int)target_filename_length , " with a prefix of ", FIRMWARE_NAME_PREFIX, " not found in ", name);
  858. file.close();
  859. root.close();
  860. return;
  861. }
  862. }
  863. if (parser.FoundMatch())
  864. {
  865. logmsg("Unzipping matching firmware with prefix: ", FIRMWARE_NAME_PREFIX);
  866. FsFile target_firmware;
  867. char firmware_name[64] = {0};
  868. memcpy(firmware_name, FIRMWARE_NAME_PREFIX, sizeof(FIRMWARE_NAME_PREFIX) - 1);
  869. memcpy(firmware_name + sizeof(FIRMWARE_NAME_PREFIX) - 1, ".bin", sizeof(".bin"));
  870. target_firmware.open(&root, firmware_name, O_BINARY | O_WRONLY | O_CREAT | O_TRUNC);
  871. uint32_t position = 0;
  872. while ((bytes_read = file.read(buf, sizeof(buf))) > 0)
  873. {
  874. if (bytes_read > parser.GetCompressedSize() - position)
  875. bytes_read = parser.GetCompressedSize() - position;
  876. target_firmware.write(buf, bytes_read);
  877. position += bytes_read;
  878. if (position >= parser.GetCompressedSize())
  879. {
  880. break;
  881. }
  882. }
  883. // zip file has a central directory at the end of the file,
  884. // so the compressed data should never hit the end of the file
  885. // so bytes read should always be greater than 0 for a valid datastream
  886. if (bytes_read > 0)
  887. {
  888. target_firmware.close();
  889. file.close();
  890. root.remove(name);
  891. root.close();
  892. logmsg("Update extracted from package, rebooting MCU");
  893. platform_reset_mcu();
  894. }
  895. else
  896. {
  897. target_firmware.close();
  898. logmsg("Error reading firmware package file");
  899. root.remove(firmware_name);
  900. }
  901. }
  902. file.close();
  903. root.close();
  904. }
  905. // Checks if SD card is still present
  906. static bool poll_sd_card()
  907. {
  908. #ifdef SD_USE_SDIO
  909. return SD.card()->status() != 0 && SD.card()->errorCode() == 0;
  910. #else
  911. uint32_t ocr;
  912. return SD.card()->readOCR(&ocr);
  913. #endif
  914. }
  915. #define NUM_EJECT_BUTTONS 2
  916. static void init_eject_button()
  917. {
  918. if (platform_has_phy_eject_button() && !g_scsi_settings.isEjectButtonSet())
  919. {
  920. int8_t eject_button = 1;
  921. for (uint8_t i = 0; i < S2S_MAX_TARGETS; i++)
  922. {
  923. S2S_CFG_TYPE dev_type = (S2S_CFG_TYPE)scsiDev.targets[i].cfg->deviceType;
  924. if (dev_type == S2S_CFG_OPTICAL
  925. ||dev_type == S2S_CFG_ZIP100
  926. || dev_type == S2S_CFG_REMOVABLE
  927. || dev_type == S2S_CFG_FLOPPY_14MB
  928. || dev_type == S2S_CFG_MO
  929. || dev_type == S2S_CFG_SEQUENTIAL
  930. )
  931. {
  932. setEjectButton(i, eject_button);
  933. logmsg("ID: ", (int)i, ", Eject button: #", (int)eject_button);
  934. if (++eject_button > NUM_EJECT_BUTTONS) {
  935. logmsg("");
  936. return;
  937. }
  938. }
  939. }
  940. dbgmsg("No removable media found for ", NUM_EJECT_BUTTONS, " eject buttons, skipping.");
  941. }
  942. }
  943. // Place all the setup code that requires the SD card to be initialized here
  944. // Which is pretty much everything after platform_init and and platform_late_init
  945. static void bluescsi_setup_sd_card(bool wait_for_card = true)
  946. {
  947. g_sdcard_present = mountSDCard();
  948. if(!g_sdcard_present)
  949. {
  950. if (SD.sdErrorCode() == platform_no_sd_card_on_init_error_code())
  951. {
  952. #ifdef PLATFORM_HAS_INITIATOR_MODE
  953. if (platform_is_initiator_mode_enabled())
  954. {
  955. logmsg("No SD card detected, imaging to SD card not possible");
  956. }
  957. else
  958. #endif
  959. {
  960. logmsg("No SD card detected, please check SD card slot to make sure it is in correctly");
  961. }
  962. }
  963. dbgmsg("SD card init failed, sdErrorCode: ", (int)SD.sdErrorCode(),
  964. " sdErrorData: ", (int)SD.sdErrorData());
  965. if (romDriveCheckPresent())
  966. {
  967. reinitSCSI();
  968. if (g_romdrive_active)
  969. {
  970. logmsg("Enabled ROM drive without SD card");
  971. return;
  972. }
  973. }
  974. do
  975. {
  976. blinkStatus(BLINK_ERROR_NO_SD_CARD);
  977. platform_reset_watchdog();
  978. g_sdcard_present = mountSDCard();
  979. } while (!g_sdcard_present && wait_for_card);
  980. blink_cancel();
  981. LED_OFF();
  982. if (g_sdcard_present)
  983. {
  984. logmsg("SD card init succeeded after retry");
  985. }
  986. else
  987. {
  988. logmsg("Continuing without SD card");
  989. }
  990. }
  991. check_for_unused_update_files();
  992. firmware_update();
  993. if (g_sdcard_present)
  994. {
  995. if (SD.clusterCount() == 0)
  996. {
  997. logmsg("SD card without filesystem!");
  998. }
  999. print_sd_info();
  1000. char presetName[32];
  1001. ini_gets("SCSI", "System", "", presetName, sizeof(presetName), CONFIGFILE);
  1002. scsi_system_settings_t *cfg = g_scsi_settings.initSystem(presetName);
  1003. #ifdef RECLOCKING_SUPPORTED
  1004. bluescsi_speed_grade_t speed_grade = (bluescsi_speed_grade_t) g_scsi_settings.getSystem()->speedGrade;
  1005. if (speed_grade != bluescsi_speed_grade_t::SPEED_GRADE_DEFAULT)
  1006. {
  1007. logmsg("Speed grade set to ", g_scsi_settings.getSpeedGradeString(), " reclocking system");
  1008. if (platform_reclock(speed_grade))
  1009. {
  1010. logmsg("======== Reinitializing BlueSCSI after reclock ========");
  1011. g_sdcard_present = mountSDCard();
  1012. }
  1013. }
  1014. else
  1015. {
  1016. #ifndef ENABLE_AUDIO_OUTPUT // if audio is enabled, skip message because reclocking ocurred earlier
  1017. dbgmsg("Speed grade set to Default, skipping reclocking");
  1018. #endif
  1019. }
  1020. #endif
  1021. int boot_delay_ms = cfg->initPreDelay;
  1022. if (boot_delay_ms > 0)
  1023. {
  1024. logmsg("Pre SCSI init boot delay in millis: ", boot_delay_ms);
  1025. delay(boot_delay_ms);
  1026. }
  1027. platform_post_sd_card_init();
  1028. reinitSCSI();
  1029. boot_delay_ms = cfg->initPostDelay;
  1030. if (boot_delay_ms > 0)
  1031. {
  1032. logmsg("Post SCSI init boot delay in millis: ", boot_delay_ms);
  1033. delay(boot_delay_ms);
  1034. }
  1035. }
  1036. if (g_sdcard_present)
  1037. {
  1038. init_logfile();
  1039. if (ini_getbool("SCSI", "DisableStatusLED", false, CONFIGFILE))
  1040. {
  1041. platform_disable_led();
  1042. }
  1043. }
  1044. #ifdef PLATFORM_HAS_INITIATOR_MODE
  1045. if (ini_getbool("SCSI", "InitiatorMode", false, CONFIGFILE))
  1046. {
  1047. if (platform_supports_initiator_mode()) {
  1048. logmsg("SCSI Initiator Mode");
  1049. platform_enable_initiator_mode();
  1050. if (! ini_getbool("SCSI", "InitiatorParity", true, CONFIGFILE))
  1051. {
  1052. logmsg("Initiator Mode Skipping Parity Check.");
  1053. setInitiatorModeParityCheck(false);
  1054. }
  1055. } else {
  1056. logmsg("SCSI Initiator Mode requested but not supported.");
  1057. }
  1058. }
  1059. if (!platform_is_initiator_mode_enabled())
  1060. #endif
  1061. {
  1062. if (platform_supports_initiator_mode() && ini_getbool("SCSI", "DisableI2C", false, CONFIGFILE)) {
  1063. logmsg("Disabling I2C bus for simple buttons instead.");
  1064. platform_disable_i2c();
  1065. }
  1066. init_eject_button();
  1067. }
  1068. blinkStatus(BLINK_STATUS_OK);
  1069. }
  1070. extern "C" void bluescsi_setup(void)
  1071. {
  1072. platform_init();
  1073. platform_late_init();
  1074. bool is_initiator = false;
  1075. #ifdef PLATFORM_HAS_INITIATOR_MODE
  1076. is_initiator = platform_is_initiator_mode_enabled();
  1077. #endif
  1078. bluescsi_setup_sd_card(!is_initiator);
  1079. #ifdef PLATFORM_MASS_STORAGE
  1080. static bool check_mass_storage = true;
  1081. if (check_mass_storage && !is_initiator)
  1082. {
  1083. if (platform_rebooted_into_mass_storage()
  1084. || g_scsi_settings.getSystem()->enableUSBMassStorage
  1085. || g_scsi_settings.getSystem()->usbMassStoragePresentImages
  1086. )
  1087. {
  1088. check_mass_storage = false;
  1089. // perform checks to see if a computer is attached and return true if we should enter MSC mode.
  1090. if (platform_sense_msc())
  1091. {
  1092. bluescsi_msc_loop();
  1093. logmsg("Re-processing filenames and bluescsi.ini config parameters");
  1094. bluescsi_setup_sd_card();
  1095. }
  1096. }
  1097. }
  1098. #endif
  1099. logmsg("Clock set to: ", static_cast<int>(platform_sys_clock_in_hz() / 1000000), "MHz");
  1100. logmsg("Initialization complete!");
  1101. }
  1102. extern "C" void bluescsi_main_loop(void)
  1103. {
  1104. static uint32_t sd_card_check_time = 0;
  1105. static uint32_t last_request_time = 0;
  1106. bool is_initiator = false;
  1107. #ifdef PLATFORM_HAS_INITIATOR_MODE
  1108. is_initiator = platform_is_initiator_mode_enabled();
  1109. #endif
  1110. platform_reset_watchdog();
  1111. platform_poll();
  1112. diskEjectButtonUpdate(true);
  1113. blink_poll();
  1114. #ifdef BLUESCSI_NETWORK
  1115. platform_network_poll();
  1116. #endif // BLUESCSI_NETWORK
  1117. #ifdef PLATFORM_HAS_INITIATOR_MODE
  1118. if (is_initiator)
  1119. {
  1120. scsiInitiatorMainLoop();
  1121. save_logfile();
  1122. }
  1123. else
  1124. #endif
  1125. {
  1126. scsiPoll();
  1127. scsiDiskPoll();
  1128. scsiLogPhaseChange(scsiDev.phase);
  1129. // Save log periodically during status phase if there are new messages.
  1130. // In debug mode, also save every 2 seconds if no SCSI requests come in.
  1131. // SD card writing takes a while, during which the code can't handle new
  1132. // SCSI requests, so normally we only want to save during a phase where
  1133. // the host is waiting for us. But for debugging issues where no requests
  1134. // come through or a request hangs, it's useful to force saving of log.
  1135. if (scsiDev.phase == STATUS || (g_log_debug && (uint32_t)(millis() - last_request_time) > 2000))
  1136. {
  1137. save_logfile();
  1138. last_request_time = millis();
  1139. }
  1140. }
  1141. if (g_sdcard_present)
  1142. {
  1143. // Check SD card status for hotplug
  1144. if (scsiDev.phase == BUS_FREE &&
  1145. (uint32_t)(millis() - sd_card_check_time) > SDCARD_POLL_INTERVAL)
  1146. {
  1147. sd_card_check_time = millis();
  1148. if (!poll_sd_card())
  1149. {
  1150. if (!poll_sd_card())
  1151. {
  1152. g_sdcard_present = false;
  1153. logmsg("SD card removed, trying to reinit");
  1154. }
  1155. }
  1156. }
  1157. }
  1158. if (!g_sdcard_present && (uint32_t)(millis() - sd_card_check_time) > SDCARD_POLL_INTERVAL
  1159. && !g_msc_initiator)
  1160. {
  1161. sd_card_check_time = millis();
  1162. // Try to remount SD card
  1163. do
  1164. {
  1165. g_sdcard_present = mountSDCard();
  1166. if (g_sdcard_present)
  1167. {
  1168. blink_cancel();
  1169. LED_OFF();
  1170. logmsg("SD card reinit succeeded");
  1171. print_sd_info();
  1172. reinitSCSI();
  1173. init_logfile();
  1174. blinkStatus(BLINK_STATUS_OK);
  1175. }
  1176. else if (!g_romdrive_active)
  1177. {
  1178. blinkStatus(BLINK_ERROR_NO_SD_CARD);
  1179. platform_reset_watchdog();
  1180. platform_poll();
  1181. }
  1182. } while (!g_sdcard_present && !g_romdrive_active && !is_initiator);
  1183. }
  1184. }