ZuluSCSI.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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. SdFs SD;
  53. FsFile g_logfile;
  54. /************************************/
  55. /* Status reporting by blinking led */
  56. /************************************/
  57. #define BLINK_STATUS_OK 1
  58. #define BLINK_ERROR_NO_IMAGES 3
  59. #define BLINK_ERROR_NO_SD_CARD 5
  60. void blinkStatus(int count)
  61. {
  62. for (int i = 0; i < count; i++)
  63. {
  64. LED_ON();
  65. delay(250);
  66. LED_OFF();
  67. delay(250);
  68. }
  69. }
  70. extern "C" void s2s_ledOn()
  71. {
  72. LED_ON();
  73. }
  74. extern "C" void s2s_ledOff()
  75. {
  76. LED_OFF();
  77. }
  78. /**************/
  79. /* Log saving */
  80. /**************/
  81. void save_logfile(bool always = false)
  82. {
  83. static uint32_t prev_log_pos = 0;
  84. static uint32_t prev_log_len = 0;
  85. static uint32_t prev_log_save = 0;
  86. uint32_t loglen = azlog_get_buffer_len();
  87. if (loglen != prev_log_len)
  88. {
  89. // When debug is off, save log at most every LOG_SAVE_INTERVAL_MS
  90. // When debug is on, save after every SCSI command.
  91. if (always || g_azlog_debug || (LOG_SAVE_INTERVAL_MS > 0 && (uint32_t)(millis() - prev_log_save) > LOG_SAVE_INTERVAL_MS))
  92. {
  93. g_logfile.write(azlog_get_buffer(&prev_log_pos));
  94. g_logfile.flush();
  95. prev_log_len = loglen;
  96. prev_log_save = millis();
  97. }
  98. }
  99. }
  100. void init_logfile()
  101. {
  102. static bool first_open_after_boot = true;
  103. bool truncate = first_open_after_boot;
  104. int flags = O_WRONLY | O_CREAT | (truncate ? O_TRUNC : O_APPEND);
  105. g_logfile = SD.open(LOGFILE, flags);
  106. if (!g_logfile.isOpen())
  107. {
  108. azlog("Failed to open log file: ", SD.sdErrorCode());
  109. }
  110. save_logfile(true);
  111. first_open_after_boot = false;
  112. }
  113. void print_sd_info()
  114. {
  115. uint64_t size = (uint64_t)SD.vol()->clusterCount() * SD.vol()->bytesPerCluster();
  116. azlog("SD card detected, FAT", (int)SD.vol()->fatType(),
  117. " volume size: ", (int)(size / 1024 / 1024), " MB");
  118. cid_t sd_cid;
  119. if(SD.card()->readCID(&sd_cid))
  120. {
  121. azlog("SD MID: ", (uint8_t)sd_cid.mid, ", OID: ", (uint8_t)sd_cid.oid[0], " ", (uint8_t)sd_cid.oid[1]);
  122. char sdname[6] = {sd_cid.pnm[0], sd_cid.pnm[1], sd_cid.pnm[2], sd_cid.pnm[3], sd_cid.pnm[4], 0};
  123. azlog("SD Name: ", sdname);
  124. char sdyear[5] = "2000";
  125. sdyear[2] += sd_cid.mdt_year_high;
  126. sdyear[3] += sd_cid.mdt_year_low;
  127. azlog("SD Date: ", (int)sd_cid.mdt_month, "/", sdyear);
  128. azlog("SD Serial: ", sd_cid.psn);
  129. }
  130. }
  131. /*********************************/
  132. /* Harddisk image file handling */
  133. /*********************************/
  134. // Iterate over the root path in the SD card looking for candidate image files.
  135. bool findHDDImages()
  136. {
  137. char imgdir[MAX_FILE_PATH];
  138. ini_gets("SCSI", "Dir", "/", imgdir, sizeof(imgdir), CONFIGFILE);
  139. int dirindex = 0;
  140. azlog("Finding HDD images in directory ", imgdir, ":");
  141. SdFile root;
  142. root.open(imgdir);
  143. if (!root.isOpen())
  144. {
  145. azlog("Could not open directory: ", imgdir);
  146. }
  147. SdFile file;
  148. bool imageReady;
  149. bool foundImage = false;
  150. int usedDefaultId = 0;
  151. while (1)
  152. {
  153. if (!file.openNext(&root, O_READ))
  154. {
  155. // Check for additional directories with ini keys Dir1..Dir9
  156. while (dirindex < 10)
  157. {
  158. dirindex++;
  159. char key[5] = "Dir0";
  160. key[3] += dirindex;
  161. if (ini_gets("SCSI", key, "", imgdir, sizeof(imgdir), CONFIGFILE) != 0)
  162. {
  163. break;
  164. }
  165. }
  166. if (imgdir[0] != '\0')
  167. {
  168. azlog("Finding HDD images in additional directory Dir", (int)dirindex, " = \"", imgdir, "\":");
  169. root.open(imgdir);
  170. if (!root.isOpen())
  171. {
  172. azlog("-- Could not open directory: ", imgdir);
  173. }
  174. continue;
  175. }
  176. else
  177. {
  178. break;
  179. }
  180. }
  181. char name[MAX_FILE_PATH+1];
  182. if(!file.isDir()) {
  183. file.getName(name, MAX_FILE_PATH+1);
  184. file.close();
  185. bool is_hd = (tolower(name[0]) == 'h' && tolower(name[1]) == 'd');
  186. bool is_cd = (tolower(name[0]) == 'c' && tolower(name[1]) == 'd');
  187. bool is_fd = (tolower(name[0]) == 'f' && tolower(name[1]) == 'd');
  188. bool is_mo = (tolower(name[0]) == 'm' && tolower(name[1]) == 'o');
  189. bool is_re = (tolower(name[0]) == 'r' && tolower(name[1]) == 'e');
  190. bool is_tp = (tolower(name[0]) == 't' && tolower(name[1]) == 'p');
  191. if (is_hd || is_cd || is_fd || is_mo || is_re || is_tp)
  192. {
  193. // Check file extension
  194. // We accept anything except known compressed files
  195. bool is_compressed = false;
  196. const char *extension = strrchr(name, '.');
  197. if (extension)
  198. {
  199. const char *archive_exts[] = {
  200. ".tar", ".tgz", ".gz", ".bz2", ".tbz2", ".xz", ".zst", ".z",
  201. ".zip", ".zipx", ".rar", ".lzh", ".7z", ".s7z", ".arj",
  202. ".dmg",
  203. NULL
  204. };
  205. for (int i = 0; archive_exts[i]; i++)
  206. {
  207. if (strcasecmp(extension, archive_exts[i]) == 0)
  208. {
  209. is_compressed = true;
  210. break;
  211. }
  212. }
  213. }
  214. if (is_compressed)
  215. {
  216. azlog("-- Ignoring compressed file ", name);
  217. continue;
  218. }
  219. // Defaults for Hard Disks
  220. int id = 1; // 0 and 3 are common in Macs for physical HD and CD, so avoid them.
  221. int lun = 0;
  222. int blk = 512;
  223. if (is_cd)
  224. {
  225. // Use 2048 as the default sector size for CD-ROMs
  226. blk = 2048;
  227. }
  228. // Parse SCSI device ID
  229. int file_name_length = strlen(name);
  230. if(file_name_length > 2) { // HD[N]
  231. int tmp_id = name[HDIMG_ID_POS] - '0';
  232. if(tmp_id > -1 && tmp_id < 8)
  233. {
  234. id = tmp_id; // If valid id, set it, else use default
  235. }
  236. else
  237. {
  238. id = usedDefaultId++;
  239. }
  240. }
  241. // Parse SCSI LUN number
  242. if(file_name_length > 3) { // HD0[N]
  243. int tmp_lun = name[HDIMG_LUN_POS] - '0';
  244. if(tmp_lun > -1 && tmp_lun < NUM_SCSILUN) {
  245. lun = tmp_lun; // If valid id, set it, else use default
  246. }
  247. }
  248. // Parse block size (HD00_NNNN)
  249. const char *blksize = strchr(name, '_');
  250. if (blksize)
  251. {
  252. int blktmp = strtoul(blksize + 1, NULL, 10);
  253. if (blktmp == 256 || blktmp == 512 || blktmp == 1024 ||
  254. blktmp == 2048 || blktmp == 4096 || blktmp == 8192)
  255. {
  256. blk = blktmp;
  257. }
  258. }
  259. // Add the directory name to get the full file path
  260. char fullname[MAX_FILE_PATH * 2 + 2] = {0};
  261. strncpy(fullname, imgdir, MAX_FILE_PATH);
  262. if (fullname[strlen(fullname) - 1] != '/') strcat(fullname, "/");
  263. strcat(fullname, name);
  264. // Check whether this SCSI ID has been configured yet
  265. const S2S_TargetCfg* cfg = s2s_getConfigByIndex(id);
  266. if (cfg && (cfg->scsiId & S2S_CFG_TARGET_ENABLED))
  267. {
  268. azlog("-- Ignoring ", fullname, ", SCSI ID ", id, " is already in use!");
  269. continue;
  270. }
  271. // Open the image file
  272. if(id < NUM_SCSIID && lun < NUM_SCSILUN) {
  273. azlog("-- Opening ", fullname, " for id:", id, " lun:", lun);
  274. // Type mapping based on filename.
  275. // If type is FIXED, the type can still be overridden in .ini file.
  276. S2S_CFG_TYPE type = S2S_CFG_FIXED;
  277. if (is_cd) type = S2S_CFG_OPTICAL;
  278. if (is_fd) type = S2S_CFG_FLOPPY_14MB;
  279. if (is_mo) type = S2S_CFG_MO;
  280. if (is_re) type = S2S_CFG_REMOVEABLE;
  281. if (is_tp) type = S2S_CFG_SEQUENTIAL;
  282. imageReady = scsiDiskOpenHDDImage(id, fullname, id, lun, blk, type);
  283. if(imageReady)
  284. {
  285. foundImage = true;
  286. }
  287. else
  288. {
  289. azlog("---- Failed to load image");
  290. }
  291. } else {
  292. azlog("-- Invalid lun or id for image ", fullname);
  293. }
  294. }
  295. }
  296. }
  297. if(usedDefaultId > 0) {
  298. azlog("Some images did not specify a SCSI ID. Last file will be used at ID ", usedDefaultId);
  299. }
  300. root.close();
  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. azlog("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. if (ini_getbool("SCSI", "Debug", 0, CONFIGFILE))
  328. {
  329. g_azlog_debug = true;
  330. }
  331. }
  332. /*********************************/
  333. /* Main SCSI handling loop */
  334. /*********************************/
  335. static void reinitSCSI()
  336. {
  337. scsiDiskResetImages();
  338. readSCSIDeviceConfig();
  339. findHDDImages();
  340. // Error if there are 0 image files
  341. if (scsiDiskCheckAnyImagesConfigured())
  342. {
  343. // Ok, there is an image
  344. blinkStatus(BLINK_STATUS_OK);
  345. }
  346. else
  347. {
  348. #if RAW_FALLBACK_ENABLE
  349. azlog("No images found, enabling RAW fallback partition");
  350. scsiDiskOpenHDDImage(RAW_FALLBACK_SCSI_ID, "RAW:0:0xFFFFFFFF", RAW_FALLBACK_SCSI_ID, 0,
  351. RAW_FALLBACK_BLOCKSIZE);
  352. #else
  353. azlog("No valid image files found!");
  354. #endif
  355. blinkStatus(BLINK_ERROR_NO_IMAGES);
  356. }
  357. scsiPhyReset();
  358. scsiDiskInit();
  359. scsiInit();
  360. }
  361. extern "C" void zuluscsi_setup(void)
  362. {
  363. azplatform_init();
  364. azplatform_late_init();
  365. if(!SD.begin(SD_CONFIG) && (!SD.card() || SD.sdErrorCode() != 0))
  366. {
  367. azlog("SD card init failed, sdErrorCode: ", (int)SD.sdErrorCode(),
  368. " sdErrorData: ", (int)SD.sdErrorData());
  369. do
  370. {
  371. blinkStatus(BLINK_ERROR_NO_SD_CARD);
  372. delay(1000);
  373. azplatform_reset_watchdog();
  374. } while (!SD.begin(SD_CONFIG) && (!SD.card() || SD.sdErrorCode() != 0));
  375. azlog("SD card init succeeded after retry");
  376. }
  377. if (SD.clusterCount() == 0)
  378. {
  379. azlog("SD card without filesystem!");
  380. }
  381. print_sd_info();
  382. reinitSCSI();
  383. azlog("Initialization complete!");
  384. azlog("Platform: ", g_azplatform_name);
  385. azlog("FW Version: ", g_azlog_firmwareversion);
  386. init_logfile();
  387. }
  388. extern "C" void zuluscsi_main_loop(void)
  389. {
  390. static uint32_t sd_card_check_time = 0;
  391. azplatform_reset_watchdog();
  392. scsiPoll();
  393. scsiDiskPoll();
  394. scsiLogPhaseChange(scsiDev.phase);
  395. // Save log periodically during status phase if there are new messages.
  396. if (scsiDev.phase == STATUS)
  397. {
  398. save_logfile();
  399. }
  400. // Check SD card status for hotplug
  401. if (scsiDev.phase == BUS_FREE &&
  402. (uint32_t)(millis() - sd_card_check_time) > 5000)
  403. {
  404. sd_card_check_time = millis();
  405. uint32_t ocr;
  406. if (!SD.card()->readOCR(&ocr))
  407. {
  408. if (!SD.card()->readOCR(&ocr))
  409. {
  410. azlog("SD card removed, trying to reinit");
  411. do
  412. {
  413. blinkStatus(BLINK_ERROR_NO_SD_CARD);
  414. delay(1000);
  415. azplatform_reset_watchdog();
  416. } while (!SD.begin(SD_CONFIG) && (!SD.card() || SD.sdErrorCode() != 0));
  417. azlog("SD card reinit succeeded");
  418. print_sd_info();
  419. reinitSCSI();
  420. init_logfile();
  421. }
  422. }
  423. }
  424. }