KVM: selftests: Add logic to detect if ioctl() failed because VM was killed
authorSean Christopherson <seanjc@google.com>
Wed, 8 Nov 2023 01:09:53 +0000 (17:09 -0800)
committerSean Christopherson <seanjc@google.com>
Wed, 29 Nov 2023 22:51:20 +0000 (14:51 -0800)
commit1b78d474ce4ecbf15a4a8b08994b8ed8ceec0dab
treed5c5388cba83a4455f1bbd0f7081411eca88e1ef
parent6542a00369284c951185be8fa2ed45cf423cce06
KVM: selftests: Add logic to detect if ioctl() failed because VM was killed

Add yet another macro to the VM/vCPU ioctl() framework to detect when an
ioctl() failed because KVM killed/bugged the VM, i.e. when there was
nothing wrong with the ioctl() itself.  If KVM kills a VM, e.g. by way of
a failed KVM_BUG_ON(), all subsequent VM and vCPU ioctl()s will fail with
-EIO, which can be quite misleading and ultimately waste user/developer
time.

Use KVM_CHECK_EXTENSION on KVM_CAP_USER_MEMORY to detect if the VM is
dead and/or bug, as KVM doesn't provide a dedicated ioctl().  Using a
heuristic is obviously less than ideal, but practically speaking the logic
is bulletproof barring a KVM change, and any such change would arguably
break userspace, e.g. if KVM returns something other than -EIO.

Without the detection, tearing down a bugged VM yields a cryptic failure
when deleting memslots:

  ==== Test Assertion Failure ====
  lib/kvm_util.c:689: !ret
  pid=45131 tid=45131 errno=5 - Input/output error
     1 0x00000000004036c3: __vm_mem_region_delete at kvm_util.c:689
     2 0x00000000004042f0: kvm_vm_free at kvm_util.c:724 (discriminator 12)
     3 0x0000000000402929: race_sync_regs at sync_regs_test.c:193
     4 0x0000000000401cab: main at sync_regs_test.c:334 (discriminator 6)
     5 0x0000000000416f13: __libc_start_call_main at libc-start.o:?
     6 0x000000000041855f: __libc_start_main_impl at ??:?
     7 0x0000000000401d40: _start at ??:?
  KVM_SET_USER_MEMORY_REGION failed, rc: -1 errno: 5 (Input/output error)

Which morphs into a more pointed error message with the detection:

  ==== Test Assertion Failure ====
  lib/kvm_util.c:689: false
  pid=80347 tid=80347 errno=5 - Input/output error
     1 0x00000000004039ab: __vm_mem_region_delete at kvm_util.c:689 (discriminator 5)
     2 0x0000000000404660: kvm_vm_free at kvm_util.c:724 (discriminator 12)
     3 0x0000000000402ac9: race_sync_regs at sync_regs_test.c:193
     4 0x0000000000401cb7: main at sync_regs_test.c:334 (discriminator 6)
     5 0x0000000000418263: __libc_start_call_main at libc-start.o:?
     6 0x00000000004198af: __libc_start_main_impl at ??:?
     7 0x0000000000401d90: _start at ??:?
  KVM killed/bugged the VM, check the kernel log for clues

Suggested-by: Michal Luczaj <mhal@rbox.co>
Cc: Oliver Upton <oliver.upton@linux.dev>
Cc: Colton Lewis <coltonlewis@google.com>
Link: https://lore.kernel.org/r/20231108010953.560824-3-seanjc@google.com
Signed-off-by: Sean Christopherson <seanjc@google.com>
tools/testing/selftests/kvm/include/kvm_util_base.h
tools/testing/selftests/kvm/lib/kvm_util.c