
/*
 * nvram.c
 *
 *  Created on: 4 Jun 2017
 *  Converted to use two 1K pages of STM32L1 Block Erasable Flash memory
 *   instead of 4k of genuine word erasable NVRAM
 *    on 1 Mar 2023
 *      Author: Mike
 */

/* Includes ------------------------------------------------------------------*/
#include "stm32f1xx_hal.h"

#include "nvram.h"

// erase page size on STM32F103 is 1kbytes 
#define NVRAM_PAGESIZE (1024 / sizeof(nvram_info_t))

// decided to allocate 2 pages of Flash as NVRAM
#define NVRAM_WORDS (2 * NVRAM_PAGESIZE)

// NVRAM hardware erases to all 0x
nvram_info_t const HARDWARE_ERASED = {.u16 = 0UL};
// Marked as erased change to all 1
nvram_info_t const MARKED_ERASED = {.u16 = ~0UL};

// allocate the memory for storing the NVRAM data
nvram_info_t NVRAM_Base[NVRAM_WORDS] __attribute__((section(".nvram"))); // set by linker

static void
WriteNVRAM(nvram_info_t *Address, nvram_info_t data)
{
  HAL_FLASH_Unlock();
  HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD, (uint32_t)Address, data.u16);
  HAL_FLASH_Lock();
}

static void
EraseNVRAM(nvram_info_t *Address)
{
  FLASH_EraseInitTypeDef erase = {.TypeErase = FLASH_TYPEERASE_PAGES, .PageAddress = Address, .NbPages = 1};
  uint32_t err;
  HAL_FLASH_Unlock();
  HAL_FLASHEx_Erase(&erase, &err);
  HAL_FLASH_Lock();
}

// returns true if page crossed , used to trigger erasure of
// the other page after copying out all data from other page to new page

static uint8_t _write_nvram_data(nvram_info_t data, int *pIndex)
{
  int base = *pIndex;
  uint8_t pageCrossed = 0;

  /* search blank */
  for (int ptr = 0; ptr < NVRAM_WORDS; ptr++)
  {
    int index = (ptr + base) % NVRAM_WORDS;
    // erase the entry just found
    if (NVRAM_Base[index].data.tag == data.data.tag)
    {
      // erase previous data
      WriteNVRAM(&NVRAM_Base[index], MARKED_ERASED);
      base = ptr;
      break;
    }
  }
  // search forward for next erased or empty element, use it
  for (int offset = 1; offset < NVRAM_WORDS + 1; offset++)
  {
    int index = (base + offset) % NVRAM_WORDS;

    if (NVRAM_Base[index].u16 == HARDWARE_ERASED.u16)
    {
      // if we cross a page by incrementing into it need action
      if (index % NVRAM_PAGESIZE == 0)
        pageCrossed = 1;

      WriteNVRAM(&NVRAM_Base[index], data);
      // now check to see if it actually wrote correctly
      if (NVRAM_Base[index].u16 != data.u16)
      {
        WriteNVRAM(&NVRAM_Base[index], MARKED_ERASED); // Set to all 1 if the data did not write properly
        continue;
      }
      // record where the data was written
      *pIndex = index;
      return pageCrossed;
    }
  }
  // if it gets here, failure.
  return 0;
}

void write_nvram_data(nvram_info_t data)
{
  int index = 0;
  // try the easy case - returns 0 , no further action
  if (!_write_nvram_data(data, &index))
    return;
  // Returns 1, crossed page boundary with write of new data. 
  // Now have the index pointing into the page where we need to copy the data to
  // for any data in the other page, copy it to the new page
  int oldPageBase = index >= NVRAM_PAGESIZE ? 0 : NVRAM_PAGESIZE;
  for (int i = oldPageBase; i < oldPageBase + NVRAM_WORDS; i++)
  {
    if (NVRAM_Base[i].u16 != HARDWARE_ERASED.u16 && NVRAM_Base[i].u16 != MARKED_ERASED.u16)
    {
      int base = i;
      // copy data forwards
      _write_nvram_data(NVRAM_Base[i], &base);
    }
    // erase the page we just copied out of
    EraseNVRAM(&NVRAM_Base[oldPageBase]);
  }
}

nvram_info_t *find_nvram_data(uint8_t searchTag)
{
  for (int ptr = 0; ptr < NVRAM_WORDS; ptr++)
  {
    if (NVRAM_Base[ptr].data.tag == searchTag)
      return &NVRAM_Base[ptr];
  }
  return NULL;
}
