BlueSCSI.cpp 17 KB

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