Skip to content

Commit 73369ac

Browse files
committed
KVM: selftests: Provide an API for getting a random bool from an RNG
Move memstress' random bool logic into common code to avoid reinventing the wheel for basic yes/no decisions. Provide an outer wrapper to handle the basic/common case of just wanting a 50/50 chance of something happening. Link: https://lore.kernel.org/r/20240314185459.2439072-3-seanjc@google.com Signed-off-by: Sean Christopherson <seanjc@google.com>
1 parent cb6c691 commit 73369ac

2 files changed

Lines changed: 12 additions & 1 deletion

File tree

tools/testing/selftests/kvm/include/test_util.h

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,17 @@ extern struct guest_random_state guest_rng;
9797
struct guest_random_state new_guest_random_state(uint32_t seed);
9898
uint32_t guest_random_u32(struct guest_random_state *state);
9999

100+
static inline bool __guest_random_bool(struct guest_random_state *state,
101+
uint8_t percent)
102+
{
103+
return (guest_random_u32(state) % 100) < percent;
104+
}
105+
106+
static inline bool guest_random_bool(struct guest_random_state *state)
107+
{
108+
return __guest_random_bool(state, 50);
109+
}
110+
100111
static inline uint64_t guest_random_u64(struct guest_random_state *state)
101112
{
102113
return ((uint64_t)guest_random_u32(state) << 32) | guest_random_u32(state);

tools/testing/selftests/kvm/lib/memstress.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ void memstress_guest_code(uint32_t vcpu_idx)
7474

7575
addr = gva + (page * args->guest_page_size);
7676

77-
if (guest_random_u32(&rand_state) % 100 < args->write_percent)
77+
if (__guest_random_bool(&rand_state, args->write_percent))
7878
*(uint64_t *)addr = 0x0123456789ABCDEF;
7979
else
8080
READ_ONCE(*(uint64_t *)addr);

0 commit comments

Comments
 (0)