ZuluSCSI.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. /*
  2. * ZuluSCSI
  3. * Copyright (c) 2022 Rabbit Hole Computing
  4. *
  5. * This project is based on BlueSCSI:
  6. *
  7. * BlueSCSI
  8. * Copyright (c) 2021 Eric Helgeson, Androda
  9. *
  10. * This file is free software: you may copy, redistribute and/or modify it
  11. * under the terms of the GNU General Public License as published by the
  12. * Free Software Foundation, either version 2 of the License, or (at your
  13. * option) any later version.
  14. *
  15. * This file is distributed in the hope that it will be useful, but
  16. * WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  18. * General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with this program. If not, see https://github.com/erichelgeson/bluescsi.
  22. *
  23. * This file incorporates work covered by the following copyright and
  24. * permission notice:
  25. *
  26. * Copyright (c) 2019 komatsu
  27. *
  28. * Permission to use, copy, modify, and/or distribute this software
  29. * for any purpose with or without fee is hereby granted, provided
  30. * that the above copyright notice and this permission notice appear
  31. * in all copies.
  32. *
  33. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
  34. * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
  35. * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
  36. * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
  37. * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  38. * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  39. * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  40. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  41. */
  42. #include <SdFat.h>
  43. #include <minIni.h>
  44. #include <string.h>
  45. #include <strings.h>
  46. #include <ctype.h>
  47. #include "ZuluSCSI_config.h"
  48. #include "ZuluSCSI_platform.h"
  49. #include "ZuluSCSI_log.h"
  50. #include "ZuluSCSI_log_trace.h"
  51. #include "ZuluSCSI_disk.h"
  52. #include "ZuluSCSI_initiator.h"
  53. SdFs SD;
  54. FsFile g_logfile;
  55. /************************************/
  56. /* Status reporting by blinking led */
  57. /************************************/
  58. #define BLINK_STATUS_OK 1
  59. #define BLINK_ERROR_NO_IMAGES 3
  60. #define BLINK_ERROR_NO_SD_CARD 5
  61. void blinkStatus(int count)
  62. {
  63. for (int i = 0; i < count; i++)
  64. {
  65. LED_ON();
  66. delay(250);
  67. LED_OFF();
  68. delay(250);
  69. }
  70. }
  71. extern "C" void s2s_ledOn()
  72. {
  73. LED_ON();
  74. }
  75. extern "C" void s2s_ledOff()
  76. {
  77. LED_OFF();
  78. }
  79. /**************/
  80. /* Log saving */
  81. /**************/
  82. void save_logfile(bool always = false)
  83. {
  84. static uint32_t prev_log_pos = 0;
  85. static uint32_t prev_log_len = 0;
  86. static uint32_t prev_log_save = 0;
  87. uint32_t loglen = azlog_get_buffer_len();
  88. if (loglen != prev_log_len)
  89. {
  90. // When debug is off, save log at most every LOG_SAVE_INTERVAL_MS
  91. // When debug is on, save after every SCSI command.
  92. if (always || g_azlog_debug || (LOG_SAVE_INTERVAL_MS > 0 && (uint32_t)(millis() - prev_log_save) > LOG_SAVE_INTERVAL_MS))
  93. {
  94. g_logfile.write(azlog_get_buffer(&prev_log_pos));
  95. g_logfile.flush();
  96. prev_log_len = loglen;
  97. prev_log_save = millis();
  98. }
  99. }
  100. }
  101. void init_logfile()
  102. {
  103. static bool first_open_after_boot = true;
  104. bool truncate = first_open_after_boot;
  105. int flags = O_WRONLY | O_CREAT | (truncate ? O_TRUNC : O_APPEND);
  106. g_logfile = SD.open(LOGFILE, flags);
  107. if (!g_logfile.isOpen())
  108. {
  109. azlog("Failed to open log file: ", SD.sdErrorCode());
  110. }
  111. save_logfile(true);
  112. first_open_after_boot = false;
  113. }
  114. void print_sd_info()
  115. {
  116. uint64_t size = (uint64_t)SD.vol()->clusterCount() * SD.vol()->bytesPerCluster();
  117. azlog("SD card detected, FAT", (int)SD.vol()->fatType(),
  118. " volume size: ", (int)(size / 1024 / 1024), " MB");
  119. cid_t sd_cid;
  120. if(SD.card()->readCID(&sd_cid))
  121. {
  122. azlog("SD MID: ", (uint8_t)sd_cid.mid, ", OID: ", (uint8_t)sd_cid.oid[0], " ", (uint8_t)sd_cid.oid[1]);
  123. char sdname[6] = {sd_cid.pnm[0], sd_cid.pnm[1], sd_cid.pnm[2], sd_cid.pnm[3], sd_cid.pnm[4], 0};
  124. azlog("SD Name: ", sdname);
  125. char sdyear[5] = "2000";
  126. sdyear[2] += sd_cid.mdt_year_high;
  127. sdyear[3] += sd_cid.mdt_year_low;
  128. azlog("SD Date: ", (int)sd_cid.mdt_month, "/", sdyear);
  129. azlog("SD Serial: ", sd_cid.psn);
  130. }
  131. }
  132. /*********************************/
  133. /* Harddisk image file handling */
  134. /*********************************/
  135. // Iterate over the root path in the SD card looking for candidate image files.
  136. bool findHDDImages()
  137. {
  138. char imgdir[MAX_FILE_PATH];
  139. ini_gets("SCSI", "Dir", "/", imgdir, sizeof(imgdir), CONFIGFILE);
  140. int dirindex = 0;
  141. azlog("Finding HDD images in directory ", imgdir, ":");
  142. SdFile root;
  143. root.open(imgdir);
  144. if (!root.isOpen())
  145. {
  146. azlog("Could not open directory: ", imgdir);
  147. }
  148. SdFile file;
  149. bool imageReady;
  150. bool foundImage = false;
  151. int usedDefaultId = 0;
  152. while (1)
  153. {
  154. if (!file.openNext(&root, O_READ))
  155. {
  156. // Check for additional directories with ini keys Dir1..Dir9
  157. while (dirindex < 10)
  158. {
  159. dirindex++;
  160. char key[5] = "Dir0";
  161. key[3] += dirindex;
  162. if (ini_gets("SCSI", key, "", imgdir, sizeof(imgdir), CONFIGFILE) != 0)
  163. {
  164. break;
  165. }
  166. }
  167. if (imgdir[0] != '\0')
  168. {
  169. azlog("Finding HDD images in additional directory Dir", (int)dirindex, " = \"", imgdir, "\":");
  170. root.open(imgdir);
  171. if (!root.isOpen())
  172. {
  173. azlog("-- Could not open directory: ", imgdir);
  174. }
  175. continue;
  176. }
  177. else
  178. {
  179. break;
  180. }
  181. }
  182. char name[MAX_FILE_PATH+1];
  183. if(!file.isDir()) {
  184. file.getName(name, MAX_FILE_PATH+1);
  185. file.close();
  186. bool is_hd = (tolower(name[0]) == 'h' && tolower(name[1]) == 'd');
  187. bool is_cd = (tolower(name[0]) == 'c' && tolower(name[1]) == 'd');
  188. bool is_fd = (tolower(name[0]) == 'f' && tolower(name[1]) == 'd');
  189. bool is_mo = (tolower(name[0]) == 'm' && tolower(name[1]) == 'o');
  190. bool is_re = (tolower(name[0]) == 'r' && tolower(name[1]) == 'e');
  191. bool is_tp = (tolower(name[0]) == 't' && tolower(name[1]) == 'p');
  192. if (is_hd || is_cd || is_fd || is_mo || is_re || is_tp)
  193. {
  194. // Check file extension
  195. // We accept anything except known compressed files
  196. bool is_compressed = false;
  197. const char *extension = strrchr(name, '.');
  198. if (extension)
  199. {
  200. const char *archive_exts[] = {
  201. ".tar", ".tgz", ".gz", ".bz2", ".tbz2", ".xz", ".zst", ".z",
  202. ".zip", ".zipx", ".rar", ".lzh", ".7z", ".s7z", ".arj",
  203. ".dmg",
  204. NULL
  205. };
  206. for (int i = 0; archive_exts[i]; i++)
  207. {
  208. if (strcasecmp(extension, archive_exts[i]) == 0)
  209. {
  210. is_compressed = true;
  211. break;
  212. }
  213. }
  214. }
  215. if (is_compressed)
  216. {
  217. azlog("-- Ignoring compressed file ", name);
  218. continue;
  219. }
  220. // Defaults for Hard Disks
  221. int id = 1; // 0 and 3 are common in Macs for physical HD and CD, so avoid them.
  222. int lun = 0;
  223. int blk = 512;
  224. if (is_cd)
  225. {
  226. // Use 2048 as the default sector size for CD-ROMs
  227. blk = 2048;
  228. }
  229. // Parse SCSI device ID
  230. int file_name_length = strlen(name);
  231. if(file_name_length > 2) { // HD[N]
  232. int tmp_id = name[HDIMG_ID_POS] - '0';
  233. if(tmp_id > -1 && tmp_id < 8)
  234. {
  235. id = tmp_id; // If valid id, set it, else use default
  236. }
  237. else
  238. {
  239. id = usedDefaultId++;
  240. }
  241. }
  242. // Parse SCSI LUN number
  243. if(file_name_length > 3) { // HD0[N]
  244. int tmp_lun = name[HDIMG_LUN_POS] - '0';
  245. if(tmp_lun > -1 && tmp_lun < NUM_SCSILUN) {
  246. lun = tmp_lun; // If valid id, set it, else use default
  247. }
  248. }
  249. // Parse block size (HD00_NNNN)
  250. const char *blksize = strchr(name, '_');
  251. if (blksize)
  252. {
  253. int blktmp = strtoul(blksize + 1, NULL, 10);
  254. if (blktmp == 256 || blktmp == 512 || blktmp == 1024 ||
  255. blktmp == 2048 || blktmp == 4096 || blktmp == 8192)
  256. {
  257. blk = blktmp;
  258. }
  259. }
  260. // Add the directory name to get the full file path
  261. char fullname[MAX_FILE_PATH * 2 + 2] = {0};
  262. strncpy(fullname, imgdir, MAX_FILE_PATH);
  263. if (fullname[strlen(fullname) - 1] != '/') strcat(fullname, "/");
  264. strcat(fullname, name);
  265. // Check whether this SCSI ID has been configured yet
  266. const S2S_TargetCfg* cfg = s2s_getConfigByIndex(id);
  267. if (cfg && (cfg->scsiId & S2S_CFG_TARGET_ENABLED))
  268. {
  269. azlog("-- Ignoring ", fullname, ", SCSI ID ", id, " is already in use!");
  270. continue;
  271. }
  272. // Open the image file
  273. if(id < NUM_SCSIID && lun < NUM_SCSILUN) {
  274. azlog("-- Opening ", fullname, " for id:", id, " lun:", lun);
  275. // Type mapping based on filename.
  276. // If type is FIXED, the type can still be overridden in .ini file.
  277. S2S_CFG_TYPE type = S2S_CFG_FIXED;
  278. if (is_cd) type = S2S_CFG_OPTICAL;
  279. if (is_fd) type = S2S_CFG_FLOPPY_14MB;
  280. if (is_mo) type = S2S_CFG_MO;
  281. if (is_re) type = S2S_CFG_REMOVEABLE;
  282. if (is_tp) type = S2S_CFG_SEQUENTIAL;
  283. imageReady = scsiDiskOpenHDDImage(id, fullname, id, lun, blk, type);
  284. if(imageReady)
  285. {
  286. foundImage = true;
  287. }
  288. else
  289. {
  290. azlog("---- Failed to load image");
  291. }
  292. } else {
  293. azlog("-- Invalid lun or id for image ", fullname);
  294. }
  295. }
  296. }
  297. }
  298. if(usedDefaultId > 0) {
  299. azlog("Some images did not specify a SCSI ID. Last file will be used at ID ", usedDefaultId);
  300. }
  301. root.close();
  302. // Print SCSI drive map
  303. for (int i = 0; i < NUM_SCSIID; i++)
  304. {
  305. const S2S_TargetCfg* cfg = s2s_getConfigByIndex(i);
  306. if (cfg && (cfg->scsiId & S2S_CFG_TARGET_ENABLED))
  307. {
  308. int capacity_kB = ((uint64_t)cfg->scsiSectors * cfg->bytesPerSector) / 1024;
  309. azlog("SCSI ID:", (int)(cfg->scsiId & 7),
  310. " BlockSize:", (int)cfg->bytesPerSector,
  311. " Type:", (int)cfg->deviceType,
  312. " Quirks:", (int)cfg->quirks,
  313. " ImageSize:", capacity_kB, "kB");
  314. }
  315. }
  316. return foundImage;
  317. }
  318. /************************/
  319. /* Config file loading */
  320. /************************/
  321. void readSCSIDeviceConfig()
  322. {
  323. s2s_configInit(&scsiDev.boardCfg);
  324. for (int i = 0; i < NUM_SCSIID; i++)
  325. {
  326. scsiDiskLoadConfig(i);
  327. }
  328. }
  329. /*********************************/
  330. /* Main SCSI handling loop */
  331. /*********************************/
  332. static bool mountSDCard()
  333. {
  334. // Check for the common case, FAT filesystem as first partition
  335. if (SD.begin(SD_CONFIG))
  336. return true;
  337. // Do we have any kind of card?
  338. if (!SD.card() || SD.sdErrorCode() != 0)
  339. return false;
  340. // Try to mount the whole card as FAT (without partition table)
  341. if (static_cast<FsVolume*>(&SD)->begin(SD.card(), true, 0))
  342. return true;
  343. // Failed to mount FAT filesystem, but card can still be accessed as raw image
  344. return true;
  345. }
  346. static void reinitSCSI()
  347. {
  348. if (ini_getbool("SCSI", "Debug", 0, CONFIGFILE))
  349. {
  350. g_azlog_debug = true;
  351. }
  352. #ifdef PLATFORM_HAS_INITIATOR_MODE
  353. if (azplatform_is_initiator_mode_enabled())
  354. {
  355. // Initialize scsiDev to zero values even though it is not used
  356. scsiInit();
  357. // Initializer initiator mode state machine
  358. scsiInitiatorInit();
  359. blinkStatus(BLINK_STATUS_OK);
  360. return;
  361. }
  362. #endif
  363. scsiDiskResetImages();
  364. readSCSIDeviceConfig();
  365. findHDDImages();
  366. // Error if there are 0 image files
  367. if (scsiDiskCheckAnyImagesConfigured())
  368. {
  369. // Ok, there is an image
  370. blinkStatus(BLINK_STATUS_OK);
  371. }
  372. else
  373. {
  374. #if RAW_FALLBACK_ENABLE
  375. azlog("No images found, enabling RAW fallback partition");
  376. scsiDiskOpenHDDImage(RAW_FALLBACK_SCSI_ID, "RAW:0:0xFFFFFFFF", RAW_FALLBACK_SCSI_ID, 0,
  377. RAW_FALLBACK_BLOCKSIZE);
  378. #else
  379. azlog("No valid image files found!");
  380. #endif
  381. blinkStatus(BLINK_ERROR_NO_IMAGES);
  382. }
  383. scsiPhyReset();
  384. scsiDiskInit();
  385. scsiInit();
  386. }
  387. extern "C" void zuluscsi_setup(void)
  388. {
  389. azplatform_init();
  390. azplatform_late_init();
  391. if(!mountSDCard())
  392. {
  393. azlog("SD card init failed, sdErrorCode: ", (int)SD.sdErrorCode(),
  394. " sdErrorData: ", (int)SD.sdErrorData());
  395. do
  396. {
  397. blinkStatus(BLINK_ERROR_NO_SD_CARD);
  398. delay(1000);
  399. azplatform_reset_watchdog();
  400. } while (!mountSDCard());
  401. azlog("SD card init succeeded after retry");
  402. }
  403. if (SD.clusterCount() == 0)
  404. {
  405. azlog("SD card without filesystem!");
  406. }
  407. print_sd_info();
  408. reinitSCSI();
  409. azlog("Initialization complete!");
  410. azlog("Platform: ", g_azplatform_name);
  411. azlog("FW Version: ", g_azlog_firmwareversion);
  412. init_logfile();
  413. }
  414. extern "C" void zuluscsi_main_loop(void)
  415. {
  416. static uint32_t sd_card_check_time = 0;
  417. azplatform_reset_watchdog();
  418. #ifdef PLATFORM_HAS_INITIATOR_MODE
  419. if (azplatform_is_initiator_mode_enabled())
  420. {
  421. scsiInitiatorMainLoop();
  422. save_logfile();
  423. }
  424. else
  425. #endif
  426. {
  427. scsiPoll();
  428. scsiDiskPoll();
  429. scsiLogPhaseChange(scsiDev.phase);
  430. // Save log periodically during status phase if there are new messages.
  431. if (scsiDev.phase == STATUS)
  432. {
  433. save_logfile();
  434. }
  435. }
  436. // Check SD card status for hotplug
  437. if (scsiDev.phase == BUS_FREE &&
  438. (uint32_t)(millis() - sd_card_check_time) > 5000)
  439. {
  440. sd_card_check_time = millis();
  441. uint32_t ocr;
  442. if (!SD.card()->readOCR(&ocr))
  443. {
  444. if (!SD.card()->readOCR(&ocr))
  445. {
  446. azlog("SD card removed, trying to reinit");
  447. do
  448. {
  449. blinkStatus(BLINK_ERROR_NO_SD_CARD);
  450. delay(1000);
  451. azplatform_reset_watchdog();
  452. } while (!mountSDCard());
  453. azlog("SD card reinit succeeded");
  454. print_sd_info();
  455. reinitSCSI();
  456. init_logfile();
  457. }
  458. }
  459. }
  460. }