blob: 786359a6e3641d76dd5dccf8f1d1bd8435d5e853 [file] [log] [blame]
Sughosh Ganu081da0a2019-12-29 15:30:14 +05301// SPDX-License-Identifier: GPL-2.0+
2/*
3 * Copyright (c) 2019, Linaro Limited
4 */
5
6#include <common.h>
7#include <dm.h>
Simon Glass0f2af882020-05-10 11:40:05 -06008#include <log.h>
Sughosh Ganu081da0a2019-12-29 15:30:14 +05309#include <rng.h>
10#include <virtio_types.h>
11#include <virtio.h>
12#include <virtio_ring.h>
13
14#define BUFFER_SIZE 16UL
15
16struct virtio_rng_priv {
17 struct virtqueue *rng_vq;
18};
19
20static int virtio_rng_read(struct udevice *dev, void *data, size_t len)
21{
22 int ret;
Andre Przywara8dd4ecb2023-11-07 16:09:00 +000023 unsigned int rsize = 1;
Sughosh Ganu081da0a2019-12-29 15:30:14 +053024 unsigned char buf[BUFFER_SIZE] __aligned(4);
25 unsigned char *ptr = data;
26 struct virtio_sg sg;
27 struct virtio_sg *sgs[1];
28 struct virtio_rng_priv *priv = dev_get_priv(dev);
29
30 while (len) {
31 sg.addr = buf;
Andre Przywara8dd4ecb2023-11-07 16:09:00 +000032 /*
33 * Work around implementations which always return 8 bytes
34 * less than requested, down to 0 bytes, which would
35 * cause an endless loop otherwise.
36 */
37 sg.length = min(rsize ? len : len + 8, sizeof(buf));
Sughosh Ganu081da0a2019-12-29 15:30:14 +053038 sgs[0] = &sg;
39
40 ret = virtqueue_add(priv->rng_vq, sgs, 0, 1);
41 if (ret)
42 return ret;
43
44 virtqueue_kick(priv->rng_vq);
45
46 while (!virtqueue_get_buf(priv->rng_vq, &rsize))
47 ;
48
Andrew Scull50d11fd2022-05-16 10:41:39 +000049 if (rsize > sg.length)
50 return -EIO;
51
Sughosh Ganu081da0a2019-12-29 15:30:14 +053052 memcpy(ptr, buf, rsize);
53 len -= rsize;
54 ptr += rsize;
55 }
56
57 return 0;
58}
59
60static int virtio_rng_bind(struct udevice *dev)
61{
62 struct virtio_dev_priv *uc_priv = dev_get_uclass_priv(dev->parent);
63
64 /* Indicate what driver features we support */
65 virtio_driver_features_init(uc_priv, NULL, 0, NULL, 0);
66
67 return 0;
68}
69
70static int virtio_rng_probe(struct udevice *dev)
71{
72 struct virtio_rng_priv *priv = dev_get_priv(dev);
73 int ret;
74
75 ret = virtio_find_vqs(dev, 1, &priv->rng_vq);
76 if (ret < 0) {
77 debug("%s: virtio_find_vqs failed\n", __func__);
78 return ret;
79 }
80
81 return 0;
82}
83
84static const struct dm_rng_ops virtio_rng_ops = {
85 .read = virtio_rng_read,
86};
87
88U_BOOT_DRIVER(virtio_rng) = {
89 .name = VIRTIO_RNG_DRV_NAME,
90 .id = UCLASS_RNG,
91 .bind = virtio_rng_bind,
92 .probe = virtio_rng_probe,
93 .remove = virtio_reset,
94 .ops = &virtio_rng_ops,
Simon Glass8a2b47f2020-12-03 16:55:17 -070095 .priv_auto = sizeof(struct virtio_rng_priv),
Sughosh Ganu081da0a2019-12-29 15:30:14 +053096 .flags = DM_FLAG_ACTIVE_DMA,
97};