blob: b85545c2ee5c1b74679b4e0f27ba6353704f276c [file] [log] [blame]
Sughosh Ganu03018ea2019-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 Glassf7ae49f2020-05-10 11:40:05 -06008#include <log.h>
Sughosh Ganu03018ea2019-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;
23 unsigned int rsize;
24 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;
32 sg.length = min(len, sizeof(buf));
33 sgs[0] = &sg;
34
35 ret = virtqueue_add(priv->rng_vq, sgs, 0, 1);
36 if (ret)
37 return ret;
38
39 virtqueue_kick(priv->rng_vq);
40
41 while (!virtqueue_get_buf(priv->rng_vq, &rsize))
42 ;
43
Andrew Scull43937a42022-05-16 10:41:39 +000044 if (rsize > sg.length)
45 return -EIO;
46
Sughosh Ganu03018ea2019-12-29 15:30:14 +053047 memcpy(ptr, buf, rsize);
48 len -= rsize;
49 ptr += rsize;
50 }
51
52 return 0;
53}
54
55static int virtio_rng_bind(struct udevice *dev)
56{
57 struct virtio_dev_priv *uc_priv = dev_get_uclass_priv(dev->parent);
58
59 /* Indicate what driver features we support */
60 virtio_driver_features_init(uc_priv, NULL, 0, NULL, 0);
61
62 return 0;
63}
64
65static int virtio_rng_probe(struct udevice *dev)
66{
67 struct virtio_rng_priv *priv = dev_get_priv(dev);
68 int ret;
69
70 ret = virtio_find_vqs(dev, 1, &priv->rng_vq);
71 if (ret < 0) {
72 debug("%s: virtio_find_vqs failed\n", __func__);
73 return ret;
74 }
75
76 return 0;
77}
78
79static const struct dm_rng_ops virtio_rng_ops = {
80 .read = virtio_rng_read,
81};
82
83U_BOOT_DRIVER(virtio_rng) = {
84 .name = VIRTIO_RNG_DRV_NAME,
85 .id = UCLASS_RNG,
86 .bind = virtio_rng_bind,
87 .probe = virtio_rng_probe,
88 .remove = virtio_reset,
89 .ops = &virtio_rng_ops,
Simon Glass41575d82020-12-03 16:55:17 -070090 .priv_auto = sizeof(struct virtio_rng_priv),
Sughosh Ganu03018ea2019-12-29 15:30:14 +053091 .flags = DM_FLAG_ACTIVE_DMA,
92};