OSDN Git Service

KVM: selftests: implement random number generator for guest code
authorColton Lewis <coltonlewis@google.com>
Mon, 7 Nov 2022 18:22:05 +0000 (18:22 +0000)
committerSean Christopherson <seanjc@google.com>
Wed, 16 Nov 2022 18:09:19 +0000 (10:09 -0800)
Implement random number generator for guest code to randomize parts
of the test, making it less predictable and a more accurate reflection
of reality.

The random number generator chosen is the Park-Miller Linear
Congruential Generator, a fancy name for a basic and well-understood
random number generator entirely sufficient for this purpose.

Signed-off-by: Colton Lewis <coltonlewis@google.com>
Reviewed-by: Sean Christopherson <seanjc@google.com>
Reviewed-by: David Matlack <dmatlack@google.com>
Link: https://lore.kernel.org/r/20221107182208.479157-2-coltonlewis@google.com
Signed-off-by: Sean Christopherson <seanjc@google.com>
tools/testing/selftests/kvm/include/test_util.h
tools/testing/selftests/kvm/lib/test_util.c

index 3be98e8..80d6416 100644 (file)
@@ -77,6 +77,13 @@ struct timespec timespec_sub(struct timespec ts1, struct timespec ts2);
 struct timespec timespec_elapsed(struct timespec start);
 struct timespec timespec_div(struct timespec ts, int divisor);
 
+struct guest_random_state {
+       uint32_t seed;
+};
+
+struct guest_random_state new_guest_random_state(uint32_t seed);
+uint32_t guest_random_u32(struct guest_random_state *state);
+
 enum vm_mem_backing_src_type {
        VM_MEM_SRC_ANONYMOUS,
        VM_MEM_SRC_ANONYMOUS_THP,
index c2d9c68..5c22fa4 100644 (file)
 #include "test_util.h"
 
 /*
+ * Random number generator that is usable from guest code. This is the
+ * Park-Miller LCG using standard constants.
+ */
+
+struct guest_random_state new_guest_random_state(uint32_t seed)
+{
+       struct guest_random_state s = {.seed = seed};
+       return s;
+}
+
+uint32_t guest_random_u32(struct guest_random_state *state)
+{
+       state->seed = (uint64_t)state->seed * 48271 % ((uint32_t)(1 << 31) - 1);
+       return state->seed;
+}
+
+/*
  * Parses "[0-9]+[kmgt]?".
  */
 size_t parse_size(const char *size)