boot: zephyr: clean ARM core configuration only when selected by user

Clean up the ARM core configuration only when
the CONFIG_MCUBOOT_CLEANUP_ARM_CORE is selected.
This involves cache and stack pointer limit registers.

Add also an MPU cleanup in platforms with the ARM MPU
supported.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
diff --git a/boot/zephyr/arm_cleanup.c b/boot/zephyr/arm_cleanup.c
index a365926..c52c578 100644
--- a/boot/zephyr/arm_cleanup.c
+++ b/boot/zephyr/arm_cleanup.c
@@ -20,3 +20,15 @@
 		NVIC->ICPR[i] = 0xFFFFFFFF;
 	}
 }
+
+__weak void z_arm_clear_arm_mpu_config(void)
+{
+	int i;
+
+	int num_regions =
+		((MPU->TYPE & MPU_TYPE_DREGION_Msk) >> MPU_TYPE_DREGION_Pos);
+
+	for (i = 0; i < num_regions; i++) {
+		ARM_MPU_ClrRegion(i);
+	}
+}
diff --git a/boot/zephyr/include/arm_cleanup.h b/boot/zephyr/include/arm_cleanup.h
index 7ff914a..9f9112c 100644
--- a/boot/zephyr/include/arm_cleanup.h
+++ b/boot/zephyr/include/arm_cleanup.h
@@ -12,4 +12,12 @@
  * Cleanup interrupt priority and interupt enable registers.
  */
 void cleanup_arm_nvic(void);
+
+#if defined(CONFIG_CPU_HAS_ARM_MPU)
+/**
+ * Cleanup all ARM MPU region configuration
+ */
+void z_arm_clear_arm_mpu_config(void);
+#endif
+
 #endif
diff --git a/boot/zephyr/main.c b/boot/zephyr/main.c
index 0082069..a57fba5 100644
--- a/boot/zephyr/main.c
+++ b/boot/zephyr/main.c
@@ -131,12 +131,6 @@
                                      rsp->br_image_off +
                                      rsp->br_hdr->ih_hdr_size);
 
-#ifdef CONFIG_CPU_CORTEX_M7
-    /* Disable instruction cache and data cache before chain-load the application */
-    SCB_DisableDCache();
-    SCB_DisableICache();
-#endif
-
     irq_lock();
 #ifdef CONFIG_SYS_CLOCK_EXISTS
     sys_clock_disable();
@@ -147,6 +141,15 @@
 #endif
 #if CONFIG_MCUBOOT_CLEANUP_ARM_CORE
     cleanup_arm_nvic(); /* cleanup NVIC registers */
+
+#ifdef CONFIG_CPU_CORTEX_M7
+    /* Disable instruction cache and data cache before chain-load the application */
+    SCB_DisableDCache();
+    SCB_DisableICache();
+#endif
+
+#if CONFIG_CPU_HAS_ARM_MPU
+    z_arm_clear_arm_mpu_config();
 #endif
 
 #if defined(CONFIG_BUILTIN_STACK_GUARD) && \
@@ -158,6 +161,8 @@
     __set_MSPLIM(0);
 #endif
 
+#endif /* CONFIG_MCUBOOT_CLEANUP_ARM_CORE */
+
 #ifdef CONFIG_BOOT_INTR_VEC_RELOC
 #if defined(CONFIG_SW_VECTOR_RELAY)
     _vector_table_pointer = vt;