Skip to contentSkip to conversation

perf: Cleanup user's child events

PATCH In review Alexander Shishkin 5 participants 33 messages Jan 15, 2016 – Jan 29, 2016

Subsystems (5)
BPF perf events Tracing BPF tracing +1 more subsystems
lore
Share & tools
lore

Alexander Shishkin

author reviewer
#0 lore raw

PATCH 1/1 perf: Cleanup user's child events

Events are leaking in the following scenario: user creates an event for task A, task A forks into B (producing a child event), user closes the original event. Both original user's event and its child will remain for as long as task B is around. In other words, we don't clean up children when we try to release the parent.

This patch cleans up user event's children when its file descriptor is closed.

---
 kernel/events/core.c | 38 +++++++++++++++++++++++++++++++++++++-
 1 file changed, 37 insertions(+), 1 deletion(-)
kernel/events/core.c +37 -1
index 630f53acce..867c4347ea 100644
@@ -3828,7 +3828,43 @@ EXPORT_SYMBOL_GPL(perf_event_release_kernel);
  */
 static int perf_release(struct inode *inode, struct file *file)
 {
-	put_event(file->private_data);
+	struct perf_event *event = file->private_data, *child, *tmp;
+	LIST_HEAD(child_list);
+
+	/*
+	 * event::child_mutex nests inside ctx::lock, so move children
+	 * to a safe place first and avoid inversion
+	 */
+	mutex_lock(&event->child_mutex);
+	list_splice_init(&event->child_list, &child_list);
+	mutex_unlock(&event->child_mutex);
+
+	list_for_each_entry_safe(child, tmp, &child_list, child_list) {
+		struct perf_event_context *ctx;
+
+		/*
+		 * This is somewhat similar to perf_free_event(),
+		 * except for these events are alive and need
+		 * proper perf_remove_from_context().
+		 */
+		ctx = perf_event_ctx_lock(child);
+		perf_remove_from_context(child, true);
+		perf_event_ctx_unlock(child, ctx);
+
+		list_del(&child->child_list);
+
+		/* Children will have exactly one reference */
+		free_event(child);
+
+		/*
+		 * This matches the refcount bump in inherit_event();
+		 * this can't be the last reference.
+		 */
+		put_event(event);
+	}
+
+	/* Must be the last reference */
+	put_event(event);
 	return 0;
 }
 
Signature · 1 line
2.7.0.rc3
maintainer
#1 lore raw
Quoted 5 lines · Alexander Shishkin

Events are leaking in the following scenario: user creates an event for task A, task A forks into B (producing a child event), user closes the original event. Both original user's event and its child will remain for as long as task B is around. In other words, we don't clean up children when we try to release the parent.

The orphan stuff should clear those up, no?

author reviewer
#2 lore raw
Quoted 8 lines · Peter Zijlstra
Quoted 5 lines · Alexander Shishkin

Events are leaking in the following scenario: user creates an event for task A, task A forks into B (producing a child event), user closes the original event. Both original user's event and its child will remain for as long as task B is around. In other words, we don't clean up children when we try to release the parent.

The orphan stuff should clear those up, no?

Not if they don't schedule after the parent's gone.

Regards,
--
Alex

maintainer
#3 lore raw
Quoted 9 lines · Alexander Shishkin
Quoted 7 lines · Peter Zijlstra
Quoted 5 lines · Alexander Shishkin

Events are leaking in the following scenario: user creates an event for task A, task A forks into B (producing a child event), user closes the original event. Both original user's event and its child will remain for as long as task B is around. In other words, we don't clean up children when we try to release the parent.

Quoted 3 lines
Quoted 1 line

The orphan stuff should clear those up, no?

Not if they don't schedule after the parent's gone.

This is true. So when Jiri did this we tried the immediate thing and that exploded due to lock inversions.

You mention some of that. Let me go dig out that old thread to see if its the same.

I feel that we should not have both approaches.

author reviewer
#4 lore raw

PATCH 1/1 perf: Synchronously cleanup child events

The orphan cleanup workqueue doesn't always catch orphans, for example, if they never schedule after they are orphaned. IOW, the event leak is still very real. It also wouldn't work for kernel counters.

Also, there seems to be no reason not to carry out this cleanup procedure synchronously during parent event's destruction.

This patch replaces the workqueue approach with a simple cleanup round in the event's destruction path. To avoid racing with clone, we still check that parent event has an owner in the inheritance path.

---
 include/linux/perf_event.h |   3 --
 kernel/events/core.c       | 121 ++++++++++++++++-----------------------------
 2 files changed, 43 insertions(+), 81 deletions(-)
include/linux/perf_event.h +0 -3
index 6612732d8f..cd9c1ace29 100644
@@ -634,9 +634,6 @@ struct perf_event_context {
 	int				nr_cgroups;	 /* cgroup evts */
 	void				*task_ctx_data; /* pmu specific data */
 	struct rcu_head			rcu_head;
-
-	struct delayed_work		orphans_remove;
-	bool				orphans_remove_sched;
 };
 
 /*
kernel/events/core.c +43 -78

170 lines not on this page · raw message

Signature · 1 line
2.7.0.rc3
maintainer
#5 lore raw

Re: [PATCH] perf: Synchronously cleanup child events

Quoted 7 lines · Alexander Shishkin

int perf_event_release_kernel(struct perf_event *event) {

(quoted diff) +4 -0
+	struct perf_event *child, *tmp;
+	LIST_HEAD(child_list);
 
+	if (!is_kernel_event(event))
+		perf_remove_from_owner(event);

Review

Quoted 10 lines
(quoted diff) +8 -0
 
+	event->owner = NULL;
 
+	/*
+	 * event::child_mutex nests inside ctx::lock, so move children
+	 * to a safe place first and avoid inversion
+	 */
+	mutex_lock(&event->child_mutex);
+	list_splice_init(&event->child_list, &child_list);
+	mutex_unlock(&event->child_mutex);

I suspect this races against inherit_event(), like:

	inherit_event()			perf_event_release_kernel()

	if (is_orphaned_event(parent_event) /* false */

					event->owner = NULL

	mutex_lock(child_mutex);
	list_splice
	mutex_unlock(child_mutex);

					mutex_lock(child_mutex);
					list_add_tail
					mutex_unlock(child_mutex);

Something like this would fix that I think, not sure its the best way though...

kernel/events/core.c +13 -5
@@ -979,8 +979,8 @@ static void put_ctx(struct perf_event_co
  * Lock order:
  *	task_struct::perf_event_mutex
  *	  perf_event_context::mutex
- *	    perf_event_context::lock
  *	    perf_event::child_mutex;
+ *	      perf_event_context::lock
  *	    perf_event::mmap_mutex
  *	    mmap_sem
  */
@@ -8956,6 +8958,16 @@ inherit_event(struct perf_event *parent_
 	if (parent_event->parent)
 		parent_event = parent_event->parent;
 
+	WARN_ON_ONCE(parent_event->ctx->parent_ctx);
+	/*
+	 * Serialize against perf_event_kernel_release()'s orphanage..
+	 */
+	mutex_lock(&parent_event->child_mutex);
+	if (is_orphaned_event(parent_event)) {
+		mutex_unlock(&parent_event->child_mutex);
+		return NULL;
+	}
+
 	child_event = perf_event_alloc(&parent_event->attr,
 					   parent_event->cpu,
 					   child,
@@ -8964,8 +8976,8 @@ inherit_event(struct perf_event *parent_
 	if (IS_ERR(child_event))
 		return child_event;
 
-	if (is_orphaned_event(parent_event) ||
-	    !atomic_long_inc_not_zero(&parent_event->refcount)) {
+	if (!atomic_long_inc_not_zero(&parent_event->refcount)) {
+		mutex_unlock(&parent_event->child_mutex);
 		free_event(child_event);
 		return NULL;
 	}
@@ -9013,8 +9025,6 @@ inherit_event(struct perf_event *parent_
 	/*
 	 * Link this into the parent event's child list
 	 */
-	WARN_ON_ONCE(parent_event->ctx->parent_ctx);
-	mutex_lock(&parent_event->child_mutex);
 	list_add_tail(&child_event->child_list, &parent_event->child_list);
 	mutex_unlock(&parent_event->child_mutex);
 
author reviewer
#6 lore raw

Re: [PATCH] perf: Synchronously cleanup child events

Quoted 21 lines · Peter Zijlstra
Quoted 7 lines · Alexander Shishkin

int perf_event_release_kernel(struct perf_event *event) {

(quoted diff) +4 -0
+	struct perf_event *child, *tmp;
+	LIST_HEAD(child_list);
 
+	if (!is_kernel_event(event))
+		perf_remove_from_owner(event);

Review

Quoted 10 lines
(quoted diff) +8 -0
 
+	event->owner = NULL;
 
+	/*
+	 * event::child_mutex nests inside ctx::lock, so move children
+	 * to a safe place first and avoid inversion
+	 */
+	mutex_lock(&event->child_mutex);
+	list_splice_init(&event->child_list, &child_list);
+	mutex_unlock(&event->child_mutex);

I suspect this races against inherit_event(), like:

Quoted 13 lines
	inherit_event()			perf_event_release_kernel()

	if (is_orphaned_event(parent_event) /* false */

					event->owner = NULL

	mutex_lock(child_mutex);
	list_splice
	mutex_unlock(child_mutex);

					mutex_lock(child_mutex);
					list_add_tail
					mutex_unlock(child_mutex);

Indeed, this is possible.

Quoted 8 lines

Something like this would fix that I think, not sure its the best way though...

kernel/events/core.c static void put_ctx(struct perf_event_co · line 986

Quoted 9 lines
kernel/events/core.c +1 -1
@@ -979,8 +979,8 @@ static void put_ctx(struct perf_event_co
  * Lock order:
  *	task_struct::perf_event_mutex
  *	  perf_event_context::mutex
- *	    perf_event_context::lock
  *	    perf_event::child_mutex;
+ *	      perf_event_context::lock
  *	    perf_event::mmap_mutex
  *	    mmap_sem
  */

This is, actually, the order that we have already:

perf_ioctl():                ctx::mutex
-> perf_event_for_each():    event::child_mutex
   -> _perf_event_enable():  ctx::lock

that is, ctx::lock already nests inside event::child_mutex. So what you're suggesting is an ok solution.

Regards,
--
Alex

author reviewer
#7 lore raw

Re: [PATCH] perf: Synchronously cleanup child events

In reply to Peter Zijlstra
Quoted 15 lines · Peter Zijlstra

I suspect this races against inherit_event(), like:

	inherit_event()			perf_event_release_kernel()

	if (is_orphaned_event(parent_event) /* false */

					event->owner = NULL

	mutex_lock(child_mutex);
	list_splice
	mutex_unlock(child_mutex);

					mutex_lock(child_mutex);
					list_add_tail
					mutex_unlock(child_mutex);

Or how about this instead:

kernel/events/core.c +8 -2
index 8eb3fee429..cd9f1ac537 100644
@@ -3786,8 +3786,9 @@ int perf_event_release_kernel(struct perf_event *event)
 
 	event->owner = NULL;
 
+retry:
 	/*
-	 * event::child_mutex nests inside ctx::lock, so move children
+	 * event::child_mutex nests inside ctx::mutex, so move children
 	 * to a safe place first and avoid inversion
 	 */
 	mutex_lock(&event->child_mutex);
@@ -3818,8 +3819,13 @@ int perf_event_release_kernel(struct perf_event *event)
 		put_event(event);
 	}
 
-	/* Must be the last reference */
+	/* Must be the last reference, .. */
 	put_event(event);
+
+	/* .. unless we raced with inherit_event(), in which case, repeat */
+	if (atomic_long_inc_not_zero(&event->refcount))
+		goto retry;
+
 	return 0;
 }
 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
maintainer
#8 lore raw

Re: [PATCH] perf: Synchronously cleanup child events

Quoted 1 line · Alexander Shishkin

Or how about this instead:

In principle better since it doesn't increase the lock hold times etc., but buggy I think:

Quoted 16 lines
kernel/events/core.c +2 -1
index 8eb3fee429..cd9f1ac537 100644
@@ -3786,8 +3786,9 @@ int perf_event_release_kernel(struct perf_event *event)
 
 	event->owner = NULL;
 
+retry:
 	/*
-	 * event::child_mutex nests inside ctx::lock, so move children
+	 * event::child_mutex nests inside ctx::mutex, so move children
 	 * to a safe place first and avoid inversion
 	 */
 	mutex_lock(&event->child_mutex);

kernel/events/core.c int perf_event_release_kernel(struct perf_event *event) · line 3825

Quoted 8 lines
kernel/events/core.c +3 -1
@@ -3818,8 +3819,13 @@ int perf_event_release_kernel(struct perf_event *event)
 		put_event(event);
 	}
 
-	/* Must be the last reference */
+	/* Must be the last reference, .. */
 	put_event(event);
+
+	/* .. unless we raced with inherit_event(), in which case, repeat */

Nothing prevents @event from being freed here, which would make:

kernel/events/core.c int perf_event_release_kernel(struct perf_event *event) · line 3826

Quoted 1 line
kernel/events/core.c +1 -0
+	if (atomic_long_inc_not_zero(&event->refcount))

a use-after-free.

You'll have to do something like:

static bool put_event_last(struct perf_event *event, long value)

{
	if (atomic_long_cmpxchg(&event->refcount, 1, 0)) {
		__put_event(event); /* normal put_event() body */
		return true;
	}
	return false;
}

with which you can do:

	if (!put_event_last(event))
		goto retry;
author reviewer
#9 lore raw

PATCH v2 1/1 perf: Synchronously cleanup child events

The orphan cleanup workqueue doesn't always catch orphans, for example, if they never schedule after they are orphaned. IOW, the event leak is still very real. It also wouldn't work for kernel counters.

Also, there seems to be no reason not to carry out this cleanup procedure synchronously during parent event's destruction.

This patch replaces the workqueue approach with a simple cleanup round in the event's destruction path. To avoid racing with clone, we still check that parent event has an owner in the inheritance path.

---
 include/linux/perf_event.h |   3 -
 kernel/events/core.c       | 142 ++++++++++++++++++++-------------------------
 2 files changed, 63 insertions(+), 82 deletions(-)
include/linux/perf_event.h +0 -3
index 6612732d8f..cd9c1ace29 100644
@@ -634,9 +634,6 @@ struct perf_event_context {
 	int				nr_cgroups;	 /* cgroup evts */
 	void				*task_ctx_data; /* pmu specific data */
 	struct rcu_head			rcu_head;
-
-	struct delayed_work		orphans_remove;
-	bool				orphans_remove_sched;
 };
 
 /*
kernel/events/core.c +63 -79

205 lines not on this page · raw message

Signature · 1 line
2.7.0.rc3
maintainer
#10 lore raw

Re: [PATCH v2] perf: Synchronously cleanup child events

Quoted 9 lines · Alexander Shishkin
(quoted diff) +2 -0
+static void __put_event(struct perf_event *event)
 {
 	struct perf_event_context *ctx;
 
 	if (!is_kernel_event(event))
 		perf_remove_from_owner(event);
 
 
+int perf_event_release_kernel(struct perf_event *event)

Review

Quoted 10 lines
(quoted diff) +6 -0
 {
+	struct perf_event *child, *tmp;
+	LIST_HEAD(child_list);
 
+	if (!is_kernel_event(event))
+		perf_remove_from_owner(event);
 
+	event->owner = NULL;
 
+retry:
	<snip>

kernel/events/core.c static void put_event(struct perf_event *event) · line 3843

Quoted 9 lines
kernel/events/core.c +8 -0
+	/*
+	 * If this is the last reference, we're done here, otherwise
+	 * we must have raced with inherit_event(), in which case, repeat
+	 */
+	if (!put_event_last(event))
+		goto retry;
 
+	return 0;
+}

So I think there's a number of problems still :-(

I all starts with having two perf_remove_from_owner() calls (as I mentioned on IRC), this doesn't make sense.

I think the moment you close the file and userspace looses control over it, we should drop the owner bit, which is exactly the one remove_from_owner in perf_release().

If, for some magical reason, the event lives on after that (and we'll get to that), it should live on owner-less.

Now, assume someone has such a magical reference, then our put_event_last() goto again loop will never terminate, this seems like a bad thing.

The most obvious place that generates such magical references would be the bpf arraymap doing perf_event_get() on things. There are a few other places that take temp references (perf_mmap_close), but those are 'short' lived and while ugly will not cause massive grief. The BPF one OTOH is a real problem here.

And looking at the BPF stuff, that code seems to assume perf_event_kernel_release() := put_event(), so this patch breaks that too.

Alexei, is there a reason the arraymap stuff needs a perf event ref as opposed to a file ref? I'm forever a little confused on how perf<->bpf works.

#11 lore raw

Re: [PATCH v2] perf: Synchronously cleanup child events

Quoted 56 lines · Peter Zijlstra
Quoted 9 lines · Alexander Shishkin
(quoted diff) +2 -0
+static void __put_event(struct perf_event *event)
 {
 	struct perf_event_context *ctx;
 
 	if (!is_kernel_event(event))
 		perf_remove_from_owner(event);
 
 
+int perf_event_release_kernel(struct perf_event *event)

Review

Quoted 10 lines
(quoted diff) +6 -0
 {
+	struct perf_event *child, *tmp;
+	LIST_HEAD(child_list);
 
+	if (!is_kernel_event(event))
+		perf_remove_from_owner(event);
 
+	event->owner = NULL;
 
+retry:
	<snip>

kernel/events/core.c static void put_event(struct perf_event *event) · line 3843

Quoted 9 lines
kernel/events/core.c +8 -0
+	/*
+	 * If this is the last reference, we're done here, otherwise
+	 * we must have raced with inherit_event(), in which case, repeat
+	 */
+	if (!put_event_last(event))
+		goto retry;
 
+	return 0;
+}

So I think there's a number of problems still :-(

I all starts with having two perf_remove_from_owner() calls (as I mentioned on IRC), this doesn't make sense.

I think the moment you close the file and userspace looses control over it, we should drop the owner bit, which is exactly the one remove_from_owner in perf_release().

If, for some magical reason, the event lives on after that (and we'll get to that), it should live on owner-less.

Now, assume someone has such a magical reference, then our put_event_last() goto again loop will never terminate, this seems like a bad thing.

The most obvious place that generates such magical references would be the bpf arraymap doing perf_event_get() on things. There are a few other places that take temp references (perf_mmap_close), but those are 'short' lived and while ugly will not cause massive grief. The BPF one OTOH is a real problem here.

Quoted 8 lines

And looking at the BPF stuff, that code seems to assume perf_event_kernel_release() := put_event(), so this patch breaks that too.

Alexei, is there a reason the arraymap stuff needs a perf event ref as opposed to a file ref? I'm forever a little confused on how perf<->bpf works.

A file ref will not work, since user space could have closed that perf_event file to avoid unnecessary FDs.
Program only need the stable pointer to 'struct perf_event' which it will use while running.
At the end it will call perf_event_kernel_release() which is == put_event().
It was the case that 'perf_events' were normal refcnt-ed structures and the last guy frees it.
This put_event_last() logic definitely looks problematic. There are no ordering guarantees.
User space may close FD, while struct perf_event is still alive. The loop around perf_event_last() looks buggy.
I'm obviously missing the main goal of this patch.

maintainer
#12 lore raw

Re: [PATCH v2] perf: Synchronously cleanup child events

Quoted 13 lines · Alexei Starovoitov
Quoted 11 lines · Peter Zijlstra

The most obvious place that generates such magical references would be the bpf arraymap doing perf_event_get() on things. There are a few other places that take temp references (perf_mmap_close), but those are 'short' lived and while ugly will not cause massive grief. The BPF one OTOH is a real problem here.

And looking at the BPF stuff, that code seems to assume perf_event_kernel_release() := put_event(), so this patch breaks that too.

Quoted 6 lines
Quoted 3 lines

Alexei, is there a reason the arraymap stuff needs a perf event ref as opposed to a file ref? I'm forever a little confused on how perf<->bpf works.

A file ref will not work, since user space could have closed that perf_event file to avoid unnecessary FDs.

So I'm (possibly again) confused on how BPF works.

I thought the reason you handed in perf events from userspace; as opposed to creating your own with perf_event_create_kernel_counter(); was because userspace was interested in the output.

Also, BPF should not be a way to get around the filedesc resource limit.

Quoted 6 lines

Program only need the stable pointer to 'struct perf_event' which it will use while running.
At the end it will call perf_event_kernel_release() which is == put_event().
It was the case that 'perf_events' were normal refcnt-ed structures and the last guy frees it.

Sort-of, but user events are (or should be, rather) tied to the filedesc to account the resources used.

There is also the event->owner field, we track the task that created the event, with your current scheme that is left dangling once userspace closes the last filedesc and you still have a ref open.

Quoted 5 lines

This put_event_last() logic definitely looks problematic. There are no ordering guarantees.
User space may close FD, while struct perf_event is still alive. The loop around perf_event_last() looks buggy.
I'm obviously missing the main goal of this patch.

Right, so the patch in question tries to synchronously clean up everything related to the counter when we close the file. Such that the file better reflects the actual resource usage.

Currently we do this async (and with holes).

In short, user created event really should be filedesc based, yes we have event references, but those 'should' be short lived.

#13 lore raw

Re: [PATCH v2] perf: Synchronously cleanup child events

Quoted 18 lines · Peter Zijlstra
Quoted 17 lines · Alexei Starovoitov
Quoted 14 lines · Peter Zijlstra

The most obvious place that generates such magical references would be the bpf arraymap doing perf_event_get() on things. There are a few other places that take temp references (perf_mmap_close), but those are 'short' lived and while ugly will not cause massive grief. The BPF one OTOH is a real problem here.

And looking at the BPF stuff, that code seems to assume perf_event_kernel_release() := put_event(), so this patch breaks that too.

Alexei, is there a reason the arraymap stuff needs a perf event ref as opposed to a file ref? I'm forever a little confused on how perf<->bpf works.

Quoted 8 lines
Quoted 2 lines

A file ref will not work, since user space could have closed that perf_event file to avoid unnecessary FDs.

So I'm (possibly again) confused on how BPF works.

I thought the reason you handed in perf events from userspace; as opposed to creating your own with perf_event_create_kernel_counter(); was because userspace was interested in the output.

yes. There are two use cases of perf_events from bpf:
1. sw_bpf_output event is used by bpf to push samples into it and user spaces reads it as normal via mmap
2. PERF_TYPE_HARDWARE event is used by bpf program to read counters to measure things like number of cycles or tlb misses in a given function.
In this case user space typically leaves FDs around, but it doesn't use them for anything.

Quoted 1 line

Also, BPF should not be a way to get around the filedesc resource limit.

all bpf tracing stuff is root only and maps are charged for every element.

Quoted 20 lines
Quoted 6 lines

Program only need the stable pointer to 'struct perf_event' which it will use while running.
At the end it will call perf_event_kernel_release() which is == put_event().
It was the case that 'perf_events' were normal refcnt-ed structures and the last guy frees it.

Sort-of, but user events are (or should be, rather) tied to the filedesc to account the resources used.

There is also the event->owner field, we track the task that created the event, with your current scheme that is left dangling once userspace closes the last filedesc and you still have a ref open.

Quoted 5 lines

This put_event_last() logic definitely looks problematic. There are no ordering guarantees.
User space may close FD, while struct perf_event is still alive. The loop around perf_event_last() looks buggy.
I'm obviously missing the main goal of this patch.

Quoted 8 lines

Right, so the patch in question tries to synchronously clean up everything related to the counter when we close the file. Such that the file better reflects the actual resource usage.

Currently we do this async (and with holes).

In short, user created event really should be filedesc based, yes we have event references, but those 'should' be short lived.

I'm still missing why it's the problem.
Which counter do you want to bump as part of perf_event_get() ? still event->refcount, right?
but the same perf_event can be stored in multiple bpf maps and many bpf programs can be using it, while nothing can possibly prevent the user space to do close(perf_event_fd) while programs are still running and collecting tlb miss data from the counters.
So what do you propose?

author reviewer
#14 lore raw

Re: [PATCH v2] perf: Synchronously cleanup child events

In reply to Peter Zijlstra
Quoted 8 lines · Peter Zijlstra

So I think there's a number of problems still :-(

I all starts with having two perf_remove_from_owner() calls (as I mentioned on IRC), this doesn't make sense.

I think the moment you close the file and userspace looses control over it, we should drop the owner bit, which is exactly the one remove_from_owner in perf_release().

Fair enough.

Quoted 11 lines

If, for some magical reason, the event lives on after that (and we'll get to that), it should live on owner-less.

Now, assume someone has such a magical reference, then our put_event_last() goto again loop will never terminate, this seems like a bad thing.

The most obvious place that generates such magical references would be the bpf arraymap doing perf_event_get() on things. There are a few other places that take temp references (perf_mmap_close), but those are 'short' lived and while ugly will not cause massive grief.

We won't get to perf_release() before we're done with perf_mmap_close(), so that one's not really a problem.

Quoted 5 lines

The BPF one OTOH is a real problem here.

And looking at the BPF stuff, that code seems to assume perf_event_kernel_release() := put_event(), so this patch breaks that too.

Yes, that one's very much an api abuse, it should clearly be using get_file()/fput() instead. Now that the code is there already, there's a slight chance that changing this will have userspace running into the fd limit and cause a regression. As a workaround we can probably introduce yet another magial owner to allow a userspace event to be 'stolen'. Since bpf is the only user of perf_event_get(), this can be somewhat easily arranged.

Regards,
--
Alex

maintainer
#15 lore raw

Re: [PATCH v2] perf: Synchronously cleanup child events

Quoted 9 lines · Alexander Shishkin
Quoted 4 lines · Peter Zijlstra

The most obvious place that generates such magical references would be the bpf arraymap doing perf_event_get() on things. There are a few other places that take temp references (perf_mmap_close), but those are 'short' lived and while ugly will not cause massive grief.

We won't get to perf_release() before we're done with perf_mmap_close(), so that one's not really a problem.

Only for the file we mmap()'ed, the events we've attached through IOC_SET_OUTPUT will not have a file reference from the mmap().

author reviewer
#16 lore raw

Re: [PATCH v2] perf: Synchronously cleanup child events

In reply to Peter Zijlstra
Quoted 1 line · Peter Zijlstra

So I think there's a number of problems still :-(

Also, it does indeed race with __perf_event_exit_task()/sync_child_event(), but that one I'd fix by simply wrapping the sync_child_event()/free_event() in

mutex_lock(&parent_event->child_mutex);
if (!is_orphan_event(parent_event)) {
sync_child_event(child_event);
free_event(child_event);
}
mutex_unlock(&parent_event->child_event);

At some later point in time the code there could use a bit of reshuffling, I guess.

Regards,
--
Alex

maintainer
#17 lore raw

Re: [PATCH v2] perf: Synchronously cleanup child events

Quoted 8 lines · Alexander Shishkin
Quoted 1 line · Peter Zijlstra

So I think there's a number of problems still :-(

Also, it does indeed race with __perf_event_exit_task()/sync_child_event(), but that one I'd fix by simply wrapping the sync_child_event()/free_event() in

Quoted 6 lines

mutex_lock(&parent_event->child_mutex);

if (!is_orphan_event(parent_event)) {
   sync_child_event(child_event);
   free_event(child_event);
}

mutex_unlock(&parent_event->child_event);

So I've been staring at exactly that code for a while because Ingo managed to trigger that race (and I could reproduce with his 'workload').

But I'm not seeing how; both sites hold ctx->mutex and remove the event from the ctx->event_list.

So the way I'm seeing it, either the orphan_work find and frees it, or the __perf_event_exit_task() one does, but I'm a bit stumped on how they can both do.

Sure, the sync stuff is pointless if we're orphan, but I don't see how it can harm.

Quoted 2 lines

At some later point in time the code there could use a bit of reshuffling, I guess.

Yes.

maintainer
#18 lore raw

Re: [PATCH v2] perf: Synchronously cleanup child events

In reply to Alexander Shishkin
Quoted 8 lines · Alexander Shishkin
Quoted 1 line · Peter Zijlstra

So I think there's a number of problems still :-(

Also, it does indeed race with __perf_event_exit_task()/sync_child_event(), but that one I'd fix by simply wrapping the sync_child_event()/free_event() in

Quoted 6 lines

mutex_lock(&parent_event->child_mutex);

if (!is_orphan_event(parent_event)) {
   sync_child_event(child_event);
   free_event(child_event);
}

mutex_unlock(&parent_event->child_event);

Also, note the comment with _perf_event_disable(), that relies on sync_child_event() taking event->parent->child_mutex.

#19 lore raw

Re: [PATCH v2] perf: Synchronously cleanup child events

Quoted 4 lines · Peter Zijlstra
Quoted 3 lines · Alexander Shishkin
Quoted 1 line · Peter Zijlstra

So I think there's a number of problems still :-(

I've been looking at how perf_event->owner is handled and couldn't figure out how you deal with the case of passing perf_event_fd via scm_rights. It seems one process can open an event, pass it to another process, but when current process exists owner will still point to dead task, since refcount > 0.
Which part am I missing?

maintainer
#20 lore raw

Re: [PATCH v2] perf: Synchronously cleanup child events

Quoted 4 lines · Alexei Starovoitov
Quoted 3 lines · Peter Zijlstra
Quoted 2 lines · Alexander Shishkin

Peter Zijlstra <[email protected]> writes:

Quoted 8 lines
Quoted 1 line
Quoted 1 line
Quoted 1 line

So I think there's a number of problems still :-(

I've been looking at how perf_event->owner is handled and couldn't figure out how you deal with the case of passing perf_event_fd via scm_rights. It seems one process can open an event, pass it to another process, but when current process exists owner will still point to dead task, since refcount > 0.
Which part am I missing?

Nothing, you raised a good point. I think this shows we cannot link !event->owner to an event being 'dead'.

If we keep these two states separate, the scm_rights thing should work again.

maintainer
#21 lore raw

Re: [PATCH v2] perf: Synchronously cleanup child events

Quoted 14 lines · Peter Zijlstra
Quoted 4 lines · Alexei Starovoitov
Quoted 3 lines · Peter Zijlstra
Quoted 2 lines · Alexander Shishkin

Peter Zijlstra <[email protected]> writes:

Quoted 8 lines
Quoted 1 line
Quoted 1 line
Quoted 1 line

So I think there's a number of problems still :-(

I've been looking at how perf_event->owner is handled and couldn't figure out how you deal with the case of passing perf_event_fd via scm_rights. It seems one process can open an event, pass it to another process, but when current process exists owner will still point to dead task, since refcount > 0.
Which part am I missing?

Quoted 5 lines

Nothing, you raised a good point. I think this shows we cannot link !event->owner to an event being 'dead'.

If we keep these two states separate, the scm_rights thing should work again.

Alexander, Alexei,

How about the below? That uses event->state == PERF_EVENT_STATE_EXIT to indicate the event has been given up by its 'owner' and decouples us from the actual event->owner logic.

This retains the event->owner and event->owner_list thing purely for the prclt(.option = PR_TASK_PERF_EVENTS_{EN,DIS}ABLE) calls, but does give us strict 'owner' semantics in that:

  struct perf_event *my_event = perf_event_create_kernel_counter();

/* ... */

  perf_event_release_kernel(my_event);

Or

  int fd = sys_perf_event_open(...);

close(fd); /* last, calls fops::release */

Will destroy the event dead. event::refcount will 'retain' the object but it will become non functional and is strictly meant as a temporal existence guarantee (for when RCU isn't good enough).

So this should restore the scm_rights case, which preserves the fd but could result in not having event->owner (and therefore being removed from its owner_list), which is fine.

BPF still needs to get fixed to use filedesc references instead.

---

include/linux/perf_event.h +0 -3
@@ -634,9 +634,6 @@ struct perf_event_context {
 	int				nr_cgroups;	 /* cgroup evts */
 	void				*task_ctx_data; /* pmu specific data */
 	struct rcu_head			rcu_head;
-
-	struct delayed_work		orphans_remove;
-	bool				orphans_remove_sched;
 };
 
 /*
kernel/events/core.c +144 -154

482 lines not on this page · raw message

maintainer
#22 lore raw

Re: [PATCH v2] perf: Synchronously cleanup child events

Quoted 26 lines · Peter Zijlstra

Alexander, Alexei,

How about the below? That uses event->state == PERF_EVENT_STATE_EXIT to indicate the event has been given up by its 'owner' and decouples us from the actual event->owner logic.

This retains the event->owner and event->owner_list thing purely for the prclt(.option = PR_TASK_PERF_EVENTS_{EN,DIS}ABLE) calls, but does give us strict 'owner' semantics in that:

  struct perf_event *my_event = perf_event_create_kernel_counter();

/* ... */

  perf_event_release_kernel(my_event);

Or

  int fd = sys_perf_event_open(...);

close(fd); /* last, calls fops::release */

Will destroy the event dead. event::refcount will 'retain' the object but it will become non functional and is strictly meant as a temporal existence guarantee (for when RCU isn't good enough).

Quoted 5 lines

So this should restore the scm_rights case, which preserves the fd but could result in not having event->owner (and therefore being removed from its owner_list), which is fine.

BPF still needs to get fixed to use filedesc references instead.

Still no BPF, but this one actually 'works', as in it doesn't have the blatant exit races and has survived a few hours of runtime.

---
 include/linux/perf_event.h |    3 
 kernel/events/core.c       |  304 ++++++++++++++++++++++-----------------------
 2 files changed, 150 insertions(+), 157 deletions(-)
include/linux/perf_event.h +0 -3
@@ -634,9 +634,6 @@ struct perf_event_context {
 	int				nr_cgroups;	 /* cgroup evts */
 	void				*task_ctx_data; /* pmu specific data */
 	struct rcu_head			rcu_head;
-
-	struct delayed_work		orphans_remove;
-	bool				orphans_remove_sched;
 };
 
 /*
kernel/events/core.c +150 -154

488 lines not on this page · raw message

#23 lore raw

Re: [PATCH v2] perf: Synchronously cleanup child events

Quoted 33 lines · Peter Zijlstra
Quoted 26 lines · Peter Zijlstra

Alexander, Alexei,

How about the below? That uses event->state == PERF_EVENT_STATE_EXIT to indicate the event has been given up by its 'owner' and decouples us from the actual event->owner logic.

This retains the event->owner and event->owner_list thing purely for the prclt(.option = PR_TASK_PERF_EVENTS_{EN,DIS}ABLE) calls, but does give us strict 'owner' semantics in that:

  struct perf_event *my_event = perf_event_create_kernel_counter();

/* ... */

  perf_event_release_kernel(my_event);

Or

  int fd = sys_perf_event_open(...);

close(fd); /* last, calls fops::release */

Will destroy the event dead. event::refcount will 'retain' the object but it will become non functional and is strictly meant as a temporal existence guarantee (for when RCU isn't good enough).

Quoted 5 lines

So this should restore the scm_rights case, which preserves the fd but could result in not having event->owner (and therefore being removed from its owner_list), which is fine.

BPF still needs to get fixed to use filedesc references instead.

Quoted 7 lines

Still no BPF, but this one actually 'works', as in it doesn't have the blatant exit races and has survived a few hours of runtime.

---
 include/linux/perf_event.h |    3 
 kernel/events/core.c       |  304 ++++++++++++++++++++++-----------------------
 2 files changed, 150 insertions(+), 157 deletions(-)

I think I understand what you're trying to do and the patch looks good to me.
As far as BPF side I did the following... does it match the model you outlined above? I did basic testing and it looks fine.

Subject: [PATCH ] perf,bpf: convert perf_event_array to use struct file

---
 include/linux/perf_event.h |  4 ++--
 kernel/bpf/arraymap.c      | 21 +++++++++++----------
 kernel/events/core.c       | 20 ++++++++------------
 kernel/trace/bpf_trace.c   | 14 ++++++++++----
 4 files changed, 31 insertions(+), 28 deletions(-)
include/linux/perf_event.h +2 -2
index f9828a48f16a..df275020fde9 100644
@@ -729,7 +729,7 @@ extern int perf_event_init_task(struct task_struct *child);
 extern void perf_event_exit_task(struct task_struct *child);
 extern void perf_event_free_task(struct task_struct *task);
 extern void perf_event_delayed_put(struct task_struct *task);
-extern struct perf_event *perf_event_get(unsigned int fd);
+extern struct file *perf_event_get(unsigned int fd);
 extern const struct perf_event_attr *perf_event_attrs(struct perf_event *event);
 extern void perf_event_print_debug(void);
 extern void perf_pmu_disable(struct pmu *pmu);
@@ -1070,7 +1070,7 @@ static inline int perf_event_init_task(struct task_struct *child)	{ return 0; }
 static inline void perf_event_exit_task(struct task_struct *child)	{ }
 static inline void perf_event_free_task(struct task_struct *task)	{ }
 static inline void perf_event_delayed_put(struct task_struct *task)	{ }
-static inline struct perf_event *perf_event_get(unsigned int fd)	{ return ERR_PTR(-EINVAL); }
+static inline struct file *perf_event_get(unsigned int fd)	{ return ERR_PTR(-EINVAL); }
 static inline const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
 {
 	return ERR_PTR(-EINVAL);
kernel/bpf/arraymap.c +11 -10
index b0799bced518..89ebbc4d1164 100644
@@ -291,10 +291,13 @@ static void *perf_event_fd_array_get_ptr(struct bpf_map *map, int fd)
 {
 	struct perf_event *event;
 	const struct perf_event_attr *attr;
+	struct file *file;
 
-	event = perf_event_get(fd);
-	if (IS_ERR(event))
-		return event;
+	file = perf_event_get(fd);
+	if (IS_ERR(file))
+		return file;
+
+	event = file->private_data;
 
 	attr = perf_event_attrs(event);
 	if (IS_ERR(attr))
@@ -304,24 +307,22 @@ static void *perf_event_fd_array_get_ptr(struct bpf_map *map, int fd)
 		goto err;
 
 	if (attr->type == PERF_TYPE_RAW)
-		return event;
+		return file;
 
 	if (attr->type == PERF_TYPE_HARDWARE)
-		return event;
+		return file;
 
 	if (attr->type == PERF_TYPE_SOFTWARE &&
 	    attr->config == PERF_COUNT_SW_BPF_OUTPUT)
-		return event;
+		return file;
 err:
-	perf_event_release_kernel(event);
+	fput(file);
 	return ERR_PTR(-EINVAL);
 }
 
 static void perf_event_fd_array_put_ptr(void *ptr)
 {
-	struct perf_event *event = ptr;
-
-	perf_event_release_kernel(event);
+	fput((struct file *)ptr);
 }
 
 static const struct bpf_map_ops perf_event_array_ops = {
kernel/events/core.c +8 -12
index 06ae52e99ac2..2a95e0d2370f 100644
@@ -8896,21 +8896,17 @@ void perf_event_delayed_put(struct task_struct *task)
 		WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
 }
 
-struct perf_event *perf_event_get(unsigned int fd)
+struct file *perf_event_get(unsigned int fd)
 {
-	int err;
-	struct fd f;
-	struct perf_event *event;
-
-	err = perf_fget_light(fd, &f);
-	if (err)
-		return ERR_PTR(err);
+	struct file *file;
 
-	event = f.file->private_data;
-	atomic_long_inc(&event->refcount);
-	fdput(f);
+	file = fget_raw(fd);
+	if (file->f_op != &perf_fops) {
+		fput(file);
+		return ERR_PTR(-EBADF);
+	}
 
-	return event;
+	return file;
 }
 
 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
kernel/trace/bpf_trace.c +10 -4
index 45dd798bcd37..326a75e884db 100644
@@ -191,14 +191,17 @@ static u64 bpf_perf_event_read(u64 r1, u64 index, u64 r3, u64 r4, u64 r5)
 	struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
 	struct bpf_array *array = container_of(map, struct bpf_array, map);
 	struct perf_event *event;
+	struct file *file;
 
 	if (unlikely(index >= array->map.max_entries))
 		return -E2BIG;
 
-	event = (struct perf_event *)array->ptrs[index];
-	if (!event)
+	file = (struct file *)array->ptrs[index];
+	if (unlikely(!file))
 		return -ENOENT;
 
+	event = file->private_data;
+
 	/* make sure event is local and doesn't have pmu::count */
 	if (event->oncpu != smp_processor_id() ||
 	    event->pmu->count)
@@ -228,6 +231,7 @@ static u64 bpf_perf_event_output(u64 r1, u64 r2, u64 index, u64 r4, u64 size)
 	void *data = (void *) (long) r4;
 	struct perf_sample_data sample_data;
 	struct perf_event *event;
+	struct file *file;
 	struct perf_raw_record raw = {
 		.size = size,
 		.data = data,
@@ -236,10 +240,12 @@ static u64 bpf_perf_event_output(u64 r1, u64 r2, u64 index, u64 r4, u64 size)
 	if (unlikely(index >= array->map.max_entries))
 		return -E2BIG;
 
-	event = (struct perf_event *)array->ptrs[index];
-	if (unlikely(!event))
+	file = (struct file *)array->ptrs[index];
+	if (unlikely(!file))
 		return -ENOENT;
 
+	event = file->private_data;
+
 	if (unlikely(event->attr.type != PERF_TYPE_SOFTWARE ||
 		     event->attr.config != PERF_COUNT_SW_BPF_OUTPUT))
 		return -EINVAL;
Signature · 1 line
2.4.6
maintainer
#24 lore raw

Re: [PATCH v2] perf: Synchronously cleanup child events

Quoted 2 lines · Alexei Starovoitov

I think I understand what you're trying to do and
the patch looks good to me.

Great, thanks!

Quoted 2 lines

As far as BPF side I did the following...
does it match the model you outlined above?

Yes, a few comments/questions below.

Quoted 4 lines

Subject: [PATCH ] perf,bpf: convert perf_event_array to use struct file

Can I take this through the tip/perf tree so that all these changes land together?

kernel/events/core.c void perf_event_delayed_put(struct task_struct *task) · line 8903

Quoted 13 lines
kernel/events/core.c +3 -0
index 06ae52e99ac2..2a95e0d2370f 100644
@@ -8896,21 +8896,17 @@ void perf_event_delayed_put(struct task_struct *task)
 		WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
 }
 
+struct file *perf_event_get(unsigned int fd)
 {
+	struct file *file;
 
+	file = fget_raw(fd);

fget_raw() to guarantee the return value isn't NULL? afaict the O_PATH stuff does not apply to perf events, so you'd put any fd for which the distinction matters anyway.

Quoted 7 lines
kernel/events/core.c +5 -0
+	if (file->f_op != &perf_fops) {
+		fput(file);
+		return ERR_PTR(-EBADF);
+	}
 
+	return file;
 }
maintainer
#25 lore raw

Re: [PATCH v2] perf: Synchronously cleanup child events

Quoted 10 lines · Peter Zijlstra

kernel/events/core.c void perf_event_delayed_put(struct task_struct *task) · line 8903

Quoted 5 lines
kernel/events/core.c +3 -0
+struct file *perf_event_get(unsigned int fd)
 {
+	struct file *file;
 
+	file = fget_raw(fd);

fget_raw() to guarantee the return value isn't NULL? afaict the O_PATH stuff does not apply to perf events, so you'd put any fd for which the distinction matters anyway.

Quoted 7 lines

kernel/events/core.c void perf_event_delayed_put(struct task_struct *task) · line 8910

Quoted 7 lines
kernel/events/core.c +5 -0
+	if (file->f_op != &perf_fops) {
+		fput(file);
+		return ERR_PTR(-EBADF);
+	}
 
+	return file;
 }

It is not possible for one thread to concurrently call close() while this thread tries to fget() ? In which case, we must check the return value anyway?

#26 lore raw

Re: [PATCH v2] perf: Synchronously cleanup child events

Quoted 10 lines · Peter Zijlstra
Quoted 9 lines · Peter Zijlstra

kernel/events/core.c void perf_event_delayed_put(struct task_struct *task) · line 8903

Quoted 5 lines
kernel/events/core.c +3 -0
+struct file *perf_event_get(unsigned int fd)
 {
+	struct file *file;
 
+	file = fget_raw(fd);

fget_raw() to guarantee the return value isn't NULL? afaict the O_PATH stuff does not apply to perf events, so you'd put any fd for which the distinction matters anyway.

yeah good catch. the following is needed:

        file = fget_raw(fd);

+ if (!file)
+ return ERR_PTR(-EBADF);

Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
kernel/events/core.c +4 -0
+	if (file->f_op != &perf_fops) {
+		fput(file);
+		return ERR_PTR(-EBADF);
+	}
Quoted 6 lines
Quoted 2 lines

Review

Quoted 2 lines
(quoted diff) +1 -0
+	return file;
 }

It is not possible for one thread to concurrently call close() while this thread tries to fget() ? In which case, we must check the return value anyway?

the !file check is definitely needed, fd passed by the user can be bogus. The caller of perf_event_get() checks for errors too.

This patch will conflict with kernel/bpf/arraymap.c and kernel/trace/bpf_trace.c that are planned for net-next, but the conflicts in kernel/events/core.c are probably harder to resolve, so yes please take it into tip/perf.
I think your scm_right fixes depend on this patch and together it's an important bug fix, so probably makes sense to send them right now without waiting for the next merge window? As soon as you get the whole thing into tip, I'll test it to make sure bpf side is ok and I hope Wang will test it too.

I'm still a bit concerned about taking file reference for this, since bpf prorgams that use perf_events won't be able to be 'detached'. Meaning there gotta be always a user space process that will be holding perf_event FDs. On networking side we don't have this limitation. Like we can attach bpf to TC, iproute2 will exit and reattach some time later. So it kinda sux, but sounds like you want to get rid of perf_event->refcnt completely, so I don't see any other way. We can fix it later if it really becomes an issue.

maintainer
#27 lore raw

Re: [PATCH v2] perf: Synchronously cleanup child events

Quoted 4 lines · Alexei Starovoitov

This patch will conflict with kernel/bpf/arraymap.c and kernel/trace/bpf_trace.c that are planned for net-next, but the conflicts in kernel/events/core.c are probably harder to resolve, so yes please take it into tip/perf.

Thanks.

Quoted 3 lines

I think your scm_right fixes depend on this patch and together it's an important bug fix, so probably makes sense to send them right now without waiting for the next merge window?

I'll leave that up to Ingo, but likely yes.

Quoted 6 lines

As soon as you get the whole thing into tip, I'll test it to make sure bpf side is ok and I hope Wang will test it too.

I'm still a bit concerned about taking file reference for this, since bpf prorgams that use perf_events won't be able to be 'detached'.

I was not aware BPF could be detached like that.

Quoted 2 lines

Meaning there gotta be always a user space process that will be holding perf_event FDs.

By using fget() the BPF array thing will hold the FDs, right? I mean once you do a full fget() userspace can go and kill itself, the struct file will persists.

Quoted 5 lines

On networking side we
don't have this limitation. Like we can attach bpf to TC, iproute2 will exit and reattach some time later. So it kinda sux, but sounds like you want to get rid of perf_event->refcnt completely,

We cannot actually get rid of it, we need it for some existence stuff. But yes, we need stricter cleanup.

Quoted 2 lines

so I don't see any other way.
We can fix it later if it really becomes an issue.

One possible avenue would be to allow BPF to create its own (kernel) events and manage its lifetime along with the BPF object. But so far I don't see a problem with the file thing.

#28 lore raw

Re: [PATCH v2] perf: Synchronously cleanup child events

Quoted 7 lines · Peter Zijlstra
Quoted 3 lines

Meaning there gotta be always a user space process that will be holding perf_event FDs.

By using fget() the BPF array thing will hold the FDs, right? I mean once you do a full fget() userspace can go and kill itself, the struct file will persists.

Right. I mistakenly thought that fget() will prevent the task from freeing or some fs/directory resources will be hanging. It's from anon_inode. So all good. All concerns cleared.

#29 lore raw

[tip:perf/urgent] perf/bpf: Convert perf_event_array to use struct file

In reply to Alexei Starovoitov
perf/bpf: Convert perf_event_array to use struct file
Commit-ID:  e03e7ee34fdd1c3ef494949a75cb8c61c7265fa9
Gitweb:     http://git.kernel.org/tip/e03e7ee34fdd1c3ef494949a75cb8c61c7265fa9
Author:     Alexei Starovoitov <[email protected]>
AuthorDate: Mon, 25 Jan 2016 20:59:49 -0800
Committer:  Ingo Molnar <[email protected]>
CommitDate: Fri, 29 Jan 2016 08:35:25 +0100

perf/bpf: Convert perf_event_array to use struct file

Robustify refcounting.

Cc Alexander Shishkin <[email protected]>
Cc Arnaldo Carvalho de Melo <[email protected]>
Cc Arnaldo Carvalho de Melo <[email protected]>
Cc Daniel Borkmann <[email protected]>
Cc David Ahern <[email protected]>
Cc Jiri Olsa <[email protected]>
Cc Jiri Olsa <[email protected]>
Cc Linus Torvalds <[email protected]>
Cc Namhyung Kim <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Stephane Eranian <[email protected]>
Cc Thomas Gleixner <[email protected]>
Cc Vince Weaver <[email protected]>
Cc Wang Nan <[email protected]>
---
 include/linux/perf_event.h |  4 ++--
 kernel/bpf/arraymap.c      | 21 +++++++++++----------
 kernel/events/core.c       | 21 ++++++++++-----------
 kernel/trace/bpf_trace.c   | 14 ++++++++++----
 4 files changed, 33 insertions(+), 27 deletions(-)
include/linux/perf_event.h +2 -2
index 6612732..4f90434 100644
@@ -729,7 +729,7 @@ extern int perf_event_init_task(struct task_struct *child);
 extern void perf_event_exit_task(struct task_struct *child);
 extern void perf_event_free_task(struct task_struct *task);
 extern void perf_event_delayed_put(struct task_struct *task);
-extern struct perf_event *perf_event_get(unsigned int fd);
+extern struct file *perf_event_get(unsigned int fd);
 extern const struct perf_event_attr *perf_event_attrs(struct perf_event *event);
 extern void perf_event_print_debug(void);
 extern void perf_pmu_disable(struct pmu *pmu);
@@ -1070,7 +1070,7 @@ static inline int perf_event_init_task(struct task_struct *child)	{ return 0; }
 static inline void perf_event_exit_task(struct task_struct *child)	{ }
 static inline void perf_event_free_task(struct task_struct *task)	{ }
 static inline void perf_event_delayed_put(struct task_struct *task)	{ }
-static inline struct perf_event *perf_event_get(unsigned int fd)	{ return ERR_PTR(-EINVAL); }
+static inline struct file *perf_event_get(unsigned int fd)	{ return ERR_PTR(-EINVAL); }
 static inline const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
 {
 	return ERR_PTR(-EINVAL);
kernel/bpf/arraymap.c +11 -10
index b0799bc..89ebbc4 100644
@@ -291,10 +291,13 @@ static void *perf_event_fd_array_get_ptr(struct bpf_map *map, int fd)
 {
 	struct perf_event *event;
 	const struct perf_event_attr *attr;
+	struct file *file;
 
-	event = perf_event_get(fd);
-	if (IS_ERR(event))
-		return event;
+	file = perf_event_get(fd);
+	if (IS_ERR(file))
+		return file;
+
+	event = file->private_data;
 
 	attr = perf_event_attrs(event);
 	if (IS_ERR(attr))
@@ -304,24 +307,22 @@ static void *perf_event_fd_array_get_ptr(struct bpf_map *map, int fd)
 		goto err;
 
 	if (attr->type == PERF_TYPE_RAW)
-		return event;
+		return file;
 
 	if (attr->type == PERF_TYPE_HARDWARE)
-		return event;
+		return file;
 
 	if (attr->type == PERF_TYPE_SOFTWARE &&
 	    attr->config == PERF_COUNT_SW_BPF_OUTPUT)
-		return event;
+		return file;
 err:
-	perf_event_release_kernel(event);
+	fput(file);
 	return ERR_PTR(-EINVAL);
 }
 
 static void perf_event_fd_array_put_ptr(void *ptr)
 {
-	struct perf_event *event = ptr;
-
-	perf_event_release_kernel(event);
+	fput((struct file *)ptr);
 }
 
 static const struct bpf_map_ops perf_event_array_ops = {
kernel/events/core.c +10 -11
index fe97f95..eb44730 100644
@@ -8916,21 +8916,20 @@ void perf_event_delayed_put(struct task_struct *task)
 		WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
 }
 
-struct perf_event *perf_event_get(unsigned int fd)
+struct file *perf_event_get(unsigned int fd)
 {
-	int err;
-	struct fd f;
-	struct perf_event *event;
+	struct file *file;
 
-	err = perf_fget_light(fd, &f);
-	if (err)
-		return ERR_PTR(err);
+	file = fget_raw(fd);
+	if (!file)
+		return ERR_PTR(-EBADF);
 
-	event = f.file->private_data;
-	atomic_long_inc(&event->refcount);
-	fdput(f);
+	if (file->f_op != &perf_fops) {
+		fput(file);
+		return ERR_PTR(-EBADF);
+	}
 
-	return event;
+	return file;
 }
 
 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
kernel/trace/bpf_trace.c +10 -4
index 45dd798..326a75e 100644
@@ -191,14 +191,17 @@ static u64 bpf_perf_event_read(u64 r1, u64 index, u64 r3, u64 r4, u64 r5)
 	struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
 	struct bpf_array *array = container_of(map, struct bpf_array, map);
 	struct perf_event *event;
+	struct file *file;
 
 	if (unlikely(index >= array->map.max_entries))
 		return -E2BIG;
 
-	event = (struct perf_event *)array->ptrs[index];
-	if (!event)
+	file = (struct file *)array->ptrs[index];
+	if (unlikely(!file))
 		return -ENOENT;
 
+	event = file->private_data;
+
 	/* make sure event is local and doesn't have pmu::count */
 	if (event->oncpu != smp_processor_id() ||
 	    event->pmu->count)
@@ -228,6 +231,7 @@ static u64 bpf_perf_event_output(u64 r1, u64 r2, u64 index, u64 r4, u64 size)
 	void *data = (void *) (long) r4;
 	struct perf_sample_data sample_data;
 	struct perf_event *event;
+	struct file *file;
 	struct perf_raw_record raw = {
 		.size = size,
 		.data = data,
@@ -236,10 +240,12 @@ static u64 bpf_perf_event_output(u64 r1, u64 r2, u64 index, u64 r4, u64 size)
 	if (unlikely(index >= array->map.max_entries))
 		return -E2BIG;
 
-	event = (struct perf_event *)array->ptrs[index];
-	if (unlikely(!event))
+	file = (struct file *)array->ptrs[index];
+	if (unlikely(!file))
 		return -ENOENT;
 
+	event = file->private_data;
+
 	if (unlikely(event->attr.type != PERF_TYPE_SOFTWARE ||
 		     event->attr.config != PERF_COUNT_SW_BPF_OUTPUT))
 		return -EINVAL;
#30 lore raw

Re: [tip:perf/urgent] perf/bpf: Convert perf_event_array to use struct file

Quoted 15 lines · tip-bot for Alexei Starovoitov
Commit-ID:  e03e7ee34fdd1c3ef494949a75cb8c61c7265fa9
Gitweb:     http://git.kernel.org/tip/e03e7ee34fdd1c3ef494949a75cb8c61c7265fa9
Author:     Alexei Starovoitov <[email protected]>
AuthorDate: Mon, 25 Jan 2016 20:59:49 -0800
Committer:  Ingo Molnar <[email protected]>
CommitDate: Fri, 29 Jan 2016 08:35:25 +0100

perf/bpf: Convert perf_event_array to use struct file

Robustify refcounting.

Quoted 6 lines
---
 include/linux/perf_event.h |  4 ++--
 kernel/bpf/arraymap.c      | 21 +++++++++++----------
 kernel/events/core.c       | 21 ++++++++++-----------
 kernel/trace/bpf_trace.c   | 14 ++++++++++----
 4 files changed, 33 insertions(+), 27 deletions(-)

Tested the latest perf/urgent.
bpf tests are passing. kmemleak and kasan are quiet. Thanks

maintainer
#31 lore raw

Re: [PATCH v2] perf: Synchronously cleanup child events

In reply to Alexander Shishkin

kernel/events/core.c static void put_event(struct perf_event *event) · line 3784

Quoted 3 lines · Alexander Shishkin
kernel/events/core.c +2 -0
+static bool put_event_last(struct perf_event *event)
 {
+	if (atomic_long_cmpxchg(&event->refcount, 1, 0)) {
	if (atomic_long_cmpxchg(&event->refcount, 1, 0) == 1) {
Quoted 6 lines
kernel/events/core.c +5 -0
+		__put_event(event);
+		return true;
+	}
+
+	return false;
 }
#32 lore raw

Re: [PATCH] perf: Synchronously cleanup child events

In reply to Alexander Shishkin
Quoted 6 lines · Alexander Shishkin

The orphan cleanup workqueue doesn't always catch orphans, for example, if they never schedule after they are orphaned. IOW, the event leak is still very real. It also wouldn't work for kernel counters.

Also, there seems to be no reason not to carry out this cleanup procedure synchronously during parent event's destruction.

Absolutely, synchronous cleanup will probably also be quicker at triggering any remaining (and new ;-) races.

Thanks,

Ingo