1 // Copyright 2016 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
15
16 #include <stdint.h>
17 #include <stddef.h>
18 #include <string.h>
19 #include <sys/param.h>
20 #include "esp_attr.h"
21 #include "hal/cpu_hal.h"
22 #include "esp32s2/clk.h"
23 #include "soc/wdev_reg.h"
24
esp_random(void)25 uint32_t IRAM_ATTR esp_random(void)
26 {
27 /* The PRNG which implements WDEV_RANDOM register gets 2 bits
28 * of extra entropy from a hardware randomness source every APB clock cycle
29 * (provided WiFi or BT are enabled). To make sure entropy is not drained
30 * faster than it is added, this function needs to wait for at least 16 APB
31 * clock cycles after reading previous word. This implementation may actually
32 * wait a bit longer due to extra time spent in arithmetic and branch statements.
33 *
34 * As a (probably unncessary) precaution to avoid returning the
35 * RNG state as-is, the result is XORed with additional
36 * WDEV_RND_REG reads while waiting.
37 */
38
39 /* This code does not run in a critical section, so CPU frequency switch may
40 * happens while this code runs (this will not happen in the current
41 * implementation, but possible in the future). However if that happens,
42 * the number of cycles spent on frequency switching will certainly be more
43 * than the number of cycles we need to wait here.
44 */
45 uint32_t cpu_to_apb_freq_ratio = esp_clk_cpu_freq() / esp_clk_apb_freq();
46
47 static uint32_t last_ccount = 0;
48 uint32_t ccount;
49 uint32_t result = 0;
50 do {
51 ccount = cpu_hal_get_cycle_count();
52 result ^= REG_READ(WDEV_RND_REG);
53 } while (ccount - last_ccount < cpu_to_apb_freq_ratio * 16);
54 last_ccount = ccount;
55 return result ^ REG_READ(WDEV_RND_REG);
56 }
57
esp_fill_random(void * buf,size_t len)58 void esp_fill_random(void *buf, size_t len)
59 {
60 assert(buf != NULL);
61 uint8_t *buf_bytes = (uint8_t *)buf;
62 while (len > 0) {
63 uint32_t word = esp_random();
64 uint32_t to_copy = MIN(sizeof(word), len);
65 memcpy(buf_bytes, &word, to_copy);
66 buf_bytes += to_copy;
67 len -= to_copy;
68 }
69 }
70