Skip to contentSkip to conversation

bpf: Various x86-64 BPF JIT improvements

PATCH Applied Daniel Borkmann 5 participants 26 messages Oct 13 – Oct 15

Subsystems (13)
Networking Documentation x86 PowerPC +9 more subsystems
lore
Share & tools
lore

Daniel Borkmann

author maintainer
#0 lore raw

cover bpf: Various x86-64 BPF JIT improvements

This series changes the x86-64 BPF JIT to emit shorter and faster native code for the instruction patterns that LLVM-compiled programs hit in the real world. Every change stays within the lowering of a single BPF instruction, nothing is optimized across instructions. The patterns were checked against what clang's BPF backend actually emits, and the native forms follow what LLVM's own X86 backend picks for the same operations.

The last two patches carry the instruction tests of the test_bpf.ko module over to test_progs as result-checked tests which run on every JIT, add sweeps for the rewritten patterns with every register as operand, and finally remove the module given it is legacy code and the BPF selftests today are the authoritative source of truth for BPF-based testing.

To see what the series does to code that is actually deployed, the BPF objects of Cilium (7c11a349512b), Tetragon (3f20b90ee580), Katran (2cd783e43a07) and the sched_ext schedulers (the Rust ones of the scx repository at fead94e15184 plus the C examples under tools/sched_ext) were built with clang 20 and every program of them that loads (526, another 39 fail on both kernels) was loaded on two VMs run through vmtest.sh. Both kernels (before/after this series) got the same objects through the same loader; the size below is jited_prog_len from bpf_prog_get_info_by_fd(). There are no programs which got bigger in size.

File                                  Program                    Size (A)   Size (B)         Size (DIFF)
------------------------------------  ------------------------  ---------  ---------  ------------------
tetragon/bpf_prog_iter.o              iter                            157        108       -49 (-31.21%)
scx/scx_simple.bpf.o                  simple_running                   86         80        -6 (-6.98%)
scx/scx_mitosis.bpf.o                 mitosis_init_task              3362       3130      -232 (-6.90%)
scx/scx_simple.bpf.o                  simple_enqueue                  256        239       -17 (-6.64%)
cilium/bpf_host.o                     tail_drop_notify                838        786       -52 (-6.21%)
katran/xdp_pktcntr.o                  pktcntr                         179        168       -11 (-6.15%)
scx/scx_cpu0.bpf.o                    cpu0_enqueue                    328        308       -20 (-6.10%)
scx/scx_tickless.bpf.o                tickless_init                   248        233       -15 (-6.05%)
scx/scx_cosmos.bpf.o                  cosmos_init                     662        623       -39 (-5.89%)
scx/scx_userland.bpf.o                userland_init                   123        116        -7 (-5.69%)
scx/scx_lavd.bpf.o                    lavd_tick                      1798       1698      -100 (-5.56%)
scx/scx_lavd.bpf.o                    set_power_profile               471        445       -26 (-5.52%)
cilium/bpf_wireguard.o                tail_drop_notify                716        677       -39 (-5.45%)
scx/scx_layered.bpf.o                 tp_task_rename                  382        362       -20 (-5.24%)
scx/scx_lavd.bpf.o                    lavd_cgroup_exit                 59         56        -3 (-5.08%)
scx/scx_bpfland.bpf.o                 bpfland_init                   1128       1071       -57 (-5.05%)
scx/scx_simple.bpf.o                  simple_select_cpu               240        228       -12 (-5.00%)
tetragon/bpf_execve_map_update_v61.o  execve_map_update               322        306       -16 (-4.97%)

[...]

For a feel of the native code, the two loads through an untrusted pointer at the start of Tetragon's bpf_prog_iter.o iter program.

Before:

  24:	49 c7 c2 00 00 60 ff 	mov    $0xffffffffff600000,%r10
  2b:	49 89 f3             	mov    %rsi,%r11
  2e:	49 81 c3 50 00 00 00 	add    $0x50,%r11
  35:	4d 29 d3             	sub    %r10,%r11
  38:	49 ba 00 00 a0 00 00 	movabs $0x800000a00000,%r10
  3f:	80 00 00
  42:	4d 39 d3             	cmp    %r10,%r11
  45:	77 04                	ja     0x4b
  47:	31 f6                	xor    %esi,%esi
  49:	eb 04                	jmp    0x4f
  4b:	48 8b 76 50          	mov    0x50(%rsi),%rsi
  4f:	49 c7 c2 00 00 60 ff 	mov    $0xffffffffff600000,%r10

After:

  21:	4c 8d 9e 50 00 a0 00 	lea    0xa00050(%rsi),%r11
  28:	49 c1 eb 30          	shr    $0x30,%r11
  2c:	75 04                	jne    0x32
  2e:	31 f6                	xor    %esi,%esi
  30:	eb 04                	jmp    0x36
  32:	48 8b 76 50          	mov    0x50(%rsi),%rsi
  36:	4c 8d 9e 20 00 a0 00 	lea    0xa00020(%rsi),%r11

The same JITed image dumps were run through llvm-mca 20 as straight-line
code: one pass over every instruction of the image on the scheduling model of a given CPU, with the helper calls left out since llvm-mca cannot model them and they are the same on both sides. This is a static model, the path actually taken through the program, branch prediction and cache misses are not part of it, but both sides get the same program so the delta is what the series in here rewrote.

** llvm-mca -mcpu=skylake:

Project Progs Cycles (A) Cycles (B) Cycles (DIFF) uOps (A) uOps (B) uOps (DIFF)
---------- ----- ---------- ---------- ------------------ --------- --------- ------------------
cilium 156 87259 67879 -19380 (-22.21%) 256445 244684 -11761 (-4.59%)
katran 5 1213 1213 +0 (+0.00%) 3944 3944 +0 (+0.00%)

scx          275      72560      70781     -1779 (-2.45%)    133616    131221     -2395 (-1.79%)
tetragon      90      61907      61885       -22 (-0.04%)    188155    188015      -140 (-0.07%)

** llvm-mca -mcpu=icelake-server:

Project Progs Cycles (A) Cycles (B) Cycles (DIFF) uOps (A) uOps (B) uOps (DIFF)
---------- ----- ---------- ---------- ------------------ --------- --------- ------------------
cilium 156 78114 61902 -16212 (-20.75%) 256445 244684 -11761 (-4.59%)
katran 5 1149 1149 +0 (+0.00%) 3944 3944 +0 (+0.00%)

scx          275      66903      65717     -1186 (-1.77%)    133616    131221     -2395 (-1.79%)
tetragon      90      54849      54827       -22 (-0.04%)    188155    188015      -140 (-0.07%)

** llvm-mca -mcpu=alderlake:

Project Progs Cycles (A) Cycles (B) Cycles (DIFF) uOps (A) uOps (B) uOps (DIFF)
---------- ----- ---------- ---------- ------------------ --------- --------- ------------------
cilium 156 51850 50979 -871 (-1.68%) 230693 230022 -671 (-0.29%)
katran 5 1065 1063 -2 (-0.19%) 3816 3809 -7 (-0.18%)

scx          275      54339      54255       -84 (-0.15%)    102485    102317      -168 (-0.16%)
tetragon      90      43254      43225       -29 (-0.07%)    162817    162681      -136 (-0.08%)

** llvm-mca -mcpu=znver4:

Project Progs Cycles (A) Cycles (B) Cycles (DIFF) uOps (A) uOps (B) uOps (DIFF)
---------- ----- ---------- ---------- ------------------ --------- --------- ------------------
cilium 156 66985 66665 -320 (-0.48%) 274895 275648 +753 (+0.27%)
katran 5 1387 1390 +3 (+0.22%) 5188 5188 +0 (+0.00%)

scx          275     117153     116630      -523 (-0.45%)    304094    303980      -114 (-0.04%)
tetragon      90      81172      81156       -16 (-0.02%)    277077    277069        -8 (-0.00%)

On Skylake and Ice Lake class cores the modeled cycles drop by a tenth and Cilium's by a fifth: those programs divide by constants, where llvm-mca puts a 64-bit div at 32 uops and 76 cycles of latency (its Ice Lake model carries over Skylake's divider, the hardware is at about 15 cycles), and shift by a register, which is 3 uops through cl against 1 with shlx. Cilium's BPF code holds 416 such divisions in 88 of its programs, all by NSEC_PER_SEC from its monotonic clock helper, which conntrack, NAT and the load balancer run for every entry they stamp or check; Tetragon and Katran have none, the schedulers 75, mostly by 100 and 1000000. Both are cheap on Zen 4 already, so there the model stays flat at the program level, and the few programs it rates slower come from its Zen 4 model charging a 64-bit immediate move a full issue cycle where Agner measures a quarter.

Golden Cove, here the Alder Lake P model which LLVM 20 also uses for the later client cores and which gives the same numbers as its Sapphire Rapids model, has a divider at 3 uops and 18 cycles. The division drops from 24 to 10 cycles there, and the totals move by -0.66%, Cilium's by -1.68%. That model counts register moves and adds as zero uops and puts shlx at 3 cycles of latency, so it rates the shift by a register a cycle slower. The 27 programs it rates slower are 1 to 6 cycles each, at most +1.16%.

The rewrites on their own, cycles and uops of llvm-mca for one instance of each sequence in a single pass (the pipeline fill included, and for the division without the rax/rdx save and restore both sides share):

  pattern                   Skylake    Ice Lake   Alder Lake  Zen 4
  r1 /= 1000000000          81 > 10    81 > 10    24 > 10     21 > 8
    uops                    35 > 6     35 > 6     5 > 5       5 > 6
  PROBE_MEM address check   8 > 6      8 > 6      8 > 6       7 > 6
    uops                    7 > 3      7 > 3      5 > 3       7 > 3
  cast to a user address    9 > 6      9 > 6      10 > 7      8 > 6
    uops                    7 > 5      7 > 5      8 > 5       7 > 5
  shift by a register       6 > 4      6 > 4      5 > 6       4 > 4
    uops                    3 > 1      3 > 1      2 > 1       1 > 1
  multiply by 3             6 > 4      6 > 4      6 > 4       6 > 5
    uops                    1 > 1      1 > 1      1 > 1       1 > 2

16-bit swap, inc/dec, 32-bit and, test for cmp: same cycles and uops, except one uop less for the 16-bit swap on Alder Lake

Daniel Borkmann (18):
bpf, x86: Drop redundant REX prefixes from zero and sign extensions bpf, x86: Omit the displacement byte for zero offsets
bpf, x86: Shorten the stack adjusts and the tail call counter loads bpf, x86: Use shorter test and cmp encodings for immediates bpf, x86: Compare against 0, 127 and -128 with the adjusted condition bpf, x86: Use movzx for byte and word masks and a not for xor with -1 bpf, x86: Consolidate the ALU, shift and neg encodings into helpers bpf, x86: Use shorter and faster forms for some ALU immediates bpf, x86: Swap 16-bit values with bswap and shr, not ror and movzx bpf, x86: Use BMI2 shifts also when the count is in rcx bpf, x86: Fold the PROBE_MEM address computation into a lea bpf, x86: Compare the PROBE_MEM address range with a shift bpf, x86: Divide by constants via multiplication with a magic number bpf, x86: Multiply by 3, 5 and 9 with lea
bpf, x86: Use emit_sub_rsp() for the trampoline stack
bpf, x86: Shorten the cast to a user address selftests/bpf: Add JIT instruction tests
selftests/bpf: Remove the old test_bpf module

 Documentation/bpf/bpf_devel_QA.rst            |    16 +-
 Documentation/networking/filter.rst           |    15 +-
 MAINTAINERS                                   |     1 -
 arch/m68k/configs/amiga_defconfig             |     1 -
 arch/m68k/configs/apollo_defconfig            |     1 -
 arch/m68k/configs/atari_defconfig             |     1 -
 arch/m68k/configs/bvme6000_defconfig          |     1 -
 arch/m68k/configs/hp300_defconfig             |     1 -
 arch/m68k/configs/mac_defconfig               |     1 -
 arch/m68k/configs/multi_defconfig             |     1 -
 arch/m68k/configs/mvme147_defconfig           |     1 -
 arch/m68k/configs/mvme16x_defconfig           |     1 -
 arch/m68k/configs/q40_defconfig               |     1 -
 arch/m68k/configs/sun3_defconfig              |     1 -
 arch/m68k/configs/sun3x_defconfig             |     1 -
 arch/powerpc/configs/ppc64_defconfig          |     1 -
 arch/s390/configs/debug_defconfig             |     1 -
 arch/s390/configs/defconfig                   |     1 -
 arch/x86/net/bpf_jit_comp.c                   |   720 +-
 kernel/bpf/core.c                             |     4 -
 lib/Kconfig.debug                             |    13 -
 lib/Makefile                                  |     1 -
 lib/test_bpf.c                                | 15934 ----------------
 tools/bpf/bpftool/feature.c                   |     3 -
 tools/testing/selftests/bpf/Makefile          |     3 +-
 tools/testing/selftests/bpf/config            |     1 -
 .../selftests/bpf/prog_tests/jit_insns.c      |  2433 +++
 .../selftests/bpf/progs/jit_insns_arena.c     |   113 +
 tools/testing/selftests/bpf/test_kmod.sh      |    73 -
 tools/testing/selftests/net/Makefile          |     1 -
 tools/testing/selftests/net/config            |     1 -
 tools/testing/selftests/net/test_bpf.sh       |    11 -
 32 files changed, 3098 insertions(+), 16260 deletions(-)
 delete mode 100644 lib/test_bpf.c
 create mode 100644 tools/testing/selftests/bpf/prog_tests/jit_insns.c
 create mode 100644 tools/testing/selftests/bpf/progs/jit_insns_arena.c
 delete mode 100755 tools/testing/selftests/bpf/test_kmod.sh
 delete mode 100755 tools/testing/selftests/net/test_bpf.sh
Signature · 1 line
2.43.0
author maintainer
#1 lore raw

PATCH 1/18 bpf, x86: Drop redundant REX prefixes from zero and sign extensions

movzx into a 32-bit register already clears the upper 32 bits, so the REX.W prefix on the 8 and 16-bit BPF_LDX loads only costs a byte. This also matches what the arena variants of these loads emit. Likewise, the 32-bit movsx from an 8-bit register only needs a REX prefix when the destination is an extended register or the source is sil, dil, bpl or an extended register. LLVM emits these loads for u8 and u16 fields and, with cpu v4, the movsx for a cast to s8 or s16.

Before/after for r0 = *(u8 *)(r1 + 0):

48 0f b6 47 00 movzbq 0x0(%rdi),%rax
0f b6 47 00 movzbl 0x0(%rdi),%eax

Before/after for w1 = (s8)w0:

40 0f be f8 movsbl %al,%edi
0f be f8 movsbl %al,%edi

---
 arch/x86/net/bpf_jit_comp.c | 17 +++++++++++------
 1 file changed, 11 insertions(+), 6 deletions(-)
arch/x86/net/bpf_jit_comp.c +11 -6
index 083fcd6cf15b..adec4f8e422e 100644
@@ -1106,8 +1106,9 @@ static void emit_movsx_reg(u8 **pprog, int num_bits, bool is64, u32 dst_reg,
 	} else {
 		/* movs[b,w]l dst, src */
 		if (num_bits == 8) {
-			EMIT4(add_2mod(0x40, src_reg, dst_reg), 0x0f, 0xbe,
-			      add_2reg(0xC0, src_reg, dst_reg));
+			if (is_ereg(dst_reg) || is_ereg_8l(src_reg))
+				EMIT1(add_2mod(0x40, src_reg, dst_reg));
+			EMIT3(0x0f, 0xbe, add_2reg(0xC0, src_reg, dst_reg));
 		} else if (num_bits == 16) {
 			if (is_ereg(dst_reg) || is_ereg(src_reg))
 				EMIT1(add_2mod(0x40, src_reg, dst_reg));
@@ -1273,12 +1274,16 @@ static void emit_ldx(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, int off)
 
 	switch (size) {
 	case BPF_B:
-		/* Emit 'movzx rax, byte ptr [rax + off]' */
-		EMIT3(add_2mod(0x48, src_reg, dst_reg), 0x0F, 0xB6);
+		/* Emit 'movzx eax, byte ptr [rax + off]' */
+		if (is_ereg(dst_reg) || is_ereg(src_reg))
+			EMIT1(add_2mod(0x40, src_reg, dst_reg));
+		EMIT2(0x0F, 0xB6);
 		break;
 	case BPF_H:
-		/* Emit 'movzx rax, word ptr [rax + off]' */
-		EMIT3(add_2mod(0x48, src_reg, dst_reg), 0x0F, 0xB7);
+		/* Emit 'movzx eax, word ptr [rax + off]' */
+		if (is_ereg(dst_reg) || is_ereg(src_reg))
+			EMIT1(add_2mod(0x40, src_reg, dst_reg));
+		EMIT2(0x0F, 0xB7);
 		break;
 	case BPF_W:
 		/* Emit 'mov eax, dword ptr [rax+0x14]' */
Signature · 1 line
2.43.0
author maintainer
#2 lore raw

PATCH 2/18 bpf, x86: Omit the displacement byte for zero offsets

In reply to Daniel Borkmann

A memory operand with a zero offset was encoded with a mod 01 ModR/M and an explicit zero displacement byte. Use the mod 00 form instead, which saves a byte for every load, store and atomic with a zero offset, as LLVM emits them for the first field of a struct and for every plain pointer dereference. The exception are rbp and r13 as base register, where mod 00 with r/m 101 selects a RIP-relative disp32 and with SIB base 101 a disp32 without base, so these keep their displacement byte. Also let emit_st() reuse emit_insn_suffix() instead of open-coding the ModR/M encoding.

Before/after for r0 = *(u64 *)(r1 + 0):

48 8b 47 00 movq 0x0(%rdi),%rax
48 8b 07 movq (%rdi),%rax

---
 arch/x86/net/bpf_jit_comp.c | 33 ++++++++++++++++++++-------------
 1 file changed, 20 insertions(+), 13 deletions(-)
arch/x86/net/bpf_jit_comp.c +20 -13
index adec4f8e422e..70243ccbe423 100644
@@ -1120,18 +1120,26 @@ static void emit_movsx_reg(u8 **pprog, int num_bits, bool is64, u32 dst_reg,
 	*pprog = prog;
 }
 
+/*
+ * rbp and r13 as base register always need a displacement, since mod 00
+ * with r/m 101 encodes a RIP-relative disp32 and with SIB base 101 a
+ * disp32 without base instead.
+ */
+static bool base_needs_disp(u32 reg)
+{
+	return reg2hex[reg] == 5;
+}
+
 /* Emit the suffix (ModR/M etc) for addressing *(ptr_reg + off) and val_reg */
 static void emit_insn_suffix(u8 **pprog, u32 ptr_reg, u32 val_reg, int off)
 {
 	u8 *prog = *pprog;
 
-	if (is_imm8(off)) {
-		/* 1-byte signed displacement.
-		 *
-		 * If off == 0 we could skip this and save one extra byte, but
-		 * special case of x86 R13 which always needs an offset is not
-		 * worth the hassle
-		 */
+	if (!off && !base_needs_disp(ptr_reg)) {
+		/* No displacement */
+		EMIT1(add_2reg(0x00, ptr_reg, val_reg));
+	} else if (is_imm8(off)) {
+		/* 1-byte signed displacement */
 		EMIT2(add_2reg(0x40, ptr_reg, val_reg), off);
 	} else {
 		/* 4-byte signed displacement */
@@ -1144,7 +1152,10 @@ static void emit_insn_suffix_SIB(u8 **pprog, u32 ptr_reg, u32 val_reg, u32 index
 {
 	u8 *prog = *pprog;
 
-	if (is_imm8(off)) {
+	if (!off && !base_needs_disp(ptr_reg)) {
+		EMIT2(add_2reg(0x04, BPF_REG_0, val_reg),
+		      add_2reg(0, ptr_reg, index_reg) /* SIB */);
+	} else if (is_imm8(off)) {
 		EMIT3(add_2reg(0x44, BPF_REG_0, val_reg), add_2reg(0, ptr_reg, index_reg) /* SIB */, off);
 	} else {
 		EMIT2_off32(add_2reg(0x84, BPF_REG_0, val_reg), add_2reg(0, ptr_reg, index_reg) /* SIB */, off);
@@ -1507,11 +1518,7 @@ static void emit_st(u8 **pprog, struct bpf_insn *insn, u32 dst_reg,
 		break;
 	}
 
-	if (is_imm8(insn_off))
-		EMIT2(add_1reg(0x40, dst_reg), insn_off);
-	else
-		EMIT1_off32(add_1reg(0x80, dst_reg), insn_off);
-
+	emit_insn_suffix(&prog, dst_reg, BPF_REG_0, insn_off);
 	EMIT(imm32, bpf_size_to_x86_bytes(BPF_SIZE(insn->code)));
 	*pprog = prog;
 }
Signature · 1 line
2.43.0
#3 lore raw

Re: [PATCH bpf-next 02/18] bpf, x86: Omit the displacement byte for zero offsets

Quoted 5 lines · Daniel Borkmann
arch/x86/net/bpf_jit_comp.c +0 -0
@@ -1120,18 +1120,26 @@ static void emit_movsx_reg(u8 **pprog, int num_bits, bool is64, u32 dst_reg,
 static void emit_insn_suffix(u8 **pprog, u32 ptr_reg, u32 val_reg, int off)
 {
 	u8 *prog = *pprog;
 

[...]

arch/x86/net/bpf_jit_comp.c static void emit_movsx_reg(u8 **pprog, int num_bits, bool is64, u32 dst_reg, · line 1140

Quoted 3 lines
arch/x86/net/bpf_jit_comp.c +3 -0
+	if (!off && !base_needs_disp(ptr_reg)) {
+		/* No displacement */
+		EMIT1(add_2reg(0x00, ptr_reg, val_reg));

progs/verifier_jit_convergence.c depends on the size of these insns. It's the reproducer for
commit c8831bdbfbab ("bpf, x64: Fix a jit convergence issue"). The code between 'if r1 == 0x0 goto l0' and l0 is 125 bytes when the last 'goto l9' is 2 bytes and 128 when it's 5.
That's the je <-> jmp cycle.
There are three zero offset loads and stores in there,
so it's 122/125 after this patch.
'r2 += 0x1' and 'r3 &= 0x1' in patch 8 make it 120/123. je fits into imm8 either way.
The test still passes, but it doesn't test anything.
Pls add few insns to the test to get the distance back.

author maintainer
#4 lore raw

Re: [PATCH bpf-next 02/18] bpf, x86: Omit the displacement byte for zero offsets

Quoted 7 lines · Alexei Starovoitov
Quoted 5 lines · Daniel Borkmann
arch/x86/net/bpf_jit_comp.c +0 -0
@@ -1120,18 +1120,26 @@ static void emit_movsx_reg(u8 **pprog, int num_bits, bool is64, u32 dst_reg,
  static void emit_insn_suffix(u8 **pprog, u32 ptr_reg, u32 val_reg, int off)
  {
  	u8 *prog = *pprog;
 

[...]

Quoted 16 lines

arch/x86/net/bpf_jit_comp.c static void emit_movsx_reg(u8 **pprog, int num_bits, bool is64, u32 dst_reg, · line 1140

Quoted 3 lines
arch/x86/net/bpf_jit_comp.c +3 -0
+	if (!off && !base_needs_disp(ptr_reg)) {
+		/* No displacement */
+		EMIT1(add_2reg(0x00, ptr_reg, val_reg));

progs/verifier_jit_convergence.c depends on the size of these insns. It's the reproducer for
commit c8831bdbfbab ("bpf, x64: Fix a jit convergence issue"). The code between 'if r1 == 0x0 goto l0' and l0 is 125 bytes when the last 'goto l9' is 2 bytes and 128 when it's 5.
That's the je <-> jmp cycle.
There are three zero offset loads and stores in there,
so it's 122/125 after this patch.
'r2 += 0x1' and 'r3 &= 0x1' in patch 8 make it 120/123. je fits into imm8 either way.
The test still passes, but it doesn't test anything.
Pls add few insns to the test to get the distance back.

Thanks, I'll take a look to address it.

author maintainer
#5 lore raw

PATCH 3/18 bpf, x86: Shorten the stack adjusts and the tail call counter loads

In reply to Daniel Borkmann

The prologue and the tail call sequences always used the imm32 forms of sub/add rsp and a disp32 load of the tail call counter pointer, even when the rounded stack depth fits into a byte. Route them through the existing emit_sub_rsp()/emit_add_rsp() and emit_ldx() helpers which pick the short forms, and derive the ip adjustment for the counter load in front of a subprog call from the emitted length instead of hardcoding the 7 bytes. Nothing depends on the size of these instructions: the tail call entry offset covers only the code in front of the stack adjustment, and the poke targets are computed from the emitted bytes.

Before/after for a program with 32 bytes of stack:

48 81 ec 20 00 00 00 subq $0x20,%rsp
48 83 ec 20 subq $0x20,%rsp

48 8b 85 d0 ff ff ff movq -0x30(%rbp),%rax
48 8b 45 d0 movq -0x30(%rbp),%rax

---
 arch/x86/net/bpf_jit_comp.c | 27 ++++++++++++++-------------
 1 file changed, 14 insertions(+), 13 deletions(-)
arch/x86/net/bpf_jit_comp.c +14 -13
index 70243ccbe423..c6e814f7c806 100644
@@ -421,7 +421,7 @@ static void pop_callee_regs(u8 **pprog, bool *callee_regs_used)
 }
 
 /* add rsp, depth */
-static void emit_add_rsp(u8 **pprog, u16 depth)
+static void emit_add_rsp(u8 **pprog, u32 depth)
 {
 	u8 *prog = *pprog;
 
@@ -435,7 +435,7 @@ static void emit_add_rsp(u8 **pprog, u16 depth)
 }
 
 /* sub rsp, depth */
-static void emit_sub_rsp(u8 **pprog, u16 depth)
+static void emit_sub_rsp(u8 **pprog, u32 depth)
 {
 	u8 *prog = *pprog;
 
@@ -472,6 +472,7 @@ static void emit_nops(u8 **pprog, int len)
  * in arch/x86/kernel/alternative.c
  */
 static int emit_call(u8 **prog, void *func, void *ip);
+static void emit_ldx(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, int off);
 
 static void emit_fineibt(u8 **pprog, u8 *ip, u32 hash, int arity)
 {
@@ -607,8 +608,7 @@ static void emit_prologue(u8 **pprog, u8 *ip, u32 stack_depth, bool ebpf_from_cb
 	EMIT_ENDBR();
 
 	/* sub rsp, rounded_stack_depth */
-	if (stack_depth)
-		EMIT3_off32(0x48, 0x81, 0xEC, round_up(stack_depth, 8));
+	emit_sub_rsp(&prog, round_up(stack_depth, 8));
 	if (tail_call_reachable)
 		emit_prologue_tail_call(&prog, is_subprog);
 	*pprog = prog;
@@ -851,7 +851,8 @@ static void emit_bpf_tail_call_indirect(struct bpf_prog *bpf_prog,
 	 * if ((*tcc_ptr)++ >= MAX_TAIL_CALL_CNT)
 	 *	goto out;
 	 */
-	EMIT3_off32(0x48, 0x8B, 0x85, tcc_ptr_off); /* mov rax, qword ptr [rbp - tcc_ptr_off] */
+	/* mov rax, qword ptr [rbp - tcc_ptr_off] */
+	emit_ldx(&prog, BPF_DW, BPF_REG_0, BPF_REG_FP, tcc_ptr_off);
 	EMIT4(0x48, 0x83, 0x38, MAX_TAIL_CALL_CNT); /* cmp qword ptr [rax], MAX_TAIL_CALL_CNT */
 
 	offset = ctx->tail_call_indirect_label - (prog + 2 - start);
@@ -888,9 +889,7 @@ static void emit_bpf_tail_call_indirect(struct bpf_prog *bpf_prog,
 	 * Pop tail_call_cnt_ptr, if it's subprog.
 	 */
 	EMIT1(0x58);                              /* pop rax */
-	if (stack_depth)
-		EMIT3_off32(0x48, 0x81, 0xC4,     /* add rsp, sd */
-			    round_up(stack_depth, 8));
+	emit_add_rsp(&prog, round_up(stack_depth, 8)); /* add rsp, sd */
 
 	/* goto *(prog->bpf_func + X86_TAIL_CALL_OFFSET); */
 	EMIT4(0x48, 0x8B, 0x49,                   /* mov rcx, qword ptr [rcx + 32] */
@@ -923,7 +922,8 @@ static void emit_bpf_tail_call_direct(struct bpf_prog *bpf_prog,
 	 * if ((*tcc_ptr)++ >= MAX_TAIL_CALL_CNT)
 	 *	goto out;
 	 */
-	EMIT3_off32(0x48, 0x8B, 0x85, tcc_ptr_off);   /* mov rax, qword ptr [rbp - tcc_ptr_off] */
+	/* mov rax, qword ptr [rbp - tcc_ptr_off] */
+	emit_ldx(&prog, BPF_DW, BPF_REG_0, BPF_REG_FP, tcc_ptr_off);
 	EMIT4(0x48, 0x83, 0x38, MAX_TAIL_CALL_CNT);   /* cmp qword ptr [rax], MAX_TAIL_CALL_CNT */
 
 	offset = ctx->tail_call_direct_label - (prog + 2 - start);
@@ -955,8 +955,7 @@ static void emit_bpf_tail_call_direct(struct bpf_prog *bpf_prog,
 	 * Pop tail_call_cnt_ptr, if it's subprog.
 	 */
 	EMIT1(0x58);                                  /* pop rax */
-	if (stack_depth)
-		EMIT3_off32(0x48, 0x81, 0xC4, round_up(stack_depth, 8));
+	emit_add_rsp(&prog, round_up(stack_depth, 8));
 
 	emit_nops(&prog, X86_PATCH_SIZE);
 
@@ -1857,7 +1856,7 @@ static void emit_priv_frame_ptr(u8 **pprog, void __percpu *priv_frame_ptr)
 #define INSN_SZ_DIFF (((addrs[i] - addrs[i - 1]) - (prog - temp)))
 
 #define __LOAD_TCC_PTR(off)			\
-	EMIT3_off32(0x48, 0x8B, 0x85, off)
+	emit_ldx(&prog, BPF_DW, BPF_REG_0, BPF_REG_FP, off)
 /* mov rax, qword ptr [rbp - rounded_stack_depth - 16] */
 #define LOAD_TAIL_CALL_CNT_PTR(stack)				\
 	__LOAD_TCC_PTR(BPF_TAIL_CALL_CNT_PTR_STACK_OFF(stack))
@@ -2958,8 +2957,10 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 
 			func = (u8 *) __bpf_call_base + imm32;
 			if (src_reg == BPF_PSEUDO_CALL && tail_call_reachable) {
+				u8 *tcc_load = prog;
+
 				LOAD_TAIL_CALL_CNT_PTR(stack_depth);
-				ip += 7;
+				ip += prog - tcc_load;
 			}
 			if (!imm32)
 				return -EINVAL;
Signature · 1 line
2.43.0
author maintainer
#6 lore raw

PATCH 4/18 bpf, x86: Use shorter test and cmp encodings for immediates

In reply to Daniel Borkmann

test has no sign-extended imm8 form, so a JSET against a constant was always emitted as a 6 to 7 byte test with imm32. When the mask fits into the low byte, the result only depends on that byte, so test the 8-bit register instead, which takes 2 to 4 bytes. Reading the low byte of a register that was written as a whole has no partial register penalty on Intel or AMD cores. Also use the one byte shorter accumulator forms of test and cmp with imm32 when the destination is r0, like the ALU immediates already do.

Before/after for if r1 & 0x40 goto ...:

48 f7 c7 40 00 00 00 testq $0x40,%rdi
40 f6 c7 40 testb $0x40,%dil

Before/after for if r0 == 0x1000 goto ...:

48 81 f8 00 10 00 00 cmpq $0x1000,%rax
48 3d 00 10 00 00 cmpq $0x1000,%rax

---
 arch/x86/net/bpf_jit_comp.c | 20 +++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)
arch/x86/net/bpf_jit_comp.c +19 -1
index c6e814f7c806..079703c173a5 100644
@@ -3080,10 +3080,26 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 
 		case BPF_JMP | BPF_JSET | BPF_K:
 		case BPF_JMP32 | BPF_JSET | BPF_K:
+			if ((u32)imm32 <= U8_MAX) {
+				/*
+				 * test dst_reg8, imm8: with the upper bits of the
+				 * mask clear the result only depends on the low byte.
+				 */
+				if (is_ereg_8l(dst_reg))
+					EMIT1(add_1mod(0x40, dst_reg));
+				if (is_axreg(dst_reg))
+					EMIT2(0xA8, imm32);
+				else
+					EMIT3(0xF6, add_1reg(0xC0, dst_reg), imm32);
+				goto emit_cond_jmp;
+			}
 			/* test dst_reg, imm32 */
 			maybe_emit_1mod(&prog, dst_reg,
 					BPF_CLASS(insn->code) == BPF_JMP);
-			EMIT2_off32(0xF7, add_1reg(0xC0, dst_reg), imm32);
+			if (is_axreg(dst_reg))
+				EMIT1_off32(0xA9, imm32);
+			else
+				EMIT2_off32(0xF7, add_1reg(0xC0, dst_reg), imm32);
 			goto emit_cond_jmp;
 
 		case BPF_JMP | BPF_JEQ | BPF_K:
@@ -3120,6 +3136,8 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 
 			if (is_imm8(imm32))
 				EMIT3(0x83, add_1reg(0xF8, dst_reg), imm32);
+			else if (is_axreg(dst_reg))
+				EMIT1_off32(0x3D, imm32);
 			else
 				EMIT2_off32(0x81, add_1reg(0xF8, dst_reg), imm32);
 
Signature · 1 line
2.43.0
author maintainer
#7 lore raw

PATCH 5/18 bpf, x86: Compare against 0, 127 and -128 with the adjusted condition

In reply to Daniel Borkmann

A strict compare against 1 or 128 is the non-strict compare against 0 or 127, and a strict compare against -129 or, with a signed condition, -1 the non-strict compare against -128 or 0. LLVM canonicalizes x <= 0 to x < 1, x >= 0 to x > -1 and x <= 127 to x < 128, so these reach the JIT as compares against 1, -1 and 128. Adjust the condition and the immediate, so that the compare against 0 becomes the test without an immediate already emitted for it and 127 and -128 fit into an imm8.

Before, for if r1 s> -1 goto ... and if r1 < 128 goto ...:

  48 83 ff ff           cmpq $-0x1,%rdi
  7f xx                 jg ...
  48 81 ff 80 00 00 00  cmpq $0x80,%rdi
  72 xx                 jb ...

After:

  48 85 ff              testq %rdi,%rdi
  7d xx                 jge ...
  48 83 ff 7f           cmpq $0x7f,%rdi
  76 xx                 jbe ...
---
 arch/x86/net/bpf_jit_comp.c | 65 +++++++++++++++++++++++++++++++++----
 1 file changed, 59 insertions(+), 6 deletions(-)
arch/x86/net/bpf_jit_comp.c +59 -6
index 079703c173a5..70473cd43aa8 100644
@@ -2011,6 +2011,54 @@ static int emit_kfunc_arena_args(struct bpf_prog *bpf_prog,
 	return prog - start;
 }
 
+/*
+ * A strict compare against 1 or 128 is the non-strict one against 0 or
+ * 127, a strict one against -129 or, with a signed condition, -1 the
+ * non-strict one against -128 or 0: the compare against 0 is a test
+ * without immediate, 127 and -128 fit into an imm8.
+ */
+static void adjust_cmp_imm(u32 *op, s32 *imm)
+{
+	if (*imm == 1 || *imm == 128) {
+		switch (*op) {
+		case BPF_JLT:
+			*op = BPF_JLE;
+			break;
+		case BPF_JGE:
+			*op = BPF_JGT;
+			break;
+		case BPF_JSLT:
+			*op = BPF_JSLE;
+			break;
+		case BPF_JSGE:
+			*op = BPF_JSGT;
+			break;
+		default:
+			return;
+		}
+		*imm -= 1;
+	} else if (*imm == -1 || *imm == -129) {
+		switch (*op) {
+		case BPF_JGT:
+		case BPF_JLE:
+			/* -1 is the largest unsigned value */
+			if (*imm == -1)
+				return;
+			*op = *op == BPF_JGT ? BPF_JGE : BPF_JLT;
+			break;
+		case BPF_JSGT:
+			*op = BPF_JSGE;
+			break;
+		case BPF_JSLE:
+			*op = BPF_JSLT;
+			break;
+		default:
+			return;
+		}
+		*imm += 1;
+	}
+}
+
 static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *addrs, u8 *image,
 		  u8 *rw_image, int oldproglen, struct jit_context *ctx, bool jmp_padding)
 {
@@ -2153,6 +2201,8 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 		u8 jmp_cond;
 		u8 *func;
 		int nops;
+		u32 jmp_op = BPF_OP(insn->code);
+		s32 cmp_imm;
 
 		if (priv_frame_ptr) {
 			if (src_reg == BPF_REG_FP)
@@ -3122,8 +3172,11 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 		case BPF_JMP32 | BPF_JSLT | BPF_K:
 		case BPF_JMP32 | BPF_JSGE | BPF_K:
 		case BPF_JMP32 | BPF_JSLE | BPF_K:
+			cmp_imm = imm32;
+			adjust_cmp_imm(&jmp_op, &cmp_imm);
+
 			/* test dst_reg, dst_reg to save one extra byte */
-			if (imm32 == 0) {
+			if (cmp_imm == 0) {
 				maybe_emit_mod(&prog, dst_reg, dst_reg,
 					       BPF_CLASS(insn->code) == BPF_JMP);
 				EMIT2(0x85, add_2reg(0xC0, dst_reg, dst_reg));
@@ -3134,15 +3187,15 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 			maybe_emit_1mod(&prog, dst_reg,
 					BPF_CLASS(insn->code) == BPF_JMP);
 
-			if (is_imm8(imm32))
-				EMIT3(0x83, add_1reg(0xF8, dst_reg), imm32);
+			if (is_imm8(cmp_imm))
+				EMIT3(0x83, add_1reg(0xF8, dst_reg), cmp_imm);
 			else if (is_axreg(dst_reg))
-				EMIT1_off32(0x3D, imm32);
+				EMIT1_off32(0x3D, cmp_imm);
 			else
-				EMIT2_off32(0x81, add_1reg(0xF8, dst_reg), imm32);
+				EMIT2_off32(0x81, add_1reg(0xF8, dst_reg), cmp_imm);
 
 emit_cond_jmp:		/* Convert BPF opcode to x86 */
-			switch (BPF_OP(insn->code)) {
+			switch (jmp_op) {
 			case BPF_JEQ:
 				jmp_cond = X86_JE;
 				break;
Signature · 1 line
2.43.0
author maintainer
#8 lore raw

PATCH 6/18 bpf, x86: Use movzx for byte and word masks and a not for xor with -1

In reply to Daniel Borkmann

LLVM lowers u8 and u16 truncations to r &= 0xff and r &= 0xffff, and a bitwise not to r ^= -1, since BPF has neither a zero extending move from a sub-register nor a not instruction. On x86 these masks need the imm32 form of and as they do not fit into a sign-extended imm8. Emit a movzx from the low byte or word instead, which is 3 to 4 bytes and zero extends into the full register for both the 32 and 64-bit variant, and a not for the xor with -1. Both are single cycle instructions on Intel and AMD cores.

Before/after for r1 &= 0xff, r1 &= 0xffff and r1 ^= -1:

48 81 e7 ff 00 00 00 andq $0xff,%rdi
40 0f b6 ff movzbl %dil,%edi

48 81 e7 ff ff 00 00 andq $0xffff,%rdi
0f b7 ff movzwl %di,%edi

48 83 f7 ff xorq $-1,%rdi
48 f7 d7 notq %rdi

---
 arch/x86/net/bpf_jit_comp.c | 35 ++++++++++++++++++++++++++++++-----
 1 file changed, 30 insertions(+), 5 deletions(-)
arch/x86/net/bpf_jit_comp.c +30 -5
index 70473cd43aa8..e7439fb5037d 100644
@@ -1129,6 +1129,20 @@ static bool base_needs_disp(u32 reg)
 	return reg2hex[reg] == 5;
 }
 
+static void emit_movzx_reg(u8 **pprog, int num_bits, u32 dst_reg, u32 src_reg)
+{
+	u8 *prog = *pprog;
+
+	/* movz[b,w]l dst, src */
+	if (is_ereg(dst_reg) ||
+	    (num_bits == 8 ? is_ereg_8l(src_reg) : is_ereg(src_reg)))
+		EMIT1(add_2mod(0x40, src_reg, dst_reg));
+	EMIT3(0x0F, num_bits == 8 ? 0xB6 : 0xB7,
+	      add_2reg(0xC0, src_reg, dst_reg));
+
+	*pprog = prog;
+}
+
 /* Emit the suffix (ModR/M etc) for addressing *(ptr_reg + off) and val_reg */
 static void emit_insn_suffix(u8 **pprog, u32 ptr_reg, u32 val_reg, int off)
 {
@@ -2312,6 +2326,21 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 		case BPF_ALU64 | BPF_AND | BPF_K:
 		case BPF_ALU64 | BPF_OR | BPF_K:
 		case BPF_ALU64 | BPF_XOR | BPF_K:
+			if (BPF_OP(insn->code) == BPF_AND &&
+			    (imm32 == 0xff || imm32 == 0xffff)) {
+				/* movzx dst_reg, dst_reg8/16 */
+				emit_movzx_reg(&prog, imm32 == 0xff ? 8 : 16,
+					       dst_reg, dst_reg);
+				break;
+			}
+			if (BPF_OP(insn->code) == BPF_XOR && imm32 == -1) {
+				/* not dst_reg */
+				maybe_emit_1mod(&prog, dst_reg,
+						BPF_CLASS(insn->code) == BPF_ALU64);
+				EMIT2(0xF7, add_1reg(0xD0, dst_reg));
+				break;
+			}
+
 			maybe_emit_1mod(&prog, dst_reg,
 					BPF_CLASS(insn->code) == BPF_ALU64);
 
@@ -2573,11 +2602,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 				 * Emit 'movzwl eax, ax' to zero extend 16-bit
 				 * into 64 bit
 				 */
-				if (is_ereg(dst_reg))
-					EMIT3(0x45, 0x0F, 0xB7);
-				else
-					EMIT2(0x0F, 0xB7);
-				EMIT1(add_2reg(0xC0, dst_reg, dst_reg));
+				emit_movzx_reg(&prog, 16, dst_reg, dst_reg);
 				break;
 			case 32:
 				/* Emit 'mov eax, eax' to clear upper 32-bits */
Signature · 1 line
2.43.0
author maintainer
#9 lore raw

PATCH 7/18 bpf, x86: Consolidate the ALU, shift and neg encodings into helpers

In reply to Daniel Borkmann

The add, sub, and, or and xor with an immediate or a register, the shifts by an immediate and neg are open coded in the ALU cases of do_jit(), the add with an immediate once more in the tail call and KASAN check sequences. Add emit_alu_imm(), emit_alu_reg(), emit_shift_imm() and emit_neg() for them and use them there, together with emit_mov_reg(), emit_mov_imm32() and emit_add_rsp() for the open coded moves and stack adjustment in the tail call, the division and the trampoline. The emitted code is unchanged.

---
 arch/x86/net/bpf_jit_comp.c | 144 +++++++++++++++++++-----------------
 1 file changed, 78 insertions(+), 66 deletions(-)
arch/x86/net/bpf_jit_comp.c +78 -66
index e7439fb5037d..3e367600a0ad 100644
@@ -473,6 +473,8 @@ static void emit_nops(u8 **pprog, int len)
  */
 static int emit_call(u8 **prog, void *func, void *ip);
 static void emit_ldx(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, int off);
+static void emit_mov_reg(u8 **pprog, bool is64, u32 dst_reg, u32 src_reg);
+static void emit_alu_imm(u8 **pprog, u32 op, u32 dst_reg, s32 imm, bool is64);
 
 static void emit_fineibt(u8 **pprog, u8 *ip, u32 hash, int arity)
 {
@@ -840,7 +842,7 @@ static void emit_bpf_tail_call_indirect(struct bpf_prog *bpf_prog,
 	 * if (index >= array->map.max_entries)
 	 *	goto out;
 	 */
-	EMIT2(0x89, 0xD2);                        /* mov edx, edx */
+	emit_mov_reg(&prog, false, BPF_REG_3, BPF_REG_3); /* mov edx, edx */
 	EMIT3(0x39, 0x56,                         /* cmp dword ptr [rsi + 16], edx */
 	      offsetof(struct bpf_array, map.max_entries));
 
@@ -894,8 +896,8 @@ static void emit_bpf_tail_call_indirect(struct bpf_prog *bpf_prog,
 	/* goto *(prog->bpf_func + X86_TAIL_CALL_OFFSET); */
 	EMIT4(0x48, 0x8B, 0x49,                   /* mov rcx, qword ptr [rcx + 32] */
 	      offsetof(struct bpf_prog, bpf_func));
-	EMIT4(0x48, 0x83, 0xC1,                   /* add rcx, X86_TAIL_CALL_OFFSET */
-	      X86_TAIL_CALL_OFFSET);
+	/* add rcx, X86_TAIL_CALL_OFFSET */
+	emit_alu_imm(&prog, BPF_ADD, BPF_REG_4, X86_TAIL_CALL_OFFSET, true);
 	/*
 	 * Now we're ready to jump into next BPF program
 	 * rdi == ctx (1st arg)
@@ -1204,6 +1206,67 @@ static void maybe_emit_1mod(u8 **pprog, u32 reg, bool is64)
 	*pprog = prog;
 }
 
+/* add/sub/and/or/xor dst_reg, imm with the imm8 and the rax short forms */
+static void emit_alu_imm(u8 **pprog, u32 op, u32 dst_reg, s32 imm, bool is64)
+{
+	/* ModR/M opcode extension and rax short form per operation */
+	static const u8 modrm[] = {
+		[BPF_ADD] = 0xC0, [BPF_SUB] = 0xE8, [BPF_AND] = 0xE0,
+		[BPF_OR] = 0xC8, [BPF_XOR] = 0xF0,
+	};
+	static const u8 short_op[] = {
+		[BPF_ADD] = 0x05, [BPF_SUB] = 0x2D, [BPF_AND] = 0x25,
+		[BPF_OR] = 0x0D, [BPF_XOR] = 0x35,
+	};
+	u8 *prog = *pprog;
+
+	maybe_emit_1mod(&prog, dst_reg, is64);
+	if (is_imm8(imm))
+		EMIT3(0x83, add_1reg(modrm[op], dst_reg), imm);
+	else if (is_axreg(dst_reg))
+		EMIT1_off32(short_op[op], imm);
+	else
+		EMIT2_off32(0x81, add_1reg(modrm[op], dst_reg), imm);
+
+	*pprog = prog;
+}
+
+/* add/sub/and/or/xor dst_reg, src_reg */
+static void emit_alu_reg(u8 **pprog, u32 op, u32 dst_reg, u32 src_reg, bool is64)
+{
+	u8 *prog = *pprog;
+
+	maybe_emit_mod(&prog, dst_reg, src_reg, is64);
+	EMIT2(simple_alu_opcodes[op], add_2reg(0xC0, dst_reg, src_reg));
+
+	*pprog = prog;
+}
+
+/* shl/shr/sar reg, imm */
+static void emit_shift_imm(u8 **pprog, u32 op, u32 reg, u8 imm, bool is64)
+{
+	u8 *prog = *pprog;
+
+	maybe_emit_1mod(&prog, reg, is64);
+	if (imm == 1)
+		EMIT2(0xD1, add_1reg(simple_alu_opcodes[op], reg));
+	else
+		EMIT3(0xC1, add_1reg(simple_alu_opcodes[op], reg), imm);
+
+	*pprog = prog;
+}
+
+/* neg dst_reg */
+static void emit_neg(u8 **pprog, u32 dst_reg, bool is64)
+{
+	u8 *prog = *pprog;
+
+	maybe_emit_1mod(&prog, dst_reg, is64);
+	EMIT2(0xF7, add_1reg(0xD8, dst_reg));
+
+	*pprog = prog;
+}
+
 static int emit_kasan_check(struct bpf_verifier_env *env, u8 **pprog,
 			    u32 addr_reg, s32 off, u32 bpf_size, u8 *ip,
 			    bool is_write)
@@ -1258,15 +1321,8 @@ static int emit_kasan_check(struct bpf_verifier_env *env, u8 **pprog,
 	EMIT_mov(BPF_REG_1, addr_reg);
 
 	/* add rdi, off (if offset is non-zero) */
-	if (off) {
-		if (is_imm8(off)) {
-			/* add rdi, imm8 */
-			EMIT4(0x48, 0x83, 0xC7, (u8)off);
-		} else {
-			/* add rdi, imm32 */
-			EMIT3_off32(0x48, 0x81, 0xC7, off);
-		}
-	}
+	if (off)
+		emit_alu_imm(&prog, BPF_ADD, BPF_REG_1, off, true);
 
 	/* Adjust ip to account for the instrumentation generated so far */
 	ip += (prog - *pprog);
@@ -2207,7 +2263,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 		u32 dst_reg = insn->dst_reg;
 		u32 src_reg = insn->src_reg;
 		bool accesses_stack_only;
-		u8 b2 = 0, b3 = 0;
+		u8 b3 = 0;
 		u8 *start_of_ldx;
 		s64 jmp_offset;
 		s32 insn_off;
@@ -2247,10 +2303,8 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 		case BPF_ALU64 | BPF_AND | BPF_X:
 		case BPF_ALU64 | BPF_OR | BPF_X:
 		case BPF_ALU64 | BPF_XOR | BPF_X:
-			maybe_emit_mod(&prog, dst_reg, src_reg,
-				       BPF_CLASS(insn->code) == BPF_ALU64);
-			b2 = simple_alu_opcodes[BPF_OP(insn->code)];
-			EMIT2(b2, add_2reg(0xC0, dst_reg, src_reg));
+			emit_alu_reg(&prog, BPF_OP(insn->code), dst_reg, src_reg,
+				     BPF_CLASS(insn->code) == BPF_ALU64);
 			break;
 
 		case BPF_ALU64 | BPF_MOV | BPF_X:
@@ -2311,9 +2365,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 			/* neg dst */
 		case BPF_ALU | BPF_NEG:
 		case BPF_ALU64 | BPF_NEG:
-			maybe_emit_1mod(&prog, dst_reg,
-					BPF_CLASS(insn->code) == BPF_ALU64);
-			EMIT2(0xF7, add_1reg(0xD8, dst_reg));
+			emit_neg(&prog, dst_reg, BPF_CLASS(insn->code) == BPF_ALU64);
 			break;
 
 		case BPF_ALU | BPF_ADD | BPF_K:
@@ -2341,42 +2393,8 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 				break;
 			}
 
-			maybe_emit_1mod(&prog, dst_reg,
-					BPF_CLASS(insn->code) == BPF_ALU64);
-
-			/*
-			 * b3 holds 'normal' opcode, b2 short form only valid
-			 * in case dst is eax/rax.
-			 */
-			switch (BPF_OP(insn->code)) {
-			case BPF_ADD:
-				b3 = 0xC0;
-				b2 = 0x05;
-				break;
-			case BPF_SUB:
-				b3 = 0xE8;
-				b2 = 0x2D;
-				break;
-			case BPF_AND:
-				b3 = 0xE0;
-				b2 = 0x25;
-				break;
-			case BPF_OR:
-				b3 = 0xC8;
-				b2 = 0x0D;
-				break;
-			case BPF_XOR:
-				b3 = 0xF0;
-				b2 = 0x35;
-				break;
-			}
-
-			if (is_imm8(imm32))
-				EMIT3(0x83, add_1reg(b3, dst_reg), imm32);
-			else if (is_axreg(dst_reg))
-				EMIT1_off32(b2, imm32);
-			else
-				EMIT2_off32(0x81, add_1reg(b3, dst_reg), imm32);
+			emit_alu_imm(&prog, BPF_OP(insn->code), dst_reg, imm32,
+				     BPF_CLASS(insn->code) == BPF_ALU64);
 			break;
 
 		case BPF_ALU64 | BPF_MOV | BPF_K:
@@ -2429,7 +2447,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 				 * xor edx, edx
 				 * equivalent to 'xor rdx, rdx', but one byte less
 				 */
-				EMIT2(0x31, 0xd2);
+				emit_mov_imm32(&prog, false, BPF_REG_3, 0);
 
 				/* div src_reg */
 				maybe_emit_1mod(&prog, src_reg, is64);
@@ -2493,14 +2511,8 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 		case BPF_ALU64 | BPF_LSH | BPF_K:
 		case BPF_ALU64 | BPF_RSH | BPF_K:
 		case BPF_ALU64 | BPF_ARSH | BPF_K:
-			maybe_emit_1mod(&prog, dst_reg,
-					BPF_CLASS(insn->code) == BPF_ALU64);
-
-			b3 = simple_alu_opcodes[BPF_OP(insn->code)];
-			if (imm32 == 1)
-				EMIT2(0xD1, add_1reg(b3, dst_reg));
-			else
-				EMIT3(0xC1, add_1reg(b3, dst_reg), imm32);
+			emit_shift_imm(&prog, BPF_OP(insn->code), dst_reg,
+				       imm32, BPF_CLASS(insn->code) == BPF_ALU64);
 			break;
 
 		case BPF_ALU | BPF_LSH | BPF_X:
@@ -4206,7 +4218,7 @@ static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_im
 
 	if (flags & BPF_TRAMP_F_SKIP_FRAME) {
 		/* skip our return address and return to parent */
-		EMIT4(0x48, 0x83, 0xC4, 8); /* add rsp, 8 */
+		emit_add_rsp(&prog, 8); /* add rsp, 8 */
 	}
 	emit_return(&prog, image + (prog - (u8 *)rw_image));
 	/* Make sure the trampoline generation logic doesn't overflow */
Signature · 1 line
2.43.0
author maintainer
#10 lore raw

PATCH 8/18 bpf, x86: Use shorter and faster forms for some ALU immediates

In reply to Daniel Borkmann

An add or sub of 1 or -1 is an inc or dec, which is a byte shorter and a single uop on all current cores, and the flags they leave untouched are not read across BPF instructions anyway. An add of 128 is the sub of -128 and the other way round, which fits into an imm8. An and of a 64-bit register with a non-negative immediate clears the upper half just like the 32-bit and does, which drops the REX.W prefix on the lower eight registers. A shift left by one is the add of the register to itself, the same size and a single uop that runs on more ports. LLVM emits all of them, r += 1 for every counter, r &= mask for the masks beyond the byte and word ones and r <<= 1 for x * 2 and x + x, and does the same replacements for native code.

Before, for r1 += 1, r1 += 128, r1 &= 0x3ff and r1 <<= 1:

  48 83 c7 01           addq $0x1,%rdi
  48 81 c7 80 00 00 00  addq $0x80,%rdi
  48 81 e7 ff 03 00 00  andq $0x3ff,%rdi
  48 d1 e7              shlq %rdi

After:

  48 ff c7              incq %rdi
  48 83 ef 80           subq $-0x80,%rdi
  81 e7 ff 03 00 00     andl $0x3ff,%edi
  48 01 ff              addq %rdi,%rdi
---
 arch/x86/net/bpf_jit_comp.c | 32 +++++++++++++++++++++++++-------
 1 file changed, 25 insertions(+), 7 deletions(-)
arch/x86/net/bpf_jit_comp.c +25 -7
index 3e367600a0ad..1c84d2a02aba 100644
@@ -1219,9 +1219,22 @@ static void emit_alu_imm(u8 **pprog, u32 op, u32 dst_reg, s32 imm, bool is64)
 		[BPF_OR] = 0x0D, [BPF_XOR] = 0x35,
 	};
 	u8 *prog = *pprog;
-
+	bool inc;
+
+	/* A non-negative mask clears the upper half like the 32-bit and does */
+	if (op == BPF_AND && imm >= 0)
+		is64 = false;
+	/* add 128 is sub -128 and the other way round, which fit into an imm8 */
+	if ((op == BPF_ADD || op == BPF_SUB) && imm == 128) {
+		op = op == BPF_ADD ? BPF_SUB : BPF_ADD;
+		imm = -128;
+	}
+	inc = op == BPF_ADD ? imm == 1 : imm == -1;
 	maybe_emit_1mod(&prog, dst_reg, is64);
-	if (is_imm8(imm))
+	/* inc or dec for +-1, the flags are not read across instructions */
+	if ((op == BPF_ADD || op == BPF_SUB) && (imm == 1 || imm == -1))
+		EMIT2(0xFF, add_1reg(inc ? 0xC0 : 0xC8, dst_reg));
+	else if (is_imm8(imm))
 		EMIT3(0x83, add_1reg(modrm[op], dst_reg), imm);
 	else if (is_axreg(dst_reg))
 		EMIT1_off32(short_op[op], imm);
@@ -1247,11 +1260,16 @@ static void emit_shift_imm(u8 **pprog, u32 op, u32 reg, u8 imm, bool is64)
 {
 	u8 *prog = *pprog;
 
-	maybe_emit_1mod(&prog, reg, is64);
-	if (imm == 1)
-		EMIT2(0xD1, add_1reg(simple_alu_opcodes[op], reg));
-	else
-		EMIT3(0xC1, add_1reg(simple_alu_opcodes[op], reg), imm);
+	/* The shift left by one is an add of the register to itself */
+	if (op == BPF_LSH && imm == 1) {
+		emit_alu_reg(&prog, BPF_ADD, reg, reg, is64);
+	} else {
+		maybe_emit_1mod(&prog, reg, is64);
+		if (imm == 1)
+			EMIT2(0xD1, add_1reg(simple_alu_opcodes[op], reg));
+		else
+			EMIT3(0xC1, add_1reg(simple_alu_opcodes[op], reg), imm);
+	}
 
 	*pprog = prog;
 }
Signature · 1 line
2.43.0
author maintainer
#11 lore raw

PATCH 9/18 bpf, x86: Swap 16-bit values with bswap and shr, not ror and movzx

In reply to Daniel Borkmann

The 16-bit byte swap was emitted as a 16-bit rotate followed by a zero extending move. bswap of the 32-bit register followed by a right shift by 16 has the same result, is two bytes shorter, and avoids the operand size prefix and the 16-bit partial register write. Both sequences are two single cycle uops on Intel and AMD. LLVM emits be16 for bpf_htons() and bpf_ntohs() with cpu v3 and bswap16 with cpu v4, both of which take this path.

Before, for r1 = be16 r1:

66 c1 cf 08 rorw $0x8,%di
0f b7 ff movzwl %di,%edi

After:

0f cf bswap %edi
c1 ef 10 shrl $0x10,%edi

---
 arch/x86/net/bpf_jit_comp.c | 16 +++++++---------
 1 file changed, 7 insertions(+), 9 deletions(-)
arch/x86/net/bpf_jit_comp.c +7 -9
index 1c84d2a02aba..50158d4b85b2 100644
@@ -2596,18 +2596,16 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 		case BPF_ALU64 | BPF_END | BPF_FROM_LE:
 			switch (imm32) {
 			case 16:
-				/* Emit 'ror %ax, 8' to swap lower 2 bytes */
-				EMIT1(0x66);
+				/* Emit 'bswap eax' to swap lower 4 bytes */
 				if (is_ereg(dst_reg))
 					EMIT1(0x41);
-				EMIT3(0xC1, add_1reg(0xC8, dst_reg), 8);
+				EMIT2(0x0F, add_1reg(0xC8, dst_reg));
 
-				/* Emit 'movzwl eax, ax' */
-				if (is_ereg(dst_reg))
-					EMIT3(0x45, 0x0F, 0xB7);
-				else
-					EMIT2(0x0F, 0xB7);
-				EMIT1(add_2reg(0xC0, dst_reg, dst_reg));
+				/*
+				 * Emit 'shr eax, 16' to move the swapped lower
+				 * 2 bytes back down and zero extend
+				 */
+				emit_shift_imm(&prog, BPF_RSH, dst_reg, 16, false);
 				break;
 			case 32:
 				/* Emit 'bswap eax' to swap lower 4 bytes */
Signature · 1 line
2.43.0
author maintainer
#12 lore raw

PATCH 10/18 bpf, x86: Use BMI2 shifts also when the count is in rcx

In reply to Daniel Borkmann

Commit 77d8f5d47bfb ("bpf,x64: use shrx/sarx/shlx when available") kept the legacy shift by cl when the count already is in rcx, since that encoding is two bytes shorter. However, shl/shr/sar r,cl are 3 uops on Intel from Haswell through Skylake and still 2 uops on Ice Lake, as a zero count must leave the flags untouched, whereas shlx/shrx/sarx are a single uop with a latency of 1. On AMD both forms are a single uop, so the two extra bytes are the only cost there. Use the BMI2 form whenever it is available. LLVM keeps the count in whichever register it was allocated to, r4 included.

Before/after for r1 <<= r4:

48 d3 e7 shlq %cl,%rdi
c4 e2 f1 f7 ff shlxq %rcx,%rdi,%rdi

---
 arch/x86/net/bpf_jit_comp.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
arch/x86/net/bpf_jit_comp.c +6 -2
index 50158d4b85b2..de49d7f51a54 100644
@@ -2539,8 +2539,12 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 		case BPF_ALU64 | BPF_LSH | BPF_X:
 		case BPF_ALU64 | BPF_RSH | BPF_X:
 		case BPF_ALU64 | BPF_ARSH | BPF_X:
-			/* BMI2 shifts aren't better when shift count is already in rcx */
-			if (boot_cpu_has(X86_FEATURE_BMI2) && src_reg != BPF_REG_4) {
+			/*
+			 * BMI2 shifts take the count from any register and,
+			 * unlike the cl forms, are a single uop on Intel, so
+			 * prefer them also when the count already is in rcx.
+			 */
+			if (boot_cpu_has(X86_FEATURE_BMI2)) {
 				/* shrx/sarx/shlx dst_reg, dst_reg, src_reg */
 				bool w = (BPF_CLASS(insn->code) == BPF_ALU64);
 				u8 op;
Signature · 1 line
2.43.0
author maintainer
#13 lore raw

PATCH 11/18 bpf, x86: Fold the PROBE_MEM address computation into a lea

In reply to Daniel Borkmann

The kernel address check in front of a BPF_PROBE_MEM load computed src_reg + off - VSYSCALL_ADDR with a mov of VSYSCALL_ADDR, a mov of the base register, an add of the offset in imm32 form and a sub, that is 20 bytes and 4 uops. VSYSCALL_ADDR is -10 MiB, so together with the 16-bit instruction offset it fits into a 32-bit displacement and a single lea does the same in 7 bytes and 1 uop on Intel and AMD.

Before, for the check on r0 = *(u64 *)(r1 + 16):

  49 c7 c2 00 00 60 ff           movq $0xffffffffff600000,%r10
  49 89 fb                       movq %rdi,%r11
  49 81 c3 10 00 00 00           addq $0x10,%r11
  4d 29 d3                       subq %r10,%r11

After:

4c 8d 9f 10 00 a0 00 leaq 0xa00010(%rdi),%r11

---
 arch/x86/net/bpf_jit_comp.c | 26 ++++++++++----------------
 1 file changed, 10 insertions(+), 16 deletions(-)
arch/x86/net/bpf_jit_comp.c +10 -16
index de49d7f51a54..75194f9caa5a 100644
@@ -2853,22 +2853,16 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 				u64 limit = TASK_SIZE_MAX + PAGE_SIZE - VSYSCALL_ADDR;
 				u8 *end_of_jmp;
 
-				/* movabsq r10, VSYSCALL_ADDR */
-				emit_mov_imm64(&prog, BPF_REG_AX, (long)VSYSCALL_ADDR >> 32,
-					       (u32)(long)VSYSCALL_ADDR);
-
-				/* mov src_reg, r11 */
-				EMIT_mov(AUX_REG, src_reg);
-
-				if (insn->off) {
-					/* add r11, insn->off */
-					maybe_emit_1mod(&prog, AUX_REG, true);
-					EMIT2_off32(0x81, add_1reg(0xC0, AUX_REG), insn->off);
-				}
-
-				/* sub r11, r10 */
-				maybe_emit_mod(&prog, AUX_REG, BPF_REG_AX, true);
-				EMIT2(0x29, add_2reg(0xC0, AUX_REG, BPF_REG_AX));
+				/*
+				 * lea r11, [src_reg + insn->off - VSYSCALL_ADDR]
+				 *
+				 * VSYSCALL_ADDR is a small negative number, so the
+				 * whole offset fits into the 32-bit displacement.
+				 */
+				BUILD_BUG_ON((long)(s32)VSYSCALL_ADDR != (long)VSYSCALL_ADDR);
+				EMIT2(add_2mod(0x48, src_reg, AUX_REG), 0x8D);
+				emit_insn_suffix(&prog, src_reg, AUX_REG,
+						 insn->off - (s32)VSYSCALL_ADDR);
 
 				/* movabsq r10, limit */
 				emit_mov_imm64(&prog, BPF_REG_AX, (long)limit >> 32,
Signature · 1 line
2.43.0
author maintainer
#14 lore raw

PATCH 12/18 bpf, x86: Compare the PROBE_MEM address range with a shift

In reply to Daniel Borkmann

The PROBE_MEM check rejects src_reg + off - VSYSCALL_ADDR up to a limit of TASK_SIZE_MAX + PAGE_SIZE - VSYSCALL_ADDR, which does not fit into a 32-bit immediate and therefore needed a movabs into r10 and a register compare. Compare against the next power of two above the limit instead, which is a shift by fls64(limit) followed by a jne on the result. The addresses between the limit and that power of two are non-canonical on every x86-64 layout, since user space ends at TASK_SIZE_MAX and the kernel half starts far above 2^57, so they faulted and had the register zeroed by the exception handler before. Now they are zeroed by the check without taking the fault. The compare and branch stay two uops on Intel and AMD, while the sequence shrinks from 15 to 6 bytes.

Before, for the compare of a 4-level paging kernel:

  49 ba 00 00 a0 00 00 80 00 00  movabsq $0x800000a00000,%r10
  4d 39 d3                       cmpq %r10,%r11
  77 05                          ja 0x...

After:

49 c1 eb 30 shrq $0x30,%r11
75 05 jne 0x...

---
 arch/x86/net/bpf_jit_comp.c | 20 ++++++++++----------
 1 file changed, 10 insertions(+), 10 deletions(-)
arch/x86/net/bpf_jit_comp.c +10 -10
index 75194f9caa5a..564cead6eab7 100644
@@ -2848,6 +2848,11 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 				 *   src_reg + insn->off > TASK_SIZE_MAX + PAGE_SIZE
 				 *   and
 				 *   src_reg + insn->off < VSYSCALL_ADDR
+				 *
+				 * The check is done on src_reg + insn->off - VSYSCALL_ADDR
+				 * against the next power of two above the limit. Addresses
+				 * between the limit and that power of two are non-canonical
+				 * and would fault anyway, so they get zeroed a bit earlier.
 				 */
 
 				u64 limit = TASK_SIZE_MAX + PAGE_SIZE - VSYSCALL_ADDR;
@@ -2864,16 +2869,11 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 				emit_insn_suffix(&prog, src_reg, AUX_REG,
 						 insn->off - (s32)VSYSCALL_ADDR);
 
-				/* movabsq r10, limit */
-				emit_mov_imm64(&prog, BPF_REG_AX, (long)limit >> 32,
-					       (u32)(long)limit);
-
-				/* cmp r10, r11 */
-				maybe_emit_mod(&prog, AUX_REG, BPF_REG_AX, true);
-				EMIT2(0x39, add_2reg(0xC0, AUX_REG, BPF_REG_AX));
+				/* shr r11, fls64(limit) */
+				emit_shift_imm(&prog, BPF_RSH, AUX_REG, fls64(limit), true);
 
-				/* if unsigned '>', goto load */
-				EMIT2(X86_JA, 0);
+				/* if not zero, goto load */
+				EMIT2(X86_JNE, 0);
 				end_of_jmp = prog;
 
 				/* xor dst_reg, dst_reg */
@@ -2881,7 +2881,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 				/* jmp byte_after_ldx */
 				EMIT2(0xEB, 0);
 
-				/* populate jmp_offset for JAE above to jump to start_of_ldx */
+				/* populate jmp_offset for JNE above to jump to start_of_ldx */
 				start_of_ldx = prog;
 				end_of_jmp[-1] = start_of_ldx - end_of_jmp;
 			} else if (!accesses_stack_only) {
Signature · 1 line
2.43.0
author maintainer
#15 lore raw

PATCH 13/18 bpf, x86: Divide by constants via multiplication with a magic number

In reply to Daniel Borkmann

LLVM strength-reduces 32-bit divisions by a constant into a 64-bit multiplication, but has no high-half multiply for the 64-bit ones, so these reach the JIT as BPF_DIV/BPF_MOD with BPF_K and were emitted as div or idiv, which take 20-100 cycles on Intel before Ice Lake, about 15 cycles on Ice Lake and later, and 9-19 cycles on AMD Zen 3-5, whereas a mul is 3 to 4 cycles on all current cores.

Emit the multiplication with a magic number instead, with the constants computed per Hacker's Delight, 2nd ed., figures 10-1 and 10-2, which is also what compilers do for native code: an unsigned division becomes a mul plus a shift, or plus a sub/shr/add/shr sequence when the magic number needs 65 bits, which an even divisor avoids by shifting the dividend by its trailing zeros first, a signed one an imul, an optional add or sub of the dividend, a sar and the sign bit adjustment. A modulo multiplies the quotient back and subtracts it from the dividend. Divisors 0 and +-1 as well as unsigned divisors above 2^63 (negative imm32) are left to div/idiv as before, and so are the 32-bit divisions.

The magic numbers were validated in user space against the bounds from Hacker's Delight for every divisor an imm32 can hold, in both signednesses, and the emitted sequences were executed with dividends around every multiple boundary of the divisor, at the extremes and at random.

Before, for r1 /= 1000:

  50                             pushq %rax
  52                             pushq %rdx
  49 c7 c3 e8 03 00 00           movq $0x3e8,%r11
  48 89 f8                       movq %rdi,%rax
  31 d2                          xorl %edx,%edx
  49 f7 f3                       divq %r11
  48 89 c7                       movq %rax,%rdi
  5a                             popq %rdx
  58                             popq %rax

After:

  50                             pushq %rax
  52                             pushq %rdx
  48 89 f8                       movq %rdi,%rax
  48 c1 e8 03                    shrq $0x3,%rax
  49 bb cf f7 53 e3 a5 9b c4 20  movabsq $0x20c49ba5e353f7cf,%r11
  49 f7 e3                       mulq %r11
  48 c1 ea 04                    shrq $0x4,%rdx
  48 89 d7                       movq %rdx,%rdi
  5a                             popq %rdx
  58                             popq %rax
---
 arch/x86/net/bpf_jit_comp.c | 219 +++++++++++++++++++++++++++++++++++-
 1 file changed, 218 insertions(+), 1 deletion(-)
arch/x86/net/bpf_jit_comp.c +218 -1
index 564cead6eab7..4e9c6bbe93d0 100644
@@ -1923,6 +1923,218 @@ static void emit_shiftx(u8 **pprog, u32 dst_reg, u8 src_reg, bool is64, u8 op)
 	*pprog = prog;
 }
 
+struct bpf_div_magic {
+	u64 m;		/* multiplier, sign extended for signed division */
+	int s;		/* shift of the high half of the product */
+	bool add;	/* multiplier has 65 bits, use the add sequence */
+};
+
+/*
+ * Multiplier and shift for an unsigned division by the constant d, with
+ * 2 <= d < 2^64 and a dividend below 2^(64 - lz): n / d == (mulhu(n, m)
+ * >> s), or with the add sequence when m needs 65 bits, (((n - t) >> 1)
+ * + t) >> (s - 1) with t = mulhu(n, m). Hacker's Delight, 2nd ed., figure
+ * 10-2.
+ */
+static void bpf_magic_udiv(u64 d, int lz, struct bpf_div_magic *mag)
+{
+	u64 mask = ~0ULL >> lz;
+	u64 nc, delta, q1, r1, q2, r2;
+	int p;
+
+	mag->add = false;
+	/* Largest value with nc mod d == d - 1 */
+	nc = mask - (mask % d + 1) % d;
+	p = 63;
+	q1 = (1ULL << 63) / nc;			/* 2^p / nc */
+	r1 = (1ULL << 63) - q1 * nc;		/* 2^p mod nc */
+	q2 = (~0ULL >> 1) / d;			/* (2^p - 1) / d */
+	r2 = (~0ULL >> 1) - q2 * d;		/* (2^p - 1) mod d */
+	do {
+		p++;
+		if (r1 >= nc - r1) {
+			q1 = 2 * q1 + 1;
+			r1 = 2 * r1 - nc;
+		} else {
+			q1 = 2 * q1;
+			r1 = 2 * r1;
+		}
+		if (r2 + 1 >= d - r2) {
+			if (q2 >= (~0ULL >> 1))
+				mag->add = true;
+			q2 = 2 * q2 + 1;
+			r2 = 2 * r2 + 1 - d;
+		} else {
+			if (q2 >= (1ULL << 63))
+				mag->add = true;
+			q2 = 2 * q2;
+			r2 = 2 * r2 + 1;
+		}
+		delta = d - 1 - r2;
+	} while (p < 128 && (q1 < delta || (q1 == delta && r1 == 0)));
+
+	mag->m = q2 + 1;
+	mag->s = p - 64;
+}
+
+/*
+ * Multiplier and shift for a signed division by the constant d, with
+ * 2 <= |d| < 2^63: q = mulhs(n, m), q += n if d > 0 and m < 0, q -= n
+ * if d < 0 and m > 0, q >>= s (arithmetic), n / d == q + (q >>> 63).
+ * Hacker's Delight, 2nd ed., figure 10-1.
+ */
+static void bpf_magic_sdiv(s64 d, struct bpf_div_magic *mag)
+{
+	u64 ad = d < 0 ? -(u64)d : (u64)d;
+	u64 t, anc, delta, q1, r1, q2, r2;
+	int p;
+
+	t = (1ULL << 63) + (d < 0);
+	anc = t - 1 - t % ad;			/* |nc| */
+	p = 63;
+	q1 = (1ULL << 63) / anc;		/* 2^p / |nc| */
+	r1 = (1ULL << 63) - q1 * anc;		/* 2^p mod |nc| */
+	q2 = (1ULL << 63) / ad;			/* 2^p / |d| */
+	r2 = (1ULL << 63) - q2 * ad;		/* 2^p mod |d| */
+	do {
+		p++;
+		q1 = 2 * q1;
+		r1 = 2 * r1;
+		if (r1 >= anc) {
+			q1++;
+			r1 -= anc;
+		}
+		q2 = 2 * q2;
+		r2 = 2 * r2;
+		if (r2 >= ad) {
+			q2++;
+			r2 -= ad;
+		}
+		delta = ad - r2;
+	} while (q1 < delta || (q1 == delta && r1 == 0));
+
+	mag->m = q2 + 1;
+	if (d < 0)
+		mag->m = -mag->m;
+	mag->s = p - 64;
+	mag->add = false;
+}
+
+/*
+ * Divide dst_reg by the constant in insn->imm of a 64-bit division through
+ * a multiplication with the magic number from bpf_magic_udiv() or
+ * bpf_magic_sdiv(). The dividend goes through rax and the multiplier
+ * through r11, the caller saves rax and rdx unless they are dst_reg, and
+ * r10 is scratch. Returns false for the divisors left to div/idiv.
+ */
+static bool emit_div_const(u8 **pprog, const struct bpf_insn *insn, u32 dst_reg)
+{
+	bool is_mod = BPF_OP(insn->code) == BPF_MOD;
+	bool is_signed = insn->off == 1;
+	u32 n_reg = dst_reg, q_reg;
+	s32 imm32 = insn->imm;
+	struct bpf_div_magic mag;
+	u8 *prog = *pprog;
+	int corr = 0, pre = 0, s;
+
+	if (is_signed) {
+		/* |d| >= 2, the verifier already rewrote d == -1 */
+		if (imm32 >= -1 && imm32 <= 1)
+			return false;
+		bpf_magic_sdiv(imm32, &mag);
+		/* q += n for d > 0 and m < 0, q -= n for d < 0 and m > 0 */
+		if (imm32 > 0 && (s64)mag.m < 0)
+			corr = 1;
+		else if (imm32 < 0 && (s64)mag.m > 0)
+			corr = -1;
+	} else {
+		/* d >= 2, a negative imm32 is a divisor above 2^63 */
+		if (imm32 < 2)
+			return false;
+		bpf_magic_udiv(imm32, 0, &mag);
+		/*
+		 * Shift the dividend by the trailing zeros of an even divisor
+		 * first, the magic number of the odd part then fits without
+		 * the add sequence.
+		 */
+		if (mag.add && !(imm32 & 1)) {
+			pre = __ffs(imm32);
+			bpf_magic_udiv(imm32 >> pre, pre, &mag);
+			if (mag.add)
+				return false;
+		}
+	}
+	s = mag.s;
+	/*
+	 * The shift is at most 63, or 64 with the add sequence which shifts
+	 * by s - 1 and needs s >= 1. Never hit for d >= 2, kept as a guard
+	 * against an unencodable count.
+	 */
+	if (s > 64 - !mag.add || (mag.add && !s))
+		return false;
+
+	/* Keep the dividend when the multiplication clobbers it */
+	if ((is_mod || mag.add || corr) &&
+	    (dst_reg == BPF_REG_0 || dst_reg == BPF_REG_3)) {
+		emit_mov_reg(&prog, true, BPF_REG_AX, dst_reg);
+		n_reg = BPF_REG_AX;
+	}
+
+	/* mov rax, dst_reg; shr rax, pre; mov r11, m; mul r11 or imul r11 */
+	if (dst_reg != BPF_REG_0)
+		emit_mov_reg(&prog, true, BPF_REG_0, dst_reg);
+	if (pre)
+		emit_shift_imm(&prog, BPF_RSH, BPF_REG_0, pre, true);
+	emit_mov_imm64(&prog, AUX_REG, mag.m >> 32, (u32)mag.m);
+	EMIT3(0x49, 0xF7, is_signed ? 0xEB : 0xE3);
+	if (is_signed) {
+		/* add rdx, n_reg or sub rdx, n_reg */
+		if (corr)
+			emit_alu_reg(&prog, corr > 0 ? BPF_ADD : BPF_SUB,
+				     BPF_REG_3, n_reg, true);
+		/* sar rdx, s */
+		if (s)
+			emit_shift_imm(&prog, BPF_ARSH, BPF_REG_3, s, true);
+		/* mov rax, rdx; shr rax, 63; add rdx, rax */
+		emit_mov_reg(&prog, true, BPF_REG_0, BPF_REG_3);
+		emit_shift_imm(&prog, BPF_RSH, BPF_REG_0, 63, true);
+		emit_alu_reg(&prog, BPF_ADD, BPF_REG_3, BPF_REG_0, true);
+		q_reg = BPF_REG_3;
+	} else if (!mag.add) {
+		/* shr rdx, s */
+		if (s)
+			emit_shift_imm(&prog, BPF_RSH, BPF_REG_3, s, true);
+		q_reg = BPF_REG_3;
+	} else {
+		/* mov rax, n_reg; sub rax, rdx; shr rax, 1 */
+		emit_mov_reg(&prog, true, BPF_REG_0, n_reg);
+		emit_alu_reg(&prog, BPF_SUB, BPF_REG_0, BPF_REG_3, true);
+		emit_shift_imm(&prog, BPF_RSH, BPF_REG_0, 1, true);
+		/* add rax, rdx; shr rax, s - 1 */
+		emit_alu_reg(&prog, BPF_ADD, BPF_REG_0, BPF_REG_3, true);
+		if (s > 1)
+			emit_shift_imm(&prog, BPF_RSH, BPF_REG_0, s - 1, true);
+		q_reg = BPF_REG_0;
+	}
+
+	if (is_mod) {
+		/* imul q_reg, q_reg, imm32 */
+		maybe_emit_mod(&prog, q_reg, q_reg, true);
+		if (is_imm8(imm32))
+			EMIT3(0x6B, add_2reg(0xC0, q_reg, q_reg), imm32);
+		else
+			EMIT2_off32(0x69, add_2reg(0xC0, q_reg, q_reg), imm32);
+		/* sub n_reg, q_reg */
+		emit_alu_reg(&prog, BPF_SUB, n_reg, q_reg, true);
+		q_reg = n_reg;
+	}
+	if (q_reg != dst_reg)
+		emit_mov_reg(&prog, true, dst_reg, q_reg);
+
+	*pprog = prog;
+	return true;
+}
+
 static void emit_priv_frame_ptr(u8 **pprog, void __percpu *priv_frame_ptr)
 {
 	u8 *prog = *pprog;
@@ -2443,6 +2655,11 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 			if (dst_reg != BPF_REG_3)
 				EMIT1(0x52); /* push rdx */
 
+			/* LLVM strength-reduces the 32-bit ones itself */
+			if (is64 && BPF_SRC(insn->code) == BPF_K &&
+			    emit_div_const(&prog, insn, dst_reg))
+				goto div_done;
+
 			if (BPF_SRC(insn->code) == BPF_X) {
 				if (src_reg == BPF_REG_0 ||
 				    src_reg == BPF_REG_3) {
@@ -2489,7 +2706,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 				 dst_reg != BPF_REG_0)
 				/* mov dst_reg, rax */
 				emit_mov_reg(&prog, is64, dst_reg, BPF_REG_0);
-
+div_done:
 			if (dst_reg != BPF_REG_3)
 				EMIT1(0x5A); /* pop rdx */
 			if (dst_reg != BPF_REG_0)
Signature · 1 line
2.43.0
author maintainer
#16 lore raw

PATCH 14/18 bpf, x86: Multiply by 3, 5 and 9 with lea

In reply to Daniel Borkmann

LLVM turns a multiplication by a power of two into a shift, but keeps the other constants as a multiplication since BPF has no lea to lower them into, so r *= 3 and friends reach the JIT as BPF_MUL with BPF_K and were emitted as imul with an immediate, a 3 cycle instruction on Intel and AMD. Emit lea dst, [dst + dst * 2/4/8] for 3, 5 and 9 instead, which is the same size and a single cycle on Intel and on Zen 3 and later, two cycles on older AMD cores. r13 keeps the imul, since it needs a displacement byte as base register, which makes the lea a byte longer and a slow three operand form with 3 cycles of latency on Intel.

Before/after for r1 *= 3:

48 6b ff 03 imulq $0x3,%rdi,%rdi
48 8d 3c 7f leaq (%rdi,%rdi,2),%rdi

---
 arch/x86/net/bpf_jit_comp.c | 44 ++++++++++++++++++++++++++++---------
 1 file changed, 34 insertions(+), 10 deletions(-)
arch/x86/net/bpf_jit_comp.c +34 -10
index 4e9c6bbe93d0..d1c22ae90fcc 100644
@@ -1163,17 +1163,22 @@ static void emit_insn_suffix(u8 **pprog, u32 ptr_reg, u32 val_reg, int off)
 	*pprog = prog;
 }
 
-static void emit_insn_suffix_SIB(u8 **pprog, u32 ptr_reg, u32 val_reg, u32 index_reg, int off)
+/*
+ * Emit the suffix for addressing *(ptr_reg + (index_reg << scale) + off)
+ * and val_reg, with a SIB byte
+ */
+static void emit_insn_suffix_SIB(u8 **pprog, u32 ptr_reg, u32 val_reg, u32 index_reg, int off,
+				 u8 scale)
 {
+	u8 sib = (scale << 6) | add_2reg(0, ptr_reg, index_reg);
 	u8 *prog = *pprog;
 
 	if (!off && !base_needs_disp(ptr_reg)) {
-		EMIT2(add_2reg(0x04, BPF_REG_0, val_reg),
-		      add_2reg(0, ptr_reg, index_reg) /* SIB */);
+		EMIT2(add_2reg(0x04, BPF_REG_0, val_reg), sib);
 	} else if (is_imm8(off)) {
-		EMIT3(add_2reg(0x44, BPF_REG_0, val_reg), add_2reg(0, ptr_reg, index_reg) /* SIB */, off);
+		EMIT3(add_2reg(0x44, BPF_REG_0, val_reg), sib, off);
 	} else {
-		EMIT2_off32(add_2reg(0x84, BPF_REG_0, val_reg), add_2reg(0, ptr_reg, index_reg) /* SIB */, off);
+		EMIT2_off32(add_2reg(0x84, BPF_REG_0, val_reg), sib, off);
 	}
 	*pprog = prog;
 }
@@ -1444,7 +1449,7 @@ static void emit_ldx_index(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, u32 i
 		EMIT2(add_3mod(0x48, src_reg, dst_reg, index_reg), 0x8B);
 		break;
 	}
-	emit_insn_suffix_SIB(&prog, src_reg, dst_reg, index_reg, off);
+	emit_insn_suffix_SIB(&prog, src_reg, dst_reg, index_reg, off, 0);
 	*pprog = prog;
 }
 
@@ -1466,7 +1471,7 @@ static void emit_ldsx_index(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, u32
 		EMIT2(add_3mod(0x48, src_reg, dst_reg, index_reg), 0x63);
 		break;
 	}
-	emit_insn_suffix_SIB(&prog, src_reg, dst_reg, index_reg, off);
+	emit_insn_suffix_SIB(&prog, src_reg, dst_reg, index_reg, off, 0);
 	*pprog = prog;
 }
 
@@ -1537,7 +1542,7 @@ static void emit_stx_index(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, u32 i
 		EMIT2(add_3mod(0x48, dst_reg, src_reg, index_reg), 0x89);
 		break;
 	}
-	emit_insn_suffix_SIB(&prog, dst_reg, src_reg, index_reg, off);
+	emit_insn_suffix_SIB(&prog, dst_reg, src_reg, index_reg, off, 0);
 	*pprog = prog;
 }
 
@@ -1569,7 +1574,7 @@ static void emit_st_index(u8 **pprog, u32 size, u32 dst_reg, u32 index_reg, int
 		EMIT2(add_3mod(0x48, dst_reg, 0, index_reg), 0xC7);
 		break;
 	}
-	emit_insn_suffix_SIB(&prog, dst_reg, 0, index_reg, off);
+	emit_insn_suffix_SIB(&prog, dst_reg, 0, index_reg, off, 0);
 	EMIT(imm, bpf_size_to_x86_bytes(size));
 	*pprog = prog;
 }
@@ -1713,7 +1718,7 @@ static int emit_atomic_rmw_index(u8 **pprog, u32 atomic_op, u32 size,
 		pr_err("bpf_jit: unknown atomic opcode %02x\n", atomic_op);
 		return -EFAULT;
 	}
-	emit_insn_suffix_SIB(&prog, dst_reg, src_reg, index_reg, off);
+	emit_insn_suffix_SIB(&prog, dst_reg, src_reg, index_reg, off, 0);
 	*pprog = prog;
 	return 0;
 }
@@ -2716,6 +2721,25 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 
 		case BPF_ALU | BPF_MUL | BPF_K:
 		case BPF_ALU64 | BPF_MUL | BPF_K:
+			/*
+			 * lea for 3, 5 and 9, which LLVM leaves as a
+			 * multiplication, but not for r13, which needs a
+			 * displacement as base and makes the lea a slow three
+			 * operand form on Intel.
+			 */
+			if ((imm32 == 3 || imm32 == 5 || imm32 == 9) &&
+			    !base_needs_disp(dst_reg)) {
+				/* lea dst_reg, [dst_reg + dst_reg * (imm32 - 1)] */
+				if (BPF_CLASS(insn->code) == BPF_ALU64)
+					EMIT1(add_3mod(0x48, dst_reg, dst_reg, dst_reg));
+				else if (is_ereg(dst_reg))
+					EMIT1(add_3mod(0x40, dst_reg, dst_reg, dst_reg));
+				EMIT1(0x8D);
+				emit_insn_suffix_SIB(&prog, dst_reg, dst_reg, dst_reg, 0,
+						     ilog2(imm32 - 1));
+				break;
+			}
+
 			maybe_emit_mod(&prog, dst_reg, dst_reg,
 				       BPF_CLASS(insn->code) == BPF_ALU64);
 
Signature · 1 line
2.43.0
#17 lore raw

Re: [PATCH bpf-next 14/18] bpf, x86: Multiply by 3, 5 and 9 with lea

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Critical] bpf, x86: R12 ignored as SIB index, bypassing arena base --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Critical] bpf, x86: R12 ignored as SIB index, bypassing arena base
--

commit 67afba40c1efdd0d3dc72afceed029446b9b3578
Author: Daniel Borkmann <[email protected]>

bpf, x86: Multiply by 3, 5 and 9 with lea

The commit converts BPF multiplication by 3, 5, and 9 into x86 lea instructions. It adds a scale parameter to emit_insn_suffix_SIB to support the scale factor in the SIB byte.

Quoted 7 lines
arch/x86/net/bpf_jit_comp.c +0 -0
index 4e9c6bbe93d0c..d1c22ae90fcc6 100644
@@ -1163,17 +1163,22 @@ static void emit_insn_suffix(u8 **pprog, u32 ptr_reg, u32 val_reg, int off)
 	*pprog = prog;
 }

arch/x86/net/bpf_jit_comp.c static void emit_insn_suffix(u8 **pprog, u32 ptr_reg, u32 val_reg, int off) · line 1173

Quoted 10 lines
arch/x86/net/bpf_jit_comp.c +7 -1
 
-static void emit_insn_suffix_SIB(u8 **pprog, u32 ptr_reg, u32 val_reg, u32 index_reg, int off)
+/*
+ * Emit the suffix for addressing *(ptr_reg + (index_reg << scale) + off)
+ * and val_reg, with a SIB byte
+ */
+static void emit_insn_suffix_SIB(u8 **pprog, u32 ptr_reg, u32 val_reg, u32 index_reg, int off,
+				 u8 scale)
 {
+	u8 sib = (scale << 6) | add_2reg(0, ptr_reg, index_reg);
        ^^^^

[Severity: Critical]
Does this code silently drop the arena base pointer if index_reg is X86_REG_R12?

When index_reg is X86_REG_R12 (which has a value of 4), the SIB index field becomes 100b. On x86-64, an index of 100b is interpreted as 'no index register', so the CPU completely ignores the R12 base.

For BPF programs utilizing arena memory (e.g., via BPF_PROBE_MEM32), functions like emit_ldx_r12(), emit_stx_r12(), and emit_st_r12() explicitly pass X86_REG_R12 as the index register to emit_insn_suffix_SIB().

Because the R12 index is ignored, the kernel will incorrectly dereference the user-provided 32-bit offset directly instead of adding it to the arena base. This could allow a BPF program to read and write arbitrary user-space memory, bypassing arena bounds.

Quoted 15 lines
arch/x86/net/bpf_jit_comp.c +3 -4
 	u8 *prog = *pprog;
 
 	if (!off && !base_needs_disp(ptr_reg)) {
-		EMIT2(add_2reg(0x04, BPF_REG_0, val_reg),
-		      add_2reg(0, ptr_reg, index_reg) /* SIB */);
+		EMIT2(add_2reg(0x04, BPF_REG_0, val_reg), sib);
 	} else if (is_imm8(off)) {
-		EMIT3(add_2reg(0x44, BPF_REG_0, val_reg), add_2reg(0, ptr_reg, index_reg) /* SIB */, off);
+		EMIT3(add_2reg(0x44, BPF_REG_0, val_reg), sib, off);
 	} else {
-		EMIT2_off32(add_2reg(0x84, BPF_REG_0, val_reg), add_2reg(0, ptr_reg, index_reg) /* SIB */, off);
+		EMIT2_off32(add_2reg(0x84, BPF_REG_0, val_reg), sib, off);
 	}
 	*pprog = prog;
 }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
author maintainer
#18 lore raw

Re: [PATCH bpf-next 14/18] bpf, x86: Multiply by 3, 5 and 9 with lea

On 10/13/26 7:58 PM, [email protected] wrote:
[...]

Quoted 7 lines

Does this code silently drop the arena base pointer if index_reg is X86_REG_R12?

When index_reg is X86_REG_R12 (which has a value of 4), the SIB index field becomes 100b. On x86-64, an index of 100b is interpreted as 'no index register', so the CPU completely ignores the R12 base.

Quoted 8 lines

For BPF programs utilizing arena memory (e.g., via BPF_PROBE_MEM32), functions like emit_ldx_r12(), emit_stx_r12(), and emit_st_r12() explicitly pass X86_REG_R12 as the index register to emit_insn_suffix_SIB().

Because the R12 index is ignored, the kernel will incorrectly dereference the user-provided 32-bit offset directly instead of adding it to the arena base. This could allow a BPF program to read and write arbitrary user-space memory, bypassing arena bounds.

False positive. SIB index 100b is "no index" only with REX.X = 0. Callers emit the REX byte via add_3mod(), which sets REX.X for R12, so the encoding is e.g. 4a 8b 04 20 = mov rax,[rax+r12*1]. The SIB byte is byte-identical to the pre- series code, and jit_insns_arena selftest exercises arena loads and stores with a zero offset which runs through this code, and full test_progs run passes all arena tests.

Thanks,
Daniel

author maintainer
#19 lore raw

PATCH 15/18 bpf, x86: Use emit_sub_rsp() for the trampoline stack

In reply to Daniel Borkmann

The trampoline prologue open codes the choice between the imm8 and the imm32 form of sub rsp which emit_sub_rsp() already makes. Use it.

---
 arch/x86/net/bpf_jit_comp.c | 9 ++-------
 1 file changed, 2 insertions(+), 7 deletions(-)
arch/x86/net/bpf_jit_comp.c +2 -7
index d1c22ae90fcc..c2fe72fa0bed 100644
@@ -4325,13 +4325,8 @@ static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_im
 	if (im)
 		im->ksym.fp_start = prog - (u8 *)rw_image;
 
-	if (!is_imm8(stack_size)) {
-		/* sub rsp, stack_size */
-		EMIT3_off32(0x48, 0x81, 0xEC, stack_size);
-	} else {
-		/* sub rsp, stack_size */
-		EMIT4(0x48, 0x83, 0xEC, stack_size);
-	}
+	/* sub rsp, stack_size */
+	emit_sub_rsp(&prog, stack_size);
 	if (flags & BPF_TRAMP_F_TAIL_CALL_CTX)
 		EMIT1(0x50);		/* push rax */
 	/* mov QWORD PTR [rbp - rbx_off], rbx */
Signature · 1 line
2.43.0
author maintainer
#20 lore raw

PATCH 16/18 bpf, x86: Shorten the cast to a user address

In reply to Daniel Borkmann

The cast of an arena pointer to its user address zero extended the low half, shifted it up, or'ed the user base in, rotated it back down and replaced the result with zero from a cleared r11 through a cmove for a NULL pointer: seven instructions with a dependency chain of six. Or the user base into r11 instead and pick it with a cmovne when the low half is not zero, five instructions with a chain of three. LLVM emits the cast for every arena pointer handed back to user space.

Before, for r1 = addr_space_cast(r7, 1, 0) with a user base of 0x7f1200000000:

  44 89 ef                       movl %r13d,%edi
  48 c1 e7 20                    shlq $0x20,%rdi
  48 81 cf 12 7f 00 00           orq $0x7f12,%rdi
  48 c1 c7 20                    rolq $0x20,%rdi
  4d 31 db                       xorq %r11,%r11
  85 ff                          testl %edi,%edi
  49 0f 44 fb                    cmoveq %r11,%rdi

After:

  44 89 ef                       movl %r13d,%edi
  49 bb 00 00 00 00 12 7f 00 00  movabsq $0x7f1200000000,%r11
  49 09 fb                       orq %rdi,%r11
  85 ff                          testl %edi,%edi
  49 0f 45 fb                    cmovneq %r11,%rdi
---
 arch/x86/net/bpf_jit_comp.c | 33 ++++++++-------------------------
 1 file changed, 8 insertions(+), 25 deletions(-)
arch/x86/net/bpf_jit_comp.c +8 -25
index c2fe72fa0bed..3975a94ac812 100644
@@ -2544,35 +2544,18 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 
 		case BPF_ALU64 | BPF_MOV | BPF_X:
 			if (insn_is_cast_user(insn)) {
-				if (dst_reg != src_reg)
-					/* 32-bit mov */
-					emit_mov_reg(&prog, false, dst_reg, src_reg);
-				/* shl dst_reg, 32 */
-				maybe_emit_1mod(&prog, dst_reg, true);
-				EMIT3(0xC1, add_1reg(0xE0, dst_reg), 32);
-
-				/* or dst_reg, user_vm_start */
-				maybe_emit_1mod(&prog, dst_reg, true);
-				if (is_axreg(dst_reg))
-					EMIT1_off32(0x0D,  user_vm_start >> 32);
-				else
-					EMIT2_off32(0x81, add_1reg(0xC8, dst_reg),  user_vm_start >> 32);
-
-				/* rol dst_reg, 32 */
-				maybe_emit_1mod(&prog, dst_reg, true);
-				EMIT3(0xC1, add_1reg(0xC0, dst_reg), 32);
-
-				/* xor r11, r11 */
-				EMIT3(0x4D, 0x31, 0xDB);
-
-				/* test dst_reg32, dst_reg32; check if lower 32-bit are zero */
+				/* mov dst_reg32, src_reg32 to zero extend the low half */
+				emit_mov_reg(&prog, false, dst_reg, src_reg);
+				/* mov r11, the high half of user_vm_start; or r11, dst_reg */
+				emit_mov_imm64(&prog, AUX_REG, user_vm_start >> 32, 0);
+				emit_alu_reg(&prog, BPF_OR, AUX_REG, dst_reg, true);
+				/* test dst_reg32, dst_reg32; a NULL pointer stays NULL */
 				maybe_emit_mod(&prog, dst_reg, dst_reg, false);
 				EMIT2(0x85, add_2reg(0xC0, dst_reg, dst_reg));
-
-				/* cmove r11, dst_reg; if so, set dst_reg to zero */
+				/* cmovne dst_reg, r11 */
 				/* WARNING: Intel swapped src/dst register encoding in CMOVcc !!! */
 				maybe_emit_mod(&prog, AUX_REG, dst_reg, true);
-				EMIT3(0x0F, 0x44, add_2reg(0xC0, AUX_REG, dst_reg));
+				EMIT3(0x0F, 0x45, add_2reg(0xC0, AUX_REG, dst_reg));
 				break;
 			} else if (insn_is_mov_percpu_addr(insn)) {
 				/* mov <dst>, <src> (if necessary) */
Signature · 1 line
2.43.0
author maintainer
#21 lore raw

PATCH 17/18 selftests/bpf: Add JIT instruction tests

In reply to Daniel Borkmann

Carry only the relevant instruction tests of the test_bpf kernel module over into test_progs, so that BPF CI runs them on every JIT: ALU, atomic, 64-bit immediate load and jump instructions for the power-of-two magnitudes and signs of the operands, all shift counts, all operand register combinations, the division and modulo by constants, jumps with staggered offsets, here in both directions and also for the 32-bit unconditional jump, and the maximal jump over instructions which expand in the JITs. Add sweeps for the instruction patterns a JIT has a shorter or faster native form for, with every register as operand. The families with an immediate run once more with constant blinding.

# LDLIBS=-static PKG_CONFIG='pkg-config --static' ./vmtest.sh -- ./test_progs -t jit_insns [...]

  #191/1   jit_insns/arena access with zero offset:OK
  #191/2   jit_insns/cast to a user address:OK
  #191/3   jit_insns/alu_imm:OK
  #191/4   jit_insns/alu_reg:OK
  #191/5   jit_insns/alu_imm_regs:OK
  #191/6   jit_insns/div_const:OK
  #191/7   jit_insns/alu_reg_pairs:OK
  #191/8   jit_insns/shifts:OK
  #191/9   jit_insns/atomics:OK
  #191/10  jit_insns/atomic_reg_pairs:OK
  #191/11  jit_insns/xadd_chain:OK
  #191/12  jit_insns/ld_imm64:OK
  #191/13  jit_insns/jmp_imm:OK
  #191/14  jit_insns/jmp_reg:OK
  #191/15  jit_insns/jmp_reg_pairs:OK
  #191/16  jit_insns/staggered_jumps:OK
  #191/17  jit_insns/max_jmp:OK
  #191/18  jit_insns/ldst_zero_off:OK
  #191/19  jit_insns/ldst_offsets:OK
  #191/20  jit_insns/acq_rel:OK
  #191/21  jit_insns/movsx:OK
  #191/22  jit_insns/jset_imm:OK
  #191/23  jit_insns/cmp_imm:OK
  #191/24  jit_insns/alu_consts:OK
  #191/25  jit_insns/bswap:OK
  #191/26  jit_insns/probe_mem:OK
  #191     jit_insns:OK
  #192/1   jit_insns_blinded/alu_imm:OK
  #192/2   jit_insns_blinded/alu_imm_regs:OK
  #192/3   jit_insns_blinded/div_const:OK
  #192/4   jit_insns_blinded/shifts:OK
  #192/5   jit_insns_blinded/xadd_chain:OK
  #192/6   jit_insns_blinded/ld_imm64:OK
  #192/7   jit_insns_blinded/jmp_imm:OK
  #192/8   jit_insns_blinded/ldst_zero_off:OK
  #192/9   jit_insns_blinded/ldst_offsets:OK
  #192/10  jit_insns_blinded/jset_imm:OK
  #192/11  jit_insns_blinded/cmp_imm:OK
  #192/12  jit_insns_blinded/alu_consts:OK
  #192     jit_insns_blinded:OK

Summary: 2/38 PASSED, 0 SKIPPED, 0/0 FAILED

---
 .../selftests/bpf/prog_tests/jit_insns.c      | 2433 +++++++++++++++++
 .../selftests/bpf/progs/jit_insns_arena.c     |  113 +
 2 files changed, 2546 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/jit_insns.c
 create mode 100644 tools/testing/selftests/bpf/progs/jit_insns_arena.c
tools/testing/selftests/bpf/prog_tests/jit_insns.c new file +2433 -0
new file mode 100644
index 000000000000..dabf8a4abdfe
@@ -0,0 +1,2433 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Isovalent */
+
+#include <endian.h>
+#include <stdint.h>
+#include <test_progs.h>
+#include <bpf/btf.h>
+#include <linux/filter.h>
+
+#include "sysctl_helpers.h"
+#include "jit_insns_arena.skel.h"
+
+#define NR_CASES	512
+#define CTX_SPILL	-16	/* stack slot holding the ctx pointer */
+#define MEM_SLOT	-8	/* stack slot for the atomic operations */
+
+struct sweep_ctx {
+	__u64 in[NR_CASES][2];
+	__u64 out[NR_CASES][3];
+};
+
+#define IN_OFF(k, j)	(offsetof(struct sweep_ctx, in) + ((k) * 2 + (j)) * 8)
+#define OUT_OFF(k, j)	(offsetof(struct sweep_ctx, out) + ((k) * 3 + (j)) * 8)
+
+/* The cases of one program: operands in, results out, expected results */
+struct batch {
+	struct bpf_insn *insns;
+	int cnt, cap;
+	struct sweep_ctx ctx;
+	__u64 exp[NR_CASES][3];
+	__u8 nr_out[NR_CASES];
+	int nr;
+	char desc[80];
+};
+
+static char log[1 << 16];
+
+#define EMIT(b, insn)	((b)->insns[(b)->cnt++] = (insn))
+
+static void emit_ld_imm64(struct batch *b, int reg, __u64 imm)
+{
+	EMIT(b, BPF_RAW_INSN(BPF_LD | BPF_DW | BPF_IMM, reg, 0, 0, (__u32)imm));
+	EMIT(b, BPF_RAW_INSN(0, 0, 0, 0, imm >> 32));
+}
+
+static void batch_reset(struct batch *b)
+{
+	b->cnt = 0;
+	b->nr = 0;
+	/* The ctx pointer lives on the stack, every register is an operand */
+	EMIT(b, BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_1, CTX_SPILL));
+}
+
+static bool batch_init(struct batch *b)
+{
+	b->cap = NR_CASES * 24 + 8;
+	b->insns = malloc(b->cap * sizeof(*b->insns));
+	if (!ASSERT_OK_PTR(b->insns, "insns"))
+		return false;
+	batch_reset(b);
+	return true;
+}
+
+static void batch_fini(struct batch *b)
+{
+	free(b->insns);
+}
+
+static int load_prog(struct bpf_insn *insns, int cnt, const char *desc)
+{
+	LIBBPF_OPTS(bpf_prog_load_opts, lopts,
+		.prog_flags = BPF_F_SLEEPABLE,
+		.log_buf = log,
+		.log_size = sizeof(log),
+	);
+	int fd;
+
+	fd = bpf_prog_load(BPF_PROG_TYPE_SYSCALL, NULL, "GPL", insns, cnt, &lopts);
+	if (!ASSERT_GE(fd, 0, desc))
+		fprintf(stderr, "%s", log);
+	return fd;
+}
+
+/* Run the batch, check the results, start a new one */
+static void batch_flush(struct batch *b)
+{
+	LIBBPF_OPTS(bpf_test_run_opts, opts,
+		.ctx_in = &b->ctx,
+		.ctx_size_in = sizeof(b->ctx),
+	);
+	char buf[160];
+	int fd, k, j;
+
+	if (!b->nr)
+		return;
+	EMIT(b, BPF_MOV64_IMM(BPF_REG_0, 0));
+	EMIT(b, BPF_EXIT_INSN());
+	snprintf(buf, sizeof(buf), "%s: load %d cases", b->desc, b->nr);
+	fd = load_prog(b->insns, b->cnt, buf);
+	if (fd >= 0 && ASSERT_OK(bpf_prog_test_run_opts(fd, &opts), b->desc)) {
+		for (k = 0; k < b->nr; k++) {
+			for (j = 0; j < b->nr_out[k]; j++) {
+				if (b->ctx.out[k][j] == b->exp[k][j])
+					continue;
+				snprintf(buf, sizeof(buf), "%s: in0=0x%llx in1=0x%llx out%d",
+					 b->desc, b->ctx.in[k][0], b->ctx.in[k][1], j);
+				ASSERT_EQ(b->ctx.out[k][j], b->exp[k][j], buf);
+			}
+		}
+	}
+	if (fd >= 0)
+		close(fd);
+	batch_reset(b);
+}
+
+/* Add a case: record the operands and load the ctx pointer into rc */
+static int batch_case(struct batch *b, int rc, __u64 in0, __u64 in1)
+{
+	int k;
+
+	if (b->nr == NR_CASES)
+		batch_flush(b);
+	k = b->nr++;
+	b->ctx.in[k][0] = in0;
+	b->ctx.in[k][1] = in1;
+	b->nr_out[k] = 0;
+	EMIT(b, BPF_LDX_MEM(BPF_DW, rc, BPF_REG_10, CTX_SPILL));
+	return k;
+}
+
+static void batch_expect(struct batch *b, int k, int j, __u64 val)
+{
+	b->exp[k][j] = val;
+	if (b->nr_out[k] <= j)
+		b->nr_out[k] = j + 1;
+}
+
+#define LD_IN(b, k, j, rc, reg)		EMIT(b, BPF_LDX_MEM(BPF_DW, reg, rc, IN_OFF(k, j)))
+#define ST_OUT(b, k, j, rc, reg)	EMIT(b, BPF_STX_MEM(BPF_DW, rc, reg, OUT_OFF(k, j)))
+
+/* A register that is neither of the two operand registers nor r0 */
+static int scratch_reg(int r1, int r2)
+{
+	int r;
+
+	for (r = BPF_REG_1; r <= BPF_REG_9; r++)
+		if (r != r1 && r != r2)
+			return r;
+	return BPF_REG_9;
+}
+
+static const char *alu_name(int op)
+{
+	switch (BPF_OP(op)) {
+	case BPF_MOV: return "mov";
+	case BPF_NEG: return "neg";
+	case BPF_AND: return "and";
+	case BPF_OR: return "or";
+	case BPF_XOR: return "xor";
+	case BPF_LSH: return "lsh";
+	case BPF_RSH: return "rsh";
+	case BPF_ARSH: return "arsh";
+	case BPF_ADD: return "add";
+	case BPF_SUB: return "sub";
+	case BPF_MUL: return "mul";
+	case BPF_DIV: return "div";
+	case BPF_MOD: return "mod";
+	case BPF_OP(BPF_XCHG): return "xchg";
+	case BPF_OP(BPF_CMPXCHG): return "cmpxchg";
+	default: return "?";
+	}
+}
+
+static const char *jmp_name(int op)
+{
+	switch (op) {
+	case BPF_JSET: return "jset";
+	case BPF_JEQ: return "jeq";
+	case BPF_JNE: return "jne";
+	case BPF_JGT: return "jgt";
+	case BPF_JGE: return "jge";
+	case BPF_JLT: return "jlt";
+	case BPF_JLE: return "jle";
+	case BPF_JSGT: return "jsgt";
+	case BPF_JSGE: return "jsge";
+	case BPF_JSLT: return "jslt";
+	case BPF_JSLE: return "jsle";
+	default: return "?";
+	}
+}
+
+/* ALU result computation, false when the operands are not valid */
+enum { F_ALU32 = 1, F_SIGNED = 2 };
+
+static bool alu_result(__u64 *res, __u64 v1, __u64 v2, __u8 op, __u32 flags)
+{
+	bool is_signed = flags & F_SIGNED;
+
+	/* Narrow operands for ALU32 */
+	if (flags & F_ALU32) {
+		if (is_signed) {
+			v1 = (__u64)(__s32)v1;
+			v2 = (__u64)(__s32)v2;
+		} else {
+			v1 = (__u32)v1;
+			v2 = (__u32)v2;
+		}
+	}
+
+	*res = 0;
+	switch (op) {
+	case BPF_MOV:
+		*res = v2;
+		break;
+	case BPF_NEG:
+		*res = -v1;
+		break;
+	case BPF_AND:
+		*res = v1 & v2;
+		break;
+	case BPF_OR:
+		*res = v1 | v2;
+		break;
+	case BPF_XOR:
+		*res = v1 ^ v2;
+		break;
+	case BPF_LSH:
+		*res = v1 << v2;
+		break;
+	case BPF_RSH:
+		*res = v1 >> v2;
+		break;
+	case BPF_ARSH:
+		*res = v1 >> v2;
+		if (v2 > 0 && v1 > INT64_MAX)
+			*res |= ~0ULL << (64 - v2);
+		break;
+	case BPF_ADD:
+		*res = v1 + v2;
+		break;
+	case BPF_SUB:
+		*res = v1 - v2;
+		break;
+	case BPF_MUL:
+		*res = v1 * v2;
+		break;
+	case BPF_DIV:
+		if (v2 == 0)
+			return false;
+		if (!is_signed) {
+			*res = v1 / v2;
+		} else {
+			if ((__s64)v2 == -1) /* Handled by the verifier */
+				return false;
+			*res = (__u64)((__s64)v1 / (__s64)v2);
+		}
+		break;
+	case BPF_MOD:
+		if (v2 == 0)
+			return false;
+		if (!is_signed) {
+			*res = v1 % v2;
+		} else {
+			if ((__s64)v2 == -1)
+				return false;
+			*res = (__u64)((__s64)v1 % (__s64)v2);
+		}
+		break;
+	}
+	return true;
+}
+
+/*
+ * Operand pattern generator for the power-of-two magnitude tests: all
+ * combinations of magnitudes and signs with a block of contiguous values
+ * around each magnitude, with every dstep'th magnitude of the destination,
+ * and a larger block for the same magnitude of both operands. The first
+ * pattern is where the immediates take every encoding a JIT has, the
+ * second where the sign and overflow boundaries of both operands meet.
+ */
+static __s64 value(int msb, int delta, int sign)
+{
+	return sign * (1LL << msb) + delta;
+}
+
+#define PATTERN_BLOCK1 1
+#define PATTERN_BLOCK2 3
+
+typedef void (*emit_fn)(struct batch *b, void *arg, __s64 dst, __s64 src);
+
+static void fill_pattern(struct batch *b, void *arg, int dbits, int sbits,
+			 int block1, int dstep, int block2, emit_fn emit)
+{
+	static const int sgn[][2] = { { 1, 1 }, { 1, -1 }, { -1, 1 }, { -1, -1 } };
+	int di, si, bt, db, sb, k;
+
+	for (di = 0; di < dbits - 1; di += dstep)
+		for (si = 0; si < sbits - 1; si++)
+			for (k = 0; k < ARRAY_SIZE(sgn); k++)
+				for (db = -(block1 / 2); db < (block1 + 1) / 2; db++)
+					for (sb = -(block1 / 2); sb < (block1 + 1) / 2; sb++)
+						emit(b, arg, value(di, db, sgn[k][0]),
+						     value(si, sb, sgn[k][1]));
+
+	for (bt = 0; bt < (dbits > sbits ? dbits : sbits) - 1; bt++)
+		for (k = 0; k < ARRAY_SIZE(sgn); k++)
+			for (db = -(block2 / 2); db < (block2 + 1) / 2; db++)
+				for (sb = -(block2 / 2); sb < (block2 + 1) / 2; sb++)
+					emit(b, arg, value(bt % dbits, db, sgn[k][0]),
+					     value(bt % sbits, sb, sgn[k][1]));
+	batch_flush(b);
+}
+
+/* ALU operations with an immediate and with a register for all magnitudes */
+static const int alu_ops[] = {
+	BPF_MOV, BPF_AND, BPF_OR, BPF_XOR, BPF_ADD, BPF_SUB, BPF_MUL, BPF_DIV, BPF_MOD,
+};
+
+struct alu_arg {
+	int op;
+	__u32 flags;
+};
+
+static void emit_alu_imm(struct batch *b, void *arg, __s64 dst, __s64 imm)
+{
+	struct alu_arg *a = arg;
+	bool alu32 = a->flags & F_ALU32;
+	__u64 res;
+	int k;
+
+	if (!alu_result(&res, dst, (__s32)imm, a->op, a->flags))
+		return;
+	k = batch_case(b, BPF_REG_3, dst, 0);
+	LD_IN(b, k, 0, BPF_REG_3, BPF_REG_1);
+	EMIT(b, BPF_RAW_INSN((alu32 ? BPF_ALU : BPF_ALU64) | BPF_OP(a->op) | BPF_K,
+			     BPF_REG_1, 0, a->flags & F_SIGNED ? 1 : 0, imm));
+	ST_OUT(b, k, 0, BPF_REG_3, BPF_REG_1);
+	batch_expect(b, k, 0, alu32 ? (__u32)res : res);
+}
+
+static void emit_alu_reg(struct batch *b, void *arg, __s64 dst, __s64 src)
+{
+	struct alu_arg *a = arg;
+	bool alu32 = a->flags & F_ALU32;
+	__u64 res;
+	int k;
+
+	if (!alu_result(&res, dst, src, a->op, a->flags))
+		return;
+	k = batch_case(b, BPF_REG_3, dst, src);
+	LD_IN(b, k, 0, BPF_REG_3, BPF_REG_1);
+	LD_IN(b, k, 1, BPF_REG_3, BPF_REG_2);
+	EMIT(b, BPF_RAW_INSN((alu32 ? BPF_ALU : BPF_ALU64) | BPF_OP(a->op) | BPF_X,
+			     BPF_REG_1, BPF_REG_2, a->flags & F_SIGNED ? 1 : 0, 0));
+	ST_OUT(b, k, 0, BPF_REG_3, BPF_REG_1);
+	batch_expect(b, k, 0, alu32 ? (__u32)res : res);
+}
+
+static void test_alu_magnitudes(bool reg)
+{
+	struct batch b;
+	int o, f;
+
+	if (!batch_init(&b))
+		return;
+	for (f = 0; f < 2; f++) {
+		for (o = 0; o < ARRAY_SIZE(alu_ops); o++) {
+			struct alu_arg a = { alu_ops[o], f ? F_ALU32 : 0 };
+
+			snprintf(b.desc, sizeof(b.desc), "alu%d_%s_%c magnitudes",
+				 f ? 32 : 64, alu_name(a.op), reg ? 'x' : 'k');
+			if (reg)
+				fill_pattern(&b, &a, 64, 64, 0, 1, PATTERN_BLOCK2, emit_alu_reg);
+			else
+				fill_pattern(&b, &a, 64, 32, PATTERN_BLOCK1, 1, 5, emit_alu_imm);
+		}
+		for (o = 0; o < 2; o++) {
+			struct alu_arg a = { o ? BPF_MOD : BPF_DIV, F_SIGNED | (f ? F_ALU32 : 0) };
+
+			snprintf(b.desc, sizeof(b.desc), "alu%d_s%s_%c magnitudes",
+				 f ? 32 : 64, alu_name(a.op), reg ? 'x' : 'k');
+			if (reg)
+				fill_pattern(&b, &a, 64, 64, 0, 1, PATTERN_BLOCK2, emit_alu_reg);
+			else
+				fill_pattern(&b, &a, 64, 32, PATTERN_BLOCK1, 1, 5, emit_alu_imm);
+		}
+	}
+	batch_fini(&b);
+}
+
+static void test_alu_imm(void)
+{
+	test_alu_magnitudes(false);
+}
+
+static void test_alu_reg(void)
+{
+	test_alu_magnitudes(true);
+}
+
+/* ALU operations with an immediate for every destination register */
+static const int alu_reg_ops[] = {
+	BPF_MOV, BPF_AND, BPF_OR, BPF_XOR, BPF_LSH, BPF_RSH, BPF_ARSH,
+	BPF_ADD, BPF_SUB, BPF_MUL, BPF_DIV, BPF_MOD,
+};
+
+static void alu_imm_regs(struct batch *b, int op, __u32 flags)
+{
+	bool alu32 = flags & F_ALU32;
+	__u32 imm = 0x01234567U;
+	__u64 dst, res;
+	int rd, rc, k;
+
+	if (flags & F_SIGNED)
+		dst = alu32 ? (__u64)-76543210LL : (__u64)-7654321076543210LL;
+	else
+		dst = alu32 ? 0x76543210ULL : 0x7edcba9876543210ULL;
+	if (op == BPF_LSH || op == BPF_RSH || op == BPF_ARSH)
+		imm &= 31;
+	if (op == BPF_NEG)
+		imm = 0;
+	alu_result(&res, dst, imm, op, flags);
+	if (alu32)
+		res = (__u32)res;
+
+	snprintf(b->desc, sizeof(b->desc), "alu%d_%s%s_k registers", alu32 ? 32 : 64,
+		 flags & F_SIGNED ? "s" : "", alu_name(op));
+	for (rd = BPF_REG_0; rd <= BPF_REG_9; rd++) {
+		rc = scratch_reg(rd, rd);
+		k = batch_case(b, rc, dst, 0);
+		LD_IN(b, k, 0, rc, rd);
+		EMIT(b, BPF_RAW_INSN((alu32 ? BPF_ALU : BPF_ALU64) | BPF_OP(op) | BPF_K,
+				     rd, 0, flags & F_SIGNED ? 1 : 0, imm));
+		ST_OUT(b, k, 0, rc, rd);
+		batch_expect(b, k, 0, res);
+	}
+	batch_flush(b);
+}
+
+static void test_alu_imm_regs(void)
+{
+	struct batch b;
+	int o, f;
+
+	if (!batch_init(&b))
+		return;
+	for (f = 0; f < 2; f++) {
+		for (o = 0; o < ARRAY_SIZE(alu_reg_ops); o++)
+			alu_imm_regs(&b, alu_reg_ops[o], f ? F_ALU32 : 0);
+		alu_imm_regs(&b, BPF_NEG, f ? F_ALU32 : 0);
+		alu_imm_regs(&b, BPF_DIV, F_SIGNED | (f ? F_ALU32 : 0));
+		alu_imm_regs(&b, BPF_MOD, F_SIGNED | (f ? F_ALU32 : 0));
+	}
+	batch_fini(&b);
+}
+
+/*
+ * Division and modulo by constants for every width, signedness and
+ * destination register with a set of divisors and dividends around the
+ * multiple boundaries and the extremes of each range. This covers a JIT
+ * replacing the division with a multiplication by a magic number in all
+ * of its forms: magic numbers needing the extra add step, zero shifts,
+ * both signed corrections, and the divisors like 1, -1 and the ones
+ * above 2^63 that are still emitted as a real division. The dividends
+ * of the 32-bit operations carry garbage in the upper 32 bits.
+ */
+static const __s32 unsigned_divisors[] = {
+	2, 3, 7, 10, 25, 641, 1000, 4096, 65536, 1000000007, 0x7fffffff,
+	-2, -10, -0x7fffffff - 1, -1, 1,
+};
+
+static const __s32 signed_divisors[] = {
+	2, 3, 7, 25, 1000, 0x40000000, 0x7fffffff,
+	-2, -3, -5, -7, -1000, -0x7fffffff, -0x7fffffff - 1, 1, -1,
+};
+
+static int dividends(__u32 flags, __s32 imm, __u64 *n)
+{
+	bool alu32 = flags & F_ALU32, is_signed = flags & F_SIGNED;
+	__u64 d = is_signed ? (imm < 0 ? -(__s64)imm : imm) :
+		  alu32 ? (__u32)imm : (__u64)(__s64)imm;
+	int cnt = 0, i;
+
+	n[cnt++] = 0;
+	n[cnt++] = d - 1;
+	n[cnt++] = d + 1;
+	n[cnt++] = 3 * d + 2;
+	if (!alu32) {
+		n[cnt++] = (d << 40) - 1;
+		n[cnt++] = (d << 40) + 1;
+		n[cnt++] = (1ULL << 63) - 1;
+		n[cnt++] = 1ULL << 63;
+		n[cnt++] = ~0ULL;
+		n[cnt++] = 0xdaeb8ebd244a330cULL;
+	} else {
+		n[cnt++] = (d << 16) - 1;
+		n[cnt++] = (d << 16) + 1;
+		n[cnt++] = (1ULL << 31) - 1;
+		n[cnt++] = 1ULL << 31;
+		n[cnt++] = ~0U;
+		n[cnt++] = 0x8c1e86f1;
+	}
+	if (is_signed) {
+		n[cnt++] = -1;
+		n[cnt++] = -d - 1;
+		n[cnt++] = -3 * d - 2;
+		n[cnt++] = alu32 ? -(1ULL << 31) + 1 : -(1ULL << 63) + 1;
+	}
+	if (alu32)
+		for (i = 0; i < cnt; i++)
+			n[i] = (__u32)n[i] | ((0xa5a50000ULL + i) << 32);
+	return cnt;
+}
+
+static __u64 div_result(int op, __u32 flags, __s32 imm, __u64 n)
+{
+	__u64 res;
+
+	/* LLONG_MIN / -1 == LLONG_MIN, LLONG_MIN % -1 == 0, same for INT_MIN */
+	if ((flags & F_SIGNED) && imm == -1)
+		res = op == BPF_MOD ? 0 : -n;
+	else
+		alu_result(&res, n, (__s32)imm, op, flags);
+	return flags & F_ALU32 ? (__u32)res : res;
+}
+
+static void div_const(struct batch *b, int op, __u32 flags)
+{
+	bool alu32 = flags & F_ALU32, is_signed = flags & F_SIGNED;
+	const __s32 *divs = is_signed ? signed_divisors : unsigned_divisors;
+	int cnt = is_signed ? ARRAY_SIZE(signed_divisors) : ARRAY_SIZE(unsigned_divisors);
+	int code = (alu32 ? BPF_ALU : BPF_ALU64) | BPF_OP(op) | BPF_K;
+	int i, j, nr, rd, rc, k;
+	__u64 n[16];
+
+	snprintf(b->desc, sizeof(b->desc), "alu%d_%s%s_k constants", alu32 ? 32 : 64,
+		 is_signed ? "s" : "", alu_name(op));
+	for (i = 0; i < cnt; i++) {
+		nr = dividends(flags, divs[i], n);
+		for (rd = BPF_REG_0; rd <= BPF_REG_9; rd++) {
+			rc = scratch_reg(rd, rd);
+			for (j = 0; j < nr; j++) {
+				k = batch_case(b, rc, n[j], divs[i]);
+				LD_IN(b, k, 0, rc, rd);
+				EMIT(b, BPF_RAW_INSN(code, rd, 0, is_signed, divs[i]));
+				ST_OUT(b, k, 0, rc, rd);
+				batch_expect(b, k, 0, div_result(op, flags, divs[i], n[j]));
+			}
+		}
+	}
+	batch_flush(b);
+}
+
+static void test_div_const(void)
+{
+	struct batch b;
+	int f;
+
+	if (!batch_init(&b))
+		return;
+	for (f = 0; f < 2; f++) {
+		div_const(&b, BPF_DIV, f ? F_ALU32 : 0);
+		div_const(&b, BPF_MOD, f ? F_ALU32 : 0);
+		div_const(&b, BPF_DIV, F_SIGNED | (f ? F_ALU32 : 0));
+		div_const(&b, BPF_MOD, F_SIGNED | (f ? F_ALU32 : 0));
+	}
+	batch_fini(&b);
+}
+
+/* ALU operations for all combinations of operand registers */
+static void alu_reg_pairs(struct batch *b, int op, __u32 flags)
+{
+	bool alu32 = flags & F_ALU32;
+	__u64 dst, src, res, same;
+	int rd, rs, rc, k;
+
+	if (flags & F_SIGNED)
+		dst = alu32 ? (__u64)-76543210LL : (__u64)-7654321076543210LL;
+	else
+		dst = alu32 ? 0x76543210ULL : 0x7edcba9876543210ULL;
+	src = alu32 ? 0x01234567ULL : 0x0123456789abcdefULL;
+	if (op == BPF_LSH || op == BPF_RSH || op == BPF_ARSH)
+		src &= 31;
+	alu_result(&res, dst, src, op, flags);
+	alu_result(&same, src, src, op, flags);
+	if (alu32) {
+		res = (__u32)res;
+		same = (__u32)same;
+	}
+
+	snprintf(b->desc, sizeof(b->desc), "alu%d_%s%s_x register pairs", alu32 ? 32 : 64,
+		 flags & F_SIGNED ? "s" : "", alu_name(op));
+	for (rd = BPF_REG_0; rd <= BPF_REG_9; rd++) {
+		for (rs = BPF_REG_0; rs <= BPF_REG_9; rs++) {
+			rc = scratch_reg(rd, rs);
+			k = batch_case(b, rc, rd == rs ? src : dst, src);
+			LD_IN(b, k, 0, rc, rd);
+			if (rs != rd)
+				LD_IN(b, k, 1, rc, rs);
+			EMIT(b, BPF_RAW_INSN((alu32 ? BPF_ALU : BPF_ALU64) | BPF_OP(op) | BPF_X,
+					     rd, rs, flags & F_SIGNED ? 1 : 0, 0));
+			ST_OUT(b, k, 0, rc, rd);
+			batch_expect(b, k, 0, rd == rs ? same : res);
+		}
+	}
+	batch_flush(b);
+}
+
+static void test_alu_reg_pairs(void)
+{
+	struct batch b;
+	int o, f;
+
+	if (!batch_init(&b))
+		return;
+	for (f = 0; f < 2; f++) {
+		for (o = 0; o < ARRAY_SIZE(alu_reg_ops); o++)
+			alu_reg_pairs(&b, alu_reg_ops[o], f ? F_ALU32 : 0);
+		alu_reg_pairs(&b, BPF_DIV, F_SIGNED | (f ? F_ALU32 : 0));
+		alu_reg_pairs(&b, BPF_MOD, F_SIGNED | (f ? F_ALU32 : 0));
+	}
+	batch_fini(&b);
+}
+
+/* Shifts for all shift counts, by immediate, by register and by the shifted register */
+static void test_shifts(void)
+{
+	static const __s64 vals[] = {
+		0x0123456789abcdefLL, /* dword > 0, word < 0 */
+		0xfedcba9876543210LL, /* dword < 0, word > 0 */
+		0xfedcba0198765432LL, /* dword < 0, word < 0 */
+		0x0123458967abcdefLL, /* dword > 0, word > 0 */
+	};
+	static const int ops[] = { BPF_LSH, BPF_RSH, BPF_ARSH };
+	struct batch b;
+	int o, f, v, imm, k;
+
+	if (!batch_init(&b))
+		return;
+	for (f = 0; f < 2; f++) {
+		int bits = f ? 32 : 64;
+
+		for (o = 0; o < ARRAY_SIZE(ops); o++) {
+			int op = ops[o];
+
+			snprintf(b.desc, sizeof(b.desc), "alu%d_%s all shift counts", bits,
+				 alu_name(op));
+			for (v = 0; v < ARRAY_SIZE(vals); v++) {
+				for (imm = 0; imm < bits; imm++) {
+					__u64 reg = vals[v], res;
+
+					if (f)
+						reg = op == BPF_ARSH ? (__u64)(__s32)reg :
+						      (__u32)reg;
+					alu_result(&res, reg, imm, op, 0);
+					if (f)
+						res = (__u32)res;
+
+					k = batch_case(&b, BPF_REG_3, vals[v], imm);
+					LD_IN(&b, k, 0, BPF_REG_3, BPF_REG_1);
+					if (f)
+						EMIT(&b, BPF_ALU32_IMM(op, BPF_REG_1, imm));
+					else
+						EMIT(&b, BPF_ALU64_IMM(op, BPF_REG_1, imm));
+					ST_OUT(&b, k, 0, BPF_REG_3, BPF_REG_1);
+					batch_expect(&b, k, 0, res);
+
+					k = batch_case(&b, BPF_REG_3, vals[v], imm);
+					LD_IN(&b, k, 0, BPF_REG_3, BPF_REG_1);
+					LD_IN(&b, k, 1, BPF_REG_3, BPF_REG_2);
+					if (f)
+						EMIT(&b, BPF_ALU32_REG(op, BPF_REG_1, BPF_REG_2));
+					else
+						EMIT(&b, BPF_ALU64_REG(op, BPF_REG_1, BPF_REG_2));
+					ST_OUT(&b, k, 0, BPF_REG_3, BPF_REG_1);
+					batch_expect(&b, k, 0, res);
+				}
+			}
+			/* The count in the shifted register */
+			for (imm = 0; imm < bits; imm++) {
+				__u64 res;
+
+				alu_result(&res, imm, imm, op, 0);
+				k = batch_case(&b, BPF_REG_3, imm, 0);
+				LD_IN(&b, k, 0, BPF_REG_3, BPF_REG_1);
+				if (f)
+					EMIT(&b, BPF_ALU32_REG(op, BPF_REG_1, BPF_REG_1));
+				else
+					EMIT(&b, BPF_ALU64_REG(op, BPF_REG_1, BPF_REG_1));
+				ST_OUT(&b, k, 0, BPF_REG_3, BPF_REG_1);
+				batch_expect(&b, k, 0, f ? (__u32)res : res);
+			}
+			batch_flush(&b);
+		}
+	}
+	batch_fini(&b);
+}
+
+/* Atomic operations on the stack for all magnitudes of memory and source operand */
+static const int atomic_ops[] = {
+	BPF_ADD, BPF_AND, BPF_OR, BPF_XOR,
+	BPF_ADD | BPF_FETCH, BPF_AND | BPF_FETCH, BPF_OR | BPF_FETCH, BPF_XOR | BPF_FETCH,
+	BPF_XCHG,
+};
+
+struct atomic_arg {
+	int op;
+	int size;
+};
+
+static void emit_atomic(struct batch *b, void *arg, __s64 dst, __s64 src)
+{
+	struct atomic_arg *a = arg;
+	bool w = a->size == BPF_W;
+	__u64 keep = 0x0123456789abcdefULL, res, fetch;
+	int k;
+
+	if (a->op == BPF_XCHG)
+		res = src;
+	else
+		alu_result(&res, w ? (__u32)dst : dst, w ? (__u32)src : src, BPF_OP(a->op), 0);
+	/* The source register gets the old value with fetch, keeps its own without */
+	fetch = a->op & BPF_FETCH ? (w ? (__u32)dst : dst) : src;
+
+	k = batch_case(b, BPF_REG_3, dst, src);
+	LD_IN(b, k, 0, BPF_REG_3, BPF_REG_1);
+	EMIT(b, BPF_STX_MEM(a->size, BPF_REG_10, BPF_REG_1, MEM_SLOT));
+	LD_IN(b, k, 1, BPF_REG_3, BPF_REG_2);
+	emit_ld_imm64(b, BPF_REG_0, keep);
+	EMIT(b, BPF_ATOMIC_OP(a->size, a->op, BPF_REG_10, BPF_REG_2, MEM_SLOT));
+	EMIT(b, BPF_LDX_MEM(a->size, BPF_REG_1, BPF_REG_10, MEM_SLOT));
+	ST_OUT(b, k, 0, BPF_REG_3, BPF_REG_1);
+	ST_OUT(b, k, 1, BPF_REG_3, BPF_REG_2);
+	ST_OUT(b, k, 2, BPF_REG_3, BPF_REG_0);
+	batch_expect(b, k, 0, w ? (__u32)res : res);
+	batch_expect(b, k, 1, fetch);
+	batch_expect(b, k, 2, keep);
+}
+
+static void emit_cmpxchg(struct batch *b, void *arg, __s64 dst, __s64 src)
+{
+	int size = *(int *)arg;
+	bool w = size == BPF_W;
+	__u64 old = w ? (__u32)dst : dst;
+	int k;
+
+	k = batch_case(b, BPF_REG_3, dst, src);
+	LD_IN(b, k, 0, BPF_REG_3, BPF_REG_1);
+	EMIT(b, BPF_STX_MEM(size, BPF_REG_10, BPF_REG_1, MEM_SLOT));
+	LD_IN(b, k, 1, BPF_REG_3, BPF_REG_2);
+	/* Mismatch: the memory keeps its value, r0 gets it */
+	EMIT(b, BPF_MOV64_REG(BPF_REG_0, BPF_REG_1));
+	EMIT(b, BPF_ALU64_IMM(BPF_XOR, BPF_REG_0, -1));
+	EMIT(b, BPF_ATOMIC_OP(size, BPF_CMPXCHG, BPF_REG_10, BPF_REG_2, MEM_SLOT));
+	ST_OUT(b, k, 0, BPF_REG_3, BPF_REG_0);
+	/* Match: the memory gets the source, r0 the old value */
+	EMIT(b, BPF_ATOMIC_OP(size, BPF_CMPXCHG, BPF_REG_10, BPF_REG_2, MEM_SLOT));
+	EMIT(b, BPF_LDX_MEM(size, BPF_REG_1, BPF_REG_10, MEM_SLOT));
+	ST_OUT(b, k, 1, BPF_REG_3, BPF_REG_1);
+	ST_OUT(b, k, 2, BPF_REG_3, BPF_REG_0);
+	batch_expect(b, k, 0, old);
+	batch_expect(b, k, 1, w ? (__u32)src : src);
+	batch_expect(b, k, 2, old);
+}
+
+static void test_atomics(void)
+{
+	static const int sizes[] = { BPF_DW, BPF_W };
+	struct batch b;
+	int o, s;
+
+	if (!batch_init(&b))
+		return;
+	for (s = 0; s < ARRAY_SIZE(sizes); s++) {
+		int size = sizes[s];
+
+		for (o = 0; o < ARRAY_SIZE(atomic_ops); o++) {
+			struct atomic_arg a = { atomic_ops[o], size };
+
+			snprintf(b.desc, sizeof(b.desc), "atomic%d_%s%s magnitudes",
+				 size == BPF_DW ? 64 : 32, alu_name(a.op),
+				 a.op == BPF_XCHG ? "" : a.op & BPF_FETCH ? "_fetch" : "");
+			fill_pattern(&b, &a, 64, 64, 0, 1, PATTERN_BLOCK2, emit_atomic);
+		}
+		snprintf(b.desc, sizeof(b.desc), "atomic%d_cmpxchg magnitudes",
+			 size == BPF_DW ? 64 : 32);
+		fill_pattern(&b, &size, 64, 64, 0, 1, PATTERN_BLOCK2, emit_cmpxchg);
+	}
+	batch_fini(&b);
+}
+
+/* Atomic operations for all combinations of pointer and source register */
+static void atomic_reg_pairs(struct batch *b, int size, int op)
+{
+	bool w = size == BPF_W;
+	__u64 mem, upd;
+	int rd, rs, rc, k, n;
+
+	if (w) {
+		mem = 0x01234567U;
+		upd = 0x76543210U;
+	} else {
+		mem = 0x0123456789abcdefULL;
+		upd = 0xfedcba9876543210ULL;
+	}
+
+	snprintf(b->desc, sizeof(b->desc), "atomic%d_%s%s register pairs", w ? 32 : 64,
+		 alu_name(op), op == BPF_XCHG || op == BPF_CMPXCHG ? "" :
+		 op & BPF_FETCH ? "_fetch" : "");
+	for (rd = BPF_REG_0; rd <= BPF_REG_9; rd++) {
+		for (rs = BPF_REG_0; rs <= BPF_REG_9; rs++) {
+			__u64 regs[10], old = mem, new, src, cmp;
+
+			/* The source would be the pointer, r0 the compare value */
+			if (rs == rd || (op == BPF_CMPXCHG && rd == BPF_REG_0))
+				continue;
+			rc = scratch_reg(rd, rs);
+			k = batch_case(b, rc, mem, upd);
+			/* Memory from in0, r0 inverted, source from in1, pointer */
+			LD_IN(b, k, 0, rc, rs);
+			EMIT(b, BPF_STX_MEM(size, BPF_REG_10, rs, MEM_SLOT));
+			LD_IN(b, k, 0, rc, BPF_REG_0);
+			EMIT(b, BPF_ALU64_IMM(BPF_XOR, BPF_REG_0, -1));
+			LD_IN(b, k, 1, rc, rs);
+			EMIT(b, BPF_MOV64_REG(rd, BPF_REG_10));
+			EMIT(b, BPF_ATOMIC_OP(size, op, rd, rs, MEM_SLOT));
+			/* r0 holds the pointer when it is the destination */
+			n = 0;
+			if (rd != BPF_REG_0)
+				ST_OUT(b, k, n++, rc, BPF_REG_0);
+			ST_OUT(b, k, n++, rc, rs);
+			EMIT(b, BPF_LDX_MEM(size, rs, BPF_REG_10, MEM_SLOT));
+			ST_OUT(b, k, n, rc, rs);
+
+			/* Model with the register aliasing of r0 */
+			regs[BPF_REG_0] = ~mem;
+			regs[rs] = upd;
+			src = w ? (__u32)regs[rs] : regs[rs];
+			if (op == BPF_XCHG) {
+				new = src;
+				regs[rs] = old;
+			} else if (op == BPF_CMPXCHG) {
+				cmp = w ? (__u32)regs[BPF_REG_0] : regs[BPF_REG_0];
+				new = cmp == old ? src : old;
+				regs[BPF_REG_0] = old;
+			} else {
+				alu_result(&new, old, src, BPF_OP(op), 0);
+				if (w)
+					new = (__u32)new;
+				if (op & BPF_FETCH)
+					regs[rs] = old;
+			}
+			n = 0;
+			if (rd != BPF_REG_0)
+				batch_expect(b, k, n++, regs[BPF_REG_0]);
+			batch_expect(b, k, n++, regs[rs]);
+			batch_expect(b, k, n, new);
+		}
+	}
+	batch_flush(b);
+}
+
+static void test_atomic_reg_pairs(void)
+{
+	static const int sizes[] = { BPF_DW, BPF_W };
+	struct batch b;
+	int o, s;
+
+	if (!batch_init(&b))
+		return;
+	for (s = 0; s < ARRAY_SIZE(sizes); s++) {
+		for (o = 0; o < ARRAY_SIZE(atomic_ops); o++)
+			atomic_reg_pairs(&b, sizes[s], atomic_ops[o]);
+		atomic_reg_pairs(&b, sizes[s], BPF_CMPXCHG);
+	}
+	batch_fini(&b);
+}
+
+/* A maximal chain of atomic adds on one stack slot */
+static void test_xadd_chain(void)
+{
+	static const int sizes[] = { BPF_DW, BPF_W };
+	LIBBPF_OPTS(bpf_test_run_opts, opts);
+	struct bpf_insn *insns;
+	int len = BPF_MAXINSNS, s, i, fd;
+
+	insns = malloc(len * sizeof(*insns));
+	if (!ASSERT_OK_PTR(insns, "insns"))
+		return;
+	for (s = 0; s < ARRAY_SIZE(sizes); s++) {
+		insns[0] = BPF_MOV32_IMM(BPF_REG_0, 1);
+		insns[1] = BPF_ST_MEM(sizes[s], BPF_REG_10, -40, 42);
+		for (i = 2; i < len - 2; i++)
+			insns[i] = BPF_STX_XADD(sizes[s], BPF_REG_10, BPF_REG_0, -40);
+		insns[len - 2] = BPF_LDX_MEM(sizes[s], BPF_REG_0, BPF_REG_10, -40);
+		insns[len - 1] = BPF_EXIT_INSN();
+
+		fd = load_prog(insns, len, "xadd chain");
+		if (fd < 0)
+			break;
+		if (ASSERT_OK(bpf_prog_test_run_opts(fd, &opts), "xadd chain run"))
+			ASSERT_EQ(opts.retval, 42 + len - 4, "xadd chain result");
+		close(fd);
+	}
+	free(insns);
+}
+
+/* 64-bit immediate loads for all magnitudes and byte patterns */
+static void ld_imm64_case(struct batch *b, __u64 imm)
+{
+	int k = batch_case(b, BPF_REG_3, imm, 0);
+
+	emit_ld_imm64(b, BPF_REG_1, imm);
+	ST_OUT(b, k, 0, BPF_REG_3, BPF_REG_1);
+	batch_expect(b, k, 0, imm);
+}
+
+static void test_ld_imm64(void)
+{
+	static const struct {
+		__u8 base1, mask1, base2, mask2;
+	} bytes[] = {
+		{ 0, 0xff, 0xff, 0xff },	/* checker */
+		{ 1, 0x81, 0x80, 0x80 },	/* positive and negative */
+		{ 1, 0x81, 0, 0xff },		/* positive and zero */
+		{ 0x80, 0x80, 0, 0xff },	/* negative and zero */
+	};
+	int block = 64, bit, adj, sign, p, pattern, index;
+	struct batch b;
+
+	if (!batch_init(&b))
+		return;
+	snprintf(b.desc, sizeof(b.desc), "ld_imm64 magnitudes");
+	for (bit = 0; bit <= 62; bit++)
+		for (adj = -block / 2; adj < block / 2; adj++)
+			for (sign = -1; sign <= 1; sign += 2)
+				ld_imm64_case(&b, sign * ((1LL << bit) + adj));
+	batch_flush(&b);
+
+	for (p = 0; p < ARRAY_SIZE(bytes); p++) {
+		__u32 rand = 1;
+
+		snprintf(b.desc, sizeof(b.desc), "ld_imm64 byte pattern %d", p);
+		for (pattern = 0; pattern < 256; pattern++) {
+			__u64 imm = 0;
+
+			for (index = 0; index < 8; index++) {
+				int byte;
+
+				if (pattern & (1 << index))
+					byte = (bytes[p].base1 & bytes[p].mask1) |
+					       (rand & ~bytes[p].mask1);
+				else
+					byte = (bytes[p].base2 & bytes[p].mask2) |
+					       (rand & ~bytes[p].mask2);
+				imm = (imm << 8) | (__u8)byte;
+			}
+			rand = rand * 1664525 + 1013904223;
+			ld_imm64_case(&b, imm);
+		}
+		batch_flush(&b);
+	}
+	batch_fini(&b);
+}
+
+/* Conditional jumps with an immediate and with a register for all magnitudes */
+static const int jmp_ops[] = {
+	BPF_JSET, BPF_JEQ, BPF_JNE, BPF_JGT, BPF_JGE, BPF_JLT, BPF_JLE,
+	BPF_JSGT, BPF_JSGE, BPF_JSLT, BPF_JSLE,
+};
+
+static bool jmp_match(__s64 v1, __s64 v2, __u8 op)
+{
+	switch (op) {
+	case BPF_JSET:
+		return !!(v1 & v2);
+	case BPF_JEQ:
+		return v1 == v2;
+	case BPF_JNE:
+		return v1 != v2;
+	case BPF_JGT:
+		return (__u64)v1 > (__u64)v2;
+	case BPF_JGE:
+		return (__u64)v1 >= (__u64)v2;
+	case BPF_JLT:
+		return (__u64)v1 < (__u64)v2;
+	case BPF_JLE:
+		return (__u64)v1 <= (__u64)v2;
+	case BPF_JSGT:
+		return v1 > v2;
+	case BPF_JSGE:
+		return v1 >= v2;
+	case BPF_JSLT:
+		return v1 < v2;
+	case BPF_JSLE:
+		return v1 <= v2;
+	}
+	return false;
+}
+
+struct jmp_arg {
+	int op;
+	bool is32;
+	bool reg;
+};
+
+static void emit_jmp(struct batch *b, void *arg, __s64 dst, __s64 src)
+{
+	struct jmp_arg *a = arg;
+	bool match;
+	int k;
+
+	if (a->is32)
+		match = jmp_match((__s32)dst, (__s32)src, a->op);
+	else
+		match = jmp_match(dst, a->reg ? src : (__s32)src, a->op);
+
+	k = batch_case(b, BPF_REG_3, dst, src);
+	LD_IN(b, k, 0, BPF_REG_3, BPF_REG_1);
+	if (a->reg)
+		LD_IN(b, k, 1, BPF_REG_3, BPF_REG_2);
+	EMIT(b, BPF_MOV64_IMM(BPF_REG_4, 1));
+	if (a->reg && a->is32)
+		EMIT(b, BPF_JMP32_REG(a->op, BPF_REG_1, BPF_REG_2, 1));
+	else if (a->reg)
+		EMIT(b, BPF_JMP_REG(a->op, BPF_REG_1, BPF_REG_2, 1));
+	else if (a->is32)
+		EMIT(b, BPF_JMP32_IMM(a->op, BPF_REG_1, src, 1));
+	else
+		EMIT(b, BPF_JMP_IMM(a->op, BPF_REG_1, src, 1));
+	EMIT(b, BPF_MOV64_IMM(BPF_REG_4, 0));
+	ST_OUT(b, k, 0, BPF_REG_3, BPF_REG_4);
+	batch_expect(b, k, 0, match);
+}
+
+static void test_jmp_magnitudes(bool reg)
+{
+	struct batch b;
+	int o, f;
+
+	if (!batch_init(&b))
+		return;
+	for (f = 0; f < 2; f++) {
+		for (o = 0; o < ARRAY_SIZE(jmp_ops); o++) {
+			struct jmp_arg a = { jmp_ops[o], f, reg };
+
+			snprintf(b.desc, sizeof(b.desc), "jmp%s_%s_%c magnitudes", f ? "32" : "",
+				 jmp_name(a.op), reg ? 'x' : 'k');
+			if (reg)
+				fill_pattern(&b, &a, 64, 64, 0, 1, PATTERN_BLOCK2, emit_jmp);
+			else
+				fill_pattern(&b, &a, 64, 32, PATTERN_BLOCK1, 8, PATTERN_BLOCK2,
+					     emit_jmp);
+		}
+	}
+	batch_fini(&b);
+}
+
+static void test_jmp_imm(void)
+{
+	test_jmp_magnitudes(false);
+}
+
+static void test_jmp_reg(void)
+{
+	test_jmp_magnitudes(true);
+}
+
+/* A conditional jump on two registers, with the operands swapped for n == 1 */
+static void jmp_reg_pair(struct batch *b, bool is32, int op, int rd, int rs, int n)
+{
+	const __u64 a = 0x7edcba9876543210ULL, c = 0x0123456789abcdefULL;
+	__u64 v1 = n ? c : a, v2 = n ? a : c;
+	int rc, rt, k;
+	bool match;
+
+	/* Two scratch registers besides the operands */
+	rc = scratch_reg(rd, rs);
+	for (rt = BPF_REG_1; rt < BPF_REG_9; rt++)
+		if (rt != rd && rt != rs && rt != rc)
+			break;
+	if (rd == rs)
+		v2 = v1;
+	match = is32 ? jmp_match((__s32)v1, (__s32)v2, op) : jmp_match(v1, v2, op);
+
+	k = batch_case(b, rc, v1, v2);
+	LD_IN(b, k, 0, rc, rd);
+	if (rs != rd)
+		LD_IN(b, k, 1, rc, rs);
+	EMIT(b, BPF_MOV64_IMM(rt, 1));
+	if (is32)
+		EMIT(b, BPF_JMP32_REG(op, rd, rs, 1));
+	else
+		EMIT(b, BPF_JMP_REG(op, rd, rs, 1));
+	EMIT(b, BPF_MOV64_IMM(rt, 0));
+	ST_OUT(b, k, 0, rc, rt);
+	batch_expect(b, k, 0, match);
+}
+
+/* Conditional jumps for all combinations of operand registers, taken and not */
+static void test_jmp_reg_pairs(void)
+{
+	struct batch b;
+	int o, f, rd, rs, n;
+
+	if (!batch_init(&b))
+		return;
+	for (f = 0; f < 2; f++) {
+		for (o = 0; o < ARRAY_SIZE(jmp_ops); o++) {
+			snprintf(b.desc, sizeof(b.desc), "jmp%s_%s_x register pairs",
+				 f ? "32" : "", jmp_name(jmp_ops[o]));
+			for (rd = BPF_REG_0; rd <= BPF_REG_9; rd++)
+				for (rs = BPF_REG_0; rs <= BPF_REG_9; rs++)
+					for (n = 0; n < 2; n++)
+						jmp_reg_pair(&b, f, jmp_ops[o], rd, rs, n);
+			batch_flush(&b);
+		}
+	}
+	batch_fini(&b);
+}
+
+/* The offset of a jump instruction, which the 32-bit unconditional jump keeps in imm */
+static void set_jmp_off(struct bpf_insn *insn, bool ja32, int off)
+{
+	if (ja32)
+		insn->imm = off;
+	else
+		insn->off = off;
+}
+
+static struct bpf_insn jmp_insn(bool ja32)
+{
+	return ja32 ? BPF_RAW_INSN(BPF_JMP32 | BPF_JA, 0, 0, 0, 0) : BPF_JMP_IMM(BPF_JA, 0, 0, 0);
+}
+
+/*
+ * Taken jumps over regions of doubling length, forward or backward, up to
+ * the maximal offset of the jump: 16 bits, or 2^17 for the 32-bit
+ * unconditional jump. The not taken path of a conditional jump and the
+ * guard of an unconditional one lead to an exit with the region number, so
+ * the verifier sees every instruction reachable and a jump landing anywhere
+ * else than on its target fails the run.
+ */
+static void staggered_jumps(const struct bpf_insn *jmp, __s64 r1, __s64 r2, bool backward,
+			    const char *desc)
+{
+	bool ja32 = BPF_CLASS(jmp->code) == BPF_JMP32 && BPF_OP(jmp->code) == BPF_JA;
+	bool ja = BPF_OP(jmp->code) == BPF_JA;
+	struct { __u64 r1, r2; } ctx = { r1, r2 };
+	LIBBPF_OPTS(bpf_test_run_opts, opts,
+		.ctx_in = &ctx,
+		.ctx_size_in = sizeof(ctx),
+	);
+	int max = ja32 ? 1 << 17 : INT16_MAX;
+	int len = 128 + 2 * max, i = 0, n = 0, gap, fd;
+	struct bpf_insn *insns;
+
+	insns = malloc(len * sizeof(*insns));
+	if (!ASSERT_OK_PTR(insns, "insns"))
+		return;
+	insns[i++] = BPF_LDX_MEM(BPF_DW, BPF_REG_2, BPF_REG_1, 8);
+	insns[i++] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
+	insns[i++] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_0, 0);
+	for (gap = backward ? 4 : 2; gap <= max; gap = gap < max / 2 ? gap * 2 : max) {
+		int k, a, t, x, g, j;
+
+		if (backward) {
+			/*
+			 * Over the region to its guard and jump, which comes back
+			 * to the start of the region, from where it leads on to
+			 * the next one.
+			 */
+			a = i++;
+			t = i;
+			for (k = 0; k < gap - 3; k++)
+				insns[i++] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_3, 0);
+			x = i++;
+			g = i;
+			if (ja)
+				insns[i++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_2, 0, 1);
+			j = i;
+			insns[i] = *jmp;
+			set_jmp_off(&insns[i++], ja32, t - (j + 1));
+			insns[i++] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_0, ++n);
+			insns[i++] = BPF_EXIT_INSN();
+			insns[a] = jmp_insn(ja32);
+			set_jmp_off(&insns[a], ja32, g - (a + 1));
+			insns[x] = jmp_insn(ja32);
+			set_jmp_off(&insns[x], ja32, i - (x + 1));
+		} else {
+			/* An unconditional jump needs a way into its region */
+			if (ja)
+				insns[i++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_2, 0, 1);
+			insns[i] = *jmp;
+			set_jmp_off(&insns[i++], ja32, gap);
+			insns[i++] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_0, ++n);
+			for (k = 0; k < gap - 2; k++)
+				insns[i++] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_3, 0);
+			insns[i++] = BPF_EXIT_INSN();
+		}
+		if (gap == max)
+			break;
+	}
+	insns[i++] = BPF_EXIT_INSN();
+	if (!ASSERT_LE(i, len, "insn count"))
+		goto out;
+
+	fd = load_prog(insns, i, desc);
+	if (fd >= 0) {
+		if (ASSERT_OK(bpf_prog_test_run_opts(fd, &opts), desc))
+			ASSERT_EQ(opts.retval, 0, desc);
+		close(fd);
+	}
+out:
+	free(insns);
+}
+
+static void test_staggered_jumps(void)
+{
+	/* A representative set, with operands which make the jump taken */
+	static const struct {
+		const char *desc;
+		struct bpf_insn jmp;
+		__s64 r1, r2;
+	} kinds[] = {
+		{ "staggered ja",
+		  BPF_JMP_IMM(BPF_JA, 0, 0, 0), 0, 1 },
+		{ "staggered gotol",
+		  BPF_RAW_INSN(BPF_JMP32 | BPF_JA, 0, 0, 0, 0), 0, 1 },
+		{ "staggered jmp_jeq_k",
+		  BPF_JMP_IMM(BPF_JEQ, BPF_REG_1, 1234, 0), 1234, 0 },
+		{ "staggered jmp_jne_x",
+		  BPF_JMP_REG(BPF_JNE, BPF_REG_1, BPF_REG_2, 0), 4321, 1234 },
+		{ "staggered jmp_jset_k",
+		  BPF_JMP_IMM(BPF_JSET, BPF_REG_1, 0x82, 0), 0x86, 0 },
+		{ "staggered jmp_jsgt_x",
+		  BPF_JMP_REG(BPF_JSGT, BPF_REG_1, BPF_REG_2, 0), -1, -2 },
+		{ "staggered jmp32_jlt_k",
+		  BPF_JMP32_IMM(BPF_JLT, BPF_REG_1, 0x80000000, 0), 1234, 0 },
+		{ "staggered jmp32_jsge_x",
+		  BPF_JMP32_REG(BPF_JSGE, BPF_REG_1, BPF_REG_2, 0), -2, -2 },
+	};
+	char desc[64];
+	int i, d;
+
+	for (i = 0; i < ARRAY_SIZE(kinds); i++) {
+		for (d = 0; d < 2; d++) {
+			snprintf(desc, sizeof(desc), "%s %s", kinds[i].desc,
+				 d ? "backward" : "forward");
+			staggered_jumps(&kinds[i].jmp, kinds[i].r1, kinds[i].r2, d, desc);
+		}
+	}
+}
+
+/*
+ * The pattern sweeps: one program per pattern and register choice, run
+ * once per input with the operands in the ctx and the result handed back
+ * through it.
+ */
+struct pat_ctx {
+	__u64 in0;
+	__u64 in1;
+	__u64 res;
+};
+
+#define IN0	offsetof(struct pat_ctx, in0)
+#define IN1	offsetof(struct pat_ctx, in1)
+#define RES	offsetof(struct pat_ctx, res)
+
+/* r6 holds the ctx */
+static const int pat_regs[] = {
+	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4,
+	BPF_REG_5, BPF_REG_7, BPF_REG_8, BPF_REG_9,
+};
+
+/* The second register of a pattern: the same one, the next and a far one */
+#define NR_PAIRS 3
+static const int pair_off[NR_PAIRS] = { 0, 1, 5 };
+
+static int pair_reg(int i, int k)
+{
+	return pat_regs[(i + pair_off[k]) % ARRAY_SIZE(pat_regs)];
+}
+
+static const __u64 inputs[] = {
+	0, 0x1122334455667788ULL, 0xfedcba9876543210ULL, 0x80, 0xffffffffffffff7fULL,
+};
+
+struct prog {
+	struct bpf_insn insns[16];
+	int cnt;
+};
+
+static void prog_start(struct prog *p)
+{
+	p->cnt = 0;
+	EMIT(p, BPF_MOV64_REG(BPF_REG_6, BPF_REG_1));
+}
+
+/* Hand the result in reg back and return */
+static void prog_end(struct prog *p, int reg)
+{
+	EMIT(p, BPF_STX_MEM(BPF_DW, BPF_REG_6, reg, RES));
+	EMIT(p, BPF_MOV64_IMM(BPF_REG_0, 0));
+	EMIT(p, BPF_EXIT_INSN());
+}
+
+static int prog_load(struct prog *p, const char *desc)
+{
+	LIBBPF_OPTS(bpf_prog_load_opts, lopts,
+		.prog_flags = BPF_F_SLEEPABLE,
+		.log_buf = log,
+		.log_size = sizeof(log),
+	);
+	int fd;
+
+	fd = bpf_prog_load(BPF_PROG_TYPE_SYSCALL, NULL, "GPL", p->insns, p->cnt, &lopts);
+	if (!ASSERT_GE(fd, 0, desc))
+		fprintf(stderr, "%s", log);
+	return fd;
+}
+
+static void prog_run(int fd, __u64 in0, __u64 in1, __u64 expected, const char *desc)
+{
+	struct pat_ctx ctx = { .in0 = in0, .in1 = in1 };
+	LIBBPF_OPTS(bpf_test_run_opts, opts,
+		.ctx_in = &ctx,
+		.ctx_size_in = sizeof(ctx),
+	);
+	char buf[128];
+
+	snprintf(buf, sizeof(buf), "%s in0=0x%llx in1=0x%llx", desc, in0, in1);
+	if (ASSERT_OK(bpf_prog_test_run_opts(fd, &opts), buf))
+		ASSERT_EQ(ctx.res, expected, buf);
+}
+
+static int size_bits(int size)
+{
+	switch (size) {
+	case BPF_B:
+		return 8;
+	case BPF_H:
+		return 16;
+	case BPF_W:
+		return 32;
+	default:
+		return 64;
+	}
+}
+
+/* The first size bytes of v in memory, as a load of that size reads them */
+static __u64 head_bytes(__u64 v, int size)
+{
+	int bits = size_bits(size);
+
+	if (bits == 64)
+		return v;
+#if __BYTE_ORDER == __BIG_ENDIAN
+	return v >> (64 - bits);
+#else
+	return v & ((1ULL << bits) - 1);
+#endif
+}
+
+/* v with its first size bytes in memory replaced by those of w */
+static __u64 head_merge(__u64 v, __u64 w, int size)
+{
+	int bits = size_bits(size);
+	__u64 mask;
+
+	if (bits == 64)
+		return w;
+	mask = (1ULL << bits) - 1;
+#if __BYTE_ORDER == __BIG_ENDIAN
+	return (v & ~(mask << (64 - bits))) | ((w & mask) << (64 - bits));
+#else
+	return (v & ~mask) | (w & mask);
+#endif
+}
+
+static void test_ldst_zero_off(void)
+{
+	static const int sizes[] = { BPF_B, BPF_H, BPF_W, BPF_DW };
+	static const int aops[] = {
+		BPF_ADD, BPF_ADD | BPF_FETCH, BPF_OR, BPF_XCHG, BPF_CMPXCHG,
+	};
+	static const __s32 imms[] = { 0x5a, -1 };
+	struct prog p;
+	char desc[64];
+	int b, k, s, j, fd;
+
+	for (b = 0; b < ARRAY_SIZE(pat_regs); b++) {
+		int rb = pat_regs[b];
+
+		for (s = 0; s < ARRAY_SIZE(sizes); s++) {
+			int size = sizes[s];
+
+			for (k = 0; k < NR_PAIRS; k++) {
+				int rd = pair_reg(b, k);
+
+				/* Load with a zero offset, also into the base */
+				prog_start(&p);
+				EMIT(&p, BPF_MOV64_REG(rb, BPF_REG_6));
+				EMIT(&p, BPF_LDX_MEM(size, rd, rb, 0));
+				prog_end(&p, rd);
+				snprintf(desc, sizeof(desc), "ldx size=%d base=r%d dst=r%d",
+					 size, rb, rd);
+				fd = prog_load(&p, desc);
+				if (fd < 0)
+					return;
+				for (j = 0; j < ARRAY_SIZE(inputs); j++)
+					prog_run(fd, inputs[j], 0,
+						 head_bytes(inputs[j], size), desc);
+				close(fd);
+
+				/* Sign extending load with a zero offset from the stack */
+				if (size != BPF_DW) {
+					prog_start(&p);
+					EMIT(&p, BPF_LDX_MEM(BPF_DW, rd, BPF_REG_6, IN0));
+					EMIT(&p, BPF_STX_MEM(BPF_DW, BPF_REG_10, rd, -8));
+					EMIT(&p, BPF_MOV64_REG(rb, BPF_REG_10));
+					EMIT(&p, BPF_ALU64_IMM(BPF_ADD, rb, -8));
+					EMIT(&p, BPF_RAW_INSN(BPF_LDX | BPF_MEMSX | size,
+							      rd, rb, 0, 0));
+					prog_end(&p, rd);
+					snprintf(desc, sizeof(desc),
+						 "ldsx size=%d base=r%d dst=r%d", size, rb, rd);
+					fd = prog_load(&p, desc);
+					if (fd < 0)
+						return;
+					for (j = 0; j < ARRAY_SIZE(inputs); j++) {
+						__s64 v = head_bytes(inputs[j], size);
+
+						v = size == BPF_B ? (__s8)v :
+						    size == BPF_H ? (__s16)v : (__s32)v;
+						prog_run(fd, inputs[j], 0, v, desc);
+					}
+					close(fd);
+				}
+
+				if (rd == rb)
+					continue;
+				/* Store with a zero offset over in0 */
+				prog_start(&p);
+				EMIT(&p, BPF_MOV64_REG(rb, BPF_REG_6));
+				EMIT(&p, BPF_LDX_MEM(BPF_DW, rd, BPF_REG_6, IN1));
+				EMIT(&p, BPF_STX_MEM(size, rb, rd, 0));
+				EMIT(&p, BPF_LDX_MEM(BPF_DW, rd, BPF_REG_6, IN0));
+				prog_end(&p, rd);
+				snprintf(desc, sizeof(desc), "stx size=%d base=r%d src=r%d",
+					 size, rb, rd);
+				fd = prog_load(&p, desc);
+				if (fd < 0)
+					return;
+				for (j = 0; j < ARRAY_SIZE(inputs); j++) {
+					__u64 in1 = inputs[(j + 1) % ARRAY_SIZE(inputs)];
+
+					prog_run(fd, inputs[j], in1,
+						 head_merge(inputs[j], in1, size), desc);
+				}
+				close(fd);
+			}
+
+			/* Store an immediate with a zero offset into a zeroed stack slot */
+			for (k = 0; k < ARRAY_SIZE(imms); k++) {
+				int rd = pair_reg(b, 1);
+
+				prog_start(&p);
+				EMIT(&p, BPF_ST_MEM(BPF_DW, BPF_REG_10, -8, 0));
+				EMIT(&p, BPF_MOV64_REG(rb, BPF_REG_10));
+				EMIT(&p, BPF_ALU64_IMM(BPF_ADD, rb, -8));
+				EMIT(&p, BPF_ST_MEM(size, rb, 0, imms[k]));
+				EMIT(&p, BPF_LDX_MEM(BPF_DW, rd, BPF_REG_10, -8));
+				prog_end(&p, rd);
+				snprintf(desc, sizeof(desc), "st size=%d base=r%d imm=%d",
+					 size, rb, imms[k]);
+				fd = prog_load(&p, desc);
+				if (fd < 0)
+					return;
+				prog_run(fd, 0, 0,
+					 head_merge(0, (__u64)(__s64)imms[k], size), desc);
+				close(fd);
+			}
+
+			/* Atomics with a zero offset on a stack slot holding in0 */
+			for (k = 0; k < ARRAY_SIZE(aops); k++) {
+				int rd = pair_reg(b, 1), op = aops[k];
+
+				if (size == BPF_B || size == BPF_H)
+					break;
+				/* cmpxchg compares with r0 */
+				if (op == BPF_CMPXCHG && (rb == BPF_REG_0 || rd == BPF_REG_0))
+					continue;
+				prog_start(&p);
+				EMIT(&p, BPF_LDX_MEM(BPF_DW, rd, BPF_REG_6, IN0));
+				EMIT(&p, BPF_STX_MEM(BPF_DW, BPF_REG_10, rd, -8));
+				EMIT(&p, BPF_LDX_MEM(BPF_DW, rd, BPF_REG_6, IN1));
+				EMIT(&p, BPF_MOV64_REG(rb, BPF_REG_10));
+				EMIT(&p, BPF_ALU64_IMM(BPF_ADD, rb, -8));
+				if (op == BPF_CMPXCHG)
+					EMIT(&p, BPF_LDX_MEM(size, BPF_REG_0, BPF_REG_10, -8));
+				EMIT(&p, BPF_ATOMIC_OP(size, op, rb, rd, 0));
+				EMIT(&p, BPF_LDX_MEM(BPF_DW, rd, BPF_REG_10, -8));
+				prog_end(&p, rd);
+				snprintf(desc, sizeof(desc), "atomic 0x%x size=%d base=r%d src=r%d",
+					 op, size, rb, rd);
+				fd = prog_load(&p, desc);
+				if (fd < 0)
+					return;
+				for (j = 0; j < ARRAY_SIZE(inputs); j++) {
+					__u64 in1 = inputs[(j + 1) % ARRAY_SIZE(inputs)];
+					__u64 v = head_bytes(inputs[j], size);
+					/* The source is the low half, whichever the byte order */
+					__u64 w = size == BPF_W ? (__u32)in1 : in1;
+					__u64 r = BPF_OP(op) == BPF_ADD ? v + w :
+						  BPF_OP(op) == BPF_OR ? v | w : w;
+
+					prog_run(fd, inputs[j], in1,
+						 head_merge(inputs[j], r, size), desc);
+				}
+				close(fd);
+			}
+		}
+	}
+}
+
+/*
+ * Loads, stores and stores of an immediate with the offsets around the
+ * limits of the short displacement forms, negative, large and unaligned
+ * ones, with every register as base. The memory is an array map value with
+ * the base register pointing at its middle, the loads hand their results
+ * back through a second value and the stores are checked against a copy
+ * kept here. The unaligned offsets are left out where the verifier insists
+ * on aligned accesses.
+ */
+#define MEM_SIZE	65536
+#define MEM_BASE	(MEM_SIZE / 2)
+#define MEM_KEY		0
+#define RES_KEY		1
+#define SLOT_KEY	-4	/* stack slots: map key, results and base pointer */
+#define SLOT_RES	-16
+#define SLOT_BASE	-24
+#define STORE_VAL	0x8899aabbccddeeffULL
+
+struct off_prog {
+	struct bpf_insn insns[128];
+	int cnt;
+};
+
+/* The map holding the memory and the results, a copy of the memory and a buffer */
+struct off_mem {
+	int map_fd;
+	__u8 *mem, *exp, *res;
+};
+
+enum { K_LDX, K_LDSX, K_STX, K_ST };
+
+/* The offsets for an access of size, aligned unless unaligned ones are ok */
+static int offsets_for(int size, bool unaligned, int *off)
+{
+	int n = size_bits(size) / 8, cnt = 0;
+
+	off[cnt++] = n;
+	off[cnt++] = 128 - n;
+	off[cnt++] = 128;
+	off[cnt++] = 256 - n;
+	off[cnt++] = 256;
+	off[cnt++] = 4096;
+	off[cnt++] = MEM_BASE - n;
+	off[cnt++] = -n;
+	off[cnt++] = -128;
+	off[cnt++] = -128 - n;
+	off[cnt++] = -256;
+	off[cnt++] = -4096;
+	off[cnt++] = -MEM_BASE;
+	if (n > 1 && unaligned) {
+		off[cnt++] = 13;
+		off[cnt++] = 127;
+		off[cnt++] = -13;
+		off[cnt++] = -129;
+	}
+	return cnt;
+}
+
+/* The bytes a store of size writes from the register value v */
+static void store_bytes(__u8 *dst, __u64 v, int size)
+{
+	int n = size_bits(size) / 8;
+
+#if __BYTE_ORDER == __BIG_ENDIAN
+	memcpy(dst, (__u8 *)&v + 8 - n, n);
+#else
+	memcpy(dst, &v, n);
+#endif
+}
+
+/* The value a load of size reads from the bytes at src */
+static __u64 load_bytes(const __u8 *src, int size)
+{
+	__u64 v = 0;
+
+	memcpy(&v, src, size_bits(size) / 8);
+	return head_bytes(v, size);
+}
+
+/* A register that is neither of the two given ones */
+static int other_reg(int r1, int r2)
+{
+	int i;
+
+	for (i = 0; i < ARRAY_SIZE(pat_regs); i++)
+		if (pat_regs[i] != r1 && pat_regs[i] != r2)
+			return pat_regs[i];
+	return BPF_REG_9;
+}
+
+/* Look up the value of key into r0, exit with 1 when the lookup fails */
+static void off_prog_lookup(struct off_prog *p, int map_fd, int key)
+{
+	EMIT(p, BPF_ST_MEM(BPF_W, BPF_REG_10, SLOT_KEY, key));
+	EMIT(p, BPF_RAW_INSN(BPF_LD | BPF_DW | BPF_IMM, BPF_REG_1, BPF_PSEUDO_MAP_FD, 0, map_fd));
+	EMIT(p, BPF_RAW_INSN(0, 0, 0, 0, 0));
+	EMIT(p, BPF_MOV64_REG(BPF_REG_2, BPF_REG_10));
+	EMIT(p, BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, SLOT_KEY));
+	EMIT(p, BPF_EMIT_CALL(BPF_FUNC_map_lookup_elem));
+	EMIT(p, BPF_JMP_IMM(BPF_JNE, BPF_REG_0, 0, 2));
+	EMIT(p, BPF_MOV64_IMM(BPF_REG_0, 1));
+	EMIT(p, BPF_EXIT_INSN());
+}
+
+/* rb points at the middle of the memory, the results value is spilled */
+static void off_prog_start(struct off_prog *p, int map_fd, int rb)
+{
+	p->cnt = 0;
+	off_prog_lookup(p, map_fd, RES_KEY);
+	EMIT(p, BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_0, SLOT_RES));
+	off_prog_lookup(p, map_fd, MEM_KEY);
+	EMIT(p, BPF_ALU64_IMM(BPF_ADD, BPF_REG_0, MEM_BASE));
+	EMIT(p, BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_0, SLOT_BASE));
+	if (rb != BPF_REG_0)
+		EMIT(p, BPF_MOV64_REG(rb, BPF_REG_0));
+}
+
+static int off_prog_load(struct off_prog *p, const char *desc, bool quiet)
+{
+	LIBBPF_OPTS(bpf_prog_load_opts, lopts,
+		.prog_flags = BPF_F_SLEEPABLE,
+		.log_buf = log,
+		.log_size = sizeof(log),
+	);
+	int fd;
+
+	EMIT(p, BPF_MOV64_IMM(BPF_REG_0, 0));
+	EMIT(p, BPF_EXIT_INSN());
+	fd = bpf_prog_load(BPF_PROG_TYPE_SYSCALL, NULL, "GPL", p->insns, p->cnt, &lopts);
+	if (quiet)
+		return fd;
+	if (!ASSERT_GE(fd, 0, desc))
+		fprintf(stderr, "%s", log);
+	return fd;
+}
+
+static int off_prog_run(int fd, const char *desc)
+{
+	LIBBPF_OPTS(bpf_test_run_opts, opts);
+	int err;
+
+	err = bpf_prog_test_run_opts(fd, &opts);
+	close(fd);
+	if (!ASSERT_OK(err, desc) || !ASSERT_EQ(opts.retval, 0, desc))
+		return -1;
+	return 0;
+}
+
+/* Whether the verifier accepts a halfword load from an odd offset */
+static bool unaligned_ok(int map_fd)
+{
+	struct off_prog p;
+	int fd;
+
+	off_prog_start(&p, map_fd, BPF_REG_1);
+	EMIT(&p, BPF_LDX_MEM(BPF_H, BPF_REG_0, BPF_REG_1, 1));
+	fd = off_prog_load(&p, "unaligned probe", true);
+	if (fd < 0)
+		return false;
+	close(fd);
+	return true;
+}
+
+/* One program loading from all the offsets of size through rb into rd */
+static void load_offsets(struct off_mem *m, int kind, int size, int rb, int rd,
+			 const int *off, int nr)
+{
+	__u32 mem_key = MEM_KEY, res_key = RES_KEY;
+	int rs = other_reg(rb, rd), fd, i;
+	__u64 *res = (__u64 *)m->res;
+	int map_fd = m->map_fd;
+	struct off_prog p;
+	char desc[64];
+
+	off_prog_start(&p, map_fd, rb);
+	for (i = 0; i < nr; i++) {
+		if (rd == rb)
+			EMIT(&p, BPF_LDX_MEM(BPF_DW, rb, BPF_REG_10, SLOT_BASE));
+		if (kind == K_LDX)
+			EMIT(&p, BPF_LDX_MEM(size, rd, rb, off[i]));
+		else
+			EMIT(&p, BPF_RAW_INSN(BPF_LDX | BPF_MEMSX | size, rd, rb, off[i], 0));
+		EMIT(&p, BPF_LDX_MEM(BPF_DW, rs, BPF_REG_10, SLOT_RES));
+		EMIT(&p, BPF_STX_MEM(BPF_DW, rs, rd, i * 8));
+	}
+	snprintf(desc, sizeof(desc), "%s size=%d base=r%d dst=r%d",
+		 kind == K_LDX ? "ldx" : "ldsx", size, rb, rd);
+	if (!ASSERT_OK(bpf_map_update_elem(map_fd, &mem_key, m->mem, 0), desc))
+		return;
+	fd = off_prog_load(&p, desc, false);
+	if (fd < 0)
+		return;
+	if (off_prog_run(fd, desc) || !ASSERT_OK(bpf_map_lookup_elem(map_fd, &res_key, res), desc))
+		return;
+	for (i = 0; i < nr; i++) {
+		__u64 v = load_bytes(m->mem + MEM_BASE + off[i], size);
+
+		if (kind == K_LDSX)
+			v = size == BPF_B ? (__s8)v : size == BPF_H ? (__s16)v : (__s32)v;
+		if (res[i] != v) {
+			snprintf(desc, sizeof(desc), "%s size=%d base=r%d dst=r%d off=%d",
+				 kind == K_LDX ? "ldx" : "ldsx", size, rb, rd, off[i]);
+			ASSERT_EQ(res[i], v, desc);
+		}
+	}
+}
+
+/* One program storing rd, or the immediate imm when rd < 0, at all the offsets */
+static void store_offsets(struct off_mem *m, int size, int rb, int rd, __s32 imm,
+			  const int *off, int nr)
+{
+	__u64 val = rd >= 0 ? STORE_VAL : (__u64)(__s64)imm;
+	__u8 *mem = m->mem, *exp = m->exp, *res = m->res;
+	__u32 mem_key = MEM_KEY;
+	int map_fd = m->map_fd;
+	char desc[64], buf[96];
+	struct off_prog p;
+	int fd, i;
+
+	off_prog_start(&p, map_fd, rb);
+	if (rd >= 0) {
+		EMIT(&p, BPF_RAW_INSN(BPF_LD | BPF_DW | BPF_IMM, rd, 0, 0, (__u32)STORE_VAL));
+		EMIT(&p, BPF_RAW_INSN(0, 0, 0, 0, STORE_VAL >> 32));
+	}
+	memcpy(exp, mem, MEM_SIZE);
+	for (i = 0; i < nr; i++) {
+		if (rd >= 0)
+			EMIT(&p, BPF_STX_MEM(size, rb, rd, off[i]));
+		else
+			EMIT(&p, BPF_ST_MEM(size, rb, off[i], imm));
+		store_bytes(exp + MEM_BASE + off[i], val, size);
+	}
+	if (rd >= 0)
+		snprintf(desc, sizeof(desc), "stx size=%d base=r%d src=r%d", size, rb, rd);
+	else
+		snprintf(desc, sizeof(desc), "st size=%d base=r%d imm=%d", size, rb, imm);
+	if (!ASSERT_OK(bpf_map_update_elem(map_fd, &mem_key, mem, 0), desc))
+		return;
+	fd = off_prog_load(&p, desc, false);
+	if (fd < 0)
+		return;
+	if (off_prog_run(fd, desc) || !ASSERT_OK(bpf_map_lookup_elem(map_fd, &mem_key, res), desc))
+		return;
+	for (i = 0; i < MEM_SIZE && res[i] == exp[i]; i++)
+		;
+	if (i < MEM_SIZE) {
+		snprintf(buf, sizeof(buf), "%s: byte at offset %d", desc, i - MEM_BASE);
+		ASSERT_EQ(res[i], exp[i], buf);
+	}
+}
+
+static void test_ldst_offsets(void)
+{
+	static const int sizes[] = { BPF_B, BPF_H, BPF_W, BPF_DW };
+	static const __s32 imms[] = { -1, 0x7fffffff, -0x7fffffff - 1 };
+	int b, k, s, i, nr, off[32];
+	struct off_mem m = {};
+	bool unaligned;
+
+	m.map_fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "ldst_mem", sizeof(__u32), MEM_SIZE, 2, NULL);
+	if (!ASSERT_GE(m.map_fd, 0, "ldst_mem map"))
+		return;
+	m.mem = malloc(MEM_SIZE);
+	m.exp = malloc(MEM_SIZE);
+	m.res = malloc(MEM_SIZE);
+	if (!ASSERT_OK_PTR(m.mem, "mem") || !ASSERT_OK_PTR(m.exp, "exp") ||
+	    !ASSERT_OK_PTR(m.res, "res"))
+		goto out;
+	for (i = 0; i < MEM_SIZE; i++)
+		m.mem[i] = (i * 7 + 3) ^ (i >> 8);
+	unaligned = unaligned_ok(m.map_fd);
+
+	for (b = 0; b < ARRAY_SIZE(pat_regs); b++) {
+		for (s = 0; s < ARRAY_SIZE(sizes); s++) {
+			int rb = pat_regs[b], size = sizes[s];
+
+			nr = offsets_for(size, unaligned, off);
+			/* Loads and sign extending loads, also into the base */
+			for (k = 0; k < NR_PAIRS; k++) {
+				int rd = pair_reg(b, k);
+
+				load_offsets(&m, K_LDX, size, rb, rd, off, nr);
+				if (size != BPF_DW)
+					load_offsets(&m, K_LDSX, size, rb, rd, off, nr);
+			}
+			/* Stores of a register and of an immediate */
+			for (k = 1; k < NR_PAIRS; k++)
+				store_offsets(&m, size, rb, pair_reg(b, k), 0, off, nr);
+			for (k = 0; k < ARRAY_SIZE(imms); k++)
+				store_offsets(&m, size, rb, -1, imms[k], off, nr);
+		}
+	}
+out:
+	free(m.mem);
+	free(m.exp);
+	free(m.res);
+	close(m.map_fd);
+}
+
+static void test_movsx(void)
+{
+	static const struct {
+		bool is64;
+		int off;
+	} ops[] = {
+		{ true, 8 }, { true, 16 }, { true, 32 }, { false, 8 }, { false, 16 },
+	};
+	struct prog p;
+	char desc[64];
+	int s, k, o, j, fd;
+
+	for (s = 0; s < ARRAY_SIZE(pat_regs); s++) {
+		int rs = pat_regs[s];
+
+		for (k = 0; k < NR_PAIRS; k++) {
+			int rd = pair_reg(s, k);
+
+			for (o = 0; o < ARRAY_SIZE(ops); o++) {
+				prog_start(&p);
+				EMIT(&p, BPF_LDX_MEM(BPF_DW, rs, BPF_REG_6, IN0));
+				if (ops[o].is64)
+					EMIT(&p, BPF_MOVSX64_REG(rd, rs, ops[o].off));
+				else
+					EMIT(&p, BPF_MOVSX32_REG(rd, rs, ops[o].off));
+				prog_end(&p, rd);
+				snprintf(desc, sizeof(desc), "movsx%d off=%d dst=r%d src=r%d",
+					 ops[o].is64 ? 64 : 32, ops[o].off, rd, rs);
+				fd = prog_load(&p, desc);
+				if (fd < 0)
+					return;
+				for (j = 0; j < ARRAY_SIZE(inputs); j++) {
+					__s64 v = inputs[j];
+
+					if (ops[o].off == 8)
+						v = (__s8)v;
+					else if (ops[o].off == 16)
+						v = (__s16)v;
+					else
+						v = (__s32)v;
+					prog_run(fd, inputs[j], 0,
+						 ops[o].is64 ? (__u64)v : (__u32)v, desc);
+				}
+				close(fd);
+			}
+		}
+	}
+}
+
+/* Branch on dst and imm, with 1 in res when taken and 0 otherwise */
+static void jmp_prog(struct prog *p, bool is64, int op, int d, __s32 imm)
+{
+	int rd = pat_regs[d], rt = pair_reg(d, 1);
+
+	prog_start(p);
+	EMIT(p, BPF_LDX_MEM(BPF_DW, rd, BPF_REG_6, IN0));
+	EMIT(p, BPF_MOV64_IMM(rt, 1));
+	if (is64)
+		EMIT(p, BPF_JMP_IMM(op, rd, imm, 1));
+	else
+		EMIT(p, BPF_JMP32_IMM(op, rd, imm, 1));
+	EMIT(p, BPF_MOV64_IMM(rt, 0));
+	prog_end(p, rt);
+}
+
+static void test_jset_imm(void)
+{
+	static const __s32 masks[] = {
+		0x1, 0x40, 0x80, 0xff, 0x100, 0x7fff, 0x7fffffff, -1, -0x7fffffff - 1,
+	};
+	struct prog p;
+	char desc[64];
+	int d, m, j, fd;
+	bool is64;
+
+	for (d = 0; d < ARRAY_SIZE(pat_regs); d++) {
+		int rd = pat_regs[d];
+
+		for (is64 = false; ; is64 = true) {
+			for (m = 0; m < ARRAY_SIZE(masks); m++) {
+				jmp_prog(&p, is64, BPF_JSET, d, masks[m]);
+				snprintf(desc, sizeof(desc), "jset%d dst=r%d mask=0x%x",
+					 is64 ? 64 : 32, rd, masks[m]);
+				fd = prog_load(&p, desc);
+				if (fd < 0)
+					return;
+				for (j = 0; j < ARRAY_SIZE(inputs); j++) {
+					__u64 v = inputs[j];
+					bool taken;
+
+					if (is64)
+						taken = v & (__u64)(__s64)masks[m];
+					else
+						taken = (__u32)v & (__u32)masks[m];
+					prog_run(fd, v, 0, taken, desc);
+				}
+				close(fd);
+			}
+			if (is64)
+				break;
+		}
+	}
+}
+
+static bool cmp_taken(int op, bool is64, __u64 v, __u64 c)
+{
+	__s64 sv = is64 ? (__s64)v : (__s32)v, sc = is64 ? (__s64)c : (__s32)c;
+
+	switch (op) {
+	case BPF_JEQ:
+		return v == c;
+	case BPF_JNE:
+		return v != c;
+	case BPF_JGT:
+		return v > c;
+	case BPF_JGE:
+		return v >= c;
+	case BPF_JLT:
+		return v < c;
+	case BPF_JLE:
+		return v <= c;
+	case BPF_JSGT:
+		return sv > sc;
+	case BPF_JSGE:
+		return sv >= sc;
+	case BPF_JSLT:
+		return sv < sc;
+	default:
+		return sv <= sc;
+	}
+}
+
+static void test_cmp_imm(void)
+{
+	static const __s32 imms[] = {
+		1, -1, 0x7f, 0x80, -0x80, -0x81, 0x1000, 0x7fffffff,
+	};
+	static const int ops[] = {
+		BPF_JEQ, BPF_JNE, BPF_JGT, BPF_JGE, BPF_JLT, BPF_JLE,
+		BPF_JSGT, BPF_JSGE, BPF_JSLT, BPF_JSLE,
+	};
+	struct prog p;
+	char desc[64];
+	int d, o, m, j, fd;
+	bool is64;
+
+	for (d = 0; d < ARRAY_SIZE(pat_regs); d++) {
+		int rd = pat_regs[d];
+
+		for (is64 = false; ; is64 = true) {
+			for (o = 0; o < ARRAY_SIZE(ops); o++) {
+				for (m = 0; m < ARRAY_SIZE(imms); m++) {
+					jmp_prog(&p, is64, ops[o], d, imms[m]);
+					snprintf(desc, sizeof(desc), "jmp%d op=0x%x dst=r%d imm=%d",
+						 is64 ? 64 : 32, ops[o], rd, imms[m]);
+					fd = prog_load(&p, desc);
+					if (fd < 0)
+						return;
+					for (j = 0; j < ARRAY_SIZE(inputs); j++) {
+						__u64 v = is64 ? inputs[j] : (__u32)inputs[j];
+						__u64 c = is64 ? (__u64)(__s64)imms[m] :
+							  (__u32)imms[m];
+						__u64 taken = cmp_taken(ops[o], is64, v, c);
+
+						prog_run(fd, inputs[j], 0, taken, desc);
+					}
+					close(fd);
+				}
+			}
+			if (is64)
+				break;
+		}
+	}
+}
+
+static __u64 alu_model(int op, __u64 v, __u64 c)
+{
+	switch (op) {
+	case BPF_ADD:
+		return v + c;
+	case BPF_SUB:
+		return v - c;
+	case BPF_AND:
+		return v & c;
+	case BPF_OR:
+		return v | c;
+	case BPF_XOR:
+		return v ^ c;
+	default:
+		return v * c;
+	}
+}
+
+static void test_alu_consts(void)
+{
+	static const struct {
+		int op;
+		__s32 imm;
+	} ops[] = {
+		{ BPF_ADD, 1 }, { BPF_ADD, -1 }, { BPF_SUB, 1 }, { BPF_SUB, -1 },
+		{ BPF_ADD, 128 }, { BPF_SUB, 128 }, { BPF_ADD, -128 },
+		{ BPF_AND, 0xff }, { BPF_AND, 0xffff }, { BPF_AND, 0x7f },
+		{ BPF_AND, 0x3ff }, { BPF_AND, 0x7fffffff },
+		{ BPF_OR, 0xff }, { BPF_XOR, -1 }, { BPF_XOR, 0x80 },
+		{ BPF_MUL, 2 }, { BPF_MUL, 3 }, { BPF_MUL, 4 }, { BPF_MUL, 5 },
+		{ BPF_MUL, 7 }, { BPF_MUL, 8 }, { BPF_MUL, 9 }, { BPF_MUL, 16 },
+		{ BPF_MUL, 0x40000000 }, { BPF_MUL, -3 }, { BPF_MUL, -0x7fffffff - 1 },
+		{ BPF_MUL, 0 }, { BPF_MUL, 1 }, { BPF_MUL, -1 },
+	};
+	struct prog p;
+	char desc[64];
+	int d, o, j, fd;
+	bool is64;
+
+	for (d = 0; d < ARRAY_SIZE(pat_regs); d++) {
+		int rd = pat_regs[d];
+
+		for (is64 = false; ; is64 = true) {
+			for (o = 0; o < ARRAY_SIZE(ops); o++) {
+				prog_start(&p);
+				EMIT(&p, BPF_LDX_MEM(BPF_DW, rd, BPF_REG_6, IN0));
+				if (is64)
+					EMIT(&p, BPF_ALU64_IMM(ops[o].op, rd, ops[o].imm));
+				else
+					EMIT(&p, BPF_ALU32_IMM(ops[o].op, rd, ops[o].imm));
+				prog_end(&p, rd);
+				snprintf(desc, sizeof(desc), "alu%d op=0x%x dst=r%d imm=%d",
+					 is64 ? 64 : 32, ops[o].op, rd, ops[o].imm);
+				fd = prog_load(&p, desc);
+				if (fd < 0)
+					return;
+				for (j = 0; j < ARRAY_SIZE(inputs); j++) {
+					__u64 v = is64 ? inputs[j] : (__u32)inputs[j];
+					__u64 c = is64 ? (__u64)(__s64)ops[o].imm :
+						  (__u32)ops[o].imm;
+					__u64 r = alu_model(ops[o].op, v, c);
+
+					prog_run(fd, inputs[j], 0, is64 ? r : (__u32)r, desc);
+				}
+				close(fd);
+			}
+			if (is64)
+				break;
+		}
+	}
+}
+
+static void test_bswap(void)
+{
+	static const int widths[] = { 16, 32, 64 };
+	struct prog p;
+	char desc[64];
+	int d, w, o, j, fd;
+
+	for (d = 0; d < ARRAY_SIZE(pat_regs); d++) {
+		int rd = pat_regs[d];
+
+		for (w = 0; w < ARRAY_SIZE(widths); w++) {
+			int bits = widths[w];
+
+			/* To big endian, to little endian, and the unconditional swap */
+			for (o = 0; o < 3; o++) {
+				prog_start(&p);
+				EMIT(&p, BPF_LDX_MEM(BPF_DW, rd, BPF_REG_6, IN0));
+				if (o == 0)
+					EMIT(&p, BPF_ENDIAN(BPF_TO_BE, rd, bits));
+				else if (o == 1)
+					EMIT(&p, BPF_ENDIAN(BPF_TO_LE, rd, bits));
+				else
+					EMIT(&p, BPF_RAW_INSN(BPF_ALU64 | BPF_END | BPF_TO_LE,
+							      rd, 0, 0, bits));
+				prog_end(&p, rd);
+				snprintf(desc, sizeof(desc), "%s%d dst=r%d",
+					 o == 0 ? "be" : o == 1 ? "le" : "bswap", bits, rd);
+				fd = prog_load(&p, desc);
+				if (fd < 0)
+					return;
+				for (j = 0; j < ARRAY_SIZE(inputs); j++) {
+					__u64 v = inputs[j], r;
+
+					if (bits == 16)
+						r = o == 0 ? htobe16(v) : o == 1 ? htole16(v) :
+						    __builtin_bswap16(v);
+					else if (bits == 32)
+						r = o == 0 ? htobe32(v) : o == 1 ? htole32(v) :
+						    __builtin_bswap32(v);
+					else
+						r = o == 0 ? htobe64(v) : o == 1 ? htole64(v) :
+						    __builtin_bswap64(v);
+					prog_run(fd, v, 0, r, desc);
+				}
+				close(fd);
+			}
+		}
+	}
+}
+
+static void test_probe_mem(void)
+{
+	int kfunc_id, type_id, b, k, j, fd;
+	struct btf *btf;
+	struct prog p;
+	char desc[64];
+
+	btf = btf__load_vmlinux_btf();
+	if (!ASSERT_OK_PTR(btf, "vmlinux btf"))
+		return;
+	kfunc_id = btf__find_by_name_kind(btf, "bpf_rdonly_cast", BTF_KIND_FUNC);
+	type_id = btf__find_by_name_kind(btf, "timespec64", BTF_KIND_STRUCT);
+	btf__free(btf);
+	if (!ASSERT_GT(kfunc_id, 0, "bpf_rdonly_cast id") ||
+	    !ASSERT_GT(type_id, 0, "timespec64 id"))
+		return;
+
+	/* The kernel copy of the ctx through an untrusted pointer in every register */
+	for (b = 0; b < ARRAY_SIZE(pat_regs); b++) {
+		int rb = pat_regs[b];
+
+		for (k = 0; k < NR_PAIRS; k++) {
+			int rd = pair_reg(b, k);
+
+			prog_start(&p);
+			EMIT(&p, BPF_MOV64_REG(BPF_REG_1, BPF_REG_6));
+			EMIT(&p, BPF_MOV32_IMM(BPF_REG_2, type_id));
+			EMIT(&p, BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, BPF_PSEUDO_KFUNC_CALL,
+					      0, kfunc_id));
+			if (rb != BPF_REG_0)
+				EMIT(&p, BPF_MOV64_REG(rb, BPF_REG_0));
+			EMIT(&p, BPF_LDX_MEM(BPF_DW, rd, rb, 0));
+			prog_end(&p, rd);
+			snprintf(desc, sizeof(desc), "probe_mem base=r%d dst=r%d", rb, rd);
+			fd = prog_load(&p, desc);
+			if (fd < 0)
+				return;
+			for (j = 0; j < ARRAY_SIZE(inputs); j++)
+				prog_run(fd, inputs[j], 0, inputs[j], desc);
+			close(fd);
+		}
+	}
+
+	/* NULL and a user address are not touched and read as zero */
+	for (j = 0; j < 2; j++) {
+		__u64 addr = j ? 0x00007ffffffff000ULL : 0;
+
+		prog_start(&p);
+		EMIT(&p, BPF_RAW_INSN(BPF_LD | BPF_DW | BPF_IMM, BPF_REG_1, 0, 0, (__u32)addr));
+		EMIT(&p, BPF_RAW_INSN(0, 0, 0, 0, addr >> 32));
+		EMIT(&p, BPF_MOV32_IMM(BPF_REG_2, type_id));
+		EMIT(&p, BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, BPF_PSEUDO_KFUNC_CALL,
+				      0, kfunc_id));
+		EMIT(&p, BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0));
+		prog_end(&p, BPF_REG_3);
+		snprintf(desc, sizeof(desc), "probe_mem addr=0x%llx", addr);
+		fd = prog_load(&p, desc);
+		if (fd < 0)
+			return;
+		prog_run(fd, 0, 0, 0, desc);
+		close(fd);
+	}
+}
+
+/* Whether the JIT supports load-acquire and store-release */
+static bool acq_rel_ok(void)
+{
+	LIBBPF_OPTS(bpf_prog_load_opts, lopts, .prog_flags = BPF_F_SLEEPABLE);
+	struct prog p;
+	int fd;
+
+	prog_start(&p);
+	EMIT(&p, BPF_ST_MEM(BPF_DW, BPF_REG_10, -8, 0));
+	EMIT(&p, BPF_ATOMIC_OP(BPF_DW, BPF_LOAD_ACQ, BPF_REG_0, BPF_REG_10, -8));
+	prog_end(&p, BPF_REG_0);
+	fd = bpf_prog_load(BPF_PROG_TYPE_SYSCALL, NULL, "GPL", p.insns, p.cnt, &lopts);
+	if (fd < 0)
+		return false;
+	close(fd);
+	return true;
+}
+
+/*
+ * Load-acquire and store-release of every size with every register as
+ * base, on a stack slot holding in0: the loads zero extend like the plain
+ * loads and the stores replace the first bytes of the slot like the plain
+ * stores.
+ */
+static void test_acq_rel(void)
+{
+	static const int sizes[] = { BPF_B, BPF_H, BPF_W, BPF_DW };
+	struct prog p;
+	char desc[64];
+	int b, k, s, j, fd;
+
+	if (!acq_rel_ok()) {
+		test__skip();
+		return;
+	}
+	for (b = 0; b < ARRAY_SIZE(pat_regs); b++) {
+		int rb = pat_regs[b];
+
+		for (s = 0; s < ARRAY_SIZE(sizes); s++) {
+			int size = sizes[s];
+
+			for (k = 0; k < NR_PAIRS; k++) {
+				int rd = pair_reg(b, k);
+
+				/* Load-acquire from the slot, also into the base */
+				prog_start(&p);
+				EMIT(&p, BPF_LDX_MEM(BPF_DW, rd, BPF_REG_6, IN0));
+				EMIT(&p, BPF_STX_MEM(BPF_DW, BPF_REG_10, rd, -8));
+				EMIT(&p, BPF_MOV64_REG(rb, BPF_REG_10));
+				EMIT(&p, BPF_ALU64_IMM(BPF_ADD, rb, -8));
+				EMIT(&p, BPF_ATOMIC_OP(size, BPF_LOAD_ACQ, rd, rb, 0));
+				prog_end(&p, rd);
+				snprintf(desc, sizeof(desc), "load_acq size=%d base=r%d dst=r%d",
+					 size, rb, rd);
+				fd = prog_load(&p, desc);
+				if (fd < 0)
+					return;
+				for (j = 0; j < ARRAY_SIZE(inputs); j++)
+					prog_run(fd, inputs[j], 0,
+						 head_bytes(inputs[j], size), desc);
+				close(fd);
+
+				if (rd == rb)
+					continue;
+				/* Store-release of in1 over the slot holding in0 */
+				prog_start(&p);
+				EMIT(&p, BPF_LDX_MEM(BPF_DW, rd, BPF_REG_6, IN0));
+				EMIT(&p, BPF_STX_MEM(BPF_DW, BPF_REG_10, rd, -8));
+				EMIT(&p, BPF_LDX_MEM(BPF_DW, rd, BPF_REG_6, IN1));
+				EMIT(&p, BPF_MOV64_REG(rb, BPF_REG_10));
+				EMIT(&p, BPF_ALU64_IMM(BPF_ADD, rb, -8));
+				EMIT(&p, BPF_ATOMIC_OP(size, BPF_STORE_REL, rb, rd, 0));
+				EMIT(&p, BPF_LDX_MEM(BPF_DW, rd, BPF_REG_10, -8));
+				prog_end(&p, rd);
+				snprintf(desc, sizeof(desc), "store_rel size=%d base=r%d src=r%d",
+					 size, rb, rd);
+				fd = prog_load(&p, desc);
+				if (fd < 0)
+					return;
+				for (j = 0; j < ARRAY_SIZE(inputs); j++) {
+					__u64 in1 = inputs[(j + 1) % ARRAY_SIZE(inputs)];
+
+					prog_run(fd, inputs[j], in1,
+						 head_merge(inputs[j], in1, size), desc);
+				}
+				close(fd);
+			}
+		}
+	}
+}
+
+/*
+ * A jump with the maximal offset over instructions which expand to several
+ * native ones, so that the native offset outgrows the field of a short
+ * branch and takes the JITs through their branch conversion. The region
+ * must not grow in the verifier, or the jump could not reach over it any
+ * more: the divisions are by constants, as a division by a register gets
+ * a zero check in front, and the region sticks to one width, as a 32-bit
+ * result read by a 64-bit instruction gets a zero extension on the JITs
+ * which need one. The region is the not taken path and ends with a result
+ * different from the taken one, so a jump landing inside it fails the run.
+ */
+static void max_jmp(bool alu32, bool taken)
+{
+	static const int ops[] = {
+		BPF_LSH, BPF_RSH, BPF_ARSH, BPF_ADD, BPF_SUB, BPF_MUL, BPF_DIV, BPF_MOD,
+	};
+	struct { __u64 r0, r2; } ctx = { taken, 0x0123456789abcdefULL };
+	LIBBPF_OPTS(bpf_test_run_opts, opts,
+		.ctx_in = &ctx,
+		.ctx_size_in = sizeof(ctx),
+	);
+	int len = INT16_MAX + 5, i = 0, fd;
+	struct bpf_insn *insns;
+	char desc[64];
+
+	snprintf(desc, sizeof(desc), "max jump alu%d %s", alu32 ? 32 : 64,
+		 taken ? "taken" : "not taken");
+	insns = malloc(len * sizeof(*insns));
+	if (!ASSERT_OK_PTR(insns, "insns"))
+		return;
+	insns[i++] = BPF_LDX_MEM(BPF_DW, BPF_REG_2, BPF_REG_1, 8);
+	insns[i++] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, 0);
+	insns[i++] = BPF_MOV64_REG(BPF_REG_3, BPF_REG_2);
+	insns[i++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 1, INT16_MAX);
+	while (i < len - 2) {
+		int op = ops[(i >> 1) % ARRAY_SIZE(ops)];
+
+		if (op == BPF_DIV || op == BPF_MOD)
+			insns[i++] = alu32 ? BPF_ALU32_IMM(op, BPF_REG_3, 7) :
+					     BPF_ALU64_IMM(op, BPF_REG_3, 7);
+		else
+			insns[i++] = alu32 ? BPF_ALU32_REG(op, BPF_REG_3, BPF_REG_2) :
+					     BPF_ALU64_REG(op, BPF_REG_3, BPF_REG_2);
+	}
+	insns[i++] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_0, 2);
+	insns[i++] = BPF_EXIT_INSN();
+	ASSERT_EQ(i, len, "insn count");
+
+	fd = load_prog(insns, i, desc);
+	if (fd >= 0) {
+		if (ASSERT_OK(bpf_prog_test_run_opts(fd, &opts), desc))
+			ASSERT_EQ(opts.retval, taken ? 1 : 2, desc);
+		close(fd);
+	}
+	free(insns);
+}
+
+static void test_max_jmp(void)
+{
+	max_jmp(false, true);
+	max_jmp(false, false);
+	max_jmp(true, true);
+	max_jmp(true, false);
+}
+
+void test_jit_insns(void)
+{
+	RUN_TESTS(jit_insns_arena);
+	if (test__start_subtest("alu_imm"))
+		test_alu_imm();
+	if (test__start_subtest("alu_reg"))
+		test_alu_reg();
+	if (test__start_subtest("alu_imm_regs"))
+		test_alu_imm_regs();
+	if (test__start_subtest("div_const"))
+		test_div_const();
+	if (test__start_subtest("alu_reg_pairs"))
+		test_alu_reg_pairs();
+	if (test__start_subtest("shifts"))
+		test_shifts();
+	if (test__start_subtest("atomics"))
+		test_atomics();
+	if (test__start_subtest("atomic_reg_pairs"))
+		test_atomic_reg_pairs();
+	if (test__start_subtest("xadd_chain"))
+		test_xadd_chain();
+	if (test__start_subtest("ld_imm64"))
+		test_ld_imm64();
+	if (test__start_subtest("jmp_imm"))
+		test_jmp_imm();
+	if (test__start_subtest("jmp_reg"))
+		test_jmp_reg();
+	if (test__start_subtest("jmp_reg_pairs"))
+		test_jmp_reg_pairs();
+	if (test__start_subtest("staggered_jumps"))
+		test_staggered_jumps();
+	if (test__start_subtest("max_jmp"))
+		test_max_jmp();
+	if (test__start_subtest("ldst_zero_off"))
+		test_ldst_zero_off();
+	if (test__start_subtest("ldst_offsets"))
+		test_ldst_offsets();
+	if (test__start_subtest("acq_rel"))
+		test_acq_rel();
+	if (test__start_subtest("movsx"))
+		test_movsx();
+	if (test__start_subtest("jset_imm"))
+		test_jset_imm();
+	if (test__start_subtest("cmp_imm"))
+		test_cmp_imm();
+	if (test__start_subtest("alu_consts"))
+		test_alu_consts();
+	if (test__start_subtest("bswap"))
+		test_bswap();
+	if (test__start_subtest("probe_mem"))
+		test_probe_mem();
+}
+
+/* The families with an immediate once more with the constants blinded */
+void serial_test_jit_insns_blinded(void)
+{
+	const char *harden = "/proc/sys/net/core/bpf_jit_harden";
+	char old[16] = {};
+
+	if (!is_jit_enabled()) {
+		test__skip();
+		return;
+	}
+	if (sysctl_set_or_fail(harden, old, "2"))
+		return;
+	if (test__start_subtest("alu_imm"))
+		test_alu_imm();
+	if (test__start_subtest("alu_imm_regs"))
+		test_alu_imm_regs();
+	if (test__start_subtest("div_const"))
+		test_div_const();
+	if (test__start_subtest("shifts"))
+		test_shifts();
+	if (test__start_subtest("xadd_chain"))
+		test_xadd_chain();
+	if (test__start_subtest("ld_imm64"))
+		test_ld_imm64();
+	if (test__start_subtest("jmp_imm"))
+		test_jmp_imm();
+	if (test__start_subtest("ldst_zero_off"))
+		test_ldst_zero_off();
+	if (test__start_subtest("ldst_offsets"))
+		test_ldst_offsets();
+	if (test__start_subtest("jset_imm"))
+		test_jset_imm();
+	if (test__start_subtest("cmp_imm"))
+		test_cmp_imm();
+	if (test__start_subtest("alu_consts"))
+		test_alu_consts();
+	sysctl_set_or_fail(harden, NULL, old);
+}
tools/testing/selftests/bpf/progs/jit_insns_arena.c new file +113 -0

113 lines not on this page · raw message

Signature · 1 line
2.43.0
#22 lore raw

Re: [PATCH bpf-next 17/18] selftests/bpf: Add JIT instruction tests

TL;DR: - Test gaps: verifier may fold the staggered jumps away, and mis-targeted jumps may still pass - 32-bit cmpxchg compare of a non-zero upper r0 half is no longer covered - Missing JIT features…
Quoted 1 line

selftests/bpf: Add JIT instruction tests

TL;DR:
- Test gaps: verifier may fold the staggered jumps away, and mis-targeted jumps may still pass
- 32-bit cmpxchg compare of a non-zero upper r0 half is no longer covered
- Missing JIT features may fail instead of skip

Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/jit_insns.c new file +0 -0
new file mode 100644
index 000000000000..dabf8a4abdfe
@@ -0,0 +1,2433 @@

[ ... ]

Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/jit_insns.c new file +2 -0
+static void emit_alu_imm(struct batch *b, void *arg, __s64 dst, __s64 imm)
+{

[ ... ]

tools/testing/selftests/bpf/prog_tests/jit_insns.c line 333

Quoted 3 lines
tools/testing/selftests/bpf/prog_tests/jit_insns.c new file +3 -0
+	if (!alu_result(&res, dst, (__s32)imm, a->op, a->flags))
+		return;
+	k = batch_case(b, BPF_REG_3, dst, 0);

Does this record the right second input for the failure message? batch_case(b, BPF_REG_3, dst, 0) stores in1 = 0 for every case, but the immediate is the only operand that varies within one dst value.

batch_flush() identifies a failing case only by its recorded inputs:

    snprintf(buf, sizeof(buf), "%s: in0=0x%llx in1=0x%llx out%d",
             b->desc, b->ctx.in[k][0], b->ctx.in[k][1], j);

A wrong "alu64_div_k magnitudes" or "alu64_mul_k magnitudes" result is therefore reported as in0=0x4000000000000000 in1=0x0, which cannot tell the failing immediate apart from the dozens of others used with the same dst. For div and mod it even suggests a zero divisor, which alu_result() never lets through.

emit_jmp(), test_shifts() and div_const() all pass their immediate to batch_case(). Would this work as:

    k = batch_case(b, BPF_REG_3, dst, (__s32)imm);

in[k][1] is never loaded by this program, so only the diagnostic changes.

[ ... ]

Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/jit_insns.c new file +2 -0
+static void emit_cmpxchg(struct batch *b, void *arg, __s64 dst, __s64 src)
+{

[ ... ]

tools/testing/selftests/bpf/prog_tests/jit_insns.c line 757

Quoted 7 lines
tools/testing/selftests/bpf/prog_tests/jit_insns.c new file +7 -0
+	/* Mismatch: the memory keeps its value, r0 gets it */
+	EMIT(b, BPF_MOV64_REG(BPF_REG_0, BPF_REG_1));
+	EMIT(b, BPF_ALU64_IMM(BPF_XOR, BPF_REG_0, -1));
+	EMIT(b, BPF_ATOMIC_OP(size, BPF_CMPXCHG, BPF_REG_10, BPF_REG_2, MEM_SLOT));
+	ST_OUT(b, k, 0, BPF_REG_3, BPF_REG_0);
+	/* Match: the memory gets the source, r0 the old value */
+	EMIT(b, BPF_ATOMIC_OP(size, BPF_CMPXCHG, BPF_REG_10, BPF_REG_2, MEM_SLOT));

Is the successful 32-bit compare still exercised with a non-zero upper half in r0 here?

The matching BPF_CMPXCHG reuses the r0 left behind by the mismatching one, and the verifier always zero extends r0 after a BPF_W cmpxchg, so the upper 32 bits of r0 are zero when the matching compare runs.

The test_bpf version this was ported from (__bpf_emit_cmpxchg32()) reloaded r0 with the full 64-bit dst before the matching cmpxchg:

    /* Result successful */
    i += __bpf_ld_imm64(&insns[i], R0, dst);
    insns[i++] = BPF_ATOMIC_OP(BPF_W, BPF_CMPXCHG, R10, R2, -4);

so for negative values and magnitudes of 2^32 and up the JIT had to compare only the low half.

Nothing else in jit_insns covers this. atomic_reg_pairs() sets r0 to ~mem and only tests the mismatch path, and test_ldst_zero_off() loads r0 with a zero extending BPF_LDX_MEM(BPF_W, ...). A JIT that compares all 64 bits of r0 against the zero extended memory value would pass every jit_insns case.

The next commit in the series, 5ba768097e67 ("selftests/bpf: Remove the old test_bpf module"), removes test_bpf, and nothing later restores this check.

Would reloading r0 before the matching cmpxchg, for example with LD_IN(b, k, 0, BPF_REG_3, BPF_REG_0), work? The low 32 bits of in0 still equal the memory value, so the expected results stay the same.

[ ... ]

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/jit_insns.c new file +10 -0
+/*
+ * Taken jumps over regions of doubling length, forward or backward, up to
+ * the maximal offset of the jump: 16 bits, or 2^17 for the 32-bit
+ * unconditional jump. The not taken path of a conditional jump and the
+ * guard of an unconditional one lead to an exit with the region number, so
+ * the verifier sees every instruction reachable and a jump landing anywhere
+ * else than on its target fails the run.
+ */
+static void staggered_jumps(const struct bpf_insn *jmp, __s64 r1, __s64 r2, bool backward,
+			    const char *desc)

[ ... ]

tools/testing/selftests/bpf/prog_tests/jit_insns.c line 1164

Quoted 4 lines
tools/testing/selftests/bpf/prog_tests/jit_insns.c new file +4 -0
+	insns[i++] = BPF_LDX_MEM(BPF_DW, BPF_REG_2, BPF_REG_1, 8);
+	insns[i++] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
+	insns[i++] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_0, 0);
+	for (gap = backward ? 4 : 2; gap <= max; gap = gap < max / 2 ? gap * 2 : max) {

Do all the jumps still reach the JIT with long offsets?

r1 and r2 are loaded from the ctx only once, here, and every later region reuses the bounds the verifier learned on the taken path of the region before it. For four of the eight kinds that is enough for the verifier to decide the branch:

- "staggered jmp_jeq_k": after the taken JEQ r1, 1234, r1 is the constant 1234, so every later JEQ is always taken.

- "staggered jmp32_jlt_k": after the taken JLT w1, 0x80000000, the u32 max of w1 is 0x7fffffff, so every later JLT is always taken.

- "staggered ja" and "staggered gotol": the guard JEQ r2, 0, +1 falls through with r2 != 0, so every later guard is never taken.

The skipped paths are never marked seen, and since test_progs runs with CAP_BPF the verifier then runs bpf_opt_hard_wire_dead_code_branches(), bpf_opt_remove_dead_code() and bpf_opt_remove_nops().

In the forward layout every region after the first is deleted and its jump becomes "ja +0", so "staggered ja forward", "staggered gotol forward", "staggered jmp_jeq_k forward" and "staggered jmp32_jlt_k forward" each JIT only a single 2-instruction jump.

In the backward layout the regions survive, but for jeq_k and jlt32_k every conditional jump after the first is rewritten to a plain BPF_JA with the same offset. No JMP32 conditional with an immediate, and no 64-bit JEQ with an immediate, reaches the JIT with a long offset.

This seems to contradict "so the verifier sees every instruction reachable" in the comment above. lib/test_bpf.c ran its programs without the verifier, so it had no such folding. Would reloading r1 and r2 from the ctx inside each region, right before the guard or jump, stop the refined bounds from carrying over?

The same happens in test_jmp_reg_pairs() for rd == rs, since the verifier resolves "reg1 == reg2" for every op except JSET, so those register combinations never reach the JIT as jumps.

[ ... ]

tools/testing/selftests/bpf/prog_tests/jit_insns.c line 1200

Quoted 11 lines
tools/testing/selftests/bpf/prog_tests/jit_insns.c new file +11 -0
+		} else {
+			/* An unconditional jump needs a way into its region */
+			if (ja)
+				insns[i++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_2, 0, 1);
+			insns[i] = *jmp;
+			set_jmp_off(&insns[i++], ja32, gap);
+			insns[i++] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_0, ++n);
+			for (k = 0; k < gap - 2; k++)
+				insns[i++] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_3, 0);
+			insns[i++] = BPF_EXIT_INSN();
+		}

Can a jump that lands inside the skipped region be detected here?

The program starts with r0 = 0 and passes when opts.retval is 0. In the forward layout only the "r0 = n" slot right after the jump writes r0. If a JIT miscomputes the target and the jump lands anywhere in the "r3 = 0" fillers or on the region's exit, execution reaches an exit with r0 still 0 and ASSERT_EQ(opts.retval, 0, desc) passes. All later regions are skipped as well, so their jumps never run.

The backward layout has the same weakness. The region body only holds "r3 = 0", so a backward jump that lands short in the body, or a leading jump that lands in the body instead of on the guard, still reaches the region's exit and continues to the next region.

So the only mis-target that is caught is a landing on the single "r0 = n" slot, which in practice means the jump was not taken at all. That does not match "a jump landing anywhere else than on its target fails the run" in the comment above. max_jmp() in the same file ends its skipped region in "r0 = 2", so any landing inside it changes the result.

lib/test_bpf.c checked r0 at every hop in __bpf_fill_staggered_jumps(), and 5ba768097e67 deletes that. Would filling the skipped forward region with "r0 = n" instead of "r3 = 0" close the forward gap? The backward layout would need a check that a short landing cannot get past and that the verifier cannot constant-fold.

[ ... ]

Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/jit_insns.c new file +6 -0
+	fd = load_prog(insns, i, desc);
+	if (fd >= 0) {
+		if (ASSERT_OK(bpf_prog_test_run_opts(fd, &opts), desc))
+			ASSERT_EQ(opts.retval, 0, desc);
+		close(fd);
+	}

[ ... ]

Quoted 1 line

+static int prog_load(struct prog *p, const char *desc)

[ ... ]

tools/testing/selftests/bpf/prog_tests/jit_insns.c line 1320

Quoted 4 lines
tools/testing/selftests/bpf/prog_tests/jit_insns.c new file +4 -0
+	fd = bpf_prog_load(BPF_PROG_TYPE_SYSCALL, NULL, "GPL", p->insns, p->cnt, &lopts);
+	if (!ASSERT_GE(fd, 0, desc))
+		fprintf(stderr, "%s", log);
+	return fd;

A subsystem pattern flags this as potentially concerning: the "staggered gotol" kinds load through load_prog(), and the cpu v4 sweeps load through prog_load() in the same way. Both treat every load error as a failure via ASSERT_GE(fd, 0, desc).

The x86-32, sparc64, parisc and riscv32 JITs have no BPF_JMP32 | BPF_JA case. With CONFIG_BPF_JIT_ALWAYS_ON, __bpf_prog_select_runtime() then sets *err = -ENOTSUPP, and the subtest fails instead of skipping with a reason. The same file already probes and skips for a missing JIT capability in acq_rel_ok() and test_acq_rel(). Should the capability-absent case be a skip here?

On the other hand, without JIT_ALWAYS_ON the kernel falls back to the interpreter and the load succeeds. 5ba768097e67 says that archs wanting BPF JIT support should move over to these selftests, so a hard failure on a missing JIT instruction may be intended.

[ ... ]

Quoted 1 line

+static int off_prog_load(struct off_prog *p, const char *desc, bool quiet)

[ ... ]

Quoted 3 lines
tools/testing/selftests/bpf/prog_tests/jit_insns.c new file +3 -0
+	if (!ASSERT_GE(fd, 0, desc))
+		fprintf(stderr, "%s", log);
+	return fd;

[ ... ]

Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/jit_insns.c new file +2 -0
+static void load_offsets(struct off_mem *m, int kind, int size, int rb, int rd,
+			 const int *off, int nr)

[ ... ]

tools/testing/selftests/bpf/prog_tests/jit_insns.c line 1708

Quoted 4 lines
tools/testing/selftests/bpf/prog_tests/jit_insns.c new file +4 -0
+		if (kind == K_LDX)
+			EMIT(&p, BPF_LDX_MEM(size, rd, rb, off[i]));
+		else
+			EMIT(&p, BPF_RAW_INSN(BPF_LDX | BPF_MEMSX | size, rd, rb, off[i], 0));

A subsystem pattern flags this as potentially concerning: test_ldst_offsets() calls load_offsets(&m, K_LDSX, ...) for B/H/W, which emits BPF_LDX | BPF_MEMSX loads, and off_prog_load() asserts on any load failure.

The verifier accepts BPF_MEMSX on every architecture, but the x86-32, mips, sparc, parisc and riscv32 JITs have no BPF_MEMSX case. With CONFIG_BPF_JIT_ALWAYS_ON=y, __bpf_prog_select_runtime() then returns -ENOTSUPP:

    if (!fp->jited && jit_needed) {
            *err = -ENOTSUPP;

and each LDSX combination is reported as a FAIL instead of a skip.

The same change already probes and gates one missing capability with unaligned_ok(), and gates load-acquire/store-release with acq_rel_ok() and test__skip(). progs/verifier_ldsx.c also restricts its LDSX tests to the JITs that support them. Would a one-time probe like unaligned_ok() that skips the K_LDSX calls, with a message, be appropriate?

That said, failing here may be intended, since the aim is to flag JITs that lack the cpu v4 instructions. Without JIT_ALWAYS_ON the load falls back to the interpreter and passes, and the plain LDX/STX/ST programs only use base instructions. test_movsx() behaves the same way.

[ ... ]

Quoted 1 line

+static void test_probe_mem(void)

[ ... ]

Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/jit_insns.c new file +2 -0
+			EMIT(&p, BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, BPF_PSEUDO_KFUNC_CALL,
+					      0, kfunc_id));

[ ... ]

tools/testing/selftests/bpf/prog_tests/jit_insns.c line 1410

Quoted 3 lines
tools/testing/selftests/bpf/prog_tests/jit_insns.c new file +3 -0
+			fd = prog_load(&p, desc);
+			if (fd < 0)
+				return;

A subsystem pattern flags this as potentially concerning: every program here calls the bpf_rdonly_cast kfunc, and bpf_add_kfunc_call() rejects such a program with -ENOTSUPP in two cases:

    if (!env->prog->jit_requested) {
        verbose(env, "JIT is required for calling kernel function\n");
        return -ENOTSUPP;
    }
    if (!bpf_jit_supports_kfunc_call()) {
        verbose(env, "JIT does not support calling kernel function\n");
        return -ENOTSUPP;
    }

The first case is bpf_jit_enable=0 without CONFIG_BPF_JIT_ALWAYS_ON. The second is any JIT that does not override the weak bpf_jit_supports_kfunc_call(); only loongarch, arm64, parisc, powerpc, riscv, s390, x86 and x86-32 do, so the 32-bit arm, mips and sparc JITs are among those affected.

In both cases prog_load() hits ASSERT_GE(fd, 0, desc) and the probe_mem subtest is reported as FAIL, although the -ENOTSUPP only means the capability is absent. Should this skip instead?

5ba768097e67 ("selftests/bpf: Remove the old test_bpf module") makes jit_insns the replacement for test_bpf and says that archs wanting BPF JIT support should move over to the selftests. A failure here may be intended, since the usual way to exclude a BPF selftest on an arch that lacks a feature is a DENYLIST entry.

[ ... ]

Quoted 1 line

+static bool acq_rel_ok(void)

[ ... ]

Quoted 3 lines
tools/testing/selftests/bpf/prog_tests/jit_insns.c new file +3 -0
+	fd = bpf_prog_load(BPF_PROG_TYPE_SYSCALL, NULL, "GPL", p.insns, p.cnt, &lopts);
+	if (fd < 0)
+		return false;

[ ... ]

tools/testing/selftests/bpf/prog_tests/jit_insns.c line 2221

Quoted 4 lines
tools/testing/selftests/bpf/prog_tests/jit_insns.c new file +4 -0
+	if (!acq_rel_ok()) {
+		test__skip();
+		return;
+	}

The opposite case is handled here: acq_rel_ok() returns false for any load error, and test_acq_rel() then calls a bare test__skip() without a reason.

Doesn't that treat a capability-absent error (-EOPNOTSUPP for 64-bit on 32-bit arches, or -ENOTSUPP from a JIT that cannot emit the instruction under JIT_ALWAYS_ON) the same as a verifier or JIT regression (-EINVAL, -EACCES) on a JIT that does support load-acquire? Such a regression would show up as SKIP instead of FAIL.

[ ... ]

tools/testing/selftests/bpf/prog_tests/jit_insns.c line 2345

Quoted 3 lines
tools/testing/selftests/bpf/prog_tests/jit_insns.c new file +3 -0
+void test_jit_insns(void)
+{
+	RUN_TESTS(jit_insns_arena);

A subsystem pattern flags this as potentially concerning: the two arena subtests run from here fail, rather than skip, on any JIT without arena support.

arena_map_alloc() returns -EOPNOTSUPP when !bpf_jit_supports_arena(), which is the case for the arm32, x86_32, mips, parisc, ppc32, riscv32, sparc64 and arc JITs. The "arena" map in progs/jit_insns_arena.c then fails to create, and test_loader reports "arena access with zero offset" and "cast to a user address" as FAIL. So the whole jit_insns test fails on those JITs, although the commit message says the tests run "on every JIT" and 5ba768097e67 points exactly these architectures at them.

The two arena programs also call a kfunc, and test_jit_insns() deliberately does not check is_jit_enabled(). With bpf_jit_enable=0 and no CONFIG_BPF_JIT_ALWAYS_ON they fail with "JIT is required for calling kernel function" while the raw-instruction subtests pass on the interpreter.

The same file already handles a missing JIT feature by probing and skipping in test_acq_rel(). Could the arena programs be gated the same way, for example by probing libbpf_probe_bpf_map_type(BPF_MAP_TYPE_ARENA, NULL) before RUN_TESTS(jit_insns_arena)?

The header comment of jit_insns_arena.c says a kernel without arena support "fails only these programs", and verifier_arena is also run with RUN() rather than RUN_JITED(), so failing may be intended.

[ ... ]

Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/jit_insns.c new file +2 -0
+void serial_test_jit_insns_blinded(void)
+{

[ ... ]

tools/testing/selftests/bpf/prog_tests/jit_insns.c line 2405

Quoted 4 lines
tools/testing/selftests/bpf/prog_tests/jit_insns.c new file +4 -0
+	if (!is_jit_enabled()) {
+		test__skip();
+		return;
+	}

Relatedly, serial_test_jit_insns_blinded() calls test__skip() here without printing a reason when the JIT is disabled.

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/38442623945

author maintainer
#23 lore raw

PATCH 18/18 selftests/bpf: Remove the old test_bpf module

In reply to Daniel Borkmann

The instruction tests of the test_bpf module live in the BPF selftests now, as the jit_insns test of test_progs, which BPF CI runs on every architecture it covers, and its skb_segment tests have a KUnit successor in net/core/net_test.c.

Remove the module together with its Kconfig entry, the test_kmod.sh and test_bpf.sh wrappers of the bpf and net selftests, the config fragments and defconfigs that enabled it, as well as all other references to it and symbol exports in core kernel.

For archs wanting to support BPF JITs, it's time they move over to the BPF selftests for proper coverage.

---
 Documentation/bpf/bpf_devel_QA.rst       |    16 +-
 Documentation/networking/filter.rst      |    15 +-
 MAINTAINERS                              |     1 -
 arch/m68k/configs/amiga_defconfig        |     1 -
 arch/m68k/configs/apollo_defconfig       |     1 -
 arch/m68k/configs/atari_defconfig        |     1 -
 arch/m68k/configs/bvme6000_defconfig     |     1 -
 arch/m68k/configs/hp300_defconfig        |     1 -
 arch/m68k/configs/mac_defconfig          |     1 -
 arch/m68k/configs/multi_defconfig        |     1 -
 arch/m68k/configs/mvme147_defconfig      |     1 -
 arch/m68k/configs/mvme16x_defconfig      |     1 -
 arch/m68k/configs/q40_defconfig          |     1 -
 arch/m68k/configs/sun3_defconfig         |     1 -
 arch/m68k/configs/sun3x_defconfig        |     1 -
 arch/powerpc/configs/ppc64_defconfig     |     1 -
 arch/s390/configs/debug_defconfig        |     1 -
 arch/s390/configs/defconfig              |     1 -
 kernel/bpf/core.c                        |     4 -
 lib/Kconfig.debug                        |    13 -
 lib/Makefile                             |     1 -
 lib/test_bpf.c                           | 15934 ---------------------
 tools/bpf/bpftool/feature.c              |     3 -
 tools/testing/selftests/bpf/Makefile     |     3 +-
 tools/testing/selftests/bpf/config       |     1 -
 tools/testing/selftests/bpf/test_kmod.sh |    73 -
 tools/testing/selftests/net/Makefile     |     1 -
 tools/testing/selftests/net/config       |     1 -
 tools/testing/selftests/net/test_bpf.sh  |    11 -
 29 files changed, 15 insertions(+), 16077 deletions(-)
 delete mode 100644 lib/test_bpf.c
 delete mode 100755 tools/testing/selftests/bpf/test_kmod.sh
 delete mode 100755 tools/testing/selftests/net/test_bpf.sh
Documentation/bpf/bpf_devel_QA.rst +9 -7
index edf8107a7beb..4729efd657c3 100644
@@ -374,9 +374,10 @@ developers in order to get the feature implemented in a timely manner.
 Please refer to the git log (``arch/*/net/``) to locate the necessary
 people for helping out.
 
-Also always make sure to add BPF test cases (e.g. test_bpf.c and
-test_verifier.c) for new instructions, so that they can receive
-broad test coverage and help run-time testing the various BPF JITs.
+Also always make sure to add BPF test cases (e.g. the jit_insns test
+in test_progs and test_verifier.c) for new instructions, so that they
+can receive broad test coverage and help run-time testing the various
+BPF JITs.
 
 In case of new BPF instructions, once the changes have been accepted
 into the Linux kernel, please implement support into LLVM's BPF back
@@ -514,10 +515,11 @@ A: If you run a kernel ``xyz``, then always run the BPF kernel selftests
 from that kernel ``xyz`` as well. Do not expect that the BPF selftest
 from the latest mainline tree will pass all the time.
 
-In particular, test_bpf.c and test_verifier.c have a large number of
-test cases and are constantly updated with new BPF test sequences, or
-existing ones are adapted to verifier changes e.g. due to verifier
-becoming smarter and being able to better track certain things.
+In particular, test_verifier.c and the instruction tests in test_progs
+have a large number of test cases and are constantly updated with new
+BPF test sequences, or existing ones are adapted to verifier changes
+e.g. due to verifier becoming smarter and being able to better track
+certain things.
 
 LLVM
 ====
Documentation/networking/filter.rst +5 -10
index 8eb9a5d40f31..e0b9dc14a9bf 100644
@@ -656,16 +656,11 @@ from eBPF instruction set.
 Testing
 -------
 
-Next to the BPF toolchain, the kernel also ships a test module that contains
-various test cases for classic and eBPF that can be executed against
-the BPF interpreter and JIT compiler. It can be found in lib/test_bpf.c and
-enabled via Kconfig::
-
-  CONFIG_TEST_BPF=m
-
-After the module has been built and installed, the test suite can be executed
-via insmod or modprobe against 'test_bpf' module. Results of the test cases
-including timings in nsec can be found in the kernel log (dmesg).
+Next to the BPF toolchain, the BPF selftests under tools/testing/selftests/bpf
+ship instruction tests in test_progs, see jit_insns, which runs the eBPF
+instructions over a range of operand magnitudes and signs, register
+combinations, memory offsets and jump offsets against the BPF interpreter
+or the JIT compiler, depending on the net.core.bpf_jit_enable setting.
 
 Misc
 ----
MAINTAINERS +0 -1
index fe99b7437a2d..80845ba7dfb5 100644
@@ -4981,7 +4981,6 @@ F:	include/uapi/linux/filter.h
 F:	kernel/bpf/
 F:	kernel/trace/bpf_trace.c
 F:	lib/buildid.c
-F:	lib/test_bpf.c
 F:	net/bpf/
 F:	net/core/filter.c
 F:	net/sched/act_bpf.c
arch/m68k/configs/amiga_defconfig +0 -1
index 8b7efe20dd12..0efd78d64a90 100644
@@ -576,7 +576,6 @@ CONFIG_TEST_IDA=m
 CONFIG_TEST_BITOPS=m
 CONFIG_TEST_VMALLOC=m
 CONFIG_TEST_WORKQUEUE=m
-CONFIG_TEST_BPF=m
 CONFIG_FIND_BIT_BENCHMARK=m
 CONFIG_TEST_FIRMWARE=m
 CONFIG_TEST_SYSCTL=m
arch/m68k/configs/apollo_defconfig +0 -1
index c7f7705806f9..35b54dc7e79c 100644
@@ -531,7 +531,6 @@ CONFIG_TEST_IDA=m
 CONFIG_TEST_BITOPS=m
 CONFIG_TEST_VMALLOC=m
 CONFIG_TEST_WORKQUEUE=m
-CONFIG_TEST_BPF=m
 CONFIG_FIND_BIT_BENCHMARK=m
 CONFIG_TEST_FIRMWARE=m
 CONFIG_TEST_SYSCTL=m
arch/m68k/configs/atari_defconfig +0 -1
index 2fb213161bae..265588b71b82 100644
@@ -554,7 +554,6 @@ CONFIG_TEST_IDA=m
 CONFIG_TEST_BITOPS=m
 CONFIG_TEST_VMALLOC=m
 CONFIG_TEST_WORKQUEUE=m
-CONFIG_TEST_BPF=m
 CONFIG_FIND_BIT_BENCHMARK=m
 CONFIG_TEST_FIRMWARE=m
 CONFIG_TEST_SYSCTL=m
arch/m68k/configs/bvme6000_defconfig +0 -1
index 6730242d4d48..595601e22971 100644
@@ -523,7 +523,6 @@ CONFIG_TEST_IDA=m
 CONFIG_TEST_BITOPS=m
 CONFIG_TEST_VMALLOC=m
 CONFIG_TEST_WORKQUEUE=m
-CONFIG_TEST_BPF=m
 CONFIG_FIND_BIT_BENCHMARK=m
 CONFIG_TEST_FIRMWARE=m
 CONFIG_TEST_SYSCTL=m
arch/m68k/configs/hp300_defconfig +0 -1
index 2b3ff26ac8fd..568d80e3db22 100644
@@ -533,7 +533,6 @@ CONFIG_TEST_IDA=m
 CONFIG_TEST_BITOPS=m
 CONFIG_TEST_VMALLOC=m
 CONFIG_TEST_WORKQUEUE=m
-CONFIG_TEST_BPF=m
 CONFIG_FIND_BIT_BENCHMARK=m
 CONFIG_TEST_FIRMWARE=m
 CONFIG_TEST_SYSCTL=m
arch/m68k/configs/mac_defconfig +0 -1
index 61f32ef2547e..da1f4677aa6d 100644
@@ -552,7 +552,6 @@ CONFIG_TEST_IDA=m
 CONFIG_TEST_BITOPS=m
 CONFIG_TEST_VMALLOC=m
 CONFIG_TEST_WORKQUEUE=m
-CONFIG_TEST_BPF=m
 CONFIG_FIND_BIT_BENCHMARK=m
 CONFIG_TEST_FIRMWARE=m
 CONFIG_TEST_SYSCTL=m
arch/m68k/configs/multi_defconfig +0 -1
index 2cbd6bf20a68..8e6466c51484 100644
@@ -639,7 +639,6 @@ CONFIG_TEST_IDA=m
 CONFIG_TEST_BITOPS=m
 CONFIG_TEST_VMALLOC=m
 CONFIG_TEST_WORKQUEUE=m
-CONFIG_TEST_BPF=m
 CONFIG_FIND_BIT_BENCHMARK=m
 CONFIG_TEST_FIRMWARE=m
 CONFIG_TEST_SYSCTL=m
arch/m68k/configs/mvme147_defconfig +0 -1
index 019f8b8070be..8e7882354e53 100644
@@ -523,7 +523,6 @@ CONFIG_TEST_IDA=m
 CONFIG_TEST_BITOPS=m
 CONFIG_TEST_VMALLOC=m
 CONFIG_TEST_WORKQUEUE=m
-CONFIG_TEST_BPF=m
 CONFIG_FIND_BIT_BENCHMARK=m
 CONFIG_TEST_FIRMWARE=m
 CONFIG_TEST_SYSCTL=m
arch/m68k/configs/mvme16x_defconfig +0 -1
index 389163287425..d3e7049c2e43 100644
@@ -524,7 +524,6 @@ CONFIG_TEST_IDA=m
 CONFIG_TEST_BITOPS=m
 CONFIG_TEST_VMALLOC=m
 CONFIG_TEST_WORKQUEUE=m
-CONFIG_TEST_BPF=m
 CONFIG_FIND_BIT_BENCHMARK=m
 CONFIG_TEST_FIRMWARE=m
 CONFIG_TEST_SYSCTL=m
arch/m68k/configs/q40_defconfig +0 -1
index cbc41443cffa..c517c32dbdc7 100644
@@ -542,7 +542,6 @@ CONFIG_TEST_IDA=m
 CONFIG_TEST_BITOPS=m
 CONFIG_TEST_VMALLOC=m
 CONFIG_TEST_WORKQUEUE=m
-CONFIG_TEST_BPF=m
 CONFIG_FIND_BIT_BENCHMARK=m
 CONFIG_TEST_FIRMWARE=m
 CONFIG_TEST_SYSCTL=m
arch/m68k/configs/sun3_defconfig +0 -1
index 273e840dc8d6..924f5f05906f 100644
@@ -520,7 +520,6 @@ CONFIG_TEST_IDA=m
 CONFIG_TEST_BITOPS=m
 CONFIG_TEST_VMALLOC=m
 CONFIG_TEST_WORKQUEUE=m
-CONFIG_TEST_BPF=m
 CONFIG_FIND_BIT_BENCHMARK=m
 CONFIG_TEST_FIRMWARE=m
 CONFIG_TEST_SYSCTL=m
arch/m68k/configs/sun3x_defconfig +0 -1
index 843d72924bcb..f63c6392d92e 100644
@@ -521,7 +521,6 @@ CONFIG_TEST_IDA=m
 CONFIG_TEST_BITOPS=m
 CONFIG_TEST_VMALLOC=m
 CONFIG_TEST_WORKQUEUE=m
-CONFIG_TEST_BPF=m
 CONFIG_FIND_BIT_BENCHMARK=m
 CONFIG_TEST_FIRMWARE=m
 CONFIG_TEST_SYSCTL=m
arch/powerpc/configs/ppc64_defconfig +0 -1
index 1eb8e3457e8b..e0b7901add11 100644
@@ -442,7 +442,6 @@ CONFIG_TEST_IDA=m
 CONFIG_TEST_BITOPS=m
 CONFIG_TEST_VMALLOC=m
 CONFIG_TEST_USER_COPY=m
-CONFIG_TEST_BPF=m
 CONFIG_TEST_BLACKHOLE_DEV=m
 CONFIG_FIND_BIT_BENCHMARK=m
 CONFIG_TEST_FIRMWARE=m
arch/s390/configs/debug_defconfig +0 -1
index 3dae71474333..d597b4b532a3 100644
@@ -927,6 +927,5 @@ CONFIG_INTERVAL_TREE_TEST=m
 CONFIG_PERCPU_TEST=m
 CONFIG_ATOMIC64_SELFTEST=y
 CONFIG_TEST_BITOPS=m
-CONFIG_TEST_BPF=m
 CONFIG_PAGE_TABLE_CHECK=y
 CONFIG_PAGE_TABLE_CHECK_ENFORCED=y
arch/s390/configs/defconfig +0 -1
index 6f5722634b4d..c417b1717e89 100644
@@ -851,4 +851,3 @@ CONFIG_LKDTM=m
 CONFIG_KPROBES_SANITY_TEST=m
 CONFIG_PERCPU_TEST=m
 CONFIG_ATOMIC64_SELFTEST=y
-CONFIG_TEST_BPF=m
kernel/bpf/core.c +0 -4
index 05c89396119a..642f0ab8eb2d 100644
@@ -172,7 +172,6 @@ struct bpf_prog *bpf_prog_alloc(unsigned int size, gfp_t gfp_extra_flags)
 	}
 	return prog;
 }
-EXPORT_SYMBOL_GPL(bpf_prog_alloc);
 
 int bpf_prog_alloc_jited_linfo(struct bpf_prog *prog)
 {
@@ -1681,7 +1680,6 @@ noinline u64 __bpf_call_base(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
 {
 	return 0;
 }
-EXPORT_SYMBOL_GPL(__bpf_call_base);
 
 /* All UAPI available opcodes. */
 #define BPF_INSN_MAP(INSN_2, INSN_3)		\
@@ -2747,7 +2745,6 @@ struct bpf_prog *bpf_prog_select_runtime(struct bpf_prog *fp, int *err)
 {
 	return __bpf_prog_select_runtime(NULL, fp, err);
 }
-EXPORT_SYMBOL_GPL(bpf_prog_select_runtime);
 
 static unsigned int __bpf_prog_ret1(const void *ctx,
 				    const struct bpf_insn *insn)
@@ -3138,7 +3135,6 @@ void bpf_prog_free(struct bpf_prog *fp)
 	INIT_WORK(&aux->work, bpf_prog_free_deferred);
 	schedule_work(&aux->work);
 }
-EXPORT_SYMBOL_GPL(bpf_prog_free);
 
 /* RNG for unprivileged user space with separated state from prandom_u32(). */
 static DEFINE_PER_CPU(struct rnd_state, bpf_user_rnd_state);
lib/Kconfig.debug +0 -13
index 2f34619905b6..d3d3604bedcf 100644
@@ -2638,19 +2638,6 @@ config TEST_WORKQUEUE
 
 	  If unsure, say N.
 
-config TEST_BPF
-	tristate "Test BPF filter functionality"
-	depends on m && NET
-	help
-	  This builds the "test_bpf" module that runs various test vectors
-	  against the BPF interpreter or BPF JIT compiler depending on the
-	  current setting. This is in particular useful for BPF JIT compiler
-	  development, but also to run regression tests against changes in
-	  the interpreter code. It also enables test stubs for eBPF maps and
-	  verifier used by user space verifier testsuite.
-
-	  If unsure, say N.
-
 config FIND_BIT_BENCHMARK
 	tristate "Test find_bit functions"
 	help
lib/Makefile +0 -1
index dfab958327c5..361b02903bef 100644
@@ -66,7 +66,6 @@ obj-y += kstrtox.o
 obj-$(CONFIG_FIND_BIT_BENCHMARK) += find_bit_benchmark.o
 obj-$(CONFIG_REGION_ALLOC_BENCHMARK) += region_alloc_benchmark.o
 obj-$(CONFIG_FIND_BIT_BENCHMARK_RUST) += find_bit_benchmark_rust.o
-obj-$(CONFIG_TEST_BPF) += test_bpf.o
 test_dhry-objs := dhry_1.o dhry_2.o dhry_run.o
 obj-$(CONFIG_TEST_DHRY) += test_dhry.o
 obj-$(CONFIG_TEST_FIRMWARE) += test_firmware.o
lib/test_bpf.c deleted +0 -15934

2,789 lines not on this page · raw message

tools/bpf/bpftool/feature.c +0 -3
index 0f6070a0c8e7..846a58e56203 100644

Lines of this file are not shown. View the raw message.

tools/testing/selftests/bpf/Makefile +1 -2
index 80d8bbbc3084..1e4af62e8312 100644

Lines of this file are not shown. View the raw message.

tools/testing/selftests/bpf/config +0 -1
index 2b883b388f90..1f41283ae2f0 100644

Lines of this file are not shown. View the raw message.

tools/testing/selftests/bpf/test_kmod.sh deleted +0 -73

73 lines not on this page · raw message

tools/testing/selftests/net/Makefile +0 -1
index 590b33e16d9f..0ffce8efc6d0 100644

Lines of this file are not shown. View the raw message.

tools/testing/selftests/net/config +0 -1
index 737e7e6327b3..6223b00516fe 100644

Lines of this file are not shown. View the raw message.

tools/testing/selftests/net/test_bpf.sh deleted +0 -11
deleted file mode 100755
index 65677909c574..000000000000

Lines of this file are not shown. View the raw message.

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.43.0

Part of the diff is not shown here. View the raw message.

#24 lore raw

Re: [PATCH bpf-next 18/18] selftests/bpf: Remove the old test_bpf module

TL;DR: - Commit message may overstate successors: classic BPF tests (SKF_AD_* converter, sparc32 cBPF JIT) seem to have no replacement - The two skb_segment crash-fix tests seem not covered by…
Quoted 1 line

selftests/bpf: Remove the old test_bpf module

TL;DR:
- Commit message may overstate successors: classic BPF tests (SKF_AD_* converter, sparc32 cBPF JIT) seem to have no replacement
- The two skb_segment crash-fix tests seem not covered by net_test.c, so regressions may go uncaught

Quoted 6 lines
lib/test_bpf.c deleted +0 -0
deleted file mode 100644
index af6f3340c034..000000000000
@@ -1,15934 +0,0 @@

[ ... ]

lib/test_bpf.c line 61

Quoted 4 lines
lib/test_bpf.c deleted +0 -4
-enum {
-	CLASSIC  = BIT(6),	/* Old BPF instructions only. */
-	INTERNAL = BIT(7),	/* Extended instruction set.  */
-};

The commit message says "The instruction tests of the test_bpf module live in the BPF selftests now, as the jit_insns test of test_progs". Does that hold for the tests flagged CLASSIC?

None of the roughly 135 CLASSIC tests in the deleted file appear to have been carried over. tools/testing/selftests/bpf/prog_tests/jit_insns.c has no sock_filter, BPF_STMT/BPF_JUMP, BPF_ABS/BPF_IND or SKF_AD_* usage, so only the INTERNAL tests seem to have a successor.

The classic tests went through bpf_prog_create(), and that leaves two areas without systematic in-tree coverage.

1) The ancillary load handling in convert_bpf_extensions() in net/core/filter.c, which is used by every SO_ATTACH_FILTER and seccomp filter. The deleted tests covered SKF_AD_PROTOCOL, HATYPE, IFINDEX, MARK, RXHASH, QUEUE, VLAN_TAG, VLAN_TAG_PRESENT, PAY_OFFSET, NLATTR, NLATTR_NEST and ALU_XOR_X, each of which has a "case SKF_AD_OFF + SKF_AD_..." in convert_bpf_extensions(). The remaining selftests only use SKF_AD_CPU, SKF_AD_PKTTYPE and SKF_AD_OFF (toeplitz.c, csum.c, gro.c, psock_lib.h, reuseport_bpf_cpu.c, skf_net_off.c).

2) The sparc32 classic JIT. arch/sparc/Kconfig still has:

select HAVE_CBPF_JIT if SPARC32

and bpf_jit_compile() in arch/sparc/net/bpf_jit_comp_32.c is only reached from cBPF programs. The advice that archs "move over to the BPF selftests for proper coverage" does not seem to apply there, since test_progs only loads eBPF programs.

The previous commit (71a5c374fa65) says it carries "only the relevant instruction tests", so dropping the classic tests may be deliberate. Even so, could the changelog avoid saying that the instruction tests now live in the BPF selftests, and could the lost cBPF converter and extension coverage be acknowledged or ported?

[ ... ]

Quoted 13 lines
lib/test_bpf.c deleted +0 -13
-struct skb_segment_test {
-	const char *descr;
-	struct sk_buff *(*build_skb)(void);
-	netdev_features_t features;
-};
-
-static struct skb_segment_test skb_segment_tests[] __initconst = {
-	{
-		.descr = "gso_with_rx_frags",
-		.build_skb = build_test_skb,
-		.features = NETIF_F_SG | NETIF_F_GSO_PARTIAL | NETIF_F_IP_CSUM |
-			    NETIF_F_IPV6_CSUM | NETIF_F_RXCSUM
-	},

lib/test_bpf.c line 15299

Quoted 10 lines
lib/test_bpf.c deleted +0 -10
-	{
-		.descr = "gso_linear_no_head_frag",
-		.build_skb = build_test_skb_linear_no_head_frag,
-		.features = NETIF_F_SG | NETIF_F_FRAGLIST |
-			    NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_GSO |
-			    NETIF_F_GRO | NETIF_F_IPV6_CSUM | NETIF_F_RXCSUM |
-			    NETIF_F_HW_VLAN_STAG_TX
-	}
-};
-

The commit message says the skb_segment tests "have a KUnit successor in net/core/net_test.c". Are these two cases actually covered there?

They were added as reproducers for BUG_ON crash fixes in skb_segment():

gso_with_rx_frags (76db8087c4c9) for 13acc94eff12 ("net: permit skb_segment on head_frag frag_list skb")

gso_linear_no_head_frag (cf204a718357) for 3dcbdb134f32 ("net: gso: Fix skb_segment splat when splitting gso_size mangled skb having linear-headed frag_list")

For gso_linear_no_head_frag, build_test_skb_linear_no_head_frag() builds alloc_skb() frag_list members (head_frag = 0, linear data) with SKB_GSO_TCPV6 | SKB_GSO_DODGY and a gso_size of 1288 that differs from skb_headlen(head_skb). That is the input needed to reach this block at the top of skb_segment():

    if ((skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY) &&
        !gso_by_frags && mss != skb_headlen(head_skb)) {
        ...
            if (skb_headlen(check_skb) && !check_skb->head_frag) {
                ...
                features &= ~NETIF_F_SG;

net/core/net_test.c never reaches it. gso_test_func() never sets gso_type, which stays 0 because __finalize_skb_around() clears the shinfo, and every frag_list member is built with build_skb(page_address(page), frag_size + shinfo_size), which sets head_frag = 1 whenever frag_size is non-zero. So there is no DODGY skb and no linear non-head_frag frag_list member.

For gso_with_rx_frags, the head skb and its frag_list member are dev_alloc_skb() head_frag skbs, each with 8 linear bytes plus a 64-byte rx frag, and the features include NETIF_F_SG | NETIF_F_GSO_PARTIAL. The segmentation loop then reaches this code in skb_segment():

    if (!skb_headlen(list_skb)) {
        BUG_ON(!nfrags);
    } else {
        BUG_ON(!list_skb->head_frag);
        /* to make room for head_frag. */
        i--;
        frag--;
    }

followed by:

    *nskb_frag = (i < 0) ? skb_head_frag_to_page_desc(frag_skb) : *frag;

In the net_test.c cases this path does not seem to be hit:

- frag_list and frag_list_pure have mss-aligned linear frag_list members, so after the head segment every iteration takes the skb_clone(list_skb) path under "hsize <= 0 && i >= nfrags && skb_headlen(list_skb) && (skb_headlen(list_skb) == len || sg)".
- frag_list_non_uniform clears NETIF_F_SG and takes the skb_copy_bits() path.
- gso_by_frags always takes the clone path.
- frags and gso_partial have no frag_list.

net_test.c's skb_segment test came from b3098d32ed6e ("net: add skb_segment kunit test") and was never extended with these two cases, and a search of tools/testing/, lib/ and the KUnit files finds no other skb_segment() test. After this commit, a regression of either fix would have no in-tree test that catches it.

Could the two cases be ported into the gso_test cases[] table in net/core/net_test.c, for example a DODGY case with alloc_skb()-backed frag_list members and a case with head_frag plus page-frag frag_list members, before the module is removed? Alternatively, could the commit message stop describing net_test.c as the successor of these tests?

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/38442623945

#25 lore raw
In reply to Daniel Borkmann
This series was applied to bpf/bpf-next.git (master) by Kumar Kartikeya Dwivedi <[email protected]>:

Hello:

This series was applied to bpf/bpf-next.git (master) by Kumar Kartikeya Dwivedi <[email protected]>:

Quoted 8 lines · On Tue, 13 Oct 2026 19:12:12 +0200 you wrote:

This series changes the x86-64 BPF JIT to emit shorter and faster native code for the instruction patterns that LLVM-compiled programs hit in the real world. Every change stays within the lowering of a single BPF instruction, nothing is optimized across instructions. The patterns were checked against what clang's BPF backend actually emits, and the native forms follow what LLVM's own X86 backend picks for the same operations.

[...]

Here is the summary with links:
- [bpf-next,01/18] bpf, x86: Drop redundant REX prefixes from zero and sign extensions

    https://git.kernel.org/bpf/bpf-next/c/63d4c99d25ae
  - [bpf-next,02/18] bpf, x86: Omit the displacement byte for zero offsets
    https://git.kernel.org/bpf/bpf-next/c/44df4d88aa63
  - [bpf-next,03/18] bpf, x86: Shorten the stack adjusts and the tail call counter loads
    https://git.kernel.org/bpf/bpf-next/c/c4da703867ed
  - [bpf-next,04/18] bpf, x86: Use shorter test and cmp encodings for immediates
    https://git.kernel.org/bpf/bpf-next/c/649caad437d7
  - [bpf-next,05/18] bpf, x86: Compare against 0, 127 and -128 with the adjusted condition
    https://git.kernel.org/bpf/bpf-next/c/fa6979fde9f6
  - [bpf-next,06/18] bpf, x86: Use movzx for byte and word masks and a not for xor with -1
    https://git.kernel.org/bpf/bpf-next/c/135b45cf05b9
  - [bpf-next,07/18] bpf, x86: Consolidate the ALU, shift and neg encodings into helpers
    https://git.kernel.org/bpf/bpf-next/c/707e1331f52b
  - [bpf-next,08/18] bpf, x86: Use shorter and faster forms for some ALU immediates
    https://git.kernel.org/bpf/bpf-next/c/d59f47e031ae
  - [bpf-next,09/18] bpf, x86: Swap 16-bit values with bswap and shr, not ror and movzx
    https://git.kernel.org/bpf/bpf-next/c/0847f6cb2e6a
  - [bpf-next,10/18] bpf, x86: Use BMI2 shifts also when the count is in rcx
    https://git.kernel.org/bpf/bpf-next/c/f2a5c00a80f1
  - [bpf-next,11/18] bpf, x86: Fold the PROBE_MEM address computation into a lea
    https://git.kernel.org/bpf/bpf-next/c/74309a9294a7
  - [bpf-next,12/18] bpf, x86: Compare the PROBE_MEM address range with a shift
    https://git.kernel.org/bpf/bpf-next/c/181576ebd87d
  - [bpf-next,13/18] bpf, x86: Divide by constants via multiplication with a magic number
    https://git.kernel.org/bpf/bpf-next/c/02cfd66f3d9a
  - [bpf-next,14/18] bpf, x86: Multiply by 3, 5 and 9 with lea
    https://git.kernel.org/bpf/bpf-next/c/36b383f5abc3
  - [bpf-next,15/18] bpf, x86: Use emit_sub_rsp() for the trampoline stack
    https://git.kernel.org/bpf/bpf-next/c/2378e471a6a2
  - [bpf-next,16/18] bpf, x86: Shorten the cast to a user address
    https://git.kernel.org/bpf/bpf-next/c/b878ba01b67a
  - [bpf-next,17/18] selftests/bpf: Add JIT instruction tests
    https://git.kernel.org/bpf/bpf-next/c/54e8bde13a3a
  - [bpf-next,18/18] selftests/bpf: Remove the old test_bpf module
    https://git.kernel.org/bpf/bpf-next/c/4532e525b286

You are awesome, thank you!

Signature · 2 lines
Deet-doot-dot, I am a bot.
https://korg.docs.kernel.org/patchwork/pwbot.html