2017-10-14 07:06:16 +08:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2017 Intel Corporation
|
|
|
|
*
|
|
|
|
* SPDX-License-Identifier: Apache-2.0
|
|
|
|
*/
|
|
|
|
|
2019-06-26 00:25:32 +08:00
|
|
|
#include <sys/atomic.h>
|
2017-10-14 07:06:16 +08:00
|
|
|
#include <kernel.h>
|
2019-06-26 03:53:49 +08:00
|
|
|
#include <drivers/entropy.h>
|
2017-10-14 07:06:16 +08:00
|
|
|
|
2019-05-18 05:28:20 +08:00
|
|
|
static struct device *entropy_driver;
|
2017-10-14 07:06:16 +08:00
|
|
|
|
|
|
|
u32_t sys_rand32_get(void)
|
|
|
|
{
|
2019-05-18 05:28:20 +08:00
|
|
|
struct device *dev = entropy_driver;
|
2017-10-14 07:06:16 +08:00
|
|
|
u32_t random_num;
|
|
|
|
int ret;
|
|
|
|
|
|
|
|
if (unlikely(!dev)) {
|
|
|
|
/* Only one entropy device exists, so this is safe even
|
|
|
|
* if the whole operation isn't atomic.
|
|
|
|
*/
|
|
|
|
dev = device_get_binding(CONFIG_ENTROPY_NAME);
|
2017-11-14 04:12:47 +08:00
|
|
|
__ASSERT((dev != NULL),
|
|
|
|
"Device driver for %s (CONFIG_ENTROPY_NAME) not found. "
|
|
|
|
"Check your build configuration!",
|
|
|
|
CONFIG_ENTROPY_NAME);
|
2019-05-18 05:28:20 +08:00
|
|
|
entropy_driver = dev;
|
2017-10-14 07:06:16 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
ret = entropy_get_entropy(dev, (u8_t *)&random_num,
|
|
|
|
sizeof(random_num));
|
|
|
|
if (unlikely(ret < 0)) {
|
|
|
|
/* Use system timer in case the entropy device couldn't deliver
|
|
|
|
* 32-bit of data. There's not much that can be done in this
|
|
|
|
* situation. An __ASSERT() isn't used here as the HWRNG might
|
|
|
|
* still be gathering entropy during early boot situations.
|
|
|
|
*/
|
|
|
|
|
|
|
|
random_num = k_cycle_get_32();
|
|
|
|
}
|
|
|
|
|
|
|
|
return random_num;
|
|
|
|
}
|