KVM: selftests: Provide an API for getting a random bool from an RNG
authorSean Christopherson <seanjc@google.com>
Thu, 14 Mar 2024 18:54:55 +0000 (11:54 -0700)
committerSean Christopherson <seanjc@google.com>
Mon, 29 Apr 2024 19:50:42 +0000 (12:50 -0700)
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>
tools/testing/selftests/kvm/include/test_util.h
tools/testing/selftests/kvm/lib/memstress.c

index 4b78fb7e539ee7fec3a54c6f4630775c6039c69c..3e473058849ffa81b6402f4e3526bac924edfd85 100644 (file)
@@ -97,6 +97,17 @@ extern struct guest_random_state guest_rng;
 struct guest_random_state new_guest_random_state(uint32_t seed);
 uint32_t guest_random_u32(struct guest_random_state *state);
 
+static inline bool __guest_random_bool(struct guest_random_state *state,
+                                      uint8_t percent)
+{
+       return (guest_random_u32(state) % 100) < percent;
+}
+
+static inline bool guest_random_bool(struct guest_random_state *state)
+{
+       return __guest_random_bool(state, 50);
+}
+
 static inline uint64_t guest_random_u64(struct guest_random_state *state)
 {
        return ((uint64_t)guest_random_u32(state) << 32) | guest_random_u32(state);
index 3b7fe1778d7bccfea966ddf686f9569dce58b15a..aa0a01988150401c80127e68002e12c68fa803c6 100644 (file)
@@ -74,7 +74,7 @@ void memstress_guest_code(uint32_t vcpu_idx)
 
                        addr = gva + (page * args->guest_page_size);
 
-                       if (guest_random_u32(&rand_state) % 100 < args->write_percent)
+                       if (__guest_random_bool(&rand_state, args->write_percent))
                                *(uint64_t *)addr = 0x0123456789ABCDEF;
                        else
                                READ_ONCE(*(uint64_t *)addr);