/*!
 * @file main.c
 *
 * @brief MSPM33C321A test program running from the MAIN flash: blinks the
 *        red LED (PA0, jumper J6 on the LP-MSPM33C321A) and counts in SRAM.
 *
 * The state can be checked with PEEDI (addresses from mspm33_flash.map):
 *   test.magic   = 0x600DF00D  - main() was reached
 *   test.data_ok = 1           - .data was copied from the flash
 *   test.counter                 incremented continuously
 *   test.toggles                 incremented at every LED toggle
 *   test.vtor                    SCB->VTOR seen by the program
 *   test.stop                    built with "make STOP=1": number of WFI in
 *                                STOP mode (after 6 LED toggles)
 *
 * @note Copyright (c) Ronetix GmbH. All rights reserved.
 */
#include <stdint.h>

#define REG(a)			(*(volatile uint32_t *)(a))

/* GPIOA (GPIO0), non-secure alias */
#define GPIOA_BASE		0x400F0000
#define GPIO_PWREN		REG(GPIOA_BASE + 0x0800)
#define GPIO_RSTCTL		REG(GPIOA_BASE + 0x0804)
#define GPIO_DOUTTGL	REG(GPIOA_BASE + 0x12B0)
#define GPIO_DOESET		REG(GPIOA_BASE + 0x12D0)

#define PWREN_KEY		0x26000000
#define RSTCTL_KEY		0xB1000000
#define RSTCTL_RESET	0x00000003		/* RESETSTKYCLR | RESETASSERT */

/* IOMUX: PINCM1 = PA0. The PINCM registers start at offset 4 (TRM Table 9-3),
 * the datasheet pin table shows 0x400CC000 for PINCM1, but that is wrong */
#define IOMUX_PINCM1	REG(0x400CC004)
#define PINCM_PC		(1 << 7)		/* connect the pin */
#define PINCM_PF_GPIO	1

#define SCB_VTOR		REG(0xE000ED08)
#define SCB_SCR			REG(0xE000ED10)
#define SCR_SLEEPDEEP	(1 << 2)

/* SYSCTL PMODECFG: DSLEEP = 0 - STOP on a deep sleep */
#define SYSCTL_PMODECFG	REG(0x400AF000 + 0x1144)

#define LED_PA0			(1 << 0)

struct test_state
{
	uint32_t magic;
	uint32_t data_ok;
	uint32_t counter;
	uint32_t toggles;
	uint32_t vtor;
	uint32_t stop;
};

volatile struct test_state test;		/* .bss: cleared by reset_handler */
static volatile uint32_t data_pattern = 0xA5A55A5A;	/* .data */

static void led_init(void)
{
	GPIO_RSTCTL = RSTCTL_KEY | RSTCTL_RESET;
	GPIO_PWREN = PWREN_KEY | 1;
	for (volatile int i = 0; i < 100; i++)
		;		/* the GPIO needs a few cycles after the power enable */

	IOMUX_PINCM1 = PINCM_PC | PINCM_PF_GPIO;
	GPIO_DOESET = LED_PA0;
}

int main(void)
{
	test.magic = 0x600DF00D;
	test.data_ok = (data_pattern == 0xA5A55A5A);
	test.vtor = SCB_VTOR;

	led_init();

	for (;;)
	{
		for (uint32_t i = 0; i < 2000000; i++)
			test.counter++;

		GPIO_DOUTTGL = LED_PA0;
		test.toggles++;

#ifdef TEST_STOP
		/* after 6 toggles (LED off): STOP mode, no wakeup source */
		if (test.toggles == 6)
		{
			SYSCTL_PMODECFG = 0;
			SCB_SCR |= SCR_SLEEPDEEP;

			for (;;)
			{
				test.stop++;
				__asm volatile ("dsb\n\twfi");
			}
		}
#endif
	}
}
