Re: [PATCH 2/2] KVM: selftests: Test forced instruction emulation in dirty log test (x86 only)

From: Sean Christopherson
Date: Thu Feb 15 2024 - 13:53:31 EST


On Thu, Feb 15, 2024, Oliver Upton wrote:
> On Wed, Feb 14, 2024 at 05:00:04PM -0800, Sean Christopherson wrote:
> > Add forced emulation of MOV and LOCK CMPXCHG instructions in the dirty log
> > test's guest code to verify that KVM's emulator marks pages dirty as
> > expected (and obviously to verify the emulator works at all). In the long
> > term, the guest code would ideally hammer more of KVM's emulator, but for
> > starters, cover the two major paths: writes and atomics.
> >
> > To minimize #ifdeffery, wrap only the related code that is x86 specific,
> > unnecessariliy synchronizing an extra boolean to the guest is far from the
> > end of the world.
>
> Meh, I wouldn't say the end result in guest_write_memory() is that
> pretty. Just ifdef the whole function and provide a generic implementation
> for the other architectures.
>
> > Signed-off-by: Sean Christopherson <seanjc@xxxxxxxxxx>
> > ---
> > tools/testing/selftests/kvm/dirty_log_test.c | 36 ++++++++++++++++++--
> > 1 file changed, 33 insertions(+), 3 deletions(-)
> >
> > diff --git a/tools/testing/selftests/kvm/dirty_log_test.c b/tools/testing/selftests/kvm/dirty_log_test.c
> > index eaad5b20854c..ff1d1c7f05d8 100644
> > --- a/tools/testing/selftests/kvm/dirty_log_test.c
> > +++ b/tools/testing/selftests/kvm/dirty_log_test.c
> > @@ -92,6 +92,29 @@ static uint64_t guest_test_phys_mem;
> > */
> > static uint64_t guest_test_virt_mem = DEFAULT_GUEST_TEST_MEM;
> >
> > +static bool is_forced_emulation_enabled;
> > +
> > +static void guest_write_memory(uint64_t *mem, uint64_t val, uint64_t rand)
> > +{
> > +#ifdef __x86_64__
> > + if (is_forced_emulation_enabled && (rand & 1)) {
> > + if (rand & 2) {
>
> Can't you invert the logic and drop a level of indentation?
>
> if (!(is_forced_emulation_enabled && (rand & 1))) {
> *mem = val;
> } else if (rand & 2) {
> movq
> } else {
> cmpxchg8b
> }

Yeah, the funky flow I concocted was done purely to have the "no emulation" path
fall through to the common "*mem = val". I don't have a strong preference, I
mentally flipped a coin on doing that versus what you suggested, and apparently
chose poorly :-)