/* 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 <stm-periph/backup-ram.h>
#include <stm-periph/rcc-manager.h>
#include <stm32/stm32f4xx.h>
#include <helper-macros/helper-macros.h>

#define BACKUP_RAM_BASE BKPSRAM_BASE
#define BACKUP_RAM_SIZE 4096U
#define BACKUP_RAM_SIZE_WORDS (BACKUP_RAM_SIZE / 4U)
#define BACKUP_RAM_END_ADDR (BACKUP_RAM_BASE + BACKUP_RAM_SIZE - 1U)

#define backup_ram ((volatile uint32_t *)BACKUP_RAM_BASE)

#if !is_power_of_two(BACKUP_RAM_SIZE)
#error "Backup RAM size ahs to be a power of two!"
#endif

void backup_ram_init(bool use_backup_regulator)
{
	rcc_manager_enable_clock(&RCC->APB1ENR, BITMASK_TO_BITNO(RCC_APB1ENR_PWREN));

	/* Enable access to backup RAM register set */
	PWR->CR |= PWR_CR_DBP;

	if (use_backup_regulator) {
		/* Enable the backup regulator */
		PWR->CSR |= PWR_CSR_BRE;

		/* Wait until regulator is ready */
		while (!(PWR->CSR & PWR_CSR_BRR));
	}

	/* Enable clock for backup ram interface */
	rcc_manager_enable_clock(&RCC->AHB1ENR, BITMASK_TO_BITNO(RCC_AHB1ENR_BKPSRAMEN));
}

void backup_ram_disable(void)
{
	/* Disable access to backup RAM register set */
	PWR->CR &= ~PWR_CR_DBP;
	rcc_manager_disable_clock(&RCC->APB1ENR, BITMASK_TO_BITNO(RCC_APB1ENR_PWREN));
	rcc_manager_enable_clock(&RCC->AHB1ENR, BITMASK_TO_BITNO(RCC_AHB1ENR_BKPSRAMEN));
}

void backup_ram_wipe(void)
{
	uint32_t i;

	for (i = 0; i < BACKUP_RAM_SIZE_WORDS; i++)
		backup_ram[i] = 0UL;
}

int backup_ram_get_data(uint32_t addr, uint32_t *data, uint32_t count)
{
	volatile uint32_t *ptr;

	if (!data)
		return -1002;
	if (addr >= BACKUP_RAM_SIZE_WORDS)
		return -1001;

	ptr = &backup_ram[addr];

	for (; count > 0; count--)
		*(data++) = *(ptr++);

	return 0;
}

int backup_ram_write_data(uint32_t addr, const uint32_t *data, uint32_t count)
{
	volatile uint32_t *ptr;

	if (!data)
		return -1002;
	if (addr >= BACKUP_RAM_SIZE_WORDS)
		return -1001;

	ptr = &backup_ram[addr];

	for (; count > 0; count--)
		*(ptr++) = *(data++);

	return 0;
}

uint32_t backup_ram_get_size_in_words(void)
{
	return (uint32_t)BACKUP_RAM_SIZE_WORDS;
}

volatile void *backup_ram_get_base_ptr(void)
{
	return backup_ram;
}
