ZuluSCSI_platform.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. /**
  2. * ZuluSCSI™ - Copyright (c) 2022 Rabbit Hole Computing™
  3. *
  4. * ZuluSCSI™ firmware is licensed under the GPL version 3 or any later version. 
  5. *
  6. * https://www.gnu.org/licenses/gpl-3.0.html
  7. * ----
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version. 
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16. * GNU General Public License for more details. 
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program.  If not, see <https://www.gnu.org/licenses/>.
  20. **/
  21. #include "ZuluSCSI_platform.h"
  22. #include "gd32f4xx_sdio.h"
  23. #include "gd32f4xx_fmc.h"
  24. #include "ZuluSCSI_log.h"
  25. #include "ZuluSCSI_config.h"
  26. #include "usb_hs.h"
  27. #include "usbd_conf.h"
  28. #include "greenpak.h"
  29. #include <SdFat.h>
  30. #include <scsi.h>
  31. #include <assert.h>
  32. extern "C" {
  33. const char *g_platform_name = PLATFORM_NAME;
  34. static bool g_enable_apple_quirks = false;
  35. /*************************/
  36. /* Timing functions */
  37. /*************************/
  38. static volatile uint32_t g_millisecond_counter;
  39. static volatile uint32_t g_watchdog_timeout;
  40. static uint32_t g_ns_to_cycles; // Q0.32 fixed point format
  41. static void watchdog_handler(uint32_t *sp);
  42. unsigned long millis()
  43. {
  44. return g_millisecond_counter;
  45. }
  46. void delay(unsigned long ms)
  47. {
  48. uint32_t start = g_millisecond_counter;
  49. while ((uint32_t)(g_millisecond_counter - start) < ms);
  50. }
  51. void delay_ns(unsigned long ns)
  52. {
  53. uint32_t CNT_start = DWT->CYCCNT;
  54. if (ns <= 50) return; // Approximate call overhead
  55. ns -= 50;
  56. uint32_t cycles = ((uint64_t)ns * g_ns_to_cycles) >> 32;
  57. while ((uint32_t)(DWT->CYCCNT - CNT_start) < cycles);
  58. }
  59. void SysTick_Handler_inner(uint32_t *sp)
  60. {
  61. g_millisecond_counter++;
  62. if (g_watchdog_timeout > 0)
  63. {
  64. g_watchdog_timeout--;
  65. const uint32_t busreset_time = WATCHDOG_CRASH_TIMEOUT - WATCHDOG_BUS_RESET_TIMEOUT;
  66. if (g_watchdog_timeout <= busreset_time)
  67. {
  68. if (!scsiDev.resetFlag)
  69. {
  70. logmsg("WATCHDOG TIMEOUT at PC ", sp[6], " LR ", sp[5], " attempting bus reset");
  71. scsiDev.resetFlag = 1;
  72. }
  73. if (g_watchdog_timeout == 0)
  74. {
  75. watchdog_handler(sp);
  76. }
  77. }
  78. }
  79. }
  80. __attribute__((interrupt, naked))
  81. void SysTick_Handler(void)
  82. {
  83. // Take note of stack pointer so that we can print debug
  84. // info in watchdog handler.
  85. asm("mrs r0, msp\n"
  86. "b SysTick_Handler_inner": : : "r0");
  87. }
  88. // This function is called by scsiPhy.cpp.
  89. // It resets the systick counter to give 1 millisecond of uninterrupted transfer time.
  90. // The total number of skips is kept track of to keep the correct time on average.
  91. void SysTick_Handle_PreEmptively()
  92. {
  93. static int skipped_clocks = 0;
  94. __disable_irq();
  95. uint32_t loadval = SysTick->LOAD;
  96. skipped_clocks += loadval - SysTick->VAL;
  97. SysTick->VAL = 0;
  98. if (skipped_clocks > loadval)
  99. {
  100. // We have skipped enough ticks that it is time to fake a call
  101. // to SysTick interrupt handler.
  102. skipped_clocks -= loadval;
  103. uint32_t stack_frame[8] = {0};
  104. stack_frame[6] = (uint32_t)__builtin_return_address(0);
  105. SysTick_Handler_inner(stack_frame);
  106. }
  107. __enable_irq();
  108. }
  109. /***************/
  110. /* GPIO init */
  111. /***************/
  112. // Initialize SPI and GPIO configuration
  113. // Clock has already been initialized by system_gd32f20x.c
  114. void platform_init()
  115. {
  116. SystemCoreClockUpdate();
  117. nvic_priority_group_set(NVIC_PRIGROUP_PRE2_SUB2);
  118. // Enable SysTick to drive millis()
  119. g_millisecond_counter = 0;
  120. SysTick_Config(SystemCoreClock / 1000U);
  121. nvic_irq_enable(SysTick_IRQn, 0x00U, 0x00U);
  122. //NVIC_SetPriority(SysTick_IRQn, 0x00U);
  123. //NVIC_EnableIRQ(SysTick_IRQn);
  124. // Enable DWT counter to drive delay_ns()
  125. g_ns_to_cycles = ((uint64_t)SystemCoreClock << 32) / 1000000000;
  126. CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
  127. DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
  128. // Enable debug output on SWO pin
  129. DBG_CTL0 |= DBG_CTL0_TRACE_IOEN;
  130. //TODO figure out if this code needs to execute - TPI_ACPR == 99 at the if statement below
  131. //if (TPI->ACPR == 0)
  132. {
  133. CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
  134. TPI->ACPR = SystemCoreClock / 2000000 - 1; // 2 Mbps baudrate for SWO
  135. // TPI->ACPR = SystemCoreClock / 30000000 - 1; // 30 Mbps baudrate for SWO
  136. TPI->SPPR = 2;
  137. TPI->FFCR = 0x100; // TPIU packet framing disabled
  138. // DWT->CTRL |= (1 << DWT_CTRL_EXCTRCENA_Pos);
  139. // DWT->CTRL |= (1 << DWT_CTRL_CYCTAP_Pos)
  140. // | (15 << DWT_CTRL_POSTPRESET_Pos)
  141. // | (1 << DWT_CTRL_PCSAMPLENA_Pos)
  142. // | (3 << DWT_CTRL_SYNCTAP_Pos)
  143. // | (1 << DWT_CTRL_CYCCNTENA_Pos);
  144. ITM->LAR = 0xC5ACCE55;
  145. ITM->TCR = (1 << ITM_TCR_DWTENA_Pos)
  146. | (1 << ITM_TCR_SYNCENA_Pos)
  147. | (1 << ITM_TCR_ITMENA_Pos);
  148. ITM->TER = 0xFFFFFFFF; // Enable all stimulus ports
  149. }
  150. // Enable needed clocks for GPIO
  151. rcu_periph_clock_enable(RCU_GPIOA);
  152. rcu_periph_clock_enable(RCU_GPIOB);
  153. rcu_periph_clock_enable(RCU_GPIOC);
  154. rcu_periph_clock_enable(RCU_GPIOD);
  155. rcu_periph_clock_enable(RCU_GPIOE);
  156. rcu_periph_clock_enable(RCU_GPIOF);
  157. rcu_periph_clock_enable(RCU_GPIOG);
  158. // Switch to SWD debug port (disable JTAG) to release PB4 as GPIO
  159. gpio_mode_set(GPIOB, GPIO_MODE_INPUT, GPIO_PUPD_NONE, GPIO_PIN_4);
  160. // SCSI pins.
  161. // Initialize open drain outputs to high.
  162. SCSI_RELEASE_OUTPUTS();
  163. gpio_mode_set(SCSI_OUT_PORT, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, SCSI_OUT_DATA_MASK | SCSI_OUT_REQ);
  164. gpio_mode_set(SCSI_OUT_IO_PORT, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, SCSI_OUT_IO_PIN);
  165. gpio_mode_set(SCSI_OUT_CD_PORT, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, SCSI_OUT_CD_PIN);
  166. gpio_mode_set(SCSI_OUT_SEL_PORT, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, SCSI_OUT_SEL_PIN);
  167. gpio_mode_set(SCSI_OUT_MSG_PORT, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, SCSI_OUT_MSG_PIN);
  168. gpio_mode_set(SCSI_OUT_RST_PORT, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, SCSI_OUT_RST_PIN);
  169. gpio_mode_set(SCSI_OUT_BSY_PORT, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, SCSI_OUT_BSY_PIN);
  170. gpio_output_options_set(SCSI_OUT_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_200MHZ, SCSI_OUT_DATA_MASK | SCSI_OUT_REQ);
  171. gpio_output_options_set(SCSI_OUT_IO_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_200MHZ, SCSI_OUT_IO_PIN);
  172. gpio_output_options_set(SCSI_OUT_CD_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_200MHZ, SCSI_OUT_CD_PIN);
  173. gpio_output_options_set(SCSI_OUT_SEL_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_200MHZ, SCSI_OUT_SEL_PIN);
  174. gpio_output_options_set(SCSI_OUT_MSG_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_200MHZ, SCSI_OUT_MSG_PIN);
  175. gpio_output_options_set(SCSI_OUT_RST_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_200MHZ, SCSI_OUT_RST_PIN);
  176. gpio_output_options_set(SCSI_OUT_BSY_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_200MHZ, SCSI_OUT_BSY_PIN);
  177. gpio_mode_set(SCSI_IN_PORT, GPIO_MODE_INPUT, GPIO_PUPD_NONE, SCSI_IN_MASK);
  178. gpio_mode_set(SCSI_ATN_PORT, GPIO_MODE_INPUT, GPIO_PUPD_NONE, SCSI_ATN_PIN);
  179. gpio_mode_set(SCSI_BSY_PORT, GPIO_MODE_INPUT, GPIO_PUPD_NONE, SCSI_BSY_PIN);
  180. gpio_mode_set(SCSI_SEL_PORT, GPIO_MODE_INPUT, GPIO_PUPD_NONE, SCSI_SEL_PIN);
  181. gpio_mode_set(SCSI_ACK_PORT, GPIO_MODE_INPUT, GPIO_PUPD_NONE, SCSI_ACK_PIN);
  182. gpio_mode_set(SCSI_RST_PORT, GPIO_MODE_INPUT, GPIO_PUPD_NONE, SCSI_RST_PIN);
  183. // Terminator enable
  184. gpio_bit_set(SCSI_TERM_EN_PORT, SCSI_TERM_EN_PIN);
  185. gpio_mode_set(SCSI_TERM_EN_PORT, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, SCSI_TERM_EN_PIN);
  186. gpio_output_options_set(SCSI_TERM_EN_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_2MHZ, SCSI_TERM_EN_PIN);
  187. // SD card pins using SDIO
  188. gpio_mode_set(SD_SDIO_DATA_PORT, GPIO_MODE_AF, GPIO_PUPD_NONE, SD_SDIO_D0 | SD_SDIO_D1 | SD_SDIO_D2 | SD_SDIO_D3);
  189. gpio_output_options_set(SD_SDIO_DATA_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, SD_SDIO_D0 | SD_SDIO_D1 | SD_SDIO_D2 | SD_SDIO_D3);
  190. gpio_af_set(SD_SDIO_DATA_PORT, GPIO_AF_12, SD_SDIO_D0 | SD_SDIO_D1 | SD_SDIO_D2 | SD_SDIO_D3);
  191. gpio_mode_set(SD_SDIO_CLK_PORT, GPIO_MODE_AF, GPIO_PUPD_NONE, SD_SDIO_CLK);
  192. gpio_output_options_set(SD_SDIO_CLK_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, SD_SDIO_CLK);
  193. gpio_af_set(SD_SDIO_CLK_PORT, GPIO_AF_12, SD_SDIO_CLK);
  194. gpio_mode_set(SD_SDIO_CMD_PORT, GPIO_MODE_AF, GPIO_PUPD_NONE, SD_SDIO_CMD);
  195. gpio_output_options_set(SD_SDIO_CMD_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, SD_SDIO_CMD);
  196. gpio_af_set(SD_SDIO_CMD_PORT, GPIO_AF_12, SD_SDIO_CMD);
  197. // DIP switches
  198. gpio_mode_set(DIP_PORT, GPIO_MODE_INPUT, GPIO_PUPD_PULLDOWN, DIPSW1_PIN | DIPSW2_PIN | DIPSW3_PIN);
  199. // LED pins
  200. gpio_bit_set(LED_PORT, LED_PINS);
  201. gpio_mode_set(LED_PORT, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, LED_PINS);
  202. gpio_output_options_set(LED_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_2MHZ, LED_PINS);
  203. // SWO trace pin on PB3
  204. gpio_mode_set(GPIOB, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO_PIN_3);
  205. gpio_output_options_set(GPIOB, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_3);
  206. gpio_af_set(GPIOB, GPIO_AF_0, GPIO_PIN_3);
  207. }
  208. void platform_late_init()
  209. {
  210. logmsg("Platform: ", g_platform_name);
  211. logmsg("FW Version: ", g_log_firmwareversion);
  212. if (gpio_input_bit_get(DIP_PORT, DIPSW3_PIN))
  213. {
  214. logmsg("DIPSW3 is ON: Enabling SCSI termination");
  215. gpio_bit_reset(SCSI_TERM_EN_PORT, SCSI_TERM_EN_PIN);
  216. }
  217. else
  218. {
  219. logmsg("DIPSW3 is OFF: SCSI termination disabled");
  220. }
  221. if (gpio_input_bit_get(DIP_PORT, DIPSW2_PIN))
  222. {
  223. logmsg("DIPSW2 is ON: enabling debug messages");
  224. g_log_debug = true;
  225. }
  226. else
  227. {
  228. g_log_debug = false;
  229. }
  230. if (gpio_input_bit_get(DIP_PORT, DIPSW1_PIN))
  231. {
  232. logmsg("DIPSW1 is ON: enabling Apple quirks by default");
  233. g_enable_apple_quirks = true;
  234. }
  235. usb_hs_init();
  236. greenpak_load_firmware();
  237. }
  238. void platform_disable_led(void)
  239. {
  240. gpio_mode_set(LED_PORT, GPIO_MODE_INPUT, GPIO_PUPD_PULLUP, LED_PINS);
  241. logmsg("Disabling status LED");
  242. }
  243. /*****************************************/
  244. /* Supply voltage monitor */
  245. /*****************************************/
  246. // Use ADC to implement supply voltage monitoring for the +3.0V rail.
  247. // This works by sampling the Vrefint, which has
  248. // a voltage of 1.2 V, allowing to calculate the VDD voltage.
  249. static void adc_poll()
  250. {
  251. #if PLATFORM_VDD_WARNING_LIMIT_mV > 0
  252. static bool initialized = false;
  253. static int lowest_vdd_seen = PLATFORM_VDD_WARNING_LIMIT_mV;
  254. if (!initialized)
  255. {
  256. rcu_periph_clock_enable(RCU_ADC0);
  257. adc_enable(ADC0);
  258. adc_calibration_enable(ADC0);
  259. adc_channel_16_to_18(ADC_TEMP_VREF_CHANNEL_SWITCH, ENABLE);
  260. adc_inserted_channel_config(ADC0, 0, ADC_CHANNEL_17, ADC_SAMPLETIME_144);
  261. //TODO can these be safely removed
  262. /*
  263. adc_external_trigger_source_config(ADC0, ADC_INSERTED_CHANNEL, ADC0_1_2_EXTTRIG_INSERTED_NONE);
  264. adc_external_trigger_config(ADC0, ADC_INSERTED_CHANNEL, ENABLE);
  265. */
  266. adc_software_trigger_enable(ADC0, ADC_INSERTED_CHANNEL);
  267. initialized = true;
  268. }
  269. // Read previous result and start new one
  270. int adc_value = ADC_IDATA0(ADC0);
  271. adc_software_trigger_enable(ADC0, ADC_INSERTED_CHANNEL);
  272. // adc_value = 1200mV * 4096 / Vdd
  273. // => Vdd = 1200mV * 4096 / adc_value
  274. // To avoid wasting time on division, compare against
  275. // limit directly.
  276. const int limit = (1200 * 4096) / PLATFORM_VDD_WARNING_LIMIT_mV;
  277. if (adc_value > limit)
  278. {
  279. // Warn once, and then again if we detect even a lower drop.
  280. int vdd_mV = (1200 * 4096) / adc_value;
  281. if (vdd_mV < lowest_vdd_seen)
  282. {
  283. logmsg("WARNING: Detected supply voltage drop to ", vdd_mV, "mV. Verify power supply is adequate.");
  284. lowest_vdd_seen = vdd_mV - 50; // Small hysteresis to avoid excessive warnings
  285. }
  286. }
  287. #endif
  288. }
  289. /*****************************************/
  290. /* Debug logging and watchdog */
  291. /*****************************************/
  292. // Send log data to USB UART if USB is connected.
  293. // Data is retrieved from the shared log ring buffer and
  294. // this function sends as much as fits in USB CDC buffer.
  295. //
  296. // This is normally called by platform_reset_watchdog() in
  297. // the normal polling loop. If code hangs, the watchdog_callback()
  298. // also starts calling this after 2 seconds.
  299. // This ensures that log messages get passed even if code hangs,
  300. // but does not unnecessarily delay normal execution.
  301. static void usb_log_poll()
  302. {
  303. static uint32_t logpos = 0;
  304. if (usb_hs_ready())
  305. {
  306. // Retrieve pointer to log start and determine number of bytes available.
  307. uint32_t available = 0;
  308. const char *data = log_get_buffer(&logpos, &available);
  309. // Limit to CDC packet size
  310. uint32_t len = available;
  311. if (len == 0) return;
  312. if (len > USB_CDC_EP_IN_WORKING_SIZE) len = USB_CDC_EP_IN_WORKING_SIZE;
  313. // Update log position by the actual number of bytes sent
  314. // If USB CDC buffer is full, this may be 0
  315. usb_hs_send((uint8_t*)data, len);
  316. logpos -= available - len;
  317. }
  318. }
  319. /*****************************************/
  320. /* Crash handlers */
  321. /*****************************************/
  322. extern SdFs SD;
  323. // Writes log data to the PB3 SWO pin
  324. void platform_log(const char *s)
  325. {
  326. while (*s)
  327. {
  328. // Write to SWO pin
  329. while (ITM->PORT[0].u32 == 0);
  330. ITM->PORT[0].u8 = *s++;
  331. }
  332. }
  333. void platform_emergency_log_save()
  334. {
  335. platform_set_sd_callback(NULL, NULL);
  336. SD.begin(SD_CONFIG_CRASH);
  337. FsFile crashfile = SD.open(CRASHFILE, O_WRONLY | O_CREAT | O_TRUNC);
  338. if (!crashfile.isOpen())
  339. {
  340. // Try to reinitialize
  341. int max_retry = 10;
  342. while (max_retry-- > 0 && !SD.begin(SD_CONFIG_CRASH));
  343. crashfile = SD.open(CRASHFILE, O_WRONLY | O_CREAT | O_TRUNC);
  344. }
  345. uint32_t startpos = 0;
  346. crashfile.write(log_get_buffer(&startpos));
  347. crashfile.write(log_get_buffer(&startpos));
  348. crashfile.flush();
  349. crashfile.close();
  350. }
  351. extern uint32_t _estack;
  352. __attribute__((noinline))
  353. void show_hardfault(uint32_t *sp)
  354. {
  355. uint32_t pc = sp[6];
  356. uint32_t lr = sp[5];
  357. uint32_t cfsr = SCB->CFSR;
  358. logmsg("--------------");
  359. logmsg("CRASH!");
  360. logmsg("Platform: ", g_platform_name);
  361. logmsg("FW Version: ", g_log_firmwareversion);
  362. logmsg("scsiDev.cdb: ", bytearray(scsiDev.cdb, 12));
  363. logmsg("scsiDev.phase: ", (int)scsiDev.phase);
  364. logmsg("CFSR: ", cfsr);
  365. logmsg("SP: ", (uint32_t)sp);
  366. logmsg("PC: ", pc);
  367. logmsg("LR: ", lr);
  368. logmsg("R0: ", sp[0]);
  369. logmsg("R1: ", sp[1]);
  370. logmsg("R2: ", sp[2]);
  371. logmsg("R3: ", sp[3]);
  372. uint32_t *p = (uint32_t*)((uint32_t)sp & ~3);
  373. for (int i = 0; i < 8; i++)
  374. {
  375. if (p == &_estack) break; // End of stack
  376. logmsg("STACK ", (uint32_t)p, ": ", p[0], " ", p[1], " ", p[2], " ", p[3]);
  377. p += 4;
  378. }
  379. platform_emergency_log_save();
  380. while (1)
  381. {
  382. // Flash the crash address on the LED
  383. // Short pulse means 0, long pulse means 1
  384. int base_delay = 1000;
  385. for (int i = 31; i >= 0; i--)
  386. {
  387. LED_OFF();
  388. for (int j = 0; j < base_delay; j++) delay_ns(100000);
  389. int delay = (pc & (1 << i)) ? (3 * base_delay) : base_delay;
  390. LED_ON();
  391. for (int j = 0; j < delay; j++) delay_ns(100000);
  392. LED_OFF();
  393. }
  394. for (int j = 0; j < base_delay * 10; j++) delay_ns(100000);
  395. }
  396. }
  397. __attribute__((naked, interrupt))
  398. void HardFault_Handler(void)
  399. {
  400. // Copies stack pointer into first argument
  401. asm("mrs r0, msp\n"
  402. "b show_hardfault": : : "r0");
  403. }
  404. __attribute__((naked, interrupt))
  405. void MemManage_Handler(void)
  406. {
  407. asm("mrs r0, msp\n"
  408. "b show_hardfault": : : "r0");
  409. }
  410. __attribute__((naked, interrupt))
  411. void BusFault_Handler(void)
  412. {
  413. asm("mrs r0, msp\n"
  414. "b show_hardfault": : : "r0");
  415. }
  416. __attribute__((naked, interrupt))
  417. void UsageFault_Handler(void)
  418. {
  419. asm("mrs r0, msp\n"
  420. "b show_hardfault": : : "r0");
  421. }
  422. void __assert_func(const char *file, int line, const char *func, const char *expr)
  423. {
  424. uint32_t dummy = 0;
  425. logmsg("--------------");
  426. logmsg("ASSERT FAILED!");
  427. logmsg("Platform: ", g_platform_name);
  428. logmsg("FW Version: ", g_log_firmwareversion);
  429. logmsg("scsiDev.cdb: ", bytearray(scsiDev.cdb, 12));
  430. logmsg("scsiDev.phase: ", (int)scsiDev.phase);
  431. logmsg("Assert failed: ", file , ":", line, " in ", func, ":", expr);
  432. uint32_t *p = (uint32_t*)((uint32_t)&dummy & ~3);
  433. for (int i = 0; i < 8; i++)
  434. {
  435. if (p == &_estack) break; // End of stack
  436. logmsg("STACK ", (uint32_t)p, ": ", p[0], " ", p[1], " ", p[2], " ", p[3]);
  437. p += 4;
  438. }
  439. platform_emergency_log_save();
  440. while(1)
  441. {
  442. LED_OFF();
  443. for (int j = 0; j < 1000; j++) delay_ns(100000);
  444. LED_ON();
  445. for (int j = 0; j < 1000; j++) delay_ns(100000);
  446. }
  447. }
  448. } /* extern "C" */
  449. static void watchdog_handler(uint32_t *sp)
  450. {
  451. logmsg("-------------- WATCHDOG TIMEOUT");
  452. show_hardfault(sp);
  453. }
  454. void platform_reset_watchdog()
  455. {
  456. // This uses a software watchdog based on systick timer interrupt.
  457. // It gives us opportunity to collect better debug info than the
  458. // full hardware reset that would be caused by hardware watchdog.
  459. g_watchdog_timeout = WATCHDOG_CRASH_TIMEOUT;
  460. }
  461. // Poll function that is called every few milliseconds.
  462. // Can be left empty or used for platform-specific processing.
  463. void platform_poll()
  464. {
  465. // adc_poll();
  466. usb_log_poll();
  467. }
  468. uint8_t platform_get_buttons()
  469. {
  470. return 0;
  471. }
  472. /***********************/
  473. /* Flash reprogramming */
  474. /***********************/
  475. #define SECTOR_NUMBER_TO_ID_ERROR 0xFFFFFFFF
  476. static uint32_t sector_number_to_id(uint32_t sector_number)
  477. {
  478. if(11 >= sector_number){
  479. return CTL_SN(sector_number);
  480. }else if(23 >= sector_number){
  481. return CTL_SN(sector_number + 4);
  482. }else if(27 >= sector_number){
  483. return CTL_SN(sector_number - 12);
  484. }
  485. return SECTOR_NUMBER_TO_ID_ERROR;
  486. }
  487. bool platform_erase_flash_sector(uint32_t sector)
  488. {
  489. fmc_unlock();
  490. fmc_flag_clear(FMC_FLAG_END | FMC_FLAG_OPERR | FMC_FLAG_WPERR | FMC_FLAG_PGMERR | FMC_FLAG_PGSERR);
  491. uint32_t sector_id = sector_number_to_id(sector);
  492. if (sector_id == SECTOR_NUMBER_TO_ID_ERROR)
  493. {
  494. logmsg("Sector ", (int) sector, " does not exist");
  495. return false;
  496. }
  497. if (FMC_READY != fmc_sector_erase(sector_id))
  498. {
  499. logmsg("Failed flash failed to erase sector, ", (int) sector);
  500. LED_OFF();
  501. return false;
  502. }
  503. fmc_lock();
  504. return true;
  505. }
  506. bool platform_write_flash(uint32_t offset, uint32_t length, uint8_t buffer[PLATFORM_FLASH_WRITE_BUFFER_SIZE])
  507. {
  508. if (offset == 0)
  509. {
  510. if (buffer[3] != 0x20 || buffer[7] != 0x08)
  511. {
  512. logmsg("Invalid firmware file, starts with: ", bytearray(buffer, 16));
  513. return false;
  514. }
  515. }
  516. dbgmsg("Writing flash at firmware offset ", offset, " data ", bytearray(buffer, 4));
  517. assert(offset % PLATFORM_FLASH_WRITE_BUFFER_SIZE == 0);
  518. //assert(offset >= PLATFORM_BOOTLOADER_SIZE);
  519. fmc_unlock();
  520. fmc_flag_clear(FMC_FLAG_END | FMC_FLAG_OPERR | FMC_FLAG_WPERR | FMC_FLAG_PGMERR | FMC_FLAG_PGSERR);
  521. fmc_state_enum status;
  522. uint32_t *buf32 = (uint32_t*)buffer;
  523. uint32_t memory_address = FLASH_BASE + PLATFORM_BOOTLOADER_SIZE + offset;
  524. uint32_t num_words = length / 4;
  525. if (length % 4 == 0)
  526. {
  527. for (int i = 0; i < num_words; i++)
  528. {
  529. status = fmc_word_program(memory_address, buf32[i]);
  530. if (status != FMC_READY)
  531. {
  532. logmsg("Flash write failed at address: ", memory_address, " with code ", (int)status);
  533. return false;
  534. }
  535. memory_address += 4;
  536. }
  537. }
  538. else
  539. {
  540. logmsg("Firmware size expected to be word (4byte) aligned");
  541. }
  542. fmc_lock();
  543. memory_address = FLASH_BASE + PLATFORM_BOOTLOADER_SIZE + offset;
  544. for (int i = 0; i < num_words; i++)
  545. {
  546. uint32_t expected = buf32[i];
  547. uint32_t actual = *(volatile uint32_t*)(memory_address);
  548. if (actual != expected)
  549. {
  550. logmsg("Flash word verify failed memory address ", memory_address, " got ", actual, " expected ", expected);
  551. return false;
  552. }
  553. memory_address += 4;
  554. }
  555. return true;
  556. }
  557. void platform_boot_to_main_firmware()
  558. {
  559. uint32_t *mainprogram_start = (uint32_t*)(0x08000000 + PLATFORM_BOOTLOADER_SIZE);
  560. SCB->VTOR = (uint32_t)mainprogram_start;
  561. __asm__(
  562. "msr msp, %0\n\t"
  563. "bx %1" : : "r" (mainprogram_start[0]),
  564. "r" (mainprogram_start[1]) : "memory");
  565. }
  566. /**************************************/
  567. /* SCSI configuration based on DIPSW1 */
  568. /**************************************/
  569. void platform_config_hook(S2S_TargetCfg *config)
  570. {
  571. // Enable Apple quirks by dip switch
  572. if (g_enable_apple_quirks)
  573. {
  574. if (config->quirks == S2S_CFG_QUIRKS_NONE)
  575. {
  576. config->quirks = S2S_CFG_QUIRKS_APPLE;
  577. }
  578. }
  579. }
  580. /**********************************************/
  581. /* Mapping from data bytes to GPIO BOP values */
  582. /**********************************************/
  583. #define PARITY(n) ((1 ^ (n) ^ ((n)>>1) ^ ((n)>>2) ^ ((n)>>3) ^ ((n)>>4) ^ ((n)>>5) ^ ((n)>>6) ^ ((n)>>7)) & 1)
  584. #define X(n) (\
  585. ((n & 0x01) ? (SCSI_OUT_DB0 << 16) : SCSI_OUT_DB0) | \
  586. ((n & 0x02) ? (SCSI_OUT_DB1 << 16) : SCSI_OUT_DB1) | \
  587. ((n & 0x04) ? (SCSI_OUT_DB2 << 16) : SCSI_OUT_DB2) | \
  588. ((n & 0x08) ? (SCSI_OUT_DB3 << 16) : SCSI_OUT_DB3) | \
  589. ((n & 0x10) ? (SCSI_OUT_DB4 << 16) : SCSI_OUT_DB4) | \
  590. ((n & 0x20) ? (SCSI_OUT_DB5 << 16) : SCSI_OUT_DB5) | \
  591. ((n & 0x40) ? (SCSI_OUT_DB6 << 16) : SCSI_OUT_DB6) | \
  592. ((n & 0x80) ? (SCSI_OUT_DB7 << 16) : SCSI_OUT_DB7) | \
  593. (PARITY(n) ? (SCSI_OUT_DBP << 16) : SCSI_OUT_DBP) | \
  594. (SCSI_OUT_REQ) \
  595. )
  596. const uint32_t g_scsi_out_byte_to_bop[256] =
  597. {
  598. X(0x00), X(0x01), X(0x02), X(0x03), X(0x04), X(0x05), X(0x06), X(0x07), X(0x08), X(0x09), X(0x0a), X(0x0b), X(0x0c), X(0x0d), X(0x0e), X(0x0f),
  599. X(0x10), X(0x11), X(0x12), X(0x13), X(0x14), X(0x15), X(0x16), X(0x17), X(0x18), X(0x19), X(0x1a), X(0x1b), X(0x1c), X(0x1d), X(0x1e), X(0x1f),
  600. X(0x20), X(0x21), X(0x22), X(0x23), X(0x24), X(0x25), X(0x26), X(0x27), X(0x28), X(0x29), X(0x2a), X(0x2b), X(0x2c), X(0x2d), X(0x2e), X(0x2f),
  601. X(0x30), X(0x31), X(0x32), X(0x33), X(0x34), X(0x35), X(0x36), X(0x37), X(0x38), X(0x39), X(0x3a), X(0x3b), X(0x3c), X(0x3d), X(0x3e), X(0x3f),
  602. X(0x40), X(0x41), X(0x42), X(0x43), X(0x44), X(0x45), X(0x46), X(0x47), X(0x48), X(0x49), X(0x4a), X(0x4b), X(0x4c), X(0x4d), X(0x4e), X(0x4f),
  603. X(0x50), X(0x51), X(0x52), X(0x53), X(0x54), X(0x55), X(0x56), X(0x57), X(0x58), X(0x59), X(0x5a), X(0x5b), X(0x5c), X(0x5d), X(0x5e), X(0x5f),
  604. X(0x60), X(0x61), X(0x62), X(0x63), X(0x64), X(0x65), X(0x66), X(0x67), X(0x68), X(0x69), X(0x6a), X(0x6b), X(0x6c), X(0x6d), X(0x6e), X(0x6f),
  605. X(0x70), X(0x71), X(0x72), X(0x73), X(0x74), X(0x75), X(0x76), X(0x77), X(0x78), X(0x79), X(0x7a), X(0x7b), X(0x7c), X(0x7d), X(0x7e), X(0x7f),
  606. X(0x80), X(0x81), X(0x82), X(0x83), X(0x84), X(0x85), X(0x86), X(0x87), X(0x88), X(0x89), X(0x8a), X(0x8b), X(0x8c), X(0x8d), X(0x8e), X(0x8f),
  607. X(0x90), X(0x91), X(0x92), X(0x93), X(0x94), X(0x95), X(0x96), X(0x97), X(0x98), X(0x99), X(0x9a), X(0x9b), X(0x9c), X(0x9d), X(0x9e), X(0x9f),
  608. X(0xa0), X(0xa1), X(0xa2), X(0xa3), X(0xa4), X(0xa5), X(0xa6), X(0xa7), X(0xa8), X(0xa9), X(0xaa), X(0xab), X(0xac), X(0xad), X(0xae), X(0xaf),
  609. X(0xb0), X(0xb1), X(0xb2), X(0xb3), X(0xb4), X(0xb5), X(0xb6), X(0xb7), X(0xb8), X(0xb9), X(0xba), X(0xbb), X(0xbc), X(0xbd), X(0xbe), X(0xbf),
  610. X(0xc0), X(0xc1), X(0xc2), X(0xc3), X(0xc4), X(0xc5), X(0xc6), X(0xc7), X(0xc8), X(0xc9), X(0xca), X(0xcb), X(0xcc), X(0xcd), X(0xce), X(0xcf),
  611. X(0xd0), X(0xd1), X(0xd2), X(0xd3), X(0xd4), X(0xd5), X(0xd6), X(0xd7), X(0xd8), X(0xd9), X(0xda), X(0xdb), X(0xdc), X(0xdd), X(0xde), X(0xdf),
  612. X(0xe0), X(0xe1), X(0xe2), X(0xe3), X(0xe4), X(0xe5), X(0xe6), X(0xe7), X(0xe8), X(0xe9), X(0xea), X(0xeb), X(0xec), X(0xed), X(0xee), X(0xef),
  613. X(0xf0), X(0xf1), X(0xf2), X(0xf3), X(0xf4), X(0xf5), X(0xf6), X(0xf7), X(0xf8), X(0xf9), X(0xfa), X(0xfb), X(0xfc), X(0xfd), X(0xfe), X(0xff)
  614. };
  615. #undef X