From 97884f62e2cb834bea3eb708045db503752db8f0 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 | 16 ++++++++++++++--
 1 file changed, 14 insertions(+), 2 deletions(-)

diff --git a/epicardium/api/control.c b/epicardium/api/control.c
index b8987b43e..3bed0ec82 100644
--- a/epicardium/api/control.c
+++ b/epicardium/api/control.c
@@ -45,9 +45,21 @@ static uintptr_t core1_initial_ivt[] = {
  */
 __attribute__((naked)) void __core1_reset(void)
 {
-	__asm volatile("mov	sp, %0\n\t"
+	/* 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]));
+		       : "r"(core1_initial_ivt[0])
+		       : "r0");
+
+	/* Reset FPU */
+	SCB->CPACR  = 0x00000000;
+	FPU->FPDSCR = 0x00000000;
+	FPU->FPCCR  = 0x00000000;
+	__DSB();
+	__ISB();
+
 	__core1_init();
 }
 
-- 
GitLab