Re: [PATCH 2/2] KVM: Fix rcu splat if vm creation fails

From: Wanpeng Li
Date: Mon Nov 04 2019 - 07:25:20 EST


On Mon, 4 Nov 2019 at 20:21, Paolo Bonzini <pbonzini@xxxxxxxxxx> wrote:
>
> On 04/11/19 13:16, Wanpeng Li wrote:
> >> I don't understand this one, hasn't
> >>
> >> WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
> >>
> >> decreased the conut already? With your patch the refcount would then
> >> underflow.
> >
> > r = kvm_arch_init_vm(kvm, type);
> > if (r)
> > goto out_err_no_arch_destroy_vm;
> >
> > out_err_no_disable:
> > kvm_arch_destroy_vm(kvm);
> > WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
> > out_err_no_arch_destroy_vm:
> >
> > So, if kvm_arch_init_vm() fails, we will not execute
> > WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
>
> Uuh of course. But I'd rather do the opposite: move the refcount_set
> earlier so that refcount_dec_and_test can be moved after
> no_arch_destroy_vm. Moving the refcount_set is not strictly necessary,
> but avoids the introduction of yet another label.
>
> diff --git a/virt/kvm/kvm_main.c b/virt/kvm/kvm_main.c
> index e22ff63e5b1a..e7a07132cd7f 100644
> --- a/virt/kvm/kvm_main.c
> +++ b/virt/kvm/kvm_main.c
> @@ -650,6 +650,7 @@ static struct kvm *kvm_create_vm(unsigned long type)
> if (init_srcu_struct(&kvm->irq_srcu))
> goto out_err_no_irq_srcu;
>
> + refcount_set(&kvm->users_count, 1);
> for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
> struct kvm_memslots *slots = kvm_alloc_memslots();
>
> @@ -667,7 +668,6 @@ static struct kvm *kvm_create_vm(unsigned long type)
> goto out_err_no_arch_destroy_vm;
> }
>
> - refcount_set(&kvm->users_count, 1);
> r = kvm_arch_init_vm(kvm, type);
> if (r)
> goto out_err_no_arch_destroy_vm;
> @@ -696,8 +696,8 @@ static struct kvm *kvm_create_vm(unsigned long type)
> hardware_disable_all();
> out_err_no_disable:
> kvm_arch_destroy_vm(kvm);
> - WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
> out_err_no_arch_destroy_vm:
> + WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
> for (i = 0; i < KVM_NR_BUSES; i++)
> kfree(kvm_get_bus(kvm, i));
> for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)

Good point, I will handle these two patches later.

Wanpeng