/*- * 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 #include #include #include #include #include #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 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. * * Note: This depends upon sbrk pointing to uinitalized SRAM. */ strobe_seed_prng(sbrk(0), 2*1024); } SYSINIT_VF(rng_init, SI_SUB_HAL, SI_ORDER_LAST, strobe_rng_init); void strobe_rng_save(void) { rng_word_t tmp[sizeof rng_save / sizeof(rng_word_t)]; size_t i; uint32_t primask; int r; /* * Save entropy for next reset. */ r = strobe_randomize((uint8_t *)tmp, sizeof tmp); (void)r; primask = __get_PRIMASK(); __disable_irq( ); 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(); __set_PRIMASK(primask); } SYSINIT_VF(rng_save, SI_SUB_LAST, SI_ORDER_LAST, strobe_rng_save);