Skip to content

Commit

Permalink
KVM: selftests: implement random number generator for guest code
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
Colton Lewis authored and Sean Christopherson committed Nov 16, 2022
1 parent d886724 commit b31f21a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
7 changes: 7 additions & 0 deletions tools/testing/selftests/kvm/include/test_util.h
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
17 changes: 17 additions & 0 deletions tools/testing/selftests/kvm/lib/test_util.c
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,23 @@

#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]?".
*/
Expand Down

0 comments on commit b31f21a

Please sign in to comment.