Re: [PATCH v3 05/16] KVM: selftests: Add helper to generate random u64 in range [min,max]

From: Sean Christopherson

Date: Tue May 26 2026 - 21:58:30 EST


On Tue, Apr 21, 2026, Josh Hilke wrote:
> Introduce kvm_random_u64_in_range(state, min, max). This function
> returns a random u64 in the inclusive range of [min, max] using a struct
> kvm_random_state.
>
> Suggested-by: Sean Christopherson <seanjc@xxxxxxxxxx>
> Signed-off-by: Josh Hilke <jrhilke@xxxxxxxxxx>
> ---
> tools/testing/selftests/kvm/include/test_util.h | 4 ++++
> tools/testing/selftests/kvm/lib/test_util.c | 16 ++++++++++++++++
> 2 files changed, 20 insertions(+)
>
> diff --git a/tools/testing/selftests/kvm/include/test_util.h b/tools/testing/selftests/kvm/include/test_util.h
> index ae39c4293b9a..584a4ab43db5 100644
> --- a/tools/testing/selftests/kvm/include/test_util.h
> +++ b/tools/testing/selftests/kvm/include/test_util.h
> @@ -132,6 +132,10 @@ static inline uint64_t kvm_random_u64(struct kvm_random_state *state)
> return ((uint64_t)kvm_random_u32(state) << 32) | kvm_random_u32(state);
> }
>
> +/* Returns a random u64 in the inclusive range [min, max] */

Put the comment above the definition (But thank you for writing it! I had typed
up a response asking for exactly this, before I realized it was there, just on
the declaration).

> +uint64_t kvm_random_u64_in_range(struct kvm_random_state *state, uint64_t min,
> + uint64_t max);
> +
> enum vm_mem_backing_src_type {
> VM_MEM_SRC_ANONYMOUS,
> VM_MEM_SRC_ANONYMOUS_THP,
> diff --git a/tools/testing/selftests/kvm/lib/test_util.c b/tools/testing/selftests/kvm/lib/test_util.c
> index e342d9fb4771..23d543a9053e 100644
> --- a/tools/testing/selftests/kvm/lib/test_util.c
> +++ b/tools/testing/selftests/kvm/lib/test_util.c
> @@ -42,6 +42,22 @@ uint32_t kvm_random_u32(struct kvm_random_state *state)
> return state->seed;
> }
>
> +uint64_t kvm_random_u64_in_range(struct kvm_random_state *state, uint64_t min, uint64_t max)

Wrap.

> +{
> + uint64_t value;
> + uint64_t range;
> +
> + TEST_ASSERT(min <= max, "min (0x%lx) cannot be greater than max (0x%lx)", min, max);

LOL, that's a rather hilarious error message. Partly because it's so pointless
(gotta love TEST_ASSERT()), partly because @min obviously _can_ be greater than
@max :-)

The "min <= max" that gets printed is pretty darn self-explanatory, maybe take
the opportunity to throw shade at the user/developer?

TEST_ASSERT(min <= max, "PEBKAC, min = 0x%lx, max = 0x%lx", min, max);

> +
> + value = kvm_random_u64(state);
> +
> + range = max - min;
> + if (range == ULLONG_MAX)
> + return value;
> +
> + return min + (value % (range + 1));
> +}
> +
> /*
> * Parses "[0-9]+[kmgt]?".
> */
> --
> 2.54.0.rc2.533.g4f5dca5207-goog
>