1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright (c) 2022 Google, Inc.
4  * Written by Andrew Scull <ascull@google.com>
5  */
6 
7 #include <dm.h>
8 #include <virtio_types.h>
9 #include <virtio.h>
10 #include <virtio_ring.h>
11 #include <dm/device-internal.h>
12 #include <dm/test.h>
13 #include <rng.h>
14 #include <test/test.h>
15 #include <test/ut.h>
16 
17 /* This is a brittle means of getting access to the virtqueue */
18 struct virtio_rng_priv {
19 	struct virtqueue *rng_vq;
20 };
21 
22 /* Test the virtio-rng driver validates the used size */
dm_test_virtio_rng_check_len(struct unit_test_state * uts)23 static int dm_test_virtio_rng_check_len(struct unit_test_state *uts)
24 {
25 	struct udevice *bus, *dev;
26 	struct virtio_rng_priv *priv;
27 	u8 buffer[16];
28 
29 	/* check probe success */
30 	ut_assertok(uclass_first_device_err(UCLASS_VIRTIO, &bus));
31 	ut_assertnonnull(bus);
32 
33 	/* check the child virtio-rng device is bound */
34 	ut_assertok(device_find_first_child(bus, &dev));
35 	ut_assertnonnull(dev);
36 
37 	/* probe the virtio-rng driver */
38 	ut_assertok(device_probe(dev));
39 
40 	/* simulate the device returning the buffer with too much data */
41 	priv = dev_get_priv(dev);
42 	priv->rng_vq->vring.used->idx = 1;
43 	priv->rng_vq->vring.used->ring[0].id = 0;
44 	priv->rng_vq->vring.used->ring[0].len = U32_MAX;
45 
46 	/* check the driver gracefully handles the error */
47 	ut_asserteq(-EIO, dm_rng_read(dev, buffer, sizeof(buffer)));
48 
49 	return 0;
50 }
51 DM_TEST(dm_test_virtio_rng_check_len, UTF_SCAN_PDATA | UTF_SCAN_FDT);
52