|
- /*-
- * Copyright 2021 John-Mark Gurney.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- */
-
- #include <strobe.h>
-
- #include <strobe_rng_init.h>
-
- #include <stm32l1xx.h>
- #include <stm32l1xx_hal_flash_ex.h>
-
- #include <utilities.h>
-
- #define nitems(x) (sizeof(x) / sizeof *(x))
- #define DEFINE_RNG_SAVE 1
- #if DEFINE_RNG_SAVE
- const rng_word_t rng_save[roundup(32, sizeof(rng_word_t)) / sizeof(rng_word_t)] __attribute__ ((section (".eeprom")));
- #endif
-
- /*
- * Note: This is the end of allocated SRAM, aka, the begining of
- * uninitalized SRAM.
- */
- extern uint8_t end;
-
- void
- strobe_rng_init(void)
- {
-
- /*
- * Seed RNG
- * Seed w/ saved state.
- */
- strobe_seed_prng((uint8_t *)rng_save, sizeof rng_save);
-
- /*
- * On first boot, SRAM is uninitialized and randomness from
- * it is used.
- */
- strobe_seed_prng(&end, 2*1024);
-
- }
-
- void
- strobe_rng_save(void)
- {
- rng_word_t tmp[sizeof rng_save / sizeof(rng_word_t)];
- size_t i;
- int r;
-
- /*
- * Save entropy for next reset.
- */
- r = strobe_randomize((uint8_t *)tmp, sizeof tmp);
- (void)r;
-
- CRITICAL_SECTION_BEGIN();
-
- HAL_FLASHEx_DATAEEPROM_Unlock();
-
- for (i = 0; i < nitems(tmp); i++)
- HAL_FLASHEx_DATAEEPROM_Program(FLASH_TYPEPROGRAMDATA_WORD, (intptr_t)&rng_save[i], tmp[i]);
-
- HAL_FLASHEx_DATAEEPROM_Lock();
-
- CRITICAL_SECTION_END();
- }
|