Skip to contentSkip to conversation

SRCU-protected uretprobes hot path

PATCH Superseded Andrii Nakryiko 4 participants 13 messages Sep 9, 2024 – Oct 4, 2024

Subsystems (4)

v1 of 3 Superseded Latest is v3 →

lore
Share & tools
lore

Andrii Nakryiko

author maintainer
#0 lore raw

cover SRCU-protected uretprobes hot path

Recently landed changes make uprobe entry hot code path makes use of RCU Tasks Trace to avoid touching uprobe refcount, which at high frequency of uprobe triggering leads to excessive cache line bouncing and limited scalability with increased number of CPUs that simultaneously execute uprobe handlers.

This patch set adds return uprobe (uretprobe) side of this, this time utilizing SRCU for the same reasons. Given the time between entry uprobe activation (at which point uretprobe code hijacks user-space stack to get activated on user function return) and uretprobe activation can be arbitrarily long and is completely under control of user code, we need to protect ourselves from too long or unbounded SRCU grace periods.

To that end we keep SRCU protection only for a limited time, and if user space code takes longer to return, pending uretprobe instances are "downgraded" to refcounted ones. This gives us best scalability and performance for high-frequency uretprobes, and keeps upper bound on SRCU grace period duration for low frequency uretprobes.

There are a bunch of synchronization issues between timer callback running in IRQ handler and current thread executing uretprobe handlers, which is abstracted away behind "hybrid lifetime uprobe" (hprobe) wrapper around uprobe instance itself. See patch #1 for all the details.

rfc->v1:
- made put_uprobe() work in any context, not just user context (Oleg);
- changed to unconditional mod_timer() usage to avoid races (Oleg).
- I kept single-stepped uprobe changes, as they have a simple use of all the hprobe functionality developed in patch #1.

Andrii Nakryiko (3):
uprobes: allow put_uprobe() from non-sleepable softirq context
uprobes: SRCU-protect uretprobe lifetime (with timeout)
uprobes: implement SRCU-protected lifetime for single-stepped uprobe

 include/linux/uprobes.h |  53 +++++-
 kernel/events/uprobes.c | 370 +++++++++++++++++++++++++++++++++-------
 2 files changed, 353 insertions(+), 70 deletions(-)
Signature · 1 line
2.43.5
author maintainer
#1 lore raw

PATCH 1/3 uprobes: allow put_uprobe() from non-sleepable softirq context

Currently put_uprobe() might trigger mutex_lock()/mutex_unlock(), which makes it unsuitable to be called from more restricted context like softirq.

Let's make put_uprobe() agnostic to the context in which it is called, and use work queue to defer the mutex-protected clean up steps.

To avoid unnecessarily increasing the size of struct uprobe, we colocate work_struct in parallel with rb_node and rcu, both of which are unused by the time we get to schedule clean up work.

---
 kernel/events/uprobes.c | 30 +++++++++++++++++++++++++++---
 1 file changed, 27 insertions(+), 3 deletions(-)
kernel/events/uprobes.c +27 -3
index a2e6a57f79f2..377bd524bc8b 100644
@@ -27,6 +27,7 @@
 #include <linux/shmem_fs.h>
 #include <linux/khugepaged.h>
 #include <linux/rcupdate_trace.h>
+#include <linux/workqueue.h>
 
 #include <linux/uprobes.h>
 
@@ -54,14 +55,20 @@ DEFINE_STATIC_PERCPU_RWSEM(dup_mmap_sem);
 #define UPROBE_COPY_INSN	0
 
 struct uprobe {
-	struct rb_node		rb_node;	/* node in the rb tree */
+	union {
+		struct {
+			struct rb_node		rb_node;	/* node in the rb tree */
+			struct rcu_head		rcu;
+		};
+		/* work is used only during freeing, rcu and rb_node are unused at that point */
+		struct work_struct work;
+	};
 	refcount_t		ref;
 	struct rw_semaphore	register_rwsem;
 	struct rw_semaphore	consumer_rwsem;
 	struct list_head	pending_list;
 	struct list_head	consumers;
 	struct inode		*inode;		/* Also hold a ref to inode */
-	struct rcu_head		rcu;
 	loff_t			offset;
 	loff_t			ref_ctr_offset;
 	unsigned long		flags;
@@ -620,11 +627,28 @@ static inline bool uprobe_is_active(struct uprobe *uprobe)
 	return !RB_EMPTY_NODE(&uprobe->rb_node);
 }
 
+static void uprobe_free_deferred(struct work_struct *work)
+{
+	struct uprobe *uprobe = container_of(work, struct uprobe, work);
+
+	/*
+	 * If application munmap(exec_vma) before uprobe_unregister()
+	 * gets called, we don't get a chance to remove uprobe from
+	 * delayed_uprobe_list from remove_breakpoint(). Do it here.
+	 */
+	mutex_lock(&delayed_uprobe_lock);
+	delayed_uprobe_remove(uprobe, NULL);
+	mutex_unlock(&delayed_uprobe_lock);
+
+	kfree(uprobe);
+}
+
 static void uprobe_free_rcu(struct rcu_head *rcu)
 {
 	struct uprobe *uprobe = container_of(rcu, struct uprobe, rcu);
 
-	kfree(uprobe);
+	INIT_WORK(&uprobe->work, uprobe_free_deferred);
+	schedule_work(&uprobe->work);
 }
 
 static void put_uprobe(struct uprobe *uprobe)
Signature · 1 line
2.43.5
author maintainer
#9 lore raw

PATCH 2/3 uprobes: SRCU-protect uretprobe lifetime (with timeout)

In reply to Andrii Nakryiko

Avoid taking refcount on uprobe in prepare_uretprobe(), instead take uretprobe-specific SRCU lock and keep it active as kernel transfers control back to user space.

Given we can't rely on user space returning from traced function within reasonable time period, we need to make sure not to keep SRCU lock active for too long, though. To that effect, we employ a timer callback which is meant to terminate SRCU lock region after predefined timeout (currently set to 100ms), and instead transfer underlying struct uprobe's lifetime protection to refcounting.

This fallback to less scalable refcounting after 100ms is a fine tradeoff from uretprobe's scalability and performance perspective, because uretprobing *long running* user functions inherently doesn't run into scalability issues (there is just not enough frequency to cause noticeable issues with either performance or scalability).

The overall trick is in ensuring synchronization between current thread and timer's callback fired on some other thread. To cope with that with minimal logic complications, we add hprobe wrapper which is used to contain all the racy and synchronization related issues behind a small number of basic helpers: hprobe_expire() for "downgrading" uprobe from SRCU-protected state to refcounted state, and a hprobe_consume()
+ hprobe_finalize() pair of single-use consuming helpers. Other than that whatever current thread's logic is there stays the same, as timer thread cannot modify return_instance state (or add new/remove old return_instances). It only takes care of SRCU unlock and uprobe refcounting, which is hidden from the higher-level uretprobe handling logic.

We use atomic xchg() in hprobe_consume(), which is called from performance critical handle_uretprobe_chain() function run in the current context. When uncontended, this xchg() doesn't seem to hurt performance as there are no other competing CPUs fighting for the same cache line. We also mark struct return_instance as ____cacheline_aligned to ensure no false sharing can happen.

Another technical moment, we need to make sure that the list of return instances can be safely traversed under RCU from timer callback, so we delay return_instance freeing with kfree_rcu() and make sure that list modifications use RCU-aware operations.

Also, given SRCU lock survives transition from kernel to user space and back we need to use lower-level __srcu_read_lock() and __srcu_read_unlock() to avoid lockdep complaining.

Just to give an impression of a kind of performance improvements this change brings, below are benchmarking results with and without these SRCU changes, assuming other uprobe optimizations (mainly RCU Tasks Trace for entry uprobes, lockless RB-tree lookup, and lockless VMA to uprobe lookup) are left intact:

WITHOUT SRCU for uretprobes
===========================

uretprobe-nop         ( 1 cpus):    2.197 ± 0.002M/s  (  2.197M/s/cpu)
uretprobe-nop         ( 2 cpus):    3.325 ± 0.001M/s  (  1.662M/s/cpu)
uretprobe-nop         ( 3 cpus):    4.129 ± 0.002M/s  (  1.376M/s/cpu)
uretprobe-nop         ( 4 cpus):    6.180 ± 0.003M/s  (  1.545M/s/cpu)
uretprobe-nop         ( 8 cpus):    7.323 ± 0.005M/s  (  0.915M/s/cpu)
uretprobe-nop         (16 cpus):    6.943 ± 0.005M/s  (  0.434M/s/cpu)
uretprobe-nop         (32 cpus):    5.931 ± 0.014M/s  (  0.185M/s/cpu)
uretprobe-nop         (64 cpus):    5.145 ± 0.003M/s  (  0.080M/s/cpu)
uretprobe-nop         (80 cpus):    4.925 ± 0.005M/s  (  0.062M/s/cpu)

WITH SRCU for uretprobes
========================

uretprobe-nop         ( 1 cpus):    1.968 ± 0.001M/s  (  1.968M/s/cpu)
uretprobe-nop         ( 2 cpus):    3.739 ± 0.003M/s  (  1.869M/s/cpu)
uretprobe-nop         ( 3 cpus):    5.616 ± 0.003M/s  (  1.872M/s/cpu)
uretprobe-nop         ( 4 cpus):    7.286 ± 0.002M/s  (  1.822M/s/cpu)
uretprobe-nop         ( 8 cpus):   13.657 ± 0.007M/s  (  1.707M/s/cpu)
uretprobe-nop         (32 cpus):   45.305 ± 0.066M/s  (  1.416M/s/cpu)
uretprobe-nop         (64 cpus):   42.390 ± 0.922M/s  (  0.662M/s/cpu)
uretprobe-nop         (80 cpus):   47.554 ± 2.411M/s  (  0.594M/s/cpu)
---
 include/linux/uprobes.h |  49 ++++++-
 kernel/events/uprobes.c | 285 ++++++++++++++++++++++++++++++++++------
 2 files changed, 292 insertions(+), 42 deletions(-)
include/linux/uprobes.h +47 -2
index 2b294bf1881f..1b194c51d4d3 100644
@@ -15,6 +15,7 @@
 #include <linux/rbtree.h>
 #include <linux/types.h>
 #include <linux/wait.h>
+#include <linux/timer.h>
 
 struct uprobe;
 struct vm_area_struct;
@@ -56,6 +57,45 @@ enum uprobe_task_state {
 	UTASK_SSTEP_TRAPPED,
 };
 
+/*
+ * Hybrid lifetime uprobe. Represents a uprobe instance that could be either
+ * SRCU protected (with SRCU protection eventually potentially timing out),
+ * refcounted using uprobe->ref, or there could be no valid uprobe (NULL).
+ *
+ * hprobe's internal state is setup such that background timer thread can
+ * atomically "downgrade" temporarily RCU-protected uprobe into refcounted one
+ * (or no uprobe, if refcounting failed).
+ *
+ * *stable* pointer always point to the uprobe (or could be NULL if there is
+ * was no valid underlying uprobe to begin with).
+ *
+ * *leased* pointer is the key to achieving race-free atomic lifetime state
+ * transition and can have three possible states:
+ *   - either the same non-NULL value as *stable*, in which case uprobe is
+ *     SRCU-protected;
+ *   - NULL, in which case uprobe (if there is any) is refcounted;
+ *   - special __UPROBE_DEAD value, which represents an uprobe that was SRCU
+ *     protected initially, but SRCU period timed out and we attempted to
+ *     convert it to refcounted, but refcount_inc_not_zero() failed, because
+ *     uprobe effectively went away (the last consumer unsubscribed). In this
+ *     case it's important to know that *stable* pointer (which still has
+ *     non-NULL uprobe pointer) shouldn't be used, because lifetime of
+ *     underlying uprobe is not guaranteed anymore. __UPROBE_DEAD is just an
+ *     internal marker and is handled transparently by hprobe_fetch() helper.
+ *
+ * When uprobe is SRCU-protected, we also record srcu_idx value, necessary for
+ * SRCU unlocking.
+ *
+ * See hprobe_expire() and hprobe_fetch() for details of race-free uprobe
+ * state transitioning details. It all hinges on atomic xchg() over *leaded*
+ * pointer. *stable* pointer, once initially set, is not modified concurrently.
+ */
+struct hprobe {
+	struct uprobe *stable;
+	struct uprobe *leased;
+	int srcu_idx;
+};
+
 /*
  * uprobe_task: Metadata of a task while it singlesteps.
  */
@@ -75,6 +115,7 @@ struct uprobe_task {
 	};
 
 	struct uprobe			*active_uprobe;
+	struct timer_list		ri_timer;
 	unsigned long			xol_vaddr;
 
 	struct arch_uprobe              *auprobe;
@@ -84,14 +125,18 @@ struct uprobe_task {
 };
 
 struct return_instance {
-	struct uprobe		*uprobe;
 	unsigned long		func;
 	unsigned long		stack;		/* stack pointer */
 	unsigned long		orig_ret_vaddr; /* original return address */
 	bool			chained;	/* true, if instance is nested */
 
 	struct return_instance	*next;		/* keep as stack */
-};
+
+	union {
+		struct hprobe		hprobe;
+		struct rcu_head		rcu;
+	};
+} ____cacheline_aligned;
 
 enum rp_check {
 	RP_CHECK_CALL,
kernel/events/uprobes.c +245 -40

446 lines not on this page · raw message

Signature · 1 line
2.43.5
author maintainer
#10 lore raw

PATCH 3/3 uprobes: implement SRCU-protected lifetime for single-stepped uprobe

In reply to Andrii Nakryiko

Similarly to how we SRCU-protect uprobe instance (and avoid refcounting it unnecessarily) when waiting for return probe hit, use hprobe approach to do the same with single-stepped uprobe. Same hprobe_* primitives are used. We also reuse ri_timer() callback to expire both pending single-step uprobe and return instances.

---
 include/linux/uprobes.h |  4 +--
 kernel/events/uprobes.c | 55 ++++++++++++++++++++++++-----------------
 2 files changed, 34 insertions(+), 25 deletions(-)
include/linux/uprobes.h +2 -2
index 1b194c51d4d3..31cf7306cdf6 100644
@@ -114,7 +114,7 @@ struct uprobe_task {
 		};
 	};
 
-	struct uprobe			*active_uprobe;
+	struct hprobe			active_hprobe;
 	struct timer_list		ri_timer;
 	unsigned long			xol_vaddr;
 
@@ -122,7 +122,7 @@ struct uprobe_task {
 
 	struct return_instance		*return_instances;
 	unsigned int			depth;
-};
+} ____cacheline_aligned;
 
 struct return_instance {
 	unsigned long		func;
kernel/events/uprobes.c +32 -23

142 lines not on this page · raw message

Signature · 1 line
2.43.5
#2 lore raw

Re: [PATCH 1/3] uprobes: allow put_uprobe() from non-sleepable softirq context

In reply to Andrii Nakryiko
Quoted 71 lines · Andrii Nakryiko

Currently put_uprobe() might trigger mutex_lock()/mutex_unlock(), which makes it unsuitable to be called from more restricted context like softirq.

Let's make put_uprobe() agnostic to the context in which it is called, and use work queue to defer the mutex-protected clean up steps.

To avoid unnecessarily increasing the size of struct uprobe, we colocate work_struct in parallel with rb_node and rcu, both of which are unused by the time we get to schedule clean up work.

---
 kernel/events/uprobes.c | 30 +++++++++++++++++++++++++++---
 1 file changed, 27 insertions(+), 3 deletions(-)
kernel/events/uprobes.c +25 -2
index a2e6a57f79f2..377bd524bc8b 100644
@@ -27,6 +27,7 @@
 #include <linux/shmem_fs.h>
 #include <linux/khugepaged.h>
 #include <linux/rcupdate_trace.h>
+#include <linux/workqueue.h>
 
 #include <linux/uprobes.h>
 
@@ -54,14 +55,20 @@ DEFINE_STATIC_PERCPU_RWSEM(dup_mmap_sem);
 #define UPROBE_COPY_INSN       0
 
 struct uprobe {
-       struct rb_node          rb_node;        /* node in the rb tree */
+       union {
+               struct {
+                       struct rb_node          rb_node;        /* node in the rb tree */
+                       struct rcu_head         rcu;
+               };
+               /* work is used only during freeing, rcu and rb_node are unused at that point */
+               struct work_struct work;
+       };
        refcount_t              ref;
        struct rw_semaphore     register_rwsem;
        struct rw_semaphore     consumer_rwsem;
        struct list_head        pending_list;
        struct list_head        consumers;
        struct inode            *inode;         /* Also hold a ref to inode */
-       struct rcu_head         rcu;
        loff_t                  offset;
        loff_t                  ref_ctr_offset;
        unsigned long           flags;
@@ -620,11 +627,28 @@ static inline bool uprobe_is_active(struct uprobe *uprobe)
        return !RB_EMPTY_NODE(&uprobe->rb_node);
 }
 
+static void uprobe_free_deferred(struct work_struct *work)
+{
+       struct uprobe *uprobe = container_of(work, struct uprobe, work);
+
+       /*
+        * If application munmap(exec_vma) before uprobe_unregister()
+        * gets called, we don't get a chance to remove uprobe from
+        * delayed_uprobe_list from remove_breakpoint(). Do it here.
+        */
+       mutex_lock(&delayed_uprobe_lock);
+       delayed_uprobe_remove(uprobe, NULL);
+       mutex_unlock(&delayed_uprobe_lock);
+
+       kfree(uprobe);
+}
+

kernel/events/uprobes.c static inline bool uprobe_is_active(struct uprobe *uprobe) · line 654

Quoted 10 lines
kernel/events/uprobes.c +2 -1
 static void uprobe_free_rcu(struct rcu_head *rcu)
 {
        struct uprobe *uprobe = container_of(rcu, struct uprobe, rcu);
 
-       kfree(uprobe);
+       INIT_WORK(&uprobe->work, uprobe_free_deferred);
+       schedule_work(&uprobe->work);
 }
 
 static void put_uprobe(struct uprobe *uprobe)

It seems put_uprobe hunk was lost, since the patch is not doing what commit log describes.

#3 lore raw

Re: [PATCH 1/3] uprobes: allow put_uprobe() from non-sleepable softirq context

Quoted 82 lines · Alexei Starovoitov
Quoted 80 lines · Andrii Nakryiko

Currently put_uprobe() might trigger mutex_lock()/mutex_unlock(), which makes it unsuitable to be called from more restricted context like softirq.

Let's make put_uprobe() agnostic to the context in which it is called, and use work queue to defer the mutex-protected clean up steps.

To avoid unnecessarily increasing the size of struct uprobe, we colocate work_struct in parallel with rb_node and rcu, both of which are unused by the time we get to schedule clean up work.

---
 kernel/events/uprobes.c | 30 +++++++++++++++++++++++++++---
 1 file changed, 27 insertions(+), 3 deletions(-)
kernel/events/uprobes.c +27 -3
index a2e6a57f79f2..377bd524bc8b 100644
@@ -27,6 +27,7 @@
 #include <linux/shmem_fs.h>
 #include <linux/khugepaged.h>
 #include <linux/rcupdate_trace.h>
+#include <linux/workqueue.h>
 
 #include <linux/uprobes.h>
 
@@ -54,14 +55,20 @@ DEFINE_STATIC_PERCPU_RWSEM(dup_mmap_sem);
 #define UPROBE_COPY_INSN       0
 
 struct uprobe {
-       struct rb_node          rb_node;        /* node in the rb tree */
+       union {
+               struct {
+                       struct rb_node          rb_node;        /* node in the rb tree */
+                       struct rcu_head         rcu;
+               };
+               /* work is used only during freeing, rcu and rb_node are unused at that point */
+               struct work_struct work;
+       };
        refcount_t              ref;
        struct rw_semaphore     register_rwsem;
        struct rw_semaphore     consumer_rwsem;
        struct list_head        pending_list;
        struct list_head        consumers;
        struct inode            *inode;         /* Also hold a ref to inode */
-       struct rcu_head         rcu;
        loff_t                  offset;
        loff_t                  ref_ctr_offset;
        unsigned long           flags;
@@ -620,11 +627,28 @@ static inline bool uprobe_is_active(struct uprobe *uprobe)
        return !RB_EMPTY_NODE(&uprobe->rb_node);
 }
 
+static void uprobe_free_deferred(struct work_struct *work)
+{
+       struct uprobe *uprobe = container_of(work, struct uprobe, work);
+
+       /*
+        * If application munmap(exec_vma) before uprobe_unregister()
+        * gets called, we don't get a chance to remove uprobe from
+        * delayed_uprobe_list from remove_breakpoint(). Do it here.
+        */
+       mutex_lock(&delayed_uprobe_lock);
+       delayed_uprobe_remove(uprobe, NULL);
+       mutex_unlock(&delayed_uprobe_lock);
+
+       kfree(uprobe);
+}
+
 static void uprobe_free_rcu(struct rcu_head *rcu)
 {
        struct uprobe *uprobe = container_of(rcu, struct uprobe, rcu);
 
-       kfree(uprobe);
+       INIT_WORK(&uprobe->work, uprobe_free_deferred);
+       schedule_work(&uprobe->work);
 }
 
Quoted 4 lines

kernel/events/uprobes.c static inline bool uprobe_is_active(struct uprobe *uprobe) · line 654

Quoted 1 line
kernel/events/uprobes.c +0 -0
 static void put_uprobe(struct uprobe *uprobe)

It seems put_uprobe hunk was lost, since the patch is not doing what commit log describes.

Hmm, put_uprobe() has:

call_srcu(&uprobes_srcu, &uprobe->rcu, uprobe_free_rcu);

at the end (see [0], which added that), so we do schedule_work() in RCU callback, similarly to what we do with bpf_map freeing in the BPF subsystem.

This patch set is based on the latest tip/perf/core (and also assuming the RCU Tasks Trace patch that mysteriously disappeared is actually there, hopefully it will just as magically be restored).

[0] https://git.kernel.org/pub/scm/linux/kernel/git/tip/tip.git/commit/?h=perf/core&id=8617408f7a01e94ce1f73e40a7704530e5dfb25c

#4 lore raw

Re: [PATCH 1/3] uprobes: allow put_uprobe() from non-sleepable softirq context

Quoted 99 lines · Andrii Nakryiko
Quoted 82 lines · Alexei Starovoitov
Quoted 80 lines · Andrii Nakryiko

Currently put_uprobe() might trigger mutex_lock()/mutex_unlock(), which makes it unsuitable to be called from more restricted context like softirq.

Let's make put_uprobe() agnostic to the context in which it is called, and use work queue to defer the mutex-protected clean up steps.

To avoid unnecessarily increasing the size of struct uprobe, we colocate work_struct in parallel with rb_node and rcu, both of which are unused by the time we get to schedule clean up work.

---
 kernel/events/uprobes.c | 30 +++++++++++++++++++++++++++---
 1 file changed, 27 insertions(+), 3 deletions(-)
kernel/events/uprobes.c +27 -3
index a2e6a57f79f2..377bd524bc8b 100644
@@ -27,6 +27,7 @@
 #include <linux/shmem_fs.h>
 #include <linux/khugepaged.h>
 #include <linux/rcupdate_trace.h>
+#include <linux/workqueue.h>
 
 #include <linux/uprobes.h>
 
@@ -54,14 +55,20 @@ DEFINE_STATIC_PERCPU_RWSEM(dup_mmap_sem);
 #define UPROBE_COPY_INSN       0
 
 struct uprobe {
-       struct rb_node          rb_node;        /* node in the rb tree */
+       union {
+               struct {
+                       struct rb_node          rb_node;        /* node in the rb tree */
+                       struct rcu_head         rcu;
+               };
+               /* work is used only during freeing, rcu and rb_node are unused at that point */
+               struct work_struct work;
+       };
        refcount_t              ref;
        struct rw_semaphore     register_rwsem;
        struct rw_semaphore     consumer_rwsem;
        struct list_head        pending_list;
        struct list_head        consumers;
        struct inode            *inode;         /* Also hold a ref to inode */
-       struct rcu_head         rcu;
        loff_t                  offset;
        loff_t                  ref_ctr_offset;
        unsigned long           flags;
@@ -620,11 +627,28 @@ static inline bool uprobe_is_active(struct uprobe *uprobe)
        return !RB_EMPTY_NODE(&uprobe->rb_node);
 }
 
+static void uprobe_free_deferred(struct work_struct *work)
+{
+       struct uprobe *uprobe = container_of(work, struct uprobe, work);
+
+       /*
+        * If application munmap(exec_vma) before uprobe_unregister()
+        * gets called, we don't get a chance to remove uprobe from
+        * delayed_uprobe_list from remove_breakpoint(). Do it here.
+        */
+       mutex_lock(&delayed_uprobe_lock);
+       delayed_uprobe_remove(uprobe, NULL);
+       mutex_unlock(&delayed_uprobe_lock);
+
+       kfree(uprobe);
+}
+
 static void uprobe_free_rcu(struct rcu_head *rcu)
 {
        struct uprobe *uprobe = container_of(rcu, struct uprobe, rcu);
 
-       kfree(uprobe);
+       INIT_WORK(&uprobe->work, uprobe_free_deferred);
+       schedule_work(&uprobe->work);
 }
 
Quoted 4 lines

kernel/events/uprobes.c static inline bool uprobe_is_active(struct uprobe *uprobe) · line 654

Quoted 1 line
kernel/events/uprobes.c +0 -0
 static void put_uprobe(struct uprobe *uprobe)

It seems put_uprobe hunk was lost, since the patch is not doing what commit log describes.

Hmm, put_uprobe() has:

call_srcu(&uprobes_srcu, &uprobe->rcu, uprobe_free_rcu);

at the end (see [0], which added that), so we do schedule_work() in RCU callback, similarly to what we do with bpf_map freeing in the BPF subsystem.

Quoted 5 lines

This patch set is based on the latest tip/perf/core (and also assuming the RCU Tasks Trace patch that mysteriously disappeared is actually there, hopefully it will just as magically be restored).

[0] https://git.kernel.org/pub/scm/linux/kernel/git/tip/tip.git/commit/?h=perf/core&id=8617408f7a01e94ce1f73e40a7704530e5dfb25c

I'm still not following.
put_uprobe() did delayed_uprobe_remove() and this patch is doing it again.

The commit log implies that mutex+delayed_uprobe_remove should be removed from put_uprobe(), but that's not what the patch is doing.

#5 lore raw

Re: [PATCH 1/3] uprobes: allow put_uprobe() from non-sleepable softirq context

Quoted 106 lines · Alexei Starovoitov
Quoted 103 lines · Andrii Nakryiko
Quoted 82 lines · Alexei Starovoitov
Quoted 80 lines · Andrii Nakryiko

Currently put_uprobe() might trigger mutex_lock()/mutex_unlock(), which makes it unsuitable to be called from more restricted context like softirq.

Let's make put_uprobe() agnostic to the context in which it is called, and use work queue to defer the mutex-protected clean up steps.

To avoid unnecessarily increasing the size of struct uprobe, we colocate work_struct in parallel with rb_node and rcu, both of which are unused by the time we get to schedule clean up work.

---
 kernel/events/uprobes.c | 30 +++++++++++++++++++++++++++---
 1 file changed, 27 insertions(+), 3 deletions(-)
kernel/events/uprobes.c +27 -3
index a2e6a57f79f2..377bd524bc8b 100644
@@ -27,6 +27,7 @@
 #include <linux/shmem_fs.h>
 #include <linux/khugepaged.h>
 #include <linux/rcupdate_trace.h>
+#include <linux/workqueue.h>
 
 #include <linux/uprobes.h>
 
@@ -54,14 +55,20 @@ DEFINE_STATIC_PERCPU_RWSEM(dup_mmap_sem);
 #define UPROBE_COPY_INSN       0
 
 struct uprobe {
-       struct rb_node          rb_node;        /* node in the rb tree */
+       union {
+               struct {
+                       struct rb_node          rb_node;        /* node in the rb tree */
+                       struct rcu_head         rcu;
+               };
+               /* work is used only during freeing, rcu and rb_node are unused at that point */
+               struct work_struct work;
+       };
        refcount_t              ref;
        struct rw_semaphore     register_rwsem;
        struct rw_semaphore     consumer_rwsem;
        struct list_head        pending_list;
        struct list_head        consumers;
        struct inode            *inode;         /* Also hold a ref to inode */
-       struct rcu_head         rcu;
        loff_t                  offset;
        loff_t                  ref_ctr_offset;
        unsigned long           flags;
@@ -620,11 +627,28 @@ static inline bool uprobe_is_active(struct uprobe *uprobe)
        return !RB_EMPTY_NODE(&uprobe->rb_node);
 }
 
+static void uprobe_free_deferred(struct work_struct *work)
+{
+       struct uprobe *uprobe = container_of(work, struct uprobe, work);
+
+       /*
+        * If application munmap(exec_vma) before uprobe_unregister()
+        * gets called, we don't get a chance to remove uprobe from
+        * delayed_uprobe_list from remove_breakpoint(). Do it here.
+        */
+       mutex_lock(&delayed_uprobe_lock);
+       delayed_uprobe_remove(uprobe, NULL);
+       mutex_unlock(&delayed_uprobe_lock);
+
+       kfree(uprobe);
+}
+
 static void uprobe_free_rcu(struct rcu_head *rcu)
 {
        struct uprobe *uprobe = container_of(rcu, struct uprobe, rcu);
 
-       kfree(uprobe);
+       INIT_WORK(&uprobe->work, uprobe_free_deferred);
+       schedule_work(&uprobe->work);
 }
 
Quoted 4 lines

kernel/events/uprobes.c static inline bool uprobe_is_active(struct uprobe *uprobe) · line 654

Quoted 1 line
kernel/events/uprobes.c +0 -0
 static void put_uprobe(struct uprobe *uprobe)

It seems put_uprobe hunk was lost, since the patch is not doing what commit log describes.

Hmm, put_uprobe() has:

call_srcu(&uprobes_srcu, &uprobe->rcu, uprobe_free_rcu);

at the end (see [0], which added that), so we do schedule_work() in RCU callback, similarly to what we do with bpf_map freeing in the BPF subsystem.

This patch set is based on the latest tip/perf/core (and also assuming the RCU Tasks Trace patch that mysteriously disappeared is actually there, hopefully it will just as magically be restored).

Quoted 7 lines
Quoted 1 line

[0] https://git.kernel.org/pub/scm/linux/kernel/git/tip/tip.git/commit/?h=perf/core&id=8617408f7a01e94ce1f73e40a7704530e5dfb25c

I'm still not following.
put_uprobe() did delayed_uprobe_remove() and this patch is doing it again.

The commit log implies that mutex+delayed_uprobe_remove should be removed from put_uprobe(), but that's not what the patch is doing.

Ah, that part. You are right, it's my bad. I copied that lock to a work queue callback, but didn't remove it from the put_uprobe(). Will fix it in v2, thanks for catching!

maintainer
#6 lore raw

Re: [PATCH 1/3] uprobes: allow put_uprobe() from non-sleepable softirq context

In reply to Andrii Nakryiko
Quoted 6 lines · Andrii Nakryiko

Currently put_uprobe() might trigger mutex_lock()/mutex_unlock(), which makes it unsuitable to be called from more restricted context like softirq.

Let's make put_uprobe() agnostic to the context in which it is called, and use work queue to defer the mutex-protected clean up steps.

...

Quoted 14 lines
kernel/events/uprobes.c +14 -0
+static void uprobe_free_deferred(struct work_struct *work)
+{
+	struct uprobe *uprobe = container_of(work, struct uprobe, work);
+
+	/*
+	 * If application munmap(exec_vma) before uprobe_unregister()
+	 * gets called, we don't get a chance to remove uprobe from
+	 * delayed_uprobe_list from remove_breakpoint(). Do it here.
+	 */
+	mutex_lock(&delayed_uprobe_lock);
+	delayed_uprobe_remove(uprobe, NULL);
+	mutex_unlock(&delayed_uprobe_lock);
+
+	kfree(uprobe);

kernel/events/uprobes.c static inline bool uprobe_is_active(struct uprobe *uprobe) · line 652

Quoted 10 lines
kernel/events/uprobes.c +4 -1
+}
+
 static void uprobe_free_rcu(struct rcu_head *rcu)
 {
 	struct uprobe *uprobe = container_of(rcu, struct uprobe, rcu);
 
-	kfree(uprobe);
+	INIT_WORK(&uprobe->work, uprobe_free_deferred);
+	schedule_work(&uprobe->work);
 }

This is still wrong afaics...

If put_uprobe() can be called from softirq (after the next patch), then put_uprobe() and all other users of uprobes_treelock should use write_lock_bh/read_lock_bh to avoid the deadlock.

To be honest... I simply can't force myself to even try to read 2/3 ;) I'll try to do this later, but I am sure I will never like it, sorry.

Oleg.

maintainer
#11 lore raw

Re: [PATCH 3/3] uprobes: implement SRCU-protected lifetime for single-stepped uprobe

In reply to Andrii Nakryiko
Quoted 6 lines · Andrii Nakryiko

Similarly to how we SRCU-protect uprobe instance (and avoid refcounting it unnecessarily) when waiting for return probe hit, use hprobe approach to do the same with single-stepped uprobe. Same hprobe_* primitives are used. We also reuse ri_timer() callback to expire both pending single-step uprobe and return instances.

Well, I still think it would be better (and much simpler) to simply kill utask->active_uprobe, iirc I even sent the RFC patch...

Oleg.

#7 lore raw

Re: [PATCH 1/3] uprobes: allow put_uprobe() from non-sleepable softirq context

In reply to Oleg Nesterov
Quoted 38 lines · Oleg Nesterov
Quoted 6 lines · Andrii Nakryiko

Currently put_uprobe() might trigger mutex_lock()/mutex_unlock(), which makes it unsuitable to be called from more restricted context like softirq.

Let's make put_uprobe() agnostic to the context in which it is called, and use work queue to defer the mutex-protected clean up steps.

...

Quoted 14 lines
kernel/events/uprobes.c +14 -0
+static void uprobe_free_deferred(struct work_struct *work)
+{
+     struct uprobe *uprobe = container_of(work, struct uprobe, work);
+
+     /*
+      * If application munmap(exec_vma) before uprobe_unregister()
+      * gets called, we don't get a chance to remove uprobe from
+      * delayed_uprobe_list from remove_breakpoint(). Do it here.
+      */
+     mutex_lock(&delayed_uprobe_lock);
+     delayed_uprobe_remove(uprobe, NULL);
+     mutex_unlock(&delayed_uprobe_lock);
+
+     kfree(uprobe);

kernel/events/uprobes.c static inline bool uprobe_is_active(struct uprobe *uprobe) · line 652

Quoted 10 lines
kernel/events/uprobes.c +4 -1
+}
+
 static void uprobe_free_rcu(struct rcu_head *rcu)
 {
      struct uprobe *uprobe = container_of(rcu, struct uprobe, rcu);
 
-     kfree(uprobe);
+     INIT_WORK(&uprobe->work, uprobe_free_deferred);
+     schedule_work(&uprobe->work);
 }

This is still wrong afaics...

Quoted 3 lines

If put_uprobe() can be called from softirq (after the next patch), then put_uprobe() and all other users of uprobes_treelock should use write_lock_bh/read_lock_bh to avoid the deadlock.

Ok, I see the problem, that's unfortunate.

I see three ways to handle that:

1) keep put_uprobe() as is, and instead do schedule_work() from the timer thread to postpone put_uprobe(). (but I'm not a big fan of this)
2) move uprobes_treelock part of put_uprobe() into rcu callback, I think it has no bearing on correctness, uprobe_is_active() is there already to handle races between putting uprobe and removing it from uprobes_tree (I prefer this one over #1 )
3) you might like this the most ;) I think I can simplify hprobes_expire() from patch #2 to not need put_uprobe() at all, if I protect uprobe lifetime with non-sleepable rcu_read_lock()/rcu_read_unlock() and perform try_get_uprobe() as the very last step after cmpxchg() succeeded.

I'm leaning towards #3, but #2 seems fine to me as well.

Quoted 3 lines

To be honest... I simply can't force myself to even try to read 2/3 ;) I'll try to do this later, but I am sure I will never like it, sorry.

This might sound rude, but the goal here is not to make you like it :) The goal is to improve performance with minimal complexity. And I'm very open to any alternative proposals as to how to make uretprobes RCU-protected to avoid refcounting in the hot path.

I think #3 proposal above will make it a bit more palatable (but there is still locklessness, cmpxchg, etc, I see no way around that, unfortunately).

Quoted 3 lines

Oleg.

#12 lore raw

Re: [PATCH 3/3] uprobes: implement SRCU-protected lifetime for single-stepped uprobe

In reply to Oleg Nesterov
Quoted 12 lines · Oleg Nesterov
Quoted 6 lines · Andrii Nakryiko

Similarly to how we SRCU-protect uprobe instance (and avoid refcounting it unnecessarily) when waiting for return probe hit, use hprobe approach to do the same with single-stepped uprobe. Same hprobe_* primitives are used. We also reuse ri_timer() callback to expire both pending single-step uprobe and return instances.

Well, I still think it would be better (and much simpler) to simply kill utask->active_uprobe, iirc I even sent the RFC patch...

let's do it, please send non-RFC patches and get them landed!

Quoted 2 lines

Oleg.

#8 lore raw

Re: [PATCH 1/3] uprobes: allow put_uprobe() from non-sleepable softirq context

In reply to Andrii Nakryiko
Quoted 60 lines · Andrii Nakryiko
Quoted 38 lines · Oleg Nesterov
Quoted 6 lines · Andrii Nakryiko

Currently put_uprobe() might trigger mutex_lock()/mutex_unlock(), which makes it unsuitable to be called from more restricted context like softirq.

Let's make put_uprobe() agnostic to the context in which it is called, and use work queue to defer the mutex-protected clean up steps.

...

Quoted 14 lines
kernel/events/uprobes.c +14 -0
+static void uprobe_free_deferred(struct work_struct *work)
+{
+     struct uprobe *uprobe = container_of(work, struct uprobe, work);
+
+     /*
+      * If application munmap(exec_vma) before uprobe_unregister()
+      * gets called, we don't get a chance to remove uprobe from
+      * delayed_uprobe_list from remove_breakpoint(). Do it here.
+      */
+     mutex_lock(&delayed_uprobe_lock);
+     delayed_uprobe_remove(uprobe, NULL);
+     mutex_unlock(&delayed_uprobe_lock);
+
+     kfree(uprobe);

kernel/events/uprobes.c static inline bool uprobe_is_active(struct uprobe *uprobe) · line 652

Quoted 10 lines
kernel/events/uprobes.c +4 -1
+}
+
 static void uprobe_free_rcu(struct rcu_head *rcu)
 {
      struct uprobe *uprobe = container_of(rcu, struct uprobe, rcu);
 
-     kfree(uprobe);
+     INIT_WORK(&uprobe->work, uprobe_free_deferred);
+     schedule_work(&uprobe->work);
 }

This is still wrong afaics...

Quoted 3 lines

If put_uprobe() can be called from softirq (after the next patch), then put_uprobe() and all other users of uprobes_treelock should use write_lock_bh/read_lock_bh to avoid the deadlock.

Ok, I see the problem, that's unfortunate.

I see three ways to handle that:

1) keep put_uprobe() as is, and instead do schedule_work() from the timer thread to postpone put_uprobe(). (but I'm not a big fan of this)
2) move uprobes_treelock part of put_uprobe() into rcu callback, I think it has no bearing on correctness, uprobe_is_active() is there already to handle races between putting uprobe and removing it from uprobes_tree (I prefer this one over #1 )
3) you might like this the most ;) I think I can simplify hprobes_expire() from patch #2 to not need put_uprobe() at all, if I protect uprobe lifetime with non-sleepable rcu_read_lock()/rcu_read_unlock() and perform try_get_uprobe() as the very last step after cmpxchg() succeeded.

Quoted 1 line

I'm leaning towards #3, but #2 seems fine to me as well.

Ok, so just a short update. I don't think #3 works, I do need try_get_uprobe() before I know for sure that cmpxchg() succeeds. Which means I'd need a compensating put_uprobe() if cmpxchg() fails. So for put_uprobe(), I just made it do all the locking in deferred work callback (which is #2 above), which I think resolved the issue you pointed out with potential deadlock and removes any limitations on put_uprobe().

Also, I rewrote the hprobe_consume() and hprobe_expire() in terms of an explicit state machine with 4 possible states (LEASED, STABLE, GONE, CONSUMED), which I think makes the logic a bit more straightforward to follow. Hopefully that will make the change more palatable for you. I'm probably going to post patches next week, though.

Quoted 17 lines
Quoted 4 lines

To be honest... I simply can't force myself to even try to read 2/3 ;) I'll try to do this later, but I am sure I will never like it, sorry.

This might sound rude, but the goal here is not to make you like it :) The goal is to improve performance with minimal complexity. And I'm very open to any alternative proposals as to how to make uretprobes RCU-protected to avoid refcounting in the hot path.

I think #3 proposal above will make it a bit more palatable (but there is still locklessness, cmpxchg, etc, I see no way around that, unfortunately).

Quoted 3 lines

Oleg.