BlueSCSI.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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 = log_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_log_debug || (LOG_SAVE_INTERVAL_MS > 0 && (uint32_t)(millis() - prev_log_save) > LOG_SAVE_INTERVAL_MS))
  68. {
  69. g_logfile.write(log_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. log("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. log("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. log("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. log("SD Name: ", sdname);
  100. log("SD Date: ", (int)sd_cid.mdtMonth(), "/", sd_cid.mdtYear());
  101. log("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. log("Finding HDD images in directory ", imgdir, ":");
  114. SdFile root;
  115. root.open(imgdir);
  116. if (!root.isOpen())
  117. {
  118. log("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. log("Finding HDD images in additional directory Dir", (int)dirindex, " = \"", imgdir, "\":");
  142. root.open(imgdir);
  143. if (!root.isOpen())
  144. {
  145. log("-- 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. log("-- 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. const S2S_TargetCfg* cfg = s2s_getConfigById(id);
  250. if (cfg)
  251. {
  252. log("-- Ignoring ", fullname, ", SCSI ID ", id, " is already in use!");
  253. continue;
  254. }
  255. // Apple computers reserve ID 7, so warn the user this configuration wont work
  256. if(id == 7 && cfg->quirks == S2S_CFG_QUIRKS_APPLE )
  257. {
  258. bluelog("-- Ignoring ", fullname, ", SCSI ID ", id, " Quirks set to Apple so can not use SCSI ID 7!");
  259. continue;
  260. }
  261. // Type mapping based on filename.
  262. // If type is FIXED, the type can still be overridden in .ini file.
  263. S2S_CFG_TYPE type = S2S_CFG_FIXED;
  264. if (is_cd) type = S2S_CFG_OPTICAL;
  265. if (is_fd) type = S2S_CFG_FLOPPY_14MB;
  266. if (is_mo) type = S2S_CFG_MO;
  267. if (is_re) type = S2S_CFG_REMOVEABLE;
  268. if (is_tp) type = S2S_CFG_SEQUENTIAL;
  269. // Open the image file
  270. if (id < NUM_SCSIID && is_romdrive)
  271. {
  272. log("-- Loading ROM drive from ", fullname, " for id:", id);
  273. imageReady = scsiDiskProgramRomDrive(fullname, id, blk, type);
  274. if (imageReady)
  275. {
  276. foundImage = true;
  277. }
  278. }
  279. else if(id < NUM_SCSIID && lun < NUM_SCSILUN) {
  280. log("-- Opening ", fullname, " for id:", id, " lun:", lun);
  281. imageReady = scsiDiskOpenHDDImage(id, fullname, id, lun, blk, type);
  282. if(imageReady)
  283. {
  284. foundImage = true;
  285. }
  286. else
  287. {
  288. log("---- Failed to load image");
  289. }
  290. } else {
  291. log("-- Invalid lun or id for image ", fullname);
  292. }
  293. }
  294. }
  295. }
  296. if(usedDefaultId > 0) {
  297. log("Some images did not specify a SCSI ID. Last file will be used at ID ", usedDefaultId);
  298. }
  299. root.close();
  300. g_romdrive_active = scsiDiskActivateRomDrive();
  301. // Print SCSI drive map
  302. for (int i = 0; i < NUM_SCSIID; i++)
  303. {
  304. const S2S_TargetCfg* cfg = s2s_getConfigByIndex(i);
  305. if (cfg && (cfg->scsiId & S2S_CFG_TARGET_ENABLED))
  306. {
  307. int capacity_kB = ((uint64_t)cfg->scsiSectors * cfg->bytesPerSector) / 1024;
  308. log("SCSI ID:", (int)(cfg->scsiId & 7),
  309. " BlockSize:", (int)cfg->bytesPerSector,
  310. " Type:", (int)cfg->deviceType,
  311. " Quirks:", (int)cfg->quirks,
  312. " ImageSize:", capacity_kB, "kB");
  313. }
  314. }
  315. return foundImage;
  316. }
  317. /************************/
  318. /* Config file loading */
  319. /************************/
  320. void readSCSIDeviceConfig()
  321. {
  322. s2s_configInit(&scsiDev.boardCfg);
  323. for (int i = 0; i < NUM_SCSIID; i++)
  324. {
  325. scsiDiskLoadConfig(i);
  326. }
  327. }
  328. /*********************************/
  329. /* Main SCSI handling loop */
  330. /*********************************/
  331. static bool mountSDCard()
  332. {
  333. // Check for the common case, FAT filesystem as first partition
  334. if (SD.begin(SD_CONFIG))
  335. return true;
  336. // Do we have any kind of card?
  337. if (!SD.card() || SD.sdErrorCode() != 0)
  338. return false;
  339. // Try to mount the whole card as FAT (without partition table)
  340. if (static_cast<FsVolume*>(&SD)->begin(SD.card(), true, 0))
  341. return true;
  342. // Failed to mount FAT filesystem, but card can still be accessed as raw image
  343. return true;
  344. }
  345. static void reinitSCSI()
  346. {
  347. if (ini_getbool("SCSI", "Debug", 0, CONFIGFILE))
  348. {
  349. g_log_debug = true;
  350. }
  351. #ifdef PLATFORM_HAS_INITIATOR_MODE
  352. if (platform_is_initiator_mode_enabled())
  353. {
  354. // Initialize scsiDev to zero values even though it is not used
  355. scsiInit();
  356. // Initializer initiator mode state machine
  357. scsiInitiatorInit();
  358. blinkStatus(BLINK_STATUS_OK);
  359. return;
  360. }
  361. #endif
  362. scsiDiskResetImages();
  363. readSCSIDeviceConfig();
  364. findHDDImages();
  365. // Error if there are 0 image files
  366. if (scsiDiskCheckAnyImagesConfigured())
  367. {
  368. // Ok, there is an image
  369. blinkStatus(BLINK_STATUS_OK);
  370. }
  371. else
  372. {
  373. #if RAW_FALLBACK_ENABLE
  374. log("No images found, enabling RAW fallback partition");
  375. scsiDiskOpenHDDImage(RAW_FALLBACK_SCSI_ID, "RAW:0:0xFFFFFFFF", RAW_FALLBACK_SCSI_ID, 0,
  376. RAW_FALLBACK_BLOCKSIZE);
  377. #else
  378. log("No valid image files found!");
  379. #endif
  380. blinkStatus(BLINK_ERROR_NO_IMAGES);
  381. }
  382. scsiPhyReset();
  383. scsiDiskInit();
  384. scsiInit();
  385. }
  386. extern "C" void bluescsi_setup(void)
  387. {
  388. platform_init();
  389. platform_late_init();
  390. g_sdcard_present = mountSDCard();
  391. if(!g_sdcard_present)
  392. {
  393. log("SD card init failed, sdErrorCode: ", (int)SD.sdErrorCode(),
  394. " sdErrorData: ", (int)SD.sdErrorData());
  395. blinkStatus(BLINK_ERROR_NO_SD_CARD);
  396. if (scsiDiskCheckRomDrive())
  397. {
  398. reinitSCSI();
  399. if (g_romdrive_active)
  400. {
  401. log("Enabled ROM drive without SD card");
  402. return;
  403. }
  404. }
  405. do
  406. {
  407. blinkStatus(BLINK_ERROR_NO_SD_CARD);
  408. delay(1000);
  409. platform_reset_watchdog();
  410. g_sdcard_present = mountSDCard();
  411. } while (!g_sdcard_present);
  412. log("SD card init succeeded after retry");
  413. }
  414. if (g_sdcard_present)
  415. {
  416. if (SD.clusterCount() == 0)
  417. {
  418. log("SD card without filesystem!");
  419. }
  420. print_sd_info();
  421. reinitSCSI();
  422. }
  423. log("Initialization complete!");
  424. if (g_sdcard_present)
  425. {
  426. init_logfile();
  427. if (ini_getbool("SCSI", "DisableStatusLED", false, CONFIGFILE))
  428. {
  429. platform_disable_led();
  430. }
  431. }
  432. }
  433. extern "C" void bluescsi_main_loop(void)
  434. {
  435. static uint32_t sd_card_check_time = 0;
  436. platform_reset_watchdog();
  437. #ifdef PLATFORM_HAS_INITIATOR_MODE
  438. if (platform_is_initiator_mode_enabled())
  439. {
  440. scsiInitiatorMainLoop();
  441. save_logfile();
  442. }
  443. else
  444. #endif
  445. {
  446. scsiPoll();
  447. scsiDiskPoll();
  448. scsiLogPhaseChange(scsiDev.phase);
  449. // Save log periodically during status phase if there are new messages.
  450. if (scsiDev.phase == STATUS)
  451. {
  452. save_logfile();
  453. }
  454. }
  455. if (g_sdcard_present)
  456. {
  457. // Check SD card status for hotplug
  458. if (scsiDev.phase == BUS_FREE &&
  459. (uint32_t)(millis() - sd_card_check_time) > 5000)
  460. {
  461. sd_card_check_time = millis();
  462. uint32_t ocr;
  463. if (!SD.card()->readOCR(&ocr))
  464. {
  465. if (!SD.card()->readOCR(&ocr))
  466. {
  467. g_sdcard_present = false;
  468. log("SD card removed, trying to reinit");
  469. }
  470. }
  471. }
  472. }
  473. if (!g_sdcard_present)
  474. {
  475. // Try to remount SD card
  476. do
  477. {
  478. g_sdcard_present = mountSDCard();
  479. if (g_sdcard_present)
  480. {
  481. log("SD card reinit succeeded");
  482. print_sd_info();
  483. reinitSCSI();
  484. init_logfile();
  485. }
  486. else if (!g_romdrive_active)
  487. {
  488. blinkStatus(BLINK_ERROR_NO_SD_CARD);
  489. delay(1000);
  490. platform_reset_watchdog();
  491. }
  492. } while (!g_sdcard_present && !g_romdrive_active);
  493. }
  494. else
  495. {
  496. }
  497. }