AzulSCSI.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. /*
  2. * AzulSCSI
  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 <ctype.h>
  46. #include "AzulSCSI_config.h"
  47. #include "AzulSCSI_platform.h"
  48. #include "AzulSCSI_log.h"
  49. #include "AzulSCSI_log_trace.h"
  50. #include "AzulSCSI_disk.h"
  51. SdFs SD;
  52. FsFile g_logfile;
  53. /************************************/
  54. /* Status reporting by blinking led */
  55. /************************************/
  56. #define BLINK_ERROR_NO_IMAGES 3
  57. #define BLINK_ERROR_NO_SD_CARD 5
  58. void blinkStatus(int count)
  59. {
  60. for (int i = 0; i < count; i++)
  61. {
  62. LED_ON();
  63. delay(250);
  64. LED_OFF();
  65. delay(250);
  66. }
  67. }
  68. extern "C" void s2s_ledOn()
  69. {
  70. LED_ON();
  71. }
  72. extern "C" void s2s_ledOff()
  73. {
  74. LED_OFF();
  75. }
  76. /**************/
  77. /* Log saving */
  78. /**************/
  79. void save_logfile(bool always = false)
  80. {
  81. static uint32_t prev_log_pos = 0;
  82. static uint32_t prev_log_len = 0;
  83. static uint32_t prev_log_save = 0;
  84. uint32_t loglen = azlog_get_buffer_len();
  85. if (loglen != prev_log_len)
  86. {
  87. // When debug is off, save log at most every LOG_SAVE_INTERVAL_MS
  88. // When debug is on, save after every SCSI command.
  89. if (always || g_azlog_debug || (LOG_SAVE_INTERVAL_MS > 0 && (uint32_t)(millis() - prev_log_save) > LOG_SAVE_INTERVAL_MS))
  90. {
  91. g_logfile.write(azlog_get_buffer(&prev_log_pos));
  92. g_logfile.flush();
  93. prev_log_len = loglen;
  94. prev_log_save = millis();
  95. }
  96. }
  97. }
  98. void init_logfile()
  99. {
  100. static bool first_open_after_boot = true;
  101. bool truncate = first_open_after_boot;
  102. int flags = O_WRONLY | O_CREAT | (truncate ? O_TRUNC : O_APPEND);
  103. g_logfile = SD.open(LOGFILE, flags);
  104. if (!g_logfile.isOpen())
  105. {
  106. azlog("Failed to open log file: ", SD.sdErrorCode());
  107. }
  108. save_logfile(true);
  109. first_open_after_boot = false;
  110. }
  111. void print_sd_info()
  112. {
  113. uint64_t size = (uint64_t)SD.vol()->clusterCount() * SD.vol()->bytesPerCluster();
  114. azlog("SD card detected, FAT", (int)SD.vol()->fatType(),
  115. " volume size: ", (int)(size / 1024 / 1024), " MB");
  116. cid_t sd_cid;
  117. if(SD.card()->readCID(&sd_cid))
  118. {
  119. azlog("SD MID: ", (uint8_t)sd_cid.mid, ", OID: ", (uint8_t)sd_cid.oid[0], " ", (uint8_t)sd_cid.oid[1]);
  120. char sdname[6] = {sd_cid.pnm[0], sd_cid.pnm[1], sd_cid.pnm[2], sd_cid.pnm[3], sd_cid.pnm[4], 0};
  121. azlog("SD Name: ", sdname);
  122. char sdyear[5] = "2000";
  123. sdyear[2] += sd_cid.mdt_year_high;
  124. sdyear[3] += sd_cid.mdt_year_low;
  125. azlog("SD Date: ", (int)sd_cid.mdt_month, "/", sdyear);
  126. azlog("SD Serial: ", sd_cid.psn);
  127. }
  128. }
  129. /*********************************/
  130. /* Harddisk image file handling */
  131. /*********************************/
  132. // Iterate over the root path in the SD card looking for candidate image files.
  133. bool findHDDImages()
  134. {
  135. char imgdir[MAX_FILE_PATH];
  136. ini_gets("SCSI", "Dir", "/", imgdir, sizeof(imgdir), CONFIGFILE);
  137. int dirindex = 0;
  138. azlog("Finding HDD images in directory ", imgdir, ":");
  139. SdFile root;
  140. root.open(imgdir);
  141. if (!root.isOpen())
  142. {
  143. azlog("Could not open directory: ", imgdir);
  144. }
  145. SdFile file;
  146. bool imageReady;
  147. bool foundImage = false;
  148. uint8_t usedIds = 0;
  149. int usedDefaultId = 0;
  150. while (1)
  151. {
  152. if (!file.openNext(&root, O_READ))
  153. {
  154. // Check for additional directories with ini keys Dir1..Dir9
  155. while (dirindex < 10)
  156. {
  157. dirindex++;
  158. char key[5] = "Dir0";
  159. key[3] += dirindex;
  160. if (ini_gets("SCSI", key, "", imgdir, sizeof(imgdir), CONFIGFILE) != 0)
  161. {
  162. break;
  163. }
  164. }
  165. if (imgdir[0] != '\0')
  166. {
  167. azlog("Finding HDD images in additional directory Dir", (int)dirindex, " = \"", imgdir, "\":");
  168. root.open(imgdir);
  169. if (!root.isOpen())
  170. {
  171. azlog("-- Could not open directory: ", imgdir);
  172. }
  173. continue;
  174. }
  175. else
  176. {
  177. break;
  178. }
  179. }
  180. char name[MAX_FILE_PATH+1];
  181. if(!file.isDir()) {
  182. file.getName(name, MAX_FILE_PATH+1);
  183. file.close();
  184. bool is_hd = (tolower(name[0]) == 'h' && tolower(name[1]) == 'd');
  185. bool is_cd = (tolower(name[0]) == 'c' && tolower(name[1]) == 'd');
  186. if (is_hd || is_cd)
  187. {
  188. // Defaults for Hard Disks
  189. int id = 1; // 0 and 3 are common in Macs for physical HD and CD, so avoid them.
  190. int lun = 0;
  191. int blk = 512;
  192. if (is_cd)
  193. {
  194. // Use 2048 as the default sector size for CD-ROMs
  195. blk = 2048;
  196. }
  197. // Positionally read in and coerase the chars to integers.
  198. // We only require the minimum and read in the next if provided.
  199. int file_name_length = strlen(name);
  200. if(file_name_length > 2) { // HD[N]
  201. int tmp_id = name[HDIMG_ID_POS] - '0';
  202. if(tmp_id > -1 && tmp_id < 8)
  203. {
  204. id = tmp_id; // If valid id, set it, else use default
  205. }
  206. else
  207. {
  208. id = usedDefaultId++;
  209. }
  210. }
  211. if(file_name_length > 3) { // HD0[N]
  212. int tmp_lun = name[HDIMG_LUN_POS] - '0';
  213. if(tmp_lun > -1 && tmp_lun < 2) {
  214. lun = tmp_lun; // If valid id, set it, else use default
  215. }
  216. }
  217. int blk1 = 0, blk2 = 0, blk3 = 0, blk4 = 0;
  218. if(file_name_length > 8) { // HD00_[111]
  219. blk1 = name[HDIMG_BLK_POS] - '0';
  220. blk2 = name[HDIMG_BLK_POS+1] - '0';
  221. blk3 = name[HDIMG_BLK_POS+2] - '0';
  222. if(file_name_length > 9) // HD00_NNN[1]
  223. blk4 = name[HDIMG_BLK_POS+3] - '0';
  224. }
  225. if(blk1 == 2 && blk2 == 5 && blk3 == 6) {
  226. blk = 256;
  227. } else if(blk1 == 1 && blk2 == 0 && blk3 == 2 && blk4 == 4) {
  228. blk = 1024;
  229. } else if(blk1 == 2 && blk2 == 0 && blk3 == 4 && blk4 == 8) {
  230. blk = 2048;
  231. }
  232. char fullname[MAX_FILE_PATH * 2 + 2] = {0};
  233. strncpy(fullname, imgdir, MAX_FILE_PATH);
  234. if (fullname[strlen(fullname) - 1] != '/') strcat(fullname, "/");
  235. strcat(fullname, name);
  236. if (usedIds & (1 << id))
  237. {
  238. azlog("-- Ignoring ", fullname, ", SCSI ID ", id, " is already in use!");
  239. continue;
  240. }
  241. if(id < NUM_SCSIID && lun < NUM_SCSILUN) {
  242. azlog("-- Opening ", fullname, " for id:", id, " lun:", lun);
  243. imageReady = scsiDiskOpenHDDImage(id, fullname, id, lun, blk, is_cd);
  244. if(imageReady)
  245. {
  246. foundImage = true;
  247. usedIds |= (1 << id);
  248. }
  249. else
  250. {
  251. azlog("---- Failed to load image");
  252. }
  253. } else {
  254. azlog("-- Invalid lun or id for image ", fullname);
  255. }
  256. }
  257. }
  258. }
  259. if(usedDefaultId > 0) {
  260. azlog("Some images did not specify a SCSI ID. Last file will be used at ID ", usedDefaultId);
  261. }
  262. root.close();
  263. // Error if there are 0 image files
  264. if(!foundImage) {
  265. azlog("ERROR: No valid images found!");
  266. blinkStatus(BLINK_ERROR_NO_IMAGES);
  267. }
  268. // Print SCSI drive map
  269. for (int i = 0; i < NUM_SCSIID; i++)
  270. {
  271. const S2S_TargetCfg* cfg = s2s_getConfigByIndex(i);
  272. if (cfg && cfg->scsiId & S2S_CFG_TARGET_ENABLED)
  273. {
  274. int capacity_kB = ((uint64_t)cfg->scsiSectors * cfg->bytesPerSector) / 1024;
  275. azlog("SCSI ID:", (int)(cfg->scsiId & 7),
  276. " BlockSize:", (int)cfg->bytesPerSector,
  277. " Type:", (int)cfg->deviceType,
  278. " Quirks:", (int)cfg->quirks,
  279. " ImageSize:", capacity_kB, "kB");
  280. }
  281. }
  282. return foundImage;
  283. }
  284. /************************/
  285. /* Config file loading */
  286. /************************/
  287. void readSCSIDeviceConfig()
  288. {
  289. s2s_configInit(&scsiDev.boardCfg);
  290. for (int i = 0; i < NUM_SCSIID; i++)
  291. {
  292. scsiDiskLoadConfig(i);
  293. }
  294. if (ini_getbool("SCSI", "Debug", 0, CONFIGFILE))
  295. {
  296. g_azlog_debug = true;
  297. }
  298. }
  299. /*********************************/
  300. /* Main SCSI handling loop */
  301. /*********************************/
  302. static void reinitSCSI()
  303. {
  304. scsiDiskResetImages();
  305. readSCSIDeviceConfig();
  306. bool foundImage = findHDDImages();
  307. if (foundImage)
  308. {
  309. // Ok, there is an image
  310. blinkStatus(1);
  311. }
  312. scsiPhyReset();
  313. scsiDiskInit();
  314. scsiInit();
  315. }
  316. extern "C" int azulscsi_main(void)
  317. {
  318. azplatform_init();
  319. azplatform_late_init();
  320. if(!SD.begin(SD_CONFIG))
  321. {
  322. azlog("SD card init failed, sdErrorCode: ", (int)SD.sdErrorCode(),
  323. " sdErrorData: ", (int)SD.sdErrorData());
  324. do
  325. {
  326. blinkStatus(BLINK_ERROR_NO_SD_CARD);
  327. delay(1000);
  328. azplatform_reset_watchdog();
  329. } while (!SD.begin(SD_CONFIG));
  330. azlog("SD card init succeeded after retry");
  331. }
  332. print_sd_info();
  333. reinitSCSI();
  334. azlog("Initialization complete!");
  335. azlog("Platform: ", g_azplatform_name);
  336. azlog("FW Version: ", g_azlog_firmwareversion);
  337. init_logfile();
  338. uint32_t sd_card_check_time = 0;
  339. while (1)
  340. {
  341. azplatform_reset_watchdog();
  342. scsiPoll();
  343. scsiDiskPoll();
  344. scsiLogPhaseChange(scsiDev.phase);
  345. // Save log periodically during status phase if there are new messages.
  346. if (scsiDev.phase == STATUS)
  347. {
  348. save_logfile();
  349. }
  350. // Check SD card status for hotplug
  351. if (scsiDev.phase == BUS_FREE &&
  352. (uint32_t)(millis() - sd_card_check_time) > 5000)
  353. {
  354. sd_card_check_time = millis();
  355. uint32_t ocr;
  356. if (!SD.card()->readOCR(&ocr))
  357. {
  358. if (!SD.card()->readOCR(&ocr))
  359. {
  360. azlog("SD card removed, trying to reinit");
  361. do
  362. {
  363. blinkStatus(BLINK_ERROR_NO_SD_CARD);
  364. delay(1000);
  365. azplatform_reset_watchdog();
  366. } while (!SD.begin(SD_CONFIG));
  367. azlog("SD card reinit succeeded");
  368. print_sd_info();
  369. reinitSCSI();
  370. init_logfile();
  371. }
  372. }
  373. }
  374. }
  375. }