BlueSCSI.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. /*
  2. BlueSCSI Copyright (c) 2022 the BlueSCSI contributors (CONTRIBUTORS.txt)
  3. This file is part of BlueSCSI.
  4. BlueSCSI is free software: you can redistribute it and/or modify it under the terms of the
  5. GNU General Public License as published by the Free Software Foundation, either version 3
  6. of the License, or (at your option) any later version.
  7. BlueSCSI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
  8. without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  9. See the GNU General Public License for more details.
  10. You should have received a copy of the GNU General Public License along with BlueSCSI.
  11. If not, see <https://www.gnu.org/licenses/>.
  12. */
  13. #include <SdFat.h>
  14. #include <minIni.h>
  15. #include <string.h>
  16. #include <strings.h>
  17. #include <ctype.h>
  18. #include "BlueSCSI_config.h"
  19. #include "BlueSCSI_platform.h"
  20. #include "BlueSCSI_log.h"
  21. #include "BlueSCSI_log_trace.h"
  22. #include "BlueSCSI_disk.h"
  23. #include "BlueSCSI_initiator.h"
  24. SdFs SD;
  25. FsFile g_logfile;
  26. static bool g_romdrive_active;
  27. static bool g_sdcard_present;
  28. /************************************/
  29. /* Status reporting by blinking led */
  30. /************************************/
  31. #define BLINK_STATUS_OK 1
  32. #define BLINK_ERROR_NO_IMAGES 3
  33. #define BLINK_ERROR_NO_SD_CARD 5
  34. void blinkStatus(int count)
  35. {
  36. for (int i = 0; i < count; i++)
  37. {
  38. LED_ON();
  39. delay(250);
  40. LED_OFF();
  41. delay(250);
  42. }
  43. }
  44. extern "C" void s2s_ledOn()
  45. {
  46. LED_ON();
  47. }
  48. extern "C" void s2s_ledOff()
  49. {
  50. LED_OFF();
  51. }
  52. /**************/
  53. /* Log saving */
  54. /**************/
  55. void save_logfile(bool always = false)
  56. {
  57. static uint32_t prev_log_pos = 0;
  58. static uint32_t prev_log_len = 0;
  59. static uint32_t prev_log_save = 0;
  60. uint32_t loglen = log_get_buffer_len();
  61. if (loglen != prev_log_len && g_sdcard_present)
  62. {
  63. // When debug is off, save log at most every LOG_SAVE_INTERVAL_MS
  64. // When debug is on, save after every SCSI command.
  65. if (always || g_log_debug || (LOG_SAVE_INTERVAL_MS > 0 && (uint32_t)(millis() - prev_log_save) > LOG_SAVE_INTERVAL_MS))
  66. {
  67. g_logfile.write(log_get_buffer(&prev_log_pos));
  68. g_logfile.flush();
  69. prev_log_len = loglen;
  70. prev_log_save = millis();
  71. }
  72. }
  73. }
  74. void init_logfile()
  75. {
  76. static bool first_open_after_boot = true;
  77. bool truncate = first_open_after_boot;
  78. int flags = O_WRONLY | O_CREAT | (truncate ? O_TRUNC : O_APPEND);
  79. g_logfile = SD.open(LOGFILE, flags);
  80. if (!g_logfile.isOpen())
  81. {
  82. log("Failed to open log file: ", SD.sdErrorCode());
  83. }
  84. save_logfile(true);
  85. first_open_after_boot = false;
  86. }
  87. const char * fatTypeToChar(int fatType)
  88. {
  89. switch (fatType)
  90. {
  91. case FAT_TYPE_EXFAT:
  92. return "exFAT";
  93. case FAT_TYPE_FAT32:
  94. return "FAT32";
  95. case FAT_TYPE_FAT16:
  96. return "FAT16";
  97. case FAT_TYPE_FAT12:
  98. return "FAT12";
  99. default:
  100. return "Unknown";
  101. }
  102. }
  103. void print_sd_info()
  104. {
  105. log(" ");
  106. log("=== SD Card Info ===");
  107. uint64_t size = (uint64_t)SD.vol()->clusterCount() * SD.vol()->bytesPerCluster();
  108. log("SD card detected, ", fatTypeToChar((int)SD.vol()->fatType()),
  109. " volume size: ", (int)(size / 1024 / 1024), " MB");
  110. cid_t sd_cid;
  111. if(SD.card()->readCID(&sd_cid))
  112. {
  113. char sdname[6] = {sd_cid.pnm[0], sd_cid.pnm[1], sd_cid.pnm[2], sd_cid.pnm[3], sd_cid.pnm[4], 0};
  114. log("SD Name: ", sdname, ", MID: ", (uint8_t)sd_cid.mid, ", OID: ", (uint8_t)sd_cid.oid[0], " ", (uint8_t)sd_cid.oid[1]);
  115. debuglog("SD Date: ", (int)sd_cid.mdtMonth(), "/", sd_cid.mdtYear());
  116. debuglog("SD Serial: ", sd_cid.psn());
  117. }
  118. }
  119. /*********************************/
  120. /* Harddisk image file handling */
  121. /*********************************/
  122. const char * typeToChar(int deviceType)
  123. {
  124. switch (deviceType)
  125. {
  126. case S2S_CFG_OPTICAL:
  127. return "Optical";
  128. case S2S_CFG_FIXED:
  129. return "Fixed";
  130. case S2S_CFG_FLOPPY_14MB:
  131. return "Floppy1.4MB";
  132. case S2S_CFG_MO:
  133. return "MO";
  134. case S2S_CFG_SEQUENTIAL:
  135. return "Tape";
  136. case S2S_CFG_REMOVEABLE:
  137. return "Removable";
  138. default:
  139. return "Unknown";
  140. }
  141. }
  142. const char * quirksToChar(int quirks)
  143. {
  144. switch (quirks)
  145. {
  146. case S2S_CFG_QUIRKS_APPLE:
  147. return "Apple";
  148. case S2S_CFG_QUIRKS_OMTI:
  149. return "OMTI";
  150. case S2S_CFG_QUIRKS_VMS:
  151. return "VMS";
  152. case S2S_CFG_QUIRKS_XEBEC:
  153. return "XEBEC";
  154. case S2S_CFG_QUIRKS_NONE:
  155. return "None";
  156. default:
  157. return "Unknown";
  158. }
  159. }
  160. // Iterate over the root path in the SD card looking for candidate image files.
  161. bool findHDDImages()
  162. {
  163. char imgdir[MAX_FILE_PATH];
  164. ini_gets("SCSI", "Dir", "/", imgdir, sizeof(imgdir), CONFIGFILE);
  165. int dirindex = 0;
  166. log(" ");
  167. log("=== Finding images in ", imgdir, " ===");
  168. SdFile root;
  169. root.open(imgdir);
  170. if (!root.isOpen())
  171. {
  172. log("Could not open directory: ", imgdir);
  173. }
  174. SdFile file;
  175. bool imageReady;
  176. bool foundImage = false;
  177. int usedDefaultId = 0;
  178. while (1)
  179. {
  180. if (!file.openNext(&root, O_READ))
  181. {
  182. // Check for additional directories with ini keys Dir1..Dir9
  183. while (dirindex < 10)
  184. {
  185. dirindex++;
  186. char key[5] = "Dir0";
  187. key[3] += dirindex;
  188. if (ini_gets("SCSI", key, "", imgdir, sizeof(imgdir), CONFIGFILE) != 0)
  189. {
  190. break;
  191. }
  192. }
  193. if (imgdir[0] != '\0')
  194. {
  195. log("== Finding HDD images in additional Dir", (int)dirindex, " = \"", imgdir, "\" ==");
  196. root.open(imgdir);
  197. if (!root.isOpen())
  198. {
  199. log("-- Could not open directory: ", imgdir);
  200. }
  201. continue;
  202. }
  203. else
  204. {
  205. break;
  206. }
  207. }
  208. char name[MAX_FILE_PATH+1];
  209. if(!file.isDir())
  210. {
  211. file.getName(name, MAX_FILE_PATH+1);
  212. file.close();
  213. bool is_hd = (tolower(name[0]) == 'h' && tolower(name[1]) == 'd');
  214. bool is_cd = (tolower(name[0]) == 'c' && tolower(name[1]) == 'd');
  215. bool is_fd = (tolower(name[0]) == 'f' && tolower(name[1]) == 'd');
  216. bool is_mo = (tolower(name[0]) == 'm' && tolower(name[1]) == 'o');
  217. bool is_re = (tolower(name[0]) == 'r' && tolower(name[1]) == 'e');
  218. bool is_tp = (tolower(name[0]) == 't' && tolower(name[1]) == 'p');
  219. if (is_hd || is_cd || is_fd || is_mo || is_re || is_tp)
  220. {
  221. // Check file extension
  222. // We accept anything except known compressed files
  223. bool is_compressed = false;
  224. const char *extension = strrchr(name, '.');
  225. if (extension)
  226. {
  227. const char *archive_exts[] = {
  228. ".tar", ".tgz", ".gz", ".bz2", ".tbz2", ".xz", ".zst", ".z",
  229. ".zip", ".zipx", ".rar", ".lzh", ".lha", ".lzo", ".lz4", ".arj",
  230. ".dmg", ".hqx", ".cpt", ".7z", ".s7z",
  231. NULL
  232. };
  233. for (int i = 0; archive_exts[i]; i++)
  234. {
  235. if (strcasecmp(extension, archive_exts[i]) == 0)
  236. {
  237. is_compressed = true;
  238. break;
  239. }
  240. }
  241. }
  242. if (is_compressed)
  243. {
  244. log("-- Ignoring compressed file ", name);
  245. continue;
  246. }
  247. // Check if the image should be loaded to microcontroller flash ROM drive
  248. bool is_romdrive = false;
  249. if (extension && strcasecmp(extension, ".rom") == 0)
  250. {
  251. is_romdrive = true;
  252. }
  253. else if (extension && strcasecmp(extension, ".rom_loaded") == 0)
  254. {
  255. // Already loaded ROM drive, ignore the image
  256. continue;
  257. }
  258. // Defaults for Hard Disks
  259. int id = 1; // 0 and 3 are common in Macs for physical HD and CD, so avoid them.
  260. int lun = 0;
  261. int blk = 512;
  262. if (is_cd)
  263. {
  264. // Use 2048 as the default sector size for CD-ROMs
  265. blk = 2048;
  266. }
  267. // Parse SCSI device ID
  268. int file_name_length = strlen(name);
  269. if(file_name_length > 2) { // HD[N]
  270. int tmp_id = name[HDIMG_ID_POS] - '0';
  271. if(tmp_id > -1 && tmp_id < 8)
  272. {
  273. id = tmp_id; // If valid id, set it, else use default
  274. }
  275. else
  276. {
  277. id = usedDefaultId++;
  278. }
  279. }
  280. // Parse SCSI LUN number
  281. if(file_name_length > 3) // HD0[N]
  282. {
  283. int tmp_lun = name[HDIMG_LUN_POS] - '0';
  284. if(tmp_lun > -1 && tmp_lun < NUM_SCSILUN)
  285. {
  286. lun = tmp_lun; // If valid id, set it, else use default
  287. }
  288. }
  289. // Parse block size (HD00_NNNN)
  290. const char *blksize = strchr(name, '_');
  291. if (blksize)
  292. {
  293. int blktmp = strtoul(blksize + 1, NULL, 10);
  294. if (blktmp == 256 || blktmp == 512 || blktmp == 1024 ||
  295. blktmp == 2048 || blktmp == 4096 || blktmp == 8192)
  296. {
  297. blk = blktmp;
  298. }
  299. }
  300. // Add the directory name to get the full file path
  301. char fullname[MAX_FILE_PATH * 2 + 2] = {0};
  302. strncpy(fullname, imgdir, MAX_FILE_PATH);
  303. if (fullname[strlen(fullname) - 1] != '/') strcat(fullname, "/");
  304. strcat(fullname, name);
  305. // Check whether this SCSI ID has been configured yet
  306. const S2S_TargetCfg* cfg = s2s_getConfigById(id);
  307. if (cfg)
  308. {
  309. log("-- Ignoring ", fullname, ", SCSI ID ", id, " is already in use!");
  310. continue;
  311. }
  312. // Apple computers reserve ID 7, so warn the user this configuration wont work
  313. if(id == 7 && cfg->quirks == S2S_CFG_QUIRKS_APPLE )
  314. {
  315. log("-- Ignoring ", fullname, ", SCSI ID ", id, " Quirks set to Apple so can not use SCSI ID 7!");
  316. continue;
  317. }
  318. // Type mapping based on filename.
  319. // If type is FIXED, the type can still be overridden in .ini file.
  320. S2S_CFG_TYPE type = S2S_CFG_FIXED;
  321. if (is_cd) type = S2S_CFG_OPTICAL;
  322. if (is_fd) type = S2S_CFG_FLOPPY_14MB;
  323. if (is_mo) type = S2S_CFG_MO;
  324. if (is_re) type = S2S_CFG_REMOVEABLE;
  325. if (is_tp) type = S2S_CFG_SEQUENTIAL;
  326. // Open the image file
  327. if (id < NUM_SCSIID && is_romdrive)
  328. {
  329. log("== Loading ROM drive from ", fullname, " for ID: ", id);
  330. imageReady = scsiDiskProgramRomDrive(fullname, id, blk, type);
  331. if (imageReady)
  332. {
  333. foundImage = true;
  334. }
  335. }
  336. else if(id < NUM_SCSIID && lun < NUM_SCSILUN)
  337. {
  338. log("== Opening ", fullname, " for ID: ", id, " LUN: ", lun);
  339. imageReady = scsiDiskOpenHDDImage(id, fullname, id, lun, blk, type);
  340. if(imageReady)
  341. {
  342. foundImage = true;
  343. log("---- Image ready");
  344. }
  345. else
  346. {
  347. log("---- Failed to load image");
  348. }
  349. }
  350. else
  351. {
  352. log("-- Invalid lun or id for image ", fullname);
  353. }
  354. }
  355. }
  356. }
  357. if(usedDefaultId > 0)
  358. {
  359. log("-- ", usedDefaultId, " images did not specify a SCSI ID and were assigned one if possible.");
  360. }
  361. root.close();
  362. g_romdrive_active = scsiDiskActivateRomDrive();
  363. // Print SCSI drive map
  364. log(" ");
  365. log("=== Configured SCSI Devices ===");
  366. for (int i = 0; i < NUM_SCSIID; i++)
  367. {
  368. const S2S_TargetCfg* cfg = s2s_getConfigByIndex(i);
  369. if (cfg && (cfg->scsiId & S2S_CFG_TARGET_ENABLED))
  370. {
  371. int capacity_kB = ((uint64_t)cfg->scsiSectors * cfg->bytesPerSector) / 1024;
  372. log("* ID: ", (int)(cfg->scsiId & 7),
  373. ", BlockSize: ", (int)cfg->bytesPerSector,
  374. ", Type: ", typeToChar((int)cfg->deviceType),
  375. ", Quirks: ", quirksToChar((int)cfg->quirks),
  376. ", Size: ", capacity_kB, "kB");
  377. }
  378. }
  379. return foundImage;
  380. }
  381. /************************/
  382. /* Config file loading */
  383. /************************/
  384. void readSCSIDeviceConfig()
  385. {
  386. log(" ");
  387. log("=== Global Config ===");
  388. s2s_configInit(&scsiDev.boardCfg);
  389. for (int i = 0; i < NUM_SCSIID; i++)
  390. {
  391. scsiDiskLoadConfig(i);
  392. }
  393. }
  394. /*********************************/
  395. /* Main SCSI handling loop */
  396. /*********************************/
  397. static bool mountSDCard()
  398. {
  399. // Check for the common case, FAT filesystem as first partition
  400. if (SD.begin(SD_CONFIG))
  401. return true;
  402. // Do we have any kind of card?
  403. if (!SD.card() || SD.sdErrorCode() != 0)
  404. return false;
  405. // Try to mount the whole card as FAT (without partition table)
  406. if (static_cast<FsVolume*>(&SD)->begin(SD.card(), true, 0))
  407. return true;
  408. // Failed to mount FAT filesystem, but card can still be accessed as raw image
  409. return true;
  410. }
  411. static void reinitSCSI()
  412. {
  413. if (ini_getbool("SCSI", "Debug", 0, CONFIGFILE))
  414. {
  415. g_log_debug = true;
  416. }
  417. #ifdef PLATFORM_HAS_INITIATOR_MODE
  418. if (platform_is_initiator_mode_enabled())
  419. {
  420. // Initialize scsiDev to zero values even though it is not used
  421. scsiInit();
  422. // Initializer initiator mode state machine
  423. scsiInitiatorInit();
  424. blinkStatus(BLINK_STATUS_OK);
  425. return;
  426. }
  427. #endif
  428. scsiDiskResetImages();
  429. readSCSIDeviceConfig();
  430. findHDDImages();
  431. // Error if there are 0 image files
  432. if (scsiDiskCheckAnyImagesConfigured())
  433. {
  434. // Ok, there is an image
  435. blinkStatus(BLINK_STATUS_OK);
  436. }
  437. else
  438. {
  439. #if RAW_FALLBACK_ENABLE
  440. log("No images found, enabling RAW fallback partition");
  441. scsiDiskOpenHDDImage(RAW_FALLBACK_SCSI_ID, "RAW:0:0xFFFFFFFF", RAW_FALLBACK_SCSI_ID, 0,
  442. RAW_FALLBACK_BLOCKSIZE);
  443. #else
  444. log("No valid image files found!");
  445. #endif
  446. blinkStatus(BLINK_ERROR_NO_IMAGES);
  447. }
  448. scsiPhyReset();
  449. scsiDiskInit();
  450. scsiInit();
  451. }
  452. extern "C" void bluescsi_setup(void)
  453. {
  454. platform_init();
  455. platform_late_init();
  456. g_sdcard_present = mountSDCard();
  457. if(!g_sdcard_present)
  458. {
  459. log("SD card init failed, sdErrorCode: ", (int)SD.sdErrorCode(),
  460. " sdErrorData: ", (int)SD.sdErrorData());
  461. if (scsiDiskCheckRomDrive())
  462. {
  463. reinitSCSI();
  464. if (g_romdrive_active)
  465. {
  466. log("Enabled ROM drive without SD card");
  467. return;
  468. }
  469. }
  470. do
  471. {
  472. blinkStatus(BLINK_ERROR_NO_SD_CARD);
  473. delay(1000);
  474. platform_reset_watchdog();
  475. g_sdcard_present = mountSDCard();
  476. } while (!g_sdcard_present);
  477. log("SD card init succeeded after retry");
  478. }
  479. if (g_sdcard_present)
  480. {
  481. if (SD.clusterCount() == 0)
  482. {
  483. log("SD card without filesystem!");
  484. }
  485. print_sd_info();
  486. reinitSCSI();
  487. }
  488. log(" ");
  489. log("Initialization complete!");
  490. if (g_sdcard_present)
  491. {
  492. init_logfile();
  493. if (ini_getbool("SCSI", "DisableStatusLED", false, CONFIGFILE))
  494. {
  495. platform_disable_led();
  496. }
  497. }
  498. }
  499. extern "C" void bluescsi_main_loop(void)
  500. {
  501. static uint32_t sd_card_check_time = 0;
  502. platform_reset_watchdog();
  503. #ifdef PLATFORM_HAS_INITIATOR_MODE
  504. if (platform_is_initiator_mode_enabled())
  505. {
  506. scsiInitiatorMainLoop();
  507. save_logfile();
  508. }
  509. else
  510. #endif
  511. {
  512. scsiPoll();
  513. scsiDiskPoll();
  514. scsiLogPhaseChange(scsiDev.phase);
  515. // Save log periodically during status phase if there are new messages.
  516. if (scsiDev.phase == STATUS)
  517. {
  518. save_logfile();
  519. }
  520. }
  521. if (g_sdcard_present)
  522. {
  523. // Check SD card status for hotplug
  524. if (scsiDev.phase == BUS_FREE &&
  525. (uint32_t)(millis() - sd_card_check_time) > 5000)
  526. {
  527. sd_card_check_time = millis();
  528. uint32_t ocr;
  529. if (!SD.card()->readOCR(&ocr))
  530. {
  531. if (!SD.card()->readOCR(&ocr))
  532. {
  533. g_sdcard_present = false;
  534. log("SD card removed, trying to reinit");
  535. }
  536. }
  537. }
  538. }
  539. if (!g_sdcard_present)
  540. {
  541. // Try to remount SD card
  542. do
  543. {
  544. g_sdcard_present = mountSDCard();
  545. if (g_sdcard_present)
  546. {
  547. log("SD card reinit succeeded");
  548. print_sd_info();
  549. reinitSCSI();
  550. init_logfile();
  551. }
  552. else if (!g_romdrive_active)
  553. {
  554. blinkStatus(BLINK_ERROR_NO_SD_CARD);
  555. delay(1000);
  556. platform_reset_watchdog();
  557. }
  558. } while (!g_sdcard_present && !g_romdrive_active);
  559. }
  560. else
  561. {
  562. }
  563. }