Re: [PATCH v2] KVM: Move VM's worker kthreads back to the original cgroups before exiting.

From: Vipin Sharma
Date: Tue Jan 18 2022 - 14:54:36 EST


On Tue, Dec 28, 2021 at 9:17 AM Sean Christopherson <seanjc@xxxxxxxxxx> wrote:
>
> On Wed, Dec 22, 2021, Vipin Sharma wrote:
> > diff --git a/kernel/cgroup/cgroup-v1.c b/kernel/cgroup/cgroup-v1.c
> > index 81c9e0685948..81d4b2f2acf0 100644
> > --- a/kernel/cgroup/cgroup-v1.c
> > +++ b/kernel/cgroup/cgroup-v1.c
> > int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
> > @@ -58,6 +60,9 @@ int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
> > struct cgroup_root *root;
> > int retval = 0;
> >
> > + if (!from)
> > + from = kthreadd_task;
>
> Rather than sully cgroup_attach_task_all() with this behavior, can't KVM do
>
> cgroup_attach_task_all(current->real_parent, current)
>
> since AFAICT real_parent is guaranteed to point at kthreadd_task.
>

Thanks for the "real_parent" suggestion. This is much cleaner and
better than changing cgroup logic. I will make this change.

> > diff --git a/virt/kvm/kvm_main.c b/virt/kvm/kvm_main.c
> > index b0f7e6eb00ff..f7504578c374 100644
> > --- a/virt/kvm/kvm_main.c
> > +++ b/virt/kvm/kvm_main.c
> > @@ -5793,6 +5793,19 @@ static int kvm_vm_worker_thread(void *context)
> > if (!kthread_should_stop())
> > err = thread_fn(kvm, data);
> >
> > +out:
> > + /*
> > + * We need to move the kthread back to its original cgroups, so that it
>
> Please state what is being done, not what "needs" to be done. The need to do
> something is implicit, otherwise we wouldn't be doing it.
>

I will update the statement. Thanks.

> > + * doesn't linger in the cgroups of the user process after the user
> > + * process has already terminated.
> > + *
> > + * kthread_stop() waits on 'exited' completion condition which is set
> > + * in exit_mm(), via mm_release(), in do_exit(). However, kthread
> > + * is removed from cgroups in the cgroup_exit() which is called after
> > + * exit_mm(). This causes lingering of kthreads in cgroups after main
> > + * VM process has finished.
> > + */
> > + WARN_ON(cgroup_attach_task_all(NULL, current));
>
> This should not WARN, cgroup_attach_task_all() needs to perform allocations and
> will fail with -ENOMEM even in the absense of kernel bugs.
>

I will remove WARN_ON and print an error using kvm_err(), it will be
similar to the earlier call of cgroup_attach_task_all() in the same
function.

Thanks