1 /*
2 * Copyright 2022, NXP
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #define DT_DRV_COMPAT nxp_imx_caam
8
9 #include <zephyr/device.h>
10 #include <zephyr/drivers/entropy.h>
11 #include <zephyr/random/random.h>
12 #include <zephyr/init.h>
13 #include <zephyr/kernel.h>
14
15 #include "fsl_caam.h"
16
17 struct mcux_entropy_config {
18 CAAM_Type *base;
19 };
20
21 static caam_job_ring_interface_t jrif0 __attribute__((__section__(".nocache")));
22 static uint8_t rng_buff_pool[CONFIG_ENTRY_MCUX_CAAM_POOL_SIZE]
23 __attribute__((__section__(".nocache")));
24
25
26 /* This semaphore is needed to prevent race condition to static variables in the HAL driver */
27 K_SEM_DEFINE(mcux_caam_sem, 1, 1)
28
entropy_mcux_caam_get_entropy(const struct device * dev,uint8_t * buffer,uint16_t length)29 static int entropy_mcux_caam_get_entropy(const struct device *dev,
30 uint8_t *buffer,
31 uint16_t length)
32 {
33 const struct mcux_entropy_config *config = dev->config;
34 status_t status;
35 caam_handle_t handle;
36 uint16_t read_length = 0;
37 uint16_t insert_idx = 0;
38 int ret = 0;
39 k_timeout_t sem_timeout = K_MSEC(10);
40
41 handle.jobRing = kCAAM_JobRing0;
42
43 /*
44 * The buffer passed to the CAAM RNG function needs to be in non-cache
45 * memory. Use an intermediate buffer to stage the data to the user
46 * buffer.
47 */
48 while (insert_idx < length) {
49 read_length = MIN(sizeof(rng_buff_pool), (length - insert_idx));
50
51 ret = k_sem_take(&mcux_caam_sem, sem_timeout);
52 if (ret) {
53 return ret;
54 }
55
56 status = CAAM_RNG_GetRandomData(
57 config->base, &handle, kCAAM_RngStateHandle0,
58 &rng_buff_pool[0], read_length, kCAAM_RngDataAny, NULL);
59
60 k_sem_give(&mcux_caam_sem);
61
62 memcpy(&buffer[insert_idx], &rng_buff_pool[0], read_length);
63 insert_idx += read_length;
64 }
65
66 return 0;
67 }
68
69 static const struct entropy_driver_api entropy_mcux_caam_api_funcs = {
70 .get_entropy = entropy_mcux_caam_get_entropy
71 };
72
73 static const struct mcux_entropy_config entropy_mcux_config = {
74 .base = (CAAM_Type *)DT_INST_REG_ADDR(0)
75 };
76
entropy_mcux_caam_init(const struct device * dev)77 static int entropy_mcux_caam_init(const struct device *dev)
78 {
79 const struct mcux_entropy_config *config = dev->config;
80 caam_config_t conf;
81 status_t status;
82
83 CAAM_GetDefaultConfig(&conf);
84 conf.jobRingInterface[0] = &jrif0;
85
86 status = CAAM_Init(config->base, &conf);
87 __ASSERT_NO_MSG(!status);
88
89 if (status != 0) {
90 return -ENODEV;
91 }
92
93 return 0;
94 }
95
96 DEVICE_DT_INST_DEFINE(0,
97 entropy_mcux_caam_init, NULL, NULL,
98 &entropy_mcux_config,
99 PRE_KERNEL_1, CONFIG_ENTROPY_INIT_PRIORITY,
100 &entropy_mcux_caam_api_funcs);
101