Re: [PATCH v13 13/14] KVM: selftests: Let dirty_log_test async for dirty ring test

From: Peter Xu
Date: Fri Nov 06 2020 - 13:06:19 EST


On Fri, Nov 06, 2020 at 12:27:54PM +0100, Paolo Bonzini wrote:
> On 01/10/20 03:22, Peter Xu wrote:
> > +
> > +static void vcpu_sig_handler(int sig)
> > +{
> > + TEST_ASSERT(sig == SIG_IPI, "unknown signal: %d", sig);
> > +}
> > +
>
> Unless you also use run->immediate_exit in vcpu_kick, this is racy. The
> alternative is to _not_ set up a signal handler and instead block the
> signal. KVM_SET_SIGNAL_MASK unblocks the signal inside the VM and on -EINTR
> sigwait accepts the signal (removes it from the set of pending signal).

Thanks for picking up the series!

I think you're right. One trivial comment below:

>
> This is a bit more complicated, but I think it's a good idea to do it this
> way for documentation purposes. Here is the patch:
>
> diff --git a/tools/testing/selftests/kvm/dirty_log_test.c
> b/tools/testing/selftests/kvm/dirty_log_test.c
> index 4b404dfdc2f9..9a5b876b74af 100644
> --- a/tools/testing/selftests/kvm/dirty_log_test.c
> +++ b/tools/testing/selftests/kvm/dirty_log_test.c
> @@ -172,11 +172,6 @@ static pthread_t vcpu_thread;
> /* Only way to pass this to the signal handler */
> static struct kvm_vm *current_vm;
>
> -static void vcpu_sig_handler(int sig)
> -{
> - TEST_ASSERT(sig == SIG_IPI, "unknown signal: %d", sig);
> -}
> -
> static void vcpu_kick(void)
> {
> pthread_kill(vcpu_thread, SIG_IPI);
> @@ -484,13 +479,26 @@ static void *vcpu_worker(void *data)
> struct kvm_vm *vm = data;
> uint64_t *guest_array;
> uint64_t pages_count = 0;
> - struct sigaction sigact;
> + struct kvm_signal_mask *sigmask = alloca(offsetof(struct kvm_signal_mask,
> sigset)
> + + sizeof(sigset_t));
> + sigset_t *sigset = (sigset_t *) &sigmask->sigset;
>
> current_vm = vm;
> vcpu_fd = vcpu_get_fd(vm, VCPU_ID);
> - memset(&sigact, 0, sizeof(sigact));
> - sigact.sa_handler = vcpu_sig_handler;
> - sigaction(SIG_IPI, &sigact, NULL);
> +
> + /*
> + * SIG_IPI is unblocked atomically while in KVM_RUN. It causes the
> + * ioctl to return with -EINTR, but it is still pending and we need
> + * to accept it with the sigwait.
> + */
> + sigmask->len = 8;
> + pthread_sigmask(0, NULL, sigset);

Not extremely important, but still better with SIG_BLOCK imho, since it seems
not all archs defined SIG_BLOCK as zero.

> + vcpu_ioctl(vm, VCPU_ID, KVM_SET_SIGNAL_MASK, sigmask);
> + sigaddset(sigset, SIG_IPI);
> + pthread_sigmask(SIG_BLOCK, sigset, NULL);
> +
> + sigemptyset(sigset);
> + sigaddset(sigset, SIG_IPI);
>
> guest_array = addr_gva2hva(vm, (vm_vaddr_t)random_array);
>
> @@ -500,6 +508,11 @@ static void *vcpu_worker(void *data)
> pages_count += TEST_PAGES_PER_LOOP;
> /* Let the guest dirty the random pages */
> ret = ioctl(vcpu_fd, KVM_RUN, NULL);
> + if (ret == -EINTR) {
> + int sig = -1;
> + sigwait(sigset, &sig);
> + assert(sig == SIG_IPI);
> + }
> log_mode_after_vcpu_run(vm, ret, errno);
> }
>

--
Peter Xu