From e924ecee80534ead89af910578276ce0e69d883b Mon Sep 17 00:00:00 2001
From: Rahix <rahix@rahix.de>
Date: Sun, 18 Aug 2019 12:55:34 +0200
Subject: [PATCH] fix(api): Reset FPU before loading a new payload

Without resetting the FPU we get spurious failures in Pycardium.  These
manifest in many different forms, ranging from HardFaults and triggered
assertions to "syntax errors" in loaded scripts while said script does
not contain any.

These failures stem from the FPU still containing state from the last
loaded payload and thus sometimes corrupting stack locations where the
previous payload had floating point state.

Closes #72.

Signed-off-by: Rahix <rahix@rahix.de>
---
 epicardium/api/control.c | 19 ++++++++++++++++---
 1 file changed, 16 insertions(+), 3 deletions(-)

diff --git a/epicardium/api/control.c b/epicardium/api/control.c
index b8987b43e..9302eb5e6 100644
--- a/epicardium/api/control.c
+++ b/epicardium/api/control.c
@@ -45,9 +45,22 @@ static uintptr_t core1_initial_ivt[] = {
  */
 __attribute__((naked)) void __core1_reset(void)
 {
-	__asm volatile("mov	sp, %0\n\t"
-		       : /* No Outputs */
-		       : "r"(core1_initial_ivt[0]));
+	/* Reset stack to MSP and set it to 0x20080000 */
+	__asm volatile(
+		"mov	r0, #0\n\t"
+		"msr	control, r0\n\t"
+		"mov	sp, %0\n\t"
+		: /* No Outputs */
+		: "r"(core1_initial_ivt[0])
+		: "r0");
+
+	/* Reset FPU */
+	SCB->CPACR  = 0x00000000;
+	FPU->FPDSCR = 0x00000000;
+	FPU->FPCCR  = 0x00000000;
+	__DSB();
+	__ISB();
+
 	__core1_init();
 }
 
-- 
GitLab