Skip to contentSkip to conversation

bpf: Fast-Path approach for BPF program termination

PATCH In review Siddharth Chintamaneni 3 participants 12 messages Sep 7, 2025 – Sep 17, 2025

Subsystems (6)
x86 Kselftest BPF BPF selftests +2 more subsystems
lore
Share & tools
lore
#0 lore raw

cover bpf: Fast-Path approach for BPF program termination

This is RFC v3 of

	https://lore.kernel.org/all/[email protected]/

The termination handler call from the softlockup detector is mainly for the demonstration of the entire workflow and also serves as a potential use case for discussion. However, the runtime mechanism is modular enough to be ported to different scenarios such as deadlocks, page faults, userspace BPF management tools, and stack overflows.

The main changes that we bring in this version are: We have avoided the memory overhead caused by program cloning in previous versions. During normal program execution, none of the termination logic causes any additional overhead.

Change log:
v2 -> v3:
- Cloning of BPF programs has been removed.
- Created call sites table to maintain helper/ kfunc call instruction offsets.
- Termination is triggered inside the softlockup detector not affecting any fast path operations.

v1 -> v2:
- Patch generation has been moved after verification and before JIT.
- Now patch generation handles both helpers and kfuncs.
- Sanity check on original prog and patch prog after JIT.
- Runtime termination handler is now global termination mechanism using text_poke.
- Termination is triggered by watchdog timer.

 arch/x86/net/bpf_jit_comp.c                   | 141 ++++++++++++++++++
 include/linux/bpf.h                           |  77 ++++++----
 include/linux/bpf_verifier.h                  |   1 +
 include/linux/filter.h                        |   6 +
 kernel/bpf/core.c                             |  67 +++++++++
 kernel/bpf/verifier.c                         | 135 +++++++++++++++--
 kernel/watchdog.c                             |   8 +
 .../bpf/prog_tests/bpf_termination.c          |  39 +++++
 .../selftests/bpf/progs/bpf_termination.c     |  47 ++++++
 9 files changed, 482 insertions(+), 39 deletions(-)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/bpf_termination.c
 create mode 100644 tools/testing/selftests/bpf/progs/bpf_termination.c
Signature · 1 line
2.43.0
#1 lore raw

PATCH 1/4 bpf: Introduce new structs and struct fields for fast path termination

Introduced the definition of struct bpf_term_aux_states required to support fast-path termination of BPF programs. Added the memory allocation and free logic for newly added term_states feild in struct bpf_prog.

---
 include/linux/bpf.h | 75 +++++++++++++++++++++++++++++----------------
 kernel/bpf/core.c   | 31 +++++++++++++++++++
 2 files changed, 79 insertions(+), 27 deletions(-)
include/linux/bpf.h +48 -27
index 8f6e87f0f3a8..caaee33744fc 100644
@@ -1584,6 +1584,25 @@ struct bpf_stream_stage {
 	int len;
 };
 
+struct call_aux_states {
+	int call_bpf_insn_idx;
+	int jit_call_idx;
+	u8 is_helper_kfunc;
+	u8 is_bpf_loop;
+	u8 is_bpf_loop_cb_inline;
+};
+
+struct bpf_term_patch_call_sites {
+	u32 call_sites_cnt;
+	struct call_aux_states *call_states;
+};
+
+struct bpf_term_aux_states {
+	struct bpf_prog *prog;
+	struct work_struct work;
+	struct bpf_term_patch_call_sites *patch_call_sites;
+};
+
 struct bpf_prog_aux {
 	atomic64_t refcnt;
 	u32 used_map_cnt;
@@ -1618,6 +1637,7 @@ struct bpf_prog_aux {
 	bool tail_call_reachable;
 	bool xdp_has_frags;
 	bool exception_cb;
+	bool is_bpf_loop_cb_non_inline;
 	bool exception_boundary;
 	bool is_extended; /* true if extended by freplace program */
 	bool jits_use_priv_stack;
@@ -1696,33 +1716,34 @@ struct bpf_prog_aux {
 };
 
 struct bpf_prog {
-	u16			pages;		/* Number of allocated pages */
-	u16			jited:1,	/* Is our filter JIT'ed? */
-				jit_requested:1,/* archs need to JIT the prog */
-				gpl_compatible:1, /* Is filter GPL compatible? */
-				cb_access:1,	/* Is control block accessed? */
-				dst_needed:1,	/* Do we need dst entry? */
-				blinding_requested:1, /* needs constant blinding */
-				blinded:1,	/* Was blinded */
-				is_func:1,	/* program is a bpf function */
-				kprobe_override:1, /* Do we override a kprobe? */
-				has_callchain_buf:1, /* callchain buffer allocated? */
-				enforce_expected_attach_type:1, /* Enforce expected_attach_type checking at attach time */
-				call_get_stack:1, /* Do we call bpf_get_stack() or bpf_get_stackid() */
-				call_get_func_ip:1, /* Do we call get_func_ip() */
-				tstamp_type_access:1, /* Accessed __sk_buff->tstamp_type */
-				sleepable:1;	/* BPF program is sleepable */
-	enum bpf_prog_type	type;		/* Type of BPF program */
-	enum bpf_attach_type	expected_attach_type; /* For some prog types */
-	u32			len;		/* Number of filter blocks */
-	u32			jited_len;	/* Size of jited insns in bytes */
-	u8			tag[BPF_TAG_SIZE];
-	struct bpf_prog_stats __percpu *stats;
-	int __percpu		*active;
-	unsigned int		(*bpf_func)(const void *ctx,
-					    const struct bpf_insn *insn);
-	struct bpf_prog_aux	*aux;		/* Auxiliary fields */
-	struct sock_fprog_kern	*orig_prog;	/* Original BPF program */
+	u16				pages;		/* Number of allocated pages */
+	u16				jited:1,	/* Is our filter JIT'ed? */
+					jit_requested:1,/* archs need to JIT the prog */
+					gpl_compatible:1, /* Is filter GPL compatible? */
+					cb_access:1,	/* Is control block accessed? */
+					dst_needed:1,	/* Do we need dst entry? */
+					blinding_requested:1, /* needs constant blinding */
+					blinded:1,	/* Was blinded */
+					is_func:1,	/* program is a bpf function */
+					kprobe_override:1, /* Do we override a kprobe? */
+					has_callchain_buf:1, /* callchain buffer allocated? */
+					enforce_expected_attach_type:1, /* Enforce expected_attach_type checking at attach time */
+					call_get_stack:1, /* Do we call bpf_get_stack() or bpf_get_stackid() */
+					call_get_func_ip:1, /* Do we call get_func_ip() */
+					tstamp_type_access:1, /* Accessed __sk_buff->tstamp_type */
+					sleepable:1;	/* BPF program is sleepable */
+	enum bpf_prog_type		type;		/* Type of BPF program */
+	enum bpf_attach_type		expected_attach_type; /* For some prog types */
+	u32				len;		/* Number of filter blocks */
+	u32				jited_len;	/* Size of jited insns in bytes */
+	u8				tag[BPF_TAG_SIZE];
+	struct bpf_prog_stats __percpu	*stats;
+	int __percpu			*active;
+	unsigned int			(*bpf_func)(const void *ctx,
+						    const struct bpf_insn *insn);
+	struct bpf_prog_aux		*aux;		/* Auxiliary fields */
+	struct sock_fprog_kern		*orig_prog;	/* Original BPF program */
+	struct bpf_term_aux_states	*term_states;
 	/* Instructions for interpreter */
 	union {
 		DECLARE_FLEX_ARRAY(struct sock_filter, insns);
kernel/bpf/core.c +31 -0
index ef01cc644a96..740b5a3a6b55 100644
@@ -100,6 +100,8 @@ struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flag
 	gfp_t gfp_flags = bpf_memcg_flags(GFP_KERNEL | __GFP_ZERO | gfp_extra_flags);
 	struct bpf_prog_aux *aux;
 	struct bpf_prog *fp;
+	struct bpf_term_aux_states *term_states = NULL;
+	struct bpf_term_patch_call_sites *patch_call_sites = NULL;
 
 	size = round_up(size, __PAGE_SIZE);
 	fp = __vmalloc(size, gfp_flags);
@@ -118,11 +120,24 @@ struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flag
 		return NULL;
 	}
 
+	term_states = kzalloc(sizeof(*term_states), bpf_memcg_flags(GFP_KERNEL | gfp_extra_flags));
+	if (!term_states)
+		goto free_alloc_percpu;
+
+	patch_call_sites = kzalloc(sizeof(*patch_call_sites), bpf_memcg_flags(GFP_KERNEL | gfp_extra_flags));
+	if (!patch_call_sites)
+		goto free_bpf_term_states;
+
 	fp->pages = size / PAGE_SIZE;
 	fp->aux = aux;
 	fp->aux->prog = fp;
 	fp->jit_requested = ebpf_jit_enabled();
 	fp->blinding_requested = bpf_jit_blinding_enabled(fp);
+	fp->term_states = term_states;
+	fp->term_states->patch_call_sites = patch_call_sites;
+	fp->term_states->patch_call_sites->call_sites_cnt = 0;
+	fp->term_states->prog = fp;
+
 #ifdef CONFIG_CGROUP_BPF
 	aux->cgroup_atype = CGROUP_BPF_ATTACH_TYPE_INVALID;
 #endif
@@ -140,6 +155,15 @@ struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flag
 #endif
 
 	return fp;
+
+free_bpf_term_states:
+	kfree(term_states);
+free_alloc_percpu:
+	free_percpu(fp->active);
+	kfree(aux);
+	vfree(fp);
+
+	return NULL;
 }
 
 struct bpf_prog *bpf_prog_alloc(unsigned int size, gfp_t gfp_extra_flags)
@@ -266,6 +290,7 @@ struct bpf_prog *bpf_prog_realloc(struct bpf_prog *fp_old, unsigned int size,
 		memcpy(fp, fp_old, fp_old->pages * PAGE_SIZE);
 		fp->pages = pages;
 		fp->aux->prog = fp;
+		fp->term_states->prog = fp;
 
 		/* We keep fp->aux from fp_old around in the new
 		 * reallocated structure.
@@ -273,6 +298,7 @@ struct bpf_prog *bpf_prog_realloc(struct bpf_prog *fp_old, unsigned int size,
 		fp_old->aux = NULL;
 		fp_old->stats = NULL;
 		fp_old->active = NULL;
+		fp_old->term_states = NULL;
 		__bpf_prog_free(fp_old);
 	}
 
@@ -287,6 +313,11 @@ void __bpf_prog_free(struct bpf_prog *fp)
 		kfree(fp->aux->poke_tab);
 		kfree(fp->aux);
 	}
+	if (fp->term_states) {
+		if (fp->term_states->patch_call_sites)
+			kfree(fp->term_states->patch_call_sites);
+		kfree(fp->term_states);
+	}
 	free_percpu(fp->stats);
 	free_percpu(fp->active);
 	vfree(fp);
Signature · 1 line
2.43.0
#2 lore raw

Re: [PATCH 1/4] bpf: Introduce new structs and struct fields for fast path termination

Quoted 5 lines · Siddharth Chintamaneni

Introduced the definition of struct bpf_term_aux_states required to support fast-path termination of BPF programs. Added the memory allocation and free logic for newly added term_states feild in struct bpf_prog.

typo: field

Quoted 96 lines
---
 include/linux/bpf.h | 75 +++++++++++++++++++++++++++++----------------
 kernel/bpf/core.c   | 31 +++++++++++++++++++
 2 files changed, 79 insertions(+), 27 deletions(-)
include/linux/bpf.h +39 -27
index 8f6e87f0f3a8..caaee33744fc 100644
@@ -1584,6 +1584,25 @@ struct bpf_stream_stage {
        int len;
 };
 
+struct call_aux_states {
+       int call_bpf_insn_idx;
+       int jit_call_idx;
+       u8 is_helper_kfunc;
+       u8 is_bpf_loop;
+       u8 is_bpf_loop_cb_inline;
+};
+
+struct bpf_term_patch_call_sites {
+       u32 call_sites_cnt;
+       struct call_aux_states *call_states;
+};
+
+struct bpf_term_aux_states {
+       struct bpf_prog *prog;
+       struct work_struct work;
+       struct bpf_term_patch_call_sites *patch_call_sites;
+};
+
 struct bpf_prog_aux {
        atomic64_t refcnt;
        u32 used_map_cnt;
@@ -1618,6 +1637,7 @@ struct bpf_prog_aux {
        bool tail_call_reachable;
        bool xdp_has_frags;
        bool exception_cb;
+       bool is_bpf_loop_cb_non_inline;
        bool exception_boundary;
        bool is_extended; /* true if extended by freplace program */
        bool jits_use_priv_stack;
@@ -1696,33 +1716,34 @@ struct bpf_prog_aux {
 };
 
 struct bpf_prog {
-       u16                     pages;          /* Number of allocated pages */
-       u16                     jited:1,        /* Is our filter JIT'ed? */
-                               jit_requested:1,/* archs need to JIT the prog */
-                               gpl_compatible:1, /* Is filter GPL compatible? */
-                               cb_access:1,    /* Is control block accessed? */
-                               dst_needed:1,   /* Do we need dst entry? */
-                               blinding_requested:1, /* needs constant blinding */
-                               blinded:1,      /* Was blinded */
-                               is_func:1,      /* program is a bpf function */
-                               kprobe_override:1, /* Do we override a kprobe? */
-                               has_callchain_buf:1, /* callchain buffer allocated? */
-                               enforce_expected_attach_type:1, /* Enforce expected_attach_type checking at attach time */
-                               call_get_stack:1, /* Do we call bpf_get_stack() or bpf_get_stackid() */
-                               call_get_func_ip:1, /* Do we call get_func_ip() */
-                               tstamp_type_access:1, /* Accessed __sk_buff->tstamp_type */
-                               sleepable:1;    /* BPF program is sleepable */
-       enum bpf_prog_type      type;           /* Type of BPF program */
-       enum bpf_attach_type    expected_attach_type; /* For some prog types */
-       u32                     len;            /* Number of filter blocks */
-       u32                     jited_len;      /* Size of jited insns in bytes */
-       u8                      tag[BPF_TAG_SIZE];
-       struct bpf_prog_stats __percpu *stats;
-       int __percpu            *active;
-       unsigned int            (*bpf_func)(const void *ctx,
-                                           const struct bpf_insn *insn);
-       struct bpf_prog_aux     *aux;           /* Auxiliary fields */
-       struct sock_fprog_kern  *orig_prog;     /* Original BPF program */
+       u16                             pages;          /* Number of allocated pages */
+       u16                             jited:1,        /* Is our filter JIT'ed? */
+                                       jit_requested:1,/* archs need to JIT the prog */
+                                       gpl_compatible:1, /* Is filter GPL compatible? */
+                                       cb_access:1,    /* Is control block accessed? */
+                                       dst_needed:1,   /* Do we need dst entry? */
+                                       blinding_requested:1, /* needs constant blinding */
+                                       blinded:1,      /* Was blinded */
+                                       is_func:1,      /* program is a bpf function */
+                                       kprobe_override:1, /* Do we override a kprobe? */
+                                       has_callchain_buf:1, /* callchain buffer allocated? */
+                                       enforce_expected_attach_type:1, /* Enforce expected_attach_type checking at attach time */
+                                       call_get_stack:1, /* Do we call bpf_get_stack() or bpf_get_stackid() */
+                                       call_get_func_ip:1, /* Do we call get_func_ip() */
+                                       tstamp_type_access:1, /* Accessed __sk_buff->tstamp_type */
+                                       sleepable:1;    /* BPF program is sleepable */
+       enum bpf_prog_type              type;           /* Type of BPF program */
+       enum bpf_attach_type            expected_attach_type; /* For some prog types */
+       u32                             len;            /* Number of filter blocks */

include/linux/bpf.h struct bpf_prog_aux { · line 1747

Quoted 10 lines
include/linux/bpf.h +9 -0
+       u32                             jited_len;      /* Size of jited insns in bytes */
+       u8                              tag[BPF_TAG_SIZE];
+       struct bpf_prog_stats __percpu  *stats;
+       int __percpu                    *active;
+       unsigned int                    (*bpf_func)(const void *ctx,
+                                                   const struct bpf_insn *insn);
+       struct bpf_prog_aux             *aux;           /* Auxiliary fields */
+       struct sock_fprog_kern          *orig_prog;     /* Original BPF program */
+       struct bpf_term_aux_states      *term_states;
        /* Instructions for interpreter */

This hunk looks bad, please only include what you touched, and don't reformat the rest.

Quoted 87 lines
include/linux/bpf.h +0 -0
        union {
                DECLARE_FLEX_ARRAY(struct sock_filter, insns);
kernel/bpf/core.c +31 -1
index ef01cc644a96..740b5a3a6b55 100644
@@ -100,6 +100,8 @@ struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flag
        gfp_t gfp_flags = bpf_memcg_flags(GFP_KERNEL | __GFP_ZERO | gfp_extra_flags);
        struct bpf_prog_aux *aux;
        struct bpf_prog *fp;
+       struct bpf_term_aux_states *term_states = NULL;
+       struct bpf_term_patch_call_sites *patch_call_sites = NULL;
 
        size = round_up(size, __PAGE_SIZE);
        fp = __vmalloc(size, gfp_flags);
@@ -118,11 +120,24 @@ struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flag
                return NULL;
        }
 
+       term_states = kzalloc(sizeof(*term_states), bpf_memcg_flags(GFP_KERNEL | gfp_extra_flags));
+       if (!term_states)
+               goto free_alloc_percpu;
+
+       patch_call_sites = kzalloc(sizeof(*patch_call_sites), bpf_memcg_flags(GFP_KERNEL | gfp_extra_flags));
+       if (!patch_call_sites)
+               goto free_bpf_term_states;
+
        fp->pages = size / PAGE_SIZE;
        fp->aux = aux;
        fp->aux->prog = fp;
        fp->jit_requested = ebpf_jit_enabled();
        fp->blinding_requested = bpf_jit_blinding_enabled(fp);
+       fp->term_states = term_states;
+       fp->term_states->patch_call_sites = patch_call_sites;
+       fp->term_states->patch_call_sites->call_sites_cnt = 0;
+       fp->term_states->prog = fp;
+
 #ifdef CONFIG_CGROUP_BPF
        aux->cgroup_atype = CGROUP_BPF_ATTACH_TYPE_INVALID;
 #endif
@@ -140,6 +155,15 @@ struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flag
 #endif
 
        return fp;
+
+free_bpf_term_states:
+       kfree(term_states);
+free_alloc_percpu:
+       free_percpu(fp->active);
+       kfree(aux);
+       vfree(fp);
+
+       return NULL;
 }
 
 struct bpf_prog *bpf_prog_alloc(unsigned int size, gfp_t gfp_extra_flags)
@@ -266,6 +290,7 @@ struct bpf_prog *bpf_prog_realloc(struct bpf_prog *fp_old, unsigned int size,
                memcpy(fp, fp_old, fp_old->pages * PAGE_SIZE);
                fp->pages = pages;
                fp->aux->prog = fp;
+               fp->term_states->prog = fp;
 
                /* We keep fp->aux from fp_old around in the new
                 * reallocated structure.
@@ -273,6 +298,7 @@ struct bpf_prog *bpf_prog_realloc(struct bpf_prog *fp_old, unsigned int size,
                fp_old->aux = NULL;
                fp_old->stats = NULL;
                fp_old->active = NULL;
+               fp_old->term_states = NULL;
                __bpf_prog_free(fp_old);
        }
 
@@ -287,6 +313,11 @@ void __bpf_prog_free(struct bpf_prog *fp)
                kfree(fp->aux->poke_tab);
                kfree(fp->aux);
        }
+       if (fp->term_states) {
+               if (fp->term_states->patch_call_sites)
+                       kfree(fp->term_states->patch_call_sites);
+               kfree(fp->term_states);
+       }
        free_percpu(fp->stats);
        free_percpu(fp->active);
        vfree(fp);
--

2.43.0

#3 lore raw

Re: [PATCH 1/4] bpf: Introduce new structs and struct fields for fast path termination

Quoted 112 lines · Kumar Kartikeya Dwivedi
Quoted 5 lines · Siddharth Chintamaneni

Introduced the definition of struct bpf_term_aux_states required to support fast-path termination of BPF programs. Added the memory allocation and free logic for newly added term_states feild in struct bpf_prog.

typo: field

Quoted 101 lines
---
 include/linux/bpf.h | 75 +++++++++++++++++++++++++++++----------------
 kernel/bpf/core.c   | 31 +++++++++++++++++++
 2 files changed, 79 insertions(+), 27 deletions(-)
include/linux/bpf.h +44 -27
index 8f6e87f0f3a8..caaee33744fc 100644
@@ -1584,6 +1584,25 @@ struct bpf_stream_stage {
        int len;
 };
 
+struct call_aux_states {
+       int call_bpf_insn_idx;
+       int jit_call_idx;
+       u8 is_helper_kfunc;
+       u8 is_bpf_loop;
+       u8 is_bpf_loop_cb_inline;
+};
+
+struct bpf_term_patch_call_sites {
+       u32 call_sites_cnt;
+       struct call_aux_states *call_states;
+};
+
+struct bpf_term_aux_states {
+       struct bpf_prog *prog;
+       struct work_struct work;
+       struct bpf_term_patch_call_sites *patch_call_sites;
+};
+
 struct bpf_prog_aux {
        atomic64_t refcnt;
        u32 used_map_cnt;
@@ -1618,6 +1637,7 @@ struct bpf_prog_aux {
        bool tail_call_reachable;
        bool xdp_has_frags;
        bool exception_cb;
+       bool is_bpf_loop_cb_non_inline;
        bool exception_boundary;
        bool is_extended; /* true if extended by freplace program */
        bool jits_use_priv_stack;
@@ -1696,33 +1716,34 @@ struct bpf_prog_aux {
 };
 
 struct bpf_prog {
-       u16                     pages;          /* Number of allocated pages */
-       u16                     jited:1,        /* Is our filter JIT'ed? */
-                               jit_requested:1,/* archs need to JIT the prog */
-                               gpl_compatible:1, /* Is filter GPL compatible? */
-                               cb_access:1,    /* Is control block accessed? */
-                               dst_needed:1,   /* Do we need dst entry? */
-                               blinding_requested:1, /* needs constant blinding */
-                               blinded:1,      /* Was blinded */
-                               is_func:1,      /* program is a bpf function */
-                               kprobe_override:1, /* Do we override a kprobe? */
-                               has_callchain_buf:1, /* callchain buffer allocated? */
-                               enforce_expected_attach_type:1, /* Enforce expected_attach_type checking at attach time */
-                               call_get_stack:1, /* Do we call bpf_get_stack() or bpf_get_stackid() */
-                               call_get_func_ip:1, /* Do we call get_func_ip() */
-                               tstamp_type_access:1, /* Accessed __sk_buff->tstamp_type */
-                               sleepable:1;    /* BPF program is sleepable */
-       enum bpf_prog_type      type;           /* Type of BPF program */
-       enum bpf_attach_type    expected_attach_type; /* For some prog types */
-       u32                     len;            /* Number of filter blocks */
-       u32                     jited_len;      /* Size of jited insns in bytes */
-       u8                      tag[BPF_TAG_SIZE];
-       struct bpf_prog_stats __percpu *stats;
-       int __percpu            *active;
-       unsigned int            (*bpf_func)(const void *ctx,
-                                           const struct bpf_insn *insn);
-       struct bpf_prog_aux     *aux;           /* Auxiliary fields */
-       struct sock_fprog_kern  *orig_prog;     /* Original BPF program */
+       u16                             pages;          /* Number of allocated pages */
+       u16                             jited:1,        /* Is our filter JIT'ed? */
+                                       jit_requested:1,/* archs need to JIT the prog */
+                                       gpl_compatible:1, /* Is filter GPL compatible? */
+                                       cb_access:1,    /* Is control block accessed? */
+                                       dst_needed:1,   /* Do we need dst entry? */
+                                       blinding_requested:1, /* needs constant blinding */
+                                       blinded:1,      /* Was blinded */
+                                       is_func:1,      /* program is a bpf function */
+                                       kprobe_override:1, /* Do we override a kprobe? */
+                                       has_callchain_buf:1, /* callchain buffer allocated? */
+                                       enforce_expected_attach_type:1, /* Enforce expected_attach_type checking at attach time */
+                                       call_get_stack:1, /* Do we call bpf_get_stack() or bpf_get_stackid() */
+                                       call_get_func_ip:1, /* Do we call get_func_ip() */
+                                       tstamp_type_access:1, /* Accessed __sk_buff->tstamp_type */
+                                       sleepable:1;    /* BPF program is sleepable */
+       enum bpf_prog_type              type;           /* Type of BPF program */
+       enum bpf_attach_type            expected_attach_type; /* For some prog types */
+       u32                             len;            /* Number of filter blocks */
+       u32                             jited_len;      /* Size of jited insns in bytes */
+       u8                              tag[BPF_TAG_SIZE];
+       struct bpf_prog_stats __percpu  *stats;
+       int __percpu                    *active;
+       unsigned int                    (*bpf_func)(const void *ctx,
Quoted 10 lines

include/linux/bpf.h struct bpf_prog_aux { · line 1747

Quoted 5 lines
include/linux/bpf.h +4 -0
+                                                   const struct bpf_insn *insn);
+       struct bpf_prog_aux             *aux;           /* Auxiliary fields */
+       struct sock_fprog_kern          *orig_prog;     /* Original BPF program */
+       struct bpf_term_aux_states      *term_states;
        /* Instructions for interpreter */

This hunk looks bad, please only include what you touched, and don't reformat the rest.

I'll drop it

<SNIP>

#4 lore raw

PATCH 2/4 bpf: Creating call sites table to stub instructions during runtime

In reply to Siddharth Chintamaneni

Create callsites tables and store jit indexes of RET_NULL calls to poke them later with dummy functions. Additional to jit indexes, meta data about helpers/kfuncs/loops is stored. Later this could be extended to remaining potential long running iterator helpers/kfuncs.

---
 arch/x86/net/bpf_jit_comp.c  |   9 +++
 include/linux/bpf_verifier.h |   1 +
 kernel/bpf/core.c            |   5 +-
 kernel/bpf/verifier.c        | 135 +++++++++++++++++++++++++++++++----
 4 files changed, 137 insertions(+), 13 deletions(-)
arch/x86/net/bpf_jit_comp.c +9 -0
index 7e3fca164620..107a44729675 100644
@@ -3733,6 +3733,15 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_prog *prog)
 	}
 
 	if (!image || !prog->is_func || extra_pass) {
+		
+		if (addrs) {
+			struct bpf_term_patch_call_sites *patch_call_sites = prog->term_states->patch_call_sites;
+			for (int i = 0; i < patch_call_sites->call_sites_cnt; i++) {
+				struct call_aux_states *call_states = patch_call_sites->call_states + i;
+				call_states->jit_call_idx = addrs[call_states->call_bpf_insn_idx];
+			}
+		}
+		
 		if (image)
 			bpf_prog_fill_jited_linfo(prog, addrs + 1);
 out_addrs:
include/linux/bpf_verifier.h +1 -0
index 020de62bd09c..2c8bfde8191a 100644
@@ -677,6 +677,7 @@ struct bpf_subprog_info {
 	bool is_cb: 1;
 	bool is_async_cb: 1;
 	bool is_exception_cb: 1;
+	bool is_bpf_loop_cb_non_inline: 1;
 	bool args_cached: 1;
 	/* true if bpf_fastcall stack region is used by functions that can't be inlined */
 	bool keep_fastcall_stack: 1;
kernel/bpf/core.c +4 -1
index 740b5a3a6b55..93442ab2acde 100644
@@ -136,6 +136,7 @@ struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flag
 	fp->term_states = term_states;
 	fp->term_states->patch_call_sites = patch_call_sites;
 	fp->term_states->patch_call_sites->call_sites_cnt = 0;
+	fp->term_states->patch_call_sites->call_states = NULL;
 	fp->term_states->prog = fp;
 
 #ifdef CONFIG_CGROUP_BPF
@@ -314,8 +315,10 @@ void __bpf_prog_free(struct bpf_prog *fp)
 		kfree(fp->aux);
 	}
 	if (fp->term_states) {
-		if (fp->term_states->patch_call_sites)
+		if (fp->term_states->patch_call_sites) {
+			vfree(fp->term_states->patch_call_sites->call_states);
 			kfree(fp->term_states->patch_call_sites);
+		}
 		kfree(fp->term_states);
 	}
 	free_percpu(fp->stats);
kernel/bpf/verifier.c +123 -12

259 lines not on this page · raw message

Signature · 1 line
2.43.0
#5 lore raw

PATCH 3/4 bpf: runtime part of fast-path termination approach

In reply to Siddharth Chintamaneni

Update softlock detection logic to detect any stalls due to BPF programs. When softlockup is detected, bpf_die will be added to a workqueue on a CPU. With this implementation termination handler will only get triggered when CONFIG_SOFTLOCKUP_DETECTOR is enabled.

Inside bpf_die, we perform the text_poke to stub helpers/kfuncs. The current implementation handles termination of long running bpf_loop iterators both inlining and non-inlining case.

The limitation of this implementation is that the termination handler atleast need a single CPU to run.

---
 arch/x86/net/bpf_jit_comp.c | 132 ++++++++++++++++++++++++++++++++++++
 include/linux/bpf.h         |   2 +
 include/linux/filter.h      |   6 ++
 kernel/bpf/core.c           |  35 +++++++++-
 kernel/watchdog.c           |   8 +++
 5 files changed, 182 insertions(+), 1 deletion(-)
arch/x86/net/bpf_jit_comp.c +132 -0
index 107a44729675..4de9a8cdc465 100644
@@ -2606,6 +2606,10 @@ st:			if (is_imm8(insn->off))
 				if (arena_vm_start)
 					pop_r12(&prog);
 			}
+			/* emiting 5 byte nop for non-inline bpf_loop callback */
+			if (bpf_is_subprog(bpf_prog) && bpf_prog->aux->is_bpf_loop_cb_non_inline) {
+				emit_nops(&prog, X86_PATCH_SIZE);
+			}
 			EMIT1(0xC9);         /* leave */
 			emit_return(&prog, image + addrs[i - 1] + (prog - temp));
 			break;
@@ -3833,6 +3837,8 @@ bool bpf_jit_supports_private_stack(void)
 	return true;
 }
 
+
+
 void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp), void *cookie)
 {
 #if defined(CONFIG_UNWINDER_ORC)
@@ -3849,6 +3855,132 @@ void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp
 #endif
 }
 
+void in_place_patch_bpf_prog(struct bpf_prog *prog)
+{
+	struct call_aux_states *call_states;
+	unsigned long new_target;
+	unsigned char *addr;
+	u8 ret_jmp_size = 1;
+	if (cpu_wants_rethunk()) {
+		ret_jmp_size = 5;
+	}
+	call_states = prog->term_states->patch_call_sites->call_states;
+	for (int i = 0; i < prog->term_states->patch_call_sites->call_sites_cnt; i++) {
+		
+		new_target = (unsigned long) bpf_termination_null_func;
+		if (call_states[i].is_bpf_loop_cb_inline) {
+			new_target = (unsigned long) bpf_loop_term_callback;	
+		}
+		char new_insn[5];
+
+		addr = (unsigned char *)prog->bpf_func + call_states->jit_call_idx;
+
+		unsigned long new_rel = (unsigned long)(new_target - (unsigned long)(addr + 5));
+		new_insn[0] = 0xE8;
+		new_insn[1] = (new_rel >> 0) & 0xFF;
+		new_insn[2] = (new_rel >> 8) & 0xFF;
+		new_insn[3] = (new_rel >> 16) & 0xFF;
+		new_insn[4] = (new_rel >> 24) & 0xFF;
+
+		smp_text_poke_batch_add(addr, new_insn, 5 /* call instruction len */, NULL);
+	}
+
+	if (prog->aux->is_bpf_loop_cb_non_inline) {
+		
+		char new_insn[5] = { 0xB8, 0x01, 0x00, 0x00, 0x00 };
+		char old_insn[5] = { 0x0F, 0x1F, 0x44, 0x00, 0x00 };
+		smp_text_poke_batch_add(prog->bpf_func + prog->jited_len - 
+				(1 + ret_jmp_size) /* leave, jmp/ ret */ - 5 /* nop size */, new_insn, 5 /* mov eax, 1 */, old_insn);
+	}
+
+
+	/* flush all text poke calls */
+	smp_text_poke_batch_finish();
+}
+
+void bpf_die(struct bpf_prog *prog)
+{
+	u8 ret_jmp_size = 1;
+	if (cpu_wants_rethunk()) {
+		ret_jmp_size = 5;
+	}
+
+	/*
+	 * Replacing 5 byte nop in prologue with jmp instruction to ret
+	 */
+	unsigned long jmp_offset = prog->jited_len - (4 /* First endbr is 4 bytes */ 
+					+ 5 /* noop is 5 bytes */ 
+					+ ret_jmp_size /* 5 bytes of jmp return_thunk or 1 byte ret*/);
+
+	char new_insn[5];
+	new_insn[0] = 0xE9;
+	new_insn[1] = (jmp_offset >> 0) & 0xFF;
+	new_insn[2] = (jmp_offset >> 8) & 0xFF;
+	new_insn[3] = (jmp_offset >> 16) & 0xFF;
+	new_insn[4] = (jmp_offset >> 24) & 0xFF;
+
+	smp_text_poke_batch_add(prog->bpf_func + 4, new_insn, 5, NULL);
+
+	if (prog->aux->func_cnt) {
+		for (int i = 0; i < prog->aux->func_cnt; i++) {
+			in_place_patch_bpf_prog(prog->aux->func[i]);
+		}
+	} else {
+		in_place_patch_bpf_prog(prog);
+	}
+
+}
+
+void bpf_prog_termination_deferred(struct work_struct *work)
+{
+	struct bpf_term_aux_states *term_states = container_of(work, struct bpf_term_aux_states,
+						 work);
+	struct bpf_prog *prog = term_states->prog;
+
+	bpf_die(prog);
+}
+
+static struct workqueue_struct *bpf_termination_wq;
+
+void bpf_softlockup(u32 dur_s)
+{
+	unsigned long addr;
+	struct unwind_state state;
+	struct bpf_prog *prog;
+
+	for (unwind_start(&state, current, NULL, NULL); !unwind_done(&state);
+	     unwind_next_frame(&state)) {
+		addr = unwind_get_return_address(&state);
+		if (!addr)
+			break;
+
+		if (!is_bpf_text_address(addr))
+			continue;
+
+		rcu_read_lock();
+		prog = bpf_prog_ksym_find(addr);
+		rcu_read_unlock();
+		if (bpf_is_subprog(prog))
+			continue;
+
+		if (atomic_cmpxchg(&prog->term_states->bpf_die_in_progress, 0, 1))
+			break;
+	
+		bpf_termination_wq = alloc_workqueue("bpf_termination_wq", WQ_UNBOUND, 1);
+		if (!bpf_termination_wq)
+			pr_err("Failed to alloc workqueue for bpf termination.\n");
+
+		queue_work(bpf_termination_wq, &prog->term_states->work);
+
+		/* Currently nested programs are not terminated together.
+		 * Removing this break will result in BPF trampolines being
+		 * identified as is_bpf_text_address resulting in NULL ptr
+		 * deref in next step.
+		 */
+		break;
+	}
+}
+
 void bpf_arch_poke_desc_update(struct bpf_jit_poke_descriptor *poke,
 			       struct bpf_prog *new, struct bpf_prog *old)
 {
include/linux/bpf.h +2 -0
index caaee33744fc..03fce8f2c466 100644
@@ -71,6 +71,7 @@ typedef int (*bpf_iter_init_seq_priv_t)(void *private_data,
 typedef void (*bpf_iter_fini_seq_priv_t)(void *private_data);
 typedef unsigned int (*bpf_func_t)(const void *,
 				   const struct bpf_insn *);
+
 struct bpf_iter_seq_info {
 	const struct seq_operations *seq_ops;
 	bpf_iter_init_seq_priv_t init_seq_private;
@@ -1600,6 +1601,7 @@ struct bpf_term_patch_call_sites {
 struct bpf_term_aux_states {
 	struct bpf_prog *prog;
 	struct work_struct work;
+	atomic_t bpf_die_in_progress;
 	struct bpf_term_patch_call_sites *patch_call_sites;
 };
 
include/linux/filter.h +6 -0
index 9092d8ea95c8..4f0f8fe478bf 100644
@@ -1123,6 +1123,8 @@ int sk_get_filter(struct sock *sk, sockptr_t optval, unsigned int len);
 bool sk_filter_charge(struct sock *sk, struct sk_filter *fp);
 void sk_filter_uncharge(struct sock *sk, struct sk_filter *fp);
 
+void *bpf_termination_null_func(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5);
+int bpf_loop_term_callback(u64 reg_loop_cnt, u64 *reg_loop_ctx);
 u64 __bpf_call_base(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5);
 #define __bpf_call_base_args \
 	((u64 (*)(u64, u64, u64, u64, u64, const struct bpf_insn *)) \
@@ -1257,6 +1259,10 @@ bpf_jit_binary_pack_hdr(const struct bpf_prog *fp);
 
 void *bpf_prog_pack_alloc(u32 size, bpf_jit_fill_hole_t bpf_fill_ill_insns);
 void bpf_prog_pack_free(void *ptr, u32 size);
+void bpf_softlockup(u32 dur_s);
+void bpf_prog_termination_deferred(struct work_struct *work);
+void bpf_die(struct bpf_prog *prog);
+void in_place_patch_bpf_prog(struct bpf_prog *prog);
 
 static inline bool bpf_prog_kallsyms_verify_off(const struct bpf_prog *fp)
 {
kernel/bpf/core.c +34 -1
index 93442ab2acde..7b0552d15be3 100644
@@ -41,6 +41,7 @@
 #include <linux/execmem.h>
 
 #include <asm/barrier.h>
+#include <asm/unwind.h>
 #include <linux/unaligned.h>
 
 /* Registers */
@@ -95,6 +96,37 @@ enum page_size_enum {
 	__PAGE_SIZE = PAGE_SIZE
 };
 
+void *bpf_termination_null_func(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
+{
+	return NULL;
+}
+
+int bpf_loop_term_callback(u64 reg_loop_cnt, u64 *reg_loop_ctx)
+{
+	return 1;
+}
+
+
+void __weak in_place_patch_bpf_prog(struct bpf_prog *prog)
+{
+	return;
+}
+
+void __weak bpf_die(struct bpf_prog *prog)
+{
+	return;
+}
+
+void __weak bpf_prog_termination_deferred(struct work_struct *work)
+{
+	return;
+}
+
+void __weak bpf_softlockup(u32 dur_s)
+{
+	return;
+}
+
 struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flags)
 {
 	gfp_t gfp_flags = bpf_memcg_flags(GFP_KERNEL | __GFP_ZERO | gfp_extra_flags);
@@ -134,11 +166,12 @@ struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flag
 	fp->jit_requested = ebpf_jit_enabled();
 	fp->blinding_requested = bpf_jit_blinding_enabled(fp);
 	fp->term_states = term_states;
+	atomic_set(&fp->term_states->bpf_die_in_progress, 0);
 	fp->term_states->patch_call_sites = patch_call_sites;
 	fp->term_states->patch_call_sites->call_sites_cnt = 0;
 	fp->term_states->patch_call_sites->call_states = NULL;
 	fp->term_states->prog = fp;
-
+	INIT_WORK(&fp->term_states->work, bpf_prog_termination_deferred);
 #ifdef CONFIG_CGROUP_BPF
 	aux->cgroup_atype = CGROUP_BPF_ATTACH_TYPE_INVALID;
 #endif
kernel/watchdog.c +8 -0
index 80b56c002c7f..59c91c18ca0e 100644
@@ -25,6 +25,7 @@
 #include <linux/stop_machine.h>
 #include <linux/sysctl.h>
 #include <linux/tick.h>
+#include <linux/filter.h>
 
 #include <linux/sched/clock.h>
 #include <linux/sched/debug.h>
@@ -700,6 +701,13 @@ static int is_softlockup(unsigned long touch_ts,
 		if (time_after_eq(now, period_ts + get_softlockup_thresh() * 3 / 4))
 			scx_softlockup(now - touch_ts);
 
+		/*
+		 * Long running BPF programs can cause CPU's to stall.
+		 * So trigger fast path termination to terminate such BPF programs.
+		 */
+		if (time_after_eq(now, period_ts + get_softlockup_thresh() * 3 / 4))
+			bpf_softlockup(now - touch_ts);
+
 		/* Warn about unreasonable delays. */
 		if (time_after(now, period_ts + get_softlockup_thresh()))
 			return now - touch_ts;
Signature · 1 line
2.43.0
#6 lore raw

Re: [PATCH 3/4] bpf: runtime part of fast-path termination approach

kernel test robot noticed the following build warnings:

Hi Siddharth,

kernel test robot noticed the following build warnings:

[auto build test WARNING on bpf-next/net]
[also build test WARNING on bpf-next/master bpf/master linus/master v6.17-rc5 next-20250905] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Siddharth-Chintamaneni/bpf-Introduce-new-structs-and-struct-fields-for-fast-path-termination/20250908-070655
base:   https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git net
patch link:    https://lore.kernel.org/r/20250907230415.289327-4-sidchintamaneni%40gmail.com
patch subject: [PATCH 3/4] bpf: runtime part of fast-path termination approach
config: s390-randconfig-001-20250908 (https://download.01.org/0day-ci/archive/20250908/[email protected]/config)
compiler: clang version 22.0.0git (https://github.com/llvm/llvm-project 7fb1dc08d2f025aad5777bb779dfac1197e9ef87)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20250908/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All warnings (new ones prefixed by >>):

>> kernel/bpf/core.c:109:13: warning: no previous prototype for function 'in_place_patch_bpf_prog' [-Wmissing-prototypes]
     109 | void __weak in_place_patch_bpf_prog(struct bpf_prog *prog)
         |             ^
   kernel/bpf/core.c:109:1: note: declare 'static' if the function is not intended to be used outside of this translation unit
     109 | void __weak in_place_patch_bpf_prog(struct bpf_prog *prog)
         | ^
         | static 
>> kernel/bpf/core.c:114:13: warning: no previous prototype for function 'bpf_die' [-Wmissing-prototypes]
     114 | void __weak bpf_die(struct bpf_prog *prog)
         |             ^
   kernel/bpf/core.c:114:1: note: declare 'static' if the function is not intended to be used outside of this translation unit
     114 | void __weak bpf_die(struct bpf_prog *prog)
         | ^
         | static 
>> kernel/bpf/core.c:119:13: warning: no previous prototype for function 'bpf_prog_termination_deferred' [-Wmissing-prototypes]
     119 | void __weak bpf_prog_termination_deferred(struct work_struct *work)
         |             ^
   kernel/bpf/core.c:119:1: note: declare 'static' if the function is not intended to be used outside of this translation unit
     119 | void __weak bpf_prog_termination_deferred(struct work_struct *work)
         | ^
         | static 
>> kernel/bpf/core.c:124:13: warning: no previous prototype for function 'bpf_softlockup' [-Wmissing-prototypes]
     124 | void __weak bpf_softlockup(u32 dur_s)
         |             ^
   kernel/bpf/core.c:124:1: note: declare 'static' if the function is not intended to be used outside of this translation unit
     124 | void __weak bpf_softlockup(u32 dur_s)
         | ^
         | static 

4 warnings generated.

vim +/in_place_patch_bpf_prog +109 kernel/bpf/core.c

107
108

 > 109	void __weak in_place_patch_bpf_prog(struct bpf_prog *prog)
   110	{
   111		return;
   112	}
   113	
 > 114	void __weak bpf_die(struct bpf_prog *prog)
   115	{
   116		return;
   117	}
   118	
 > 119	void __weak bpf_prog_termination_deferred(struct work_struct *work)
   120	{
   121		return;
   122	}
   123	
 > 124	void __weak bpf_softlockup(u32 dur_s)

125 {
126 return;
127 }
128

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#7 lore raw

Re: [PATCH 3/4] bpf: runtime part of fast-path termination approach

In reply to Siddharth Chintamaneni
kernel test robot noticed the following build errors:

Hi Siddharth,

kernel test robot noticed the following build errors:

[auto build test ERROR on bpf-next/net]
[also build test ERROR on bpf-next/master bpf/master linus/master v6.17-rc5 next-20250905] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Siddharth-Chintamaneni/bpf-Introduce-new-structs-and-struct-fields-for-fast-path-termination/20250908-070655
base:   https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git net
patch link:    https://lore.kernel.org/r/20250907230415.289327-4-sidchintamaneni%40gmail.com
patch subject: [PATCH 3/4] bpf: runtime part of fast-path termination approach
config: sh-randconfig-001-20250908 (https://download.01.org/0day-ci/archive/20250908/[email protected]/config)
compiler: sh4-linux-gcc (GCC) 14.3.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20250908/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

kernel/watchdog.c: In function 'is_softlockup':

>> kernel/watchdog.c:709:25: error: implicit declaration of function 'bpf_softlockup'; did you mean 'is_softlockup'? [-Wimplicit-function-declaration]
     709 |                         bpf_softlockup(now - touch_ts);
         |                         ^~~~~~~~~~~~~~
         |                         is_softlockup

vim +709 kernel/watchdog.c

678
679 static int is_softlockup(unsigned long touch_ts,
680 unsigned long period_ts,
681 unsigned long now)
682 {
683 if ((watchdog_enabled & WATCHDOG_SOFTOCKUP_ENABLED) && watchdog_thresh) {
684 /*
685 * If period_ts has not been updated during a sample_period, then
686 * in the subsequent few sample_periods, period_ts might also not
687 * be updated, which could indicate a potential softlockup. In
688 * this case, if we suspect the cause of the potential softlockup
689 * might be interrupt storm, then we need to count the interrupts
690 * to find which interrupt is storming.
691 */
692 if (time_after_eq(now, period_ts + get_softlockup_thresh() / NUM_SAMPLE_PERIODS) &&
693 need_counting_irqs())
694 start_counting_irqs();
695
696 /*
697 * A poorly behaving BPF scheduler can live-lock the system into
698 * soft lockups. Tell sched_ext to try ejecting the BPF
699 * scheduler when close to a soft lockup.
700 */
701 if (time_after_eq(now, period_ts + get_softlockup_thresh() * 3 / 4))
702 scx_softlockup(now - touch_ts);
703
704 /*
705 * Long running BPF programs can cause CPU's to stall.
706 * So trigger fast path termination to terminate such BPF programs.
707 */
708 if (time_after_eq(now, period_ts + get_softlockup_thresh() * 3 / 4))

 > 709				bpf_softlockup(now - touch_ts);

710
711 /* Warn about unreasonable delays. */
712 if (time_after(now, period_ts + get_softlockup_thresh()))
713 return now - touch_ts;
714 }
715 return 0;
716 }
717

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#8 lore raw

Re: [PATCH 3/4] bpf: runtime part of fast-path termination approach

In reply to Siddharth Chintamaneni
Quoted 7 lines · Siddharth Chintamaneni

Update softlock detection logic to detect any stalls due to BPF programs. When softlockup is detected, bpf_die will be added to a workqueue on a CPU. With this implementation termination handler will only get triggered when CONFIG_SOFTLOCKUP_DETECTOR is enabled.

This is probably good for demonstration, but I'm not sure piggy-backing off of optional softlockup detection is a good idea. In any case, let's focus on the mechanism for now.

Quoted 6 lines

Inside bpf_die, we perform the text_poke to stub helpers/kfuncs. The current implementation handles termination of long running bpf_loop iterators both inlining and non-inlining case.

The limitation of this implementation is that the termination handler atleast need a single CPU to run.

Yeah, as discussed in v2, there were other options without this limitation, i.e. take some overhead and check a terminate bit that doesn't rely on punting work off to a wq to ensure prog is killed.

Quoted 16 lines
---
 arch/x86/net/bpf_jit_comp.c | 132 ++++++++++++++++++++++++++++++++++++
 include/linux/bpf.h         |   2 +
 include/linux/filter.h      |   6 ++
 kernel/bpf/core.c           |  35 +++++++++-
 kernel/watchdog.c           |   8 +++
 5 files changed, 182 insertions(+), 1 deletion(-)
arch/x86/net/bpf_jit_comp.c +0 -0
index 107a44729675..4de9a8cdc465 100644

arch/x86/net/bpf_jit_comp.c st: if (is_imm8(insn->off)) · line 2609

Quoted 4 lines
arch/x86/net/bpf_jit_comp.c +1 -0
@@ -2606,6 +2606,10 @@ st:                      if (is_imm8(insn->off))
                                if (arena_vm_start)
                                        pop_r12(&prog);
                        }
+                       /* emiting 5 byte nop for non-inline bpf_loop callback */

typo: emitting

arch/x86/net/bpf_jit_comp.c st: if (is_imm8(insn->off)) · line 2612

Quoted 3 lines
arch/x86/net/bpf_jit_comp.c +3 -0
+                       if (bpf_is_subprog(bpf_prog) && bpf_prog->aux->is_bpf_loop_cb_non_inline) {
+                               emit_nops(&prog, X86_PATCH_SIZE);
+                       }

But this is not the only source of potential stalls, right? E.g. bpf iterators can stall (if nested), cond_break, etc.

Quoted 80 lines
arch/x86/net/bpf_jit_comp.c +66 -0
                        EMIT1(0xC9);         /* leave */
                        emit_return(&prog, image + addrs[i - 1] + (prog - temp));
                        break;
@@ -3833,6 +3837,8 @@ bool bpf_jit_supports_private_stack(void)
        return true;
 }
 
+
+
 void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp), void *cookie)
 {
 #if defined(CONFIG_UNWINDER_ORC)
@@ -3849,6 +3855,132 @@ void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp
 #endif
 }
 
+void in_place_patch_bpf_prog(struct bpf_prog *prog)
+{
+       struct call_aux_states *call_states;
+       unsigned long new_target;
+       unsigned char *addr;
+       u8 ret_jmp_size = 1;
+       if (cpu_wants_rethunk()) {
+               ret_jmp_size = 5;
+       }
+       call_states = prog->term_states->patch_call_sites->call_states;
+       for (int i = 0; i < prog->term_states->patch_call_sites->call_sites_cnt; i++) {
+
+               new_target = (unsigned long) bpf_termination_null_func;
+               if (call_states[i].is_bpf_loop_cb_inline) {
+                       new_target = (unsigned long) bpf_loop_term_callback;
+               }
+               char new_insn[5];
+
+               addr = (unsigned char *)prog->bpf_func + call_states->jit_call_idx;
+
+               unsigned long new_rel = (unsigned long)(new_target - (unsigned long)(addr + 5));
+               new_insn[0] = 0xE8;
+               new_insn[1] = (new_rel >> 0) & 0xFF;
+               new_insn[2] = (new_rel >> 8) & 0xFF;
+               new_insn[3] = (new_rel >> 16) & 0xFF;
+               new_insn[4] = (new_rel >> 24) & 0xFF;
+
+               smp_text_poke_batch_add(addr, new_insn, 5 /* call instruction len */, NULL);
+       }
+
+       if (prog->aux->is_bpf_loop_cb_non_inline) {
+
+               char new_insn[5] = { 0xB8, 0x01, 0x00, 0x00, 0x00 };
+               char old_insn[5] = { 0x0F, 0x1F, 0x44, 0x00, 0x00 };
+               smp_text_poke_batch_add(prog->bpf_func + prog->jited_len -
+                               (1 + ret_jmp_size) /* leave, jmp/ ret */ - 5 /* nop size */, new_insn, 5 /* mov eax, 1 */, old_insn);
+       }
+
+
+       /* flush all text poke calls */
+       smp_text_poke_batch_finish();
+}
+
+void bpf_die(struct bpf_prog *prog)
+{
+       u8 ret_jmp_size = 1;
+       if (cpu_wants_rethunk()) {
+               ret_jmp_size = 5;
+       }
+
+       /*
+        * Replacing 5 byte nop in prologue with jmp instruction to ret
+        */
+       unsigned long jmp_offset = prog->jited_len - (4 /* First endbr is 4 bytes */
+                                       + 5 /* noop is 5 bytes */
+                                       + ret_jmp_size /* 5 bytes of jmp return_thunk or 1 byte ret*/);
+
+       char new_insn[5];
+       new_insn[0] = 0xE9;
+       new_insn[1] = (jmp_offset >> 0) & 0xFF;
+       new_insn[2] = (jmp_offset >> 8) & 0xFF;
+       new_insn[3] = (jmp_offset >> 16) & 0xFF;
+       new_insn[4] = (jmp_offset >> 24) & 0xFF;
+

arch/x86/net/bpf_jit_comp.c void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp · line 3931

Quoted 10 lines
arch/x86/net/bpf_jit_comp.c +10 -0
+       smp_text_poke_batch_add(prog->bpf_func + 4, new_insn, 5, NULL);
+
+       if (prog->aux->func_cnt) {
+               for (int i = 0; i < prog->aux->func_cnt; i++) {
+                       in_place_patch_bpf_prog(prog->aux->func[i]);
+               }
+       } else {
+               in_place_patch_bpf_prog(prog);
+       }
+

Are you relying on batch finish() inside in_place_patch_bpf_prog()?

Quoted 11 lines
arch/x86/net/bpf_jit_comp.c +11 -0
+}
+
+void bpf_prog_termination_deferred(struct work_struct *work)
+{
+       struct bpf_term_aux_states *term_states = container_of(work, struct bpf_term_aux_states,
+                                                work);
+       struct bpf_prog *prog = term_states->prog;
+
+       bpf_die(prog);
+}
+

arch/x86/net/bpf_jit_comp.c void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp · line 3952

Quoted 10 lines
arch/x86/net/bpf_jit_comp.c +10 -0
+static struct workqueue_struct *bpf_termination_wq;
+
+void bpf_softlockup(u32 dur_s)
+{
+       unsigned long addr;
+       struct unwind_state state;
+       struct bpf_prog *prog;
+
+       for (unwind_start(&state, current, NULL, NULL); !unwind_done(&state);
+            unwind_next_frame(&state)) {

Why not use arch_bpf_stack_walk?

Quoted 7 lines
arch/x86/net/bpf_jit_comp.c +7 -0
+               addr = unwind_get_return_address(&state);
+               if (!addr)
+                       break;
+
+               if (!is_bpf_text_address(addr))
+                       continue;
+

arch/x86/net/bpf_jit_comp.c void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp · line 3969

Quoted 10 lines
arch/x86/net/bpf_jit_comp.c +10 -0
+               rcu_read_lock();
+               prog = bpf_prog_ksym_find(addr);
+               rcu_read_unlock();
+               if (bpf_is_subprog(prog))
+                       continue;
+
+               if (atomic_cmpxchg(&prog->term_states->bpf_die_in_progress, 0, 1))
+                       break;
+
+               bpf_termination_wq = alloc_workqueue("bpf_termination_wq", WQ_UNBOUND, 1);

Err, even if you have to, I'd rather go with system_unbound_wq for now. We have bpf_wq, and should probably have a dedicated bpf wq for all wq executions coming from the BPF subsystem, but that's a discussion for later.

Quoted 154 lines
arch/x86/net/bpf_jit_comp.c +14 -0
+               if (!bpf_termination_wq)
+                       pr_err("Failed to alloc workqueue for bpf termination.\n");
+
+               queue_work(bpf_termination_wq, &prog->term_states->work);
+
+               /* Currently nested programs are not terminated together.
+                * Removing this break will result in BPF trampolines being
+                * identified as is_bpf_text_address resulting in NULL ptr
+                * deref in next step.
+                */
+               break;
+       }
+}
+
 void bpf_arch_poke_desc_update(struct bpf_jit_poke_descriptor *poke,
                               struct bpf_prog *new, struct bpf_prog *old)
 {
include/linux/bpf.h +2 -0
index caaee33744fc..03fce8f2c466 100644
@@ -71,6 +71,7 @@ typedef int (*bpf_iter_init_seq_priv_t)(void *private_data,
 typedef void (*bpf_iter_fini_seq_priv_t)(void *private_data);
 typedef unsigned int (*bpf_func_t)(const void *,
                                   const struct bpf_insn *);
+
 struct bpf_iter_seq_info {
        const struct seq_operations *seq_ops;
        bpf_iter_init_seq_priv_t init_seq_private;
@@ -1600,6 +1601,7 @@ struct bpf_term_patch_call_sites {
 struct bpf_term_aux_states {
        struct bpf_prog *prog;
        struct work_struct work;
+       atomic_t bpf_die_in_progress;
        struct bpf_term_patch_call_sites *patch_call_sites;
 };
 
include/linux/filter.h +6 -0
index 9092d8ea95c8..4f0f8fe478bf 100644
@@ -1123,6 +1123,8 @@ int sk_get_filter(struct sock *sk, sockptr_t optval, unsigned int len);
 bool sk_filter_charge(struct sock *sk, struct sk_filter *fp);
 void sk_filter_uncharge(struct sock *sk, struct sk_filter *fp);
 
+void *bpf_termination_null_func(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5);
+int bpf_loop_term_callback(u64 reg_loop_cnt, u64 *reg_loop_ctx);
 u64 __bpf_call_base(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5);
 #define __bpf_call_base_args \
        ((u64 (*)(u64, u64, u64, u64, u64, const struct bpf_insn *)) \
@@ -1257,6 +1259,10 @@ bpf_jit_binary_pack_hdr(const struct bpf_prog *fp);
 
 void *bpf_prog_pack_alloc(u32 size, bpf_jit_fill_hole_t bpf_fill_ill_insns);
 void bpf_prog_pack_free(void *ptr, u32 size);
+void bpf_softlockup(u32 dur_s);
+void bpf_prog_termination_deferred(struct work_struct *work);
+void bpf_die(struct bpf_prog *prog);
+void in_place_patch_bpf_prog(struct bpf_prog *prog);
 
 static inline bool bpf_prog_kallsyms_verify_off(const struct bpf_prog *fp)
 {
kernel/bpf/core.c +34 -1
index 93442ab2acde..7b0552d15be3 100644
@@ -41,6 +41,7 @@
 #include <linux/execmem.h>
 
 #include <asm/barrier.h>
+#include <asm/unwind.h>
 #include <linux/unaligned.h>
 
 /* Registers */
@@ -95,6 +96,37 @@ enum page_size_enum {
        __PAGE_SIZE = PAGE_SIZE
 };
 
+void *bpf_termination_null_func(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
+{
+       return NULL;
+}
+
+int bpf_loop_term_callback(u64 reg_loop_cnt, u64 *reg_loop_ctx)
+{
+       return 1;
+}
+
+
+void __weak in_place_patch_bpf_prog(struct bpf_prog *prog)
+{
+       return;
+}
+
+void __weak bpf_die(struct bpf_prog *prog)
+{
+       return;
+}
+
+void __weak bpf_prog_termination_deferred(struct work_struct *work)
+{
+       return;
+}
+
+void __weak bpf_softlockup(u32 dur_s)
+{
+       return;
+}
+
 struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flags)
 {
        gfp_t gfp_flags = bpf_memcg_flags(GFP_KERNEL | __GFP_ZERO | gfp_extra_flags);
@@ -134,11 +166,12 @@ struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flag
        fp->jit_requested = ebpf_jit_enabled();
        fp->blinding_requested = bpf_jit_blinding_enabled(fp);
        fp->term_states = term_states;
+       atomic_set(&fp->term_states->bpf_die_in_progress, 0);
        fp->term_states->patch_call_sites = patch_call_sites;
        fp->term_states->patch_call_sites->call_sites_cnt = 0;
        fp->term_states->patch_call_sites->call_states = NULL;
        fp->term_states->prog = fp;
-
+       INIT_WORK(&fp->term_states->work, bpf_prog_termination_deferred);
 #ifdef CONFIG_CGROUP_BPF
        aux->cgroup_atype = CGROUP_BPF_ATTACH_TYPE_INVALID;
 #endif
kernel/watchdog.c +8 -1
index 80b56c002c7f..59c91c18ca0e 100644
@@ -25,6 +25,7 @@
 #include <linux/stop_machine.h>
 #include <linux/sysctl.h>
 #include <linux/tick.h>
+#include <linux/filter.h>
 
 #include <linux/sched/clock.h>
 #include <linux/sched/debug.h>
@@ -700,6 +701,13 @@ static int is_softlockup(unsigned long touch_ts,
                if (time_after_eq(now, period_ts + get_softlockup_thresh() * 3 / 4))
                        scx_softlockup(now - touch_ts);
 
+               /*
+                * Long running BPF programs can cause CPU's to stall.
+                * So trigger fast path termination to terminate such BPF programs.
+                */
+               if (time_after_eq(now, period_ts + get_softlockup_thresh() * 3 / 4))
+                       bpf_softlockup(now - touch_ts);
+
                /* Warn about unreasonable delays. */
                if (time_after(now, period_ts + get_softlockup_thresh()))
                        return now - touch_ts;
--

2.43.0

#9 lore raw

Re: [PATCH 3/4] bpf: runtime part of fast-path termination approach

Quoted 19 lines · Kumar Kartikeya Dwivedi
Quoted 7 lines · Siddharth Chintamaneni

Update softlock detection logic to detect any stalls due to BPF programs. When softlockup is detected, bpf_die will be added to a workqueue on a CPU. With this implementation termination handler will only get triggered when CONFIG_SOFTLOCKUP_DETECTOR is enabled.

This is probably good for demonstration, but I'm not sure piggy-backing off of optional softlockup detection is a good idea. In any case, let's focus on the mechanism for now.

Quoted 4 lines

Inside bpf_die, we perform the text_poke to stub helpers/kfuncs. The current implementation handles termination of long running bpf_loop iterators both inlining and non-inlining case.

Quoted 7 lines
Quoted 2 lines

The limitation of this implementation is that the termination handler atleast need a single CPU to run.

Yeah, as discussed in v2, there were other options without this limitation, i.e. take some overhead and check a terminate bit that doesn't rely on punting work off to a wq to ensure prog is killed.

The termination bit approach will work, if we were able to identify predefined cancellation points in the helpers functions implementation. The current termination handler implementation can be easily ported there. We are also thinking of a termination case where if BPF programs has to run under strict execution time constraints which might not involve any long running iterators but still execution of multiple helpers can accrue the cost. In those cases, the workqueue approach could work. We will extend the current implementation to the termination bit approach in the next iteration.

Quoted 23 lines
Quoted 16 lines
---
 arch/x86/net/bpf_jit_comp.c | 132 ++++++++++++++++++++++++++++++++++++
 include/linux/bpf.h         |   2 +
 include/linux/filter.h      |   6 ++
 kernel/bpf/core.c           |  35 +++++++++-
 kernel/watchdog.c           |   8 +++
 5 files changed, 182 insertions(+), 1 deletion(-)
arch/x86/net/bpf_jit_comp.c +0 -0
index 107a44729675..4de9a8cdc465 100644

arch/x86/net/bpf_jit_comp.c st: if (is_imm8(insn->off)) · line 2609

Quoted 4 lines
arch/x86/net/bpf_jit_comp.c +1 -0
@@ -2606,6 +2606,10 @@ st:                      if (is_imm8(insn->off))
                                if (arena_vm_start)
                                        pop_r12(&prog);
                        }
+                       /* emiting 5 byte nop for non-inline bpf_loop callback */

typo: emitting

Quoted 7 lines

arch/x86/net/bpf_jit_comp.c st: if (is_imm8(insn->off)) · line 2612

Quoted 3 lines
arch/x86/net/bpf_jit_comp.c +3 -0
+                       if (bpf_is_subprog(bpf_prog) && bpf_prog->aux->is_bpf_loop_cb_non_inline) {
+                               emit_nops(&prog, X86_PATCH_SIZE);
+                       }

But this is not the only source of potential stalls, right? E.g. bpf iterators can stall (if nested), cond_break, etc.

We've just implemented it to work for bpf_loop and honestly didn't look into other iterators thinking that it should be straight forward. In the next iteration, we will extend it to the other potential stalls.

Quoted 84 lines
Quoted 84 lines
arch/x86/net/bpf_jit_comp.c +70 -0
                        EMIT1(0xC9);         /* leave */
                        emit_return(&prog, image + addrs[i - 1] + (prog - temp));
                        break;
@@ -3833,6 +3837,8 @@ bool bpf_jit_supports_private_stack(void)
        return true;
 }
 
+
+
 void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp), void *cookie)
 {
 #if defined(CONFIG_UNWINDER_ORC)
@@ -3849,6 +3855,132 @@ void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp
 #endif
 }
 
+void in_place_patch_bpf_prog(struct bpf_prog *prog)
+{
+       struct call_aux_states *call_states;
+       unsigned long new_target;
+       unsigned char *addr;
+       u8 ret_jmp_size = 1;
+       if (cpu_wants_rethunk()) {
+               ret_jmp_size = 5;
+       }
+       call_states = prog->term_states->patch_call_sites->call_states;
+       for (int i = 0; i < prog->term_states->patch_call_sites->call_sites_cnt; i++) {
+
+               new_target = (unsigned long) bpf_termination_null_func;
+               if (call_states[i].is_bpf_loop_cb_inline) {
+                       new_target = (unsigned long) bpf_loop_term_callback;
+               }
+               char new_insn[5];
+
+               addr = (unsigned char *)prog->bpf_func + call_states->jit_call_idx;
+
+               unsigned long new_rel = (unsigned long)(new_target - (unsigned long)(addr + 5));
+               new_insn[0] = 0xE8;
+               new_insn[1] = (new_rel >> 0) & 0xFF;
+               new_insn[2] = (new_rel >> 8) & 0xFF;
+               new_insn[3] = (new_rel >> 16) & 0xFF;
+               new_insn[4] = (new_rel >> 24) & 0xFF;
+
+               smp_text_poke_batch_add(addr, new_insn, 5 /* call instruction len */, NULL);
+       }
+
+       if (prog->aux->is_bpf_loop_cb_non_inline) {
+
+               char new_insn[5] = { 0xB8, 0x01, 0x00, 0x00, 0x00 };
+               char old_insn[5] = { 0x0F, 0x1F, 0x44, 0x00, 0x00 };
+               smp_text_poke_batch_add(prog->bpf_func + prog->jited_len -
+                               (1 + ret_jmp_size) /* leave, jmp/ ret */ - 5 /* nop size */, new_insn, 5 /* mov eax, 1 */, old_insn);
+       }
+
+
+       /* flush all text poke calls */
+       smp_text_poke_batch_finish();
+}
+
+void bpf_die(struct bpf_prog *prog)
+{
+       u8 ret_jmp_size = 1;
+       if (cpu_wants_rethunk()) {
+               ret_jmp_size = 5;
+       }
+
+       /*
+        * Replacing 5 byte nop in prologue with jmp instruction to ret
+        */
+       unsigned long jmp_offset = prog->jited_len - (4 /* First endbr is 4 bytes */
+                                       + 5 /* noop is 5 bytes */
+                                       + ret_jmp_size /* 5 bytes of jmp return_thunk or 1 byte ret*/);
+
+       char new_insn[5];
+       new_insn[0] = 0xE9;
+       new_insn[1] = (jmp_offset >> 0) & 0xFF;
+       new_insn[2] = (jmp_offset >> 8) & 0xFF;
+       new_insn[3] = (jmp_offset >> 16) & 0xFF;
+       new_insn[4] = (jmp_offset >> 24) & 0xFF;
+
+       smp_text_poke_batch_add(prog->bpf_func + 4, new_insn, 5, NULL);
+
+       if (prog->aux->func_cnt) {
+               for (int i = 0; i < prog->aux->func_cnt; i++) {
Quoted 8 lines

arch/x86/net/bpf_jit_comp.c void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp · line 3931

Quoted 6 lines
arch/x86/net/bpf_jit_comp.c +6 -0
+                       in_place_patch_bpf_prog(prog->aux->func[i]);
+               }
+       } else {
+               in_place_patch_bpf_prog(prog);
+       }
+

Are you relying on batch finish() inside in_place_patch_bpf_prog()?

Yes

Quoted 15 lines
Quoted 15 lines
arch/x86/net/bpf_jit_comp.c +15 -0
+}
+
+void bpf_prog_termination_deferred(struct work_struct *work)
+{
+       struct bpf_term_aux_states *term_states = container_of(work, struct bpf_term_aux_states,
+                                                work);
+       struct bpf_prog *prog = term_states->prog;
+
+       bpf_die(prog);
+}
+
+static struct workqueue_struct *bpf_termination_wq;
+
+void bpf_softlockup(u32 dur_s)
+{
Quoted 8 lines

arch/x86/net/bpf_jit_comp.c void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp · line 3952

Quoted 6 lines
arch/x86/net/bpf_jit_comp.c +6 -0
+       unsigned long addr;
+       struct unwind_state state;
+       struct bpf_prog *prog;
+
+       for (unwind_start(&state, current, NULL, NULL); !unwind_done(&state);
+            unwind_next_frame(&state)) {

Why not use arch_bpf_stack_walk?

we will reuse it, kinda overlooked it. Also we have a question, is trampoline text supposed to be identified as is_bpf_text_address?

Quoted 15 lines
Quoted 15 lines
arch/x86/net/bpf_jit_comp.c +14 -0
+               addr = unwind_get_return_address(&state);
+               if (!addr)
+                       break;
+
+               if (!is_bpf_text_address(addr))
+                       continue;
+
+               rcu_read_lock();
+               prog = bpf_prog_ksym_find(addr);
+               rcu_read_unlock();
+               if (bpf_is_subprog(prog))
+                       continue;
+
+               if (atomic_cmpxchg(&prog->term_states->bpf_die_in_progress, 0, 1))
Quoted 10 lines

arch/x86/net/bpf_jit_comp.c void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp · line 3969

Quoted 3 lines
arch/x86/net/bpf_jit_comp.c +3 -0
+                       break;
+
+               bpf_termination_wq = alloc_workqueue("bpf_termination_wq", WQ_UNBOUND, 1);

Err, even if you have to, I'd rather go with system_unbound_wq for now. We have bpf_wq, and should probably have a dedicated bpf wq for all wq executions coming from the BPF subsystem, but that's a discussion for later.

Will look into this.

<SNIP>

#10 lore raw

PATCH 4/4 selftests/bpf: Adds selftests to check termination of long running nested bpf loops

In reply to Siddharth Chintamaneni

Adds tests checks for loops termination which are nested.

32/1 bpf_termination/bpf_termination:OK
32 bpf_termination:OK
Summary: 1/1 PASSED, 0 SKIPPED, 0 FAILED

---
 .../bpf/prog_tests/bpf_termination.c          | 39 +++++++++++++++
 .../selftests/bpf/progs/bpf_termination.c     | 47 +++++++++++++++++++
 2 files changed, 86 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/bpf_termination.c
 create mode 100644 tools/testing/selftests/bpf/progs/bpf_termination.c
tools/testing/selftests/bpf/prog_tests/bpf_termination.c new file +39 -0
new file mode 100644
index 000000000000..d060073db8f9
@@ -0,0 +1,39 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <test_progs.h>
+#include <sys/socket.h>
+
+#include "bpf_termination.skel.h"
+
+void test_loop_termination(void)
+{
+	struct bpf_termination *skel;
+	int err;
+	
+	skel = bpf_termination__open();
+	if (!ASSERT_OK_PTR(skel, "bpf_termination__open"))
+	        return;
+	
+	err = bpf_termination__load(skel);
+	if (!ASSERT_OK(err, "bpf_termination__load"))
+	        goto out;
+	
+	skel->bss->pid = getpid();
+	err = bpf_termination__attach(skel);
+	if (!ASSERT_OK(err, "bpf_termination__attach"))
+	        goto out;
+	
+	/* Triggers long running BPF program */
+	socket(AF_UNSPEC, SOCK_DGRAM, 0);
+
+	/* If the program is not terminated, it doesn't reach this point */
+	ASSERT_TRUE(true, "Program is terminated");
+out:
+       bpf_termination__destroy(skel);
+}
+
+void test_bpf_termination(void)
+{
+	if (test__start_subtest("bpf_termination"))
+		test_loop_termination();
+}
tools/testing/selftests/bpf/progs/bpf_termination.c new file +47 -0

47 lines not on this page · raw message

Signature · 1 line
2.43.0
#11 lore raw
In reply to Siddharth Chintamaneni
Quoted 10 lines · Siddharth Chintamaneni

This is RFC v3 of

        https://lore.kernel.org/all/[email protected]/

The termination handler call from the softlockup detector is mainly for the demonstration of the entire workflow and also serves as a potential use case for discussion. However, the runtime mechanism is modular enough to be ported to different scenarios such as deadlocks, page faults, userspace BPF management tools, and stack overflows.

Quoted 4 lines

The main changes that we bring in this version are: We have avoided the memory overhead caused by program cloning in previous versions. During normal program execution, none of the termination logic causes any additional overhead.

I think the bit missing from the changelog is why the sampling of a terminate bit in various sources of stalls in a program was not investigated.

https://lore.kernel.org/all/CAP01T760JcsZ0o5BfKZ7pi0viseocTQCUW6KjqbxzTW7TwXF9g@mail.gmail.com/

The last time we discussed v2 the conclusion was that it was possible for all CPUs to simultaneously get stuck, such that the punting of patching to wq or other non-prog context isn't useful in making any progress.

It seems to me that the terminate bit sampling approach can apply more broadly, to cond_break, iterators, bpf_loop(), etc.

Did you investigate that approach? Was there a reason to discard it and continue with this in v3?
I am curious why you didn't look into it after the discussion in v2.

Quoted 33 lines

Change log:
v2 -> v3:
- Cloning of BPF programs has been removed.
- Created call sites table to maintain helper/ kfunc call instruction offsets.
- Termination is triggered inside the softlockup detector not affecting any fast path operations.

v1 -> v2:
- Patch generation has been moved after verification and before JIT.
- Now patch generation handles both helpers and kfuncs.
- Sanity check on original prog and patch prog after JIT.
- Runtime termination handler is now global termination mechanism using text_poke.
- Termination is triggered by watchdog timer.

 arch/x86/net/bpf_jit_comp.c                   | 141 ++++++++++++++++++
 include/linux/bpf.h                           |  77 ++++++----
 include/linux/bpf_verifier.h                  |   1 +
 include/linux/filter.h                        |   6 +
 kernel/bpf/core.c                             |  67 +++++++++
 kernel/bpf/verifier.c                         | 135 +++++++++++++++--
 kernel/watchdog.c                             |   8 +
 .../bpf/prog_tests/bpf_termination.c          |  39 +++++
 .../selftests/bpf/progs/bpf_termination.c     |  47 ++++++
 9 files changed, 482 insertions(+), 39 deletions(-)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/bpf_termination.c
 create mode 100644 tools/testing/selftests/bpf/progs/bpf_termination.c

--
2.43.0