/* 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.
*
* GDSII-Converter 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/>.
*/

#ifndef __STACK_CHECK_H__
#define __STACK_CHECK_H__

#include <stdint.h>

#define STACK_CHECK_MIN_HEAP_GAP 16UL

/**
 * @brief Get usage of the stack
 * @return Usage of the stack in bytes
 */
int32_t stack_check_get_usage();

/**
 * @brief Get free stack space
 * @return free stack space in bytes. If negative, a stack overflow occured
 */
int32_t stack_check_get_free();

/**
 * @brief Check if the current free stack space is bigger than @ref STACK_CHECK_MIN_HEAP_GAP
 * @return 0: enough space available, -1: stack space low
 */
static inline int stack_check_collision()
{
	int ret = 0;
	int32_t free_space = stack_check_get_free();

	if ((unsigned int)free_space < STACK_CHECK_MIN_HEAP_GAP) {
			ret = -1;
	}

	return ret;
}

/**
 * @brief Get the current stack pointer value
 * @return
 */
static inline uint32_t read_stack_pointer()
{
	uint32_t stack_pointer;

	__asm__ __volatile__ ("mov %0, sp\n\t" : "=r"(stack_pointer) : : );

	return stack_pointer;
}

/**
 * @brief Init the stack corruption detection area.
 *
 * This function initializes the memory area between heap and stack with random values generated by the
 * STM's random number generator. A 32 bit CRC generated by the CRC unit of the STM is appended for verification of the
 * area.
 *
 *
 * @return 0 if successful, else an error has occured in generating a random number. This should never happen
 * @note This function turns on the CRC unit but does not disable it afterwards. Therefore, the CRC unit does not have
 * to be explicitly initialized before calling @ref stack_check_corruption_detect_area.
 */
int stack_check_init_corruption_detect_area(void);

/**
 * @brief Check the CRC of the stack corruption detection area
 *
 * This function checks the stack corruption detection area, which must be initialized by
 * @ref stack_check_init_corruption_detect_area beforehand.
 *
 * The CRC unit must be enabled for this function to work properly.
 * After calling @ref stack_check_init_corruption_detect_area, this is the case.
 *
 * @return 0 if no error is detected, all other values are an error.
 * @note Make sure CRC unit is enabled.
 */
int stack_check_corruption_detect_area(void);

#endif /* __STACK_CHECK_H__ */
