perf: Fix race in removing an event
perf: Fix race in removing an event

When removing a (sibling) event we do:

	raw_spin_lock_irq(&ctx->lock);
	perf_group_detach(event);
	raw_spin_unlock_irq(&ctx->lock);

	<hole>

	perf_remove_from_context(event);
		raw_spin_lock_irq(&ctx->lock);
		...
		raw_spin_unlock_irq(&ctx->lock);

Now, assuming the event is a sibling, it will be 'unreachable' for
things like ctx_sched_out() because that iterates the
groups->siblings, and we just unhooked the sibling.

So, if during <hole> we get ctx_sched_out(), it will miss the event
and not call event_sched_out() on it, leaving it programmed on the
PMU.

The subsequent perf_remove_from_context() call will find the ctx is
inactive and only call list_del_event() to remove the event from all
other lists.

Hereafter we can proceed to free the event; while still programmed!

Close this hole by moving perf_group_detach() inside the same
ctx->lock region(s) perf_remove_from_context() has.

The condition on inherited events only in __perf_event_exit_task() is
likely complete crap because non-inherited events are part of groups
too and we're tearing down just the same. But leave that for another
patch.

Most-likely-Fixes: e03a9a55b4e ("perf: Change close() semantics for group events")
Reported-by: Vince Weaver <b486a64568929e3535e394c7ca98794b49f6ab74@maine.edu>
Tested-by: Vince Weaver <b486a64568929e3535e394c7ca98794b49f6ab74@maine.edu>
Much-staring-at-traces-by: Vince Weaver <b486a64568929e3535e394c7ca98794b49f6ab74@maine.edu>
Much-staring-at-traces-by: Thomas Gleixner <00e4cf8f46a57000a44449bf9dd8cbbcc209fd2a@linutronix.de>
Cc: Arnaldo Carvalho de Melo <293abb6b76d7791c0732cc517d38c4b5c734b87f@kernel.org>
Cc: Linus Torvalds <69652caca27c8b940640ad396ab71f93cacec34f@linux-foundation.org>
Signed-off-by: Peter Zijlstra <3fddac958924aef220f202ca567388ddab3f14a8@infradead.org>
Link: 32acf34bdefb3f2b6344dac19cd00fc98d582d31@laptop.programming.kicks-ass.net
Signed-off-by: Ingo Molnar <9dbbbf0688fedc85ad4da37637f1a64b8c718ee2@kernel.org>

KristFoundation/Programs,KristFoundation/Programs,KristFoundation/Programs,KristFoundation/Programs,KristFoundation/Programs,KristFoundation/Programs