BlueSCSI.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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. SCSI_OUT(BSY, 1);
  40. delay(250);
  41. LED_OFF();
  42. SCSI_OUT(BSY, 0);
  43. delay(250);
  44. }
  45. }
  46. extern "C" void s2s_ledOn()
  47. {
  48. LED_ON();
  49. }
  50. extern "C" void s2s_ledOff()
  51. {
  52. LED_OFF();
  53. }
  54. /**************/
  55. /* Log saving */
  56. /**************/
  57. void save_logfile(bool always = false)
  58. {
  59. static uint32_t prev_log_pos = 0;
  60. static uint32_t prev_log_len = 0;
  61. static uint32_t prev_log_save = 0;
  62. uint32_t loglen = bluelog_get_buffer_len();
  63. if (loglen != prev_log_len && g_sdcard_present)
  64. {
  65. // When debug is off, save log at most every LOG_SAVE_INTERVAL_MS
  66. // When debug is on, save after every SCSI command.
  67. if (always || g_bluelog_debug || (LOG_SAVE_INTERVAL_MS > 0 && (uint32_t)(millis() - prev_log_save) > LOG_SAVE_INTERVAL_MS))
  68. {
  69. g_logfile.write(bluelog_get_buffer(&prev_log_pos));
  70. g_logfile.flush();
  71. prev_log_len = loglen;
  72. prev_log_save = millis();
  73. }
  74. }
  75. }
  76. void init_logfile()
  77. {
  78. static bool first_open_after_boot = true;
  79. bool truncate = first_open_after_boot;
  80. int flags = O_WRONLY | O_CREAT | (truncate ? O_TRUNC : O_APPEND);
  81. g_logfile = SD.open(LOGFILE, flags);
  82. if (!g_logfile.isOpen())
  83. {
  84. bluelog("Failed to open log file: ", SD.sdErrorCode());
  85. }
  86. save_logfile(true);
  87. first_open_after_boot = false;
  88. }
  89. void print_sd_info()
  90. {
  91. uint64_t size = (uint64_t)SD.vol()->clusterCount() * SD.vol()->bytesPerCluster();
  92. bluelog("SD card detected, FAT", (int)SD.vol()->fatType(),
  93. " volume size: ", (int)(size / 1024 / 1024), " MB");
  94. cid_t sd_cid;
  95. if(SD.card()->readCID(&sd_cid))
  96. {
  97. bluelog("SD MID: ", (uint8_t)sd_cid.mid, ", OID: ", (uint8_t)sd_cid.oid[0], " ", (uint8_t)sd_cid.oid[1]);
  98. char sdname[6] = {sd_cid.pnm[0], sd_cid.pnm[1], sd_cid.pnm[2], sd_cid.pnm[3], sd_cid.pnm[4], 0};
  99. bluelog("SD Name: ", sdname);
  100. bluelog("SD Date: ", (int)sd_cid.mdtMonth(), "/", sd_cid.mdtYear());
  101. bluelog("SD Serial: ", sd_cid.psn());
  102. }
  103. }
  104. /*********************************/
  105. /* Harddisk image file handling */
  106. /*********************************/
  107. // Iterate over the root path in the SD card looking for candidate image files.
  108. bool findHDDImages()
  109. {
  110. char imgdir[MAX_FILE_PATH];
  111. ini_gets("SCSI", "Dir", "/", imgdir, sizeof(imgdir), CONFIGFILE);
  112. int dirindex = 0;
  113. bluelog("Finding HDD images in directory ", imgdir, ":");
  114. SdFile root;
  115. root.open(imgdir);
  116. if (!root.isOpen())
  117. {
  118. bluelog("Could not open directory: ", imgdir);
  119. }
  120. SdFile file;
  121. bool imageReady;
  122. bool foundImage = false;
  123. int usedDefaultId = 0;
  124. while (1)
  125. {
  126. if (!file.openNext(&root, O_READ))
  127. {
  128. // Check for additional directories with ini keys Dir1..Dir9
  129. while (dirindex < 10)
  130. {
  131. dirindex++;
  132. char key[5] = "Dir0";
  133. key[3] += dirindex;
  134. if (ini_gets("SCSI", key, "", imgdir, sizeof(imgdir), CONFIGFILE) != 0)
  135. {
  136. break;
  137. }
  138. }
  139. if (imgdir[0] != '\0')
  140. {
  141. bluelog("Finding HDD images in additional directory Dir", (int)dirindex, " = \"", imgdir, "\":");
  142. root.open(imgdir);
  143. if (!root.isOpen())
  144. {
  145. bluelog("-- Could not open directory: ", imgdir);
  146. }
  147. continue;
  148. }
  149. else
  150. {
  151. break;
  152. }
  153. }
  154. char name[MAX_FILE_PATH+1];
  155. if(!file.isDir()) {
  156. file.getName(name, MAX_FILE_PATH+1);
  157. file.close();
  158. bool is_hd = (tolower(name[0]) == 'h' && tolower(name[1]) == 'd');
  159. bool is_cd = (tolower(name[0]) == 'c' && tolower(name[1]) == 'd');
  160. bool is_fd = (tolower(name[0]) == 'f' && tolower(name[1]) == 'd');
  161. bool is_mo = (tolower(name[0]) == 'm' && tolower(name[1]) == 'o');
  162. bool is_re = (tolower(name[0]) == 'r' && tolower(name[1]) == 'e');
  163. bool is_tp = (tolower(name[0]) == 't' && tolower(name[1]) == 'p');
  164. if (is_hd || is_cd || is_fd || is_mo || is_re || is_tp)
  165. {
  166. // Check file extension
  167. // We accept anything except known compressed files
  168. bool is_compressed = false;
  169. const char *extension = strrchr(name, '.');
  170. if (extension)
  171. {
  172. const char *archive_exts[] = {
  173. ".tar", ".tgz", ".gz", ".bz2", ".tbz2", ".xz", ".zst", ".z",
  174. ".zip", ".zipx", ".rar", ".lzh", ".lha", ".lzo", ".lz4", ".arj",
  175. ".dmg", ".hqx", ".cpt", ".7z", ".s7z",
  176. NULL
  177. };
  178. for (int i = 0; archive_exts[i]; i++)
  179. {
  180. if (strcasecmp(extension, archive_exts[i]) == 0)
  181. {
  182. is_compressed = true;
  183. break;
  184. }
  185. }
  186. }
  187. if (is_compressed)
  188. {
  189. bluelog("-- Ignoring compressed file ", name);
  190. continue;
  191. }
  192. // Check if the image should be loaded to microcontroller flash ROM drive
  193. bool is_romdrive = false;
  194. if (extension && strcasecmp(extension, ".rom") == 0)
  195. {
  196. is_romdrive = true;
  197. }
  198. else if (extension && strcasecmp(extension, ".rom_loaded") == 0)
  199. {
  200. // Already loaded ROM drive, ignore the image
  201. continue;
  202. }
  203. // Defaults for Hard Disks
  204. int id = 1; // 0 and 3 are common in Macs for physical HD and CD, so avoid them.
  205. int lun = 0;
  206. int blk = 512;
  207. if (is_cd)
  208. {
  209. // Use 2048 as the default sector size for CD-ROMs
  210. blk = 2048;
  211. }
  212. // Parse SCSI device ID
  213. int file_name_length = strlen(name);
  214. if(file_name_length > 2) { // HD[N]
  215. int tmp_id = name[HDIMG_ID_POS] - '0';
  216. if(tmp_id > -1 && tmp_id < 8)
  217. {
  218. id = tmp_id; // If valid id, set it, else use default
  219. }
  220. else
  221. {
  222. id = usedDefaultId++;
  223. }
  224. }
  225. // Parse SCSI LUN number
  226. if(file_name_length > 3) { // HD0[N]
  227. int tmp_lun = name[HDIMG_LUN_POS] - '0';
  228. if(tmp_lun > -1 && tmp_lun < NUM_SCSILUN) {
  229. lun = tmp_lun; // If valid id, set it, else use default
  230. }
  231. }
  232. // Parse block size (HD00_NNNN)
  233. const char *blksize = strchr(name, '_');
  234. if (blksize)
  235. {
  236. int blktmp = strtoul(blksize + 1, NULL, 10);
  237. if (blktmp == 256 || blktmp == 512 || blktmp == 1024 ||
  238. blktmp == 2048 || blktmp == 4096 || blktmp == 8192)
  239. {
  240. blk = blktmp;
  241. }
  242. }
  243. // Add the directory name to get the full file path
  244. char fullname[MAX_FILE_PATH * 2 + 2] = {0};
  245. strncpy(fullname, imgdir, MAX_FILE_PATH);
  246. if (fullname[strlen(fullname) - 1] != '/') strcat(fullname, "/");
  247. strcat(fullname, name);
  248. // Check whether this SCSI ID has been configured yet
  249. if (s2s_getConfigById(id))
  250. {
  251. bluelog("-- Ignoring ", fullname, ", SCSI ID ", id, " is already in use!");
  252. continue;
  253. }
  254. // Type mapping based on filename.
  255. // If type is FIXED, the type can still be overridden in .ini file.
  256. S2S_CFG_TYPE type = S2S_CFG_FIXED;
  257. if (is_cd) type = S2S_CFG_OPTICAL;
  258. if (is_fd) type = S2S_CFG_FLOPPY_14MB;
  259. if (is_mo) type = S2S_CFG_MO;
  260. if (is_re) type = S2S_CFG_REMOVEABLE;
  261. if (is_tp) type = S2S_CFG_SEQUENTIAL;
  262. // Open the image file
  263. if (id < NUM_SCSIID && is_romdrive)
  264. {
  265. bluelog("-- Loading ROM drive from ", fullname, " for id:", id);
  266. imageReady = scsiDiskProgramRomDrive(fullname, id, blk, type);
  267. if (imageReady)
  268. {
  269. foundImage = true;
  270. }
  271. }
  272. else if(id < NUM_SCSIID && lun < NUM_SCSILUN) {
  273. bluelog("-- Opening ", fullname, " for id:", id, " lun:", lun);
  274. imageReady = scsiDiskOpenHDDImage(id, fullname, id, lun, blk, type);
  275. if(imageReady)
  276. {
  277. foundImage = true;
  278. }
  279. else
  280. {
  281. bluelog("---- Failed to load image");
  282. }
  283. } else {
  284. bluelog("-- Invalid lun or id for image ", fullname);
  285. }
  286. }
  287. }
  288. }
  289. if(usedDefaultId > 0) {
  290. bluelog("Some images did not specify a SCSI ID. Last file will be used at ID ", usedDefaultId);
  291. }
  292. root.close();
  293. g_romdrive_active = scsiDiskActivateRomDrive();
  294. // Print SCSI drive map
  295. for (int i = 0; i < NUM_SCSIID; i++)
  296. {
  297. const S2S_TargetCfg* cfg = s2s_getConfigByIndex(i);
  298. if (cfg && (cfg->scsiId & S2S_CFG_TARGET_ENABLED))
  299. {
  300. int capacity_kB = ((uint64_t)cfg->scsiSectors * cfg->bytesPerSector) / 1024;
  301. bluelog("SCSI ID:", (int)(cfg->scsiId & 7),
  302. " BlockSize:", (int)cfg->bytesPerSector,
  303. " Type:", (int)cfg->deviceType,
  304. " Quirks:", (int)cfg->quirks,
  305. " ImageSize:", capacity_kB, "kB");
  306. }
  307. }
  308. return foundImage;
  309. }
  310. /************************/
  311. /* Config file loading */
  312. /************************/
  313. void readSCSIDeviceConfig()
  314. {
  315. s2s_configInit(&scsiDev.boardCfg);
  316. for (int i = 0; i < NUM_SCSIID; i++)
  317. {
  318. scsiDiskLoadConfig(i);
  319. }
  320. }
  321. /*********************************/
  322. /* Main SCSI handling loop */
  323. /*********************************/
  324. static bool mountSDCard()
  325. {
  326. // Check for the common case, FAT filesystem as first partition
  327. if (SD.begin(SD_CONFIG))
  328. return true;
  329. // Do we have any kind of card?
  330. if (!SD.card() || SD.sdErrorCode() != 0)
  331. return false;
  332. // Try to mount the whole card as FAT (without partition table)
  333. if (static_cast<FsVolume*>(&SD)->begin(SD.card(), true, 0))
  334. return true;
  335. // Failed to mount FAT filesystem, but card can still be accessed as raw image
  336. return true;
  337. }
  338. static void reinitSCSI()
  339. {
  340. if (ini_getbool("SCSI", "Debug", 0, CONFIGFILE))
  341. {
  342. g_bluelog_debug = true;
  343. }
  344. #ifdef PLATFORM_HAS_INITIATOR_MODE
  345. if (platform_is_initiator_mode_enabled())
  346. {
  347. // Initialize scsiDev to zero values even though it is not used
  348. scsiInit();
  349. // Initializer initiator mode state machine
  350. scsiInitiatorInit();
  351. blinkStatus(BLINK_STATUS_OK);
  352. return;
  353. }
  354. #endif
  355. scsiDiskResetImages();
  356. readSCSIDeviceConfig();
  357. findHDDImages();
  358. // Error if there are 0 image files
  359. if (scsiDiskCheckAnyImagesConfigured())
  360. {
  361. // Ok, there is an image
  362. blinkStatus(BLINK_STATUS_OK);
  363. }
  364. else
  365. {
  366. #if RAW_FALLBACK_ENABLE
  367. bluelog("No images found, enabling RAW fallback partition");
  368. scsiDiskOpenHDDImage(RAW_FALLBACK_SCSI_ID, "RAW:0:0xFFFFFFFF", RAW_FALLBACK_SCSI_ID, 0,
  369. RAW_FALLBACK_BLOCKSIZE);
  370. #else
  371. bluelog("No valid image files found!");
  372. #endif
  373. blinkStatus(BLINK_ERROR_NO_IMAGES);
  374. }
  375. scsiPhyReset();
  376. scsiDiskInit();
  377. scsiInit();
  378. }
  379. extern "C" void bluescsi_setup(void)
  380. {
  381. platform_init();
  382. platform_late_init();
  383. g_sdcard_present = mountSDCard();
  384. if(!g_sdcard_present)
  385. {
  386. bluelog("SD card init failed, sdErrorCode: ", (int)SD.sdErrorCode(),
  387. " sdErrorData: ", (int)SD.sdErrorData());
  388. blinkStatus(BLINK_ERROR_NO_SD_CARD);
  389. if (scsiDiskCheckRomDrive())
  390. {
  391. reinitSCSI();
  392. if (g_romdrive_active)
  393. {
  394. bluelog("Enabled ROM drive without SD card");
  395. return;
  396. }
  397. }
  398. do
  399. {
  400. blinkStatus(BLINK_ERROR_NO_SD_CARD);
  401. delay(1000);
  402. platform_reset_watchdog();
  403. g_sdcard_present = mountSDCard();
  404. } while (!g_sdcard_present);
  405. bluelog("SD card init succeeded after retry");
  406. }
  407. if (g_sdcard_present)
  408. {
  409. if (SD.clusterCount() == 0)
  410. {
  411. bluelog("SD card without filesystem!");
  412. }
  413. print_sd_info();
  414. reinitSCSI();
  415. }
  416. bluelog("Initialization complete!");
  417. if (g_sdcard_present)
  418. {
  419. init_logfile();
  420. if (ini_getbool("SCSI", "DisableStatusLED", false, CONFIGFILE))
  421. {
  422. platform_disable_led();
  423. }
  424. }
  425. }
  426. extern "C" void bluescsi_main_loop(void)
  427. {
  428. static uint32_t sd_card_check_time = 0;
  429. platform_reset_watchdog();
  430. #ifdef PLATFORM_HAS_INITIATOR_MODE
  431. if (platform_is_initiator_mode_enabled())
  432. {
  433. scsiInitiatorMainLoop();
  434. save_logfile();
  435. }
  436. else
  437. #endif
  438. {
  439. scsiPoll();
  440. scsiDiskPoll();
  441. scsiLogPhaseChange(scsiDev.phase);
  442. // Save log periodically during status phase if there are new messages.
  443. if (scsiDev.phase == STATUS)
  444. {
  445. save_logfile();
  446. }
  447. }
  448. if (g_sdcard_present)
  449. {
  450. // Check SD card status for hotplug
  451. if (scsiDev.phase == BUS_FREE &&
  452. (uint32_t)(millis() - sd_card_check_time) > 5000)
  453. {
  454. sd_card_check_time = millis();
  455. uint32_t ocr;
  456. if (!SD.card()->readOCR(&ocr))
  457. {
  458. if (!SD.card()->readOCR(&ocr))
  459. {
  460. g_sdcard_present = false;
  461. bluelog("SD card removed, trying to reinit");
  462. }
  463. }
  464. }
  465. }
  466. if (!g_sdcard_present)
  467. {
  468. // Try to remount SD card
  469. do
  470. {
  471. g_sdcard_present = mountSDCard();
  472. if (g_sdcard_present)
  473. {
  474. bluelog("SD card reinit succeeded");
  475. print_sd_info();
  476. reinitSCSI();
  477. init_logfile();
  478. }
  479. else if (!g_romdrive_active)
  480. {
  481. blinkStatus(BLINK_ERROR_NO_SD_CARD);
  482. delay(1000);
  483. platform_reset_watchdog();
  484. }
  485. } while (!g_sdcard_present && !g_romdrive_active);
  486. }
  487. else
  488. {
  489. }
  490. }