blob: 90a371a59cc73d33066d20e280fc42597ac9006c [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
Sughosh Ganu081da0a2019-12-29 15:30:14 +05306#include <dm.h>
Simon Glass0f2af882020-05-10 11:40:05 -06007#include <log.h>
Sughosh Ganu081da0a2019-12-29 15:30:14 +05308#include <rng.h>
9#include <virtio_types.h>
10#include <virtio.h>
11#include <virtio_ring.h>
12
13#define BUFFER_SIZE 16UL
14
15struct virtio_rng_priv {
16 struct virtqueue *rng_vq;
17};
18
19static int virtio_rng_read(struct udevice *dev, void *data, size_t len)
20{
21 int ret;
Andre Przywara8dd4ecb2023-11-07 16:09:00 +000022 unsigned int rsize = 1;
Sughosh Ganu081da0a2019-12-29 15:30:14 +053023 unsigned char buf[BUFFER_SIZE] __aligned(4);
24 unsigned char *ptr = data;
25 struct virtio_sg sg;
26 struct virtio_sg *sgs[1];
27 struct virtio_rng_priv *priv = dev_get_priv(dev);
28
29 while (len) {
30 sg.addr = buf;
Andre Przywara8dd4ecb2023-11-07 16:09:00 +000031 /*
32 * Work around implementations which always return 8 bytes
33 * less than requested, down to 0 bytes, which would
34 * cause an endless loop otherwise.
35 */
36 sg.length = min(rsize ? len : len + 8, sizeof(buf));
Sughosh Ganu081da0a2019-12-29 15:30:14 +053037 sgs[0] = &sg;
38
39 ret = virtqueue_add(priv->rng_vq, sgs, 0, 1);
40 if (ret)
41 return ret;
42
43 virtqueue_kick(priv->rng_vq);
44
45 while (!virtqueue_get_buf(priv->rng_vq, &rsize))
46 ;
47
Andrew Scull50d11fd2022-05-16 10:41:39 +000048 if (rsize > sg.length)
49 return -EIO;
50
Sughosh Ganu081da0a2019-12-29 15:30:14 +053051 memcpy(ptr, buf, rsize);
52 len -= rsize;
53 ptr += rsize;
54 }
55
56 return 0;
57}
58
59static int virtio_rng_bind(struct udevice *dev)
60{
61 struct virtio_dev_priv *uc_priv = dev_get_uclass_priv(dev->parent);
62
63 /* Indicate what driver features we support */
64 virtio_driver_features_init(uc_priv, NULL, 0, NULL, 0);
65
66 return 0;
67}
68
69static int virtio_rng_probe(struct udevice *dev)
70{
71 struct virtio_rng_priv *priv = dev_get_priv(dev);
72 int ret;
73
74 ret = virtio_find_vqs(dev, 1, &priv->rng_vq);
75 if (ret < 0) {
76 debug("%s: virtio_find_vqs failed\n", __func__);
77 return ret;
78 }
79
80 return 0;
81}
82
83static const struct dm_rng_ops virtio_rng_ops = {
84 .read = virtio_rng_read,
85};
86
87U_BOOT_DRIVER(virtio_rng) = {
88 .name = VIRTIO_RNG_DRV_NAME,
89 .id = UCLASS_RNG,
90 .bind = virtio_rng_bind,
91 .probe = virtio_rng_probe,
92 .remove = virtio_reset,
93 .ops = &virtio_rng_ops,
Simon Glass8a2b47f2020-12-03 16:55:17 -070094 .priv_auto = sizeof(struct virtio_rng_priv),
Sughosh Ganu081da0a2019-12-29 15:30:14 +053095 .flags = DM_FLAG_ACTIVE_DMA,
96};