1 // SPDX-License-Identifier: GPL-2.0
3 * sun8i-ce-trng.c - hardware cryptographic offloader for
4 * Allwinner H3/A64/H5/H2+/H6/R40 SoC
6 * Copyright (C) 2015-2020 Corentin Labbe <clabbe@baylibre.com>
8 * This file handle the TRNG
10 * You could find a link for the datasheet in Documentation/arm/sunxi.rst
13 #include <linux/dma-mapping.h>
14 #include <linux/pm_runtime.h>
15 #include <linux/hw_random.h>
17 * Note that according to the algorithm ID, 2 versions of the TRNG exists,
18 * The first present in H3/H5/R40/A64 and the second present in H6.
19 * This file adds support for both, but only the second is working
20 * reliabily according to rngtest.
23 static int sun8i_ce_trng_read(struct hwrng *rng, void *data, size_t max, bool wait)
25 struct sun8i_ce_dev *ce;
30 struct sun8i_ce_flow *chan;
35 ce = container_of(rng, struct sun8i_ce_dev, trng);
37 /* round the data length to a multiple of 32*/
41 d = kzalloc(todo, GFP_KERNEL | GFP_DMA);
45 #ifdef CONFIG_CRYPTO_DEV_SUN8I_CE_DEBUG
47 ce->hwrng_stat_bytes += todo;
50 dma_dst = dma_map_single(ce->dev, d, todo, DMA_FROM_DEVICE);
51 if (dma_mapping_error(ce->dev, dma_dst)) {
52 dev_err(ce->dev, "Cannot DMA MAP DST\n");
57 err = pm_runtime_get_sync(ce->dev);
59 pm_runtime_put_noidle(ce->dev);
63 mutex_lock(&ce->rnglock);
64 chan = &ce->chanlist[flow];
67 memset(cet, 0, sizeof(struct ce_task));
69 cet->t_id = cpu_to_le32(flow);
70 common = ce->variant->trng | CE_COMM_INT;
71 cet->t_common_ctl = cpu_to_le32(common);
73 /* recent CE (H6) need length in bytes, in word otherwise */
74 if (ce->variant->trng_t_dlen_in_bytes)
75 cet->t_dlen = cpu_to_le32(todo);
77 cet->t_dlen = cpu_to_le32(todo / 4);
82 cet->t_dst[0].addr = cpu_to_le32(dma_dst);
83 cet->t_dst[0].len = cpu_to_le32(todo / 4);
84 ce->chanlist[flow].timeout = todo;
86 err = sun8i_ce_run_task(ce, 3, "TRNG");
87 mutex_unlock(&ce->rnglock);
89 pm_runtime_put(ce->dev);
92 dma_unmap_single(ce->dev, dma_dst, todo, DMA_FROM_DEVICE);
98 memzero_explicit(d, todo);
104 int sun8i_ce_hwrng_register(struct sun8i_ce_dev *ce)
108 if (ce->variant->trng == CE_ID_NOTSUPP) {
109 dev_info(ce->dev, "TRNG not supported\n");
112 ce->trng.name = "sun8i Crypto Engine TRNG";
113 ce->trng.read = sun8i_ce_trng_read;
114 ce->trng.quality = 1000;
116 ret = hwrng_register(&ce->trng);
118 dev_err(ce->dev, "Fail to register the TRNG\n");
122 void sun8i_ce_hwrng_unregister(struct sun8i_ce_dev *ce)
124 if (ce->variant->trng == CE_ID_NOTSUPP)
126 hwrng_unregister(&ce->trng);