• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2010-2020 Espressif Systems (Shanghai) PTE LTD
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 #include "sdkconfig.h"
15 #include "bootloader_random.h"
16 #include "hal/cpu_hal.h"
17 #include "soc/wdev_reg.h"
18 
19 #ifndef BOOTLOADER_BUILD
20 #include "esp_system.h"
21 #include "driver/periph_ctrl.h"
22 
bootloader_fill_random(void * buffer,size_t length)23  __attribute__((weak)) void bootloader_fill_random(void *buffer, size_t length)
24 {
25     return esp_fill_random(buffer, length);
26 }
27 
28 #else
bootloader_fill_random(void * buffer,size_t length)29  __attribute__((weak)) void bootloader_fill_random(void *buffer, size_t length)
30 {
31     uint8_t *buffer_bytes = (uint8_t *)buffer;
32     uint32_t random;
33     uint32_t start, now;
34 
35     assert(buffer != NULL);
36 
37     for (size_t i = 0; i < length; i++) {
38         if (i == 0 || i % 4 == 0) { /* redundant check is for a compiler warning */
39             /* in bootloader with ADC feeding HWRNG, we accumulate 1
40                bit of entropy per 40 APB cycles (==80 CPU cycles.)
41 
42                To avoid reading the entire RNG hardware state out
43                as-is, we repeatedly read the RNG register and XOR all
44                values.
45             */
46             random = REG_READ(WDEV_RND_REG);
47             start = cpu_hal_get_cycle_count();
48             do {
49                 random ^= REG_READ(WDEV_RND_REG);
50                 now = cpu_hal_get_cycle_count();
51             } while (now - start < 80 * 32 * 2); /* extra factor of 2 is precautionary */
52         }
53         buffer_bytes[i] = random >> ((i % 4) * 8);
54     }
55 }
56 
57 #endif // BOOTLOADER_BUILD
58