Sughosh Ganu | 081da0a | 2019-12-29 15:30:14 +0530 | [diff] [blame] | 1 | // SPDX-License-Identifier: GPL-2.0+ |
| 2 | /* |
| 3 | * Copyright (c) 2019, Linaro Limited |
| 4 | */ |
| 5 | |
| 6 | #include <common.h> |
| 7 | #include <dm.h> |
| 8 | #include <rng.h> |
| 9 | #include <virtio_types.h> |
| 10 | #include <virtio.h> |
| 11 | #include <virtio_ring.h> |
| 12 | |
| 13 | #define BUFFER_SIZE 16UL |
| 14 | |
| 15 | struct virtio_rng_priv { |
| 16 | struct virtqueue *rng_vq; |
| 17 | }; |
| 18 | |
| 19 | static int virtio_rng_read(struct udevice *dev, void *data, size_t len) |
| 20 | { |
| 21 | int ret; |
| 22 | unsigned int rsize; |
| 23 | 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; |
| 31 | sg.length = min(len, sizeof(buf)); |
| 32 | sgs[0] = &sg; |
| 33 | |
| 34 | ret = virtqueue_add(priv->rng_vq, sgs, 0, 1); |
| 35 | if (ret) |
| 36 | return ret; |
| 37 | |
| 38 | virtqueue_kick(priv->rng_vq); |
| 39 | |
| 40 | while (!virtqueue_get_buf(priv->rng_vq, &rsize)) |
| 41 | ; |
| 42 | |
| 43 | memcpy(ptr, buf, rsize); |
| 44 | len -= rsize; |
| 45 | ptr += rsize; |
| 46 | } |
| 47 | |
| 48 | return 0; |
| 49 | } |
| 50 | |
| 51 | static int virtio_rng_bind(struct udevice *dev) |
| 52 | { |
| 53 | struct virtio_dev_priv *uc_priv = dev_get_uclass_priv(dev->parent); |
| 54 | |
| 55 | /* Indicate what driver features we support */ |
| 56 | virtio_driver_features_init(uc_priv, NULL, 0, NULL, 0); |
| 57 | |
| 58 | return 0; |
| 59 | } |
| 60 | |
| 61 | static int virtio_rng_probe(struct udevice *dev) |
| 62 | { |
| 63 | struct virtio_rng_priv *priv = dev_get_priv(dev); |
| 64 | int ret; |
| 65 | |
| 66 | ret = virtio_find_vqs(dev, 1, &priv->rng_vq); |
| 67 | if (ret < 0) { |
| 68 | debug("%s: virtio_find_vqs failed\n", __func__); |
| 69 | return ret; |
| 70 | } |
| 71 | |
| 72 | return 0; |
| 73 | } |
| 74 | |
| 75 | static const struct dm_rng_ops virtio_rng_ops = { |
| 76 | .read = virtio_rng_read, |
| 77 | }; |
| 78 | |
| 79 | U_BOOT_DRIVER(virtio_rng) = { |
| 80 | .name = VIRTIO_RNG_DRV_NAME, |
| 81 | .id = UCLASS_RNG, |
| 82 | .bind = virtio_rng_bind, |
| 83 | .probe = virtio_rng_probe, |
| 84 | .remove = virtio_reset, |
| 85 | .ops = &virtio_rng_ops, |
| 86 | .priv_auto_alloc_size = sizeof(struct virtio_rng_priv), |
| 87 | .flags = DM_FLAG_ACTIVE_DMA, |
| 88 | }; |