1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) 2019, Linaro Limited
4  */
5 
6 #include <common.h>
7 #include <dm.h>
8 #include <rand.h>
9 #include <rng.h>
10 
11 #include <linux/string.h>
12 
sandbox_rng_read(struct udevice * dev,void * data,size_t len)13 static int sandbox_rng_read(struct udevice *dev, void *data, size_t len)
14 {
15 	unsigned int i, seed, random;
16 	unsigned char *buf = data;
17 	size_t nrem, nloops;
18 
19 	if (!len)
20 		return 0;
21 
22 	nloops = len / sizeof(random);
23 	seed = get_timer(0) ^ rand();
24 	srand(seed);
25 
26 	for (i = 0, nrem = len; i < nloops; i++) {
27 		random = rand();
28 		memcpy(buf, &random, sizeof(random));
29 		buf += sizeof(random);
30 		nrem -= sizeof(random);
31 	}
32 
33 	if (nrem) {
34 		random = rand();
35 		memcpy(buf, &random, nrem);
36 	}
37 
38 	return 0;
39 }
40 
41 static const struct dm_rng_ops sandbox_rng_ops = {
42 	.read = sandbox_rng_read,
43 };
44 
45 static const struct udevice_id sandbox_rng_match[] = {
46 	{
47 		.compatible = "sandbox,sandbox-rng",
48 	},
49 	{},
50 };
51 
52 U_BOOT_DRIVER(sandbox_rng) = {
53 	.name = "sandbox-rng",
54 	.id = UCLASS_RNG,
55 	.of_match = sandbox_rng_match,
56 	.ops = &sandbox_rng_ops,
57 };
58