From 65d9d27098fcbca2b80b79db136372f55373d5ca Mon Sep 17 00:00:00 2001
From: Rahix <rahix@rahix.de>
Date: Wed, 21 Aug 2019 02:49:26 +0200
Subject: [PATCH] fix(rtc): Call RTC_EnableRTCE after RTC_Init

RTC_Init will turn off the RTC and readout will not be possible until
RTC_EnableRTCE is called.  The previous version worked because the
bootloader would call RTC_Init and Epicardium would then call
RTC_EnableRTCE.

This broke with the hardware-init changes in

    b76ac8fc500c51d3948b34db0c607dc6f46fab13

and lead to behavior where cold boot would not enable the RTC.  This
commit switches the order of the two calls in the bootloader so it is
always initialized correctly.  Because some older bootloaders are
already out in the field, this commit also introduces basic rtc init
into Epicardium so the new firmware can work correctly with older
bootloaders.

Signed-off-by: Rahix <rahix@rahix.de>
---
 epicardium/modules/hardware.c | 16 ++++++++++++++++
 lib/card10/card10.c           |  6 +++---
 2 files changed, 19 insertions(+), 3 deletions(-)

diff --git a/epicardium/modules/hardware.c b/epicardium/modules/hardware.c
index cb6b70b5..5cb95dc2 100644
--- a/epicardium/modules/hardware.c
+++ b/epicardium/modules/hardware.c
@@ -17,6 +17,7 @@
 
 #include "gpio.h"
 #include "i2c.h"
+#include "rtc.h"
 #include "spi.h"
 #include "trng.h"
 
@@ -70,6 +71,21 @@ int hardware_early_init(void)
 	 */
 	PB_Init();
 
+	/* Enable 32 kHz output */
+	while (RTC_SquareWave(
+		       MXC_RTC,
+		       SQUARE_WAVE_ENABLED,
+		       F_32KHZ,
+		       NOISE_IMMUNE_MODE,
+		       NULL) == E_BUSY
+	)
+		;
+
+	/* If we don't have a valid time yet, set it to 2019-01-01 */
+	if (RTC_GetSecond() < 1546300800UL) {
+		epic_rtc_set_milliseconds(1546300800UL * 1000);
+	}
+
 	/*
 	 * SPI for ECG
 	 */
diff --git a/lib/card10/card10.c b/lib/card10/card10.c
index 624db760..371912d5 100644
--- a/lib/card10/card10.c
+++ b/lib/card10/card10.c
@@ -53,9 +53,6 @@ void card10_init(void)
 
 	TMR_Delay(MXC_TMR0, MSEC(1000), 0);
 
-	while (RTC_EnableRTCE(MXC_RTC) == E_BUSY)
-		;
-
 	// Enable 32 kHz output
 	while (RTC_SquareWave(
 		       MXC_RTC,
@@ -71,6 +68,9 @@ void card10_init(void)
 			;
 	}
 
+	while (RTC_EnableRTCE(MXC_RTC) == E_BUSY)
+		;
+
 	// Enable SPI
 	sys_cfg_spi_t spi17y_master_cfg;
 
-- 
GitLab