|
| 1 | +/* |
| 2 | + * Copyright (c) 2021 Telink Semiconductor |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + */ |
| 6 | + |
| 7 | +#define DT_DRV_COMPAT telink_b91_trng |
| 8 | + |
| 9 | +#include <trng.h> |
| 10 | +#include <drivers/entropy.h> |
| 11 | +#include <string.h> |
| 12 | + |
| 13 | + |
| 14 | +/* API implementation: driver initialization */ |
| 15 | +static int entropy_b91_trng_init(const struct device *dev) |
| 16 | +{ |
| 17 | + ARG_UNUSED(dev); |
| 18 | + |
| 19 | + trng_init(); |
| 20 | + |
| 21 | + return 0; |
| 22 | +} |
| 23 | + |
| 24 | +/* API implementation: get_entropy */ |
| 25 | +static int entropy_b91_trng_get_entropy(const struct device *dev, |
| 26 | + uint8_t *buffer, uint16_t length) |
| 27 | +{ |
| 28 | + ARG_UNUSED(dev); |
| 29 | + |
| 30 | + uint32_t value = 0; |
| 31 | + |
| 32 | + while (length) { |
| 33 | + value = trng_rand(); |
| 34 | + |
| 35 | + if (length >= sizeof(value)) { |
| 36 | + memcpy(buffer, &value, sizeof(value)); |
| 37 | + buffer += sizeof(value); |
| 38 | + length -= sizeof(value); |
| 39 | + } else { |
| 40 | + memcpy(buffer, &value, length); |
| 41 | + break; |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + return 0; |
| 46 | +} |
| 47 | + |
| 48 | +/* API implementation: get_entropy_isr */ |
| 49 | +static int entropy_b91_trng_get_entropy_isr(const struct device *dev, |
| 50 | + uint8_t *buffer, uint16_t length, |
| 51 | + uint32_t flags) |
| 52 | +{ |
| 53 | + ARG_UNUSED(flags); |
| 54 | + |
| 55 | + /* No specific handling in case of running from ISR, just call standard API */ |
| 56 | + entropy_b91_trng_get_entropy(dev, buffer, length); |
| 57 | + |
| 58 | + return 0; |
| 59 | +} |
| 60 | + |
| 61 | +/* Entropy driver APIs structure */ |
| 62 | +static const struct entropy_driver_api entropy_b91_trng_api = { |
| 63 | + .get_entropy = entropy_b91_trng_get_entropy, |
| 64 | + .get_entropy_isr = entropy_b91_trng_get_entropy_isr |
| 65 | +}; |
| 66 | + |
| 67 | +/* Entropy driver registration */ |
| 68 | +DEVICE_DT_INST_DEFINE(0, entropy_b91_trng_init, |
| 69 | + NULL, NULL, NULL, |
| 70 | + PRE_KERNEL_1, CONFIG_KERNEL_INIT_PRIORITY_DEVICE, |
| 71 | + &entropy_b91_trng_api); |
0 commit comments