Skip to contentSkip to conversation

LoongArch: BPF: Add private stack, exceptions, large stack and arena support

PATCH New George Guo 2 participants 8 messages Dec 1

Subsystems (4)
lore
Share & tools
lore

George Guo

author
#0 lore raw

v4 cover LoongArch: BPF: Add private stack, exceptions, large stack and arena support

From: George Guo <[email protected]>

This series adds the following features to the LoongArch BPF JIT:

- private stack
- 2 KiB of stack for programs, the same as on x86-64 and arm64
- exceptions (bpf_throw)
- sign-extending loads from arena (BPF_PROBE_MEM32SX)
- atomics on arena pointers (BPF_PROBE_ATOMIC)

The series is based on 7.4-rc5 with the following patches applied:

1. My 1 fix patch:
LoongArch: BPF: Fix the offset of stptr.w and stptr.d stores
https://lore.kernel.org/loongarch/[email protected]/

2. Tiezhu's 1 optimization patch:
LoongArch: BPF: Optimize doubleword loads with ld.d and ldptr.d
https://lore.kernel.org/loongarch/[email protected]/

3. Tiezhu's 4 feature patches:
LoongArch: BPF: Support instructions array, indirect jumps and calls
https://lore.kernel.org/loongarch/[email protected]/

"LoongArch: BPF: Allow programs 2 KiB of stack" needs the stptr fix:
stack stores beyond the signed 12-bit offset range use stptr.{w/d}.

With this series, the following tests passed on a Loongson-3C6000:

  $ sudo ./test_progs -t exceptions
  Summary: 1/119 PASSED, 0 SKIPPED, 0/0 FAILED
  $ sudo ./test_progs -a verifier_large_stack
  Summary: 1/17 PASSED, 1 SKIPPED, 0/0 FAILED
  $ sudo ./test_progs -t tailcalls
  Summary: 1/43 PASSED, 0 SKIPPED, 0/0 FAILED
  $ sudo ./test_progs -t struct_ops_private_stack
  Summary: 1/4 PASSED, 0 SKIPPED, 0/0 FAILED
  $ sudo ./test_progs -t verifier_ldsx | tail -1
  Summary: 1/24 PASSED, 0 SKIPPED, 0/0 FAILED
  $ sudo ./test_progs -t arena_atomics | tail -1
  Summary: 1/11 PASSED, 0 SKIPPED, 0/0 FAILED
  $ sudo ./test_progs -t libarena | tail -1
  Summary: 2/43 PASSED, 0 SKIPPED, 0/0 FAILED

The skipped verifier_large_stack test only runs without large stack support.

libarena also needs commit 27f2cf406a35 ("selftests/bpf: libarena: Raise arena spinlock CPU limits") from bpf-next, since CONFIG_NR_CPUS is 2048 by default on LoongArch.

The struct_ops_private_stack, arena_atomics load-acquire/store-release and libarena parallel tests, the arena tests in verifier_ldsx and the "private stack: two frames of 2048 bytes" test in verifier_large_stack are not enabled for LoongArch in mainline yet. They were enabled locally for these runs, and the selftests patches will go to bpf-next once this series is merged.

Changes since v3:
- Move "Allow programs 2 KiB of stack" before "Add support for exceptions", so that the exception frame changes are added only once in jit_save_area_size() (Tiezhu).
- Patch 3: save and restore $s7 and $s8 for the exception boundary and callback programs, since bpf_throw() skips the epilogues of the C functions it unwinds (Sashiko).
- New patch 5: consolidate the five zero-extensions of src in emit_atomic_rmw() into one, as a no-op preparation for patch 6 (Tiezhu).
- Patch 6: keep only the arena atomics changes.
- Test the arena atomics with LAMCAS and SCQ reported by the CPU under KVM, instead of forcing them on in cpu_probe_common().
- Rebase onto 7.4-rc5.

v3: https://lore.kernel.org/loongarch/[email protected]/
v2: https://lore.kernel.org/loongarch/[email protected]/

George Guo (6):
LoongArch: BPF: Add support for private stack
LoongArch: BPF: Allow programs 2 KiB of stack
LoongArch: BPF: Add support for exceptions
LoongArch: BPF: Add support for signed arena loads
LoongArch: BPF: Consolidate zero-extension in emit_atomic_rmw()
LoongArch: BPF: Add support for arena atomics

 Documentation/bpf/bpf_design_QA.rst |  13 +-
 arch/loongarch/include/asm/inst.h   |   4 +
 arch/loongarch/net/bpf_jit.c        | 421 ++++++++++++++++++++++++----
 arch/loongarch/net/bpf_jit.h        |   1 +
 4 files changed, 386 insertions(+), 53 deletions(-)

base-commit: fe6ff8d5d675c01793b9f051d16055dd4aa75244
prerequisite-patch-id: ee451ad20d651112f42e66d7ba6fa4242b124fb4
prerequisite-patch-id: 403cb992a7f660379bedce79e3068f1bc6facf05
prerequisite-patch-id: 221fa3fc56a55b9a7462ae7b21330a660240c8d2
prerequisite-patch-id: 08e033b51cefbf1d41f2e5325d591ff900ab81ef
prerequisite-patch-id: ffd6050832069f626c1f55492f0a1898137f6aa4
prerequisite-patch-id: 25f0b3ea5219dfd0676bdf22466453f2bf5dd5ea

Signature · 1 line
2.53.0
author
#1 lore raw

PATCH v4 1/6 LoongArch: BPF: Add support for private stack

From: George Guo <[email protected]>

Currently, the BPF stack of a program always lives on the kernel stack. If the JIT supports private stack, the verifier marks a deep tracing or struct_ops program with jits_use_priv_stack, so that its BPF stack can be moved into a per-CPU allocation to reduce the kernel stack pressure.

Allocate a per-CPU private stack with guard regions to detect overflow and underflow, and check the guards in bpf_jit_free(). In the prologue, use $r21 to locate the current CPU's private stack and set the BPF frame pointer, instead of allocating the BPF stack on the kernel stack.

This is similar to commit 6c17a882d380 ("bpf, arm64: JIT support for private stack").

---
 arch/loongarch/net/bpf_jit.c | 111 ++++++++++++++++++++++++++++++++++-
 arch/loongarch/net/bpf_jit.h |   1 +
 2 files changed, 109 insertions(+), 3 deletions(-)
arch/loongarch/net/bpf_jit.c +108 -3
index 567729921d6d..3ff15b64925f 100644
@@ -30,6 +30,10 @@
 #define REG_ARENA	LOONGARCH_GPR_S6 /* For storing arena_vm_start */
 #define BPF_TAIL_CALL_CNT_PTR_STACK_OFF(stack) (round_up(stack, 16) - 80)
 
+/* Memory size/value to protect private stack overflow/underflow */
+#define PRIV_STACK_GUARD_SZ	16
+#define PRIV_STACK_GUARD_VAL	0xEB9F12345678eb9fULL
+
 static const int regmap[] = {
 	/* return value from in-kernel function, and exit value for eBPF program */
 	[BPF_REG_0] = LOONGARCH_GPR_A5,
@@ -50,6 +54,15 @@ static const int regmap[] = {
 	[BPF_REG_AX] = LOONGARCH_GPR_T0,
 };
 
+static void emit_percpu_ptr(struct jit_ctx *ctx, u8 dst, void __percpu *ptr)
+{
+	move_imm(ctx, dst, (__force long)ptr);
+#ifdef CONFIG_SMP
+	/* dst += __my_cpu_offset, held in $r21 */
+	emit_insn(ctx, addd, dst, dst, LOONGARCH_GPR_U0);
+#endif
+}
+
 static void prepare_bpf_tail_call_cnt(struct jit_ctx *ctx, int *store_offset)
 {
 	const struct bpf_prog *prog = ctx->prog;
@@ -133,7 +146,14 @@ static void build_prologue(struct jit_ctx *ctx)
 		stack_adjust += sizeof(long);
 
 	stack_adjust = round_up(stack_adjust, 16);
-	stack_adjust += bpf_stack_adjust;
+
+	/*
+	 * When a private stack is used the BPF stack lives in a per-CPU
+	 * allocation rather than on the kernel stack, so only the non-BPF
+	 * part is reserved here.
+	 */
+	if (!ctx->priv_sp_used)
+		stack_adjust += bpf_stack_adjust;
 
 	/*
 	 * Save the original return address to a temporary register to prevent
@@ -188,8 +208,16 @@ static void build_prologue(struct jit_ctx *ctx)
 
 	emit_insn(ctx, addid, LOONGARCH_GPR_FP, LOONGARCH_GPR_SP, stack_adjust);
 
-	if (bpf_stack_adjust)
+	if (ctx->priv_sp_used) {
+		/* Point the BPF frame pointer at the top of this CPU's private stack */
+		void __percpu *priv_stack_ptr;
+
+		priv_stack_ptr = prog->aux->priv_stack_ptr + PRIV_STACK_GUARD_SZ;
+		emit_percpu_ptr(ctx, regmap[BPF_REG_FP], priv_stack_ptr);
+		emit_insn(ctx, addid, regmap[BPF_REG_FP], regmap[BPF_REG_FP], bpf_stack_adjust);
+	} else if (bpf_stack_adjust) {
 		emit_insn(ctx, addid, regmap[BPF_REG_FP], LOONGARCH_GPR_SP, bpf_stack_adjust);
+	}
 
 	ctx->stack_size = stack_adjust;
 
@@ -2280,6 +2308,39 @@ int arch_bpf_trampoline_size(const struct btf_func_model *m, u32 flags,
 	return ret < 0 ? ret : ret * LOONGARCH_INSN_SIZE;
 }
 
+static void priv_stack_init_guard(void __percpu *priv_stack_ptr, int alloc_size)
+{
+	int cpu, underflow_idx = (alloc_size - PRIV_STACK_GUARD_SZ) >> 3;
+	u64 *stack_ptr;
+
+	for_each_possible_cpu(cpu) {
+		stack_ptr = per_cpu_ptr(priv_stack_ptr, cpu);
+		stack_ptr[0] = PRIV_STACK_GUARD_VAL;
+		stack_ptr[1] = PRIV_STACK_GUARD_VAL;
+		stack_ptr[underflow_idx] = PRIV_STACK_GUARD_VAL;
+		stack_ptr[underflow_idx + 1] = PRIV_STACK_GUARD_VAL;
+	}
+}
+
+static void priv_stack_check_guard(void __percpu *priv_stack_ptr, int alloc_size,
+				   struct bpf_prog *prog)
+{
+	int cpu, underflow_idx = (alloc_size - PRIV_STACK_GUARD_SZ) >> 3;
+	u64 *stack_ptr;
+
+	for_each_possible_cpu(cpu) {
+		stack_ptr = per_cpu_ptr(priv_stack_ptr, cpu);
+		if (stack_ptr[0] != PRIV_STACK_GUARD_VAL ||
+		    stack_ptr[1] != PRIV_STACK_GUARD_VAL ||
+		    stack_ptr[underflow_idx] != PRIV_STACK_GUARD_VAL ||
+		    stack_ptr[underflow_idx + 1] != PRIV_STACK_GUARD_VAL) {
+			pr_err("BPF private stack overflow/underflow detected for prog %s\n",
+			       bpf_jit_get_prog_name(prog));
+			break;
+		}
+	}
+}
+
 struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_prog *prog)
 {
 	bool extra_pass = false;
@@ -2288,7 +2349,9 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 	struct jit_ctx ctx;
 	struct jit_data *jit_data;
 	struct bpf_binary_header *header;
-	struct bpf_binary_header *ro_header;
+	struct bpf_binary_header *ro_header = NULL;
+	void __percpu *priv_stack_ptr = NULL;
+	int priv_stack_alloc_sz;
 
 	/*
 	 * If BPF JIT was not enabled then we must fall back to
@@ -2304,6 +2367,22 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 			return prog;
 		prog->aux->jit_data = jit_data;
 	}
+	priv_stack_ptr = prog->aux->priv_stack_ptr;
+	if (!priv_stack_ptr && prog->aux->jits_use_priv_stack) {
+		/*
+		 * Allocate the actual private stack: the verifier-calculated
+		 * stack size plus two guard regions to detect overflow and
+		 * underflow.
+		 */
+		priv_stack_alloc_sz = round_up(prog->aux->stack_depth, 16) +
+				      2 * PRIV_STACK_GUARD_SZ;
+		priv_stack_ptr = __alloc_percpu_gfp(priv_stack_alloc_sz, 16, GFP_KERNEL);
+		if (!priv_stack_ptr)
+			goto out_priv_stack;
+
+		priv_stack_init_guard(priv_stack_ptr, priv_stack_alloc_sz);
+		prog->aux->priv_stack_ptr = priv_stack_ptr;
+	}
 	if (jit_data->ctx.offset) {
 		ctx = jit_data->ctx;
 		ro_header = jit_data->ro_header;
@@ -2321,6 +2400,7 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 		ctx.arena_vm_start = bpf_arena_get_kern_vm_start(prog->aux->arena);
 		ctx.user_vm_start = bpf_arena_get_user_vm_start(prog->aux->arena);
 	}
+	ctx.priv_sp_used = priv_stack_ptr ? true : false;
 
 	ctx.offset = kvzalloc_objs(u32, prog->len + 1);
 	if (ctx.offset == NULL)
@@ -2422,7 +2502,17 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 		bpf_prog_update_insn_ptrs(prog, ctx.offset, ctx.ro_image);
 
 out_offset:
+		/*
+		 * A NULL ro_header here means the JIT failed, so release the
+		 * private stack that was allocated above; on success the
+		 * program keeps it until bpf_jit_free().
+		 */
+		if (!ro_header && priv_stack_ptr) {
+			free_percpu(priv_stack_ptr);
+			prog->aux->priv_stack_ptr = NULL;
+		}
 		kvfree(ctx.offset);
+out_priv_stack:
 		kfree(jit_data);
 		prog->aux->jit_data = NULL;
 	}
@@ -2439,6 +2529,7 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 	if (header) {
 		bpf_arch_text_copy(&ro_header->size, &header->size, sizeof(header->size));
 		bpf_jit_binary_pack_free(ro_header, header);
+		ro_header = NULL;
 	}
 	goto out_offset;
 }
@@ -2448,6 +2539,8 @@ void bpf_jit_free(struct bpf_prog *prog)
 	if (prog->jited) {
 		struct jit_data *jit_data = prog->aux->jit_data;
 		struct bpf_binary_header *hdr;
+		void __percpu *priv_stack_ptr;
+		int priv_stack_alloc_sz;
 
 		/*
 		 * If we fail the final pass of JIT (from jit_subprogs), the
@@ -2461,6 +2554,13 @@ void bpf_jit_free(struct bpf_prog *prog)
 		}
 		hdr = bpf_jit_binary_pack_hdr(prog);
 		bpf_jit_binary_pack_free(hdr, NULL);
+		priv_stack_ptr = prog->aux->priv_stack_ptr;
+		if (priv_stack_ptr) {
+			priv_stack_alloc_sz = round_up(prog->aux->stack_depth, 16) +
+					      2 * PRIV_STACK_GUARD_SZ;
+			priv_stack_check_guard(priv_stack_ptr, priv_stack_alloc_sz, prog);
+			free_percpu(prog->aux->priv_stack_ptr);
+		}
 		WARN_ON_ONCE(!bpf_prog_kallsyms_verify_off(prog));
 	}
 
@@ -2544,6 +2644,11 @@ bool bpf_jit_supports_ptr_xchg(void)
 	return true;
 }
 
+bool bpf_jit_supports_private_stack(void)
+{
+	return true;
+}
+
 /* Indicate the JIT backend supports mixing bpf2bpf and tailcalls. */
 bool bpf_jit_supports_subprog_tailcalls(void)
 {
arch/loongarch/net/bpf_jit.h +1 -0
index 777c76112d95..bd11ca8fec53 100644
@@ -22,6 +22,7 @@ struct jit_ctx {
 	u32 stack_size;
 	u64 arena_vm_start;
 	u64 user_vm_start;
+	bool priv_sp_used;
 };
 
 struct jit_data {
Signature · 1 line
2.53.0
author
#2 lore raw

PATCH v4 2/6 LoongArch: BPF: Allow programs 2 KiB of stack

In reply to George Guo

From: George Guo <[email protected]>

Currently, the LoongArch JIT allocates the whole frame of a program with a single addi.d, and saves and restores the callee-saved registers at $sp-relative offsets computed from the whole frame size. All of these instructions take a signed 12-bit immediate, so the frame must stay below 2 KiB, otherwise emit_insn() silently truncates the offsets. The same applies to loading tcc_ptr from $sp and to adding the private stack depth to the BPF frame pointer with addi.d.

To fix this, allocate the save area and the BPF stack separately. The save area is still addressed with small offsets from $sp, and the BPF stack below it is allocated with addi.d if its size fits the immediate, otherwise with move_imm() and sub.d. The epilogue releases the BPF stack by deriving $sp from $fp before restoring the registers. tcc_ptr is at a fixed offset from $fp, so load it from $fp for tail calls, direct and indirect bpf2bpf calls. Fold the depth of a private stack into the per-CPU address of its top.

The frame layout does not change, and a program whose BPF stack is on the kernel stack gets one more instruction in both the prologue and the epilogue. Then make bpf_jit_supports_large_stack() return true to give the JITed programs the same 2 KiB budget as on x86-64 and arm64. Since LoongArch has 16 KiB kernel stacks, the worst case of a tail call chain is the same as on x86-64, a little over 10 KiB.

This is similar to commit 1d5306c11da2 ("bpf, arm64: Allow programs 2 KiB of stack").

---
 Documentation/bpf/bpf_design_QA.rst |  13 ++--
 arch/loongarch/net/bpf_jit.c        | 105 +++++++++++++++++-----------
 2 files changed, 72 insertions(+), 46 deletions(-)
Documentation/bpf/bpf_design_QA.rst +7 -6
index 98d70b8a2533..cbedc56379c3 100644
@@ -223,12 +223,13 @@ Q: How much stack space a BPF program uses?
 -------------------------------------------
 A: A program may use up to 2 KiB of stack, combined over its call
 chain, when the JIT of the architecture reports support for large
-stacks (currently x86-64 and arm64); a single function may use all of
-it, and every frame of a program running on a private stack gets the
-whole amount. Elsewhere, and for programs verified for the interpreter,
-the limit is 512 bytes; the interpreter itself never runs a frame
-larger than that. The verifier computes the actual amount of stack
-used and both interpreter and most JITed code consume necessary amount.
+stacks (currently x86-64, arm64 and LoongArch); a single function may
+use all of it, and every frame of a program running on a private stack
+gets the whole amount. Elsewhere, and for programs verified for the
+interpreter, the limit is 512 bytes; the interpreter itself never runs
+a frame larger than that. The verifier computes the actual amount of
+stack used and both interpreter and most JITed code consume necessary
+amount.
 
 Q: Can BPF be offloaded to HW?
 ------------------------------
arch/loongarch/net/bpf_jit.c +65 -40

195 lines not on this page · raw message

Signature · 1 line
2.53.0
author
#3 lore raw

PATCH v4 3/6 LoongArch: BPF: Add support for exceptions

In reply to George Guo

From: George Guo <[email protected]>

In order to implement JIT support for BPF exceptions, bpf_throw() needs to find the frame of the exception boundary program by walking the stack, and then call the exception callback with the stack pointer and frame pointer of that frame.

The stack walking is done by arch_bpf_stack_walk(), which was added by commit e7103e5e3bde ("LoongArch: BPF: Add arch_bpf_stack_walk() implementation") and only works with the ORC unwinder, so make bpf_jit_supports_exceptions() return true only if CONFIG_UNWINDER_ORC is enabled.

The exception callback does not set up a frame of its own: it takes the frame pointer of the boundary program from its third argument (a2) and reuses that frame, so its epilogue restores the callee-saved registers of the boundary program and returns to the caller of the boundary program. In order to keep the same stack layout for the boundary program and the callback, always reserve the $s6 slot for them, just like for arena programs.

bpf_throw() does not return, so the C functions it unwinds never restore the callee-saved registers they use. The JIT does not use $s7 and $s8 otherwise, but save and restore them as well for these programs, so that all callee-saved registers are restored when returning to the caller of the boundary program.

This is similar to commit 22fc0e80aeb5 ("bpf, arm64: support exceptions").

---
 arch/loongarch/net/bpf_jit.c | 82 +++++++++++++++++++++++++++++++++---
 1 file changed, 76 insertions(+), 6 deletions(-)
arch/loongarch/net/bpf_jit.c +76 -6
index eafa8e8d3e15..04b40558a859 100644
@@ -121,27 +121,45 @@ static void prepare_bpf_tail_call_cnt(struct jit_ctx *ctx, int *store_offset)
  *                            +-------------------------+
  *                            |           tcc_ptr       |
  *                            +-------------------------+
- *                            |           arena         |
- *                            |         (optional)      |
+ *                            |   $s6 (arena/exception) |
+ *                            |        (optional)       |
+ *                            +-------------------------+
+ *                            |           $s7           |
+ *                            +-------------------------+
+ *                            |           $s8           |
+ *                            |   (exception, optional) |
  *                            +-------------------------+ <--BPF_REG_FP
  *                            |  prog->aux->stack_depth |
  *                            |        (optional)       |
  * current $sp -------------> +-------------------------+
  *                                        low
  *
- * The area from $ra down to the optional arena slot is allocated on its own
+ * The area from $ra down to the optional $s8 slot is allocated on its own
  * and addressed with small offsets from $sp or $fp. The BPF stack below
  * it can be up to MAX_BPF_STACK_JIT bytes plus the may_goto slots, which
  * do not fit the 12-bit immediate of addi.d, ld.d and st.d.
  */
 static int jit_save_area_size(const struct jit_ctx *ctx)
 {
+	const struct bpf_prog *prog = ctx->prog;
+	/*
+	 * Exception boundary and callback programs must agree on the frame
+	 * layout: the callback reuses the boundary's frame to restore its
+	 * callee-saved registers, so the s6, s7 and s8 slots are always
+	 * reserved for them.
+	 */
+	const bool is_exception_prog = prog->aux->exception_boundary ||
+				       prog->aux->exception_cb;
 	/* To store ra, fp, s0, s1, s2, s3, s4, s5, tcc and tcc_ptr */
 	int size = sizeof(long) * 10;
 
-	if (ctx->arena_vm_start)
+	if (ctx->arena_vm_start || is_exception_prog)
 		size += sizeof(long);
 
+	/* To store s7 and s8 */
+	if (is_exception_prog)
+		size += sizeof(long) * 2;
+
 	return round_up(size, 16);
 }
 
@@ -150,6 +168,8 @@ static void build_prologue(struct jit_ctx *ctx)
 	int i, save_size, store_offset, bpf_stack_adjust;
 	const struct bpf_prog *prog = ctx->prog;
 	const bool is_main_prog = !bpf_is_subprog(prog);
+	const bool is_exception_prog = prog->aux->exception_boundary ||
+				       prog->aux->exception_cb;
 
 	bpf_stack_adjust = round_up(ctx->prog->aux->stack_depth, 16);
 	save_size = jit_save_area_size(ctx);
@@ -172,6 +192,19 @@ static void build_prologue(struct jit_ctx *ctx)
 	if (is_main_prog)
 		emit_insn(ctx, addid, REG_TCC, LOONGARCH_GPR_ZERO, 0);
 
+	if (prog->aux->exception_cb) {
+		/*
+		 * The exception callback receives the boundary program's frame
+		 * pointer as its third argument (a2). Reuse that frame so the
+		 * (FP-anchored) epilogue restores the boundary's callee-saved
+		 * registers and returns to the boundary's caller. The boundary
+		 * already saved them, so nothing is pushed here.
+		 */
+		move_reg(ctx, LOONGARCH_GPR_FP, LOONGARCH_GPR_A2);
+		emit_insn(ctx, addid, LOONGARCH_GPR_SP, LOONGARCH_GPR_FP, -save_size);
+		goto setup_bpf_fp;
+	}
+
 	emit_insn(ctx, addid, LOONGARCH_GPR_SP, LOONGARCH_GPR_SP, -save_size);
 
 	store_offset = save_size - sizeof(long);
@@ -200,13 +233,28 @@ static void build_prologue(struct jit_ctx *ctx)
 
 	prepare_bpf_tail_call_cnt(ctx, &store_offset);
 
-	if (ctx->arena_vm_start) {
+	if (ctx->arena_vm_start || is_exception_prog) {
 		store_offset -= sizeof(long);
 		emit_insn(ctx, std, REG_ARENA, LOONGARCH_GPR_SP, store_offset);
 	}
 
+	/*
+	 * bpf_throw() does not return, so the C functions it unwinds never
+	 * restore the callee-saved registers they use. The JIT does not use
+	 * s7 and s8, but save them here too, so the exception callback can
+	 * restore all of them before returning to the boundary's caller.
+	 */
+	if (is_exception_prog) {
+		store_offset -= sizeof(long);
+		emit_insn(ctx, std, LOONGARCH_GPR_S7, LOONGARCH_GPR_SP, store_offset);
+
+		store_offset -= sizeof(long);
+		emit_insn(ctx, std, LOONGARCH_GPR_S8, LOONGARCH_GPR_SP, store_offset);
+	}
+
 	emit_insn(ctx, addid, LOONGARCH_GPR_FP, LOONGARCH_GPR_SP, save_size);
 
+setup_bpf_fp:
 	ctx->stack_size = save_size;
 
 	if (ctx->priv_sp_used) {
@@ -242,6 +290,9 @@ static void __build_epilogue(struct jit_ctx *ctx, bool is_tail_call)
 {
 	int save_size = jit_save_area_size(ctx);
 	int load_offset;
+	const struct bpf_prog *prog = ctx->prog;
+	const bool is_exception_prog = prog->aux->exception_boundary ||
+				       prog->aux->exception_cb;
 
 	/*
 	 * Release the BPF stack, if it is on the kernel stack, by deriving
@@ -282,11 +333,19 @@ static void __build_epilogue(struct jit_ctx *ctx, bool is_tail_call)
 	/* Skip the unused local 'tcc_ptr' slot to align with arena */
 	load_offset -= sizeof(long);
 
-	if (ctx->arena_vm_start) {
+	if (ctx->arena_vm_start || is_exception_prog) {
 		load_offset -= sizeof(long);
 		emit_insn(ctx, ldd, REG_ARENA, LOONGARCH_GPR_SP, load_offset);
 	}
 
+	if (is_exception_prog) {
+		load_offset -= sizeof(long);
+		emit_insn(ctx, ldd, LOONGARCH_GPR_S7, LOONGARCH_GPR_SP, load_offset);
+
+		load_offset -= sizeof(long);
+		emit_insn(ctx, ldd, LOONGARCH_GPR_S8, LOONGARCH_GPR_SP, load_offset);
+	}
+
 	emit_insn(ctx, addid, LOONGARCH_GPR_SP, LOONGARCH_GPR_SP, save_size);
 
 	if (!is_tail_call) {
@@ -2669,6 +2728,17 @@ bool bpf_jit_supports_private_stack(void)
 	return true;
 }
 
+bool bpf_jit_supports_exceptions(void)
+{
+	/*
+	 * Walking kernel and BPF frames from within bpf_throw() relies on
+	 * arch_bpf_stack_walk(), which is only implemented for the ORC
+	 * unwinder. ORC reports each frame's stack and frame pointer and
+	 * walks JITed BPF frames via its frame-pointer fallback.
+	 */
+	return IS_ENABLED(CONFIG_UNWINDER_ORC);
+}
+
 /* Indicate the JIT backend supports mixing bpf2bpf and tailcalls. */
 bool bpf_jit_supports_subprog_tailcalls(void)
 {
Signature · 1 line
2.53.0
author
#4 lore raw

PATCH v4 4/6 LoongArch: BPF: Add support for signed arena loads

In reply to George Guo

From: George Guo <[email protected]>

Currently, the verifier rejects sign-extending loads from arena on LoongArch with "sign extending loads from arena are not supported yet", because the JIT does not implement bpf_jit_supports_insn() and the weak default returns false.

In order to support them, implement bpf_jit_supports_insn() and handle BPF_PROBE_MEM32SX like BPF_PROBE_MEM32: add the arena base held in REG_ARENA to the address, use sign-extending load instructions, and add an exception table entry for the load.

This is similar to commit b4757714cc63 ("bpf, riscv: Add support for signed arena loads").

---
 arch/loongarch/net/bpf_jit.c | 18 +++++++++++++++---
 1 file changed, 15 insertions(+), 3 deletions(-)
arch/loongarch/net/bpf_jit.c +15 -3
index 04b40558a859..423c9807a84a 100644
@@ -741,7 +741,8 @@ static int add_exception_handler(const struct bpf_insn *insn,
 
 	if (BPF_MODE(insn->code) != BPF_PROBE_MEM &&
 	    BPF_MODE(insn->code) != BPF_PROBE_MEMSX &&
-	    BPF_MODE(insn->code) != BPF_PROBE_MEM32)
+	    BPF_MODE(insn->code) != BPF_PROBE_MEM32 &&
+	    BPF_MODE(insn->code) != BPF_PROBE_MEM32SX)
 		return 0;
 
 	if (WARN_ON_ONCE(ctx->num_exentries >= ctx->prog->aux->num_exentries))
@@ -1421,10 +1422,16 @@ static int build_insn(const struct bpf_insn *insn, struct jit_ctx *ctx, bool ext
 	case BPF_LDX | BPF_PROBE_MEM32 | BPF_H:
 	case BPF_LDX | BPF_PROBE_MEM32 | BPF_W:
 	case BPF_LDX | BPF_PROBE_MEM32 | BPF_DW:
+	/* LDX | PROBE_MEM32SX: dst = *(signed size *)(src + REG_ARENA + off) */
+	case BPF_LDX | BPF_PROBE_MEM32SX | BPF_B:
+	case BPF_LDX | BPF_PROBE_MEM32SX | BPF_H:
+	case BPF_LDX | BPF_PROBE_MEM32SX | BPF_W:
 		sign_extend = BPF_MODE(code) == BPF_MEMSX ||
-			      BPF_MODE(code) == BPF_PROBE_MEMSX;
+			      BPF_MODE(code) == BPF_PROBE_MEMSX ||
+			      BPF_MODE(code) == BPF_PROBE_MEM32SX;
 
-		if (BPF_MODE(code) == BPF_PROBE_MEM32) {
+		if (BPF_MODE(code) == BPF_PROBE_MEM32 ||
+		    BPF_MODE(code) == BPF_PROBE_MEM32SX) {
 			emit_insn(ctx, addd, t2, src, REG_ARENA);
 			src = t2;
 		}
@@ -2708,6 +2715,11 @@ bool bpf_jit_supports_arena(void)
 #endif
 }
 
+bool bpf_jit_supports_insn(struct bpf_insn *insn, bool in_arena)
+{
+	return true;
+}
+
 bool bpf_jit_supports_fsession(void)
 {
 	return true;
Signature · 1 line
2.53.0
author
#5 lore raw

PATCH v4 5/6 LoongArch: BPF: Consolidate zero-extension in emit_atomic_rmw()

In reply to George Guo

From: George Guo <[email protected]>

Currently, emit_atomic_rmw() emits 'bstrpickd' right after the 32-bit fetch and xchg instructions in five places, to zero-extend the old value loaded into src.

In order to support atomics on arena, a later patch adds an exception table entry for the memory access instruction. add_exception_handler() takes the last emitted instruction as the one that can fault, so the zero-extension must come after the entry is added.

So set a zext flag in these five places instead, and emit 'bstrpickd' once after the switch statement. The emitted instructions are the same.

This is preparation for later patch, no functional changes.

---
 arch/loongarch/net/bpf_jit.c | 16 +++++++++-------
 1 file changed, 9 insertions(+), 7 deletions(-)
arch/loongarch/net/bpf_jit.c +9 -7
index 423c9807a84a..b78d38559598 100644
@@ -461,6 +461,7 @@ static int emit_atomic_rmw(const struct bpf_insn *insn, struct jit_ctx *ctx)
 	const s16 off = insn->off;
 	const s32 imm = insn->imm;
 	const bool isdw = BPF_SIZE(insn->code) == BPF_DW;
+	bool zext = false;
 
 	move_imm(ctx, t1, off);
 	emit_insn(ctx, addd, t1, dst, t1);
@@ -534,15 +535,14 @@ static int emit_atomic_rmw(const struct bpf_insn *insn, struct jit_ctx *ctx)
 			emit_insn(ctx, amadddbd, src, t1, t3);
 			break;
 		}
-		if (!isdw)
-			emit_insn(ctx, bstrpickd, src, src, 31, 0);
+		zext = !isdw;
 		break;
 	case BPF_AND | BPF_FETCH:
 		if (isdw) {
 			emit_insn(ctx, amanddbd, src, t1, t3);
 		} else {
 			emit_insn(ctx, amanddbw, src, t1, t3);
-			emit_insn(ctx, bstrpickd, src, src, 31, 0);
+			zext = true;
 		}
 		break;
 	case BPF_OR | BPF_FETCH:
@@ -550,7 +550,7 @@ static int emit_atomic_rmw(const struct bpf_insn *insn, struct jit_ctx *ctx)
 			emit_insn(ctx, amordbd, src, t1, t3);
 		} else {
 			emit_insn(ctx, amordbw, src, t1, t3);
-			emit_insn(ctx, bstrpickd, src, src, 31, 0);
+			zext = true;
 		}
 		break;
 	case BPF_XOR | BPF_FETCH:
@@ -558,7 +558,7 @@ static int emit_atomic_rmw(const struct bpf_insn *insn, struct jit_ctx *ctx)
 			emit_insn(ctx, amxordbd, src, t1, t3);
 		} else {
 			emit_insn(ctx, amxordbw, src, t1, t3);
-			emit_insn(ctx, bstrpickd, src, src, 31, 0);
+			zext = true;
 		}
 		break;
 	/* src = atomic_xchg(dst + off, src); */
@@ -585,8 +585,7 @@ static int emit_atomic_rmw(const struct bpf_insn *insn, struct jit_ctx *ctx)
 			emit_insn(ctx, amswapdbd, src, t1, t3);
 			break;
 		}
-		if (!isdw)
-			emit_insn(ctx, bstrpickd, src, src, 31, 0);
+		zext = !isdw;
 		break;
 	/* r0 = atomic_cmpxchg(dst + off, r0, src); */
 	case BPF_CMPXCHG:
@@ -614,6 +613,9 @@ static int emit_atomic_rmw(const struct bpf_insn *insn, struct jit_ctx *ctx)
 		return -EINVAL;
 	}
 
+	if (zext)
+		emit_insn(ctx, bstrpickd, src, src, 31, 0);
+
 	return 0;
 }
 
Signature · 1 line
2.53.0
author
#6 lore raw

PATCH v4 6/6 LoongArch: BPF: Add support for arena atomics

In reply to George Guo

From: George Guo <[email protected]>

In order to support the atomic instructions on arena pointers (BPF_PROBE_ATOMIC), add the arena base held in REG_ARENA to the address and add an exception table entry for the memory access instruction of read-modify-write, fetch, xchg, cmpxchg, load-acquire and store-release.

If the memory access faults, clear the register that the instruction loads into, as the verifier expects: dst_reg for load-acquire, r0 for cmpxchg and src_reg for the fetch instructions. The zero-extension of the 32-bit fetch instructions is emitted after the memory access, so the cleared register remains zero.

The ll/sc loop of cmpxchg is not suitable for arena: both ll and sc can fault if another CPU frees the page between them, but the verifier only reserves one exception table entry for each instruction. So emit a single amcas_db.{w/d} instruction for cmpxchg on arena, and make bpf_jit_supports_insn() return cpu_has_lamcas for it, just like RISC-V does with Zacas.

This is similar to commit fb7cefabae81 ("riscv, bpf: Add support arena atomics for RV64") and commit 1519f488e8ce ("bpf, riscv: Clear fetch destination on faulting arena atomic").

---
 arch/loongarch/include/asm/inst.h |   4 +
 arch/loongarch/net/bpf_jit.c      | 123 ++++++++++++++++++++++++++++--
 2 files changed, 122 insertions(+), 5 deletions(-)
arch/loongarch/include/asm/inst.h +4 -0
index e061f966f7d1..1fc99b7d70be 100644
@@ -198,6 +198,8 @@ enum reg3_op {
 	fstxs_op	= 0x7070,
 	fstxd_op	= 0x7078,
 	scq_op		= 0x70ae,
+	amcasdbw_op	= 0x70b6,
+	amcasdbd_op	= 0x70b7,
 	amswapb_op	= 0x70b8,
 	amswaph_op	= 0x70b9,
 	amaddb_op	= 0x70ba,
@@ -817,6 +819,8 @@ DEF_EMIT_REG3_FORMAT(amorw, amorw_op)
 DEF_EMIT_REG3_FORMAT(amord, amord_op)
 DEF_EMIT_REG3_FORMAT(amxorw, amxorw_op)
 DEF_EMIT_REG3_FORMAT(amxord, amxord_op)
+DEF_EMIT_REG3_FORMAT(amcasdbw, amcasdbw_op)
+DEF_EMIT_REG3_FORMAT(amcasdbd, amcasdbd_op)
 DEF_EMIT_REG3_FORMAT(amswapb, amswapb_op)
 DEF_EMIT_REG3_FORMAT(amswaph, amswaph_op)
 DEF_EMIT_REG3_FORMAT(amswapw, amswapw_op)
arch/loongarch/net/bpf_jit.c +118 -5

192 lines not on this page · raw message

Signature · 1 line
2.53.0
#7 lore raw

Re: [PATCH v4 6/6] LoongArch: BPF: Add support for arena atomics

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] loongarch: bpf: unhandled ALE fault on unaligned BPF_PROBE_ATOMIC in do_ale() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] loongarch: bpf: unhandled ALE fault on unaligned BPF_PROBE_ATOMIC in do_ale()
--

commit 816bae6b80f89e3bbb5bce679c6317c6a3a89d2d
Author: George Guo <[email protected]>

LoongArch: BPF: Add support for arena atomics

This commit adds LoongArch BPF JIT support for atomic instructions on arena pointers (BPF_PROBE_ATOMIC), including exception table registration and amcas.{w/d} emission for arena cmpxchg.

Quoted 4 lines
arch/loongarch/net/bpf_jit.c +0 -0
index b78d38559598d..abf96ed6cd649 100644

[ ... ]

Quoted 8 lines
arch/loongarch/net/bpf_jit.c +4 -0
@@ -613,8 +645,23 @@ static int emit_atomic_rmw(const struct bpf_insn *insn, struct jit_ctx *ctx)
 		return -EINVAL;
 	}
 
+	/*
+	 * On arena, the memory access is the last instruction emitted so far.
+	 * If it faults, clear the register it loads into, as the verifier
+	 * expects, and resume at the next instruction: zero-extending the

arch/loongarch/net/bpf_jit.c static int emit_atomic_rmw(const struct bpf_insn *insn, struct jit_ctx *ctx) · line 661

Quoted 10 lines
arch/loongarch/net/bpf_jit.c +10 -0
+	 * cleared register keeps it zero.
+	 */
+	if (arena) {
+		int load_reg = bpf_atomic_load_reg(insn);
+
+		ret = add_exception_handler(insn, ctx, load_reg < 0 ?
+					    REG_DONT_CLEAR_MARKER : regmap[load_reg]);
+		if (ret)
+			return ret;
+	}

[Severity: High]
Can an unaligned BPF_PROBE_ATOMIC read-modify-write access trigger a kernel Oops in do_ale() instead of recovering through ex_handler_bpf()?

check_ptr_alignment() returns 0 unconditionally for PTR_TO_ARENA, so the verifier allows unaligned arena addresses to reach the atomic instructions emitted by emit_atomic_rmw(). On LoongArch, AM* atomic instructions require natural alignment and raise EXCCODE_ALE when unaligned.

However, neither do_ale() nor emulate_load_store_insn() consults fixup_exception(regs) on kernel alignment faults:

arch/loongarch/kernel/traps.c:do_ale() {
	...
#ifndef CONFIG_ARCH_STRICT_ALIGN
	die_if_kernel("Kernel ale access", regs);
	...
}
arch/loongarch/kernel/unaligned.c:emulate_load_store_insn() {
	...
	if (!size)
		goto sigbus;
	...
sigbus:
	die_if_kernel("Unhandled kernel unaligned access", regs);
	...
}

Since AM* opcodes are not emulated in emulate_load_store_insn() (size == 0), an unaligned arena atomic RMW faults into die_if_kernel() rather than invoking the BPF exception table fixup.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6