Re: [kvm-unit-tests PATCH 1/5] lib: Add pseudo random functions

Andrew Jones
2023-12-13T13:38:38Z

On Wed, Dec 13, 2023 at 01:49:38PM +0100, Nina Schoetterl-Glausch wrote:
> Add functions for generating pseudo random 32 and 64 bit values.
> The implementation is very simple and the randomness likely not
> of high quality.
>
> Signed-off-by: Nina Schoetterl-Glausch <nsg@linux.ibm.com>
> ---
> Makefile | 1 +
> lib/libcflat.h | 7 +++++++
> lib/rand.c | 19 +++++++++++++++++++
> 3 files changed, 27 insertions(+)
> create mode 100644 lib/rand.c
>
> diff --git a/Makefile b/Makefile
> index 602910dd..7997e035 100644
> --- a/Makefile
> +++ b/Makefile
> @@ -28,6 +28,7 @@ cflatobjs := \
> lib/printf.o \
> lib/string.o \
> lib/abort.o \
> + lib/rand.o \
> lib/report.o \
> lib/stack.o
>
> diff --git a/lib/libcflat.h b/lib/libcflat.h
> index 700f4352..ed947f98 100644
> --- a/lib/libcflat.h
> +++ b/lib/libcflat.h
> @@ -83,6 +83,13 @@ extern void abort(void) __attribute__((noreturn));
> extern long atol(const char *ptr);
> extern char *getenv(const char *name);
>
> +typedef struct {
> + uint32_t val;
> +} rand_state;
> +#define RAND_STATE_INIT(x) ((rand_state){ .val = (x) })
> +uint32_t rand32(rand_state *state);
> +uint64_t rand64(rand_state *state);
> +
> extern int printf(const char *fmt, ...)
> __attribute__((format(printf, 1, 2)));
> extern int snprintf(char *buf, int size, const char *fmt, ...)
> diff --git a/lib/rand.c b/lib/rand.c
> new file mode 100644
> index 00000000..658c4cbf
> --- /dev/null
> +++ b/lib/rand.c
> @@ -0,0 +1,19 @@
> +/* SPDX-License-Identifier: GPL-2.0-only */
> +/*
> + * pseudo random functions
> + *
> + * Copyright IBM Corp. 2023
> + */
> +
> +#include "libcflat.h"
> +
> +uint32_t rand32(rand_state *state)
> +{
> + state->val = 0x915f77f5 * state->val + 1;
> + return state->val ^ (state->val >> 16);
> +}
> +
> +uint64_t rand64(rand_state *state)
> +{
> + return (uint64_t)rand32(state) << 32 | rand32(state);
> +}
> --
> 2.41.0
>

Alex Bennée posted a prng patch a long time ago that never got merged.

https://www.spinics.net/lists/kvm-arm/msg50921.html

would it be better to merge that?

Thanks,
drew