/* Reflow Oven Controller
*
* Copyright (C) 2020  Mario Hüttel <mario.huettel@gmx.net>
*
* This file is part of the Reflow Oven Controller Project.
*
* The reflow oven controller is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* The Reflow Oven Control Firmware is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the reflow oven controller project.
* If not, see <http://www.gnu.org/licenses/>.
*/

#include <reflow-controller/updater/updater.h>
#include <reflow-controller/safety/watchdog.h>
#include "ram-code/updater-ram-code.bin.h"
#include <stm32/stm32f4xx.h>
#include <cmsis/core_cm4.h>
#include <stdint.h>
#include <stddef.h>

void __attribute__((noreturn)) start_updater(void)
{
	const char *updater_src = binary_blob;
	char *dest_ptr = (char *)UPDATER_RAM_CODE_BASE_ADDRESS;
	uint32_t *dest_ptr_words = (uint32_t *)UPDATER_RAM_CODE_BASE_ADDRESS;
	uint32_t updater_size = (uint32_t)sizeof(binary_blob);
	uint32_t i;
	void (*reset_ptr)(void);

	/* This function will never return
	 * because it corrupts memory by copying the ram code for updating
	 * Therefore we have to make sure to only use stack in this function
	 */

	/* Disable all IRQs and ack the watchdog */
	__disable_irq();
	watchdog_ack(WATCHDOG_MAGIC_KEY);

	for (i = 0UL; i < updater_size; i++)
		*(dest_ptr++) = *(updater_src++);

	/* Load the reset vector of the RAM code */
	reset_ptr = (void (*)(void))dest_ptr_words[1];

	/* Move the interrupt vector table to ram code */
	SCB->VTOR = UPDATER_RAM_CODE_BASE_ADDRESS;

	reset_ptr();

	while(1);
}
