BlueSCSI.cpp 17 KB

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