AzulSCSI.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. azlog("Finding HDD images:");
  136. SdFile root;
  137. root.open("/");
  138. SdFile file;
  139. bool imageReady;
  140. bool foundImage = false;
  141. uint8_t usedIds = 0;
  142. int usedDefaultId = 0;
  143. while (1) {
  144. if (!file.openNext(&root, O_READ)) break;
  145. char name[MAX_FILE_PATH+1];
  146. if(!file.isDir()) {
  147. file.getName(name, MAX_FILE_PATH+1);
  148. file.close();
  149. if ((tolower(name[0]) == 'h' && tolower(name[1]) == 'd') ||
  150. (tolower(name[0]) == 'c' && tolower(name[1]) == 'd')) {
  151. // Defaults for Hard Disks
  152. int id = 1; // 0 and 3 are common in Macs for physical HD and CD, so avoid them.
  153. int lun = 0;
  154. int blk = 512;
  155. // Positionally read in and coerase the chars to integers.
  156. // We only require the minimum and read in the next if provided.
  157. int file_name_length = strlen(name);
  158. if(file_name_length > 2) { // HD[N]
  159. int tmp_id = name[HDIMG_ID_POS] - '0';
  160. if(tmp_id > -1 && tmp_id < 8)
  161. {
  162. id = tmp_id; // If valid id, set it, else use default
  163. }
  164. else
  165. {
  166. id = usedDefaultId++;
  167. }
  168. }
  169. if(file_name_length > 3) { // HD0[N]
  170. int tmp_lun = name[HDIMG_LUN_POS] - '0';
  171. if(tmp_lun > -1 && tmp_lun < 2) {
  172. lun = tmp_lun; // If valid id, set it, else use default
  173. }
  174. }
  175. int blk1 = 0, blk2 = 0, blk3 = 0, blk4 = 0;
  176. if(file_name_length > 8) { // HD00_[111]
  177. blk1 = name[HDIMG_BLK_POS] - '0';
  178. blk2 = name[HDIMG_BLK_POS+1] - '0';
  179. blk3 = name[HDIMG_BLK_POS+2] - '0';
  180. if(file_name_length > 9) // HD00_NNN[1]
  181. blk4 = name[HDIMG_BLK_POS+3] - '0';
  182. }
  183. if(blk1 == 2 && blk2 == 5 && blk3 == 6) {
  184. blk = 256;
  185. } else if(blk1 == 1 && blk2 == 0 && blk3 == 2 && blk4 == 4) {
  186. blk = 1024;
  187. } else if(blk1 == 2 && blk2 == 0 && blk3 == 4 && blk4 == 8) {
  188. blk = 2048;
  189. }
  190. if (usedIds & (1 << id))
  191. {
  192. azlog("-- Ignoring ", name, ", SCSI ID ", id, " is already in use!");
  193. continue;
  194. }
  195. if(id < NUM_SCSIID && lun < NUM_SCSILUN) {
  196. azlog("-- Opening ", name, " for id:", id, " lun:", lun);
  197. imageReady = scsiDiskOpenHDDImage(id, name, id, lun, blk);
  198. if(imageReady) { // Marked as a responsive ID
  199. foundImage = true;
  200. usedIds |= (1 << id);
  201. }
  202. } else {
  203. azlog("-- Invalid lun or id for image ", name);
  204. }
  205. }
  206. }
  207. }
  208. if(usedDefaultId > 0) {
  209. azlog("Some images did not specify a SCSI ID. Last file will be used at ID ", usedDefaultId);
  210. }
  211. root.close();
  212. // Error if there are 0 image files
  213. if(!foundImage) {
  214. azlog("ERROR: No valid images found!");
  215. blinkStatus(BLINK_ERROR_NO_IMAGES);
  216. }
  217. // Print SCSI drive map
  218. for (int i = 0; i < NUM_SCSIID; i++)
  219. {
  220. const S2S_TargetCfg* cfg = s2s_getConfigByIndex(i);
  221. if (cfg && cfg->scsiId & S2S_CFG_TARGET_ENABLED)
  222. {
  223. int capacity_kB = ((uint64_t)cfg->scsiSectors * cfg->bytesPerSector) / 1024;
  224. azlog("SCSI ID:", (int)(cfg->scsiId & 7),
  225. " BlockSize:", (int)cfg->bytesPerSector,
  226. " Type:", (int)cfg->deviceType,
  227. " Quirks:", (int)cfg->quirks,
  228. " ImageSize:", capacity_kB, "kB");
  229. }
  230. }
  231. return foundImage;
  232. }
  233. /************************/
  234. /* Config file loading */
  235. /************************/
  236. void readSCSIDeviceConfig()
  237. {
  238. s2s_configInit(&scsiDev.boardCfg);
  239. for (int i = 0; i < NUM_SCSIID; i++)
  240. {
  241. scsiDiskLoadConfig(i);
  242. }
  243. if (ini_getbool("SCSI", "Debug", 0, CONFIGFILE))
  244. {
  245. g_azlog_debug = true;
  246. }
  247. }
  248. /*********************************/
  249. /* Main SCSI handling loop */
  250. /*********************************/
  251. static void reinitSCSI()
  252. {
  253. scsiDiskResetImages();
  254. readSCSIDeviceConfig();
  255. bool foundImage = findHDDImages();
  256. if (foundImage)
  257. {
  258. // Ok, there is an image
  259. blinkStatus(1);
  260. }
  261. scsiPhyReset();
  262. scsiDiskInit();
  263. scsiInit();
  264. }
  265. extern "C" int azulscsi_main(void)
  266. {
  267. azplatform_init();
  268. if(!SD.begin(SD_CONFIG))
  269. {
  270. azlog("SD card init failed, sdErrorCode: ", (int)SD.sdErrorCode(),
  271. " sdErrorData: ", (int)SD.sdErrorData());
  272. do
  273. {
  274. blinkStatus(BLINK_ERROR_NO_SD_CARD);
  275. delay(1000);
  276. azplatform_reset_watchdog();
  277. } while (!SD.begin(SD_CONFIG));
  278. azlog("SD card init succeeded after retry");
  279. }
  280. print_sd_info();
  281. reinitSCSI();
  282. azlog("Initialization complete!");
  283. azlog("Platform: ", g_azplatform_name);
  284. azlog("FW Version: ", g_azlog_firmwareversion);
  285. init_logfile();
  286. uint32_t sd_card_check_time = 0;
  287. while (1)
  288. {
  289. azplatform_reset_watchdog();
  290. scsiPoll();
  291. scsiDiskPoll();
  292. scsiLogPhaseChange(scsiDev.phase);
  293. // Save log periodically during status phase if there are new messages.
  294. if (scsiDev.phase == STATUS)
  295. {
  296. save_logfile();
  297. }
  298. // Check SD card status for hotplug
  299. if (scsiDev.phase == BUS_FREE &&
  300. (uint32_t)(millis() - sd_card_check_time) > 5000)
  301. {
  302. sd_card_check_time = millis();
  303. uint32_t ocr;
  304. if (!SD.card()->readOCR(&ocr))
  305. {
  306. if (!SD.card()->readOCR(&ocr))
  307. {
  308. azlog("SD card removed, trying to reinit");
  309. do
  310. {
  311. blinkStatus(BLINK_ERROR_NO_SD_CARD);
  312. delay(1000);
  313. azplatform_reset_watchdog();
  314. } while (!SD.begin(SD_CONFIG));
  315. azlog("SD card reinit succeeded");
  316. print_sd_info();
  317. reinitSCSI();
  318. init_logfile();
  319. }
  320. }
  321. }
  322. }
  323. }