Linux-Next discussions
 help / color / mirror / Atom feed
* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2018-02-26  0:41 Stephen Rothwell
  2018-02-26  9:03 ` Daniel Borkmann
  2018-02-26 23:28 ` Stephen Rothwell
  0 siblings, 2 replies; 69+ messages in thread
From: Stephen Rothwell @ 2018-02-26  0:41 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Networking
  Cc: Linux-Next Mailing List, Linux Kernel Mailing List

[-- Attachment #1: Type: text/plain, Size: 6001 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  tools/testing/selftests/bpf/test_verifier.c

between commit:

  ca36960211eb ("bpf: allow xadd only on aligned memory")

from the bpf tree and commit:

  23d191a82c13 ("bpf: add various jit test cases")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

-- 
Cheers,
Stephen Rothwell

diff --cc tools/testing/selftests/bpf/test_verifier.c
index 437c0b1c9d21,c987d3a2426f..000000000000
--- a/tools/testing/selftests/bpf/test_verifier.c
+++ b/tools/testing/selftests/bpf/test_verifier.c
@@@ -11163,64 -11140,95 +11166,153 @@@ static struct bpf_test tests[] = 
  		.result = REJECT,
  		.prog_type = BPF_PROG_TYPE_TRACEPOINT,
  	},
 +	{
 +		"xadd/w check unaligned stack",
 +		.insns = {
 +			BPF_MOV64_IMM(BPF_REG_0, 1),
 +			BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_0, -8),
 +			BPF_STX_XADD(BPF_W, BPF_REG_10, BPF_REG_0, -7),
 +			BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_10, -8),
 +			BPF_EXIT_INSN(),
 +		},
 +		.result = REJECT,
 +		.errstr = "misaligned stack access off",
 +		.prog_type = BPF_PROG_TYPE_SCHED_CLS,
 +	},
 +	{
 +		"xadd/w check unaligned map",
 +		.insns = {
 +			BPF_ST_MEM(BPF_DW, BPF_REG_10, -8, 0),
 +			BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
 +			BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -8),
 +			BPF_LD_MAP_FD(BPF_REG_1, 0),
 +			BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
 +				     BPF_FUNC_map_lookup_elem),
 +			BPF_JMP_IMM(BPF_JNE, BPF_REG_0, 0, 1),
 +			BPF_EXIT_INSN(),
 +			BPF_MOV64_IMM(BPF_REG_1, 1),
 +			BPF_STX_XADD(BPF_W, BPF_REG_0, BPF_REG_1, 3),
 +			BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 3),
 +			BPF_EXIT_INSN(),
 +		},
 +		.fixup_map1 = { 3 },
 +		.result = REJECT,
 +		.errstr = "misaligned value access off",
 +		.prog_type = BPF_PROG_TYPE_SCHED_CLS,
 +	},
 +	{
 +		"xadd/w check unaligned pkt",
 +		.insns = {
 +			BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
 +				    offsetof(struct xdp_md, data)),
 +			BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
 +				    offsetof(struct xdp_md, data_end)),
 +			BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
 +			BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
 +			BPF_JMP_REG(BPF_JLT, BPF_REG_1, BPF_REG_3, 2),
 +			BPF_MOV64_IMM(BPF_REG_0, 99),
 +			BPF_JMP_IMM(BPF_JA, 0, 0, 6),
 +			BPF_MOV64_IMM(BPF_REG_0, 1),
 +			BPF_ST_MEM(BPF_W, BPF_REG_2, 0, 0),
 +			BPF_ST_MEM(BPF_W, BPF_REG_2, 3, 0),
 +			BPF_STX_XADD(BPF_W, BPF_REG_2, BPF_REG_0, 1),
 +			BPF_STX_XADD(BPF_W, BPF_REG_2, BPF_REG_0, 2),
 +			BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_2, 1),
 +			BPF_EXIT_INSN(),
 +		},
 +		.result = REJECT,
 +		.errstr = "BPF_XADD stores into R2 packet",
 +		.prog_type = BPF_PROG_TYPE_XDP,
 +	},
+ 	{
+ 		"jit: lsh, rsh, arsh by 1",
+ 		.insns = {
+ 			BPF_MOV64_IMM(BPF_REG_0, 1),
+ 			BPF_MOV64_IMM(BPF_REG_1, 0xff),
+ 			BPF_ALU64_IMM(BPF_LSH, BPF_REG_1, 1),
+ 			BPF_ALU32_IMM(BPF_LSH, BPF_REG_1, 1),
+ 			BPF_JMP_IMM(BPF_JEQ, BPF_REG_1, 0x3fc, 1),
+ 			BPF_EXIT_INSN(),
+ 			BPF_ALU64_IMM(BPF_RSH, BPF_REG_1, 1),
+ 			BPF_ALU32_IMM(BPF_RSH, BPF_REG_1, 1),
+ 			BPF_JMP_IMM(BPF_JEQ, BPF_REG_1, 0xff, 1),
+ 			BPF_EXIT_INSN(),
+ 			BPF_ALU64_IMM(BPF_ARSH, BPF_REG_1, 1),
+ 			BPF_JMP_IMM(BPF_JEQ, BPF_REG_1, 0x7f, 1),
+ 			BPF_EXIT_INSN(),
+ 			BPF_MOV64_IMM(BPF_REG_0, 2),
+ 			BPF_EXIT_INSN(),
+ 		},
+ 		.result = ACCEPT,
+ 		.retval = 2,
+ 	},
+ 	{
+ 		"jit: mov32 for ldimm64, 1",
+ 		.insns = {
+ 			BPF_MOV64_IMM(BPF_REG_0, 2),
+ 			BPF_LD_IMM64(BPF_REG_1, 0xfeffffffffffffffULL),
+ 			BPF_ALU64_IMM(BPF_RSH, BPF_REG_1, 32),
+ 			BPF_LD_IMM64(BPF_REG_2, 0xfeffffffULL),
+ 			BPF_JMP_REG(BPF_JEQ, BPF_REG_1, BPF_REG_2, 1),
+ 			BPF_MOV64_IMM(BPF_REG_0, 1),
+ 			BPF_EXIT_INSN(),
+ 		},
+ 		.result = ACCEPT,
+ 		.retval = 2,
+ 	},
+ 	{
+ 		"jit: mov32 for ldimm64, 2",
+ 		.insns = {
+ 			BPF_MOV64_IMM(BPF_REG_0, 1),
+ 			BPF_LD_IMM64(BPF_REG_1, 0x1ffffffffULL),
+ 			BPF_LD_IMM64(BPF_REG_2, 0xffffffffULL),
+ 			BPF_JMP_REG(BPF_JEQ, BPF_REG_1, BPF_REG_2, 1),
+ 			BPF_MOV64_IMM(BPF_REG_0, 2),
+ 			BPF_EXIT_INSN(),
+ 		},
+ 		.result = ACCEPT,
+ 		.retval = 2,
+ 	},
+ 	{
+ 		"jit: various mul tests",
+ 		.insns = {
+ 			BPF_LD_IMM64(BPF_REG_2, 0xeeff0d413122ULL),
+ 			BPF_LD_IMM64(BPF_REG_0, 0xfefefeULL),
+ 			BPF_LD_IMM64(BPF_REG_1, 0xefefefULL),
+ 			BPF_ALU64_REG(BPF_MUL, BPF_REG_0, BPF_REG_1),
+ 			BPF_JMP_REG(BPF_JEQ, BPF_REG_0, BPF_REG_2, 2),
+ 			BPF_MOV64_IMM(BPF_REG_0, 1),
+ 			BPF_EXIT_INSN(),
+ 			BPF_LD_IMM64(BPF_REG_3, 0xfefefeULL),
+ 			BPF_ALU64_REG(BPF_MUL, BPF_REG_3, BPF_REG_1),
+ 			BPF_JMP_REG(BPF_JEQ, BPF_REG_3, BPF_REG_2, 2),
+ 			BPF_MOV64_IMM(BPF_REG_0, 1),
+ 			BPF_EXIT_INSN(),
+ 			BPF_MOV32_REG(BPF_REG_2, BPF_REG_2),
+ 			BPF_LD_IMM64(BPF_REG_0, 0xfefefeULL),
+ 			BPF_ALU32_REG(BPF_MUL, BPF_REG_0, BPF_REG_1),
+ 			BPF_JMP_REG(BPF_JEQ, BPF_REG_0, BPF_REG_2, 2),
+ 			BPF_MOV64_IMM(BPF_REG_0, 1),
+ 			BPF_EXIT_INSN(),
+ 			BPF_LD_IMM64(BPF_REG_3, 0xfefefeULL),
+ 			BPF_ALU32_REG(BPF_MUL, BPF_REG_3, BPF_REG_1),
+ 			BPF_JMP_REG(BPF_JEQ, BPF_REG_3, BPF_REG_2, 2),
+ 			BPF_MOV64_IMM(BPF_REG_0, 1),
+ 			BPF_EXIT_INSN(),
+ 			BPF_LD_IMM64(BPF_REG_0, 0x952a7bbcULL),
+ 			BPF_LD_IMM64(BPF_REG_1, 0xfefefeULL),
+ 			BPF_LD_IMM64(BPF_REG_2, 0xeeff0d413122ULL),
+ 			BPF_ALU32_REG(BPF_MUL, BPF_REG_2, BPF_REG_1),
+ 			BPF_JMP_REG(BPF_JEQ, BPF_REG_2, BPF_REG_0, 2),
+ 			BPF_MOV64_IMM(BPF_REG_0, 1),
+ 			BPF_EXIT_INSN(),
+ 			BPF_MOV64_IMM(BPF_REG_0, 2),
+ 			BPF_EXIT_INSN(),
+ 		},
+ 		.result = ACCEPT,
+ 		.retval = 2,
+ 	},
+ 
  };
  
  static int probe_filter_length(const struct bpf_insn *fp)

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2018-02-26  0:41 Stephen Rothwell
@ 2018-02-26  9:03 ` Daniel Borkmann
  2018-02-26 23:28 ` Stephen Rothwell
  1 sibling, 0 replies; 69+ messages in thread
From: Daniel Borkmann @ 2018-02-26  9:03 UTC (permalink / raw)
  To: Stephen Rothwell, Alexei Starovoitov, Networking
  Cc: Linux-Next Mailing List, Linux Kernel Mailing List

On 02/26/2018 01:41 AM, Stephen Rothwell wrote:
> Hi all,
> 
> Today's linux-next merge of the bpf-next tree got a conflict in:
> 
>   tools/testing/selftests/bpf/test_verifier.c
> 
> between commit:
> 
>   ca36960211eb ("bpf: allow xadd only on aligned memory")
> 
> from the bpf tree and commit:
> 
>   23d191a82c13 ("bpf: add various jit test cases")
> 
> from the bpf-next tree.
> 
> I fixed it up (see below) and can carry the fix as necessary. This
> is now fixed as far as linux-next is concerned, but any non trivial
> conflicts should be mentioned to your upstream maintainer when your tree
> is submitted for merging.  You may also want to consider cooperating
> with the maintainer of the conflicting tree to minimise any particularly
> complex conflicts.

Looks good, thanks!

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2018-02-26  0:41 Stephen Rothwell
  2018-02-26  9:03 ` Daniel Borkmann
@ 2018-02-26 23:28 ` Stephen Rothwell
  1 sibling, 0 replies; 69+ messages in thread
From: Stephen Rothwell @ 2018-02-26 23:28 UTC (permalink / raw)
  To: Networking, David Miller
  Cc: Daniel Borkmann, Alexei Starovoitov, Linux-Next Mailing List,
	Linux Kernel Mailing List

[-- Attachment #1: Type: text/plain, Size: 6556 bytes --]

Hi Dave,

On Mon, 26 Feb 2018 11:41:47 +1100 Stephen Rothwell <sfr@canb.auug.org.au> wrote:
>
> Today's linux-next merge of the bpf-next tree got a conflict in:
> 
>   tools/testing/selftests/bpf/test_verifier.c
> 
> between commit:
> 
>   ca36960211eb ("bpf: allow xadd only on aligned memory")
> 
> from the bpf tree and commit:
> 
>   23d191a82c13 ("bpf: add various jit test cases")
> 
> from the bpf-next tree.
> 
> I fixed it up (see below) and can carry the fix as necessary. This
> is now fixed as far as linux-next is concerned, but any non trivial
> conflicts should be mentioned to your upstream maintainer when your tree
> is submitted for merging.  You may also want to consider cooperating
> with the maintainer of the conflicting tree to minimise any particularly
> complex conflicts.
> 
> -- 
> Cheers,
> Stephen Rothwell
> 
> diff --cc tools/testing/selftests/bpf/test_verifier.c
> index 437c0b1c9d21,c987d3a2426f..000000000000
> --- a/tools/testing/selftests/bpf/test_verifier.c
> +++ b/tools/testing/selftests/bpf/test_verifier.c
> @@@ -11163,64 -11140,95 +11166,153 @@@ static struct bpf_test tests[] = 
>   		.result = REJECT,
>   		.prog_type = BPF_PROG_TYPE_TRACEPOINT,
>   	},
>  +	{
>  +		"xadd/w check unaligned stack",
>  +		.insns = {
>  +			BPF_MOV64_IMM(BPF_REG_0, 1),
>  +			BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_0, -8),
>  +			BPF_STX_XADD(BPF_W, BPF_REG_10, BPF_REG_0, -7),
>  +			BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_10, -8),
>  +			BPF_EXIT_INSN(),
>  +		},
>  +		.result = REJECT,
>  +		.errstr = "misaligned stack access off",
>  +		.prog_type = BPF_PROG_TYPE_SCHED_CLS,
>  +	},
>  +	{
>  +		"xadd/w check unaligned map",
>  +		.insns = {
>  +			BPF_ST_MEM(BPF_DW, BPF_REG_10, -8, 0),
>  +			BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
>  +			BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -8),
>  +			BPF_LD_MAP_FD(BPF_REG_1, 0),
>  +			BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
>  +				     BPF_FUNC_map_lookup_elem),
>  +			BPF_JMP_IMM(BPF_JNE, BPF_REG_0, 0, 1),
>  +			BPF_EXIT_INSN(),
>  +			BPF_MOV64_IMM(BPF_REG_1, 1),
>  +			BPF_STX_XADD(BPF_W, BPF_REG_0, BPF_REG_1, 3),
>  +			BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 3),
>  +			BPF_EXIT_INSN(),
>  +		},
>  +		.fixup_map1 = { 3 },
>  +		.result = REJECT,
>  +		.errstr = "misaligned value access off",
>  +		.prog_type = BPF_PROG_TYPE_SCHED_CLS,
>  +	},
>  +	{
>  +		"xadd/w check unaligned pkt",
>  +		.insns = {
>  +			BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,
>  +				    offsetof(struct xdp_md, data)),
>  +			BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,
>  +				    offsetof(struct xdp_md, data_end)),
>  +			BPF_MOV64_REG(BPF_REG_1, BPF_REG_2),
>  +			BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, 8),
>  +			BPF_JMP_REG(BPF_JLT, BPF_REG_1, BPF_REG_3, 2),
>  +			BPF_MOV64_IMM(BPF_REG_0, 99),
>  +			BPF_JMP_IMM(BPF_JA, 0, 0, 6),
>  +			BPF_MOV64_IMM(BPF_REG_0, 1),
>  +			BPF_ST_MEM(BPF_W, BPF_REG_2, 0, 0),
>  +			BPF_ST_MEM(BPF_W, BPF_REG_2, 3, 0),
>  +			BPF_STX_XADD(BPF_W, BPF_REG_2, BPF_REG_0, 1),
>  +			BPF_STX_XADD(BPF_W, BPF_REG_2, BPF_REG_0, 2),
>  +			BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_2, 1),
>  +			BPF_EXIT_INSN(),
>  +		},
>  +		.result = REJECT,
>  +		.errstr = "BPF_XADD stores into R2 packet",
>  +		.prog_type = BPF_PROG_TYPE_XDP,
>  +	},
> + 	{
> + 		"jit: lsh, rsh, arsh by 1",
> + 		.insns = {
> + 			BPF_MOV64_IMM(BPF_REG_0, 1),
> + 			BPF_MOV64_IMM(BPF_REG_1, 0xff),
> + 			BPF_ALU64_IMM(BPF_LSH, BPF_REG_1, 1),
> + 			BPF_ALU32_IMM(BPF_LSH, BPF_REG_1, 1),
> + 			BPF_JMP_IMM(BPF_JEQ, BPF_REG_1, 0x3fc, 1),
> + 			BPF_EXIT_INSN(),
> + 			BPF_ALU64_IMM(BPF_RSH, BPF_REG_1, 1),
> + 			BPF_ALU32_IMM(BPF_RSH, BPF_REG_1, 1),
> + 			BPF_JMP_IMM(BPF_JEQ, BPF_REG_1, 0xff, 1),
> + 			BPF_EXIT_INSN(),
> + 			BPF_ALU64_IMM(BPF_ARSH, BPF_REG_1, 1),
> + 			BPF_JMP_IMM(BPF_JEQ, BPF_REG_1, 0x7f, 1),
> + 			BPF_EXIT_INSN(),
> + 			BPF_MOV64_IMM(BPF_REG_0, 2),
> + 			BPF_EXIT_INSN(),
> + 		},
> + 		.result = ACCEPT,
> + 		.retval = 2,
> + 	},
> + 	{
> + 		"jit: mov32 for ldimm64, 1",
> + 		.insns = {
> + 			BPF_MOV64_IMM(BPF_REG_0, 2),
> + 			BPF_LD_IMM64(BPF_REG_1, 0xfeffffffffffffffULL),
> + 			BPF_ALU64_IMM(BPF_RSH, BPF_REG_1, 32),
> + 			BPF_LD_IMM64(BPF_REG_2, 0xfeffffffULL),
> + 			BPF_JMP_REG(BPF_JEQ, BPF_REG_1, BPF_REG_2, 1),
> + 			BPF_MOV64_IMM(BPF_REG_0, 1),
> + 			BPF_EXIT_INSN(),
> + 		},
> + 		.result = ACCEPT,
> + 		.retval = 2,
> + 	},
> + 	{
> + 		"jit: mov32 for ldimm64, 2",
> + 		.insns = {
> + 			BPF_MOV64_IMM(BPF_REG_0, 1),
> + 			BPF_LD_IMM64(BPF_REG_1, 0x1ffffffffULL),
> + 			BPF_LD_IMM64(BPF_REG_2, 0xffffffffULL),
> + 			BPF_JMP_REG(BPF_JEQ, BPF_REG_1, BPF_REG_2, 1),
> + 			BPF_MOV64_IMM(BPF_REG_0, 2),
> + 			BPF_EXIT_INSN(),
> + 		},
> + 		.result = ACCEPT,
> + 		.retval = 2,
> + 	},
> + 	{
> + 		"jit: various mul tests",
> + 		.insns = {
> + 			BPF_LD_IMM64(BPF_REG_2, 0xeeff0d413122ULL),
> + 			BPF_LD_IMM64(BPF_REG_0, 0xfefefeULL),
> + 			BPF_LD_IMM64(BPF_REG_1, 0xefefefULL),
> + 			BPF_ALU64_REG(BPF_MUL, BPF_REG_0, BPF_REG_1),
> + 			BPF_JMP_REG(BPF_JEQ, BPF_REG_0, BPF_REG_2, 2),
> + 			BPF_MOV64_IMM(BPF_REG_0, 1),
> + 			BPF_EXIT_INSN(),
> + 			BPF_LD_IMM64(BPF_REG_3, 0xfefefeULL),
> + 			BPF_ALU64_REG(BPF_MUL, BPF_REG_3, BPF_REG_1),
> + 			BPF_JMP_REG(BPF_JEQ, BPF_REG_3, BPF_REG_2, 2),
> + 			BPF_MOV64_IMM(BPF_REG_0, 1),
> + 			BPF_EXIT_INSN(),
> + 			BPF_MOV32_REG(BPF_REG_2, BPF_REG_2),
> + 			BPF_LD_IMM64(BPF_REG_0, 0xfefefeULL),
> + 			BPF_ALU32_REG(BPF_MUL, BPF_REG_0, BPF_REG_1),
> + 			BPF_JMP_REG(BPF_JEQ, BPF_REG_0, BPF_REG_2, 2),
> + 			BPF_MOV64_IMM(BPF_REG_0, 1),
> + 			BPF_EXIT_INSN(),
> + 			BPF_LD_IMM64(BPF_REG_3, 0xfefefeULL),
> + 			BPF_ALU32_REG(BPF_MUL, BPF_REG_3, BPF_REG_1),
> + 			BPF_JMP_REG(BPF_JEQ, BPF_REG_3, BPF_REG_2, 2),
> + 			BPF_MOV64_IMM(BPF_REG_0, 1),
> + 			BPF_EXIT_INSN(),
> + 			BPF_LD_IMM64(BPF_REG_0, 0x952a7bbcULL),
> + 			BPF_LD_IMM64(BPF_REG_1, 0xfefefeULL),
> + 			BPF_LD_IMM64(BPF_REG_2, 0xeeff0d413122ULL),
> + 			BPF_ALU32_REG(BPF_MUL, BPF_REG_2, BPF_REG_1),
> + 			BPF_JMP_REG(BPF_JEQ, BPF_REG_2, BPF_REG_0, 2),
> + 			BPF_MOV64_IMM(BPF_REG_0, 1),
> + 			BPF_EXIT_INSN(),
> + 			BPF_MOV64_IMM(BPF_REG_0, 2),
> + 			BPF_EXIT_INSN(),
> + 		},
> + 		.result = ACCEPT,
> + 		.retval = 2,
> + 	},
> + 
>   };
>   
>   static int probe_filter_length(const struct bpf_insn *fp)

This conflict is now between the bfp tree and the net-next tree.

-- 
Cheers,
Stephen Rothwell

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2018-04-26  0:53 Stephen Rothwell
  2018-04-26  7:57 ` Daniel Borkmann
  0 siblings, 1 reply; 69+ messages in thread
From: Stephen Rothwell @ 2018-04-26  0:53 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Networking
  Cc: Linux-Next Mailing List, Linux Kernel Mailing List,
	John Fastabend

[-- Attachment #1: Type: text/plain, Size: 740 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  samples/sockmap/Makefile

between commit:

  4dfe1bb95235 ("bpf: sockmap sample use clang flag, -target bpf")

from the bpf tree and commit:

  2e04eb1dd1ca ("bpf: sockmap, remove samples program")

from the bpf-next tree.

I fixed it up (I just removed the file) and can carry the fix as
necessary. This is now fixed as far as linux-next is concerned, but any
non trivial conflicts should be mentioned to your upstream maintainer
when your tree is submitted for merging.  You may also want to consider
cooperating with the maintainer of the conflicting tree to minimise any
particularly complex conflicts.

-- 
Cheers,
Stephen Rothwell

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2018-04-26  0:53 Stephen Rothwell
@ 2018-04-26  7:57 ` Daniel Borkmann
  0 siblings, 0 replies; 69+ messages in thread
From: Daniel Borkmann @ 2018-04-26  7:57 UTC (permalink / raw)
  To: Stephen Rothwell, Alexei Starovoitov, Networking
  Cc: Linux-Next Mailing List, Linux Kernel Mailing List,
	John Fastabend

On 04/26/2018 02:53 AM, Stephen Rothwell wrote:
> Hi all,
> 
> Today's linux-next merge of the bpf-next tree got a conflict in:
> 
>   samples/sockmap/Makefile
> 
> between commit:
> 
>   4dfe1bb95235 ("bpf: sockmap sample use clang flag, -target bpf")
> 
> from the bpf tree and commit:
> 
>   2e04eb1dd1ca ("bpf: sockmap, remove samples program")
> 
> from the bpf-next tree.
> 
> I fixed it up (I just removed the file) and can carry the fix as
> necessary. This is now fixed as far as linux-next is concerned, but any
> non trivial conflicts should be mentioned to your upstream maintainer
> when your tree is submitted for merging.  You may also want to consider
> cooperating with the maintainer of the conflicting tree to minimise any
> particularly complex conflicts.

That's correct as well, thank you!

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2018-05-02  2:09 Stephen Rothwell
  2018-05-02  4:40 ` Song Liu
  0 siblings, 1 reply; 69+ messages in thread
From: Stephen Rothwell @ 2018-05-02  2:09 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Networking
  Cc: Linux-Next Mailing List, Linux Kernel Mailing List, Song Liu,
	Yonghong Song

[-- Attachment #1: Type: text/plain, Size: 2342 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  tools/testing/selftests/bpf/test_progs.c

between commit:

  a4e21ff8d9a3 ("bpf: minor fix to selftest test_stacktrace_build_id()")

from the bpf tree and commit:

  79b453501310 ("tools/bpf: add a test for bpf_get_stack with tracepoint prog")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

-- 
Cheers,
Stephen Rothwell

diff --cc tools/testing/selftests/bpf/test_progs.c
index fac581f1c57f,aa336f0abebc..000000000000
--- a/tools/testing/selftests/bpf/test_progs.c
+++ b/tools/testing/selftests/bpf/test_progs.c
@@@ -1137,9 -1193,14 +1193,14 @@@ static void test_stacktrace_build_id(vo
  		  err, errno))
  		goto disable_pmu;
  
+ 	stack_amap_fd = bpf_find_map(__func__, obj, "stack_amap");
+ 	if (CHECK(stack_amap_fd < 0, "bpf_find_map stack_amap",
+ 		  "err %d errno %d\n", err, errno))
+ 		goto disable_pmu;
+ 
  	assert(system("dd if=/dev/urandom of=/dev/zero count=4 2> /dev/null")
  	       == 0);
 -	assert(system("./urandom_read if=/dev/urandom of=/dev/zero count=4 2> /dev/null") == 0);
 +	assert(system("./urandom_read") == 0);
  	/* disable stack trace collection */
  	key = 0;
  	val = 1;
@@@ -1188,8 -1249,15 +1249,15 @@@
  		previous_key = key;
  	} while (bpf_map_get_next_key(stackmap_fd, &previous_key, &key) == 0);
  
- 	CHECK(build_id_matches < 1, "build id match",
- 	      "Didn't find expected build ID from the map\n");
+ 	if (CHECK(build_id_matches < 1, "build id match",
 -		  "Didn't find expected build ID from the map"))
++		  "Didn't find expected build ID from the map\n"))
+ 		goto disable_pmu;
+ 
+ 	stack_trace_len = PERF_MAX_STACK_DEPTH
+ 		* sizeof(struct bpf_stack_build_id);
+ 	err = compare_stack_ips(stackmap_fd, stack_amap_fd, stack_trace_len);
+ 	CHECK(err, "compare_stack_ips stackmap vs. stack_amap",
+ 	      "err %d errno %d\n", err, errno);
  
  disable_pmu:
  	ioctl(pmu_fd, PERF_EVENT_IOC_DISABLE);

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2018-05-02  2:09 Stephen Rothwell
@ 2018-05-02  4:40 ` Song Liu
  2018-05-02  5:50   ` Stephen Rothwell
  0 siblings, 1 reply; 69+ messages in thread
From: Song Liu @ 2018-05-02  4:40 UTC (permalink / raw)
  To: Stephen Rothwell
  Cc: Daniel Borkmann, Alexei Starovoitov, Networking,
	Linux-Next Mailing List, Linux Kernel Mailing List, Yonghong Song



> On May 1, 2018, at 7:09 PM, Stephen Rothwell <sfr@canb.auug.org.au> wrote:
> 
> Hi all,
> 
> Today's linux-next merge of the bpf-next tree got a conflict in:
> 
>  tools/testing/selftests/bpf/test_progs.c
> 
> between commit:
> 
>  a4e21ff8d9a3 ("bpf: minor fix to selftest test_stacktrace_build_id()")
> 
> from the bpf tree and commit:
> 
>  79b453501310 ("tools/bpf: add a test for bpf_get_stack with tracepoint prog")
> 
> from the bpf-next tree.
> 
> I fixed it up (see below) and can carry the fix as necessary. This
> is now fixed as far as linux-next is concerned, but any non trivial
> conflicts should be mentioned to your upstream maintainer when your tree
> is submitted for merging.  You may also want to consider cooperating
> with the maintainer of the conflicting tree to minimise any particularly
> complex conflicts.
> 
> -- 
> Cheers,
> Stephen Rothwell
> 
> diff --cc tools/testing/selftests/bpf/test_progs.c
> index fac581f1c57f,aa336f0abebc..000000000000
> --- a/tools/testing/selftests/bpf/test_progs.c
> +++ b/tools/testing/selftests/bpf/test_progs.c
> @@@ -1137,9 -1193,14 +1193,14 @@@ static void test_stacktrace_build_id(vo
>  		  err, errno))
>  		goto disable_pmu;
> 
> + 	stack_amap_fd = bpf_find_map(__func__, obj, "stack_amap");
> + 	if (CHECK(stack_amap_fd < 0, "bpf_find_map stack_amap",
> + 		  "err %d errno %d\n", err, errno))
> + 		goto disable_pmu;
> + 
>  	assert(system("dd if=/dev/urandom of=/dev/zero count=4 2> /dev/null")
>  	       == 0);
> -	assert(system("./urandom_read if=/dev/urandom of=/dev/zero count=4 2> /dev/null") == 0);
> +	assert(system("./urandom_read") == 0);
>  	/* disable stack trace collection */
>  	key = 0;
>  	val = 1;
> @@@ -1188,8 -1249,15 +1249,15 @@@
>  		previous_key = key;
>  	} while (bpf_map_get_next_key(stackmap_fd, &previous_key, &key) == 0);
> 
> - 	CHECK(build_id_matches < 1, "build id match",
> - 	      "Didn't find expected build ID from the map\n");
> + 	if (CHECK(build_id_matches < 1, "build id match",
> -		  "Didn't find expected build ID from the map"))
> ++		  "Didn't find expected build ID from the map\n"))

^^^  Is there a "+" at the beginning of this line? 

Thanks,
Song

> + 		goto disable_pmu;
> + 
> + 	stack_trace_len = PERF_MAX_STACK_DEPTH
> + 		* sizeof(struct bpf_stack_build_id);
> + 	err = compare_stack_ips(stackmap_fd, stack_amap_fd, stack_trace_len);
> + 	CHECK(err, "compare_stack_ips stackmap vs. stack_amap",
> + 	      "err %d errno %d\n", err, errno);
> 
>  disable_pmu:
>  	ioctl(pmu_fd, PERF_EVENT_IOC_DISABLE);

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2018-05-02  4:40 ` Song Liu
@ 2018-05-02  5:50   ` Stephen Rothwell
  2018-05-02  6:05     ` Song Liu
  0 siblings, 1 reply; 69+ messages in thread
From: Stephen Rothwell @ 2018-05-02  5:50 UTC (permalink / raw)
  To: Song Liu
  Cc: Daniel Borkmann, Alexei Starovoitov, Networking,
	Linux-Next Mailing List, Linux Kernel Mailing List, Yonghong Song

[-- Attachment #1: Type: text/plain, Size: 588 bytes --]

Hi Song,

On Wed, 2 May 2018 04:40:20 +0000 Song Liu <songliubraving@fb.com> wrote:
>
> > - 	CHECK(build_id_matches < 1, "build id match",
> > - 	      "Didn't find expected build ID from the map\n");
> > + 	if (CHECK(build_id_matches < 1, "build id match",
> > -		  "Didn't find expected build ID from the map"))
> > ++		  "Didn't find expected build ID from the map\n"))  
> 
> ^^^  Is there a "+" at the beginning of this line? 

No, this is a merge resolution diff, so the ++ means that the line did
not appear in either parent commit.

-- 
Cheers,
Stephen Rothwell

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2018-05-02  5:50   ` Stephen Rothwell
@ 2018-05-02  6:05     ` Song Liu
  0 siblings, 0 replies; 69+ messages in thread
From: Song Liu @ 2018-05-02  6:05 UTC (permalink / raw)
  To: Stephen Rothwell
  Cc: Daniel Borkmann, Alexei Starovoitov, Networking,
	Linux-Next Mailing List, Linux Kernel Mailing List, Yonghong Song



> On May 1, 2018, at 10:50 PM, Stephen Rothwell <sfr@canb.auug.org.au> wrote:
> 
> Hi Song,
> 
> On Wed, 2 May 2018 04:40:20 +0000 Song Liu <songliubraving@fb.com> wrote:
>> 
>>> - 	CHECK(build_id_matches < 1, "build id match",
>>> - 	      "Didn't find expected build ID from the map\n");
>>> + 	if (CHECK(build_id_matches < 1, "build id match",
>>> -		  "Didn't find expected build ID from the map"))
>>> ++		  "Didn't find expected build ID from the map\n"))  
>> 
>> ^^^  Is there a "+" at the beginning of this line? 
> 
> No, this is a merge resolution diff, so the ++ means that the line did
> not appear in either parent commit.

Hi Stephen,

Thanks for the explanation! 

Song

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2018-05-14  1:57 Stephen Rothwell
  2018-05-14 20:41 ` Jakub Kicinski
  0 siblings, 1 reply; 69+ messages in thread
From: Stephen Rothwell @ 2018-05-14  1:57 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Networking
  Cc: Linux-Next Mailing List, Linux Kernel Mailing List,
	Jakub Kicinski

[-- Attachment #1: Type: text/plain, Size: 1334 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  tools/lib/bpf/libbpf.c

between commit:

  3597683c9da6 ("tools: bpf: handle NULL return in bpf_prog_load_xattr()")

from the bpf tree and commit:

  17387dd5ac2c ("tools: bpf: don't complain about no kernel version for networking code")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

-- 
Cheers,
Stephen Rothwell

diff --cc tools/lib/bpf/libbpf.c
index 8da4eeb101a6,df54c4c9e48a..000000000000
--- a/tools/lib/bpf/libbpf.c
+++ b/tools/lib/bpf/libbpf.c
@@@ -2163,9 -2193,12 +2193,12 @@@ int bpf_prog_load_xattr(const struct bp
  
  	if (!attr)
  		return -EINVAL;
+ 	if (!attr->file)
+ 		return -EINVAL;
  
- 	obj = bpf_object__open(attr->file);
+ 	obj = __bpf_object__open(attr->file, NULL, 0,
+ 				 bpf_prog_type__needs_kver(attr->prog_type));
 -	if (IS_ERR(obj))
 +	if (IS_ERR_OR_NULL(obj))
  		return -ENOENT;
  
  	bpf_object__for_each_program(prog, obj) {

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2018-05-14  1:57 Stephen Rothwell
@ 2018-05-14 20:41 ` Jakub Kicinski
  2018-05-14 21:57   ` Stephen Rothwell
  0 siblings, 1 reply; 69+ messages in thread
From: Jakub Kicinski @ 2018-05-14 20:41 UTC (permalink / raw)
  To: Stephen Rothwell
  Cc: Daniel Borkmann, Alexei Starovoitov, Networking,
	Linux-Next Mailing List, Linux Kernel Mailing List

On Mon, 14 May 2018 11:57:00 +1000, Stephen Rothwell wrote:
> diff --cc tools/lib/bpf/libbpf.c
> index 8da4eeb101a6,df54c4c9e48a..000000000000
> --- a/tools/lib/bpf/libbpf.c
> +++ b/tools/lib/bpf/libbpf.c
> @@@ -2163,9 -2193,12 +2193,12 @@@ int bpf_prog_load_xattr(const struct bp
>   
>   	if (!attr)
>   		return -EINVAL;
> + 	if (!attr->file)
> + 		return -EINVAL;
>   
> - 	obj = bpf_object__open(attr->file);
> + 	obj = __bpf_object__open(attr->file, NULL, 0,
> + 				 bpf_prog_type__needs_kver(attr->prog_type));
>  -	if (IS_ERR(obj))
>  +	if (IS_ERR_OR_NULL(obj))
>   		return -ENOENT;

This is okay, thanks.  The OR_NULL is unnecessary just using the
bpf-next code is a better merge IMO.

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2018-05-14 20:41 ` Jakub Kicinski
@ 2018-05-14 21:57   ` Stephen Rothwell
  0 siblings, 0 replies; 69+ messages in thread
From: Stephen Rothwell @ 2018-05-14 21:57 UTC (permalink / raw)
  To: Jakub Kicinski, Alexei Starovoitov
  Cc: Daniel Borkmann, Networking, Linux-Next Mailing List,
	Linux Kernel Mailing List

[-- Attachment #1: Type: text/plain, Size: 958 bytes --]

Hi Jakub,

On Mon, 14 May 2018 13:41:40 -0700 Jakub Kicinski <jakub.kicinski@netronome.com> wrote:
>
> On Mon, 14 May 2018 11:57:00 +1000, Stephen Rothwell wrote:
> > diff --cc tools/lib/bpf/libbpf.c
> > index 8da4eeb101a6,df54c4c9e48a..000000000000
> > --- a/tools/lib/bpf/libbpf.c
> > +++ b/tools/lib/bpf/libbpf.c
> > @@@ -2163,9 -2193,12 +2193,12 @@@ int bpf_prog_load_xattr(const struct bp
> >   
> >   	if (!attr)
> >   		return -EINVAL;
> > + 	if (!attr->file)
> > + 		return -EINVAL;
> >   
> > - 	obj = bpf_object__open(attr->file);
> > + 	obj = __bpf_object__open(attr->file, NULL, 0,
> > + 				 bpf_prog_type__needs_kver(attr->prog_type));
> >  -	if (IS_ERR(obj))
> >  +	if (IS_ERR_OR_NULL(obj))
> >   		return -ENOENT;  
> 
> This is okay, thanks.  The OR_NULL is unnecessary just using the
> bpf-next code is a better merge IMO.

Thanks, I have updated my merge resolution from today.

-- 
Cheers,
Stephen Rothwell

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2018-11-12  0:54 Stephen Rothwell
  0 siblings, 0 replies; 69+ messages in thread
From: Stephen Rothwell @ 2018-11-12  0:54 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Networking
  Cc: Linux-Next Mailing List, Linux Kernel Mailing List,
	Andrey Ignatov, Nitin Hande

[-- Attachment #1: Type: text/plain, Size: 1751 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  net/core/filter.c

between commit:

  b13b8787c95c ("bpf: Fix IPv6 dport byte order in bpf_sk_lookup_udp")

from the bpf tree and commit:

  c8123ead13a5 ("bpf: Extend the sk_lookup() helper to XDP hookpoint.")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

-- 
Cheers,
Stephen Rothwell

diff --cc net/core/filter.c
index 9a1327eb25fa,53d50fb75ea1..000000000000
--- a/net/core/filter.c
+++ b/net/core/filter.c
@@@ -4852,19 -4867,19 +4867,18 @@@ static struct sock *sk_lookup(struct ne
  	} else {
  		struct in6_addr *src6 = (struct in6_addr *)&tuple->ipv6.saddr;
  		struct in6_addr *dst6 = (struct in6_addr *)&tuple->ipv6.daddr;
- 		int sdif = inet6_sdif(skb);
 -		u16 hnum = ntohs(tuple->ipv6.dport);
  
  		if (proto == IPPROTO_TCP)
- 			sk = __inet6_lookup(net, &tcp_hashinfo, skb, 0,
+ 			sk = __inet6_lookup(net, &tcp_hashinfo, NULL, 0,
  					    src6, tuple->ipv6.sport,
 -					    dst6, hnum,
 +					    dst6, ntohs(tuple->ipv6.dport),
  					    dif, sdif, &refcounted);
  		else if (likely(ipv6_bpf_stub))
  			sk = ipv6_bpf_stub->udp6_lib_lookup(net,
  							    src6, tuple->ipv6.sport,
 -							    dst6, hnum,
 +							    dst6, tuple->ipv6.dport,
  							    dif, sdif,
- 							    &udp_table, skb);
+ 							    &udp_table, NULL);
  #endif
  	}
  

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2018-12-04  1:05 Stephen Rothwell
  0 siblings, 0 replies; 69+ messages in thread
From: Stephen Rothwell @ 2018-12-04  1:05 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Networking
  Cc: Linux Next Mailing List, Linux Kernel Mailing List,
	Quentin Monnet, Joe Stringer

[-- Attachment #1: Type: text/plain, Size: 3370 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got conflicts in:

  include/uapi/linux/bpf.h

between commit:

  d74286d2c25a ("bpf: Improve socket lookup reuseport documentation")

from the bpf tree and commit:

  90b1023f68c7 ("bpf: fix documentation for eBPF helpers")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

-- 
Cheers,
Stephen Rothwell

diff --cc include/uapi/linux/bpf.h
index ec8b40ff386e,572eb2d42768..000000000000
--- a/include/uapi/linux/bpf.h
+++ b/include/uapi/linux/bpf.h
@@@ -2209,11 -2210,11 +2212,11 @@@ union bpf_attr 
   *		This helper is available only if the kernel was compiled with
   *		**CONFIG_NET** configuration option.
   *	Return
-  *		Pointer to *struct bpf_sock*, or NULL in case of failure.
-  *		For sockets with reuseport option, the *struct bpf_sock*
-  *		result is from reuse->socks[] using the hash of the tuple.
+  *		A pointer to *struct bpf_sock*, or **NULL** in case of failure.
 - *		For sockets with reuseport option, **struct bpf_sock**
++ *		For sockets with reuseport option, the **struct bpf_sock**
+  *		return is from **reuse->socks**\ [] using hash of the packet.
   *
 - * struct bpf_sock *bpf_sk_lookup_udp(void *ctx, struct bpf_sock_tuple *tuple, u32 tuple_size, u32 netns, u64 flags)
 + * struct bpf_sock *bpf_sk_lookup_udp(void *ctx, struct bpf_sock_tuple *tuple, u32 tuple_size, u64 netns, u64 flags)
   *	Description
   *		Look for UDP socket matching *tuple*, optionally in a child
   *		network namespace *netns*. The return value must be checked,
@@@ -2245,14 -2244,15 +2248,16 @@@
   *		This helper is available only if the kernel was compiled with
   *		**CONFIG_NET** configuration option.
   *	Return
-  *		Pointer to *struct bpf_sock*, or NULL in case of failure.
-  *		For sockets with reuseport option, the *struct bpf_sock*
-  *		result is from reuse->socks[] using the hash of the tuple.
+  *		A pointer to **struct bpf_sock**, or **NULL** in case of
 - *		failure. For sockets with reuseport option, **struct bpf_sock**
 - *		return is from **reuse->socks**\ [] using hash of the packet.
++ *		failure. For sockets with reuseport option, the
++ *		**struct bpf_sock** return is from **reuse->socks**\ []
++ *		using hash of the packet.
   *
-  * int bpf_sk_release(struct bpf_sock *sk)
+  * int bpf_sk_release(struct bpf_sock *sock)
   *	Description
-  *		Release the reference held by *sock*. *sock* must be a non-NULL
-  *		pointer that was returned from bpf_sk_lookup_xxx\ ().
+  *		Release the reference held by *sock*. *sock* must be a
+  *		non-**NULL** pointer that was returned from
+  *		**bpf_sk_lookup_xxx**\ ().
   *	Return
   *		0 on success, or a negative error in case of failure.
   *
@@@ -2494,8 -2495,9 +2509,9 @@@ struct __sk_buff 
  	/* ... here. */
  
  	__u32 data_meta;
 -	struct bpf_flow_keys *flow_keys;
 +	__bpf_md_ptr(struct bpf_flow_keys *, flow_keys);
  	__u64 tstamp;
+ 	__u32 wire_len;
  };
  
  struct bpf_tunnel_key {

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2018-12-04  1:09 Stephen Rothwell
  0 siblings, 0 replies; 69+ messages in thread
From: Stephen Rothwell @ 2018-12-04  1:09 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Networking
  Cc: Linux Next Mailing List, Linux Kernel Mailing List, Petar Penkov,
	Vlad Dumitrescu, Willem de Bruijn

[-- Attachment #1: Type: text/plain, Size: 2797 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  net/core/filter.c

between commit:

  b7df9ada9a77 ("bpf: fix pointer offsets in context for 32 bit")

from the bpf tree and commit:

  e3da08d05700 ("bpf: allow BPF read access to qdisc pkt_len")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

-- 
Cheers,
Stephen Rothwell

diff --cc net/core/filter.c
index 8659b40172d1,3d54af4c363d..000000000000
--- a/net/core/filter.c
+++ b/net/core/filter.c
@@@ -5771,9 -5770,10 +5771,10 @@@ static bool sk_filter_is_valid_access(i
  	case bpf_ctx_range(struct __sk_buff, data):
  	case bpf_ctx_range(struct __sk_buff, data_meta):
  	case bpf_ctx_range(struct __sk_buff, data_end):
 -	case bpf_ctx_range(struct __sk_buff, flow_keys):
 +	case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
  	case bpf_ctx_range_till(struct __sk_buff, family, local_port):
  	case bpf_ctx_range(struct __sk_buff, tstamp):
+ 	case bpf_ctx_range(struct __sk_buff, wire_len):
  		return false;
  	}
  
@@@ -5797,7 -5797,8 +5798,8 @@@ static bool cg_skb_is_valid_access(int 
  	switch (off) {
  	case bpf_ctx_range(struct __sk_buff, tc_classid):
  	case bpf_ctx_range(struct __sk_buff, data_meta):
 -	case bpf_ctx_range(struct __sk_buff, flow_keys):
 +	case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
+ 	case bpf_ctx_range(struct __sk_buff, wire_len):
  		return false;
  	case bpf_ctx_range(struct __sk_buff, data):
  	case bpf_ctx_range(struct __sk_buff, data_end):
@@@ -5842,8 -5843,9 +5844,9 @@@ static bool lwt_is_valid_access(int off
  	case bpf_ctx_range(struct __sk_buff, tc_classid):
  	case bpf_ctx_range_till(struct __sk_buff, family, local_port):
  	case bpf_ctx_range(struct __sk_buff, data_meta):
 -	case bpf_ctx_range(struct __sk_buff, flow_keys):
 +	case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
  	case bpf_ctx_range(struct __sk_buff, tstamp):
+ 	case bpf_ctx_range(struct __sk_buff, wire_len):
  		return false;
  	}
  
@@@ -6272,8 -6274,9 +6275,9 @@@ static bool sk_skb_is_valid_access(int 
  	switch (off) {
  	case bpf_ctx_range(struct __sk_buff, tc_classid):
  	case bpf_ctx_range(struct __sk_buff, data_meta):
 -	case bpf_ctx_range(struct __sk_buff, flow_keys):
 +	case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
  	case bpf_ctx_range(struct __sk_buff, tstamp):
+ 	case bpf_ctx_range(struct __sk_buff, wire_len):
  		return false;
  	}
  

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2019-04-17  1:08 Stephen Rothwell
  2019-04-24  3:12 ` Stephen Rothwell
  0 siblings, 1 reply; 69+ messages in thread
From: Stephen Rothwell @ 2019-04-17  1:08 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Networking
  Cc: Linux Next Mailing List, Linux Kernel Mailing List,
	Benjamin Poirier

[-- Attachment #1: Type: text/plain, Size: 1555 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  tools/bpf/bpftool/map.c

between commit:

  e0665239e07f ("bpftool: Fix errno variable usage")

from the bpf tree and commit:

  0478c3bf8124 ("bpftool: Use print_entry_error() in case of ENOENT when dumping")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

-- 
Cheers,
Stephen Rothwell

diff --cc tools/bpf/bpftool/map.c
index 1744bf61a0b8,44b192e87708..000000000000
--- a/tools/bpf/bpftool/map.c
+++ b/tools/bpf/bpftool/map.c
@@@ -722,11 -715,16 +715,16 @@@ static int dump_map_elem(int fd, void *
  		jsonw_string_field(json_wtr, "error", strerror(lookup_errno));
  		jsonw_end_object(json_wtr);
  	} else {
+ 		const char *msg = NULL;
+ 
 -		if (errno == ENOENT)
 +		if (lookup_errno == ENOENT)
- 			print_entry_plain(map_info, key, NULL);
- 		else
- 			print_entry_error(map_info, key,
- 					  strerror(lookup_errno));
+ 			msg = "<no entry>";
+ 		else if (lookup_errno == ENOSPC &&
+ 			 map_info->type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY)
+ 			msg = "<cannot read>";
+ 
+ 		print_entry_error(map_info, key,
+ 				  msg ? : strerror(lookup_errno));
  	}
  
  	return 0;

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2019-04-17  1:08 Stephen Rothwell
@ 2019-04-24  3:12 ` Stephen Rothwell
  0 siblings, 0 replies; 69+ messages in thread
From: Stephen Rothwell @ 2019-04-24  3:12 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Networking, David Miller
  Cc: Linux Next Mailing List, Linux Kernel Mailing List,
	Benjamin Poirier

[-- Attachment #1: Type: text/plain, Size: 1406 bytes --]

Hi all,

On Wed, 17 Apr 2019 11:08:56 +1000 Stephen Rothwell <sfr@canb.auug.org.au> wrote:
>
> Today's linux-next merge of the bpf-next tree got a conflict in:
> 
>   tools/bpf/bpftool/map.c
> 
> between commit:
> 
>   e0665239e07f ("bpftool: Fix errno variable usage")
> 
> from the bpf tree and commit:
> 
>   0478c3bf8124 ("bpftool: Use print_entry_error() in case of ENOENT when dumping")
> 
> from the bpf-next tree.
> 
> diff --cc tools/bpf/bpftool/map.c
> index 1744bf61a0b8,44b192e87708..000000000000
> --- a/tools/bpf/bpftool/map.c
> +++ b/tools/bpf/bpftool/map.c
> @@@ -722,11 -715,16 +715,16 @@@ static int dump_map_elem(int fd, void *
>   		jsonw_string_field(json_wtr, "error", strerror(lookup_errno));
>   		jsonw_end_object(json_wtr);
>   	} else {
> + 		const char *msg = NULL;
> + 
>  -		if (errno == ENOENT)
>  +		if (lookup_errno == ENOENT)
> - 			print_entry_plain(map_info, key, NULL);
> - 		else
> - 			print_entry_error(map_info, key,
> - 					  strerror(lookup_errno));
> + 			msg = "<no entry>";
> + 		else if (lookup_errno == ENOSPC &&
> + 			 map_info->type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY)
> + 			msg = "<cannot read>";
> + 
> + 		print_entry_error(map_info, key,
> + 				  msg ? : strerror(lookup_errno));
>   	}
>   
>   	return 0;

This is now a conflict between the net-next and bpf trees.

-- 
Cheers,
Stephen Rothwell

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2019-10-07 22:48 Stephen Rothwell
  2019-10-15 23:27 ` Stephen Rothwell
  0 siblings, 1 reply; 69+ messages in thread
From: Stephen Rothwell @ 2019-10-07 22:48 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Networking
  Cc: Linux Next Mailing List, Linux Kernel Mailing List, Yonghong Song,
	Toke Høiland-Jørgensen

[-- Attachment #1: Type: text/plain, Size: 1411 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  tools/lib/bpf/Makefile

between commit:

  1bd63524593b ("libbpf: handle symbol versioning properly for libbpf.a")

from the bpf tree and commit:

  a9eb048d5615 ("libbpf: Add cscope and tags targets to Makefile")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

-- 
Cheers,
Stephen Rothwell

diff --cc tools/lib/bpf/Makefile
index 56ce6292071b,10b77644a17c..000000000000
--- a/tools/lib/bpf/Makefile
+++ b/tools/lib/bpf/Makefile
@@@ -143,7 -133,9 +143,9 @@@ LIB_TARGET	:= $(addprefix $(OUTPUT),$(L
  LIB_FILE	:= $(addprefix $(OUTPUT),$(LIB_FILE))
  PC_FILE		:= $(addprefix $(OUTPUT),$(PC_FILE))
  
+ TAGS_PROG := $(if $(shell which etags 2>/dev/null),etags,ctags)
+ 
 -GLOBAL_SYM_COUNT = $(shell readelf -s --wide $(BPF_IN) | \
 +GLOBAL_SYM_COUNT = $(shell readelf -s --wide $(BPF_IN_SHARED) | \
  			   cut -d "@" -f1 | sed 's/_v[0-9]_[0-9]_[0-9].*//' | \
  			   awk '/GLOBAL/ && /DEFAULT/ && !/UND/ {print $$8}' | \
  			   sort -u | wc -l)

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2019-10-08 22:47 Stephen Rothwell
  2019-10-15 23:29 ` Stephen Rothwell
  0 siblings, 1 reply; 69+ messages in thread
From: Stephen Rothwell @ 2019-10-08 22:47 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Networking
  Cc: Linux Next Mailing List, Linux Kernel Mailing List,
	Andrii Nakryiko, Yonghong Song

[-- Attachment #1: Type: text/plain, Size: 3752 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  tools/lib/bpf/Makefile

between commit:

  1bd63524593b ("libbpf: handle symbol versioning properly for libbpf.a")

from the bpf tree and commit:

  e01a75c15969 ("libbpf: Move bpf_{helpers, helper_defs, endian, tracing}.h into libbpf")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

-- 
Cheers,
Stephen Rothwell

diff --cc tools/lib/bpf/Makefile
index 56ce6292071b,1270955e4845..000000000000
--- a/tools/lib/bpf/Makefile
+++ b/tools/lib/bpf/Makefile
@@@ -143,7 -133,9 +143,9 @@@ LIB_TARGET	:= $(addprefix $(OUTPUT),$(L
  LIB_FILE	:= $(addprefix $(OUTPUT),$(LIB_FILE))
  PC_FILE		:= $(addprefix $(OUTPUT),$(PC_FILE))
  
+ TAGS_PROG := $(if $(shell which etags 2>/dev/null),etags,ctags)
+ 
 -GLOBAL_SYM_COUNT = $(shell readelf -s --wide $(BPF_IN) | \
 +GLOBAL_SYM_COUNT = $(shell readelf -s --wide $(BPF_IN_SHARED) | \
  			   cut -d "@" -f1 | sed 's/_v[0-9]_[0-9]_[0-9].*//' | \
  			   awk '/GLOBAL/ && /DEFAULT/ && !/UND/ {print $$8}' | \
  			   sort -u | wc -l)
@@@ -165,7 -157,7 +167,7 @@@ all: fixde
  
  all_cmd: $(CMD_TARGETS) check
  
- $(BPF_IN_SHARED): force elfdep bpfdep
 -$(BPF_IN): force elfdep bpfdep bpf_helper_defs.h
++$(BPF_IN_SHARED): force elfdep bpfdep bpf_helper_defs.h
  	@(test -f ../../include/uapi/linux/bpf.h -a -f ../../../include/uapi/linux/bpf.h && ( \
  	(diff -B ../../include/uapi/linux/bpf.h ../../../include/uapi/linux/bpf.h >/dev/null) || \
  	echo "Warning: Kernel ABI header at 'tools/include/uapi/linux/bpf.h' differs from latest version at 'include/uapi/linux/bpf.h'" >&2 )) || true
@@@ -181,14 -173,15 +183,18 @@@
  	@(test -f ../../include/uapi/linux/if_xdp.h -a -f ../../../include/uapi/linux/if_xdp.h && ( \
  	(diff -B ../../include/uapi/linux/if_xdp.h ../../../include/uapi/linux/if_xdp.h >/dev/null) || \
  	echo "Warning: Kernel ABI header at 'tools/include/uapi/linux/if_xdp.h' differs from latest version at 'include/uapi/linux/if_xdp.h'" >&2 )) || true
 -	$(Q)$(MAKE) $(build)=libbpf
 +	$(Q)$(MAKE) $(build)=libbpf OUTPUT=$(SHARED_OBJDIR) CFLAGS="$(CFLAGS) $(SHLIB_FLAGS)"
 +
 +$(BPF_IN_STATIC): force elfdep bpfdep
 +	$(Q)$(MAKE) $(build)=libbpf OUTPUT=$(STATIC_OBJDIR)
  
+ bpf_helper_defs.h: $(srctree)/include/uapi/linux/bpf.h
+ 	$(Q)$(srctree)/scripts/bpf_helpers_doc.py --header 		\
+ 		--file $(srctree)/include/uapi/linux/bpf.h > bpf_helper_defs.h
+ 
  $(OUTPUT)libbpf.so: $(OUTPUT)libbpf.so.$(LIBBPF_VERSION)
  
 -$(OUTPUT)libbpf.so.$(LIBBPF_VERSION): $(BPF_IN)
 +$(OUTPUT)libbpf.so.$(LIBBPF_VERSION): $(BPF_IN_SHARED)
  	$(QUIET_LINK)$(CC) --shared -Wl,-soname,libbpf.so.$(LIBBPF_MAJOR_VERSION) \
  				    -Wl,--version-script=$(VERSION_SCRIPT) $^ -lelf -o $@
  	@ln -sf $(@F) $(OUTPUT)libbpf.so
@@@ -268,9 -266,9 +279,10 @@@ config-clean
  	$(Q)$(MAKE) -C $(srctree)/tools/build/feature/ clean >/dev/null
  
  clean:
 -	$(call QUIET_CLEAN, libbpf) $(RM) $(TARGETS) $(CXX_TEST_TARGET) \
 +	$(call QUIET_CLEAN, libbpf) $(RM) -rf $(TARGETS) $(CXX_TEST_TARGET) \
  		*.o *~ *.a *.so *.so.$(LIBBPF_MAJOR_VERSION) .*.d .*.cmd \
- 		*.pc LIBBPF-CFLAGS $(SHARED_OBJDIR) $(STATIC_OBJDIR)
 -		*.pc LIBBPF-CFLAGS bpf_helper_defs.h
++		*.pc LIBBPF-CFLAGS $(SHARED_OBJDIR) $(STATIC_OBJDIR) \
++		bpf_helper_defs.h
  	$(call QUIET_CLEAN, core-gen) $(RM) $(OUTPUT)FEATURE-DUMP.libbpf
  
  

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2019-10-07 22:48 Stephen Rothwell
@ 2019-10-15 23:27 ` Stephen Rothwell
  0 siblings, 0 replies; 69+ messages in thread
From: Stephen Rothwell @ 2019-10-15 23:27 UTC (permalink / raw)
  To: David Miller
  Cc: Daniel Borkmann, Alexei Starovoitov, Networking,
	Linux Next Mailing List, Linux Kernel Mailing List, Yonghong Song,
	Toke Høiland-Jørgensen

[-- Attachment #1: Type: text/plain, Size: 1672 bytes --]

Hi all,

This is now a conflict between the net and net-next trees.

On Tue, 8 Oct 2019 09:48:40 +1100 Stephen Rothwell <sfr@canb.auug.org.au> wrote:
>
> Today's linux-next merge of the bpf-next tree got a conflict in:
> 
>   tools/lib/bpf/Makefile
> 
> between commit:
> 
>   1bd63524593b ("libbpf: handle symbol versioning properly for libbpf.a")
> 
> from the bpf tree and commit:
> 
>   a9eb048d5615 ("libbpf: Add cscope and tags targets to Makefile")
> 
> from the bpf-next tree.
> 
> I fixed it up (see below) and can carry the fix as necessary. This
> is now fixed as far as linux-next is concerned, but any non trivial
> conflicts should be mentioned to your upstream maintainer when your tree
> is submitted for merging.  You may also want to consider cooperating
> with the maintainer of the conflicting tree to minimise any particularly
> complex conflicts.
> 
> -- 
> Cheers,
> Stephen Rothwell
> 
> diff --cc tools/lib/bpf/Makefile
> index 56ce6292071b,10b77644a17c..000000000000
> --- a/tools/lib/bpf/Makefile
> +++ b/tools/lib/bpf/Makefile
> @@@ -143,7 -133,9 +143,9 @@@ LIB_TARGET	:= $(addprefix $(OUTPUT),$(L
>   LIB_FILE	:= $(addprefix $(OUTPUT),$(LIB_FILE))
>   PC_FILE		:= $(addprefix $(OUTPUT),$(PC_FILE))
>   
> + TAGS_PROG := $(if $(shell which etags 2>/dev/null),etags,ctags)
> + 
>  -GLOBAL_SYM_COUNT = $(shell readelf -s --wide $(BPF_IN) | \
>  +GLOBAL_SYM_COUNT = $(shell readelf -s --wide $(BPF_IN_SHARED) | \
>   			   cut -d "@" -f1 | sed 's/_v[0-9]_[0-9]_[0-9].*//' | \
>   			   awk '/GLOBAL/ && /DEFAULT/ && !/UND/ {print $$8}' | \
>   			   sort -u | wc -l)

-- 
Cheers,
Stephen Rothwell

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2019-10-08 22:47 Stephen Rothwell
@ 2019-10-15 23:29 ` Stephen Rothwell
  0 siblings, 0 replies; 69+ messages in thread
From: Stephen Rothwell @ 2019-10-15 23:29 UTC (permalink / raw)
  To: David Miller
  Cc: Daniel Borkmann, Alexei Starovoitov, Networking,
	Linux Next Mailing List, Linux Kernel Mailing List,
	Andrii Nakryiko, Yonghong Song

[-- Attachment #1: Type: text/plain, Size: 4103 bytes --]

Hi all,

This is now a conflict between the net and net-next trees.

On Wed, 9 Oct 2019 09:47:25 +1100 Stephen Rothwell <sfr@canb.auug.org.au> wrote:
>
> Today's linux-next merge of the bpf-next tree got a conflict in:
> 
>   tools/lib/bpf/Makefile
> 
> between commit:
> 
>   1bd63524593b ("libbpf: handle symbol versioning properly for libbpf.a")
> 
> from the bpf tree and commit:
> 
>   e01a75c15969 ("libbpf: Move bpf_{helpers, helper_defs, endian, tracing}.h into libbpf")
> 
> from the bpf-next tree.
> 
> I fixed it up (see below) and can carry the fix as necessary. This
> is now fixed as far as linux-next is concerned, but any non trivial
> conflicts should be mentioned to your upstream maintainer when your tree
> is submitted for merging.  You may also want to consider cooperating
> with the maintainer of the conflicting tree to minimise any particularly
> complex conflicts.
> 
> -- 
> Cheers,
> Stephen Rothwell
> 
> diff --cc tools/lib/bpf/Makefile
> index 56ce6292071b,1270955e4845..000000000000
> --- a/tools/lib/bpf/Makefile
> +++ b/tools/lib/bpf/Makefile
> @@@ -143,7 -133,9 +143,9 @@@ LIB_TARGET	:= $(addprefix $(OUTPUT),$(L
>   LIB_FILE	:= $(addprefix $(OUTPUT),$(LIB_FILE))
>   PC_FILE		:= $(addprefix $(OUTPUT),$(PC_FILE))
>   
> + TAGS_PROG := $(if $(shell which etags 2>/dev/null),etags,ctags)
> + 
>  -GLOBAL_SYM_COUNT = $(shell readelf -s --wide $(BPF_IN) | \
>  +GLOBAL_SYM_COUNT = $(shell readelf -s --wide $(BPF_IN_SHARED) | \
>   			   cut -d "@" -f1 | sed 's/_v[0-9]_[0-9]_[0-9].*//' | \
>   			   awk '/GLOBAL/ && /DEFAULT/ && !/UND/ {print $$8}' | \
>   			   sort -u | wc -l)
> @@@ -165,7 -157,7 +167,7 @@@ all: fixde
>   
>   all_cmd: $(CMD_TARGETS) check
>   
> - $(BPF_IN_SHARED): force elfdep bpfdep
>  -$(BPF_IN): force elfdep bpfdep bpf_helper_defs.h
> ++$(BPF_IN_SHARED): force elfdep bpfdep bpf_helper_defs.h
>   	@(test -f ../../include/uapi/linux/bpf.h -a -f ../../../include/uapi/linux/bpf.h && ( \
>   	(diff -B ../../include/uapi/linux/bpf.h ../../../include/uapi/linux/bpf.h >/dev/null) || \
>   	echo "Warning: Kernel ABI header at 'tools/include/uapi/linux/bpf.h' differs from latest version at 'include/uapi/linux/bpf.h'" >&2 )) || true
> @@@ -181,14 -173,15 +183,18 @@@
>   	@(test -f ../../include/uapi/linux/if_xdp.h -a -f ../../../include/uapi/linux/if_xdp.h && ( \
>   	(diff -B ../../include/uapi/linux/if_xdp.h ../../../include/uapi/linux/if_xdp.h >/dev/null) || \
>   	echo "Warning: Kernel ABI header at 'tools/include/uapi/linux/if_xdp.h' differs from latest version at 'include/uapi/linux/if_xdp.h'" >&2 )) || true
>  -	$(Q)$(MAKE) $(build)=libbpf
>  +	$(Q)$(MAKE) $(build)=libbpf OUTPUT=$(SHARED_OBJDIR) CFLAGS="$(CFLAGS) $(SHLIB_FLAGS)"
>  +
>  +$(BPF_IN_STATIC): force elfdep bpfdep
>  +	$(Q)$(MAKE) $(build)=libbpf OUTPUT=$(STATIC_OBJDIR)
>   
> + bpf_helper_defs.h: $(srctree)/include/uapi/linux/bpf.h
> + 	$(Q)$(srctree)/scripts/bpf_helpers_doc.py --header 		\
> + 		--file $(srctree)/include/uapi/linux/bpf.h > bpf_helper_defs.h
> + 
>   $(OUTPUT)libbpf.so: $(OUTPUT)libbpf.so.$(LIBBPF_VERSION)
>   
>  -$(OUTPUT)libbpf.so.$(LIBBPF_VERSION): $(BPF_IN)
>  +$(OUTPUT)libbpf.so.$(LIBBPF_VERSION): $(BPF_IN_SHARED)
>   	$(QUIET_LINK)$(CC) --shared -Wl,-soname,libbpf.so.$(LIBBPF_MAJOR_VERSION) \
>   				    -Wl,--version-script=$(VERSION_SCRIPT) $^ -lelf -o $@
>   	@ln -sf $(@F) $(OUTPUT)libbpf.so
> @@@ -268,9 -266,9 +279,10 @@@ config-clean
>   	$(Q)$(MAKE) -C $(srctree)/tools/build/feature/ clean >/dev/null
>   
>   clean:
>  -	$(call QUIET_CLEAN, libbpf) $(RM) $(TARGETS) $(CXX_TEST_TARGET) \
>  +	$(call QUIET_CLEAN, libbpf) $(RM) -rf $(TARGETS) $(CXX_TEST_TARGET) \
>   		*.o *~ *.a *.so *.so.$(LIBBPF_MAJOR_VERSION) .*.d .*.cmd \
> - 		*.pc LIBBPF-CFLAGS $(SHARED_OBJDIR) $(STATIC_OBJDIR)
>  -		*.pc LIBBPF-CFLAGS bpf_helper_defs.h
> ++		*.pc LIBBPF-CFLAGS $(SHARED_OBJDIR) $(STATIC_OBJDIR) \
> ++		bpf_helper_defs.h
>   	$(call QUIET_CLEAN, core-gen) $(RM) $(OUTPUT)FEATURE-DUMP.libbpf
>   
>   

-- 
Cheers,
Stephen Rothwell

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2020-05-15  3:18 Stephen Rothwell
  0 siblings, 0 replies; 69+ messages in thread
From: Stephen Rothwell @ 2020-05-15  3:18 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Networking
  Cc: Linux Next Mailing List, Linux Kernel Mailing List, Yonghong Song

[-- Attachment #1: Type: text/plain, Size: 748 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  kernel/bpf/verifier.c

between commit:

  e92888c72fbd ("bpf: Enforce returning 0 for fentry/fexit progs")

from the bpf tree and commit:

  15d83c4d7cef ("bpf: Allow loading of a bpf_iter program")

from the bpf-next tree.

I fixed it up (I just used the latter version) and can carry the fix as
necessary. This is now fixed as far as linux-next is concerned, but any
non trivial conflicts should be mentioned to your upstream maintainer
when your tree is submitted for merging.  You may also want to consider
cooperating with the maintainer of the conflicting tree to minimise any
particularly complex conflicts.

-- 
Cheers,
Stephen Rothwell

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2020-06-26  0:05 Stephen Rothwell
  2020-07-06  1:43 ` Stephen Rothwell
  0 siblings, 1 reply; 69+ messages in thread
From: Stephen Rothwell @ 2020-06-26  0:05 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Networking
  Cc: Linux Next Mailing List, Linux Kernel Mailing List, Yonghong Song,
	Andrii Nakryiko

[-- Attachment #1: Type: text/plain, Size: 1792 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  tools/testing/selftests/bpf/progs/bpf_iter_netlink.c

between commits:

  9c82a63cf370 ("libbpf: Fix CO-RE relocs against .text section")
  647b502e3d54 ("selftests/bpf: Refactor some net macros to bpf_tracing_net.h")

from the bpf tree and commit:

  84544f5637ff ("selftests/bpf: Move newer bpf_iter_* type redefining to a new header file")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

-- 
Cheers,
Stephen Rothwell

diff --cc tools/testing/selftests/bpf/progs/bpf_iter_netlink.c
index 75ecf956a2df,cec82a419800..000000000000
--- a/tools/testing/selftests/bpf/progs/bpf_iter_netlink.c
+++ b/tools/testing/selftests/bpf/progs/bpf_iter_netlink.c
@@@ -11,21 -7,7 +7,7 @@@
  
  char _license[] SEC("license") = "GPL";
  
- #define sk_rmem_alloc	sk_backlog.rmem_alloc
- #define sk_refcnt	__sk_common.skc_refcnt
- 
- struct bpf_iter_meta {
- 	struct seq_file *seq;
- 	__u64 session_id;
- 	__u64 seq_num;
- } __attribute__((preserve_access_index));
- 
- struct bpf_iter__netlink {
- 	struct bpf_iter_meta *meta;
- 	struct netlink_sock *sk;
- } __attribute__((preserve_access_index));
- 
 -static inline struct inode *SOCK_INODE(struct socket *socket)
 +static __attribute__((noinline)) struct inode *SOCK_INODE(struct socket *socket)
  {
  	return &container_of(socket, struct socket_alloc, socket)->vfs_inode;
  }

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2020-06-26  0:05 Stephen Rothwell
@ 2020-07-06  1:43 ` Stephen Rothwell
  0 siblings, 0 replies; 69+ messages in thread
From: Stephen Rothwell @ 2020-07-06  1:43 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Networking, David Miller
  Cc: Linux Next Mailing List, Linux Kernel Mailing List, Yonghong Song,
	Andrii Nakryiko

[-- Attachment #1: Type: text/plain, Size: 2042 bytes --]

Hi all,

On Fri, 26 Jun 2020 10:05:27 +1000 Stephen Rothwell <sfr@canb.auug.org.au> wrote:
>
> Today's linux-next merge of the bpf-next tree got a conflict in:
> 
>   tools/testing/selftests/bpf/progs/bpf_iter_netlink.c
> 
> between commits:
> 
>   9c82a63cf370 ("libbpf: Fix CO-RE relocs against .text section")
>   647b502e3d54 ("selftests/bpf: Refactor some net macros to bpf_tracing_net.h")
> 
> from the bpf tree and commit:
> 
>   84544f5637ff ("selftests/bpf: Move newer bpf_iter_* type redefining to a new header file")
> 
> from the bpf-next tree.
> 
> I fixed it up (see below) and can carry the fix as necessary. This
> is now fixed as far as linux-next is concerned, but any non trivial
> conflicts should be mentioned to your upstream maintainer when your tree
> is submitted for merging.  You may also want to consider cooperating
> with the maintainer of the conflicting tree to minimise any particularly
> complex conflicts.
> 
> diff --cc tools/testing/selftests/bpf/progs/bpf_iter_netlink.c
> index 75ecf956a2df,cec82a419800..000000000000
> --- a/tools/testing/selftests/bpf/progs/bpf_iter_netlink.c
> +++ b/tools/testing/selftests/bpf/progs/bpf_iter_netlink.c
> @@@ -11,21 -7,7 +7,7 @@@
>   
>   char _license[] SEC("license") = "GPL";
>   
> - #define sk_rmem_alloc	sk_backlog.rmem_alloc
> - #define sk_refcnt	__sk_common.skc_refcnt
> - 
> - struct bpf_iter_meta {
> - 	struct seq_file *seq;
> - 	__u64 session_id;
> - 	__u64 seq_num;
> - } __attribute__((preserve_access_index));
> - 
> - struct bpf_iter__netlink {
> - 	struct bpf_iter_meta *meta;
> - 	struct netlink_sock *sk;
> - } __attribute__((preserve_access_index));
> - 
>  -static inline struct inode *SOCK_INODE(struct socket *socket)
>  +static __attribute__((noinline)) struct inode *SOCK_INODE(struct socket *socket)
>   {
>   	return &container_of(socket, struct socket_alloc, socket)->vfs_inode;
>   }

This is now a conflict between net-next tree and the net tree.

-- 
Cheers,
Stephen Rothwell

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2020-09-30  4:07 Stephen Rothwell
  2020-10-02  3:59 ` Stephen Rothwell
  0 siblings, 1 reply; 69+ messages in thread
From: Stephen Rothwell @ 2020-09-30  4:07 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Networking
  Cc: Andrii Nakryiko, Tony Ambardar, Linux Next Mailing List,
	Linux Kernel Mailing List

[-- Attachment #1: Type: text/plain, Size: 773 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  tools/lib/bpf/btf.c

between commit:

  1245008122d7 ("libbpf: Fix native endian assumption when parsing BTF")

from the bpf tree and commit:

  3289959b97ca ("libbpf: Support BTF loading and raw data output in both endianness")

from the bpf-next tree.

I fixed it up (I used the latter version) and can carry the fix as
necessary. This is now fixed as far as linux-next is concerned, but any
non trivial conflicts should be mentioned to your upstream maintainer
when your tree is submitted for merging.  You may also want to consider
cooperating with the maintainer of the conflicting tree to minimise any
particularly complex conflicts.

-- 
Cheers,
Stephen Rothwell

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2020-09-30  4:07 Stephen Rothwell
@ 2020-10-02  3:59 ` Stephen Rothwell
  0 siblings, 0 replies; 69+ messages in thread
From: Stephen Rothwell @ 2020-10-02  3:59 UTC (permalink / raw)
  To: Networking, David Miller
  Cc: Daniel Borkmann, Alexei Starovoitov, Andrii Nakryiko,
	Tony Ambardar, Linux Next Mailing List, Linux Kernel Mailing List

[-- Attachment #1: Type: text/plain, Size: 959 bytes --]

Hi all,

On Wed, 30 Sep 2020 14:07:15 +1000 Stephen Rothwell <sfr@canb.auug.org.au> wrote:
>
> Today's linux-next merge of the bpf-next tree got a conflict in:
> 
>   tools/lib/bpf/btf.c
> 
> between commit:
> 
>   1245008122d7 ("libbpf: Fix native endian assumption when parsing BTF")
> 
> from the bpf tree and commit:
> 
>   3289959b97ca ("libbpf: Support BTF loading and raw data output in both endianness")
> 
> from the bpf-next tree.
> 
> I fixed it up (I used the latter version) and can carry the fix as
> necessary. This is now fixed as far as linux-next is concerned, but any
> non trivial conflicts should be mentioned to your upstream maintainer
> when your tree is submitted for merging.  You may also want to consider
> cooperating with the maintainer of the conflicting tree to minimise any
> particularly complex conflicts.

This is now a conflict between the net-next and net trees.
-- 
Cheers,
Stephen Rothwell

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2021-12-05 23:39 Stephen Rothwell
  0 siblings, 0 replies; 69+ messages in thread
From: Stephen Rothwell @ 2021-12-05 23:39 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Andrii Nakryiko, bpf,
	Networking
  Cc: Kumar Kartikeya Dwivedi, Linux Kernel Mailing List,
	Linux Next Mailing List

[-- Attachment #1: Type: text/plain, Size: 12085 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  kernel/bpf/btf.c

between commit:

  d9847eb8be3d ("bpf: Make CONFIG_DEBUG_INFO_BTF depend upon CONFIG_BPF_SYSCALL")

from the bpf tree and commit:

  29db4bea1d10 ("bpf: Prepare relo_core.c for kernel duty.")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

-- 
Cheers,
Stephen Rothwell

diff --cc kernel/bpf/btf.c
index 48cdf5b425a7,36a5cc0f53c6..000000000000
--- a/kernel/bpf/btf.c
+++ b/kernel/bpf/btf.c
@@@ -6405,4 -6418,382 +6409,384 @@@ bool bpf_check_mod_kfunc_call(struct kf
  DEFINE_KFUNC_BTF_ID_LIST(bpf_tcp_ca_kfunc_list);
  DEFINE_KFUNC_BTF_ID_LIST(prog_test_kfunc_list);
  
 +#endif
++
+ int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
+ 			      const struct btf *targ_btf, __u32 targ_id)
+ {
+ 	return -EOPNOTSUPP;
+ }
+ 
+ static bool bpf_core_is_flavor_sep(const char *s)
+ {
+ 	/* check X___Y name pattern, where X and Y are not underscores */
+ 	return s[0] != '_' &&				      /* X */
+ 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
+ 	       s[4] != '_';				      /* Y */
+ }
+ 
+ size_t bpf_core_essential_name_len(const char *name)
+ {
+ 	size_t n = strlen(name);
+ 	int i;
+ 
+ 	for (i = n - 5; i >= 0; i--) {
+ 		if (bpf_core_is_flavor_sep(name + i))
+ 			return i + 1;
+ 	}
+ 	return n;
+ }
+ 
+ struct bpf_cand_cache {
+ 	const char *name;
+ 	u32 name_len;
+ 	u16 kind;
+ 	u16 cnt;
+ 	struct {
+ 		const struct btf *btf;
+ 		u32 id;
+ 	} cands[];
+ };
+ 
+ static void bpf_free_cands(struct bpf_cand_cache *cands)
+ {
+ 	if (!cands->cnt)
+ 		/* empty candidate array was allocated on stack */
+ 		return;
+ 	kfree(cands);
+ }
+ 
+ static void bpf_free_cands_from_cache(struct bpf_cand_cache *cands)
+ {
+ 	kfree(cands->name);
+ 	kfree(cands);
+ }
+ 
+ #define VMLINUX_CAND_CACHE_SIZE 31
+ static struct bpf_cand_cache *vmlinux_cand_cache[VMLINUX_CAND_CACHE_SIZE];
+ 
+ #define MODULE_CAND_CACHE_SIZE 31
+ static struct bpf_cand_cache *module_cand_cache[MODULE_CAND_CACHE_SIZE];
+ 
+ static DEFINE_MUTEX(cand_cache_mutex);
+ 
+ static void __print_cand_cache(struct bpf_verifier_log *log,
+ 			       struct bpf_cand_cache **cache,
+ 			       int cache_size)
+ {
+ 	struct bpf_cand_cache *cc;
+ 	int i, j;
+ 
+ 	for (i = 0; i < cache_size; i++) {
+ 		cc = cache[i];
+ 		if (!cc)
+ 			continue;
+ 		bpf_log(log, "[%d]%s(", i, cc->name);
+ 		for (j = 0; j < cc->cnt; j++) {
+ 			bpf_log(log, "%d", cc->cands[j].id);
+ 			if (j < cc->cnt - 1)
+ 				bpf_log(log, " ");
+ 		}
+ 		bpf_log(log, "), ");
+ 	}
+ }
+ 
+ static void print_cand_cache(struct bpf_verifier_log *log)
+ {
+ 	mutex_lock(&cand_cache_mutex);
+ 	bpf_log(log, "vmlinux_cand_cache:");
+ 	__print_cand_cache(log, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
+ 	bpf_log(log, "\nmodule_cand_cache:");
+ 	__print_cand_cache(log, module_cand_cache, MODULE_CAND_CACHE_SIZE);
+ 	bpf_log(log, "\n");
+ 	mutex_unlock(&cand_cache_mutex);
+ }
+ 
+ static u32 hash_cands(struct bpf_cand_cache *cands)
+ {
+ 	return jhash(cands->name, cands->name_len, 0);
+ }
+ 
+ static struct bpf_cand_cache *check_cand_cache(struct bpf_cand_cache *cands,
+ 					       struct bpf_cand_cache **cache,
+ 					       int cache_size)
+ {
+ 	struct bpf_cand_cache *cc = cache[hash_cands(cands) % cache_size];
+ 
+ 	if (cc && cc->name_len == cands->name_len &&
+ 	    !strncmp(cc->name, cands->name, cands->name_len))
+ 		return cc;
+ 	return NULL;
+ }
+ 
+ static size_t sizeof_cands(int cnt)
+ {
+ 	return offsetof(struct bpf_cand_cache, cands[cnt]);
+ }
+ 
+ static struct bpf_cand_cache *populate_cand_cache(struct bpf_cand_cache *cands,
+ 						  struct bpf_cand_cache **cache,
+ 						  int cache_size)
+ {
+ 	struct bpf_cand_cache **cc = &cache[hash_cands(cands) % cache_size], *new_cands;
+ 
+ 	if (*cc) {
+ 		bpf_free_cands_from_cache(*cc);
+ 		*cc = NULL;
+ 	}
+ 	new_cands = kmalloc(sizeof_cands(cands->cnt), GFP_KERNEL);
+ 	if (!new_cands) {
+ 		bpf_free_cands(cands);
+ 		return ERR_PTR(-ENOMEM);
+ 	}
+ 	memcpy(new_cands, cands, sizeof_cands(cands->cnt));
+ 	/* strdup the name, since it will stay in cache.
+ 	 * the cands->name points to strings in prog's BTF and the prog can be unloaded.
+ 	 */
+ 	new_cands->name = kmemdup_nul(cands->name, cands->name_len, GFP_KERNEL);
+ 	bpf_free_cands(cands);
+ 	if (!new_cands->name) {
+ 		kfree(new_cands);
+ 		return ERR_PTR(-ENOMEM);
+ 	}
+ 	*cc = new_cands;
+ 	return new_cands;
+ }
+ 
+ static void __purge_cand_cache(struct btf *btf, struct bpf_cand_cache **cache,
+ 			       int cache_size)
+ {
+ 	struct bpf_cand_cache *cc;
+ 	int i, j;
+ 
+ 	for (i = 0; i < cache_size; i++) {
+ 		cc = cache[i];
+ 		if (!cc)
+ 			continue;
+ 		if (!btf) {
+ 			/* when new module is loaded purge all of module_cand_cache,
+ 			 * since new module might have candidates with the name
+ 			 * that matches cached cands.
+ 			 */
+ 			bpf_free_cands_from_cache(cc);
+ 			cache[i] = NULL;
+ 			continue;
+ 		}
+ 		/* when module is unloaded purge cache entries
+ 		 * that match module's btf
+ 		 */
+ 		for (j = 0; j < cc->cnt; j++)
+ 			if (cc->cands[j].btf == btf) {
+ 				bpf_free_cands_from_cache(cc);
+ 				cache[i] = NULL;
+ 				break;
+ 			}
+ 	}
+ 
+ }
+ 
+ static void purge_cand_cache(struct btf *btf)
+ {
+ 	mutex_lock(&cand_cache_mutex);
+ 	__purge_cand_cache(btf, module_cand_cache, MODULE_CAND_CACHE_SIZE);
+ 	mutex_unlock(&cand_cache_mutex);
+ }
+ 
+ static struct bpf_cand_cache *
+ bpf_core_add_cands(struct bpf_cand_cache *cands, const struct btf *targ_btf,
+ 		   int targ_start_id)
+ {
+ 	struct bpf_cand_cache *new_cands;
+ 	const struct btf_type *t;
+ 	const char *targ_name;
+ 	size_t targ_essent_len;
+ 	int n, i;
+ 
+ 	n = btf_nr_types(targ_btf);
+ 	for (i = targ_start_id; i < n; i++) {
+ 		t = btf_type_by_id(targ_btf, i);
+ 		if (btf_kind(t) != cands->kind)
+ 			continue;
+ 
+ 		targ_name = btf_name_by_offset(targ_btf, t->name_off);
+ 		if (!targ_name)
+ 			continue;
+ 
+ 		/* the resched point is before strncmp to make sure that search
+ 		 * for non-existing name will have a chance to schedule().
+ 		 */
+ 		cond_resched();
+ 
+ 		if (strncmp(cands->name, targ_name, cands->name_len) != 0)
+ 			continue;
+ 
+ 		targ_essent_len = bpf_core_essential_name_len(targ_name);
+ 		if (targ_essent_len != cands->name_len)
+ 			continue;
+ 
+ 		/* most of the time there is only one candidate for a given kind+name pair */
+ 		new_cands = kmalloc(sizeof_cands(cands->cnt + 1), GFP_KERNEL);
+ 		if (!new_cands) {
+ 			bpf_free_cands(cands);
+ 			return ERR_PTR(-ENOMEM);
+ 		}
+ 
+ 		memcpy(new_cands, cands, sizeof_cands(cands->cnt));
+ 		bpf_free_cands(cands);
+ 		cands = new_cands;
+ 		cands->cands[cands->cnt].btf = targ_btf;
+ 		cands->cands[cands->cnt].id = i;
+ 		cands->cnt++;
+ 	}
+ 	return cands;
+ }
+ 
+ static struct bpf_cand_cache *
+ bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id)
+ {
+ 	struct bpf_cand_cache *cands, *cc, local_cand = {};
+ 	const struct btf *local_btf = ctx->btf;
+ 	const struct btf_type *local_type;
+ 	const struct btf *main_btf;
+ 	size_t local_essent_len;
+ 	struct btf *mod_btf;
+ 	const char *name;
+ 	int id;
+ 
+ 	main_btf = bpf_get_btf_vmlinux();
+ 	if (IS_ERR(main_btf))
+ 		return (void *)main_btf;
+ 
+ 	local_type = btf_type_by_id(local_btf, local_type_id);
+ 	if (!local_type)
+ 		return ERR_PTR(-EINVAL);
+ 
+ 	name = btf_name_by_offset(local_btf, local_type->name_off);
+ 	if (str_is_empty(name))
+ 		return ERR_PTR(-EINVAL);
+ 	local_essent_len = bpf_core_essential_name_len(name);
+ 
+ 	cands = &local_cand;
+ 	cands->name = name;
+ 	cands->kind = btf_kind(local_type);
+ 	cands->name_len = local_essent_len;
+ 
+ 	cc = check_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
+ 	/* cands is a pointer to stack here */
+ 	if (cc) {
+ 		if (cc->cnt)
+ 			return cc;
+ 		goto check_modules;
+ 	}
+ 
+ 	/* Attempt to find target candidates in vmlinux BTF first */
+ 	cands = bpf_core_add_cands(cands, main_btf, 1);
+ 	if (IS_ERR(cands))
+ 		return cands;
+ 
+ 	/* cands is a pointer to kmalloced memory here if cands->cnt > 0 */
+ 
+ 	/* populate cache even when cands->cnt == 0 */
+ 	cc = populate_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
+ 	if (IS_ERR(cc))
+ 		return cc;
+ 
+ 	/* if vmlinux BTF has any candidate, don't go for module BTFs */
+ 	if (cc->cnt)
+ 		return cc;
+ 
+ check_modules:
+ 	/* cands is a pointer to stack here and cands->cnt == 0 */
+ 	cc = check_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
+ 	if (cc)
+ 		/* if cache has it return it even if cc->cnt == 0 */
+ 		return cc;
+ 
+ 	/* If candidate is not found in vmlinux's BTF then search in module's BTFs */
+ 	spin_lock_bh(&btf_idr_lock);
+ 	idr_for_each_entry(&btf_idr, mod_btf, id) {
+ 		if (!btf_is_module(mod_btf))
+ 			continue;
+ 		/* linear search could be slow hence unlock/lock
+ 		 * the IDR to avoiding holding it for too long
+ 		 */
+ 		btf_get(mod_btf);
+ 		spin_unlock_bh(&btf_idr_lock);
+ 		cands = bpf_core_add_cands(cands, mod_btf, btf_nr_types(main_btf));
+ 		if (IS_ERR(cands)) {
+ 			btf_put(mod_btf);
+ 			return cands;
+ 		}
+ 		spin_lock_bh(&btf_idr_lock);
+ 		btf_put(mod_btf);
+ 	}
+ 	spin_unlock_bh(&btf_idr_lock);
+ 	/* cands is a pointer to kmalloced memory here if cands->cnt > 0
+ 	 * or pointer to stack if cands->cnd == 0.
+ 	 * Copy it into the cache even when cands->cnt == 0 and
+ 	 * return the result.
+ 	 */
+ 	return populate_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
+ }
+ 
+ int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
+ 		   int relo_idx, void *insn)
+ {
+ 	bool need_cands = relo->kind != BPF_CORE_TYPE_ID_LOCAL;
+ 	struct bpf_core_cand_list cands = {};
+ 	struct bpf_core_spec *specs;
+ 	int err;
+ 
+ 	/* ~4k of temp memory necessary to convert LLVM spec like "0:1:0:5"
+ 	 * into arrays of btf_ids of struct fields and array indices.
+ 	 */
+ 	specs = kcalloc(3, sizeof(*specs), GFP_KERNEL);
+ 	if (!specs)
+ 		return -ENOMEM;
+ 
+ 	if (need_cands) {
+ 		struct bpf_cand_cache *cc;
+ 		int i;
+ 
+ 		mutex_lock(&cand_cache_mutex);
+ 		cc = bpf_core_find_cands(ctx, relo->type_id);
+ 		if (IS_ERR(cc)) {
+ 			bpf_log(ctx->log, "target candidate search failed for %d\n",
+ 				relo->type_id);
+ 			err = PTR_ERR(cc);
+ 			goto out;
+ 		}
+ 		if (cc->cnt) {
+ 			cands.cands = kcalloc(cc->cnt, sizeof(*cands.cands), GFP_KERNEL);
+ 			if (!cands.cands) {
+ 				err = -ENOMEM;
+ 				goto out;
+ 			}
+ 		}
+ 		for (i = 0; i < cc->cnt; i++) {
+ 			bpf_log(ctx->log,
+ 				"CO-RE relocating %s %s: found target candidate [%d]\n",
+ 				btf_kind_str[cc->kind], cc->name, cc->cands[i].id);
+ 			cands.cands[i].btf = cc->cands[i].btf;
+ 			cands.cands[i].id = cc->cands[i].id;
+ 		}
+ 		cands.len = cc->cnt;
+ 		/* cand_cache_mutex needs to span the cache lookup and
+ 		 * copy of btf pointer into bpf_core_cand_list,
+ 		 * since module can be unloaded while bpf_core_apply_relo_insn
+ 		 * is working with module's btf.
+ 		 */
+ 	}
+ 
+ 	err = bpf_core_apply_relo_insn((void *)ctx->log, insn, relo->insn_off / 8,
+ 				       relo, relo_idx, ctx->btf, &cands, specs);
+ out:
+ 	kfree(specs);
+ 	if (need_cands) {
+ 		kfree(cands.cands);
+ 		mutex_unlock(&cand_cache_mutex);
+ 		if (ctx->log->level & BPF_LOG_LEVEL2)
+ 			print_cand_cache(ctx->log);
+ 	}
+ 	return err;
+ }

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2022-08-22  1:01 Stephen Rothwell
  0 siblings, 0 replies; 69+ messages in thread
From: Stephen Rothwell @ 2022-08-22  1:01 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Andrii Nakryiko, bpf,
	Networking
  Cc: Daniel Müller, Linux Kernel Mailing List,
	Linux Next Mailing List, Martin KaFai Lau

[-- Attachment #1: Type: text/plain, Size: 1490 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  tools/testing/selftests/bpf/DENYLIST.s390x

between commit:

  27e23836ce22 ("selftests/bpf: Add lru_bug to s390x deny list")

from the bpf tree and commit:

  b979f005d9b1 ("selftest/bpf: Add setget_sockopt to DENYLIST.s390x")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

-- 
Cheers,
Stephen Rothwell

diff --cc tools/testing/selftests/bpf/DENYLIST.s390x
index 5cadfbdadf36,a708c3dcc154..000000000000
--- a/tools/testing/selftests/bpf/DENYLIST.s390x
+++ b/tools/testing/selftests/bpf/DENYLIST.s390x
@@@ -65,4 -65,4 +65,5 @@@ send_signa
  select_reuseport                         # intermittently fails on new s390x setup
  xdp_synproxy                             # JIT does not support calling kernel function                                (kfunc)
  unpriv_bpf_disabled                      # fentry
 +lru_bug                                  # prog 'printk': failed to auto-attach: -524
+ setget_sockopt                           # attach unexpected error: -524                                               (trampoline)

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2022-08-25  0:50 Stephen Rothwell
  0 siblings, 0 replies; 69+ messages in thread
From: Stephen Rothwell @ 2022-08-25  0:50 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Andrii Nakryiko, bpf,
	Networking
  Cc: Daniel Müller, Linux Kernel Mailing List,
	Linux Next Mailing List, Martin KaFai Lau

[-- Attachment #1: Type: text/plain, Size: 1697 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  tools/testing/selftests/bpf/DENYLIST.s390x

between commit:

  27e23836ce22 ("selftests/bpf: Add lru_bug to s390x deny list")

from the bpf tree and commits:

  b979f005d9b1 ("selftest/bpf: Add setget_sockopt to DENYLIST.s390x")
  092e67772728 ("selftests/bpf: Add cb_refs test to s390x deny list")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

-- 
Cheers,
Stephen Rothwell

diff --cc tools/testing/selftests/bpf/DENYLIST.s390x
index 5cadfbdadf36,37bafcbf952a..000000000000
--- a/tools/testing/selftests/bpf/DENYLIST.s390x
+++ b/tools/testing/selftests/bpf/DENYLIST.s390x
@@@ -65,4 -65,5 +65,6 @@@ send_signa
  select_reuseport                         # intermittently fails on new s390x setup
  xdp_synproxy                             # JIT does not support calling kernel function                                (kfunc)
  unpriv_bpf_disabled                      # fentry
 +lru_bug                                  # prog 'printk': failed to auto-attach: -524
+ setget_sockopt                           # attach unexpected error: -524                                               (trampoline)
+ cb_refs                                  # expected error message unexpected error: -524                               (trampoline)

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2022-08-26  1:46 Stephen Rothwell
  0 siblings, 0 replies; 69+ messages in thread
From: Stephen Rothwell @ 2022-08-26  1:46 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Andrii Nakryiko, bpf,
	Networking
  Cc: Daniel Müller, Hao Luo, Linux Kernel Mailing List,
	Linux Next Mailing List, Yosry Ahmed

[-- Attachment #1: Type: text/plain, Size: 1775 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  tools/testing/selftests/bpf/DENYLIST.s390x

between commit:

  27e23836ce22 ("selftests/bpf: Add lru_bug to s390x deny list")

from the bpf tree and commit:

  88886309d2e8 ("selftests/bpf: add a selftest for cgroup hierarchical stats collection")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

-- 
Cheers,
Stephen Rothwell

diff --cc tools/testing/selftests/bpf/DENYLIST.s390x
index 5cadfbdadf36,736b65f61022..000000000000
--- a/tools/testing/selftests/bpf/DENYLIST.s390x
+++ b/tools/testing/selftests/bpf/DENYLIST.s390x
@@@ -65,4 -65,6 +65,7 @@@ send_signa
  select_reuseport                         # intermittently fails on new s390x setup
  xdp_synproxy                             # JIT does not support calling kernel function                                (kfunc)
  unpriv_bpf_disabled                      # fentry
 +lru_bug                                  # prog 'printk': failed to auto-attach: -524
+ setget_sockopt                           # attach unexpected error: -524                                               (trampoline)
+ cb_refs                                  # expected error message unexpected error: -524                               (trampoline)
+ cgroup_hierarchical_stats                # JIT does not support calling kernel function                                (kfunc)

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2022-11-21  1:27 Stephen Rothwell
  0 siblings, 0 replies; 69+ messages in thread
From: Stephen Rothwell @ 2022-11-21  1:27 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Andrii Nakryiko
  Cc: bpf, Networking, Hou Tao, Kang Minchul, Linux Kernel Mailing List,
	Linux Next Mailing List

[-- Attachment #1: Type: text/plain, Size: 1688 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  tools/lib/bpf/ringbuf.c

between commit:

  927cbb478adf ("libbpf: Handle size overflow for ringbuf mmap")

from the bpf tree and commit:

  b486d19a0ab0 ("libbpf: checkpatch: Fixed code alignments in ringbuf.c")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

-- 
Cheers,
Stephen Rothwell

diff --cc tools/lib/bpf/ringbuf.c
index 6af142953a94,51808c5f0014..000000000000
--- a/tools/lib/bpf/ringbuf.c
+++ b/tools/lib/bpf/ringbuf.c
@@@ -128,13 -128,9 +128,13 @@@ int ring_buffer__add(struct ring_buffe
  	/* Map read-only producer page and data pages. We map twice as big
  	 * data size to allow simple reading of samples that wrap around the
  	 * end of a ring buffer. See kernel implementation for details.
- 	 * */
+ 	 */
 -	tmp = mmap(NULL, rb->page_size + 2 * info.max_entries, PROT_READ,
 -		   MAP_SHARED, map_fd, rb->page_size);
 +	mmap_sz = rb->page_size + 2 * (__u64)info.max_entries;
 +	if (mmap_sz != (__u64)(size_t)mmap_sz) {
 +		pr_warn("ringbuf: ring buffer size (%u) is too big\n", info.max_entries);
 +		return libbpf_err(-E2BIG);
 +	}
 +	tmp = mmap(NULL, (size_t)mmap_sz, PROT_READ, MAP_SHARED, map_fd, rb->page_size);
  	if (tmp == MAP_FAILED) {
  		err = -errno;
  		ringbuf_unmap_ring(rb, r);

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2023-03-06 22:58 Stephen Rothwell
  2023-03-10  0:38 ` Stephen Rothwell
  2023-03-10  3:18 ` Bagas Sanjaya
  0 siblings, 2 replies; 69+ messages in thread
From: Stephen Rothwell @ 2023-03-06 22:58 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Andrii Nakryiko, bpf,
	Networking
  Cc: Bagas Sanjaya, David Vernet, Linux Kernel Mailing List,
	Linux Next Mailing List

[-- Attachment #1: Type: text/plain, Size: 1542 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  Documentation/bpf/bpf_devel_QA.rst

between commit:

  b7abcd9c656b ("bpf, doc: Link to submitting-patches.rst for general patch submission info")

from the bpf tree and commit:

  d56b0c461d19 ("bpf, docs: Fix link to netdev-FAQ target")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

-- 
Cheers,
Stephen Rothwell

diff --cc Documentation/bpf/bpf_devel_QA.rst
index b421d94dc9f2,5f5f9ccc3862..000000000000
--- a/Documentation/bpf/bpf_devel_QA.rst
+++ b/Documentation/bpf/bpf_devel_QA.rst
@@@ -684,8 -684,12 +684,8 @@@ when
  
  
  .. Links
- .. _netdev-FAQ: Documentation/process/maintainer-netdev.rst
 -.. _Documentation/process/: https://www.kernel.org/doc/html/latest/process/
+ .. _netdev-FAQ: https://www.kernel.org/doc/html/latest/process/maintainer-netdev.html
  .. _selftests:
     https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/
 -.. _Documentation/dev-tools/kselftest.rst:
 -   https://www.kernel.org/doc/html/latest/dev-tools/kselftest.html
 -.. _Documentation/bpf/btf.rst: btf.rst
  
  Happy BPF hacking!

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2023-03-06 22:58 Stephen Rothwell
@ 2023-03-10  0:38 ` Stephen Rothwell
  2023-03-10  3:18 ` Bagas Sanjaya
  1 sibling, 0 replies; 69+ messages in thread
From: Stephen Rothwell @ 2023-03-10  0:38 UTC (permalink / raw)
  To: David Miller
  Cc: Daniel Borkmann, Alexei Starovoitov, Andrii Nakryiko, bpf,
	Networking, Bagas Sanjaya, David Vernet,
	Linux Kernel Mailing List, Linux Next Mailing List

[-- Attachment #1: Type: text/plain, Size: 1817 bytes --]

Hi all,

On Tue, 7 Mar 2023 09:58:12 +1100 Stephen Rothwell <sfr@canb.auug.org.au> wrote:
> 
> Today's linux-next merge of the bpf-next tree got a conflict in:
> 
>   Documentation/bpf/bpf_devel_QA.rst
> 
> between commit:
> 
>   b7abcd9c656b ("bpf, doc: Link to submitting-patches.rst for general patch submission info")
> 
> from the bpf tree and commit:
> 
>   d56b0c461d19 ("bpf, docs: Fix link to netdev-FAQ target")
> 
> from the bpf-next tree.
> 
> I fixed it up (see below) and can carry the fix as necessary. This
> is now fixed as far as linux-next is concerned, but any non trivial
> conflicts should be mentioned to your upstream maintainer when your tree
> is submitted for merging.  You may also want to consider cooperating
> with the maintainer of the conflicting tree to minimise any particularly
> complex conflicts.
> 
> -- 
> Cheers,
> Stephen Rothwell
> 
> diff --cc Documentation/bpf/bpf_devel_QA.rst
> index b421d94dc9f2,5f5f9ccc3862..000000000000
> --- a/Documentation/bpf/bpf_devel_QA.rst
> +++ b/Documentation/bpf/bpf_devel_QA.rst
> @@@ -684,8 -684,12 +684,8 @@@ when
>   
>   
>   .. Links
> - .. _netdev-FAQ: Documentation/process/maintainer-netdev.rst
>  -.. _Documentation/process/: https://www.kernel.org/doc/html/latest/process/
> + .. _netdev-FAQ: https://www.kernel.org/doc/html/latest/process/maintainer-netdev.html
>   .. _selftests:
>      https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/
>  -.. _Documentation/dev-tools/kselftest.rst:
>  -   https://www.kernel.org/doc/html/latest/dev-tools/kselftest.html
>  -.. _Documentation/bpf/btf.rst: btf.rst
>   
>   Happy BPF hacking!

This is now a conflict between the net-next tree and Linus' tree.

-- 
Cheers,
Stephen Rothwell

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2023-03-06 22:58 Stephen Rothwell
  2023-03-10  0:38 ` Stephen Rothwell
@ 2023-03-10  3:18 ` Bagas Sanjaya
  1 sibling, 0 replies; 69+ messages in thread
From: Bagas Sanjaya @ 2023-03-10  3:18 UTC (permalink / raw)
  To: Stephen Rothwell, Daniel Borkmann, Alexei Starovoitov,
	Andrii Nakryiko, bpf, Networking
  Cc: David Vernet, Linux Kernel Mailing List, Linux Next Mailing List

[-- Attachment #1: Type: text/plain, Size: 5502 bytes --]

On Tue, Mar 07, 2023 at 09:58:12AM +1100, Stephen Rothwell wrote:
> Hi all,
> 
> Today's linux-next merge of the bpf-next tree got a conflict in:
> 
>   Documentation/bpf/bpf_devel_QA.rst
> 
> between commit:
> 
>   b7abcd9c656b ("bpf, doc: Link to submitting-patches.rst for general patch submission info")
> 
> from the bpf tree and commit:
> 
>   d56b0c461d19 ("bpf, docs: Fix link to netdev-FAQ target")
> 
> from the bpf-next tree.
> 
> I fixed it up (see below) and can carry the fix as necessary. This
> is now fixed as far as linux-next is concerned, but any non trivial
> conflicts should be mentioned to your upstream maintainer when your tree
> is submitted for merging.  You may also want to consider cooperating
> with the maintainer of the conflicting tree to minimise any particularly
> complex conflicts.
> 
> -- 
> Cheers,
> Stephen Rothwell
> 
> diff --cc Documentation/bpf/bpf_devel_QA.rst
> index b421d94dc9f2,5f5f9ccc3862..000000000000
> --- a/Documentation/bpf/bpf_devel_QA.rst
> +++ b/Documentation/bpf/bpf_devel_QA.rst
> @@@ -684,8 -684,12 +684,8 @@@ when
>   
>   
>   .. Links
> - .. _netdev-FAQ: Documentation/process/maintainer-netdev.rst
>  -.. _Documentation/process/: https://www.kernel.org/doc/html/latest/process/
> + .. _netdev-FAQ: https://www.kernel.org/doc/html/latest/process/maintainer-netdev.html
>   .. _selftests:
>      https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/
>  -.. _Documentation/dev-tools/kselftest.rst:
>  -   https://www.kernel.org/doc/html/latest/dev-tools/kselftest.html
>  -.. _Documentation/bpf/btf.rst: btf.rst
>   
>   Happy BPF hacking!

I think the correct solution is to instead use internal link to netdev FAQ,
to be consistent with my change in bpf tree:

---- >8 ----
diff --git a/Documentation/bpf/bpf_devel_QA.rst b/Documentation/bpf/bpf_devel_QA.rst
index 5f5f9ccc3862b4..e523991da9e0ce 100644
--- a/Documentation/bpf/bpf_devel_QA.rst
+++ b/Documentation/bpf/bpf_devel_QA.rst
@@ -128,7 +128,7 @@ into the bpf-next tree will make their way into net-next tree. net and
 net-next are both run by David S. Miller. From there, they will go
 into the kernel mainline tree run by Linus Torvalds. To read up on the
 process of net and net-next being merged into the mainline tree, see
-the `netdev-FAQ`_.
+the :doc:`netdev-FAQ </process/maintainer-netdev>`.
 
 
 
@@ -147,7 +147,8 @@ request)::
 Q: How do I indicate which tree (bpf vs. bpf-next) my patch should be applied to?
 ---------------------------------------------------------------------------------
 
-A: The process is the very same as described in the `netdev-FAQ`_,
+A: The process is the very same as described in the
+:doc:`netdev-FAQ </process/maintainer-netdev>`,
 so please read up on it. The subject line must indicate whether the
 patch is a fix or rather "next-like" content in order to let the
 maintainers know whether it is targeted at bpf or bpf-next.
@@ -206,8 +207,8 @@ ii) run extensive BPF test suite and
 Once the BPF pull request was accepted by David S. Miller, then
 the patches end up in net or net-next tree, respectively, and
 make their way from there further into mainline. Again, see the
-`netdev-FAQ`_ for additional information e.g. on how often they are
-merged to mainline.
+:doc:`netdev-FAQ </process/maintainer-netdev>` for additional
+information e.g. on how often they are merged to mainline.
 
 Q: How long do I need to wait for feedback on my BPF patches?
 -------------------------------------------------------------
@@ -230,7 +231,8 @@ Q: Are patches applied to bpf-next when the merge window is open?
 -----------------------------------------------------------------
 A: For the time when the merge window is open, bpf-next will not be
 processed. This is roughly analogous to net-next patch processing,
-so feel free to read up on the `netdev-FAQ`_ about further details.
+so feel free to read up on the
+:doc:`netdev-FAQ </process/maintainer-netdev>` about further details.
 
 During those two weeks of merge window, we might ask you to resend
 your patch series once bpf-next is open again. Once Linus released
@@ -394,7 +396,7 @@ netdev kernel mailing list in Cc and ask for the fix to be queued up:
   netdev@vger.kernel.org
 
 The process in general is the same as on netdev itself, see also the
-`netdev-FAQ`_.
+:doc:`netdev-FAQ </process/maintainer-netdev>`.
 
 Q: Do you also backport to kernels not currently maintained as stable?
 ----------------------------------------------------------------------
@@ -410,7 +412,7 @@ Q: The BPF patch I am about to submit needs to go to stable as well
 What should I do?
 
 A: The same rules apply as with netdev patch submissions in general, see
-the `netdev-FAQ`_.
+the :doc:`netdev-FAQ </process/maintainer-netdev>`.
 
 Never add "``Cc: stable@vger.kernel.org``" to the patch description, but
 ask the BPF maintainers to queue the patches instead. This can be done
@@ -685,7 +687,6 @@ when:
 
 .. Links
 .. _Documentation/process/: https://www.kernel.org/doc/html/latest/process/
-.. _netdev-FAQ: https://www.kernel.org/doc/html/latest/process/maintainer-netdev.html
 .. _selftests:
    https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/
 .. _Documentation/dev-tools/kselftest.rst:


Thanks.

-- 
An old man doll... just what I always wanted! - Clara

[-- Attachment #2: signature.asc --]
[-- Type: application/pgp-signature, Size: 228 bytes --]

^ permalink raw reply related	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2024-03-07  1:40 Stephen Rothwell
  0 siblings, 0 replies; 69+ messages in thread
From: Stephen Rothwell @ 2024-03-07  1:40 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Andrii Nakryiko
  Cc: bpf, Networking, Eduard Zingerman, Linux Kernel Mailing List,
	Linux Next Mailing List

[-- Attachment #1: Type: text/plain, Size: 4464 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  tools/testing/selftests/bpf/progs/verifier_iterating_callbacks.c

between commit:

  5c2bc5e2f81d ("selftests/bpf: test case for callback_depth states pruning logic")

from the bpf tree and commit:

  0c8bbf990bdd ("selftests/bpf: Test may_goto")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

-- 
Cheers,
Stephen Rothwell

diff --cc tools/testing/selftests/bpf/progs/verifier_iterating_callbacks.c
index a955a6358206,04cdbce4652f..000000000000
--- a/tools/testing/selftests/bpf/progs/verifier_iterating_callbacks.c
+++ b/tools/testing/selftests/bpf/progs/verifier_iterating_callbacks.c
@@@ -239,74 -237,103 +237,173 @@@ int bpf_loop_iter_limit_nested(void *un
  	return 1000 * a + b + c;
  }
  
 +struct iter_limit_bug_ctx {
 +	__u64 a;
 +	__u64 b;
 +	__u64 c;
 +};
 +
 +static __naked void iter_limit_bug_cb(void)
 +{
 +	/* This is the same as C code below, but written
 +	 * in assembly to control which branches are fall-through.
 +	 *
 +	 *   switch (bpf_get_prandom_u32()) {
 +	 *   case 1:  ctx->a = 42; break;
 +	 *   case 2:  ctx->b = 42; break;
 +	 *   default: ctx->c = 42; break;
 +	 *   }
 +	 */
 +	asm volatile (
 +	"r9 = r2;"
 +	"call %[bpf_get_prandom_u32];"
 +	"r1 = r0;"
 +	"r2 = 42;"
 +	"r0 = 0;"
 +	"if r1 == 0x1 goto 1f;"
 +	"if r1 == 0x2 goto 2f;"
 +	"*(u64 *)(r9 + 16) = r2;"
 +	"exit;"
 +	"1: *(u64 *)(r9 + 0) = r2;"
 +	"exit;"
 +	"2: *(u64 *)(r9 + 8) = r2;"
 +	"exit;"
 +	:
 +	: __imm(bpf_get_prandom_u32)
 +	: __clobber_all
 +	);
 +}
 +
 +SEC("tc")
 +__failure
 +__flag(BPF_F_TEST_STATE_FREQ)
 +int iter_limit_bug(struct __sk_buff *skb)
 +{
 +	struct iter_limit_bug_ctx ctx = { 7, 7, 7 };
 +
 +	bpf_loop(2, iter_limit_bug_cb, &ctx, 0);
 +
 +	/* This is the same as C code below,
 +	 * written in assembly to guarantee checks order.
 +	 *
 +	 *   if (ctx.a == 42 && ctx.b == 42 && ctx.c == 7)
 +	 *     asm volatile("r1 /= 0;":::"r1");
 +	 */
 +	asm volatile (
 +	"r1 = *(u64 *)%[ctx_a];"
 +	"if r1 != 42 goto 1f;"
 +	"r1 = *(u64 *)%[ctx_b];"
 +	"if r1 != 42 goto 1f;"
 +	"r1 = *(u64 *)%[ctx_c];"
 +	"if r1 != 7 goto 1f;"
 +	"r1 /= 0;"
 +	"1:"
 +	:
 +	: [ctx_a]"m"(ctx.a),
 +	  [ctx_b]"m"(ctx.b),
 +	  [ctx_c]"m"(ctx.c)
 +	: "r1"
 +	);
 +	return 0;
 +}
 +
+ #define ARR_SZ 1000000
+ int zero;
+ char arr[ARR_SZ];
+ 
+ SEC("socket")
+ __success __retval(0xd495cdc0)
+ int cond_break1(const void *ctx)
+ {
+ 	unsigned long i;
+ 	unsigned int sum = 0;
+ 
+ 	for (i = zero; i < ARR_SZ; cond_break, i++)
+ 		sum += i;
+ 	for (i = zero; i < ARR_SZ; i++) {
+ 		barrier_var(i);
+ 		sum += i + arr[i];
+ 		cond_break;
+ 	}
+ 
+ 	return sum;
+ }
+ 
+ SEC("socket")
+ __success __retval(999000000)
+ int cond_break2(const void *ctx)
+ {
+ 	int i, j;
+ 	int sum = 0;
+ 
+ 	for (i = zero; i < 1000; cond_break, i++)
+ 		for (j = zero; j < 1000; j++) {
+ 			sum += i + j;
+ 			cond_break;
+ 		}
+ 
+ 	return sum;
+ }
+ 
+ static __noinline int loop(void)
+ {
+ 	int i, sum = 0;
+ 
+ 	for (i = zero; i <= 1000000; i++, cond_break)
+ 		sum += i;
+ 
+ 	return sum;
+ }
+ 
+ SEC("socket")
+ __success __retval(0x6a5a2920)
+ int cond_break3(const void *ctx)
+ {
+ 	return loop();
+ }
+ 
+ SEC("socket")
+ __success __retval(1)
+ int cond_break4(const void *ctx)
+ {
+ 	int cnt = zero;
+ 
+ 	for (;;) {
+ 		/* should eventually break out of the loop */
+ 		cond_break;
+ 		cnt++;
+ 	}
+ 	/* if we looped a bit, it's a success */
+ 	return cnt > 1 ? 1 : 0;
+ }
+ 
+ static __noinline int static_subprog(void)
+ {
+ 	int cnt = zero;
+ 
+ 	for (;;) {
+ 		cond_break;
+ 		cnt++;
+ 	}
+ 
+ 	return cnt;
+ }
+ 
+ SEC("socket")
+ __success __retval(1)
+ int cond_break5(const void *ctx)
+ {
+ 	int cnt1 = zero, cnt2;
+ 
+ 	for (;;) {
+ 		cond_break;
+ 		cnt1++;
+ 	}
+ 
+ 	cnt2 = static_subprog();
+ 
+ 	/* main and subprog have to loop a bit */
+ 	return cnt1 > 1 && cnt2 > 1 ? 1 : 0;
+ }
+ 
  char _license[] SEC("license") = "GPL";

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2025-02-14  5:07 Stephen Rothwell
  2025-02-14  5:33 ` Alexei Starovoitov
  0 siblings, 1 reply; 69+ messages in thread
From: Stephen Rothwell @ 2025-02-14  5:07 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Andrii Nakryiko
  Cc: Jiri Olsa, Kuniyuki Iwashima, bpf, Networking,
	Linux Kernel Mailing List, Linux Next Mailing List

[-- Attachment #1: Type: text/plain, Size: 1203 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  kernel/bpf/btf.c

between commit:

  5da7e15fb5a1 ("net: Add rx_skb of kfree_skb to raw_tp_null_args[].")

from the bpf tree and commit:

  c83e2d970bae ("bpf: Add tracepoints with null-able arguments")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

-- 
Cheers,
Stephen Rothwell

diff --cc kernel/bpf/btf.c
index c3223e0db2f5,f8335bdc8bf8..000000000000
--- a/kernel/bpf/btf.c
+++ b/kernel/bpf/btf.c
@@@ -6507,8 -6505,8 +6505,10 @@@ static const struct bpf_raw_tp_null_arg
  	/* rxrpc */
  	{ "rxrpc_recvdata", 0x1 },
  	{ "rxrpc_resend", 0x10 },
+ 	{ "rxrpc_tq", 0x10 },
+ 	{ "rxrpc_client", 0x1 },
 +	/* skb */
 +	{"kfree_skb", 0x1000},
  	/* sunrpc */
  	{ "xs_stream_read_data", 0x1 },
  	/* ... from xprt_cong_event event class */

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2025-02-14  5:07 linux-next: manual merge of the bpf-next tree with the bpf tree Stephen Rothwell
@ 2025-02-14  5:33 ` Alexei Starovoitov
  2025-02-14  5:40   ` Stephen Rothwell
  2025-02-14  9:12   ` Jiri Olsa
  0 siblings, 2 replies; 69+ messages in thread
From: Alexei Starovoitov @ 2025-02-14  5:33 UTC (permalink / raw)
  To: Stephen Rothwell
  Cc: Daniel Borkmann, Alexei Starovoitov, Andrii Nakryiko, Jiri Olsa,
	Kuniyuki Iwashima, bpf, Networking, Linux Kernel Mailing List,
	Linux Next Mailing List

On Thu, Feb 13, 2025 at 9:07 PM Stephen Rothwell <sfr@canb.auug.org.au> wrote:
>
> Hi all,
>
> Today's linux-next merge of the bpf-next tree got a conflict in:
>
>   kernel/bpf/btf.c
>
> between commit:
>
>   5da7e15fb5a1 ("net: Add rx_skb of kfree_skb to raw_tp_null_args[].")
>
> from the bpf tree and commit:
>
>   c83e2d970bae ("bpf: Add tracepoints with null-able arguments")
>
> from the bpf-next tree.
>
> I fixed it up (see below) and can carry the fix as necessary. This
> is now fixed as far as linux-next is concerned, but any non trivial
> conflicts should be mentioned to your upstream maintainer when your tree
> is submitted for merging.  You may also want to consider cooperating
> with the maintainer of the conflicting tree to minimise any particularly
> complex conflicts.

Thanks for headsup.

Jiri,
what should we do ?
I feel that moving c83e2d970bae into bpf tree would be the best ?

Pls warn me next time of conflicts.

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2025-02-14  5:33 ` Alexei Starovoitov
@ 2025-02-14  5:40   ` Stephen Rothwell
  2025-02-14  9:12   ` Jiri Olsa
  1 sibling, 0 replies; 69+ messages in thread
From: Stephen Rothwell @ 2025-02-14  5:40 UTC (permalink / raw)
  To: Alexei Starovoitov
  Cc: Daniel Borkmann, Alexei Starovoitov, Andrii Nakryiko, Jiri Olsa,
	Kuniyuki Iwashima, bpf, Networking, Linux Kernel Mailing List,
	Linux Next Mailing List

[-- Attachment #1: Type: text/plain, Size: 479 bytes --]

Hi Alexei,

On Thu, 13 Feb 2025 21:33:11 -0800 Alexei Starovoitov <alexei.starovoitov@gmail.com> wrote:
>
> what should we do ?
> I feel that moving c83e2d970bae into bpf tree would be the best ?

Just remember to mention the conflict to whomever merges the bpf-next
tree towards Linus' tree.  Its a trivial conflict.  Or merge the bpf
tree into the bpf-next tree if you feel that you need the bug fixes in
the bpf-next tree as well.

-- 
Cheers,
Stephen Rothwell

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2025-02-14  5:33 ` Alexei Starovoitov
  2025-02-14  5:40   ` Stephen Rothwell
@ 2025-02-14  9:12   ` Jiri Olsa
  2025-02-14 18:50     ` Alexei Starovoitov
  1 sibling, 1 reply; 69+ messages in thread
From: Jiri Olsa @ 2025-02-14  9:12 UTC (permalink / raw)
  To: Alexei Starovoitov
  Cc: Stephen Rothwell, Daniel Borkmann, Alexei Starovoitov,
	Andrii Nakryiko, Kuniyuki Iwashima, bpf, Networking,
	Linux Kernel Mailing List, Linux Next Mailing List

On Thu, Feb 13, 2025 at 09:33:11PM -0800, Alexei Starovoitov wrote:
> On Thu, Feb 13, 2025 at 9:07 PM Stephen Rothwell <sfr@canb.auug.org.au> wrote:
> >
> > Hi all,
> >
> > Today's linux-next merge of the bpf-next tree got a conflict in:
> >
> >   kernel/bpf/btf.c
> >
> > between commit:
> >
> >   5da7e15fb5a1 ("net: Add rx_skb of kfree_skb to raw_tp_null_args[].")
> >
> > from the bpf tree and commit:
> >
> >   c83e2d970bae ("bpf: Add tracepoints with null-able arguments")
> >
> > from the bpf-next tree.
> >
> > I fixed it up (see below) and can carry the fix as necessary. This
> > is now fixed as far as linux-next is concerned, but any non trivial
> > conflicts should be mentioned to your upstream maintainer when your tree
> > is submitted for merging.  You may also want to consider cooperating
> > with the maintainer of the conflicting tree to minimise any particularly
> > complex conflicts.
> 
> Thanks for headsup.
> 
> Jiri,
> what should we do ?
> I feel that moving c83e2d970bae into bpf tree would be the best ?

right, bpf tree would have been better fit for that.. should I resend that for bpf tree?

> 
> Pls warn me next time of conflicts.

will do

jirka

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2025-02-14  9:12   ` Jiri Olsa
@ 2025-02-14 18:50     ` Alexei Starovoitov
  0 siblings, 0 replies; 69+ messages in thread
From: Alexei Starovoitov @ 2025-02-14 18:50 UTC (permalink / raw)
  To: Jiri Olsa
  Cc: Stephen Rothwell, Daniel Borkmann, Alexei Starovoitov,
	Andrii Nakryiko, Kuniyuki Iwashima, bpf, Networking,
	Linux Kernel Mailing List, Linux Next Mailing List

On Fri, Feb 14, 2025 at 1:12 AM Jiri Olsa <olsajiri@gmail.com> wrote:
>
> On Thu, Feb 13, 2025 at 09:33:11PM -0800, Alexei Starovoitov wrote:
> > On Thu, Feb 13, 2025 at 9:07 PM Stephen Rothwell <sfr@canb.auug.org.au> wrote:
> > >
> > > Hi all,
> > >
> > > Today's linux-next merge of the bpf-next tree got a conflict in:
> > >
> > >   kernel/bpf/btf.c
> > >
> > > between commit:
> > >
> > >   5da7e15fb5a1 ("net: Add rx_skb of kfree_skb to raw_tp_null_args[].")
> > >
> > > from the bpf tree and commit:
> > >
> > >   c83e2d970bae ("bpf: Add tracepoints with null-able arguments")
> > >
> > > from the bpf-next tree.
> > >
> > > I fixed it up (see below) and can carry the fix as necessary. This
> > > is now fixed as far as linux-next is concerned, but any non trivial
> > > conflicts should be mentioned to your upstream maintainer when your tree
> > > is submitted for merging.  You may also want to consider cooperating
> > > with the maintainer of the conflicting tree to minimise any particularly
> > > complex conflicts.
> >
> > Thanks for headsup.
> >
> > Jiri,
> > what should we do ?
> > I feel that moving c83e2d970bae into bpf tree would be the best ?
>
> right, bpf tree would have been better fit for that.. should I resend that for bpf tree?

After sleeping on it I guess it's fine as-is.
When bpf tree gets pulled we will merge Linus's tree and resolve that
conflict way before the merge window.

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2025-11-06  0:35 Stephen Rothwell
  2025-11-06 17:57 ` Andrii Nakryiko
  0 siblings, 1 reply; 69+ messages in thread
From: Stephen Rothwell @ 2025-11-06  0:35 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Andrii Nakryiko
  Cc: Mykyta Yatsenko, bpf, Networking, Linux Kernel Mailing List,
	Linux Next Mailing List

[-- Attachment #1: Type: text/plain, Size: 1757 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  kernel/bpf/helpers.c

between commits:

  ea0714d61dea ("bpf:add _impl suffix for bpf_task_work_schedule* kfuncs")
  137cc92ffe2e ("bpf: add _impl suffix for bpf_stream_vprintk() kfunc")

from the bpf tree and commit:

  8d8771dc03e4 ("bpf: add plumbing for file-backed dynptr")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

-- 
Cheers,
Stephen Rothwell

diff --cc kernel/bpf/helpers.c
index e4007fea4909,865b0dae38d1..000000000000
--- a/kernel/bpf/helpers.c
+++ b/kernel/bpf/helpers.c
@@@ -4380,9 -4531,11 +4535,11 @@@ BTF_ID_FLAGS(func, bpf_strncasestr)
  #if defined(CONFIG_BPF_LSM) && defined(CONFIG_CGROUPS)
  BTF_ID_FLAGS(func, bpf_cgroup_read_xattr, KF_RCU)
  #endif
 -BTF_ID_FLAGS(func, bpf_stream_vprintk, KF_TRUSTED_ARGS)
 -BTF_ID_FLAGS(func, bpf_task_work_schedule_signal, KF_TRUSTED_ARGS)
 -BTF_ID_FLAGS(func, bpf_task_work_schedule_resume, KF_TRUSTED_ARGS)
 +BTF_ID_FLAGS(func, bpf_stream_vprintk_impl, KF_TRUSTED_ARGS)
 +BTF_ID_FLAGS(func, bpf_task_work_schedule_signal_impl, KF_TRUSTED_ARGS)
 +BTF_ID_FLAGS(func, bpf_task_work_schedule_resume_impl, KF_TRUSTED_ARGS)
+ BTF_ID_FLAGS(func, bpf_dynptr_from_file, KF_TRUSTED_ARGS)
+ BTF_ID_FLAGS(func, bpf_dynptr_file_discard)
  BTF_KFUNCS_END(common_btf_ids)
  
  static const struct btf_kfunc_id_set common_kfunc_set = {

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2025-11-06  0:35 Stephen Rothwell
@ 2025-11-06 17:57 ` Andrii Nakryiko
  0 siblings, 0 replies; 69+ messages in thread
From: Andrii Nakryiko @ 2025-11-06 17:57 UTC (permalink / raw)
  To: Stephen Rothwell
  Cc: Daniel Borkmann, Alexei Starovoitov, Andrii Nakryiko,
	Mykyta Yatsenko, bpf, Networking, Linux Kernel Mailing List,
	Linux Next Mailing List

On Wed, Nov 5, 2025 at 4:35 PM Stephen Rothwell <sfr@canb.auug.org.au> wrote:
>
> Hi all,
>
> Today's linux-next merge of the bpf-next tree got a conflict in:
>
>   kernel/bpf/helpers.c
>
> between commits:
>
>   ea0714d61dea ("bpf:add _impl suffix for bpf_task_work_schedule* kfuncs")
>   137cc92ffe2e ("bpf: add _impl suffix for bpf_stream_vprintk() kfunc")
>
> from the bpf tree and commit:
>
>   8d8771dc03e4 ("bpf: add plumbing for file-backed dynptr")
>
> from the bpf-next tree.
>
> I fixed it up (see below) and can carry the fix as necessary. This
> is now fixed as far as linux-next is concerned, but any non trivial
> conflicts should be mentioned to your upstream maintainer when your tree
> is submitted for merging.  You may also want to consider cooperating
> with the maintainer of the conflicting tree to minimise any particularly
> complex conflicts.
>
> --
> Cheers,
> Stephen Rothwell
>
> diff --cc kernel/bpf/helpers.c
> index e4007fea4909,865b0dae38d1..000000000000
> --- a/kernel/bpf/helpers.c
> +++ b/kernel/bpf/helpers.c
> @@@ -4380,9 -4531,11 +4535,11 @@@ BTF_ID_FLAGS(func, bpf_strncasestr)
>   #if defined(CONFIG_BPF_LSM) && defined(CONFIG_CGROUPS)
>   BTF_ID_FLAGS(func, bpf_cgroup_read_xattr, KF_RCU)
>   #endif
>  -BTF_ID_FLAGS(func, bpf_stream_vprintk, KF_TRUSTED_ARGS)
>  -BTF_ID_FLAGS(func, bpf_task_work_schedule_signal, KF_TRUSTED_ARGS)
>  -BTF_ID_FLAGS(func, bpf_task_work_schedule_resume, KF_TRUSTED_ARGS)
>  +BTF_ID_FLAGS(func, bpf_stream_vprintk_impl, KF_TRUSTED_ARGS)
>  +BTF_ID_FLAGS(func, bpf_task_work_schedule_signal_impl, KF_TRUSTED_ARGS)
>  +BTF_ID_FLAGS(func, bpf_task_work_schedule_resume_impl, KF_TRUSTED_ARGS)
> + BTF_ID_FLAGS(func, bpf_dynptr_from_file, KF_TRUSTED_ARGS)
> + BTF_ID_FLAGS(func, bpf_dynptr_file_discard)
>   BTF_KFUNCS_END(common_btf_ids)

LGTM, thanks

>
>   static const struct btf_kfunc_id_set common_kfunc_set = {

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2026-02-24 12:39 Mark Brown
  2026-02-24 16:22 ` Alexei Starovoitov
  0 siblings, 1 reply; 69+ messages in thread
From: Mark Brown @ 2026-02-24 12:39 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Andrii Nakryiko, bpf,
	Networking
  Cc: Eduard Zingerman, Ihor Solodrai, Linux Kernel Mailing List,
	Linux Next Mailing List

[-- Attachment #1: Type: text/plain, Size: 763 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  tools/testing/selftests/bpf/prog_tests/align.c

between commit:

  05849ec34f3d7 ("selftests/bpf: Replace strncpy() with strscpy()")

from the bpf tree and commit:

  f632de6e19553 ("selftests/bpf: Migrate align.c tests to test_loader framework")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

(deleted the file)

[-- Attachment #2: signature.asc --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2026-02-24 12:39 Mark Brown
@ 2026-02-24 16:22 ` Alexei Starovoitov
  0 siblings, 0 replies; 69+ messages in thread
From: Alexei Starovoitov @ 2026-02-24 16:22 UTC (permalink / raw)
  To: Mark Brown
  Cc: Daniel Borkmann, Alexei Starovoitov, Andrii Nakryiko, bpf,
	Networking, Eduard Zingerman, Ihor Solodrai,
	Linux Kernel Mailing List, Linux Next Mailing List

On Tue, Feb 24, 2026 at 4:39 AM Mark Brown <broonie@kernel.org> wrote:
>
> Hi all,
>
> Today's linux-next merge of the bpf-next tree got a conflict in:
>
>   tools/testing/selftests/bpf/prog_tests/align.c
>
> between commit:
>
>   05849ec34f3d7 ("selftests/bpf: Replace strncpy() with strscpy()")
>
> from the bpf tree and commit:
>
>   f632de6e19553 ("selftests/bpf: Migrate align.c tests to test_loader framework")
>
> from the bpf-next tree.
>
> I fixed it up (see below) and can carry the fix as necessary. This
> is now fixed as far as linux-next is concerned, but any non trivial
> conflicts should be mentioned to your upstream maintainer when your tree
> is submitted for merging.  You may also want to consider cooperating
> with the maintainer of the conflicting tree to minimise any particularly
> complex conflicts.
>
> (deleted the file)

Thanks for heads up.
Since the file is deleted in bpf-next anyway I dropped this hunk
of patch 05849ec34f3d7 and force pushed bpf tree.
There should be no conflict anymore. Saves the headache for us
to resolve it when bpf goes to Linus and then back to bpf-next.

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2026-04-01 12:29 Mark Brown
  2026-04-01 15:27 ` Alexei Starovoitov
  0 siblings, 1 reply; 69+ messages in thread
From: Mark Brown @ 2026-04-01 12:29 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Andrii Nakryiko, bpf,
	Networking
  Cc: Eduard Zingerman, Linux Kernel Mailing List,
	Linux Next Mailing List

[-- Attachment #1: Type: text/plain, Size: 1622 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  kernel/bpf/verifier.c

between commit:

  a8502a79e832b ("bpf: Fix regsafe() for pointers to packet")

from the bpf tree and commit:

  022ac07508836 ("bpf: use reg->var_off instead of reg->off for pointers")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

diff --cc kernel/bpf/verifier.c
index a3388cb8fcbdf,8c1cf2eb6cbbd..0000000000000
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@@ -19915,18 -20075,8 +20075,13 @@@ static bool regsafe(struct bpf_verifier
  		 * since someone could have accessed through (ptr - k), or
  		 * even done ptr -= k in a register, to get a safe access.
  		 */
 -		if (rold->range > rcur->range)
 +		if (rold->range < 0 || rcur->range < 0) {
 +			/* special case for [BEYOND|AT]_PKT_END */
 +			if (rold->range != rcur->range)
 +				return false;
 +		} else if (rold->range > rcur->range) {
  			return false;
 +		}
- 		/* If the offsets don't match, we can't trust our alignment;
- 		 * nor can we be sure that we won't fall out of range.
- 		 */
- 		if (rold->off != rcur->off)
- 			return false;
  		/* id relations must be preserved */
  		if (!check_ids(rold->id, rcur->id, idmap))
  			return false;

[-- Attachment #2: signature.asc --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2026-04-01 12:29 Mark Brown
@ 2026-04-01 15:27 ` Alexei Starovoitov
  0 siblings, 0 replies; 69+ messages in thread
From: Alexei Starovoitov @ 2026-04-01 15:27 UTC (permalink / raw)
  To: Mark Brown
  Cc: Daniel Borkmann, Alexei Starovoitov, Andrii Nakryiko, bpf,
	Networking, Eduard Zingerman, Linux Kernel Mailing List,
	Linux Next Mailing List

On Wed, Apr 1, 2026 at 5:29 AM Mark Brown <broonie@kernel.org> wrote:
>
> Hi all,
>
> Today's linux-next merge of the bpf-next tree got a conflict in:
>
>   kernel/bpf/verifier.c
>
> between commit:
>
>   a8502a79e832b ("bpf: Fix regsafe() for pointers to packet")
>
> from the bpf tree and commit:
>
>   022ac07508836 ("bpf: use reg->var_off instead of reg->off for pointers")
>
> from the bpf-next tree.
>
> I fixed it up (see below) and can carry the fix as necessary. This
> is now fixed as far as linux-next is concerned, but any non trivial
> conflicts should be mentioned to your upstream maintainer when your tree
> is submitted for merging.  You may also want to consider cooperating
> with the maintainer of the conflicting tree to minimise any particularly
> complex conflicts.

thanks for headsup.
lgtm
we will get it resolved once bpf tree gets pulled.

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2026-09-03 14:10 Mark Brown
  2026-09-06 23:18 ` Alexei Starovoitov
  0 siblings, 1 reply; 69+ messages in thread
From: Mark Brown @ 2026-09-03 14:10 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Andrii Nakryiko, bpf,
	Networking
  Cc: Eduard Zingerman, Linux Kernel Mailing List,
	Linux Next Mailing List, Yonghong Song

[-- Attachment #1: Type: text/plain, Size: 1663 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  kernel/bpf/backtrack.c

between commit:

  e3e4f66cc4b72 ("bpf: backtracking shouldn't clear outer frame R1-R5 for callbacks")

from the bpf tree and commit:

  5bbb242c08590 ("bpf: Handle R2 as a return register in precision backtracking")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

I'm not entirely happy with this resolution but I think it's OK?

diff --cc kernel/bpf/backtrack.c
index 47282ffeeaf94,653db80bcc47b..0000000000000
--- a/kernel/bpf/backtrack.c
+++ b/kernel/bpf/backtrack.c
@@@ -533,8 -538,12 +537,12 @@@ static int backtrack_insn(struct bpf_ve
  			from_subprog_call = subseq_idx - 1 >= 0 &&
  					    bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]);
  
 -			/* Sample the return registers before the callback
 -			 * handling below clears R1-R5.
 -			 */
  			r0_precise = from_subprog_call && bt_is_reg_set(bt, BPF_REG_0);
+ 			r2_precise = from_subprog_call && bt_is_reg_set(bt, BPF_REG_2);
+ 
++			bt_clear_reg(bt, BPF_REG_0);
++			bt_clear_reg(bt, BPF_REG_2);
 +
  			/* Backtracking to a nested function call, 'idx' is a part of
  			 * the inner frame 'subseq_idx' is a part of the outer frame.
  			 * In case of a regular function call, instructions giving

[-- Attachment #2: signature.asc --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2026-09-03 14:10 Mark Brown
@ 2026-09-06 23:18 ` Alexei Starovoitov
  0 siblings, 0 replies; 69+ messages in thread
From: Alexei Starovoitov @ 2026-09-06 23:18 UTC (permalink / raw)
  To: Mark Brown
  Cc: Daniel Borkmann, Alexei Starovoitov, Andrii Nakryiko, bpf,
	Networking, Eduard Zingerman, Linux Kernel Mailing List,
	Linux Next Mailing List, Yonghong Song

On Thu, Sep 3, 2026 at 7:10 AM Mark Brown <broonie@kernel.org> wrote:
>
> Hi all,
>
> Today's linux-next merge of the bpf-next tree got a conflict in:
>
>   kernel/bpf/backtrack.c
>
> between commit:
>
>   e3e4f66cc4b72 ("bpf: backtracking shouldn't clear outer frame R1-R5 for callbacks")
>
> from the bpf tree and commit:
>
>   5bbb242c08590 ("bpf: Handle R2 as a return register in precision backtracking")
>
> from the bpf-next tree.
>
> I fixed it up (see below) and can carry the fix as necessary. This
> is now fixed as far as linux-next is concerned, but any non trivial
> conflicts should be mentioned to your upstream maintainer when your tree
> is submitted for merging.  You may also want to consider cooperating
> with the maintainer of the conflicting tree to minimise any particularly
> complex conflicts.
>
> I'm not entirely happy with this resolution but I think it's OK?
>
> diff --cc kernel/bpf/backtrack.c
> index 47282ffeeaf94,653db80bcc47b..0000000000000
> --- a/kernel/bpf/backtrack.c
> +++ b/kernel/bpf/backtrack.c
> @@@ -533,8 -538,12 +537,12 @@@ static int backtrack_insn(struct bpf_ve
>                         from_subprog_call = subseq_idx - 1 >= 0 &&
>                                             bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]);
>
>  -                      /* Sample the return registers before the callback
>  -                       * handling below clears R1-R5.
>  -                       */
>                         r0_precise = from_subprog_call && bt_is_reg_set(bt, BPF_REG_0);
> +                       r2_precise = from_subprog_call && bt_is_reg_set(bt, BPF_REG_2);
> +
> ++                      bt_clear_reg(bt, BPF_REG_0);
> ++                      bt_clear_reg(bt, BPF_REG_2);
>  +

It was more involved than that,
but now the conflict is resolved.

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2026-09-14 11:31 Mark Brown
  2026-09-14 11:34 ` Daniel Borkmann
  0 siblings, 1 reply; 69+ messages in thread
From: Mark Brown @ 2026-09-14 11:31 UTC (permalink / raw)
  To: Daniel Borkmann, Alexei Starovoitov, Andrii Nakryiko, bpf,
	Networking
  Cc: Amery Hung, Linux Kernel Mailing List, Linux Next Mailing List

[-- Attachment #1: Type: text/plain, Size: 2069 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  tools/testing/selftests/bpf/prog_tests/verifier.c

between commit:

  a903f145a8914 ("selftests/bpf: Add tests for the KF_PERFMON gates")

from the bpf tree and commit:

  5647b77587ce1 ("selftests/bpf: Test kfunc packet memory direct writes")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

diff --cc tools/testing/selftests/bpf/prog_tests/verifier.c
index 8b439e194bcc5,7732df9bc8701..0000000000000
--- a/tools/testing/selftests/bpf/prog_tests/verifier.c
+++ b/tools/testing/selftests/bpf/prog_tests/verifier.c
@@@ -54,7 -55,7 +56,8 @@@
  #include "verifier_iterating_callbacks.skel.h"
  #include "verifier_jeq_infer_not_null.skel.h"
  #include "verifier_jit_convergence.skel.h"
+ #include "verifier_kfunc_packet_access.skel.h"
 +#include "verifier_kfunc_perfmon.skel.h"
  #include "verifier_ld_ind.skel.h"
  #include "verifier_ldsx.skel.h"
  #include "verifier_leak_ptr.skel.h"
@@@ -219,7 -221,7 +224,8 @@@ void test_verifier_int_ptr(void
  void test_verifier_iterating_callbacks(void)  { RUN(verifier_iterating_callbacks); }
  void test_verifier_jeq_infer_not_null(void)   { RUN(verifier_jeq_infer_not_null); }
  void test_verifier_jit_convergence(void)      { RUN(verifier_jit_convergence); }
+ void test_verifier_kfunc_packet_access(void)  { RUN_TESTS(verifier_kfunc_packet_access); }
 +void test_verifier_kfunc_perfmon(void)        { RUN(verifier_kfunc_perfmon); }
  void test_verifier_load_acquire(void)         { RUN(verifier_load_acquire); }
  void test_verifier_ld_ind(void)               { RUN(verifier_ld_ind); }
  void test_verifier_ldsx(void)                  { RUN(verifier_ldsx); }

[-- Attachment #2: signature.asc --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2026-09-14 11:31 Mark Brown
@ 2026-09-14 11:34 ` Daniel Borkmann
  0 siblings, 0 replies; 69+ messages in thread
From: Daniel Borkmann @ 2026-09-14 11:34 UTC (permalink / raw)
  To: Mark Brown, Alexei Starovoitov, Andrii Nakryiko, bpf, Networking
  Cc: Amery Hung, Linux Kernel Mailing List, Linux Next Mailing List

On 9/14/26 1:31 PM, Mark Brown wrote:
> Hi all,
> 
> Today's linux-next merge of the bpf-next tree got a conflict in:
> 
>    tools/testing/selftests/bpf/prog_tests/verifier.c
> 
> between commit:
> 
>    a903f145a8914 ("selftests/bpf: Add tests for the KF_PERFMON gates")
> 
> from the bpf tree and commit:
> 
>    5647b77587ce1 ("selftests/bpf: Test kfunc packet memory direct writes")
> 
> from the bpf-next tree.
> 
> I fixed it up (see below) and can carry the fix as necessary. This
> is now fixed as far as linux-next is concerned, but any non trivial
> conflicts should be mentioned to your upstream maintainer when your tree
> is submitted for merging.  You may also want to consider cooperating
> with the maintainer of the conflicting tree to minimise any particularly
> complex conflicts.
lgtm

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2026-09-18 11:05 Mark Brown
  0 siblings, 0 replies; 69+ messages in thread
From: Mark Brown @ 2026-09-18 11:05 UTC (permalink / raw)
  To: Kumar Kartikeya Dwivedi, Eduard Zingerman, Daniel Borkmann,
	Alexei Starovoitov, Andrii Nakryiko, bpf, Networking
  Cc: Amery Hung, Linux Kernel Mailing List, Linux Next Mailing List

[-- Attachment #1: Type: text/plain, Size: 1840 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  tools/testing/selftests/bpf/prog_tests/cb_refs.c

between commit:

  04ae4ffc57a6b ("selftests/bpf: Check callback map value lock identity")

from the bpf tree and commits:

  ab7fff217fd14 ("bpf: Check helper and kfunc arguments in one path")
  5dc1549afac9c ("bpf: Consolidate release argument validation")
  750f3770809ac ("bpf: Consolidate nullable argument validation")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

diff --cc tools/testing/selftests/bpf/prog_tests/cb_refs.c
index 490e15e7126d9,c32c6dab49bce..0000000000000
--- a/tools/testing/selftests/bpf/prog_tests/cb_refs.c
+++ b/tools/testing/selftests/bpf/prog_tests/cb_refs.c
@@@ -11,9 -11,9 +11,9 @@@ struct 
  	const char *prog_name;
  	const char *err_msg;
  } cb_refs_tests[] = {
- 	{ "underflow_prog", "release kfunc bpf_kfunc_call_test_release expects referenced PTR_TO_BTF_ID passed to R1" },
- 	{ "leak_prog", "Possibly NULL pointer passed to helper R2" },
+ 	{ "underflow_prog", "R1 type=scalar expected=ptr_, trusted_ptr_, rcu_ptr_" },
+ 	{ "leak_prog", "Unreleased reference id=4 alloc_insn=3" }, /* alloc_insn=3{2,3} */
 -	{ "nested_cb", "Unreleased reference id=4 alloc_insn=2" }, /* alloc_insn=2{4,5} */
 +	{ "nested_cb", "Unreleased reference id=5 alloc_insn=2" }, /* alloc_insn=2{4,5} */
  	{ "non_cb_transfer_ref", "Unreleased reference id=4 alloc_insn=1" }, /* alloc_insn=1{1,2} */
  };
  

[-- Attachment #2: signature.asc --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2026-09-21  9:49 Mark Brown
  2026-09-21 12:12 ` Daniel Borkmann
  0 siblings, 1 reply; 69+ messages in thread
From: Mark Brown @ 2026-09-21  9:49 UTC (permalink / raw)
  To: Kumar Kartikeya Dwivedi, Eduard Zingerman, Daniel Borkmann,
	Alexei Starovoitov, Andrii Nakryiko, bpf, Networking
  Cc: Anastasios Papagiannis, Linux Kernel Mailing List,
	Linux Next Mailing List

[-- Attachment #1: Type: text/plain, Size: 2185 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  kernel/bpf/helpers.c

between commit:

  81c975aae375d ("bpf: Require CAP_PERFMON for kfuncs reading memory")

from the bpf tree and commit:

  3f9d98dfed79f ("bpf: Add user memory access kfuncs for mm_struct")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

diff --cc kernel/bpf/helpers.c
index 712dca5a2c5bd,82402d97ce67c..0000000000000
--- a/kernel/bpf/helpers.c
+++ b/kernel/bpf/helpers.c
@@@ -4920,12 -5049,14 +5049,14 @@@ BTF_ID_FLAGS(func, bpf_wq_set_callback
  BTF_ID_FLAGS(func, bpf_wq_start)
  BTF_ID_FLAGS(func, bpf_preempt_disable)
  BTF_ID_FLAGS(func, bpf_preempt_enable)
 -BTF_ID_FLAGS(func, bpf_iter_bits_new, KF_ITER_NEW)
 +BTF_ID_FLAGS(func, bpf_iter_bits_new, KF_ITER_NEW | KF_PERFMON)
  BTF_ID_FLAGS(func, bpf_iter_bits_next, KF_ITER_NEXT | KF_RET_NULL)
  BTF_ID_FLAGS(func, bpf_iter_bits_destroy, KF_ITER_DESTROY)
 -BTF_ID_FLAGS(func, bpf_copy_from_user_str, KF_SLEEPABLE)
 -BTF_ID_FLAGS(func, bpf_copy_from_user_mm, KF_SLEEPABLE)
 -BTF_ID_FLAGS(func, bpf_copy_from_user_mm_str, KF_SLEEPABLE)
 -BTF_ID_FLAGS(func, bpf_copy_from_user_task_str, KF_SLEEPABLE)
 -BTF_ID_FLAGS(func, bpf_get_kmem_cache)
 +BTF_ID_FLAGS(func, bpf_copy_from_user_str, KF_SLEEPABLE | KF_PERFMON)
++BTF_ID_FLAGS(func, bpf_copy_from_user_mm, KF_SLEEPABLE | KF_PERFMON)
++BTF_ID_FLAGS(func, bpf_copy_from_user_mm_str, KF_SLEEPABLE | KF_PERFMON)
 +BTF_ID_FLAGS(func, bpf_copy_from_user_task_str, KF_SLEEPABLE | KF_PERFMON)
 +BTF_ID_FLAGS(func, bpf_get_kmem_cache, KF_PERFMON)
  BTF_ID_FLAGS(func, bpf_iter_kmem_cache_new, KF_ITER_NEW | KF_SLEEPABLE)
  BTF_ID_FLAGS(func, bpf_iter_kmem_cache_next, KF_ITER_NEXT | KF_RET_NULL | KF_SLEEPABLE)
  BTF_ID_FLAGS(func, bpf_iter_kmem_cache_destroy, KF_ITER_DESTROY | KF_SLEEPABLE)

[-- Attachment #2: signature.asc --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2026-09-21  9:49 Mark Brown
@ 2026-09-21 12:12 ` Daniel Borkmann
  0 siblings, 0 replies; 69+ messages in thread
From: Daniel Borkmann @ 2026-09-21 12:12 UTC (permalink / raw)
  To: Mark Brown, Kumar Kartikeya Dwivedi, Eduard Zingerman,
	Alexei Starovoitov, Andrii Nakryiko, bpf, Networking
  Cc: Anastasios Papagiannis, Linux Kernel Mailing List,
	Linux Next Mailing List

On 9/21/26 11:49 AM, Mark Brown wrote:
> Hi all,
> 
> Today's linux-next merge of the bpf-next tree got a conflict in:
> 
>    kernel/bpf/helpers.c
> 
> between commit:
> 
>    81c975aae375d ("bpf: Require CAP_PERFMON for kfuncs reading memory")
> 
> from the bpf tree and commit:
> 
>    3f9d98dfed79f ("bpf: Add user memory access kfuncs for mm_struct")
> 
> from the bpf-next tree.
> 
> I fixed it up (see below) and can carry the fix as necessary. This
> is now fixed as far as linux-next is concerned, but any non trivial
> conflicts should be mentioned to your upstream maintainer when your tree
> is submitted for merging.  You may also want to consider cooperating
> with the maintainer of the conflicting tree to minimise any particularly
> complex conflicts.
> 
> diff --cc kernel/bpf/helpers.c
> index 712dca5a2c5bd,82402d97ce67c..0000000000000
> --- a/kernel/bpf/helpers.c
> +++ b/kernel/bpf/helpers.c
> @@@ -4920,12 -5049,14 +5049,14 @@@ BTF_ID_FLAGS(func, bpf_wq_set_callback
>    BTF_ID_FLAGS(func, bpf_wq_start)
>    BTF_ID_FLAGS(func, bpf_preempt_disable)
>    BTF_ID_FLAGS(func, bpf_preempt_enable)
>   -BTF_ID_FLAGS(func, bpf_iter_bits_new, KF_ITER_NEW)
>   +BTF_ID_FLAGS(func, bpf_iter_bits_new, KF_ITER_NEW | KF_PERFMON)
>    BTF_ID_FLAGS(func, bpf_iter_bits_next, KF_ITER_NEXT | KF_RET_NULL)
>    BTF_ID_FLAGS(func, bpf_iter_bits_destroy, KF_ITER_DESTROY)
>   -BTF_ID_FLAGS(func, bpf_copy_from_user_str, KF_SLEEPABLE)
>   -BTF_ID_FLAGS(func, bpf_copy_from_user_mm, KF_SLEEPABLE)
>   -BTF_ID_FLAGS(func, bpf_copy_from_user_mm_str, KF_SLEEPABLE)
>   -BTF_ID_FLAGS(func, bpf_copy_from_user_task_str, KF_SLEEPABLE)
>   -BTF_ID_FLAGS(func, bpf_get_kmem_cache)
>   +BTF_ID_FLAGS(func, bpf_copy_from_user_str, KF_SLEEPABLE | KF_PERFMON)
> ++BTF_ID_FLAGS(func, bpf_copy_from_user_mm, KF_SLEEPABLE | KF_PERFMON)
> ++BTF_ID_FLAGS(func, bpf_copy_from_user_mm_str, KF_SLEEPABLE | KF_PERFMON)

LGTM, yes, we need to mark the added kfuncs from Anastasios with KF_PERFMON.

>   +BTF_ID_FLAGS(func, bpf_copy_from_user_task_str, KF_SLEEPABLE | KF_PERFMON)
>   +BTF_ID_FLAGS(func, bpf_get_kmem_cache, KF_PERFMON)
>    BTF_ID_FLAGS(func, bpf_iter_kmem_cache_new, KF_ITER_NEW | KF_SLEEPABLE)
>    BTF_ID_FLAGS(func, bpf_iter_kmem_cache_next, KF_ITER_NEXT | KF_RET_NULL | KF_SLEEPABLE)
>    BTF_ID_FLAGS(func, bpf_iter_kmem_cache_destroy, KF_ITER_DESTROY | KF_SLEEPABLE)


^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2026-09-22 10:05 Mark Brown
  0 siblings, 0 replies; 69+ messages in thread
From: Mark Brown @ 2026-09-22 10:05 UTC (permalink / raw)
  To: Kumar Kartikeya Dwivedi, Eduard Zingerman, Daniel Borkmann,
	Alexei Starovoitov, Andrii Nakryiko, bpf, Networking
  Cc: Linux Kernel Mailing List, Linux Next Mailing List

[-- Attachment #1: Type: text/plain, Size: 5374 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  tools/testing/selftests/bpf/prog_tests/verifier.c

between commit:

  a903f145a8914 ("selftests/bpf: Add tests for the KF_PERFMON gates")

from the bpf tree and commit:

  a8bbd9ee1bbc7 ("selftests/bpf: Cover generic __uninit output initialization")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

diff --cc kernel/bpf/helpers.c
index 712dca5a2c5bd,501c7ce35cba9..0000000000000
--- a/kernel/bpf/helpers.c
+++ b/kernel/bpf/helpers.c
@@@ -4920,12 -5049,14 +5049,14 @@@ BTF_ID_FLAGS(func, bpf_wq_set_callback
  BTF_ID_FLAGS(func, bpf_wq_start)
  BTF_ID_FLAGS(func, bpf_preempt_disable)
  BTF_ID_FLAGS(func, bpf_preempt_enable)
 -BTF_ID_FLAGS(func, bpf_iter_bits_new, KF_ITER_NEW)
 +BTF_ID_FLAGS(func, bpf_iter_bits_new, KF_ITER_NEW | KF_PERFMON)
  BTF_ID_FLAGS(func, bpf_iter_bits_next, KF_ITER_NEXT | KF_RET_NULL)
  BTF_ID_FLAGS(func, bpf_iter_bits_destroy, KF_ITER_DESTROY)
 -BTF_ID_FLAGS(func, bpf_copy_from_user_str, KF_SLEEPABLE)
 -BTF_ID_FLAGS(func, bpf_copy_from_user_mm, KF_SLEEPABLE)
 -BTF_ID_FLAGS(func, bpf_copy_from_user_mm_str, KF_SLEEPABLE)
 -BTF_ID_FLAGS(func, bpf_copy_from_user_task_str, KF_SLEEPABLE)
 -BTF_ID_FLAGS(func, bpf_get_kmem_cache)
 +BTF_ID_FLAGS(func, bpf_copy_from_user_str, KF_SLEEPABLE | KF_PERFMON)
++BTF_ID_FLAGS(func, bpf_copy_from_user_mm, KF_SLEEPABLE | KF_PERFMON)
++BTF_ID_FLAGS(func, bpf_copy_from_user_mm_str, KF_SLEEPABLE | KF_PERFMON)
 +BTF_ID_FLAGS(func, bpf_copy_from_user_task_str, KF_SLEEPABLE | KF_PERFMON)
 +BTF_ID_FLAGS(func, bpf_get_kmem_cache, KF_PERFMON)
  BTF_ID_FLAGS(func, bpf_iter_kmem_cache_new, KF_ITER_NEW | KF_SLEEPABLE)
  BTF_ID_FLAGS(func, bpf_iter_kmem_cache_next, KF_ITER_NEXT | KF_RET_NULL | KF_SLEEPABLE)
  BTF_ID_FLAGS(func, bpf_iter_kmem_cache_destroy, KF_ITER_DESTROY | KF_SLEEPABLE)
diff --cc mm/internal.h
index 0434dfcfc36f1,9e3be236f18c0..0000000000000
--- a/mm/internal.h
+++ b/mm/internal.h
@@@ -24,7 -23,17 +24,10 @@@
  #include "vma.h"
  
  struct folio_batch;
 -struct hstate;
  
+ int __copy_remote_mm_str(struct mm_struct *mm, unsigned long addr,
+ 		void *buf, int len, unsigned int gup_flags);
+ 
 -struct huge_bootmem_page {
 -	struct list_head list;
 -	struct hstate *hstate;
 -	unsigned long flags;
 -};
 -
  /* mm/workingset.c */
  bool workingset_test_recent(void *shadow, bool file, bool *workingset,
  			    bool flush);
diff --cc tools/testing/selftests/bpf/prog_tests/cb_refs.c
index 490e15e7126d9,c32c6dab49bce..0000000000000
--- a/tools/testing/selftests/bpf/prog_tests/cb_refs.c
+++ b/tools/testing/selftests/bpf/prog_tests/cb_refs.c
@@@ -11,9 -11,9 +11,9 @@@ struct 
  	const char *prog_name;
  	const char *err_msg;
  } cb_refs_tests[] = {
- 	{ "underflow_prog", "release kfunc bpf_kfunc_call_test_release expects referenced PTR_TO_BTF_ID passed to R1" },
- 	{ "leak_prog", "Possibly NULL pointer passed to helper R2" },
+ 	{ "underflow_prog", "R1 type=scalar expected=ptr_, trusted_ptr_, rcu_ptr_" },
+ 	{ "leak_prog", "Unreleased reference id=4 alloc_insn=3" }, /* alloc_insn=3{2,3} */
 -	{ "nested_cb", "Unreleased reference id=4 alloc_insn=2" }, /* alloc_insn=2{4,5} */
 +	{ "nested_cb", "Unreleased reference id=5 alloc_insn=2" }, /* alloc_insn=2{4,5} */
  	{ "non_cb_transfer_ref", "Unreleased reference id=4 alloc_insn=1" }, /* alloc_insn=1{1,2} */
  };
  
diff --cc tools/testing/selftests/bpf/prog_tests/verifier.c
index 8b439e194bcc5,4f1e1c1cd5ab3..0000000000000
--- a/tools/testing/selftests/bpf/prog_tests/verifier.c
+++ b/tools/testing/selftests/bpf/prog_tests/verifier.c
@@@ -54,7 -55,9 +56,10 @@@
  #include "verifier_iterating_callbacks.skel.h"
  #include "verifier_jeq_infer_not_null.skel.h"
  #include "verifier_jit_convergence.skel.h"
+ #include "verifier_kfunc_packet_access.skel.h"
 +#include "verifier_kfunc_perfmon.skel.h"
+ #include "verifier_kfunc_uninit.skel.h"
+ #include "verifier_kfunc_uninit_multi.skel.h"
  #include "verifier_ld_ind.skel.h"
  #include "verifier_ldsx.skel.h"
  #include "verifier_leak_ptr.skel.h"
@@@ -219,7 -224,9 +227,10 @@@ void test_verifier_int_ptr(void
  void test_verifier_iterating_callbacks(void)  { RUN(verifier_iterating_callbacks); }
  void test_verifier_jeq_infer_not_null(void)   { RUN(verifier_jeq_infer_not_null); }
  void test_verifier_jit_convergence(void)      { RUN(verifier_jit_convergence); }
+ void test_verifier_kfunc_packet_access(void)  { RUN_TESTS(verifier_kfunc_packet_access); }
 +void test_verifier_kfunc_perfmon(void)        { RUN(verifier_kfunc_perfmon); }
+ void test_verifier_kfunc_uninit(void)         { RUN_TESTS(verifier_kfunc_uninit); }
+ void test_verifier_kfunc_uninit_multi(void)   { RUN_TESTS(verifier_kfunc_uninit_multi); }
  void test_verifier_load_acquire(void)         { RUN(verifier_load_acquire); }
  void test_verifier_ld_ind(void)               { RUN(verifier_ld_ind); }
  void test_verifier_ldsx(void)                  { RUN(verifier_ldsx); }

[-- Attachment #2: signature.asc --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2026-09-24 12:39 Mark Brown
  2026-09-24 16:12 ` Ihor Solodrai
  0 siblings, 1 reply; 69+ messages in thread
From: Mark Brown @ 2026-09-24 12:39 UTC (permalink / raw)
  To: Kumar Kartikeya Dwivedi, Eduard Zingerman, Daniel Borkmann,
	Alexei Starovoitov, Andrii Nakryiko, bpf, Networking
  Cc: Ihor Solodrai, Linux Kernel Mailing List, Linux Next Mailing List

[-- Attachment #1: Type: text/plain, Size: 781 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  tools/testing/selftests/bpf/prog_tests/cb_refs.c

between commit:

  04ae4ffc57a6b ("selftests/bpf: Check callback map value lock identity")

from the bpf tree and commit:

  11300f54bd887 ("selftests/bpf: Refactor cb_refs selftests")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

(deleted the file, which probably lost the test)

[-- Attachment #2: signature.asc --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2026-09-24 12:39 Mark Brown
@ 2026-09-24 16:12 ` Ihor Solodrai
  2026-09-24 16:22   ` Alexei Starovoitov
  0 siblings, 1 reply; 69+ messages in thread
From: Ihor Solodrai @ 2026-09-24 16:12 UTC (permalink / raw)
  To: Mark Brown, Kumar Kartikeya Dwivedi, Eduard Zingerman,
	Daniel Borkmann, Alexei Starovoitov, Andrii Nakryiko, bpf,
	Networking
  Cc: Linux Kernel Mailing List, Linux Next Mailing List

On 9/24/26 5:39 AM, Mark Brown wrote:
> Hi all,
> 
> Today's linux-next merge of the bpf-next tree got a conflict in:
> 
>   tools/testing/selftests/bpf/prog_tests/cb_refs.c
> 
> between commit:
> 
>   04ae4ffc57a6b ("selftests/bpf: Check callback map value lock identity")
> 
> from the bpf tree and commit:
> 
>   11300f54bd887 ("selftests/bpf: Refactor cb_refs selftests")
> 
> from the bpf-next tree.
> 
> I fixed it up (see below) and can carry the fix as necessary. This
> is now fixed as far as linux-next is concerned, but any non trivial
> conflicts should be mentioned to your upstream maintainer when your tree
> is submitted for merging.  You may also want to consider cooperating
> with the maintainer of the conflicting tree to minimise any particularly
> complex conflicts.
> 
> (deleted the file, which probably lost the test)

Hi Mark.

I submitted 11300f54bd887 ("selftests/bpf: Refactor cb_refs selftests")
yesterday to address a non-code conflict between bpf and bpf-next. A
test would start failing after bpf is merged into bpf-next.

Deleting tools/testing/selftests/bpf/prog_tests/cb_refs.c is correct,
the tests were moved.

Thank you for resolving this.

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2026-09-24 16:12 ` Ihor Solodrai
@ 2026-09-24 16:22   ` Alexei Starovoitov
  0 siblings, 0 replies; 69+ messages in thread
From: Alexei Starovoitov @ 2026-09-24 16:22 UTC (permalink / raw)
  To: Ihor Solodrai, Mark Brown, Kumar Kartikeya Dwivedi,
	Eduard Zingerman, Daniel Borkmann, Alexei Starovoitov,
	Andrii Nakryiko, bpf, Networking
  Cc: Linux Kernel Mailing List, Linux Next Mailing List

On Thu Sep 24, 2026 at 4:12 PM UTC, Ihor Solodrai wrote:
> On 9/24/26 5:39 AM, Mark Brown wrote:
>> Hi all,
>> 
>> Today's linux-next merge of the bpf-next tree got a conflict in:
>> 
>>   tools/testing/selftests/bpf/prog_tests/cb_refs.c
>> 
>> between commit:
>> 
>>   04ae4ffc57a6b ("selftests/bpf: Check callback map value lock identity")
>> 
>> from the bpf tree and commit:
>> 
>>   11300f54bd887 ("selftests/bpf: Refactor cb_refs selftests")
>> 
>> from the bpf-next tree.
>> 
>> I fixed it up (see below) and can carry the fix as necessary. This
>> is now fixed as far as linux-next is concerned, but any non trivial
>> conflicts should be mentioned to your upstream maintainer when your tree
>> is submitted for merging.  You may also want to consider cooperating
>> with the maintainer of the conflicting tree to minimise any particularly
>> complex conflicts.
>> 
>> (deleted the file, which probably lost the test)
>
> Hi Mark.
>
> I submitted 11300f54bd887 ("selftests/bpf: Refactor cb_refs selftests")
> yesterday to address a non-code conflict between bpf and bpf-next. A
> test would start failing after bpf is merged into bpf-next.
>
> Deleting tools/testing/selftests/bpf/prog_tests/cb_refs.c is correct,
> the tests were moved.
>
> Thank you for resolving this.

+1

bpf tree was cross merged into bpf-next and all conflicts resolved.
Next linux-next should be clean. fingers crossed.


^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2026-09-29 12:15 Mark Brown
  0 siblings, 0 replies; 69+ messages in thread
From: Mark Brown @ 2026-09-29 12:15 UTC (permalink / raw)
  To: Kumar Kartikeya Dwivedi, Eduard Zingerman, Daniel Borkmann,
	Alexei Starovoitov, Andrii Nakryiko, bpf, Networking
  Cc: Florent Revest, Linux Kernel Mailing List,
	Linux Next Mailing List

[-- Attachment #1: Type: text/plain, Size: 1631 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  arch/arm64/net/bpf_jit_comp.c

between commit:

  17637e1a581a2 ("bpf: Skip detached progs in trampoline images that are still in use")

from the bpf tree and commits:

  1d5306c11da2d ("bpf, arm64: Allow programs 2 KiB of stack")
  11a516144d9a8 ("bpf, arm64: Add JIT support for callx")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

diff --cc arch/arm64/net/bpf_jit_comp.c
index 8108012cd7e4a,475e706534543..0000000000000
--- a/arch/arm64/net/bpf_jit_comp.c
+++ b/arch/arm64/net/bpf_jit_comp.c
@@@ -2413,11 -2498,20 +2493,21 @@@ bool bpf_jit_supports_subprog_tailcalls
  	return true;
  }
  
+ bool bpf_jit_supports_callx(void)
+ {
+ 	return true;
+ }
+ 
+ bool bpf_jit_supports_large_stack(void)
+ {
+ 	return true;
+ }
+ 
 -static void invoke_bpf_prog(struct jit_ctx *ctx, struct bpf_tramp_node *node,
 -			    int bargs_off, int retval_off, int run_ctx_off,
 -			    bool save_ret)
 +static void invoke_bpf_prog(struct jit_ctx *ctx, struct bpf_tramp_image *im,
 +			    struct bpf_tramp_node *node, int bargs_off,
 +			    int retval_off, int run_ctx_off, bool save_ret)
  {
 +	void *skip;
  	__le32 *branch;
  	u64 enter_prog;
  	u64 exit_prog;

[-- Attachment #2: signature.asc --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2026-09-29 14:56 Mark Brown
  2026-09-29 16:31 ` Alexei Starovoitov
  2026-09-30  7:07 ` Jiri Olsa
  0 siblings, 2 replies; 69+ messages in thread
From: Mark Brown @ 2026-09-29 14:56 UTC (permalink / raw)
  To: Kumar Kartikeya Dwivedi, Eduard Zingerman, Daniel Borkmann,
	Alexei Starovoitov, Andrii Nakryiko, bpf, Networking
  Cc: Florent Revest, Jiri Olsa, Linux Kernel Mailing List,
	Linux Next Mailing List

[-- Attachment #1: Type: text/plain, Size: 2090 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  arch/x86/net/bpf_jit_comp.c

between commit:

  17637e1a581a2 ("bpf: Skip detached progs in trampoline images that are still in use")

from the bpf tree and commit:

  29fcf9ce4bbdf ("bpf, x86: Use global buffer for trampoline size generation")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

diff --cc arch/x86/net/bpf_jit_comp.c
index 6bca87457e872,6c7a0578760e7..0000000000000
--- a/arch/x86/net/bpf_jit_comp.c
+++ b/arch/x86/net/bpf_jit_comp.c
@@@ -3817,25 -4152,15 +4158,15 @@@ out
  int arch_bpf_trampoline_size(const struct btf_func_model *m, u32 flags,
  			     struct bpf_tramp_nodes *tnodes, void *func_addr)
  {
 -	struct bpf_tramp_image im;
 +	struct bpf_tramp_image im = {};
- 	void *image;
- 	int ret;
  
- 	/* Allocate a temporary buffer for __arch_prepare_bpf_trampoline().
- 	 *
- 	 * We cannot use kvmalloc here, because we need image to be in
- 	 * module memory range.
- 	 * Since it must be writable use execmem_alloc(EXECMEM_MODULE_DATA)
- 	 * that returns writable memory in the module address space.
- 	 */
- 	image = execmem_alloc(EXECMEM_MODULE_DATA, PAGE_SIZE);
- 	if (!image)
+ 	if (!trampoline_size_image)
  		return -ENOMEM;
  
- 	ret = __arch_prepare_bpf_trampoline(&im, image, image + PAGE_SIZE, image,
- 					    m, flags, tnodes, func_addr);
- 	execmem_free(image);
- 	return ret;
+ 	return __arch_prepare_bpf_trampoline(&im, trampoline_size_image,
+ 					     trampoline_size_image + PAGE_SIZE,
+ 					     trampoline_size_image, m, flags,
+ 					     tnodes, func_addr);
  }
  
  static int emit_bpf_dispatcher(u8 **pprog, int a, int b, s64 *progs, u8 *image, u8 *buf)

[-- Attachment #2: signature.asc --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2026-09-29 14:56 Mark Brown
@ 2026-09-29 16:31 ` Alexei Starovoitov
  2026-09-30  7:07 ` Jiri Olsa
  1 sibling, 0 replies; 69+ messages in thread
From: Alexei Starovoitov @ 2026-09-29 16:31 UTC (permalink / raw)
  To: Mark Brown, Kumar Kartikeya Dwivedi, Eduard Zingerman,
	Daniel Borkmann, Alexei Starovoitov, Andrii Nakryiko, bpf,
	Networking
  Cc: Florent Revest, Jiri Olsa, Linux Kernel Mailing List,
	Linux Next Mailing List

On Tue Sep 29, 2026 at 2:56 PM UTC, Mark Brown wrote:
> Hi all,
>
> Today's linux-next merge of the bpf-next tree got a conflict in:
>
>   arch/x86/net/bpf_jit_comp.c
>
> between commit:
>
>   17637e1a581a2 ("bpf: Skip detached progs in trampoline images that are still in use")
>
> from the bpf tree and commit:
>
>   29fcf9ce4bbdf ("bpf, x86: Use global buffer for trampoline size generation")
>
> from the bpf-next tree.
>
> I fixed it up (see below) and can carry the fix as necessary. This

all correct. It will get fixed when bpf gets cross mereged into bpf-next.
Likely on Thu or Fri this week.

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2026-09-29 14:56 Mark Brown
  2026-09-29 16:31 ` Alexei Starovoitov
@ 2026-09-30  7:07 ` Jiri Olsa
  1 sibling, 0 replies; 69+ messages in thread
From: Jiri Olsa @ 2026-09-30  7:07 UTC (permalink / raw)
  To: Mark Brown
  Cc: Kumar Kartikeya Dwivedi, Eduard Zingerman, Daniel Borkmann,
	Alexei Starovoitov, Andrii Nakryiko, bpf, Networking,
	Florent Revest, Linux Kernel Mailing List,
	Linux Next Mailing List

On Tue, Sep 29, 2026 at 03:56:51PM +0100, Mark Brown wrote:
> Hi all,
> 
> Today's linux-next merge of the bpf-next tree got a conflict in:
> 
>   arch/x86/net/bpf_jit_comp.c
> 
> between commit:
> 
>   17637e1a581a2 ("bpf: Skip detached progs in trampoline images that are still in use")
> 
> from the bpf tree and commit:
> 
>   29fcf9ce4bbdf ("bpf, x86: Use global buffer for trampoline size generation")
> 
> from the bpf-next tree.
> 
> I fixed it up (see below) and can carry the fix as necessary. This

lgtm, thanks

jirka

> is now fixed as far as linux-next is concerned, but any non trivial
> conflicts should be mentioned to your upstream maintainer when your tree
> is submitted for merging.  You may also want to consider cooperating
> with the maintainer of the conflicting tree to minimise any particularly
> complex conflicts.
> 
> diff --cc arch/x86/net/bpf_jit_comp.c
> index 6bca87457e872,6c7a0578760e7..0000000000000
> --- a/arch/x86/net/bpf_jit_comp.c
> +++ b/arch/x86/net/bpf_jit_comp.c
> @@@ -3817,25 -4152,15 +4158,15 @@@ out
>   int arch_bpf_trampoline_size(const struct btf_func_model *m, u32 flags,
>   			     struct bpf_tramp_nodes *tnodes, void *func_addr)
>   {
>  -	struct bpf_tramp_image im;
>  +	struct bpf_tramp_image im = {};
> - 	void *image;
> - 	int ret;
>   
> - 	/* Allocate a temporary buffer for __arch_prepare_bpf_trampoline().
> - 	 *
> - 	 * We cannot use kvmalloc here, because we need image to be in
> - 	 * module memory range.
> - 	 * Since it must be writable use execmem_alloc(EXECMEM_MODULE_DATA)
> - 	 * that returns writable memory in the module address space.
> - 	 */
> - 	image = execmem_alloc(EXECMEM_MODULE_DATA, PAGE_SIZE);
> - 	if (!image)
> + 	if (!trampoline_size_image)
>   		return -ENOMEM;
>   
> - 	ret = __arch_prepare_bpf_trampoline(&im, image, image + PAGE_SIZE, image,
> - 					    m, flags, tnodes, func_addr);
> - 	execmem_free(image);
> - 	return ret;
> + 	return __arch_prepare_bpf_trampoline(&im, trampoline_size_image,
> + 					     trampoline_size_image + PAGE_SIZE,
> + 					     trampoline_size_image, m, flags,
> + 					     tnodes, func_addr);
>   }
>   
>   static int emit_bpf_dispatcher(u8 **pprog, int a, int b, s64 *progs, u8 *image, u8 *buf)



^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2026-11-03 14:08 Mark Brown
  2026-11-03 17:40 ` Alexei Starovoitov
  0 siblings, 1 reply; 69+ messages in thread
From: Mark Brown @ 2026-11-03 14:08 UTC (permalink / raw)
  To: Kumar Kartikeya Dwivedi, Eduard Zingerman, Daniel Borkmann,
	Alexei Starovoitov, Andrii Nakryiko, bpf, Networking
  Cc: Linux Kernel Mailing List, Linux Next Mailing List, Qiliang Yuan

[-- Attachment #1: Type: text/plain, Size: 10900 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  kernel/bpf/fixups.c

between commits:

  ec274bb4665c2 ("bpf: One may_goto time slice per prog invocation")
  1ddffb57b3623 ("bpf: Emit timed may_goto for JITed progs only")
  1ddffb57b3623 ("bpf: Emit timed may_goto for JITed progs only")

from the bpf tree and commit:

  a7a767c66a2e2 ("bpf: Queue the rewrites of bpf_do_misc_fixups()")

and likely others from the bpf-next tree.  Given the nature of the
conflict and my total lack of familiarity with this code it seems
vanishingly unlikely that I'd be able to do a sensible merge here,
instead I will hold the bpf-next tree at the version from next-20261102.
If someone could help me out with the merge here that would be very much
appreciated.

The conflict is:

diff --cc kernel/bpf/fixups.c
index a656634fa9e46,ead78713e04f4..0000000000000
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@@ -1804,47 -1776,24 +1776,68 @@@ static int may_goto_expand(struct bpf_i
  }
  
  /*
++<<<<<<< HEAD
 + * Timed may_goto. All may_goto of a prog use one count and one timestamp: per-cpu memory of the
 + * prog, set in the first insns of the main prog, and by the callers of async callbacks.
 + * @reg holds the address. It is a register that is dead at the may_goto, or R0 that is saved at
 + * @save_off in the stack.
 + */
 +static int may_goto_expand_timed(struct bpf_insn *insn_buf, int off,
 +				 struct bpf_timed_may_goto __percpu *tmg, int reg, int save_off)
 +{
 +	struct bpf_insn ld_tmg[] = { BPF_LD_IMM64(reg, (__force unsigned long)tmg) };
 +	int cnt = 0, jmp, tail_cnt = save_off ? 6 : 5;
 +
 +	if (save_off)
 +		insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, reg, save_off);
 +	insn_buf[cnt++] = ld_tmg[0];
 +	insn_buf[cnt++] = ld_tmg[1];
 +	insn_buf[cnt++] = BPF_MOV64_PERCPU_REG(reg, reg);
 +	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, reg, 0);
 +	if (save_off) {
 +		insn_buf[cnt++] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2);
 +		insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, reg, BPF_REG_10, save_off);
 +		jmp = cnt++;
 +		insn_buf[jmp] = BPF_JMP32_A(off >= 0 ? off + tail_cnt : off - jmp);
 +	} else {
 +		jmp = cnt;
 +		off = off >= 0 ? off + tail_cnt : off - jmp;
 +		if (off == (s16)off) {
 +			insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, off);
 +		} else {
 +			insn_buf[cnt++] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 1);
 +			insn_buf[cnt++] = BPF_JMP32_A(off >= 0 ? off : off - 1);
 +		}
 +	}
 +	insn_buf[cnt++] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
 +	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2);
 +	/* AX is the argument and the return value */
 +	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_AX, reg);
 +	insn_buf[cnt++] = BPF_EMIT_CALL(arch_bpf_timed_may_goto);
 +	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, reg, BPF_REG_AX, 0);
 +	if (save_off)
 +		insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, reg, BPF_REG_10, save_off);
 +	return cnt;
++=======
+  * The offset of may_goto at 'idx' once the patches queued in front are applied.
+  * The patches that a forward may_goto jumps over aren't queued yet, so its
+  * offset stays as it is.
+  */
+ static int may_goto_off(struct bpf_verifier_env *env, const struct bpf_insn *insn,
+ 			u32 idx)
+ {
+ 	struct bpf_patch_list *pl = &env->patch_list;
+ 	u32 tgt = idx + insn->off + 1;
+ 	int off = insn->off;
+ 	u32 k = pl->cnt;
+ 
+ 	if (off >= 0)
+ 		return off;
+ 	/* all queued patches are in front of idx */
+ 	while (k > 0 && pl->patches[k - 1].off >= tgt)
+ 		off -= pl->patches[--k].len - 1;
+ 	return off;
++>>>>>>> bpf-next/for-next
  }
  
  /* Do various post-verification rewrites in a single program pass.
@@@ -2125,36 -2050,43 +2097,53 @@@ int bpf_do_misc_fixups(struct bpf_verif
  			goto next_insn;
  		}
  
 -		if (bpf_is_may_goto_insn(insn) && bpf_jit_supports_timed_may_goto()) {
 -			int stack_off_cnt = -stack_depth - 16;
 -			/*
 -			 * AX is used as an argument to pass in stack_off_cnt
 -			 * (to add to r10/fp), and also as the return value of
 -			 * the call to arch_bpf_timed_may_goto.
 -			 */
 -			struct bpf_insn tail[] = {
 -				BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1),
 -				BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2),
 -				BPF_MOV64_IMM(BPF_REG_AX, stack_off_cnt),
 -				BPF_EMIT_CALL(arch_bpf_timed_may_goto),
 -				BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off_cnt),
 -			};
 +		if (bpf_is_may_goto_insn(insn) && timed_may_goto) {
 +			u16 live = env->insn_aux_data[i + delta].live_regs_before;
 +			int reg, save_off = 0;
  
++<<<<<<< HEAD
 +			/* a register that is dead here holds the address of the count */
 +			for (reg = BPF_REG_0; reg <= BPF_REG_9; reg++)
 +				if (!(live & BIT(reg)))
 +					break;
 +			if (reg > BPF_REG_9) {
 +				reg = BPF_REG_0;
 +				save_off = -stack_depth - 8;
 +				stack_depth_extra = 8;
 +			}
 +			if (!tmg) {
 +				tmg = alloc_percpu_gfp(struct bpf_timed_may_goto,
 +						       GFP_KERNEL_ACCOUNT);
 +				if (!tmg)
 +					return -ENOMEM;
 +				prog->aux->timed_may_goto = tmg;
 +			}
 +			prog->jit_required = 1;
 +			cnt = may_goto_expand_timed(insn_buf, insn->off, tmg, reg, save_off);
++=======
+ 			/*
+ 			 * Two 8 byte slots, depth-16 stores the count, and
+ 			 * depth-8 stores the start timestamp of the loop.
+ 			 *
+ 			 * The starting value of count is BPF_MAX_TIMED_LOOPS
+ 			 * (0xffff).  Every iteration loads it and subs it by 1,
+ 			 * until the value becomes 0 in AX (thus, 1 in stack),
+ 			 * after which we call arch_bpf_timed_may_goto, which
+ 			 * either sets AX to 0xffff to keep looping, or to 0
+ 			 * upon timeout. AX is then stored into the stack. In
+ 			 * the next iteration, we either see 0 and break out, or
+ 			 * continue iterating until the next time value is 0
+ 			 * after subtraction, rinse and repeat.
+ 			 */
+ 			stack_depth_extra = 16;
+ 			cnt = may_goto_expand(insn_buf, insn->off,
+ 					      may_goto_off(env, insn, i),
+ 					      stack_off_cnt, tail, ARRAY_SIZE(tail));
++>>>>>>> bpf-next/for-next
  
- 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
- 			if (!new_prog)
- 				return -ENOMEM;
- 
- 			delta += cnt - 1;
- 			env->prog = prog = new_prog;
- 			insn = new_prog->insnsi + i + delta;
+ 			insn = bpf_patch_list_add(env, i, insn_buf, cnt);
+ 			if (IS_ERR(insn))
+ 				return PTR_ERR(insn);
  			goto next_insn;
  		} else if (bpf_is_may_goto_insn(insn)) {
  			int stack_off = -stack_depth - 8;
@@@ -2762,86 -2630,49 +2687,102 @@@ next_insn
  			stack_depth_extra = 0;
  		}
  		i++;
- 		insn++;
+ 		insn = &prog->insnsi[i];
  	}
  
+ 	ret = bpf_patch_list_commit(env);
+ 	if (ret)
+ 		return ret;
+ 	prog = env->prog;
+ 
  	env->prog->aux->stack_depth = subprogs[0].stack_depth;
  	for (i = 0; i < env->subprog_cnt; i++) {
++<<<<<<< HEAD
 +		int subprog_start = subprogs[i].start;
 +		int stack_slots = subprogs[i].stack_extra / 8;
 +		/* an invocation begins, see bpf_timed_may_goto_save() for async callbacks */
 +		bool main_prog = tmg && !i;
 +		/* only a helper calls it, in a loop that ends when it returns 1 */
 +		bool loop_cb = tmg && i && subprogs[i].is_loop_cb && !subprogs[i].is_called &&
 +			       !subprogs[i].is_async_cb;
 +		int cnt = 0;
++=======
+ 		int slots = bpf_jit_supports_timed_may_goto() ? 2 : 1;
+ 		int stack_slots = subprogs[i].stack_extra / 8;
++>>>>>>> bpf-next/for-next
  
 -		if (!stack_slots)
 +		if (timed_may_goto ? !main_prog && !loop_cb : !stack_slots)
  			continue;
 -		/* We need two slots in case timed may_goto is supported. */
 -		if (stack_slots > slots) {
 +		if (stack_slots > 1) {
  			verifier_bug(env, "stack_slots supports may_goto only");
  			return -EFAULT;
  		}
  
+ 		cnt = 0;
  		stack_depth = subprogs[i].stack_depth;
 -		if (bpf_jit_supports_timed_may_goto()) {
 -			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
 -						     BPF_MAX_TIMED_LOOPS);
 -			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth + 8, 0);
 +		if (timed_may_goto) {
 +			struct bpf_insn ld_tmg[] = {
 +				BPF_LD_IMM64(BPF_REG_0, (__force unsigned long)tmg)
 +			};
 +			int count_off = offsetof(struct bpf_timed_may_goto, count);
 +			int timestamp_off = offsetof(struct bpf_timed_may_goto, timestamp);
 +			int owner_off = offsetof(struct bpf_timed_may_goto, owner);
 +
 +			/* R0 has nothing at the entry */
 +			insn_buf[cnt++] = ld_tmg[0];
 +			insn_buf[cnt++] = ld_tmg[1];
 +			insn_buf[cnt++] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
 +			if (main_prog) {
 +				insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_0, count_off,
 +							     BPF_MAX_TIMED_LOOPS);
 +				insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_0, timestamp_off, 0);
 +				insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_0, owner_off, 0);
 +			} else {
 +				/*
 +				 * The time is up, but the helper would call the function again and
 +				 * again. End its loop. The verifier has seen that: the loop can end
 +				 * after each call.
 +				 */
 +				insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_0,
 +							      count_off);
 +				insn_buf[cnt++] = BPF_JMP_IMM(BPF_JNE, BPF_REG_0, 0, 2);
 +				insn_buf[cnt++] = BPF_MOV64_IMM(BPF_REG_0, 1);
 +				insn_buf[cnt++] = BPF_EXIT_INSN();
 +			}
  		} else {
  			/* Add ST insn to subprog prologue to init extra stack */
  			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
  						     BPF_MAX_LOOPS);
  		}
- 		/* Copy first actual insn to preserve it */
- 		insn_buf[cnt] = env->prog->insnsi[subprog_start];
- 		ret = bpf_adj_moved_insn(&insn_buf[cnt], cnt);
- 		if (ret) {
- 			verbose(env, "insn %d cannot be patched due to 16-bit range\n",
- 				env->insn_aux_data[subprog_start].orig_idx);
+ 		/* jumps to the first insn of the subprog skip the setup */
+ 		ret = bpf_patch_list_insert(env, subprogs[i].start, insn_buf, cnt);
+ 		if (ret)
  			return ret;
++<<<<<<< HEAD
 +		}
 +		cnt++;
 +
 +		new_prog = __bpf_patch_insn_data(env, subprog_start, insn_buf, cnt,
 +						 BPF_PATCH_MOVE_TARGET);
 +		if (!new_prog)
 +			return -ENOMEM;
 +		env->prog = prog = new_prog;
 +		/*
 +		 * If may_goto is a first insn of a prog there could be a jmp
 +		 * insn that points to it, hence adjust all such jmps to point
 +		 * to insn after BPF_ST that inits may_goto count.
 +		 * Adjustment will succeed because bpf_patch_insn_data() didn't fail.
 +		 */
 +		WARN_ON(adjust_jmp_off(env->prog, subprog_start, cnt - 1));
++=======
++>>>>>>> bpf-next/for-next
  	}
  
+ 	ret = bpf_patch_list_commit(env);
+ 	if (ret)
+ 		return ret;
+ 	prog = env->prog;
+ 
  	/* Since poke tab is now finalized, publish aux to tracker. */
  	for (i = 0; i < prog->aux->size_poke_tab; i++) {
  		map_ptr = prog->aux->poke_tab[i].tail_call.map;

[-- Attachment #2: signature.asc --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2026-11-03 14:08 Mark Brown
@ 2026-11-03 17:40 ` Alexei Starovoitov
  2026-11-03 17:50   ` Mark Brown
  0 siblings, 1 reply; 69+ messages in thread
From: Alexei Starovoitov @ 2026-11-03 17:40 UTC (permalink / raw)
  To: Mark Brown, Kumar Kartikeya Dwivedi, Eduard Zingerman,
	Daniel Borkmann, Alexei Starovoitov, Andrii Nakryiko, bpf,
	Networking
  Cc: Linux Kernel Mailing List, Linux Next Mailing List, Qiliang Yuan

On Tue Nov 3, 2026 at 2:08 PM UTC, Mark Brown wrote:
> Hi all,
>
> Today's linux-next merge of the bpf-next tree got a conflict in:
>
>   kernel/bpf/fixups.c
>
> between commits:
>
>   ec274bb4665c2 ("bpf: One may_goto time slice per prog invocation")
>   1ddffb57b3623 ("bpf: Emit timed may_goto for JITed progs only")
>   1ddffb57b3623 ("bpf: Emit timed may_goto for JITed progs only")
>
> from the bpf tree and commit:
>
>   a7a767c66a2e2 ("bpf: Queue the rewrites of bpf_do_misc_fixups()")
>
> and likely others from the bpf-next tree.  Given the nature of the
> conflict and my total lack of familiarity with this code it seems
> vanishingly unlikely that I'd be able to do a sensible merge here,
> instead I will hold the bpf-next tree at the version from next-20261102.
> If someone could help me out with the merge here that would be very much
> appreciated.
>
> The conflict is:

Yep. It wasn't easy.
bpf tree is now ffwded and merged into bpf-next.
Conflict is resolved.


^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2026-11-03 17:40 ` Alexei Starovoitov
@ 2026-11-03 17:50   ` Mark Brown
  0 siblings, 0 replies; 69+ messages in thread
From: Mark Brown @ 2026-11-03 17:50 UTC (permalink / raw)
  To: Alexei Starovoitov
  Cc: Kumar Kartikeya Dwivedi, Eduard Zingerman, Daniel Borkmann,
	Alexei Starovoitov, Andrii Nakryiko, bpf, Networking,
	Linux Kernel Mailing List, Linux Next Mailing List, Qiliang Yuan

[-- Attachment #1: Type: text/plain, Size: 615 bytes --]

On Tue, Nov 03, 2026 at 05:40:04PM +0000, Alexei Starovoitov wrote:
> On Tue Nov 3, 2026 at 2:08 PM UTC, Mark Brown wrote:

> > and likely others from the bpf-next tree.  Given the nature of the
> > conflict and my total lack of familiarity with this code it seems
> > vanishingly unlikely that I'd be able to do a sensible merge here,
> > instead I will hold the bpf-next tree at the version from next-20261102.
> > If someone could help me out with the merge here that would be very much
> > appreciated.

> Yep. It wasn't easy.
> bpf tree is now ffwded and merged into bpf-next.
> Conflict is resolved.

Thanks!

[-- Attachment #2: signature.asc --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2026-11-17 21:36 Mark Brown
  2026-11-18 15:47 ` J4f J4f
  0 siblings, 1 reply; 69+ messages in thread
From: Mark Brown @ 2026-11-17 21:36 UTC (permalink / raw)
  To: Kumar Kartikeya Dwivedi, Eduard Zingerman, Daniel Borkmann,
	Alexei Starovoitov, Andrii Nakryiko, bpf, Networking
  Cc: Linux Kernel Mailing List, Linux Next Mailing List, Shihuang Liu

[-- Attachment #1: Type: text/plain, Size: 31542 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  kernel/bpf/btf.c

between commit:

  b7cc45994c3f9 ("bpf: Check variable-offset accesses against special fields")

from the bpf tree and commit:

  ca4395aade31a ("bpf: Walk each type once when looking for special fields")

from the bpf-next tree.  I'm not confident of this merge, it discards
the bpf commit on the basis that it looks like there is some new
handling of special fields in the bpf-next tree but I'm not sure that
overlaps with the fix.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

diff --combined kernel/bpf/btf.c
index 49fcd32d418a9,e95ca39f990c6..0000000000000
--- a/kernel/bpf/btf.c
+++ b/kernel/bpf/btf.c
@@@ -281,6 -281,7 +281,7 @@@ struct btf 
  	char name[MODULE_NAME_LEN];
  	bool kernel_btf;
  	__u32 *base_id_map; /* map from distilled base BTF -> vmlinux BTF ids */
+ 	u32 *next_tag; /* see btf_link_decl_tags() */
  };
  
  enum verifier_phase {
@@@ -308,6 -309,9 +309,9 @@@ enum resolve_mode 
  					 */
  };
  
+ /* It bounds the time of the loops that compare or print names */
+ #define BTF_MAX_NAME_LEN 4096
+ 
  #define MAX_RESOLVE_DEPTH 32
  
  struct btf_sec_info {
@@@ -319,6 -323,7 +323,7 @@@ struct btf_verifier_env 
  	struct btf *btf;
  	u8 *visit_states;
  	struct resolve_vertex stack[MAX_RESOLVE_DEPTH];
+ 	unsigned long *names;	/* offsets of the strings that can be names */
  	struct bpf_verifier_log log;
  	u32 log_type_id;
  	u32 top_stack;
@@@ -684,10 -689,15 +689,15 @@@ s32 btf_find_by_name_kind(const struct 
  				return id;
  		}
  	} else {
+ 		/* only the tags in BTF of a program have long names */
+ 		bool slow = !btf->kernel_btf && strlen(name) > KSYM_NAME_LEN;
+ 
  		for (id = btf_start_id(btf); id < total; id++) {
  			t = btf_type_by_id(btf, id);
  			if (BTF_INFO_KIND(t->info) != kind)
  				continue;
+ 			if (slow && bpf_must_abort())
+ 				return -EINTR;
  			tname = btf_name_by_offset(btf, t->name_off);
  			if (strcmp(tname, name) == 0)
  				return id;
@@@ -914,49 -924,6 +924,6 @@@ const char *btf_str_by_offset(const str
  	return NULL;
  }
  
- /* Names in BTF of Rust are not C identifiers. Allow any printable character */
- static bool btf_name_valid_identifier(const struct btf *btf, u32 offset)
- {
- 	/* offset must be valid */
- 	const char *src = btf_str_by_offset(btf, offset);
- 	const char *src_limit;
- 
- 	if (!isprint(*src))
- 		return false;
- 
- 	/* set a limit on identifier length */
- 	src_limit = src + KSYM_NAME_LEN;
- 	src++;
- 	while (*src && src < src_limit) {
- 		if (!isprint(*src))
- 			return false;
- 		src++;
- 	}
- 
- 	return !*src;
- }
- 
- /* Allow any printable character in DATASEC names */
- static bool btf_name_valid_section(const struct btf *btf, u32 offset)
- {
- 	/* offset must be valid */
- 	const char *src = btf_str_by_offset(btf, offset);
- 	const char *src_limit;
- 
- 	if (!*src)
- 		return false;
- 
- 	/* set a limit on identifier length */
- 	src_limit = src + KSYM_NAME_LEN;
- 	while (*src && src < src_limit) {
- 		if (!isprint(*src))
- 			return false;
- 		src++;
- 	}
- 
- 	return !*src;
- }
- 
  static const char *__btf_name_by_offset(const struct btf *btf, u32 offset)
  {
  	const char *name;
@@@ -1907,6 -1874,7 +1874,7 @@@ static void btf_free(struct btf *btf
  	if (!btf_is_vmlinux(btf))
  		kvfree(btf->data);
  	kvfree(btf->base_id_map);
+ 	kvfree(btf->next_tag);
  	kfree(btf);
  }
  
@@@ -1991,9 -1959,21 +1959,21 @@@ nomem
  static void btf_verifier_env_free(struct btf_verifier_env *env)
  {
  	kvfree(env->visit_states);
+ 	kvfree(env->names);
  	kfree(env);
  }
  
+ /* Names in BTF of Rust are not C identifiers. Allow any printable character */
+ static bool btf_name_valid(const struct btf_verifier_env *env, u32 offset)
+ {
+ 	const struct btf *btf = env->btf;
+ 
+ 	/* offset must be valid */
+ 	if (offset < btf->start_str_off)
+ 		return *btf_str_by_offset(btf, offset);
+ 	return test_bit(offset - btf->start_str_off, env->names);
+ }
+ 
  static bool env_type_is_resolve_sink(const struct btf_verifier_env *env,
  				     const struct btf_type *next_type)
  {
@@@ -2766,7 -2746,7 +2746,7 @@@ static int btf_ref_type_check_meta(stru
  	 */
  	if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPEDEF) {
  		if (!t->name_off ||
- 		    !btf_name_valid_identifier(env->btf, t->name_off)) {
+ 		    !btf_name_valid(env, t->name_off)) {
  			btf_verifier_log_type(env, t, "Invalid name");
  			return -EINVAL;
  		}
@@@ -3028,7 -3008,7 +3008,7 @@@ static s32 btf_fwd_check_meta(struct bt
  
  	/* fwd type must have a valid name */
  	if (!t->name_off ||
- 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
+ 	    !btf_name_valid(env, t->name_off)) {
  		btf_verifier_log_type(env, t, "Invalid name");
  		return -EINVAL;
  	}
@@@ -3351,7 -3331,7 +3331,7 @@@ static s32 btf_struct_check_meta(struc
  
  	/* struct type either no name or a valid one */
  	if (t->name_off &&
- 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
+ 	    !btf_name_valid(env, t->name_off)) {
  		btf_verifier_log_type(env, t, "Invalid name");
  		return -EINVAL;
  	}
@@@ -3369,7 -3349,7 +3349,7 @@@
  
  		/* struct member either no name or a valid one */
  		if (member->name_off &&
- 		    !btf_name_valid_identifier(btf, member->name_off)) {
+ 		    !btf_name_valid(env, member->name_off)) {
  			btf_verifier_log_member(env, t, member, "Invalid name");
  			return -EINVAL;
  		}
@@@ -3636,13 -3616,45 +3616,45 @@@ static int btf_find_kptr(const struct b
  	return BTF_FIELD_FOUND;
  }
  
+ /* For BTF of programs: next_tag[type] -> its first tag, next_tag[tag] -> its next tag, ... 0 */
+ static int btf_link_decl_tags(struct btf *btf)
+ {
+ 	u32 i;
+ 
+ 	btf->next_tag = kvcalloc(btf->nr_types, sizeof(u32), GFP_KERNEL | __GFP_NOWARN);
+ 	if (!btf->next_tag)
+ 		return -ENOMEM;
+ 	for (i = btf->nr_types; --i;) {
+ 		if (!btf_type_is_decl_tag(btf->types[i]))
+ 			continue;
+ 		btf->next_tag[i] = btf->next_tag[btf->types[i]->type];
+ 		btf->next_tag[btf->types[i]->type] = i;
+ 	}
+ 	return 0;
+ }
+ 
+ static int btf_type_ptr_cmp(const void *a, const void *b)
+ {
+ 	return cmp_int(*(void **)a, *(void **)b);
+ }
+ 
+ /* last_id is 0 for the first tag */
  int btf_find_next_decl_tag(const struct btf *btf, const struct btf_type *pt,
  			   int comp_idx, const char *tag_key, int last_id)
  {
+ 	int i = last_id ?: btf_named_start_id(btf, false) - 1, n = btf_nr_types(btf);
  	int len = strlen(tag_key);
- 	int i, n;
+ 	struct btf_type **p;
  
- 	for (i = last_id + 1, n = btf_nr_types(btf); i < n; i++) {
+ 	if (btf->next_tag && !last_id) {
+ 		/* the types are in the order of their ids in btf->data */
+ 		p = bsearch(&pt, btf->types + 1, n - 1, sizeof(*p), btf_type_ptr_cmp);
+ 		if (!p)
+ 			return -ENOENT;
+ 		i = p - btf->types;
+ 	}
+ 
+ 	while ((i = btf->next_tag ? btf->next_tag[i] ?: n : i + 1) < n) {
  		const struct btf_type *t = btf_type_by_id(btf, i);
  
  		if (!btf_type_is_decl_tag(t))
@@@ -3665,8 -3677,7 +3677,7 @@@ const char *btf_find_decl_tag_value(con
  	const struct btf_type *t;
  	int len, id;
  
- 	id = btf_find_next_decl_tag(btf, pt, comp_idx, tag_key,
- 				    btf_named_start_id(btf, false) - 1);
+ 	id = btf_find_next_decl_tag(btf, pt, comp_idx, tag_key, 0);
  	if (id < 0)
  		return ERR_PTR(id);
  
@@@ -3682,6 -3693,36 +3693,36 @@@
  	return value;
  }
  
+ /*
+  * The value of the decl tag "<tag_key><value>" on a function of the kernel or of
+  * a module. The build sorts their BTF by name: the tags with one key are
+  * neighbours, and so are those with one value.
+  *
+  * Only the own types of btf are searched, not its base. With the BTF of a module
+  * func_id can be a FUNC of vmlinux: it stands for the function of that name in the
+  * module. What the build found in the code of vmlinux is not true for it.
+  */
+ const char *btf_find_func_tag_value(const struct btf *btf, u32 func_id, const char *tag_key)
+ {
+ 	int id, n = btf_nr_types(btf), len = strlen(tag_key);
+ 	const char *name = NULL;
+ 	u32 name_off = 0;
+ 
+ 	for (id = btf_find_by_name_kind_bsearch(btf, tag_key); id < n; id++) {
+ 		const struct btf_type *t = btf_type_by_id(btf, id);
+ 
+ 		if (t->name_off != name_off) {
+ 			name_off = t->name_off;
+ 			name = btf_name_by_offset(btf, name_off);
+ 			if (strncmp(name, tag_key, len))
+ 				break;
+ 		}
+ 		if (t->type == func_id && btf_type_is_decl_tag(t))
+ 			return name + len;
+ 	}
+ 	return NULL;
+ }
+ 
  static int
  btf_find_graph_root(const struct btf *btf, const struct btf_type *pt,
  		    const struct btf_type *t, int comp_idx, u32 off,
@@@ -3773,106 -3814,106 +3814,106 @@@ end
  	return type;
  }
  
- /* Repeat a number of fields for a specified number of times.
+ /*
+  * A walk over the members of a type and of the structs in it. A struct is entered once.
+  * The next member of that type gets a copy of the fields that were found:
   *
-  * Copy the fields starting from the first field and repeat them for
-  * repeat_cnt times. The fields are repeated by adding the offset of each
-  * field with
-  *   (i + 1) * elem_size
-  * where i is the repeat index and elem_size is the size of an element.
+  *   struct in  { kptr p; };
+  *   struct out { struct in a; long x; struct in b[2]; };
+  *                enter 'in'           copy from a, twice
   */
- static int btf_repeat_fields(struct btf_field_info *info, int info_cnt,
- 			     u32 field_cnt, u32 repeat_cnt, u32 elem_size)
+ struct btf_field_walk {
+ 	struct btf_field_info *info;
+ 	u32 cnt;
+ 	u32 field_mask;
+ 	u32 seen_mask;
+ 	struct btf_field_scope {
+ 		const struct btf_type *t;
+ 		u32 off;	/* in the outer type */
+ 		u32 nelems;
+ 		u32 first;	/* its fields in 'info' */
+ 		u32 cnt;
+ 		u32 next;	/* member to look at */
+ 		u32 parent;
+ 	} *scopes;
+ 	u32 scope;		/* the current one */
+ 	struct bpf_index index;	/* address of the type -> scope */
+ };
+ 
+ /* An allocated object has 4096 bytes at most */
+ #define BTF_OBJ_FIELDS_MAX (SZ_4K / sizeof(u64))
+ 
+ static int btf_add_field(struct btf_field_walk *w, struct btf_field_info info)
  {
- 	u32 i, j, total_cnt, total_repeats;
- 	u32 cur;
- 
- 	/* Ensure not repeating fields that should not be repeated. */
- 	for (i = 0; i < field_cnt; i++) {
- 		switch (info[i].type) {
- 		case BPF_KPTR_UNREF:
- 		case BPF_KPTR_REF:
- 		case BPF_KPTR_PERCPU:
- 		case BPF_UPTR:
- 		case BPF_LIST_HEAD:
- 		case BPF_RB_ROOT:
- 			break;
- 		default:
- 			return -EINVAL;
- 		}
- 	}
- 
- 	if (check_add_overflow(repeat_cnt, 1, &total_repeats) ||
- 	    check_mul_overflow(field_cnt, total_repeats, &total_cnt) ||
- 	    total_cnt > (u32)info_cnt)
- 		return -E2BIG;
- 
- 	cur = field_cnt;
- 	for (i = 0; i < repeat_cnt; i++) {
- 		memcpy(&info[cur], &info[0], field_cnt * sizeof(info[0]));
- 		for (j = 0; j < field_cnt; j++)
- 			info[cur++].off += (i + 1) * elem_size;
- 	}
+ 	struct btf_field_info *last = w->cnt ? &w->info[w->cnt - 1] : NULL;
  
+ 	if (last && info.off < last->off + btf_field_type_size(last->type))
+ 		return -EEXIST;
+ 	if ((w->field_mask & BPF_GRAPH_NODE) && w->cnt == BTF_OBJ_FIELDS_MAX)
+ 		return -EFBIG;
+ 	if (bpf_must_abort())
+ 		return -EINTR;
+ 	if (!bpf_table_next(w->info, w->cnt))
+ 		return -ENOMEM;
+ 	w->info[w->cnt++] = info;
  	return 0;
  }
  
- static int btf_find_struct_field(const struct btf *btf,
- 				 const struct btf_type *t, u32 field_mask,
- 				 struct btf_field_info *info, int info_cnt,
- 				 u32 level, u32 *seen_mask);
- 
- /* Find special fields in the struct type of a field.
-  *
-  * This function is used to find fields of special types that is not a
-  * global variable or a direct field of a struct type. It also handles the
-  * repetition if it is the element type of an array.
-  */
- static int btf_find_nested_struct(const struct btf *btf, const struct btf_type *t,
- 				  u32 off, u32 nelems,
- 				  u32 field_mask, struct btf_field_info *info,
- 				  int info_cnt, u32 level, u32 *seen_mask)
+ /* Copy 'cnt' fields from 'first' on to 'nelems' elements. The first copy is 'by' bytes off. */
+ static int btf_repeat_fields(struct btf_field_walk *w, u32 first, u32 cnt, u32 by,
+ 			     u32 nelems, u32 elem_size, bool array)
  {
- 	int ret, err, i;
+ 	struct btf_field_info info;
+ 	u32 i, j;
+ 	int err;
  
- 	level++;
- 	if (level >= MAX_RESOLVE_DEPTH)
- 		return -E2BIG;
- 
- 	ret = btf_find_struct_field(btf, t, field_mask, info, info_cnt, level, seen_mask);
- 
- 	if (ret <= 0)
- 		return ret;
- 
- 	/* Shift the offsets of the nested struct fields to the offsets
- 	 * related to the container.
- 	 */
- 	for (i = 0; i < ret; i++)
- 		info[i].off += off;
- 
- 	if (nelems > 1) {
- 		err = btf_repeat_fields(info, info_cnt, ret, nelems - 1, t->size);
- 		if (err == 0)
- 			ret *= nelems;
- 		else
- 			ret = err;
+ 	for (i = 0; i < nelems && cnt; i++, by += elem_size) {
+ 		for (j = first; j < first + cnt; j++) {
+ 			info = w->info[j];
+ 			info.off += by;
+ 			if (array && !(info.type & (BPF_KPTR | BPF_UPTR | BPF_GRAPH_ROOT)))
+ 				return -EINVAL;
+ 			if (info.type & w->seen_mask)
+ 				return -E2BIG;
+ 			err = btf_add_field(w, info);
+ 			if (err)
+ 				return err;
+ 		}
  	}
+ 	return 0;
+ }
  
- 	return ret;
+ static int btf_enter_struct(struct btf_field_walk *w, const struct btf_type *t, u32 off, u32 nelems)
+ {
+ 	int i = bpf_index_find(&w->index, (unsigned long)t);
+ 	struct btf_field_scope *s;
+ 
+ 	if (i >= 0) {
+ 		s = &w->scopes[i];
+ 		return btf_repeat_fields(w, s->first, s->cnt, off - s->off, nelems, t->size,
+ 					 nelems > 1);
+ 	}
+ 	i = w->index.cnt;
+ 	s = bpf_table_next(w->scopes, i);
+ 	if (!s || bpf_index_add(&w->index, (unsigned long)t, i))
+ 		return -ENOMEM;
+ 	*s = (struct btf_field_scope){
+ 		.t = t, .off = off, .nelems = nelems, .first = w->cnt, .parent = w->scope,
+ 	};
+ 	w->scope = i;
+ 	return 0;
  }
  
  static int btf_find_field_one(const struct btf *btf,
  			      const struct btf_type *var,
  			      const struct btf_type *var_type,
  			      int var_idx,
- 			      u32 off, u32 expected_size,
- 			      u32 field_mask, u32 *seen_mask,
- 			      struct btf_field_info *info, int info_cnt,
- 			      u32 level)
+ 			      u32 base, u32 off, u32 expected_size,
+ 			      struct btf_field_walk *w)
  {
  	int ret, align, sz, field_type;
- 	struct btf_field_info tmp;
  	const struct btf_array *array;
+ 	struct btf_field_info info;
  	u32 i, nelems = 1;
  
  	/* Walk into array types to find the element type and the number of
@@@ -3889,15 -3930,13 +3930,13 @@@
  		return 0;
  
  	field_type = btf_get_field_type(btf, var_type,
- 					field_mask, seen_mask, &align, &sz);
+ 					w->field_mask, &w->seen_mask, &align, &sz);
  	/* Look into variables of struct types */
  	if (!field_type && __btf_type_is_struct(var_type)) {
  		sz = var_type->size;
  		if (expected_size && expected_size != sz * nelems)
  			return 0;
- 		ret = btf_find_nested_struct(btf, var_type, off, nelems, field_mask,
- 					     &info[0], info_cnt, level, seen_mask);
- 		return ret;
+ 		return btf_enter_struct(w, var_type, base + off, nelems);
  	}
  
  	if (field_type == 0)
@@@ -3909,6 -3948,7 +3948,7 @@@
  		return 0;
  	if (off % align)
  		return 0;
+ 	off += base;
  
  	switch (field_type) {
  	case BPF_SPIN_LOCK:
@@@ -3920,8 -3960,7 +3960,7 @@@
  	case BPF_REFCOUNT:
  	case BPF_TASK_WORK:
  	case BPF_RCU_HEAD:
- 		ret = btf_find_struct(btf, var_type, off, sz, field_type,
- 				      info_cnt ? &info[0] : &tmp);
+ 		ret = btf_find_struct(btf, var_type, off, sz, field_type, &info);
  		if (ret < 0)
  			return ret;
  		break;
@@@ -3929,17 -3968,14 +3968,14 @@@
  	case BPF_KPTR_REF:
  	case BPF_KPTR_PERCPU:
  	case BPF_UPTR:
- 		ret = btf_find_kptr(btf, var_type, off, sz,
- 				    info_cnt ? &info[0] : &tmp, field_mask);
+ 		ret = btf_find_kptr(btf, var_type, off, sz, &info, w->field_mask);
  		if (ret < 0)
  			return ret;
  		break;
  	case BPF_LIST_HEAD:
  	case BPF_RB_ROOT:
  		ret = btf_find_graph_root(btf, var, var_type,
- 					  var_idx, off, sz,
- 					  info_cnt ? &info[0] : &tmp,
- 					  field_type);
+ 					  var_idx, off, sz, &info, field_type);
  		if (ret < 0)
  			return ret;
  		break;
@@@ -3949,81 -3985,51 +3985,51 @@@
  
  	if (ret == BTF_FIELD_IGNORE)
  		return 0;
- 	if (!info_cnt)
- 		return -E2BIG;
- 	if (nelems > 1) {
- 		ret = btf_repeat_fields(info, info_cnt, 1, nelems - 1, sz);
- 		if (ret < 0)
- 			return ret;
- 	}
- 	return nelems;
- }
- 
- static int btf_find_struct_field(const struct btf *btf,
- 				 const struct btf_type *t, u32 field_mask,
- 				 struct btf_field_info *info, int info_cnt,
- 				 u32 level, u32 *seen_mask)
- {
- 	int ret, idx = 0;
- 	const struct btf_member *member;
- 	u32 i, off;
- 
- 	for_each_member(i, t, member) {
- 		const struct btf_type *member_type = btf_type_by_id(btf,
- 								    member->type);
- 
- 		off = __btf_member_bit_offset(t, member);
- 		if (off % 8)
- 			/* valid C code cannot generate such BTF */
- 			return -EINVAL;
- 		off /= 8;
- 
- 		ret = btf_find_field_one(btf, t, member_type, i,
- 					 off, 0,
- 					 field_mask, seen_mask,
- 					 &info[idx], info_cnt - idx, level);
- 		if (ret < 0)
- 			return ret;
- 		idx += ret;
- 	}
- 	return idx;
- }
- 
- static int btf_find_datasec_var(const struct btf *btf, const struct btf_type *t,
- 				u32 field_mask, struct btf_field_info *info,
- 				int info_cnt, u32 level, u32 *seen_mask)
- {
- 	int ret, idx = 0;
- 	const struct btf_var_secinfo *vsi;
- 	u32 i, off;
- 
- 	for_each_vsi(i, t, vsi) {
- 		const struct btf_type *var = btf_type_by_id(btf, vsi->type);
- 		const struct btf_type *var_type = btf_type_by_id(btf, var->type);
- 
- 		off = vsi->offset;
- 		ret = btf_find_field_one(btf, var, var_type, -1, off, vsi->size,
- 					 field_mask, seen_mask,
- 					 &info[idx], info_cnt - idx,
- 					 level);
- 		if (ret < 0)
- 			return ret;
- 		idx += ret;
- 	}
- 	return idx;
+ 	return btf_add_field(w, info) ?:
+ 	       btf_repeat_fields(w, w->cnt - 1, 1, sz, nelems - 1, sz, true);
  }
  
  static int btf_find_field(const struct btf *btf, const struct btf_type *t,
- 			  u32 field_mask, struct btf_field_info *info,
- 			  int info_cnt)
+ 			  struct btf_field_walk *w)
  {
- 	u32 seen_mask = 0;
+ 	const struct btf_var_secinfo *vsi;
+ 	const struct btf_member *member;
+ 	struct btf_field_scope *s;
+ 	const struct btf_type *var;
+ 	u32 i, off;
+ 	int err;
  
- 	if (__btf_type_is_struct(t))
- 		return btf_find_struct_field(btf, t, field_mask, info, info_cnt, 0, &seen_mask);
- 	else if (btf_type_is_datasec(t))
- 		return btf_find_datasec_var(btf, t, field_mask, info, info_cnt, 0, &seen_mask);
- 	return -EINVAL;
+ 	if (!__btf_type_is_struct(t) && !btf_type_is_datasec(t))
+ 		return -EINVAL;
+ 
+ 	for (err = btf_enter_struct(w, t, 0, 1); !err;) {
+ 		if (bpf_must_abort())
+ 			return -EINTR;
+ 		s = &w->scopes[w->scope];
+ 		i = s->next++;
+ 		if (i == btf_type_vlen(s->t)) {
+ 			if (!w->scope)
+ 				break;
+ 			s->cnt = w->cnt - s->first;
+ 			w->scope = s->parent;
+ 			err = btf_repeat_fields(w, s->first, s->cnt, s->t->size, s->nelems - 1,
+ 						s->t->size, true);
+ 		} else if (btf_type_is_datasec(s->t)) {
+ 			vsi = btf_type_var_secinfo(s->t) + i;
+ 			var = btf_type_by_id(btf, vsi->type);
+ 			err = btf_find_field_one(btf, var, btf_type_by_id(btf, var->type), -1,
+ 						 0, vsi->offset, vsi->size, w);
+ 		} else {
+ 			member = btf_type_member(s->t) + i;
+ 			off = __btf_member_bit_offset(s->t, member);
+ 			if (off % 8)
+ 				/* valid C code cannot generate such BTF */
+ 				return -EINVAL;
+ 			err = btf_find_field_one(btf, s->t, btf_type_by_id(btf, member->type), i,
+ 						 s->off, off / 8, 0, w);
+ 		}
+ 	}
+ 	return err;
  }
  
  /* Callers have to ensure the life cycle of btf if it is program BTF */
@@@ -4134,6 -4140,8 +4140,8 @@@ static int btf_parse_graph_root(const s
  	 * verify its type.
  	 */
  	for_each_member(i, t, member) {
+ 		if (bpf_must_abort())
+ 			return -EINTR;
  		if (strcmp(info->graph_root.node_name,
  			   __btf_name_by_offset(btf, member->name_off)))
  			continue;
@@@ -4175,37 -4183,29 +4183,29 @@@ static int btf_parse_rb_root(const stru
  					    __alignof__(struct bpf_rb_node));
  }
  
- static int btf_field_cmp(const void *_a, const void *_b, const void *priv)
- {
- 	const struct btf_field *a = (const struct btf_field *)_a;
- 	const struct btf_field *b = (const struct btf_field *)_b;
- 
- 	if (a->offset < b->offset)
- 		return -1;
- 	else if (a->offset > b->offset)
- 		return 1;
- 	return 0;
- }
- 
  struct btf_record *btf_parse_fields(const struct btf *btf, const struct btf_type *t,
  				    u32 field_mask, u32 value_size)
  {
- 	struct btf_field_info info_arr[BTF_FIELDS_MAX];
- 	u32 next_off = 0, field_type_size;
+ 	struct btf_field_info *info_arr __free(kvfree) = NULL;
+ 	struct btf_field_walk w = { .field_mask = field_mask };
+ 	u32 field_type_size;
  	struct btf_record *rec;
  	int ret, i, cnt;
  
- 	ret = btf_find_field(btf, t, field_mask, info_arr, ARRAY_SIZE(info_arr));
+ 	ret = btf_find_field(btf, t, &w);
+ 	kvfree(w.scopes);
+ 	kvfree(w.index.slots);
+ 	info_arr = w.info;
  	if (ret < 0)
  		return ERR_PTR(ret);
- 	if (!ret)
+ 	if (!w.cnt)
  		return NULL;
  
- 	cnt = ret;
+ 	cnt = w.cnt;
  	/* This needs to be kzalloc to zero out padding and unused fields, see
  	 * comment in btf_record_equal.
  	 */
- 	rec = kzalloc_flex(*rec, fields, cnt, GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
+ 	rec = kvzalloc_flex(*rec, fields, cnt, BPF_VERIFIER_GFP);
  	if (!rec)
  		return ERR_PTR(-ENOMEM);
  
@@@ -4223,11 -4223,10 +4223,10 @@@
  			ret = -EFAULT;
  			goto end;
  		}
- 		if (info_arr[i].off < next_off) {
- 			ret = -EEXIST;
+ 		if (bpf_must_abort()) {
+ 			ret = -EINTR;
  			goto end;
  		}
- 		next_off = info_arr[i].off + field_type_size;
  
  		rec->field_mask |= info_arr[i].type;
  		rec->fields[i].offset = info_arr[i].off;
@@@ -4316,9 -4315,6 +4315,6 @@@
  		goto end;
  	}
  
- 	sort_r(rec->fields, rec->cnt, sizeof(struct btf_field), btf_field_cmp,
- 	       NULL, rec);
- 
  	return rec;
  end:
  	btf_record_free(rec);
@@@ -4624,7 -4620,7 +4620,7 @@@ static s32 btf_enum_check_meta(struct b
  
  	/* enum type either no name or a valid one */
  	if (t->name_off &&
- 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
+ 	    !btf_name_valid(env, t->name_off)) {
  		btf_verifier_log_type(env, t, "Invalid name");
  		return -EINVAL;
  	}
@@@ -4640,7 -4636,7 +4636,7 @@@
  
  		/* enum member must have a valid name */
  		if (!enums[i].name_off ||
- 		    !btf_name_valid_identifier(btf, enums[i].name_off)) {
+ 		    !btf_name_valid(env, enums[i].name_off)) {
  			btf_verifier_log_type(env, t, "Invalid name");
  			return -EINVAL;
  		}
@@@ -4732,7 -4728,7 +4728,7 @@@ static s32 btf_enum64_check_meta(struc
  
  	/* enum type either no name or a valid one */
  	if (t->name_off &&
- 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
+ 	    !btf_name_valid(env, t->name_off)) {
  		btf_verifier_log_type(env, t, "Invalid name");
  		return -EINVAL;
  	}
@@@ -4748,7 -4744,7 +4744,7 @@@
  
  		/* enum member must have a valid name */
  		if (!enums[i].name_off ||
- 		    !btf_name_valid_identifier(btf, enums[i].name_off)) {
+ 		    !btf_name_valid(env, enums[i].name_off)) {
  			btf_verifier_log_type(env, t, "Invalid name");
  			return -EINVAL;
  		}
@@@ -5038,7 -5034,7 +5034,7 @@@ static s32 btf_locsec_check_meta(struc
  	}
  
  	if (!t->name_off ||
- 	    !btf_name_valid_section(env->btf, t->name_off)) {
+ 	    !btf_name_valid(env, t->name_off)) {
  		btf_verifier_log_type(env, t, "Invalid name");
  		return -EINVAL;
  	}
@@@ -5230,7 -5226,7 +5226,7 @@@ static s32 btf_func_check_meta(struct b
  			       u32 meta_left)
  {
  	if (!t->name_off ||
- 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
+ 	    !btf_name_valid(env, t->name_off)) {
  		btf_verifier_log_type(env, t, "Invalid name");
  		return -EINVAL;
  	}
@@@ -5299,7 -5295,7 +5295,7 @@@ static s32 btf_var_check_meta(struct bt
  	}
  
  	if (!t->name_off ||
- 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
+ 	    !btf_name_valid(env, t->name_off)) {
  		btf_verifier_log_type(env, t, "Invalid name");
  		return -EINVAL;
  	}
@@@ -5365,7 -5361,7 +5361,7 @@@ static s32 btf_datasec_check_meta(struc
  	}
  
  	if (!t->name_off ||
- 	    !btf_name_valid_section(env->btf, t->name_off)) {
+ 	    !btf_name_valid(env, t->name_off)) {
  		btf_verifier_log_type(env, t, "Invalid name");
  		return -EINVAL;
  	}
@@@ -5752,7 -5748,7 +5748,7 @@@ static int btf_func_proto_check(struct 
  
  		if (args[i].name_off &&
  		    (!btf_name_offset_valid(btf, args[i].name_off) ||
- 		     !btf_name_valid_identifier(btf, args[i].name_off))) {
+ 		     !btf_name_valid(env, args[i].name_off))) {
  			btf_verifier_log_type(env, t,
  					      "Invalid arg#%u", i + 1);
  			return -EINVAL;
@@@ -5985,6 -5981,22 +5981,22 @@@ static int btf_check_all_types(struct b
  		return err;
  
  	env->phase++;
+ 	/*
+ 	 * Structs and arrays go first. A walk from a pointer stops at them and hides this loop:
+ 	 *   ptr -> typedef -> array -+
+ 	 *             ^--------------+
+ 	 */
+ 	for (i = btf->base_btf ? 0 : 1; i < btf->nr_types; i++) {
+ 		type_id = btf->start_id + i;
+ 		t = btf_type_by_id(btf, type_id);
+ 
+ 		if ((btf_type_is_struct(t) || btf_type_is_array(t)) &&
+ 		    !env_type_is_resolved(env, type_id)) {
+ 			err = btf_resolve(env, t, type_id);
+ 			if (err)
+ 				return err;
+ 		}
+ 	}
  	for (i = btf->base_btf ? 0 : 1; i < btf->nr_types; i++) {
  		type_id = btf->start_id + i;
  		t = btf_type_by_id(btf, type_id);
@@@ -6035,6 -6047,7 +6047,7 @@@ static int btf_parse_str_sec(struct btf
  	const struct btf_header *hdr;
  	struct btf *btf = env->btf;
  	const char *start, *end;
+ 	u32 i, len = 0;
  
  	hdr = &btf->hdr;
  	start = btf->nohdr_data + hdr->str_off;
@@@ -6059,6 -6072,21 +6072,21 @@@
  		return -EINVAL;
  	}
  
+ 	/* many names can share one long string: look at each byte once */
+ 	kvfree(env->names);
+ 	env->names = kvcalloc(BITS_TO_LONGS(hdr->str_len), sizeof(long),
+ 			      GFP_KERNEL | __GFP_NOWARN);
+ 	if (!env->names)
+ 		return -ENOMEM;
+ 	for (i = hdr->str_len; i--;) {
+ 		if (!start[i])
+ 			len = 0;
+ 		else if (!isprint(start[i]))
+ 			len = BTF_MAX_NAME_LEN;
+ 		else if (len++ < BTF_MAX_NAME_LEN)
+ 			__set_bit(i, env->names);
+ 	}
+ 
  	return 0;
  }
  
@@@ -6290,6 -6318,10 +6318,10 @@@ btf_parse_struct_metas(struct bpf_verif
  			ret = -EINVAL;
  			goto free_aof;
  		}
+ 		if (bpf_must_abort()) {
+ 			ret = -EINTR;
+ 			goto free_aof;
+ 		}
  
  		ret = btf_find_kptr(btf, t, 0, 0, &tmp, BPF_KPTR);
  		if (ret != BTF_FIELD_FOUND)
@@@ -6347,6 -6379,9 +6379,9 @@@
  		record = btf_parse_fields(btf, t, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK | BPF_LIST_HEAD | BPF_LIST_NODE |
  						  BPF_RB_ROOT | BPF_RB_NODE | BPF_REFCOUNT |
  						  BPF_KPTR, t->size);
+ 		/* It cannot be allocated. A map has its own record. */
+ 		if (record == ERR_PTR(-EFBIG))
+ 			continue;
  		/* The record cannot be unset, treat it as an error if so */
  		if (IS_ERR_OR_NULL(record)) {
  			ret = PTR_ERR_OR_ZERO(record) ?: -EFAULT;
@@@ -6473,7 -6508,7 +6508,7 @@@ static struct btf *btf_parse(const unio
  	if (err)
  		goto errout;
  
- 	err = btf_parse_type_sec(env);
+ 	err = btf_parse_type_sec(env) ?: btf_link_decl_tags(btf);
  	if (err)
  		goto errout;
  
@@@ -8091,20 -8126,11 +8126,11 @@@ int btf_struct_access(struct bpf_verifi
  		if (!meta)
  			break;
  		rec = meta->record;
- 		for (i = 0; i < rec->cnt; i++) {
- 			struct btf_field *field = &rec->fields[i];
- 			u32 offset = field->offset;
- 			/* An access at 'lo' or above ends after the start of the field. */
- 			s64 lo = max(min_off, (s64)offset - size + 1);
- 
- 			/* Round up to min_off + k * step. The step is never 0. */
- 			lo += imod(min_off - lo, reg->step);
- 			if (lo <= max_off && lo < offset + field->size) {
- 				bpf_log(log,
- 					"direct access to %s is disallowed\n",
- 					btf_field_type_name(field->type));
- 				return -EACCES;
- 			}
+ 		i = btf_record_first_field(rec, off);
+ 		if (i < rec->cnt && rec->fields[i].offset < off + size) {
+ 			bpf_log(log, "direct access to %s is disallowed\n",
+ 				btf_field_type_name(rec->fields[i].type));
+ 			return -EACCES;
  		}
  		break;
  	}
@@@ -8636,8 -8662,8 +8662,8 @@@ static int btf_scan_decl_tags(struct bp
  			      const struct btf_type *fn_t,
  			      u32 arg_idx, bool is_global, u32 *tags)
  {
- 	int id = btf_named_start_id(btf, false) - 1;
  	const char tag_key[] = "arg:";
+ 	int id = 0;
  	static const struct {
  		const char *tag_value;
  		enum btf_arg_tag arg_tag;
@@@ -8747,8 -8773,7 +8773,7 @@@ static int btf_validate_return_type(str
  }
  
  static int btf_check_arg_slots(struct bpf_verifier_log *log, const char *tname,
- 			       bool is_global, u32 slot_cnt,
- 			       struct bpf_subprog_info *sub)
+ 			       bool is_global, u32 slot_cnt)
  {
  	if (slot_cnt <= MAX_BPF_FUNC_REG_ARGS)
  		return 0;
@@@ -8760,12 -8785,7 +8785,7 @@@
  			tname, slot_cnt, MAX_BPF_FUNC_REG_ARGS);
  		return -EINVAL;
  	}
- 	if (!bpf_jit_supports_stack_args()) {
- 		bpf_log(log, "JIT does not support function %s() with %d argument slots\n",
- 			tname, slot_cnt);
- 		return -EFAULT;
- 	}
- 	sub->stack_arg_cnt = slot_cnt - MAX_BPF_FUNC_REG_ARGS;
+ 	/* The code of a static function tells which stack arguments it takes */
  	return 0;
  }
  
@@@ -8832,13 -8852,15 +8852,15 @@@ int btf_prepare_func_args(struct bpf_ve
  	}
  	args = (const struct btf_param *)(t + 1);
  	nargs = btf_type_vlen(t);
- 	sub->arg_slot_cnt = nargs;
+ 	sub->arg_slot_cnt = min_t(u32, nargs, MAX_BPF_FUNC_ARGS);
  	if (nargs > MAX_BPF_FUNC_ARGS) {
+ 		if (!is_global) /* not fatal for static funcs */
+ 			return -EINVAL;
  		bpf_log(log, "kernel supports at most %d parameters, function %s has %d\n",
  			MAX_BPF_FUNC_ARGS, tname, nargs);
  		return -EFAULT;
  	}
- 	err = btf_check_arg_slots(log, tname, is_global, nargs, sub);
+ 	err = btf_check_arg_slots(log, tname, is_global, nargs);
  	if (err)
  		return err;
  
@@@ -9027,7 -9049,7 +9049,7 @@@ skip_pointer
  		return -EINVAL;
  	}
  
- 	err = btf_check_arg_slots(log, tname, is_global, slots_used, sub);
+ 	err = btf_check_arg_slots(log, tname, is_global, slots_used);
  	if (err)
  		return err;
  	sub->arg_slot_cnt = slots_used;

[-- Attachment #2: signature.asc --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2026-11-17 21:39 Mark Brown
  0 siblings, 0 replies; 69+ messages in thread
From: Mark Brown @ 2026-11-17 21:39 UTC (permalink / raw)
  To: Kumar Kartikeya Dwivedi, Eduard Zingerman, Daniel Borkmann,
	Alexei Starovoitov, Andrii Nakryiko, bpf, Networking
  Cc: Breno Leitao, Linux Kernel Mailing List, Linux Next Mailing List

[-- Attachment #1: Type: text/plain, Size: 1583 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  kernel/bpf/verifier.c

between commit:

  7f1e33230b7c7 ("bpf: Report RCU-tasks quiescent states in do_check()")

from the bpf tree and commit:

  8fd58560b71e9 ("bpf: Verify static subprogs on their own")

and it appears some other commit that removes the reset of current
history that I didn't spot from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

diff --cc kernel/bpf/verifier.c
index 9b228ffbe3fe9,1a8e5a108a681..0000000000000
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@@ -20626,13 -21560,14 +21562,16 @@@ static int do_check_block(struct bpf_ve
  		struct bpf_insn_aux_data *insn_aux;
  		int err;
  
- 		if (signal_pending(current))
- 			return -EAGAIN;
+ 		if (bpf_must_abort())
+ 			return -EINTR;
  
 +		cond_resched_tasks_rcu_qs();
 +
- 		/* reset current history entry on each new instruction */
- 		env->cur_hist_ent = NULL;
+ 		/* no insn makes as many ids as there are from here to BPF_INHERITED_ID */
+ 		if (env->id_gen >= BPF_MAX_ID) {
+ 			verbose(env, "too many ids\n");
+ 			return -E2BIG;
+ 		}
  
  		env->prev_insn_idx = prev_insn_idx;
  		if (env->insn_idx >= insn_cnt) {

[-- Attachment #2: signature.asc --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2026-11-17 21:36 Mark Brown
@ 2026-11-18 15:47 ` J4f J4f
  2026-11-19  1:17   ` Alexei Starovoitov
  0 siblings, 1 reply; 69+ messages in thread
From: J4f J4f @ 2026-11-18 15:47 UTC (permalink / raw)
  To: Mark Brown
  Cc: Kumar Kartikeya Dwivedi, Eduard Zingerman, Daniel Borkmann,
	Alexei Starovoitov, Andrii Nakryiko, bpf, Networking,
	Linux Kernel Mailing List, Linux Next Mailing List

On Wed, 18 Nov 2026 at 05:36, Mark Brown <broonie@kernel.org> wrote:
>
> Hi all,
>
> Today's linux-next merge of the bpf-next tree got a conflict in:
>
>   kernel/bpf/btf.c
>
> between commit:
>
>   b7cc45994c3f9 ("bpf: Check variable-offset accesses against special fields")
>
> from the bpf tree and commit:
>
>   ca4395aade31a ("bpf: Walk each type once when looking for special fields")
>
> from the bpf-next tree.  I'm not confident of this merge, it discards
> the bpf commit on the basis that it looks like there is some new
> handling of special fields in the bpf-next tree but I'm not sure that
> overlaps with the fix.
>
> I fixed it up (see below) and can carry the fix as necessary. This
> is now fixed as far as linux-next is concerned, but any non trivial
> conflicts should be mentioned to your upstream maintainer when your tree
> is submitted for merging.  You may also want to consider cooperating
> with the maintainer of the conflicting tree to minimise any particularly
> complex conflicts.
>
Hi Mark,

Thanks for the report.

I reproduced this on bpf-next master: the rewrite does not cover the fix,
the check in btf_struct_access() now only looks at min_off again. I will
send a v4 rebased on top of the bpf-next series shortly.

Thanks,
Shihuang
> diff --combined kernel/bpf/btf.c
> index 49fcd32d418a9,e95ca39f990c6..0000000000000
> --- a/kernel/bpf/btf.c
> +++ b/kernel/bpf/btf.c
> @@@ -281,6 -281,7 +281,7 @@@ struct btf
>         char name[MODULE_NAME_LEN];
>         bool kernel_btf;
>         __u32 *base_id_map; /* map from distilled base BTF -> vmlinux BTF ids */
> +       u32 *next_tag; /* see btf_link_decl_tags() */
>   };
>
>   enum verifier_phase {
> @@@ -308,6 -309,9 +309,9 @@@ enum resolve_mode
>                                          */
>   };
>
> + /* It bounds the time of the loops that compare or print names */
> + #define BTF_MAX_NAME_LEN 4096
> +
>   #define MAX_RESOLVE_DEPTH 32
>
>   struct btf_sec_info {
> @@@ -319,6 -323,7 +323,7 @@@ struct btf_verifier_env
>         struct btf *btf;
>         u8 *visit_states;
>         struct resolve_vertex stack[MAX_RESOLVE_DEPTH];
> +       unsigned long *names;   /* offsets of the strings that can be names */
>         struct bpf_verifier_log log;
>         u32 log_type_id;
>         u32 top_stack;
> @@@ -684,10 -689,15 +689,15 @@@ s32 btf_find_by_name_kind(const struct
>                                 return id;
>                 }
>         } else {
> +               /* only the tags in BTF of a program have long names */
> +               bool slow = !btf->kernel_btf && strlen(name) > KSYM_NAME_LEN;
> +
>                 for (id = btf_start_id(btf); id < total; id++) {
>                         t = btf_type_by_id(btf, id);
>                         if (BTF_INFO_KIND(t->info) != kind)
>                                 continue;
> +                       if (slow && bpf_must_abort())
> +                               return -EINTR;
>                         tname = btf_name_by_offset(btf, t->name_off);
>                         if (strcmp(tname, name) == 0)
>                                 return id;
> @@@ -914,49 -924,6 +924,6 @@@ const char *btf_str_by_offset(const str
>         return NULL;
>   }
>
> - /* Names in BTF of Rust are not C identifiers. Allow any printable character */
> - static bool btf_name_valid_identifier(const struct btf *btf, u32 offset)
> - {
> -       /* offset must be valid */
> -       const char *src = btf_str_by_offset(btf, offset);
> -       const char *src_limit;
> -
> -       if (!isprint(*src))
> -               return false;
> -
> -       /* set a limit on identifier length */
> -       src_limit = src + KSYM_NAME_LEN;
> -       src++;
> -       while (*src && src < src_limit) {
> -               if (!isprint(*src))
> -                       return false;
> -               src++;
> -       }
> -
> -       return !*src;
> - }
> -
> - /* Allow any printable character in DATASEC names */
> - static bool btf_name_valid_section(const struct btf *btf, u32 offset)
> - {
> -       /* offset must be valid */
> -       const char *src = btf_str_by_offset(btf, offset);
> -       const char *src_limit;
> -
> -       if (!*src)
> -               return false;
> -
> -       /* set a limit on identifier length */
> -       src_limit = src + KSYM_NAME_LEN;
> -       while (*src && src < src_limit) {
> -               if (!isprint(*src))
> -                       return false;
> -               src++;
> -       }
> -
> -       return !*src;
> - }
> -
>   static const char *__btf_name_by_offset(const struct btf *btf, u32 offset)
>   {
>         const char *name;
> @@@ -1907,6 -1874,7 +1874,7 @@@ static void btf_free(struct btf *btf
>         if (!btf_is_vmlinux(btf))
>                 kvfree(btf->data);
>         kvfree(btf->base_id_map);
> +       kvfree(btf->next_tag);
>         kfree(btf);
>   }
>
> @@@ -1991,9 -1959,21 +1959,21 @@@ nomem
>   static void btf_verifier_env_free(struct btf_verifier_env *env)
>   {
>         kvfree(env->visit_states);
> +       kvfree(env->names);
>         kfree(env);
>   }
>
> + /* Names in BTF of Rust are not C identifiers. Allow any printable character */
> + static bool btf_name_valid(const struct btf_verifier_env *env, u32 offset)
> + {
> +       const struct btf *btf = env->btf;
> +
> +       /* offset must be valid */
> +       if (offset < btf->start_str_off)
> +               return *btf_str_by_offset(btf, offset);
> +       return test_bit(offset - btf->start_str_off, env->names);
> + }
> +
>   static bool env_type_is_resolve_sink(const struct btf_verifier_env *env,
>                                      const struct btf_type *next_type)
>   {
> @@@ -2766,7 -2746,7 +2746,7 @@@ static int btf_ref_type_check_meta(stru
>          */
>         if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPEDEF) {
>                 if (!t->name_off ||
> -                   !btf_name_valid_identifier(env->btf, t->name_off)) {
> +                   !btf_name_valid(env, t->name_off)) {
>                         btf_verifier_log_type(env, t, "Invalid name");
>                         return -EINVAL;
>                 }
> @@@ -3028,7 -3008,7 +3008,7 @@@ static s32 btf_fwd_check_meta(struct bt
>
>         /* fwd type must have a valid name */
>         if (!t->name_off ||
> -           !btf_name_valid_identifier(env->btf, t->name_off)) {
> +           !btf_name_valid(env, t->name_off)) {
>                 btf_verifier_log_type(env, t, "Invalid name");
>                 return -EINVAL;
>         }
> @@@ -3351,7 -3331,7 +3331,7 @@@ static s32 btf_struct_check_meta(struc
>
>         /* struct type either no name or a valid one */
>         if (t->name_off &&
> -           !btf_name_valid_identifier(env->btf, t->name_off)) {
> +           !btf_name_valid(env, t->name_off)) {
>                 btf_verifier_log_type(env, t, "Invalid name");
>                 return -EINVAL;
>         }
> @@@ -3369,7 -3349,7 +3349,7 @@@
>
>                 /* struct member either no name or a valid one */
>                 if (member->name_off &&
> -                   !btf_name_valid_identifier(btf, member->name_off)) {
> +                   !btf_name_valid(env, member->name_off)) {
>                         btf_verifier_log_member(env, t, member, "Invalid name");
>                         return -EINVAL;
>                 }
> @@@ -3636,13 -3616,45 +3616,45 @@@ static int btf_find_kptr(const struct b
>         return BTF_FIELD_FOUND;
>   }
>
> + /* For BTF of programs: next_tag[type] -> its first tag, next_tag[tag] -> its next tag, ... 0 */
> + static int btf_link_decl_tags(struct btf *btf)
> + {
> +       u32 i;
> +
> +       btf->next_tag = kvcalloc(btf->nr_types, sizeof(u32), GFP_KERNEL | __GFP_NOWARN);
> +       if (!btf->next_tag)
> +               return -ENOMEM;
> +       for (i = btf->nr_types; --i;) {
> +               if (!btf_type_is_decl_tag(btf->types[i]))
> +                       continue;
> +               btf->next_tag[i] = btf->next_tag[btf->types[i]->type];
> +               btf->next_tag[btf->types[i]->type] = i;
> +       }
> +       return 0;
> + }
> +
> + static int btf_type_ptr_cmp(const void *a, const void *b)
> + {
> +       return cmp_int(*(void **)a, *(void **)b);
> + }
> +
> + /* last_id is 0 for the first tag */
>   int btf_find_next_decl_tag(const struct btf *btf, const struct btf_type *pt,
>                            int comp_idx, const char *tag_key, int last_id)
>   {
> +       int i = last_id ?: btf_named_start_id(btf, false) - 1, n = btf_nr_types(btf);
>         int len = strlen(tag_key);
> -       int i, n;
> +       struct btf_type **p;
>
> -       for (i = last_id + 1, n = btf_nr_types(btf); i < n; i++) {
> +       if (btf->next_tag && !last_id) {
> +               /* the types are in the order of their ids in btf->data */
> +               p = bsearch(&pt, btf->types + 1, n - 1, sizeof(*p), btf_type_ptr_cmp);
> +               if (!p)
> +                       return -ENOENT;
> +               i = p - btf->types;
> +       }
> +
> +       while ((i = btf->next_tag ? btf->next_tag[i] ?: n : i + 1) < n) {
>                 const struct btf_type *t = btf_type_by_id(btf, i);
>
>                 if (!btf_type_is_decl_tag(t))
> @@@ -3665,8 -3677,7 +3677,7 @@@ const char *btf_find_decl_tag_value(con
>         const struct btf_type *t;
>         int len, id;
>
> -       id = btf_find_next_decl_tag(btf, pt, comp_idx, tag_key,
> -                                   btf_named_start_id(btf, false) - 1);
> +       id = btf_find_next_decl_tag(btf, pt, comp_idx, tag_key, 0);
>         if (id < 0)
>                 return ERR_PTR(id);
>
> @@@ -3682,6 -3693,36 +3693,36 @@@
>         return value;
>   }
>
> + /*
> +  * The value of the decl tag "<tag_key><value>" on a function of the kernel or of
> +  * a module. The build sorts their BTF by name: the tags with one key are
> +  * neighbours, and so are those with one value.
> +  *
> +  * Only the own types of btf are searched, not its base. With the BTF of a module
> +  * func_id can be a FUNC of vmlinux: it stands for the function of that name in the
> +  * module. What the build found in the code of vmlinux is not true for it.
> +  */
> + const char *btf_find_func_tag_value(const struct btf *btf, u32 func_id, const char *tag_key)
> + {
> +       int id, n = btf_nr_types(btf), len = strlen(tag_key);
> +       const char *name = NULL;
> +       u32 name_off = 0;
> +
> +       for (id = btf_find_by_name_kind_bsearch(btf, tag_key); id < n; id++) {
> +               const struct btf_type *t = btf_type_by_id(btf, id);
> +
> +               if (t->name_off != name_off) {
> +                       name_off = t->name_off;
> +                       name = btf_name_by_offset(btf, name_off);
> +                       if (strncmp(name, tag_key, len))
> +                               break;
> +               }
> +               if (t->type == func_id && btf_type_is_decl_tag(t))
> +                       return name + len;
> +       }
> +       return NULL;
> + }
> +
>   static int
>   btf_find_graph_root(const struct btf *btf, const struct btf_type *pt,
>                     const struct btf_type *t, int comp_idx, u32 off,
> @@@ -3773,106 -3814,106 +3814,106 @@@ end
>         return type;
>   }
>
> - /* Repeat a number of fields for a specified number of times.
> + /*
> +  * A walk over the members of a type and of the structs in it. A struct is entered once.
> +  * The next member of that type gets a copy of the fields that were found:
>    *
> -  * Copy the fields starting from the first field and repeat them for
> -  * repeat_cnt times. The fields are repeated by adding the offset of each
> -  * field with
> -  *   (i + 1) * elem_size
> -  * where i is the repeat index and elem_size is the size of an element.
> +  *   struct in  { kptr p; };
> +  *   struct out { struct in a; long x; struct in b[2]; };
> +  *                enter 'in'           copy from a, twice
>    */
> - static int btf_repeat_fields(struct btf_field_info *info, int info_cnt,
> -                            u32 field_cnt, u32 repeat_cnt, u32 elem_size)
> + struct btf_field_walk {
> +       struct btf_field_info *info;
> +       u32 cnt;
> +       u32 field_mask;
> +       u32 seen_mask;
> +       struct btf_field_scope {
> +               const struct btf_type *t;
> +               u32 off;        /* in the outer type */
> +               u32 nelems;
> +               u32 first;      /* its fields in 'info' */
> +               u32 cnt;
> +               u32 next;       /* member to look at */
> +               u32 parent;
> +       } *scopes;
> +       u32 scope;              /* the current one */
> +       struct bpf_index index; /* address of the type -> scope */
> + };
> +
> + /* An allocated object has 4096 bytes at most */
> + #define BTF_OBJ_FIELDS_MAX (SZ_4K / sizeof(u64))
> +
> + static int btf_add_field(struct btf_field_walk *w, struct btf_field_info info)
>   {
> -       u32 i, j, total_cnt, total_repeats;
> -       u32 cur;
> -
> -       /* Ensure not repeating fields that should not be repeated. */
> -       for (i = 0; i < field_cnt; i++) {
> -               switch (info[i].type) {
> -               case BPF_KPTR_UNREF:
> -               case BPF_KPTR_REF:
> -               case BPF_KPTR_PERCPU:
> -               case BPF_UPTR:
> -               case BPF_LIST_HEAD:
> -               case BPF_RB_ROOT:
> -                       break;
> -               default:
> -                       return -EINVAL;
> -               }
> -       }
> -
> -       if (check_add_overflow(repeat_cnt, 1, &total_repeats) ||
> -           check_mul_overflow(field_cnt, total_repeats, &total_cnt) ||
> -           total_cnt > (u32)info_cnt)
> -               return -E2BIG;
> -
> -       cur = field_cnt;
> -       for (i = 0; i < repeat_cnt; i++) {
> -               memcpy(&info[cur], &info[0], field_cnt * sizeof(info[0]));
> -               for (j = 0; j < field_cnt; j++)
> -                       info[cur++].off += (i + 1) * elem_size;
> -       }
> +       struct btf_field_info *last = w->cnt ? &w->info[w->cnt - 1] : NULL;
>
> +       if (last && info.off < last->off + btf_field_type_size(last->type))
> +               return -EEXIST;
> +       if ((w->field_mask & BPF_GRAPH_NODE) && w->cnt == BTF_OBJ_FIELDS_MAX)
> +               return -EFBIG;
> +       if (bpf_must_abort())
> +               return -EINTR;
> +       if (!bpf_table_next(w->info, w->cnt))
> +               return -ENOMEM;
> +       w->info[w->cnt++] = info;
>         return 0;
>   }
>
> - static int btf_find_struct_field(const struct btf *btf,
> -                                const struct btf_type *t, u32 field_mask,
> -                                struct btf_field_info *info, int info_cnt,
> -                                u32 level, u32 *seen_mask);
> -
> - /* Find special fields in the struct type of a field.
> -  *
> -  * This function is used to find fields of special types that is not a
> -  * global variable or a direct field of a struct type. It also handles the
> -  * repetition if it is the element type of an array.
> -  */
> - static int btf_find_nested_struct(const struct btf *btf, const struct btf_type *t,
> -                                 u32 off, u32 nelems,
> -                                 u32 field_mask, struct btf_field_info *info,
> -                                 int info_cnt, u32 level, u32 *seen_mask)
> + /* Copy 'cnt' fields from 'first' on to 'nelems' elements. The first copy is 'by' bytes off. */
> + static int btf_repeat_fields(struct btf_field_walk *w, u32 first, u32 cnt, u32 by,
> +                            u32 nelems, u32 elem_size, bool array)
>   {
> -       int ret, err, i;
> +       struct btf_field_info info;
> +       u32 i, j;
> +       int err;
>
> -       level++;
> -       if (level >= MAX_RESOLVE_DEPTH)
> -               return -E2BIG;
> -
> -       ret = btf_find_struct_field(btf, t, field_mask, info, info_cnt, level, seen_mask);
> -
> -       if (ret <= 0)
> -               return ret;
> -
> -       /* Shift the offsets of the nested struct fields to the offsets
> -        * related to the container.
> -        */
> -       for (i = 0; i < ret; i++)
> -               info[i].off += off;
> -
> -       if (nelems > 1) {
> -               err = btf_repeat_fields(info, info_cnt, ret, nelems - 1, t->size);
> -               if (err == 0)
> -                       ret *= nelems;
> -               else
> -                       ret = err;
> +       for (i = 0; i < nelems && cnt; i++, by += elem_size) {
> +               for (j = first; j < first + cnt; j++) {
> +                       info = w->info[j];
> +                       info.off += by;
> +                       if (array && !(info.type & (BPF_KPTR | BPF_UPTR | BPF_GRAPH_ROOT)))
> +                               return -EINVAL;
> +                       if (info.type & w->seen_mask)
> +                               return -E2BIG;
> +                       err = btf_add_field(w, info);
> +                       if (err)
> +                               return err;
> +               }
>         }
> +       return 0;
> + }
>
> -       return ret;
> + static int btf_enter_struct(struct btf_field_walk *w, const struct btf_type *t, u32 off, u32 nelems)
> + {
> +       int i = bpf_index_find(&w->index, (unsigned long)t);
> +       struct btf_field_scope *s;
> +
> +       if (i >= 0) {
> +               s = &w->scopes[i];
> +               return btf_repeat_fields(w, s->first, s->cnt, off - s->off, nelems, t->size,
> +                                        nelems > 1);
> +       }
> +       i = w->index.cnt;
> +       s = bpf_table_next(w->scopes, i);
> +       if (!s || bpf_index_add(&w->index, (unsigned long)t, i))
> +               return -ENOMEM;
> +       *s = (struct btf_field_scope){
> +               .t = t, .off = off, .nelems = nelems, .first = w->cnt, .parent = w->scope,
> +       };
> +       w->scope = i;
> +       return 0;
>   }
>
>   static int btf_find_field_one(const struct btf *btf,
>                               const struct btf_type *var,
>                               const struct btf_type *var_type,
>                               int var_idx,
> -                             u32 off, u32 expected_size,
> -                             u32 field_mask, u32 *seen_mask,
> -                             struct btf_field_info *info, int info_cnt,
> -                             u32 level)
> +                             u32 base, u32 off, u32 expected_size,
> +                             struct btf_field_walk *w)
>   {
>         int ret, align, sz, field_type;
> -       struct btf_field_info tmp;
>         const struct btf_array *array;
> +       struct btf_field_info info;
>         u32 i, nelems = 1;
>
>         /* Walk into array types to find the element type and the number of
> @@@ -3889,15 -3930,13 +3930,13 @@@
>                 return 0;
>
>         field_type = btf_get_field_type(btf, var_type,
> -                                       field_mask, seen_mask, &align, &sz);
> +                                       w->field_mask, &w->seen_mask, &align, &sz);
>         /* Look into variables of struct types */
>         if (!field_type && __btf_type_is_struct(var_type)) {
>                 sz = var_type->size;
>                 if (expected_size && expected_size != sz * nelems)
>                         return 0;
> -               ret = btf_find_nested_struct(btf, var_type, off, nelems, field_mask,
> -                                            &info[0], info_cnt, level, seen_mask);
> -               return ret;
> +               return btf_enter_struct(w, var_type, base + off, nelems);
>         }
>
>         if (field_type == 0)
> @@@ -3909,6 -3948,7 +3948,7 @@@
>                 return 0;
>         if (off % align)
>                 return 0;
> +       off += base;
>
>         switch (field_type) {
>         case BPF_SPIN_LOCK:
> @@@ -3920,8 -3960,7 +3960,7 @@@
>         case BPF_REFCOUNT:
>         case BPF_TASK_WORK:
>         case BPF_RCU_HEAD:
> -               ret = btf_find_struct(btf, var_type, off, sz, field_type,
> -                                     info_cnt ? &info[0] : &tmp);
> +               ret = btf_find_struct(btf, var_type, off, sz, field_type, &info);
>                 if (ret < 0)
>                         return ret;
>                 break;
> @@@ -3929,17 -3968,14 +3968,14 @@@
>         case BPF_KPTR_REF:
>         case BPF_KPTR_PERCPU:
>         case BPF_UPTR:
> -               ret = btf_find_kptr(btf, var_type, off, sz,
> -                                   info_cnt ? &info[0] : &tmp, field_mask);
> +               ret = btf_find_kptr(btf, var_type, off, sz, &info, w->field_mask);
>                 if (ret < 0)
>                         return ret;
>                 break;
>         case BPF_LIST_HEAD:
>         case BPF_RB_ROOT:
>                 ret = btf_find_graph_root(btf, var, var_type,
> -                                         var_idx, off, sz,
> -                                         info_cnt ? &info[0] : &tmp,
> -                                         field_type);
> +                                         var_idx, off, sz, &info, field_type);
>                 if (ret < 0)
>                         return ret;
>                 break;
> @@@ -3949,81 -3985,51 +3985,51 @@@
>
>         if (ret == BTF_FIELD_IGNORE)
>                 return 0;
> -       if (!info_cnt)
> -               return -E2BIG;
> -       if (nelems > 1) {
> -               ret = btf_repeat_fields(info, info_cnt, 1, nelems - 1, sz);
> -               if (ret < 0)
> -                       return ret;
> -       }
> -       return nelems;
> - }
> -
> - static int btf_find_struct_field(const struct btf *btf,
> -                                const struct btf_type *t, u32 field_mask,
> -                                struct btf_field_info *info, int info_cnt,
> -                                u32 level, u32 *seen_mask)
> - {
> -       int ret, idx = 0;
> -       const struct btf_member *member;
> -       u32 i, off;
> -
> -       for_each_member(i, t, member) {
> -               const struct btf_type *member_type = btf_type_by_id(btf,
> -                                                                   member->type);
> -
> -               off = __btf_member_bit_offset(t, member);
> -               if (off % 8)
> -                       /* valid C code cannot generate such BTF */
> -                       return -EINVAL;
> -               off /= 8;
> -
> -               ret = btf_find_field_one(btf, t, member_type, i,
> -                                        off, 0,
> -                                        field_mask, seen_mask,
> -                                        &info[idx], info_cnt - idx, level);
> -               if (ret < 0)
> -                       return ret;
> -               idx += ret;
> -       }
> -       return idx;
> - }
> -
> - static int btf_find_datasec_var(const struct btf *btf, const struct btf_type *t,
> -                               u32 field_mask, struct btf_field_info *info,
> -                               int info_cnt, u32 level, u32 *seen_mask)
> - {
> -       int ret, idx = 0;
> -       const struct btf_var_secinfo *vsi;
> -       u32 i, off;
> -
> -       for_each_vsi(i, t, vsi) {
> -               const struct btf_type *var = btf_type_by_id(btf, vsi->type);
> -               const struct btf_type *var_type = btf_type_by_id(btf, var->type);
> -
> -               off = vsi->offset;
> -               ret = btf_find_field_one(btf, var, var_type, -1, off, vsi->size,
> -                                        field_mask, seen_mask,
> -                                        &info[idx], info_cnt - idx,
> -                                        level);
> -               if (ret < 0)
> -                       return ret;
> -               idx += ret;
> -       }
> -       return idx;
> +       return btf_add_field(w, info) ?:
> +              btf_repeat_fields(w, w->cnt - 1, 1, sz, nelems - 1, sz, true);
>   }
>
>   static int btf_find_field(const struct btf *btf, const struct btf_type *t,
> -                         u32 field_mask, struct btf_field_info *info,
> -                         int info_cnt)
> +                         struct btf_field_walk *w)
>   {
> -       u32 seen_mask = 0;
> +       const struct btf_var_secinfo *vsi;
> +       const struct btf_member *member;
> +       struct btf_field_scope *s;
> +       const struct btf_type *var;
> +       u32 i, off;
> +       int err;
>
> -       if (__btf_type_is_struct(t))
> -               return btf_find_struct_field(btf, t, field_mask, info, info_cnt, 0, &seen_mask);
> -       else if (btf_type_is_datasec(t))
> -               return btf_find_datasec_var(btf, t, field_mask, info, info_cnt, 0, &seen_mask);
> -       return -EINVAL;
> +       if (!__btf_type_is_struct(t) && !btf_type_is_datasec(t))
> +               return -EINVAL;
> +
> +       for (err = btf_enter_struct(w, t, 0, 1); !err;) {
> +               if (bpf_must_abort())
> +                       return -EINTR;
> +               s = &w->scopes[w->scope];
> +               i = s->next++;
> +               if (i == btf_type_vlen(s->t)) {
> +                       if (!w->scope)
> +                               break;
> +                       s->cnt = w->cnt - s->first;
> +                       w->scope = s->parent;
> +                       err = btf_repeat_fields(w, s->first, s->cnt, s->t->size, s->nelems - 1,
> +                                               s->t->size, true);
> +               } else if (btf_type_is_datasec(s->t)) {
> +                       vsi = btf_type_var_secinfo(s->t) + i;
> +                       var = btf_type_by_id(btf, vsi->type);
> +                       err = btf_find_field_one(btf, var, btf_type_by_id(btf, var->type), -1,
> +                                                0, vsi->offset, vsi->size, w);
> +               } else {
> +                       member = btf_type_member(s->t) + i;
> +                       off = __btf_member_bit_offset(s->t, member);
> +                       if (off % 8)
> +                               /* valid C code cannot generate such BTF */
> +                               return -EINVAL;
> +                       err = btf_find_field_one(btf, s->t, btf_type_by_id(btf, member->type), i,
> +                                                s->off, off / 8, 0, w);
> +               }
> +       }
> +       return err;
>   }
>
>   /* Callers have to ensure the life cycle of btf if it is program BTF */
> @@@ -4134,6 -4140,8 +4140,8 @@@ static int btf_parse_graph_root(const s
>          * verify its type.
>          */
>         for_each_member(i, t, member) {
> +               if (bpf_must_abort())
> +                       return -EINTR;
>                 if (strcmp(info->graph_root.node_name,
>                            __btf_name_by_offset(btf, member->name_off)))
>                         continue;
> @@@ -4175,37 -4183,29 +4183,29 @@@ static int btf_parse_rb_root(const stru
>                                             __alignof__(struct bpf_rb_node));
>   }
>
> - static int btf_field_cmp(const void *_a, const void *_b, const void *priv)
> - {
> -       const struct btf_field *a = (const struct btf_field *)_a;
> -       const struct btf_field *b = (const struct btf_field *)_b;
> -
> -       if (a->offset < b->offset)
> -               return -1;
> -       else if (a->offset > b->offset)
> -               return 1;
> -       return 0;
> - }
> -
>   struct btf_record *btf_parse_fields(const struct btf *btf, const struct btf_type *t,
>                                     u32 field_mask, u32 value_size)
>   {
> -       struct btf_field_info info_arr[BTF_FIELDS_MAX];
> -       u32 next_off = 0, field_type_size;
> +       struct btf_field_info *info_arr __free(kvfree) = NULL;
> +       struct btf_field_walk w = { .field_mask = field_mask };
> +       u32 field_type_size;
>         struct btf_record *rec;
>         int ret, i, cnt;
>
> -       ret = btf_find_field(btf, t, field_mask, info_arr, ARRAY_SIZE(info_arr));
> +       ret = btf_find_field(btf, t, &w);
> +       kvfree(w.scopes);
> +       kvfree(w.index.slots);
> +       info_arr = w.info;
>         if (ret < 0)
>                 return ERR_PTR(ret);
> -       if (!ret)
> +       if (!w.cnt)
>                 return NULL;
>
> -       cnt = ret;
> +       cnt = w.cnt;
>         /* This needs to be kzalloc to zero out padding and unused fields, see
>          * comment in btf_record_equal.
>          */
> -       rec = kzalloc_flex(*rec, fields, cnt, GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
> +       rec = kvzalloc_flex(*rec, fields, cnt, BPF_VERIFIER_GFP);
>         if (!rec)
>                 return ERR_PTR(-ENOMEM);
>
> @@@ -4223,11 -4223,10 +4223,10 @@@
>                         ret = -EFAULT;
>                         goto end;
>                 }
> -               if (info_arr[i].off < next_off) {
> -                       ret = -EEXIST;
> +               if (bpf_must_abort()) {
> +                       ret = -EINTR;
>                         goto end;
>                 }
> -               next_off = info_arr[i].off + field_type_size;
>
>                 rec->field_mask |= info_arr[i].type;
>                 rec->fields[i].offset = info_arr[i].off;
> @@@ -4316,9 -4315,6 +4315,6 @@@
>                 goto end;
>         }
>
> -       sort_r(rec->fields, rec->cnt, sizeof(struct btf_field), btf_field_cmp,
> -              NULL, rec);
> -
>         return rec;
>   end:
>         btf_record_free(rec);
> @@@ -4624,7 -4620,7 +4620,7 @@@ static s32 btf_enum_check_meta(struct b
>
>         /* enum type either no name or a valid one */
>         if (t->name_off &&
> -           !btf_name_valid_identifier(env->btf, t->name_off)) {
> +           !btf_name_valid(env, t->name_off)) {
>                 btf_verifier_log_type(env, t, "Invalid name");
>                 return -EINVAL;
>         }
> @@@ -4640,7 -4636,7 +4636,7 @@@
>
>                 /* enum member must have a valid name */
>                 if (!enums[i].name_off ||
> -                   !btf_name_valid_identifier(btf, enums[i].name_off)) {
> +                   !btf_name_valid(env, enums[i].name_off)) {
>                         btf_verifier_log_type(env, t, "Invalid name");
>                         return -EINVAL;
>                 }
> @@@ -4732,7 -4728,7 +4728,7 @@@ static s32 btf_enum64_check_meta(struc
>
>         /* enum type either no name or a valid one */
>         if (t->name_off &&
> -           !btf_name_valid_identifier(env->btf, t->name_off)) {
> +           !btf_name_valid(env, t->name_off)) {
>                 btf_verifier_log_type(env, t, "Invalid name");
>                 return -EINVAL;
>         }
> @@@ -4748,7 -4744,7 +4744,7 @@@
>
>                 /* enum member must have a valid name */
>                 if (!enums[i].name_off ||
> -                   !btf_name_valid_identifier(btf, enums[i].name_off)) {
> +                   !btf_name_valid(env, enums[i].name_off)) {
>                         btf_verifier_log_type(env, t, "Invalid name");
>                         return -EINVAL;
>                 }
> @@@ -5038,7 -5034,7 +5034,7 @@@ static s32 btf_locsec_check_meta(struc
>         }
>
>         if (!t->name_off ||
> -           !btf_name_valid_section(env->btf, t->name_off)) {
> +           !btf_name_valid(env, t->name_off)) {
>                 btf_verifier_log_type(env, t, "Invalid name");
>                 return -EINVAL;
>         }
> @@@ -5230,7 -5226,7 +5226,7 @@@ static s32 btf_func_check_meta(struct b
>                                u32 meta_left)
>   {
>         if (!t->name_off ||
> -           !btf_name_valid_identifier(env->btf, t->name_off)) {
> +           !btf_name_valid(env, t->name_off)) {
>                 btf_verifier_log_type(env, t, "Invalid name");
>                 return -EINVAL;
>         }
> @@@ -5299,7 -5295,7 +5295,7 @@@ static s32 btf_var_check_meta(struct bt
>         }
>
>         if (!t->name_off ||
> -           !btf_name_valid_identifier(env->btf, t->name_off)) {
> +           !btf_name_valid(env, t->name_off)) {
>                 btf_verifier_log_type(env, t, "Invalid name");
>                 return -EINVAL;
>         }
> @@@ -5365,7 -5361,7 +5361,7 @@@ static s32 btf_datasec_check_meta(struc
>         }
>
>         if (!t->name_off ||
> -           !btf_name_valid_section(env->btf, t->name_off)) {
> +           !btf_name_valid(env, t->name_off)) {
>                 btf_verifier_log_type(env, t, "Invalid name");
>                 return -EINVAL;
>         }
> @@@ -5752,7 -5748,7 +5748,7 @@@ static int btf_func_proto_check(struct
>
>                 if (args[i].name_off &&
>                     (!btf_name_offset_valid(btf, args[i].name_off) ||
> -                    !btf_name_valid_identifier(btf, args[i].name_off))) {
> +                    !btf_name_valid(env, args[i].name_off))) {
>                         btf_verifier_log_type(env, t,
>                                               "Invalid arg#%u", i + 1);
>                         return -EINVAL;
> @@@ -5985,6 -5981,22 +5981,22 @@@ static int btf_check_all_types(struct b
>                 return err;
>
>         env->phase++;
> +       /*
> +        * Structs and arrays go first. A walk from a pointer stops at them and hides this loop:
> +        *   ptr -> typedef -> array -+
> +        *             ^--------------+
> +        */
> +       for (i = btf->base_btf ? 0 : 1; i < btf->nr_types; i++) {
> +               type_id = btf->start_id + i;
> +               t = btf_type_by_id(btf, type_id);
> +
> +               if ((btf_type_is_struct(t) || btf_type_is_array(t)) &&
> +                   !env_type_is_resolved(env, type_id)) {
> +                       err = btf_resolve(env, t, type_id);
> +                       if (err)
> +                               return err;
> +               }
> +       }
>         for (i = btf->base_btf ? 0 : 1; i < btf->nr_types; i++) {
>                 type_id = btf->start_id + i;
>                 t = btf_type_by_id(btf, type_id);
> @@@ -6035,6 -6047,7 +6047,7 @@@ static int btf_parse_str_sec(struct btf
>         const struct btf_header *hdr;
>         struct btf *btf = env->btf;
>         const char *start, *end;
> +       u32 i, len = 0;
>
>         hdr = &btf->hdr;
>         start = btf->nohdr_data + hdr->str_off;
> @@@ -6059,6 -6072,21 +6072,21 @@@
>                 return -EINVAL;
>         }
>
> +       /* many names can share one long string: look at each byte once */
> +       kvfree(env->names);
> +       env->names = kvcalloc(BITS_TO_LONGS(hdr->str_len), sizeof(long),
> +                             GFP_KERNEL | __GFP_NOWARN);
> +       if (!env->names)
> +               return -ENOMEM;
> +       for (i = hdr->str_len; i--;) {
> +               if (!start[i])
> +                       len = 0;
> +               else if (!isprint(start[i]))
> +                       len = BTF_MAX_NAME_LEN;
> +               else if (len++ < BTF_MAX_NAME_LEN)
> +                       __set_bit(i, env->names);
> +       }
> +
>         return 0;
>   }
>
> @@@ -6290,6 -6318,10 +6318,10 @@@ btf_parse_struct_metas(struct bpf_verif
>                         ret = -EINVAL;
>                         goto free_aof;
>                 }
> +               if (bpf_must_abort()) {
> +                       ret = -EINTR;
> +                       goto free_aof;
> +               }
>
>                 ret = btf_find_kptr(btf, t, 0, 0, &tmp, BPF_KPTR);
>                 if (ret != BTF_FIELD_FOUND)
> @@@ -6347,6 -6379,9 +6379,9 @@@
>                 record = btf_parse_fields(btf, t, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK | BPF_LIST_HEAD | BPF_LIST_NODE |
>                                                   BPF_RB_ROOT | BPF_RB_NODE | BPF_REFCOUNT |
>                                                   BPF_KPTR, t->size);
> +               /* It cannot be allocated. A map has its own record. */
> +               if (record == ERR_PTR(-EFBIG))
> +                       continue;
>                 /* The record cannot be unset, treat it as an error if so */
>                 if (IS_ERR_OR_NULL(record)) {
>                         ret = PTR_ERR_OR_ZERO(record) ?: -EFAULT;
> @@@ -6473,7 -6508,7 +6508,7 @@@ static struct btf *btf_parse(const unio
>         if (err)
>                 goto errout;
>
> -       err = btf_parse_type_sec(env);
> +       err = btf_parse_type_sec(env) ?: btf_link_decl_tags(btf);
>         if (err)
>                 goto errout;
>
> @@@ -8091,20 -8126,11 +8126,11 @@@ int btf_struct_access(struct bpf_verifi
>                 if (!meta)
>                         break;
>                 rec = meta->record;
> -               for (i = 0; i < rec->cnt; i++) {
> -                       struct btf_field *field = &rec->fields[i];
> -                       u32 offset = field->offset;
> -                       /* An access at 'lo' or above ends after the start of the field. */
> -                       s64 lo = max(min_off, (s64)offset - size + 1);
> -
> -                       /* Round up to min_off + k * step. The step is never 0. */
> -                       lo += imod(min_off - lo, reg->step);
> -                       if (lo <= max_off && lo < offset + field->size) {
> -                               bpf_log(log,
> -                                       "direct access to %s is disallowed\n",
> -                                       btf_field_type_name(field->type));
> -                               return -EACCES;
> -                       }
> +               i = btf_record_first_field(rec, off);
> +               if (i < rec->cnt && rec->fields[i].offset < off + size) {
> +                       bpf_log(log, "direct access to %s is disallowed\n",
> +                               btf_field_type_name(rec->fields[i].type));
> +                       return -EACCES;
>                 }
>                 break;
>         }
> @@@ -8636,8 -8662,8 +8662,8 @@@ static int btf_scan_decl_tags(struct bp
>                               const struct btf_type *fn_t,
>                               u32 arg_idx, bool is_global, u32 *tags)
>   {
> -       int id = btf_named_start_id(btf, false) - 1;
>         const char tag_key[] = "arg:";
> +       int id = 0;
>         static const struct {
>                 const char *tag_value;
>                 enum btf_arg_tag arg_tag;
> @@@ -8747,8 -8773,7 +8773,7 @@@ static int btf_validate_return_type(str
>   }
>
>   static int btf_check_arg_slots(struct bpf_verifier_log *log, const char *tname,
> -                              bool is_global, u32 slot_cnt,
> -                              struct bpf_subprog_info *sub)
> +                              bool is_global, u32 slot_cnt)
>   {
>         if (slot_cnt <= MAX_BPF_FUNC_REG_ARGS)
>                 return 0;
> @@@ -8760,12 -8785,7 +8785,7 @@@
>                         tname, slot_cnt, MAX_BPF_FUNC_REG_ARGS);
>                 return -EINVAL;
>         }
> -       if (!bpf_jit_supports_stack_args()) {
> -               bpf_log(log, "JIT does not support function %s() with %d argument slots\n",
> -                       tname, slot_cnt);
> -               return -EFAULT;
> -       }
> -       sub->stack_arg_cnt = slot_cnt - MAX_BPF_FUNC_REG_ARGS;
> +       /* The code of a static function tells which stack arguments it takes */
>         return 0;
>   }
>
> @@@ -8832,13 -8852,15 +8852,15 @@@ int btf_prepare_func_args(struct bpf_ve
>         }
>         args = (const struct btf_param *)(t + 1);
>         nargs = btf_type_vlen(t);
> -       sub->arg_slot_cnt = nargs;
> +       sub->arg_slot_cnt = min_t(u32, nargs, MAX_BPF_FUNC_ARGS);
>         if (nargs > MAX_BPF_FUNC_ARGS) {
> +               if (!is_global) /* not fatal for static funcs */
> +                       return -EINVAL;
>                 bpf_log(log, "kernel supports at most %d parameters, function %s has %d\n",
>                         MAX_BPF_FUNC_ARGS, tname, nargs);
>                 return -EFAULT;
>         }
> -       err = btf_check_arg_slots(log, tname, is_global, nargs, sub);
> +       err = btf_check_arg_slots(log, tname, is_global, nargs);
>         if (err)
>                 return err;
>
> @@@ -9027,7 -9049,7 +9049,7 @@@ skip_pointer
>                 return -EINVAL;
>         }
>
> -       err = btf_check_arg_slots(log, tname, is_global, slots_used, sub);
> +       err = btf_check_arg_slots(log, tname, is_global, slots_used);
>         if (err)
>                 return err;
>         sub->arg_slot_cnt = slots_used;

^ permalink raw reply	[flat|nested] 69+ messages in thread

* Re: linux-next: manual merge of the bpf-next tree with the bpf tree
  2026-11-18 15:47 ` J4f J4f
@ 2026-11-19  1:17   ` Alexei Starovoitov
  0 siblings, 0 replies; 69+ messages in thread
From: Alexei Starovoitov @ 2026-11-19  1:17 UTC (permalink / raw)
  To: J4f J4f, Mark Brown
  Cc: Kumar Kartikeya Dwivedi, Eduard Zingerman, Daniel Borkmann,
	Alexei Starovoitov, Andrii Nakryiko, bpf, Networking,
	Linux Kernel Mailing List, Linux Next Mailing List

On Wed Nov 18, 2026 at 3:47 PM UTC, J4f J4f wrote:
> On Wed, 18 Nov 2026 at 05:36, Mark Brown <broonie@kernel.org> wrote:
>>
>> Hi all,
>>
>> Today's linux-next merge of the bpf-next tree got a conflict in:
>>
>>   kernel/bpf/btf.c
>>
>> between commit:
>>
>>   b7cc45994c3f9 ("bpf: Check variable-offset accesses against special fields")
>>
>> from the bpf tree and commit:
>>
>>   ca4395aade31a ("bpf: Walk each type once when looking for special fields")
>>
>> from the bpf-next tree.  I'm not confident of this merge, it discards
>> the bpf commit on the basis that it looks like there is some new
>> handling of special fields in the bpf-next tree but I'm not sure that
>> overlaps with the fix.
>>
>> I fixed it up (see below) and can carry the fix as necessary. This
>> is now fixed as far as linux-next is concerned, but any non trivial
>> conflicts should be mentioned to your upstream maintainer when your tree
>> is submitted for merging.  You may also want to consider cooperating
>> with the maintainer of the conflicting tree to minimise any particularly
>> complex conflicts.
>>
> Hi Mark,
>
> Thanks for the report.
>
> I reproduced this on bpf-next master: the rewrite does not cover the fix,
> the check in btf_struct_access() now only looks at min_off again. I will
> send a v4 rebased on top of the bpf-next series shortly.

Pls ask your bot to stop doing stupid things.


^ permalink raw reply	[flat|nested] 69+ messages in thread

* linux-next: manual merge of the bpf-next tree with the bpf tree
@ 2026-11-26 14:42 Mark Brown
  0 siblings, 0 replies; 69+ messages in thread
From: Mark Brown @ 2026-11-26 14:42 UTC (permalink / raw)
  To: Kumar Kartikeya Dwivedi, Eduard Zingerman, Daniel Borkmann,
	Alexei Starovoitov, Andrii Nakryiko, bpf, Networking
  Cc: Linux Kernel Mailing List, Linux Next Mailing List

[-- Attachment #1: Type: text/plain, Size: 484895 bytes --]

Hi all,

Today's linux-next merge of the bpf-next tree got a conflict in:

  kernel/bpf/verifier.c

between commit:

  703826e497ffa ("bpf: Give the error of bpf_res_spin_lock() a 32-bit range")

from the bpf tree and commit:

  8f58839c9ebbb ("bpf: Keep more of what is known about a number")

from the bpf-next tree.

I fixed it up (see below) and can carry the fix as necessary. This
is now fixed as far as linux-next is concerned, but any non trivial
conflicts should be mentioned to your upstream maintainer when your tree
is submitted for merging.  You may also want to consider cooperating
with the maintainer of the conflicting tree to minimise any particularly
complex conflicts.

diff --combined kernel/bpf/verifier.c
index d4b31990fcb9c,e7013ed8cadd7..0000000000000
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@@ -18,6 -18,7 +18,7 @@@
  #include <linux/vmalloc.h>
  #include <linux/stringify.h>
  #include <linux/bsearch.h>
+ #include <linux/jhash.h>
  #include <linux/sort.h>
  #include <linux/perf_event.h>
  #include <linux/ctype.h>
@@@ -28,6 -29,7 +29,7 @@@
  #include <linux/keyctl.h>
  #include <linux/btf_ids.h>
  #include <linux/poison.h>
+ #include <linux/random.h>
  #include <linux/module.h>
  #include <linux/cpumask.h>
  #include <linux/cnum.h>
@@@ -62,19 -64,16 +64,16 @@@ static bool bpf_global_percpu_ma_set
  
  /* bpf_check() is a static code analyzer that walks eBPF program
   * instruction by instruction and updates register/stack state.
-  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
   *
-  * The first pass is depth-first-search to check that the program is a DAG.
+  * The first pass is depth-first-search over the control flow graph.
   * It rejects the following programs:
-  * - larger than BPF_MAXINSNS insns
-  * - if loop is present (detected via back-edge)
+  * - if loop is present (detected via back-edge) and the program is unprivileged
   * - unreachable insns exist (shouldn't be a forest. program = one function)
   * - out of bounds or malformed jumps
-  * The second pass is all possible path descent from the 1st insn.
-  * Since it's analyzing all paths through the program, the length of the
-  * analysis is limited to 64k insn, which may be hit even if total number of
-  * insn is less then 4K, but there are too many branches that change stack/regs.
-  * Number of 'branches to be analyzed' is limited to 1k
+  * The second pass goes from basic block to basic block, starting at the 1st
+  * insn. States that meet at the start of a block are joined, so the length of
+  * the analysis follows the size of the program and not the number of paths
+  * through it. See flow.c.
   *
   * On entry to each instruction, each register has a type, and the instruction
   * changes the types of the registers depending on instruction semantics.
@@@ -185,7 -184,10 +184,10 @@@
   * reference remains at the end of the program, the verifier rejects it.
   */
  
- /* verifier_state + insn_idx are pushed to stack when branch is encountered */
+ /*
+  * verifier_state + insn_idx are pushed to stack when branch is encountered.
+  * It's emptied after every insn, see flow_drain().
+  */
  struct bpf_verifier_stack_elem {
  	/* verifier state is 'st'
  	 * before processing instruction 'insn_idx'
@@@ -194,22 -196,16 +196,16 @@@
  	struct bpf_verifier_state st;
  	int insn_idx;
  	int prev_insn_idx;
+ 	bool again;	/* see bpf_flow_deliver() */
  	struct bpf_verifier_stack_elem *next;
- 	/* length of verifier log at the time this state was pushed on stack */
- 	u32 log_pos;
- 	u64 diag_log_pos;
  };
  
- #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
- #define BPF_COMPLEXITY_LIMIT_STATES	64
- 
  #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE  512
  
  #define BPF_PRIV_STACK_MIN_SIZE		64
  
  static int acquire_reference(struct bpf_verifier_env *env, int insn_idx, int parent_id);
- static int __release_reference_nomark(struct bpf_verifier_state *state, int id);
- static int release_reference_nomark(struct bpf_verifier_env *env, int id);
+ static int release_reference_nomark(struct bpf_verifier_state *state, int id);
  static int release_reference(struct bpf_verifier_env *env, int id);
  static int invalidate_reference(struct bpf_verifier_env *env, int id);
  static u32 reg_lifetime_id(struct bpf_verifier_env *env,
@@@ -224,8 -220,6 +220,6 @@@ static bool is_trusted_reg(struct bpf_v
  static inline bool in_sleepable_context(struct bpf_verifier_env *env);
  static bool in_rcu_callback(struct bpf_verifier_env *env);
  static const char *non_sleepable_context_description(struct bpf_verifier_env *env);
- static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg);
- static void scalar_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg);
  
  static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
  			      struct bpf_map *map,
@@@ -303,11 -297,6 +297,6 @@@ static int arg_from_argno(argno_t a
  	return -1;
  }
  
- static int arg_idx_from_argno(argno_t a)
- {
- 	return arg_from_argno(a) - 1;
- }
- 
  /* Normalize helper register numbers and kfunc argument numbers to ABI slots. */
  static u32 arg_slot_from_argno(argno_t a)
  {
@@@ -357,6 -346,11 +346,11 @@@ static void verbose_invalid_scalar(stru
  	verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
  }
  
+ static bool offset_is_far(const struct bpf_reg_state *reg)
+ {
+ 	return reg_smin(reg) <= -BPF_MAX_VAR_OFF || reg_smax(reg) >= BPF_MAX_VAR_OFF;
+ }
+ 
  static bool reg_not_null(struct bpf_verifier_env *env, const struct bpf_reg_state *reg)
  {
  	enum bpf_reg_type type;
@@@ -369,7 -363,7 +363,7 @@@
  	 * The types below guarantee a non-NULL base, an unbounded offset can
  	 * still wrap base + offset to zero.
  	 */
- 	if (reg_smin(reg) <= -BPF_MAX_VAR_OFF || reg_smax(reg) >= BPF_MAX_VAR_OFF)
+ 	if (offset_is_far(reg))
  		return false;
  
  	type = base_type(type);
@@@ -465,6 -459,7 +459,7 @@@ static int bpf_compute_subprog_ret_regs
  			return -EFAULT;
  		if (ret_regs_cnt(size) > 1) {
  			subprog_info(env, subprog)->ret_reg_pair = true;
+ 			subprog_aux(env, subprog)->ret_reg_pair = true;
  			env->prog->jit_required = 1;
  		}
  	}
@@@ -726,7 -721,7 +721,7 @@@ static void mark_dynptr_stack_regs(stru
  				   struct bpf_reg_state *sreg2,
  				   enum bpf_dynptr_type type, int parent_id)
  {
- 	int id = ++env->id_gen;
+ 	int id = bpf_new_id(env);
  
  	__mark_dynptr_reg(sreg1, type, true, id, parent_id);
  	__mark_dynptr_reg(sreg2, type, false, id, parent_id);
@@@ -736,7 -731,7 +731,7 @@@ static void mark_dynptr_cb_reg(struct b
  			       struct bpf_reg_state *reg,
  			       enum bpf_dynptr_type type)
  {
- 	__mark_dynptr_reg(reg, type, true, ++env->id_gen, 0);
+ 	__mark_dynptr_reg(reg, type, true, bpf_new_id(env), 0);
  }
  
  static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
@@@ -856,15 -851,12 +851,12 @@@ static int unmark_stack_slots_dynptr(st
  				      : reg->id);
  }
  
- static void __mark_reg_unknown(const struct bpf_verifier_env *env,
- 			       struct bpf_reg_state *reg);
- 
  static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
  {
  	if (!env->allow_ptr_leaks)
  		bpf_mark_reg_not_init(env, reg);
  	else
- 		__mark_reg_unknown(env, reg);
+ 		bpf_mark_reg_unknown(reg);
  }
  
  static int dynptr_ref_cnt(struct bpf_verifier_env *env, int v_parent_id)
@@@ -1037,6 -1029,16 +1029,16 @@@ static bool in_rcu_cs(struct bpf_verifi
  
  static bool is_kfunc_rcu_protected(struct bpf_call_arg_meta *meta);
  
+ /* The number of loops that the frames of @st below @frameno are in */
+ static u32 nr_loops_below(const struct bpf_verifier_state *st, u32 frameno)
+ {
+ 	u32 fr, nr = 0;
+ 
+ 	for (fr = 0; fr < frameno; fr++)
+ 		nr += st->frame[fr]->loop_stack_cnt;
+ 	return nr;
+ }
+ 
  static int mark_stack_slots_iter(struct bpf_verifier_env *env,
  				 struct bpf_call_arg_meta *meta,
  				 struct bpf_reg_state *reg, int insn_idx,
@@@ -1069,7 -1071,7 +1071,7 @@@
  		st->iter.btf = btf;
  		st->iter.btf_id = btf_id;
  		st->iter.state = BPF_ITER_STATE_ACTIVE;
- 		st->iter.depth = 0;
+ 		st->iter.loops = nr_loops_below(env->cur_state, env->cur_state->curframe + 1);
  
  		for (j = 0; j < BPF_REG_SIZE; j++)
  			slot->slot_type[j] = STACK_ITER;
@@@ -1356,7 -1358,7 +1358,7 @@@ static bool is_stack_slot_special(cons
   * - STACK_POISON, which truly forbids access to the slot.
   * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged
   * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is
-  * unnecessary as both are considered equivalent when loading data and pruning,
+  * unnecessary as both are considered equivalent when loading data and comparing states,
   * in case of unprivileged mode it will be incorrect to allow reads of invalid
   * slots.
   */
@@@ -1420,7 -1422,7 +1422,7 @@@ static void *realloc_array(void *arr, s
  		goto out;
  
  	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
- 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL_ACCOUNT);
+ 	new_arr = krealloc(arr, alloc_size, BPF_VERIFIER_GFP);
  	if (!new_arr) {
  		kfree(arr);
  		return NULL;
@@@ -1437,17 -1439,11 +1439,11 @@@ out
  static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src)
  {
  	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
- 			       sizeof(struct bpf_reference_state), GFP_KERNEL_ACCOUNT);
+ 			       sizeof(struct bpf_reference_state), BPF_VERIFIER_GFP);
  	if (!dst->refs)
  		return -ENOMEM;
  
- 	dst->acquired_refs = src->acquired_refs;
- 	dst->active_locks = src->active_locks;
- 	dst->active_preempt_locks = src->active_preempt_locks;
- 	dst->active_rcu_locks = src->active_rcu_locks;
- 	dst->active_irq_id = src->active_irq_id;
- 	dst->active_lock_id = src->active_lock_id;
- 	dst->active_lock_ptr = src->active_lock_ptr;
+ 	dst->held = src->held;
  	return 0;
  }
  
@@@ -1456,7 -1452,7 +1452,7 @@@ static int copy_stack_state(struct bpf_
  	size_t n = bpf_stack_nr_slots(src);
  
  	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
- 				GFP_KERNEL_ACCOUNT);
+ 				BPF_VERIFIER_GFP);
  	if (!dst->stack)
  		return -ENOMEM;
  
@@@ -1467,7 -1463,7 +1463,7 @@@
  	if (n) {
  		dst->stack_arg_regs = copy_array(dst->stack_arg_regs, src->stack_arg_regs, n,
  						 sizeof(struct bpf_reg_state),
- 						 GFP_KERNEL_ACCOUNT);
+ 						 BPF_VERIFIER_GFP);
  		if (!dst->stack_arg_regs)
  			return -ENOMEM;
  	}
@@@ -1490,7 -1486,7 +1486,7 @@@ static int resize_reference_state(struc
  /* Possibly update state->allocated_stack to be at least size bytes. Also
   * possibly update the function's high-water mark in its bpf_subprog_info.
   */
- int bpf_grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
+ static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
  {
  	size_t old_n = bpf_stack_nr_slots(state), n;
  
@@@ -1508,8 -1504,10 +1504,10 @@@
  	state->allocated_stack = size;
  
  	/* update known max for given subprogram */
- 	if (env->subprog_info[state->subprogno].stack_depth < size)
+ 	if (env->subprog_info[state->subprogno].stack_depth < size) {
  		env->subprog_info[state->subprogno].stack_depth = size;
+ 		env->subprog_info[state->subprogno].deepest_insn = env->insn_idx;
+ 	}
  
  	return 0;
  }
@@@ -1558,9 -1556,9 +1556,9 @@@ static int acquire_reference(struct bpf
  	if (!s)
  		return -ENOMEM;
  	s->type = REF_TYPE_PTR;
- 	s->id = ++env->id_gen;
+ 	s->id = bpf_new_id(env);
  	s->parent_id = parent_id;
- 	bpf_diag_record_ref_acquire(env, insn_idx, s->id);
+ 	bpf_diag_record_ref_acquire(env, s);
  	return s->id;
  }
  
@@@ -1594,7 -1592,7 +1592,7 @@@ static int acquire_irq_state(struct bpf
  	if (!s)
  		return -ENOMEM;
  	s->type = REF_TYPE_IRQ;
- 	s->id = ++env->id_gen;
+ 	s->id = bpf_new_id(env);
  
  	state->active_irq_id = s->id;
  	bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_IRQ, true,
@@@ -1604,9 -1602,14 +1602,14 @@@
  
  static void release_reference_state(struct bpf_verifier_state *state, int idx)
  {
- 	int last_idx;
+ 	int last_idx, fr;
  	size_t rem;
  
+ 	/* the frames that were entered with it don't hold it ever since */
+ 	for (fr = 0; fr <= state->curframe; fr++)
+ 		if (idx < state->frame[fr]->entry_refs)
+ 			state->frame[fr]->entry_refs--;
+ 
  	/* IRQ state requires the relative ordering of elements remaining the
  	 * same, since it relies on the refs array to behave as a stack, so that
  	 * it can detect out-of-order IRQ restore. Hence use memmove to shift
@@@ -1621,6 -1624,20 +1624,20 @@@
  	return;
  }
  
+ /* bpf_rcu_read_unlock() or bpf_preempt_enable() is done, see release_reference_state() */
+ static void release_context_state(struct bpf_verifier_state *state)
+ {
+ 	struct bpf_func_state *frame;
+ 	int fr;
+ 
+ 	for (fr = 0; fr <= state->curframe; fr++) {
+ 		frame = state->frame[fr];
+ 		frame->entry_rcu_locks = min(frame->entry_rcu_locks, state->active_rcu_locks);
+ 		frame->entry_preempt_locks = min(frame->entry_preempt_locks,
+ 						 state->active_preempt_locks);
+ 	}
+ }
+ 
  static bool find_reference_state(struct bpf_verifier_state *state, int id)
  {
  	int i;
@@@ -1715,34 -1732,51 +1732,51 @@@ static struct bpf_reference_state *find
  	return NULL;
  }
  
+ static void leave_loops(struct bpf_func_state *state, u32 cnt)
+ {
+ 	while (state->loop_stack_cnt > cnt)
+ 		bpf_flow_put_header_state(&state->loop_stack[--state->loop_stack_cnt]);
+ }
+ 
  static void free_func_state(struct bpf_func_state *state)
  {
  	if (!state)
  		return;
+ 	leave_loops(state, 0);
  	kfree(state->loop_stack);
  	kfree(state->stack_arg_regs);
  	kfree(state->stack);
  	kfree(state);
  }
  
- void bpf_clear_jmp_history(struct bpf_verifier_state *state)
+ /* @st is new or has grown */
+ void bpf_charge_state(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
  {
- 	kfree(state->jmp_history);
- 	state->jmp_history = NULL;
- 	state->jmp_history_cnt = 0;
+ 	/* with the struct that holds it */
+ 	u32 bytes = 2 * sizeof(*st) + ksize(st->refs), fr;
+ 	struct bpf_func_state *f;
+ 
+ 	bytes += bpf_equations_bytes(&st->equations);
+ 	for (fr = 0; fr <= st->curframe && (f = st->frame[fr]); fr++)
+ 		bytes += kmalloc_size_roundup(sizeof(*f)) + ksize(f->stack) +
+ 			 ksize(f->stack_arg_regs) + ksize(f->loop_stack);
+ 	env->mem += bytes - (s64)st->bytes;
+ 	st->bytes = bytes;
  }
  
- void bpf_free_verifier_state(struct bpf_verifier_state *state,
- 			    bool free_self)
+ void bpf_free_verifier_state(struct bpf_verifier_env *env, struct bpf_verifier_state *state,
+ 			     bool free_self)
  {
  	int i;
  
+ 	env->mem -= state->bytes;
+ 	state->bytes = 0;
  	for (i = 0; i <= state->curframe; i++) {
  		free_func_state(state->frame[i]);
  		state->frame[i] = NULL;
  	}
  	kfree(state->refs);
- 	bpf_clear_jmp_history(state);
+ 	bpf_equations_free(&state->equations);
  	if (free_self)
  		kfree(state);
  }
@@@ -1753,55 -1787,52 +1787,52 @@@
  static int copy_func_state(struct bpf_func_state *dst,
  			   const struct bpf_func_state *src)
  {
+ 	u32 i;
+ 
+ 	leave_loops(dst, 0);
  	memcpy(dst, src, offsetof(struct bpf_func_state, stack));
  	/* Instruction accounting is path-local, not part of verifier state. */
  	dst->insns_subtotal = 0;
+ 	dst->loop_stack_cnt = 0;
  	dst->loop_stack = copy_array(dst->loop_stack, src->loop_stack, src->loop_stack_cnt,
- 				     sizeof(*src->loop_stack), GFP_KERNEL_ACCOUNT);
+ 				     sizeof(*src->loop_stack), BPF_VERIFIER_GFP);
  	if (!dst->loop_stack)
  		return -ENOMEM;
+ 	dst->loop_stack_cnt = src->loop_stack_cnt;
+ 	for (i = 0; i < src->loop_stack_cnt; i++)
+ 		if (src->loop_stack[i].header_state)
+ 			src->loop_stack[i].header_state->refcnt++;
  	return copy_stack_state(dst, src);
  }
  
- int bpf_copy_verifier_state(struct bpf_verifier_state *dst_state,
- 			   const struct bpf_verifier_state *src)
+ int bpf_copy_verifier_state(struct bpf_verifier_env *env, struct bpf_verifier_state *dst_state,
+ 			    const struct bpf_verifier_state *src)
  {
  	struct bpf_func_state *dst;
  	int i, err;
  
- 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
- 					  src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
- 					  GFP_KERNEL_ACCOUNT);
- 	if (!dst_state->jmp_history)
- 		return -ENOMEM;
- 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
- 
- 	/* if dst has more stack frames then src frame, free them, this is also
- 	 * necessary in case of exceptional exits using bpf_throw.
- 	 */
+ 	/* if dst has more stack frames then src frame, free them */
  	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
  		free_func_state(dst_state->frame[i]);
  		dst_state->frame[i] = NULL;
  	}
- 	err = copy_reference_state(dst_state, src);
+ 	err = copy_reference_state(dst_state, src) ?:
+ 	      bpf_equations_copy(env, &dst_state->equations, &src->equations);
  	if (err)
  		return err;
+ 	bpf_add_cost(env, bpf_xreg_cnt(src) + src->acquired_refs, BPF_COST_COPY);
  	dst_state->speculative = src->speculative;
- 	dst_state->in_sleepable = src->in_sleepable;
- 	dst_state->unwound = src->unwound;
- 	dst_state->curframe = src->curframe;
- 	dst_state->branches = src->branches;
- 	dst_state->parent = src->parent;
- 	dst_state->first_insn_idx = src->first_insn_idx;
+ 	dst_state->infeasible = src->infeasible;
+ 	dst_state->max_held_cnt = src->max_held_cnt;
+ 	dst_state->suspect_loops = src->suspect_loops;
+ 	dst_state->join_key = src->join_key;
+ 	dst_state->instance_id = src->instance_id;
+ 	dst_state->insn_idx = src->insn_idx;
  	dst_state->last_insn_idx = src->last_insn_idx;
- 	dst_state->dfs_depth = src->dfs_depth;
- 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
- 	dst_state->may_goto_depth = src->may_goto_depth;
- 	dst_state->equal_state = src->equal_state;
  	for (i = 0; i <= src->curframe; i++) {
  		dst = dst_state->frame[i];
  		if (!dst) {
- 			dst = kzalloc_obj(*dst, GFP_KERNEL_ACCOUNT);
+ 			dst = kzalloc_obj(*dst, BPF_VERIFIER_GFP);
  			if (!dst)
  				return -ENOMEM;
  			dst_state->frame[i] = dst;
@@@ -1810,87 -1841,16 +1841,16 @@@
  		if (err)
  			return err;
  	}
+ 	bpf_charge_state(env, dst_state);
  	return 0;
  }
  
- static u32 state_htab_size(struct bpf_verifier_env *env)
+ /*
+  * A check failed, so the insn is unproven in this state. The program is not rejected: a later
+  * pass can prove the insn. This pass continues, to find the other unproven insns.
+  */
+ static bool error_is_recoverable(int err)
  {
- 	return env->prog->len;
- }
- 
- struct list_head *bpf_explored_state(struct bpf_verifier_env *env, int idx)
- {
- 	struct bpf_verifier_state *cur = env->cur_state;
- 	struct bpf_func_state *state = cur->frame[cur->curframe];
- 
- 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
- }
- 
- static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
- {
- 	int fr;
- 
- 	if (a->curframe != b->curframe)
- 		return false;
- 
- 	for (fr = a->curframe; fr >= 0; fr--)
- 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
- 			return false;
- 
- 	return true;
- }
- 
- void bpf_free_backedges(struct bpf_scc_visit *visit)
- {
- 	struct bpf_scc_backedge *backedge, *next;
- 
- 	for (backedge = visit->backedges; backedge; backedge = next) {
- 		bpf_free_verifier_state(&backedge->state, false);
- 		next = backedge->next;
- 		kfree(backedge);
- 	}
- 	visit->backedges = NULL;
- }
- 
- static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
- 		     int *insn_idx, bool pop_log)
- {
- 	struct bpf_verifier_state *cur = env->cur_state;
- 	struct bpf_verifier_stack_elem *elem, *head = env->head;
- 	int err;
- 
- 	if (env->head == NULL)
- 		return -ENOENT;
- 
- 	if (cur) {
- 		err = bpf_copy_verifier_state(cur, &head->st);
- 		if (err)
- 			return err;
- 		bpf_diag_event_log_restore(env, head->diag_log_pos);
- 	}
- 	if (pop_log)
- 		bpf_vlog_reset(&env->log, head->log_pos);
- 	if (insn_idx)
- 		*insn_idx = head->insn_idx;
- 	if (prev_insn_idx)
- 		*prev_insn_idx = head->prev_insn_idx;
- 	elem = head->next;
- 	bpf_free_verifier_state(&head->st, false);
- 	kfree(head);
- 	env->head = elem;
- 	env->stack_size--;
- 	return 0;
- }
- 
- static bool error_recoverable_with_nospec(int err)
- {
- 	/* Should only return true for non-fatal errors that are allowed to
- 	 * occur during speculative verification. For these we can insert a
- 	 * nospec and the program might still be accepted. Do not include
- 	 * something like ENOMEM because it is likely to re-occur for the next
- 	 * architectural path once it has been recovered-from in all speculative
- 	 * paths.
- 	 */
  	return err == -EPERM || err == -EACCES || err == -EINVAL;
  }
  
@@@ -1902,38 -1862,18 +1862,18 @@@ static struct bpf_verifier_state *push_
  	struct bpf_verifier_stack_elem *elem;
  	int err;
  
- 	elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT);
+ 	elem = kzalloc_obj(struct bpf_verifier_stack_elem, BPF_VERIFIER_GFP);
  	if (!elem)
  		return ERR_PTR(-ENOMEM);
  
  	elem->insn_idx = insn_idx;
  	elem->prev_insn_idx = prev_insn_idx;
  	elem->next = env->head;
- 	elem->log_pos = env->log.end_pos;
- 	elem->diag_log_pos = bpf_diag_event_log_save(env);
  	env->head = elem;
- 	env->stack_size++;
- 	err = bpf_copy_verifier_state(&elem->st, cur);
+ 	err = bpf_copy_verifier_state(env, &elem->st, cur) ?: bpf_check_limits(env);
  	if (err)
- 		return ERR_PTR(-ENOMEM);
+ 		return ERR_PTR(err);
  	elem->st.speculative |= speculative;
- 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
- 		verbose(env, "The sequence of %d jumps is too complex.\n",
- 			env->stack_size);
- 		return ERR_PTR(-E2BIG);
- 	}
- 	if (elem->st.parent) {
- 		++elem->st.parent->branches;
- 		/* WARN_ON(branches > 2) technically makes sense here,
- 		 * but
- 		 * 1. speculative states will bump 'branches' for non-branch
- 		 * instructions
- 		 * 2. is_state_visited() heuristics may decide not to create
- 		 * a new state for a sequence of branches and all such current
- 		 * and cloned states will be pointing to a single parent state
- 		 * which might have large 'branches' count.
- 		 */
- 	}
  	return &elem->st;
  }
  
@@@ -1968,58 -1908,65 +1908,65 @@@ static void bpf_diag_record_caller_save
  	}
  }
  
- static void reg_step_reset(struct bpf_reg_state *reg)
+ static void scalar_step_reset(struct scalar *s)
  {
- 	reg->base = 0;
- 	reg->step = 1;
+ 	s->base = 0;
+ 	s->step = 1;
  }
  
- static void scalar_step_add(struct bpf_reg_state *dst_reg,
- 			    const struct bpf_reg_state *a,
- 			    const struct bpf_reg_state *b)
+ static void scalar_step_add(struct scalar *dst, const struct scalar *a, const struct scalar *b)
  {
- 	const struct bpf_reg_state *reg;
  	s64 amount, tmp;
+ 	u16 step;
  
- 	if (tnum_is_const(b->var_off)) {
- 		reg = a;
- 		amount = (s64)b->var_off.value;
- 	} else if (tnum_is_const(a->var_off)) {
- 		reg = b;
- 		amount = (s64)a->var_off.value;
- 	} else {
- 		reg_step_reset(dst_reg);
- 		return;
- 	}
+ 	if (tnum_is_const(a->var_off) && !tnum_is_const(b->var_off))
+ 		swap(a, b);
+ 	/* b is d + k * step. A constant has no step. */
+ 	amount = tnum_is_const(b->var_off) ? b->var_off.value : b->base;
+ 	step = tnum_is_const(b->var_off) ? a->step : gcd(a->step, b->step);
  
  	/*
  	 * Let x be a possible signed value of the register,
- 	 * d = amount, s = reg->step, and b = reg->base.
+ 	 * d = amount, s = step, and b = a->base mod s.
  	 * Then x mod s = b, with s > 0 and 0 <= b < s.
  	 * If the addition causes signed underflow, the resulting value
  	 * is x + d + 2**64.
  	 *
  	 * Taking the result modulo s and substituting x mod s = b gives:
  	 *   (x + d + 2**64) mod s = (b + d + (2**64 mod s)) mod s      (1)
- 	 * Keeping reg->step = s and updating reg->base to (b + d) mod s
+ 	 * Keeping the step s and updating the base to (b + d) mod s
  	 * requires (1) to equal (b + d) mod s, which holds if and only
  	 * if 2**64 mod s = 0.
  	 * Signed overflow subtracts 2**64 and has the same requirement.
  	 *
  	 * Conservatively reset the stride if either wrap is possible.
  	 */
- 	if (check_add_overflow(reg_smin(reg), amount, &tmp) ||
- 	    check_add_overflow(reg_smax(reg), amount, &tmp)) {
- 		reg_step_reset(dst_reg);
+ 	if (step == 1 || check_add_overflow(cnum64_smin(a->r64), cnum64_smin(b->r64), &tmp) ||
+ 	    check_add_overflow(cnum64_smax(a->r64), cnum64_smax(b->r64), &tmp)) {
+ 		scalar_step_reset(dst);
  		return;
  	}
  
- 	dst_reg->base = (reg->base + imod(amount, reg->step)) % reg->step;
- 	dst_reg->step = reg->step;
+ 	dst->base = (a->base + imod(amount, step)) % step;
+ 	dst->step = step;
  }
  
- static void scalar_step_scale(struct bpf_reg_state *dst_reg, u64 amount)
+ /*
+  * dst = a + b in each of the four parts. @dst can be @a or @b.
+  * The sum of reduced scalars is not always reduced: the caller calls scalar_bounds_sync().
+  */
+ void scalar_add(struct scalar *dst, const struct scalar *a, const struct scalar *b)
  {
+ 	scalar_step_add(dst, a, b);
+ 	dst->r32 = cnum32_add(a->r32, b->r32);
+ 	dst->r64 = cnum64_add(a->r64, b->r64);
+ 	dst->var_off = tnum_add(a->var_off, b->var_off);
+ }
+ 
+ /* The step of @dst * @amount. The ranges are those before the product. */
+ void scalar_step_scale(struct scalar *dst, s64 amount)
+ {
+ 	u64 factor = amount < 0 ? -(u64)amount : amount;
  	u16 step;
  	s64 tmp;
  
@@@ -2032,25 -1979,24 +1979,24 @@@
  	 * Taking the result modulo s * d gives:
  	 *   (x * d - n * 2**64) mod (s * d) =
  	 *   (b * d - (n * 2**64 mod (s * d))) mod (s * d)              (1)
- 	 * Updating dst_reg->base to b * d and dst_reg->step to s * d
+ 	 * Updating dst->base to b * d and dst->step to s * d
  	 * requires (1) to equal b * d, which holds if and only if
  	 * n * 2**64 mod (s * d) = 0.
  	 *
  	 * Conservatively reset the stride if a wrap is possible.
  	 */
- 	if (amount == 0 || check_mul_overflow(dst_reg->step, amount, &step) ||
- 	    check_mul_overflow(reg_smin(dst_reg), (s64)amount, &tmp) ||
- 	    check_mul_overflow(reg_smax(dst_reg), (s64)amount, &tmp)) {
- 		reg_step_reset(dst_reg);
+ 	if (amount == 0 || check_mul_overflow(dst->step, factor, &step) ||
+ 	    check_mul_overflow(cnum64_smin(dst->r64), amount, &tmp) ||
+ 	    check_mul_overflow(cnum64_smax(dst->r64), amount, &tmp)) {
+ 		scalar_step_reset(dst);
  		return;
  	}
  	/*
- 	 * The above established that `step = dst_reg->step * amount`
- 	 * does not overflow, therefore the base < step invariant holds
- 	 * after assignments below.
+ 	 * The above established that `step = dst->step * |amount|`
+ 	 * does not overflow. For d < 0 the same holds modulo s * -d.
  	 */
- 	dst_reg->base = dst_reg->base * amount;
- 	dst_reg->step = step;
+ 	dst->base = imod(dst->base * amount, step);
+ 	dst->step = step;
  }
  
  /*
@@@ -2073,19 -2019,27 +2019,27 @@@
   * the range where the conversion leaves them unchanged.
   * Call before updating the register's bounds. Requires 0 < bits < 64.
   */
- static void reg_step_check_unsigned(struct bpf_reg_state *reg, u32 bits)
+ static void scalar_step_check_unsigned(struct scalar *s, u32 bits)
  {
- 	if (reg_umax(reg) >= (1ULL << bits))
- 		reg_step_reset(reg);
+ 	if (cnum64_umax(s->r64) >= (1ULL << bits))
+ 		scalar_step_reset(s);
  }
  
- /* This helper doesn't clear reg->id */
- static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
+ /* Nothing is known about the value, or about the variable part of the offset of a pointer. */
+ void scalar_set_unknown(struct scalar *s)
  {
- 	reg->var_off = tnum_const(imm);
- 	reg->r64 = cnum64_from_urange(imm, imm);
- 	reg->r32 = cnum32_from_urange((u32)imm, (u32)imm);
- 	reg_step_reset(reg);
+ 	s->var_off = tnum_unknown;
+ 	s->r64 = CNUM64_UNBOUNDED;
+ 	s->r32 = CNUM32_UNBOUNDED;
+ 	scalar_step_reset(s);
+ }
+ 
+ void scalar_set_const(struct scalar *s, u64 imm)
+ {
+ 	s->var_off = tnum_const(imm);
+ 	s->r64 = cnum64_const(imm);
+ 	s->r32 = cnum32_const(imm);
+ 	scalar_step_reset(s);
  }
  
  /* Mark the unknown part of a register (variable offset or scalar value) as
@@@ -2093,13 -2047,12 +2047,12 @@@
   */
  static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
  {
- 	/* Clear off and union(map_ptr, range) */
- 	memset(((u8 *)reg) + sizeof(reg->type), 0,
- 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
+ 	/* Clear union(map_ptr, range) */
+ 	memset(&reg->raw, 0, sizeof(reg->raw));
  	reg->id = 0;
  	reg->parent_id = 0;
  	reg->map_uid = 0;
- 	___mark_reg_known(reg, imm);
+ 	scalar_set_const(scalar_of(reg), imm);
  }
  
  void bpf_mark_reg_known_scalar(struct bpf_reg_state *reg, u64 imm)
@@@ -2108,10 -2061,10 +2061,10 @@@
  	reg->type = SCALAR_VALUE;
  }
  
- static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
+ static void __mark_scalar32_known(struct scalar *s, u64 imm)
  {
- 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
- 	reg->r32 = cnum32_from_urange((u32)imm, (u32)imm);
+ 	s->var_off = tnum_const_subreg(s->var_off, imm);
+ 	s->r32 = cnum32_const(imm);
  }
  
  /* Mark the 'variable offset' part of a register as zero.  This should be
@@@ -2122,14 -2075,10 +2075,10 @@@ static void __mark_reg_known_zero(struc
  	__mark_reg_known(reg, 0);
  }
  
- static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
+ static void __mark_reg_const_zero(struct bpf_reg_state *reg)
  {
  	__mark_reg_known(reg, 0);
  	reg->type = SCALAR_VALUE;
- 	/* all scalars are assumed imprecise initially (unless unprivileged,
- 	 * in which case everything is forced to be precise)
- 	 */
- 	reg->precise = !env->bpf_capable;
  }
  
  static void mark_reg_known_zero(struct bpf_verifier_env *env,
@@@ -2226,33 -2175,33 +2175,33 @@@ static bool reg_is_init_pkt_pointer(con
  	       tnum_equals_const(reg->var_off, 0);
  }
  
- static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
+ static void __mark_scalar32_unbounded(struct scalar *s)
  {
- 	reg->r32 = CNUM32_UNBOUNDED;
+ 	s->r32 = CNUM32_UNBOUNDED;
  }
  
- static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
+ static void __mark_scalar64_unbounded(struct scalar *s)
  {
- 	reg->r64 = CNUM64_UNBOUNDED;
+ 	s->r64 = CNUM64_UNBOUNDED;
  }
  
- /* Reset the min/max bounds of a register */
- static void __mark_reg_unbounded(struct bpf_reg_state *reg)
+ /* Reset the min/max bounds */
+ static void __mark_scalar_unbounded(struct scalar *s)
  {
- 	__mark_reg64_unbounded(reg);
- 	__mark_reg32_unbounded(reg);
+ 	__mark_scalar64_unbounded(s);
+ 	__mark_scalar32_unbounded(s);
  }
  
- static void reset_reg64_and_tnum(struct bpf_reg_state *reg)
+ static void reset_scalar64_and_tnum(struct scalar *s)
  {
- 	__mark_reg64_unbounded(reg);
- 	reg->var_off = tnum_unknown;
+ 	__mark_scalar64_unbounded(s);
+ 	s->var_off = tnum_unknown;
  }
  
- static void reset_reg32_and_tnum(struct bpf_reg_state *reg)
+ static void reset_scalar32_and_tnum(struct scalar *s)
  {
- 	__mark_reg32_unbounded(reg);
- 	reg->var_off = tnum_unknown;
+ 	__mark_scalar32_unbounded(s);
+ 	s->var_off = tnum_unknown;
  }
  
  static struct cnum32 cnum32_from_tnum(struct tnum tnum)
@@@ -2278,213 -2227,251 +2227,251 @@@ static struct cnum64 cnum64_from_tnum(s
  		return cnum64_from_urange(tnum.value, (tnum.value | tnum.mask));
  }
  
- static void __update_reg32_bounds(struct bpf_reg_state *reg)
+ static void __update_scalar32_bounds(struct scalar *s)
  {
- 	cnum32_intersect_with(&reg->r32, cnum32_from_tnum(reg->var_off));
+ 	cnum32_intersect_with(&s->r32, cnum32_from_tnum(s->var_off));
  }
  
- static void __update_reg64_bounds(struct bpf_reg_state *reg)
+ static void __update_scalar64_bounds(struct scalar *s)
  {
  	u64 tnum_next, tmax;
  	bool umin_in_tnum;
  
- 	cnum64_intersect_with(&reg->r64, cnum64_from_tnum(reg->var_off));
+ 	cnum64_intersect_with(&s->r64, cnum64_from_tnum(s->var_off));
  
  	/* Check if u64 and tnum overlap in a single value */
- 	tnum_next = tnum_step(reg->var_off, reg_umin(reg));
- 	umin_in_tnum = (reg_umin(reg) & ~reg->var_off.mask) == reg->var_off.value;
- 	tmax = reg->var_off.value | reg->var_off.mask;
- 	if (umin_in_tnum && tnum_next > reg_umax(reg)) {
+ 	tnum_next = tnum_step(s->var_off, cnum64_umin(s->r64));
+ 	umin_in_tnum = (cnum64_umin(s->r64) & ~s->var_off.mask) == s->var_off.value;
+ 	tmax = s->var_off.value | s->var_off.mask;
+ 	if (umin_in_tnum && tnum_next > cnum64_umax(s->r64)) {
  		/* The u64 range and the tnum only overlap in umin.
  		 * u64:  ---[xxxxxx]-----
  		 * tnum: --xx----------x-
  		 */
- 		___mark_reg_known(reg, reg_umin(reg));
+ 		scalar_set_const(s, cnum64_umin(s->r64));
  	} else if (!umin_in_tnum && tnum_next == tmax) {
  		/* The u64 range and the tnum only overlap in the maximum value
  		 * represented by the tnum, called tmax.
  		 * u64:  ---[xxxxxx]-----
  		 * tnum: xx-----x--------
  		 */
- 		___mark_reg_known(reg, tmax);
- 	} else if (!umin_in_tnum && tnum_next <= reg_umax(reg) &&
- 		   tnum_step(reg->var_off, tnum_next) > reg_umax(reg)) {
+ 		scalar_set_const(s, tmax);
+ 	} else if (!umin_in_tnum && tnum_next <= cnum64_umax(s->r64) &&
+ 		   tnum_step(s->var_off, tnum_next) > cnum64_umax(s->r64)) {
  		/* The u64 range and the tnum only overlap in between umin
  		 * (excluded) and umax.
  		 * u64:  ---[xxxxxx]-----
  		 * tnum: xx----x-------x-
  		 */
- 		___mark_reg_known(reg, tnum_next);
+ 		scalar_set_const(s, tnum_next);
  	}
  }
  
- static void __update_reg_bounds(struct bpf_reg_state *reg)
+ static void __update_scalar_bounds(struct scalar *s)
  {
- 	__update_reg32_bounds(reg);
- 	__update_reg64_bounds(reg);
+ 	__update_scalar32_bounds(s);
+ 	__update_scalar64_bounds(s);
  }
  
- static void deduce_bounds_32_from_64(struct bpf_reg_state *reg)
+ static void deduce_bounds_32_from_64(struct scalar *s)
  {
- 	cnum32_intersect_with(&reg->r32, cnum32_from_cnum64(reg->r64));
+ 	cnum32_intersect_with(&s->r32, cnum32_from_cnum64(s->r64));
  }
  
- static void deduce_bounds_64_from_32(struct bpf_reg_state *reg)
+ static void deduce_bounds_64_from_32(struct scalar *s)
  {
- 	reg->r64 = cnum64_cnum32_intersect(reg->r64, reg->r32);
+ 	s->r64 = cnum64_cnum32_intersect(s->r64, s->r32);
  }
  
- static void __reg_deduce_bounds(struct bpf_reg_state *reg)
+ static void __scalar_deduce_bounds(struct scalar *s)
  {
- 	deduce_bounds_32_from_64(reg);
- 	deduce_bounds_64_from_32(reg);
+ 	deduce_bounds_32_from_64(s);
+ 	deduce_bounds_64_from_32(s);
  }
  
  /* Attempts to improve var_off based on unsigned min/max information */
- static void __reg_bound_offset(struct bpf_reg_state *reg)
+ static void __scalar_bound_offset(struct scalar *s)
  {
- 	struct tnum var64_off = tnum_intersect(reg->var_off,
- 					       tnum_range(reg_umin(reg),
- 							  reg_umax(reg)));
+ 	struct tnum var64_off = tnum_intersect(s->var_off,
+ 					       tnum_range(cnum64_umin(s->r64),
+ 							  cnum64_umax(s->r64)));
  	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
- 					       tnum_range(reg_u32_min(reg),
- 							  reg_u32_max(reg)));
+ 					       tnum_range(cnum32_umin(s->r32),
+ 							  cnum32_umax(s->r32)));
  	u32 trailing_zero_bits;
- 	u16 base = reg->base;
- 	u16 step = reg->step;
+ 	u16 base = s->base;
+ 	u16 step = s->step;
  
- 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
+ 	s->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
  
  	if (base == 0)
  		trailing_zero_bits = count_trailing_zeros(step);
  	else
  		trailing_zero_bits = min(count_trailing_zeros(base),
  					 count_trailing_zeros(step));
- 	reg->var_off = tnum_and(reg->var_off, tnum_const(~0ULL << trailing_zero_bits));
+ 	s->var_off = tnum_and(s->var_off, tnum_const(~0ULL << trailing_zero_bits));
  }
  
- static void __update_bounds_from_step(struct bpf_reg_state *reg)
+ static void __update_bounds_from_step(struct scalar *s)
  {
- 	reg->r64 = cnum64_intersect_linear(reg->r64, reg->base, reg->step);
- 	deduce_bounds_32_from_64(reg);
+ 	s->r64 = cnum64_intersect_linear(s->r64, s->base, s->step);
+ 	deduce_bounds_32_from_64(s);
  }
  
- static bool range_bounds_violation(struct bpf_reg_state *reg);
+ static bool range_bounds_violation(const struct scalar *s);
  
- static void reg_bounds_sync(struct bpf_reg_state *reg)
+ void scalar_bounds_sync(struct scalar *s)
  {
  	/* If the input reg_state is invalid, we can exit early */
- 	if (range_bounds_violation(reg))
+ 	if (range_bounds_violation(s))
  		return;
  	/* We might have learned new bounds from the var_off. */
- 	__update_reg_bounds(reg);
+ 	__update_scalar_bounds(s);
  	/* We might have learned something about the sign bit. */
- 	__reg_deduce_bounds(reg);
- 	__reg_deduce_bounds(reg);
+ 	__scalar_deduce_bounds(s);
+ 	__scalar_deduce_bounds(s);
  	/* We might have learned some bits from the bounds. */
- 	__reg_bound_offset(reg);
+ 	__scalar_bound_offset(s);
  	/* Intersecting with the old var_off might have improved our bounds
  	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
  	 * then new var_off is (0; 0x7f...fc) which improves our umax.
  	 */
- 	__update_reg_bounds(reg);
+ 	__update_scalar_bounds(s);
  	/*
  	 * Both tnum and base+step define a sequence of points,
  	 * potentially w/o intersection, or intersecting after N
  	 * tnum_step()'s, where N can be large. On the other hand,
  	 * step+base *must* be in sync with r64 in order for
  	 * array traversal logic starting at reg_smin() to be sound.
- 	 * Hence, place this as a final step in the reg_bounds_sync().
+ 	 * Hence, place this as a final step in the scalar_bounds_sync().
  	 */
- 	__update_bounds_from_step(reg);
+ 	__update_bounds_from_step(s);
  }
  
- static bool const_tnum_range_mismatch(struct bpf_reg_state *reg)
+ static void reg_bounds_sync(struct bpf_reg_state *reg)
  {
- 	if (!tnum_is_const(reg->var_off))
+ 	scalar_bounds_sync(scalar_of(reg));
+ }
+ 
+ static bool const_tnum_range_mismatch(const struct scalar *s)
+ {
+ 	if (!tnum_is_const(s->var_off))
  		return false;
  
- 	return !cnum64_is_const(reg->r64) || reg->r64.base != reg->var_off.value;
+ 	return !cnum64_is_const(s->r64) || s->r64.base != s->var_off.value;
  }
  
- static bool const_tnum_range_mismatch_32(struct bpf_reg_state *reg)
+ static bool const_tnum_range_mismatch_32(const struct scalar *s)
  {
- 	if (!tnum_subreg_is_const(reg->var_off))
+ 	if (!tnum_subreg_is_const(s->var_off))
  		return false;
  
- 	return !cnum32_is_const(reg->r32) || reg->r32.base != tnum_subreg(reg->var_off).value;
+ 	return !cnum32_is_const(s->r32) || s->r32.base != tnum_subreg(s->var_off).value;
  }
  
- static bool range_bounds_violation(struct bpf_reg_state *reg)
+ static bool range_bounds_violation(const struct scalar *s)
  {
- 	return cnum32_is_empty(reg->r32) || cnum64_is_empty(reg->r64);
+ 	return cnum32_is_empty(s->r32) || cnum64_is_empty(s->r64);
  }
  
+ /* Do @t and [min, max] overlap: is a member of @t in the range? */
+ static bool tnum_overlaps_urange(struct tnum t, u64 min, u64 max)
+ {
+ 	u64 tnum_next = tnum_step(t, min);
+ 
+ 	return (min & ~t.mask) == t.value || (tnum_next > min && tnum_next <= max);
+ }
+ 
+ /* The same for the cnum [@base, @base + @size]. It wraps around at @ut_max. */
+ static bool tnum_overlaps_cnum(struct tnum t, u64 base, u64 size, u64 ut_max)
+ {
+ 	u64 end = (base + size) & ut_max;
+ 
+ 	if (base <= end)
+ 		return tnum_overlaps_urange(t, base, end);
+ 	return tnum_overlaps_urange(t, base, ut_max) || tnum_overlaps_urange(t, 0, end);
+ }
+ 
+ /*
+  * A range and var_off don't overlap. reg_bounds_sync() compares var_off with umin and umax: it
+  * doesn't see that [-2, 1], which crosses 0, has no member with 5 in its low three bits.
+  */
+ static bool scalar_is_empty(const struct scalar *s)
+ {
+ 	return range_bounds_violation(s) ||
+ 	       !tnum_overlaps_cnum(s->var_off, s->r64.base, s->r64.size, U64_MAX) ||
+ 	       !tnum_overlaps_cnum(tnum_subreg(s->var_off), s->r32.base, s->r32.size,
+ 				   U32_MAX);
+ }
+ 
+ static bool reg_is_empty(const struct bpf_reg_state *reg)
+ {
+ 	return scalar_is_empty(scalar_of(reg));
+ }
+ 
+ /*
+  * var_off, r64, r32 and the line base + step * k are a product that reg_bounds_sync() doesn't
+  * reduce to the end. The verifier can take an infeasible path with a register that has no value
+  * while each part looks sane, and a later insn finds it out. That is not a verifier bug: no WARN,
+  * a line in the log, the ranges are forgotten. A malformed base or step is a bug.
+  */
  static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
  				   struct bpf_reg_state *reg, const char *ctx)
  {
+ 	struct scalar *s = scalar_of(reg);
  	const char *msg;
  
- 	if (range_bounds_violation(reg)) {
+ 	if (range_bounds_violation(s)) {
  		msg = "range bounds violation";
  		goto out;
  	}
  
- 	if (const_tnum_range_mismatch(reg)) {
+ 	if (const_tnum_range_mismatch(s)) {
  		msg = "const tnum out of sync with range bounds";
  		goto out;
  	}
  
- 	if (const_tnum_range_mismatch_32(reg)) {
+ 	if (const_tnum_range_mismatch_32(s)) {
  		msg = "const subreg tnum out of sync with range bounds";
  		goto out;
  	}
  
- 	if (reg->step == 0 || reg->base >= reg->step) {
+ 	if (verifier_bug_if(reg->step == 0 || reg->base >= reg->step, env, "%s", ctx)) {
  		msg = "invalid base/step";
  		goto out;
  	}
  
  	return 0;
  out:
- 	verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s r64={.base=%#llx, .size=%#llx} "
- 		     "r32={.base=%#x, .size=%#x} var_off=(%#llx, %#llx) step=%u+%u",
- 		     ctx, msg,
- 		     reg->r64.base, reg->r64.size,
- 		     reg->r32.base, reg->r32.size,
- 		     reg->var_off.value, reg->var_off.mask,
- 		     reg->base, reg->step);
+ 	if (env->test_reg_invariants)
+ 		bpf_note_bug(env);
+ 	verbose(env, "REG INVARIANTS VIOLATION (%s): %s r64={.base=%#llx, .size=%#llx} "
+ 		"r32={.base=%#x, .size=%#x} var_off=(%#llx, %#llx) step=%u+%u\n",
+ 		ctx, msg,
+ 		reg->r64.base, reg->r64.size,
+ 		reg->r32.base, reg->r32.size,
+ 		reg->var_off.value, reg->var_off.mask,
+ 		reg->base, reg->step);
  	if (env->test_reg_invariants)
  		return -EFAULT;
- 	__mark_reg_unbounded(reg);
- 	reg_step_reset(reg);
+ 	env->cur_state->infeasible = true;
+ 	__mark_scalar_unbounded(s);
+ 	scalar_step_reset(s);
  	return 0;
  }
  
  /* Mark a register as having a completely unknown (scalar) value. */
- void bpf_mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
+ void bpf_mark_reg_unknown(struct bpf_reg_state *reg)
  {
  	memset(reg, 0, sizeof(*reg));
  	reg->type = SCALAR_VALUE;
- 	reg->var_off = tnum_unknown;
- 	__mark_reg_unbounded(reg);
- 	reg_step_reset(reg);
- }
- 
- /* Mark a register as having a completely unknown (scalar) value,
-  * initialize .precise as true when not bpf capable.
-  */
- static void __mark_reg_unknown(const struct bpf_verifier_env *env,
- 			       struct bpf_reg_state *reg)
- {
- 	bpf_mark_reg_unknown_imprecise(reg);
- 	reg->precise = !env->bpf_capable;
+ 	scalar_set_unknown(scalar_of(reg));
  }
  
  static void mark_reg_unknown(struct bpf_verifier_env *env,
  			     struct bpf_reg_state *regs, u32 regno)
  {
- 	__mark_reg_unknown(env, regs + regno);
+ 	bpf_mark_reg_unknown(regs + regno);
  }
  
  static int __mark_reg_s32_range(struct bpf_verifier_env *env,
@@@ -2510,7 -2497,7 +2497,7 @@@
  void bpf_mark_reg_not_init(const struct bpf_verifier_env *env,
  			   struct bpf_reg_state *reg)
  {
- 	__mark_reg_unknown(env, reg);
+ 	bpf_mark_reg_unknown(reg);
  	reg->type = NOT_INIT;
  }
  
@@@ -2530,7 -2517,7 +2517,7 @@@ static int mark_btf_ld_reg(struct bpf_v
  		regs[regno].btf = btf;
  		regs[regno].btf_id = btf_id;
  		if (type_may_be_null(flag))
- 			regs[regno].id = ++env->id_gen;
+ 			regs[regno].id = bpf_new_id(env);
  		return 0;
  	case PTR_TO_MEM:
  		mark_reg_known_zero(env, regs, regno);
@@@ -2589,31 -2576,22 +2576,22 @@@ static struct bpf_verifier_state *push_
  	struct bpf_verifier_stack_elem *elem;
  	struct bpf_func_state *frame;
  
- 	elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT);
+ 	elem = kzalloc_obj(struct bpf_verifier_stack_elem, BPF_VERIFIER_GFP);
  	if (!elem)
  		return ERR_PTR(-ENOMEM);
  
  	elem->insn_idx = insn_idx;
  	elem->prev_insn_idx = prev_insn_idx;
  	elem->next = env->head;
- 	elem->log_pos = env->log.end_pos;
- 	elem->diag_log_pos = bpf_diag_event_log_save(env);
  	env->head = elem;
- 	env->stack_size++;
- 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
- 		verbose(env,
- 			"The sequence of %d jumps is too complex for async cb.\n",
- 			env->stack_size);
- 		return ERR_PTR(-E2BIG);
- 	}
  	/* Unlike push_stack() do not bpf_copy_verifier_state().
  	 * The caller state doesn't matter.
  	 * This is async callback. It starts in a fresh stack.
  	 * Initialize it similar to do_check_common().
  	 */
- 	elem->st.branches = 1;
  	elem->st.in_sleepable = is_sleepable;
- 	frame = kzalloc_obj(*frame, GFP_KERNEL_ACCOUNT);
+ 	elem->st.suspect_loops = env->cur_state->suspect_loops;
+ 	frame = kzalloc_obj(*frame, BPF_VERIFIER_GFP);
  	if (!frame)
  		return ERR_PTR(-ENOMEM);
  	init_func_state(env, frame,
@@@ -2656,31 -2634,14 +2634,14 @@@ int bpf_find_subprog(struct bpf_verifie
  	return p - env->subprog_info;
  }
  
- static int add_subprog(struct bpf_verifier_env *env, int off)
+ static int add_subprog(struct bpf_verifier_env *env, unsigned long *starts, int off)
  {
- 	struct bpf_subprog_info *subprog = env->subprog_info;
- 	int insn_cnt = env->prog->len;
- 	int i;
- 
- 	if (off >= insn_cnt || off < 0) {
+ 	if (off >= env->prog->len || off < 0) {
  		verbose(env, "call to invalid destination\n");
  		return -EINVAL;
  	}
- 	i = bpf_find_subprog(env, off);
- 	if (i >= 0)
- 		return i;
- 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
- 		verbose(env, "too many subprograms\n");
- 		return -E2BIG;
- 	}
- 	/*
- 	 * Determine subprog starts. The end is one before the next starts.
- 	 * The array stays sorted: subprogs that start after 'off' move up.
- 	 */
- 	for (i = env->subprog_cnt++; i > 0 && subprog[i - 1].start > off; i--)
- 		subprog[i] = subprog[i - 1];
- 	subprog[i] = (struct bpf_subprog_info){ .start = off, .exit_idx = U32_MAX };
- 	return i;
+ 	__set_bit(off, starts);
+ 	return 0;
  }
  
  static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
@@@ -2745,48 -2706,28 +2706,28 @@@
  	return ret;
  }
  
- #define MAX_KFUNC_BTFS	256
- 
  struct bpf_kfunc_btf {
  	struct btf *btf;
  	struct module *module;
- 	u16 offset;
  };
  
  struct bpf_kfunc_btf_tab {
- 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
+ 	struct bpf_kfunc_btf *descs;
  	u32 nr_descs;
  };
  
- static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
+ /* The key of env->kfunc_index. The BTF of a module has func_id 0. */
+ static u64 kfunc_key(u32 func_id, u16 offset, bool specialized)
  {
- 	const struct bpf_kfunc_desc *d0 = a;
- 	const struct bpf_kfunc_desc *d1 = b;
- 
- 	/* func_id is not greater than BTF_MAX_TYPE */
- 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
- }
- 
- static int kfunc_btf_cmp_by_off(const void *a, const void *b)
- {
- 	const struct bpf_kfunc_btf *d0 = a;
- 	const struct bpf_kfunc_btf *d1 = b;
- 
- 	return d0->offset - d1->offset;
+ 	return func_id | (u64)offset << 32 | (u64)specialized << 48;
  }
  
  static struct bpf_kfunc_desc *
- find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
+ find_kfunc_desc(struct bpf_verifier_env *env, u32 func_id, u16 offset)
  {
- 	struct bpf_kfunc_desc desc = {
- 		.func_id = func_id,
- 		.offset = offset,
- 	};
- 	struct bpf_kfunc_desc_tab *tab;
+ 	int i = bpf_index_find(&env->kfunc_index, kfunc_key(func_id, offset, false));
  
- 	tab = prog->aux->kfunc_tab;
- 	return bsearch(&desc, tab->descs, tab->nr_base_descs,
- 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
+ 	return func_id && i >= 0 ? &env->prog->aux->kfunc_tab->descs[i] : NULL;
  }
  
  int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
@@@ -2886,50 -2827,38 +2827,38 @@@ static struct btf *fd_array_get_btf(str
  static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
  					 s16 offset)
  {
- 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
- 	struct bpf_kfunc_btf_tab *tab;
+ 	struct bpf_kfunc_btf_tab *tab = env->prog->aux->kfunc_btf_tab;
+ 	int i = bpf_index_find(&env->kfunc_index, kfunc_key(0, offset, false));
  	struct bpf_kfunc_btf *b;
  	struct module *mod;
  	struct btf *btf;
  
- 	tab = env->prog->aux->kfunc_btf_tab;
- 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
- 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
- 	if (!b) {
- 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
- 			verbose(env, "too many different module BTFs\n");
- 			return ERR_PTR(-E2BIG);
- 		}
+ 	if (i >= 0)
+ 		return tab->descs[i].btf;
  
- 		btf = fd_array_get_btf(env, offset);
- 		if (IS_ERR(btf))
- 			return btf;
- 		if (!btf_is_module(btf)) {
- 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
- 			btf_put(btf);
- 			return ERR_PTR(-EINVAL);
- 		}
+ 	b = bpf_table_next(tab->descs, tab->nr_descs);
+ 	if (!b)
+ 		return ERR_PTR(-ENOMEM);
  
- 		mod = btf_try_get_module(btf);
- 		if (!mod) {
- 			btf_put(btf);
- 			return ERR_PTR(-ENXIO);
- 		}
- 
- 		b = &tab->descs[tab->nr_descs++];
- 		b->btf = btf;
- 		b->module = mod;
- 		b->offset = offset;
- 
- 		/* sort() reorders entries by value, so b may no longer point
- 		 * to the right entry after this
- 		 */
- 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
- 		     kfunc_btf_cmp_by_off, NULL);
- 	} else {
- 		btf = b->btf;
+ 	btf = fd_array_get_btf(env, offset);
+ 	if (IS_ERR(btf))
+ 		return btf;
+ 	if (!btf_is_module(btf)) {
+ 		verbose(env, "BTF fd for kfunc is not a module BTF\n");
+ 		btf_put(btf);
+ 		return ERR_PTR(-EINVAL);
  	}
  
+ 	mod = btf_try_get_module(btf);
+ 	if (!mod) {
+ 		btf_put(btf);
+ 		return ERR_PTR(-ENXIO);
+ 	}
+ 
+ 	b->btf = btf;
+ 	b->module = mod;
+ 	if (bpf_index_add(&env->kfunc_index, kfunc_key(0, offset, false), tab->nr_descs++))
+ 		return ERR_PTR(-ENOMEM);
  	return btf;
  }
  
@@@ -2942,6 -2871,7 +2871,7 @@@ void bpf_free_kfunc_btf_tab(struct bpf_
  		module_put(tab->descs[tab->nr_descs].module);
  		btf_put(tab->descs[tab->nr_descs].btf);
  	}
+ 	kvfree(tab->descs);
  	kfree(tab);
  }
  
@@@ -2963,22 -2893,14 +2893,14 @@@ static struct btf *find_kfunc_desc_btf(
  
  static struct btf *find_kfunc_desc_btf_cached(struct bpf_verifier_env *env, s16 offset)
  {
- 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
- 	struct bpf_kfunc_btf_tab *tab;
- 	struct bpf_kfunc_btf *b;
+ 	int i = bpf_index_find(&env->kfunc_index, kfunc_key(0, offset, false));
  
  	if (!offset)
  		return btf_vmlinux ?: ERR_PTR(-ENOENT);
  	if (offset < 0)
  		return ERR_PTR(-EINVAL);
  
- 	tab = env->prog->aux->kfunc_btf_tab;
- 	if (!tab)
- 		return ERR_PTR(-ENOENT);
- 
- 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
- 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
- 	return b ? b->btf : ERR_PTR(-ENOENT);
+ 	return i >= 0 ? env->prog->aux->kfunc_btf_tab->descs[i].btf : ERR_PTR(-ENOENT);
  }
  
  #define KF_IMPL_SUFFIX "_impl"
@@@ -3112,7 -3034,7 +3034,7 @@@ int bpf_add_kfunc_call(struct bpf_verif
  			return -EINVAL;
  		}
  
- 		tab = kzalloc_obj(*tab, GFP_KERNEL_ACCOUNT);
+ 		tab = kzalloc_obj(*tab, BPF_VERIFIER_GFP);
  		if (!tab)
  			return -ENOMEM;
  		prog_aux->kfunc_tab = tab;
@@@ -3130,25 -3052,15 +3052,15 @@@
  		return 0;
  
  	if (!btf_tab && offset) {
- 		btf_tab = kzalloc_obj(*btf_tab, GFP_KERNEL_ACCOUNT);
+ 		btf_tab = kzalloc_obj(*btf_tab, BPF_VERIFIER_GFP);
  		if (!btf_tab)
  			return -ENOMEM;
  		prog_aux->kfunc_btf_tab = btf_tab;
  	}
  
- 	if (find_kfunc_desc(env->prog, func_id, offset))
+ 	if (find_kfunc_desc(env, func_id, offset))
  		return 0;
  
- 	if (tab->nr_base_descs == MAX_KFUNC_DESCS) {
- 		verbose(env, "too many different kernel function calls\n");
- 		return -E2BIG;
- 	}
- 	if (tab->nr_descs != tab->nr_base_descs) {
- 		verifier_bug(env, "unexpected specialized func desc found (%d descs, %d base descs)",
- 			     tab->nr_descs, tab->nr_base_descs);
- 		return -EFAULT;
- 	}
- 
  	err = fetch_kfunc_meta(env, func_id, offset, &kfunc);
  	if (err)
  		return err;
@@@ -3188,12 -3100,9 +3100,9 @@@
  	meta.func_name = kfunc.name;
  	meta.kfunc_flags = kfunc.flags ? *kfunc.flags : 0;
  
- 	tab = krealloc(tab, struct_size(tab, descs, tab->nr_descs + 1), GFP_KERNEL_ACCOUNT);
- 	if (!tab)
+ 	desc = bpf_table_next(tab->descs, tab->nr_descs);
+ 	if (!desc)
  		return -ENOMEM;
- 	prog_aux->kfunc_tab = tab;
- 
- 	desc = &tab->descs[tab->nr_descs];
  	memset(desc, 0, sizeof(*desc));
  
  	err = gen_kfunc_arg_proto(env, &meta, &func_model, &desc->proto);
@@@ -3204,24 -3113,22 +3113,22 @@@
  	desc->offset = offset;
  	desc->addr = addr;
  	desc->func_model = func_model;
- 	tab->nr_descs++;
- 	tab->nr_base_descs++;
- 	sort(tab->descs, tab->nr_base_descs, sizeof(tab->descs[0]),
- 	     kfunc_desc_cmp_by_id_off, NULL);
- 	return 0;
+ 	return bpf_index_add(&env->kfunc_index, kfunc_key(func_id, offset, false), tab->nr_descs++);
  }
  
  static int add_subprogs(struct bpf_verifier_env *env)
  {
- 	struct bpf_subprog_info *subprog = env->subprog_info;
- 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
+ 	int i, cnt, ret, insn_cnt = env->prog->len, ex_cb_insn;
+ 	unsigned long *starts __free(kvfree) = NULL;
  	struct bpf_insn *insn = env->prog->insnsi;
  	const char *operation, *suggestion;
+ 	struct bpf_subprog_info *subprog;
  
+ 	starts = kvcalloc(BITS_TO_LONGS(insn_cnt), sizeof(long), BPF_VERIFIER_GFP);
+ 	if (!starts)
+ 		return -ENOMEM;
  	/* Add entry function. */
- 	ret = add_subprog(env, 0);
- 	if (ret)
- 		return ret;
+ 	__set_bit(0, starts);
  
  	for (i = 0; i < insn_cnt; i++, insn++) {
  		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
@@@ -3243,7 -3150,7 +3150,7 @@@
  			return -EPERM;
  		}
  
- 		ret = add_subprog(env, i + insn->imm + 1);
+ 		ret = add_subprog(env, starts, i + insn->imm + 1);
  		if (ret < 0)
  			return ret;
  	}
@@@ -3258,7 -3165,7 +3165,7 @@@
  		struct bpf_prog_aux *aux = env->prog->aux;
  
  		for (i = 1; i < aux->func_info_cnt; i++) {
- 			ret = add_subprog(env, aux->func_info[i].insn_off);
+ 			ret = add_subprog(env, starts, aux->func_info[i].insn_off);
  			if (ret < 0)
  				return ret;
  		}
@@@ -3272,23 -3179,32 +3179,32 @@@
  	/* If ex_cb_insn > 0, this means that the main program has a subprog
  	 * marked using BTF decl tag to serve as the exception callback.
  	 */
- 	if (ex_cb_insn) {
- 		ret = add_subprog(env, ex_cb_insn);
- 		if (ret < 0)
- 			return ret;
- 		for (i = 1; i < env->subprog_cnt; i++) {
- 			if (env->subprog_info[i].start != ex_cb_insn)
- 				continue;
- 			env->exception_callback_subprog = i;
- 			bpf_mark_subprog_exc_cb(env, i);
- 			break;
- 		}
+ 	ret = add_subprog(env, starts, ex_cb_insn);
+ 	if (ret < 0)
+ 		return ret;
+ 
+ 	/* + 2 for the fake and the hidden subprogs */
+ 	cnt = bitmap_weight(starts, insn_cnt);
+ 	subprog = env->subprog_info = kvcalloc(cnt + 2, sizeof(*subprog), BPF_VERIFIER_GFP);
+ 	env->subprog_topo_order = kvcalloc(cnt, sizeof(int), BPF_VERIFIER_GFP);
+ 	if (!subprog || !env->subprog_topo_order)
+ 		return -ENOMEM;
+ 
+ 	/* Determine subprog starts. The end is one before the next starts. */
+ 	for_each_set_bit(i, starts, insn_cnt) {
+ 		subprog[env->subprog_cnt].start = i;
+ 		subprog[env->subprog_cnt++].exit_idx = U32_MAX;
  	}
  
  	/* Add a fake 'exit' subprog which could simplify subprog iteration
  	 * logic. 'subprog_cnt' should not be increased.
  	 */
- 	subprog[env->subprog_cnt].start = insn_cnt;
+ 	subprog[cnt].start = insn_cnt;
+ 
+ 	if (ex_cb_insn) {
+ 		env->exception_callback_subprog = bpf_find_subprog(env, ex_cb_insn);
+ 		bpf_mark_subprog_exc_cb(env, env->exception_callback_subprog);
+ 	}
  
  	if (env->log.level & BPF_LOG_LEVEL2)
  		for (i = 0; i < env->subprog_cnt; i++)
@@@ -3315,7 -3231,7 +3231,7 @@@ static int add_kfuncs(struct bpf_verifi
  			return -EPERM;
  		}
  
- 		ret = bpf_add_kfunc_call(env, insn->imm, insn->off);
+ 		ret = bpf_must_abort() ? -EINTR : bpf_add_kfunc_call(env, insn->imm, insn->off);
  		if (ret < 0)
  			return ret;
  	}
@@@ -3323,7 -3239,8 +3239,8 @@@
  	return 0;
  }
  
- static void find_subprog_properties(struct bpf_verifier_env *env)
+ /* Before the main pass all insns count, after it those that were 'seen' */
+ static void find_subprog_properties(struct bpf_verifier_env *env, bool seen)
  {
  	struct bpf_subprog_info *subprog = env->subprog_info;
  	struct bpf_insn *insn = env->prog->insnsi;
@@@ -3332,10 -3249,15 +3249,15 @@@
  	for (cur_subprog = 0; cur_subprog < env->subprog_cnt; cur_subprog++) {
  		int i;
  
+ 		subprog[cur_subprog].has_tail_call = false;
+ 		subprog[cur_subprog].tail_call_reachable = false;
+ 		subprog[cur_subprog].has_ld_abs = false;
  		for (i = subprog[cur_subprog].start;
  		     i < subprog[cur_subprog + 1].start; i++) {
  			u8 code = insn[i].code;
  
+ 			if (seen && !env->insn_aux_data[i].seen)
+ 				continue;
  			if (code == (BPF_JMP | BPF_CALL) &&
  			    insn[i].src_reg == 0 &&
  			    insn[i].imm == BPF_FUNC_tail_call) {
@@@ -3416,37 -3338,22 +3338,22 @@@ next
  /*
   * The callee of callx is known to the main verification pass only, which
   * records the 'caller' -> 'callee' edge of the call graph for the checks
-  * that follow it: absence of recursion and the maximum stack depth.
+  * that follow it: recursion that was not seen coming and the maximum stack depth.
   */
  static int record_callx_edge(struct bpf_verifier_env *env, int caller, int callee)
  {
- 	u32 cnt = env->subprog_cnt;
+ 	u32 *first = &env->subprog_info[caller].callx_edge, cnt = env->callx_index.cnt;
+ 	u64 key = (u64)caller << 32 | callee;
  
- 	if (!env->callx_edges) {
- 		env->callx_edges = kvcalloc(BITS_TO_LONGS(cnt * cnt), sizeof(long),
- 					    GFP_KERNEL_ACCOUNT);
- 		if (!env->callx_edges)
- 			return -ENOMEM;
- 	}
- 	__set_bit(caller * cnt + callee, env->callx_edges);
+ 	if (bpf_index_find(&env->callx_index, key) >= 0)
+ 		return 0;
+ 	if (!bpf_table_next(env->callx_edges, cnt) || bpf_index_add(&env->callx_index, key, cnt))
+ 		return -ENOMEM;
+ 	env->callx_edges[cnt] = (struct bpf_callx_edge){ callee, *first };
+ 	*first = cnt + 1;
  	return 0;
  }
  
- /*
-  * Return the first subprog with the number >= 'from' that 'caller' calls
-  * via callx, or -1 when there is none.
-  */
- static int next_callx_callee(struct bpf_verifier_env *env, int caller, int from)
- {
- 	u32 cnt = env->subprog_cnt;
- 	unsigned long bit, end = (caller + 1) * cnt;
- 
- 	if (!env->callx_edges || from >= cnt)
- 		return -1;
- 	bit = find_next_bit(env->callx_edges, end, caller * cnt + from);
- 	return bit < end ? bit - caller * cnt : -1;
- }
- 
  /*
   * 'call foo; unwind_goto pad' goes to the pad when foo left with unwind_exit.
   * JITs don't emit a branch for it. unwind_exit finds the pad by its return
@@@ -3458,7 -3365,17 +3365,17 @@@ static int check_unwind_insns(struct bp
  	bool seen = false;
  	int i;
  
+ 	for (i = 0; i < env->subprog_cnt; i++)
+ 		env->subprog_info[i].bail_insn = -1;
+ 
  	for (i = 0; i < env->prog->len; i++, insn++) {
+ 		if (bpf_is_ldimm64(insn)) {
+ 			i++;
+ 			insn++;
+ 			continue;
+ 		}
+ 		if (insn->code == (BPF_JMP | BPF_EXIT))
+ 			bpf_find_containing_subprog(env, i)->bail_insn = i;
  		if (bpf_is_unwind_exit(insn)) {
  			bpf_find_containing_subprog(env, i)->can_unwind = true;
  			seen = true;
@@@ -3494,103 -3411,49 +3411,49 @@@
   * the current subprog to discover callees (direct subprogs and sync
   * callbacks).
   *
-  * The callees of callx are not known before the main verification pass.
-  * When callx is used the sort is repeated after it with the recorded callx
-  * edges added to the call graph to reject recursion through indirect calls.
+  * The callees of callx are not known before the main verification pass: callx
+  * is no edge here. The order within a cycle is arbitrary. For recursion see
+  * mark_recursive_subprogs() and check_recursion().
   */
  static int sort_subprogs_topo(struct bpf_verifier_env *env)
  {
  	struct bpf_subprog_info *si = env->subprog_info;
  	int *insn_postorder = env->cfg.insn_postorder;
  	struct bpf_insn *insn = env->prog->insnsi;
- 	int cnt = env->subprog_cnt;
- 	int *dfs_stack = NULL;
- 	int top = 0, order = 0;
- 	int i, ret = 0;
- 	u8 *color = NULL;
+ 	int cnt = env->subprog_cnt, i, j, idx, ret;
+ 	struct bpf_call_graph cg;
  
- 	color = kvzalloc_objs(*color, cnt, GFP_KERNEL_ACCOUNT);
- 	dfs_stack = kvmalloc_objs(*dfs_stack, cnt, GFP_KERNEL_ACCOUNT);
- 	if (!color || !dfs_stack) {
- 		ret = -ENOMEM;
- 		goto out;
- 	}
- 
- 	/*
- 	 * DFS post-order traversal.
- 	 * Color values: 0 = unvisited, 1 = on stack, 2 = done.
- 	 */
+ 	ret = bpf_call_graph_init(&cg, cnt);
  	for (i = 0; i < cnt; i++) {
- 		if (color[i])
- 			continue;
- 		color[i] = 1;
- 		dfs_stack[top++] = i;
- 
- 		while (top > 0) {
- 			int cur = dfs_stack[top - 1];
- 			int po_start = si[cur].postorder_start;
- 			int po_end = si[cur + 1].postorder_start;
- 			bool pushed = false;
- 			int j;
- 
- 			for (j = po_start; j < po_end; j++) {
- 				int idx = insn_postorder[j];
- 				int callee;
- 
- 				if (bpf_is_callx(&insn[idx])) {
- 					/* find a callee that is not explored yet */
- 					callee = -1;
- 					do {
- 						callee = next_callx_callee(env, cur, callee + 1);
- 					} while (callee >= 0 && color[callee] == 2);
- 					if (callee < 0)
- 						continue;
- 				} else if (bpf_pseudo_call(&insn[idx]) || bpf_pseudo_func(&insn[idx])) {
- 					callee = bpf_find_subprog(env, idx + insn[idx].imm + 1);
- 					if (callee < 0) {
- 						ret = -EFAULT;
- 						goto out;
- 					}
- 				} else {
- 					continue;
- 				}
- 				if (color[callee] == 2)
- 					continue;
- 				if (color[callee] == 1) {
- 					if (bpf_pseudo_func(&insn[idx]))
- 						continue;
- 					verbose(env, "recursive call from %s() to %s()\n",
- 						bpf_subprog_name(env, cur),
- 						bpf_subprog_name(env, callee));
- 					bpf_diag_program_structure(
- 						env, idx, "recursive subprogram call",
- 						"Rewrite the recursion as an explicit bounded loop, or split the logic so subprogram calls do not form a cycle.",
- 						"This bpf2bpf call would make the subprogram call graph recursive. "
- 						"The verifier requires a finite, acyclic call graph so it can bound stack depth and analysis.");
- 					ret = -EINVAL;
- 					goto out;
- 				}
- 				color[callee] = 1;
- 				dfs_stack[top++] = callee;
- 				pushed = true;
+ 		for (j = si[i].postorder_start; j < si[i + 1].postorder_start && !ret; j++) {
+ 			idx = insn_postorder[j];
+ 			if (!bpf_pseudo_call(&insn[idx]) && !bpf_pseudo_func(&insn[idx]))
+ 				continue;
+ 			/*
+ 			 * The call that is its own target never returns. It is
+ 			 * also what libbpf leaves in place of a call that it
+ 			 * could not resolve.
+ 			 */
+ 			if (bpf_pseudo_call(&insn[idx]) && insn[idx].imm == -1) {
+ 				verbose(env, "call at insn %d calls itself\n", idx);
+ 				ret = -EINVAL;
  				break;
  			}
- 
- 			if (!pushed) {
- 				color[cur] = 2;
- 				env->subprog_topo_order[order++] = cur;
- 				top--;
- 			}
+ 			ret = bpf_call_graph_add(&cg, i,
+ 						 bpf_find_subprog(env, idx + insn[idx].imm + 1));
  		}
  	}
+ 	if (ret)
+ 		goto out;
+ 	bpf_call_graph_sort(&cg, 0);
+ 	memcpy(env->subprog_topo_order, cg.postorder, cnt * sizeof(u32));
  
  	if (env->log.level & BPF_LOG_LEVEL2)
  		for (i = 0; i < cnt; i++)
  			verbose(env, "topo_order[%d] = %s\n",
  				i, bpf_subprog_name(env, env->subprog_topo_order[i]));
  out:
- 	kvfree(dfs_stack);
- 	kvfree(color);
+ 	bpf_call_graph_free(&cg);
  	return ret;
  }
  
@@@ -3654,74 -3517,6 +3517,6 @@@ static void mark_non_stack_access(struc
  	env->insn_aux_data[idx].non_stack_access = true;
  }
  
- /* Layout of one packed linked register in the jump history, see linked_regs_pack() */
- #define LR_FRAMENO_BITS	4
- #define LR_INDEX_BITS	11
- #define LR_FRAMENO_MASK	((1u << LR_FRAMENO_BITS) - 1)
- #define LR_IS_REG	BIT(LR_FRAMENO_BITS)
- #define LR_INDEX_OFF	(LR_FRAMENO_BITS + 1)
- #define LR_INDEX_MASK	((1u << LR_INDEX_BITS) - 1)
- #define LINKED_REGS_MAX	BPF_LINKED_REGS_MAX
- 
- static_assert(MAX_CALL_FRAMES <= (1 << LR_FRAMENO_BITS));
- static_assert(MAX_BPF_REG <= (1 << LR_INDEX_BITS));
- static_assert(MAX_BPF_STACK_SLOTS <= (1 << LR_INDEX_BITS));
- static_assert(LR_INDEX_OFF + LR_INDEX_BITS <= 16);
- 
- struct linked_reg {
- 	u8 frameno;
- 	union {
- 		u16 spi;
- 		u16 regno;
- 	};
- 	bool is_reg;
- };
- 
- struct linked_regs {
- 	int cnt;
- 	struct linked_reg entries[LINKED_REGS_MAX];
- };
- 
- static struct linked_reg *linked_regs_push(struct linked_regs *s)
- {
- 	if (s->cnt < LINKED_REGS_MAX)
- 		return &s->entries[s->cnt++];
- 
- 	return NULL;
- }
- 
- /*
-  * Pack linked registers for a jump history entry, one u16 each:
-  * - 4 bits frameno
-  * - 1 bit  is_reg
-  * - 11 bits register or stack slot index
-  */
- static void linked_regs_pack(const struct linked_regs *s, u16 *packed)
- {
- 	int i;
- 
- 	for (i = 0; i < s->cnt; ++i) {
- 		const struct linked_reg *e = &s->entries[i];
- 
- 		packed[i] = e->frameno | (e->is_reg ? LR_IS_REG : 0) | (e->spi << LR_INDEX_OFF);
- 	}
- }
- 
- static void linked_regs_unpack(const struct bpf_jmp_history_entry *hist, struct linked_regs *s)
- {
- 	int i;
- 
- 	s->cnt = hist->linked_regs_cnt;
- 	for (i = 0; i < s->cnt; ++i) {
- 		struct linked_reg *e = &s->entries[i];
- 		u16 packed = hist->linked_regs[i];
- 
- 		e->frameno = packed & LR_FRAMENO_MASK;
- 		e->is_reg  = packed & LR_IS_REG;
- 		e->spi     = (packed >> LR_INDEX_OFF) & LR_INDEX_MASK;
- 	}
- }
- 
  const char *bpf_disasm_kfunc_name(void *data, const struct bpf_insn *insn)
  {
  	const struct btf_type *func;
@@@ -3751,67 -3546,21 +3546,21 @@@ void bpf_verbose_insn(struct bpf_verifi
  	print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
  }
  
- /* If any register R in hist->linked_regs is marked as precise in bt,
-  * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs.
-  */
- void bpf_bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist)
+ static bool scalar_is_const(const struct scalar *s, bool subreg32)
  {
- 	struct linked_regs linked_regs;
- 	bool some_precise = false;
- 	int i;
- 
- 	if (!hist || !hist->linked_regs_cnt)
- 		return;
- 
- 	linked_regs_unpack(hist, &linked_regs);
- 	for (i = 0; i < linked_regs.cnt; ++i) {
- 		struct linked_reg *e = &linked_regs.entries[i];
- 
- 		if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) ||
- 		    (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) {
- 			some_precise = true;
- 			break;
- 		}
- 	}
- 
- 	if (!some_precise)
- 		return;
- 
- 	for (i = 0; i < linked_regs.cnt; ++i) {
- 		struct linked_reg *e = &linked_regs.entries[i];
- 
- 		if (e->is_reg)
- 			bpf_bt_set_frame_reg(bt, e->frameno, e->regno);
- 		else
- 			bpf_bt_set_frame_slot(bt, e->frameno, e->spi);
- 	}
- }
- 
- int mark_chain_precision(struct bpf_verifier_env *env, int regno)
- {
- 	return bpf_mark_chain_precision(env, env->cur_state, regno, NULL);
- }
- 
- /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
-  * desired reg and stack masks across all relevant frames
-  */
- static int mark_chain_precision_batch(struct bpf_verifier_env *env,
- 				      struct bpf_verifier_state *starting_state)
- {
- 	return bpf_mark_chain_precision(env, starting_state, -1, NULL);
+ 	return tnum_is_const(subreg32 ? tnum_subreg(s->var_off) : s->var_off);
  }
  
  /* check if register is a constant scalar value */
  static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
  {
- 	return reg->type == SCALAR_VALUE &&
- 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
+ 	return reg->type == SCALAR_VALUE && scalar_is_const(scalar_of(reg), subreg32);
  }
  
- /* assuming is_reg_const() is true, return constant value of a register */
- static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
+ /* assuming scalar_is_const() is true, return the constant */
+ static u64 scalar_const_value(const struct scalar *s, bool subreg32)
  {
- 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
+ 	return subreg32 ? tnum_subreg(s->var_off).value : s->var_off.value;
  }
  
  static bool is_pointer_regtype(enum bpf_reg_type type)
@@@ -3825,28 -3574,8 +3574,8 @@@ static bool __is_pointer_value(bool all
  	if (allow_ptr_leaks)
  		return false;
  
- 	return is_pointer_regtype(reg->type);
- }
- 
- static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
- 					struct bpf_reg_state *src_reg)
- {
- 	if (src_reg->type != SCALAR_VALUE)
- 		return;
- 	/*
- 	 * The verifier is processing rX = rY insn and
- 	 * rY->id has special linked register already.
- 	 * Cleared it, since multiple rX += const are not supported.
- 	 */
- 	if (src_reg->id & BPF_ADD_CONST)
- 		clear_scalar_id(src_reg);
- 	/*
- 	 * Ensure that src_reg has a valid ID that will be copied to
- 	 * dst_reg and then will be used by sync_linked_regs() to
- 	 * propagate min/max range.
- 	 */
- 	if (!src_reg->id && !tnum_is_const(src_reg->var_off))
- 		src_reg->id = ++env->id_gen;
+ 	/* an unreadable xreg can have a pointer */
+ 	return reg->type != SCALAR_VALUE;
  }
  
  static void save_register_state(struct bpf_verifier_env *env,
@@@ -3875,14 -3604,21 +3604,21 @@@ static bool is_bpf_st_mem(struct bpf_in
  	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
  }
  
- static int get_reg_width(struct bpf_reg_state *reg)
+ /* See bpf_partition_for_pessimized() */
+ static void note_pessimized_insn(struct bpf_verifier_env *env, u32 idx)
  {
- 	return fls64(reg_umax(reg));
+ 	if (!env->imprecise)
+ 		return;
+ 	env->insn_aux_data[idx].pessimized = true;
+ 	env->pessimized = true;
+ 	if (!env->err)
+ 		env->err_insn = idx;
  }
  
  /* See comment for mark_fastcall_pattern_for_call() */
  static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
- 					  struct bpf_func_state *state, int insn_idx, int off)
+ 					  struct bpf_func_state *state, int insn_idx, int off,
+ 					  bool var_off)
  {
  	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
  	struct bpf_insn_aux_data *aux = env->insn_aux_data;
@@@ -3900,6 -3636,10 +3636,10 @@@
  	 * happens at most once per subprogram
  	 */
  	for (i = subprog->start; i < (subprog + 1)->start; ++i) {
+ 		/* the spills can be too much for the stack, see bpf_find_unproven_after_pass() */
+ 		aux[insn_idx].pessimized |= aux[i].fastcall_spills_num && env->imprecise;
+ 		if (aux[i].fastcall_spills_num && var_off)
+ 			note_pessimized_insn(env, insn_idx);
  		aux[i].fastcall_spills_num = 0;
  		aux[i].fastcall_pattern = 0;
  	}
@@@ -3931,8 -3671,6 +3671,6 @@@ static int check_stack_write_fixed_off(
  	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
  	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
  	struct bpf_reg_state *reg = NULL;
- 	int insn_flags = INSN_F_STACK_ACCESS;
- 	int hist_spi = spi, hist_frame = state->frameno;
  	struct bpf_stack_state *ss = bpf_stack_slot(state, spi);
  
  	/*
@@@ -3982,16 -3720,7 +3720,7 @@@
  
  	mark_stack_slot_scratched(env, spi);
  	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
- 		bool reg_value_fits;
- 
- 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
- 		/* Make sure that reg had an ID to build a relation on spill. */
- 		if (reg_value_fits)
- 			assign_scalar_id_before_mov(env, reg);
  		save_register_state(env, state, spi, reg, size);
- 		/* Break the relation on a narrowing spill. */
- 		if (!reg_value_fits)
- 			clear_scalar_id(&ss->spilled_ptr);
  	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
  		   env->bpf_capable) {
  		struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
@@@ -4000,8 -3729,13 +3729,13 @@@
  		__mark_reg_known(tmp_reg, insn->imm);
  		tmp_reg->type = SCALAR_VALUE;
  		save_register_state(env, state, spi, tmp_reg, size);
- 	} else if (reg && is_pointer_regtype(reg->type)) {
- 		/* register containing pointer is being spilled into stack */
+ 	} else if (reg && is_pointer_regtype(reg->type) &&
+ 		   (size == BPF_REG_SIZE || !env->allow_ptr_leaks)) {
+ 		/*
+ 		 * register containing pointer is being spilled into stack.
+ 		 * A part of it is a number, which is fine when the program
+ 		 * may see values of pointers anyway.
+ 		 */
  		if (size != BPF_REG_SIZE) {
  			verbose_linfo(env, insn_idx, "; ");
  			verbose(env, "invalid size of register spill\n");
@@@ -4014,36 -3748,33 +3748,33 @@@
  		save_register_state(env, state, spi, reg, size);
  	} else {
  		u8 type = STACK_MISC;
+ 		int keep = 0;
  
- 		if (bpf_is_spilled_reg(ss))
- 			bpf_diag_record_scrub(env, &ss->spilled_ptr,
- 					      BPF_DIAG_MOD_WRITE);
- 		scrub_special_slot(state, spi);
+ 		/* the bytes before the write still have the low bytes of a number */
+ 		if (bpf_is_spilled_scalar_reg(ss) && off % BPF_REG_SIZE)
+ 			keep = min_t(int, rounddown_pow_of_two(off & (BPF_REG_SIZE - 1)),
+ 				     bpf_spill_size(ss));
+ 		if (keep && bpf_stack_narrow_access_ok(0, keep, bpf_spill_size(ss))) {
+ 			for (i = 0; i < BPF_REG_SIZE - keep; i++)
+ 				if (ss->slot_type[i] == STACK_SPILL)
+ 					ss->slot_type[i] = STACK_MISC;
+ 		} else {
+ 			if (bpf_is_spilled_reg(ss))
+ 				bpf_diag_record_scrub(env, &ss->spilled_ptr, BPF_DIAG_MOD_WRITE);
+ 			scrub_special_slot(state, spi);
+ 		}
  
  		/* when we zero initialize stack slots mark them as such */
  		if ((reg && bpf_register_is_null(reg)) ||
- 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
- 			/* STACK_ZERO case happened because register spill
- 			 * wasn't properly aligned at the stack slot boundary,
- 			 * so it's not a register spill anymore; force
- 			 * originating register to be precise to make
- 			 * STACK_ZERO correct for subsequent states
- 			 */
- 			err = mark_chain_precision(env, value_regno);
- 			if (err)
- 				return err;
+ 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0))
  			type = STACK_ZERO;
- 		}
  
  		/* Mark slots affected by this stack write. */
  		for (i = 0; i < size; i++)
  			ss->slot_type[(slot - i) % BPF_REG_SIZE] = type;
- 		insn_flags = 0; /* not a register spill */
+ 		return 0;
  	}
- 
- 	if (insn_flags)
- 		return bpf_push_jmp_history(env, env->cur_state, insn_flags,
- 					    hist_spi, hist_frame, NULL, 0);
+ 	bpf_equations_spill(env, state, spi, value_regno);
  	return 0;
  }
  
@@@ -4077,16 -3808,17 +3808,17 @@@ static int check_stack_write_var_off(st
  	struct bpf_reg_state *value_reg = NULL;
  	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
  	bool writing_zero = false;
- 	/* set if the fact that we're writing a zero is used to let any
- 	 * stack slots remain STACK_ZERO
- 	 */
- 	bool zero_used = false;
  
  	cur = env->cur_state->frame[env->cur_state->curframe];
  	min_off = reg_smin(ptr_reg) + off;
  	max_off = reg_smax(ptr_reg) + off + size;
  	if (value_regno >= 0)
  		value_reg = &cur->regs[value_regno];
+ 	/* no slot remembers the pointer, a load gets it as a number */
+ 	if (value_reg && __is_pointer_value(env->allow_ptr_leaks, value_reg)) {
+ 		verbose(env, "R%d leaks addr into stack\n", value_regno);
+ 		return -EACCES;
+ 	}
  	if ((value_reg && bpf_register_is_null(value_reg)) ||
  	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
  		writing_zero = true;
@@@ -4131,10 -3863,8 +3863,8 @@@
  		if (writing_zero && *stype == STACK_SPILL && bpf_is_spilled_scalar_reg(ss)) {
  			struct bpf_reg_state *spill_reg = &ss->spilled_ptr;
  
- 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
- 				zero_used = true;
+ 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0)
  				continue;
- 			}
  		}
  
  		/*
@@@ -4147,10 -3877,8 +3877,8 @@@
  
  		/* Update the slot type. */
  		new_type = STACK_MISC;
- 		if (writing_zero && *stype == STACK_ZERO) {
+ 		if (writing_zero && *stype == STACK_ZERO)
  			new_type = STACK_ZERO;
- 			zero_used = true;
- 		}
  		/* If the slot is STACK_INVALID, we check whether it's OK to
  		 * pretend that it will be initialized by this write. The slot
  		 * might not actually be written to, and so if we mark it as
@@@ -4168,12 -3896,6 +3896,6 @@@
  		}
  		*stype = new_type;
  	}
- 	if (zero_used) {
- 		/* backtracking doesn't work for STACK_ZERO yet. */
- 		err = mark_chain_precision(env, value_regno);
- 		if (err)
- 			return err;
- 	}
  	bpf_diag_record_scrub_stack(env, state, min_off, max_off,
  				    BPF_DIAG_MOD_VAR_WRITE);
  	return 0;
@@@ -4188,21 -3910,18 +3910,18 @@@
   * read.
   *
   * STACK_SPILL bytes backed by spilled scalar const zeroes are also considered
-  * zero bytes. In that case, mark the contributing stack slots precise so
-  * pruning cannot reuse a zero-spill state for a later non-zero spill state.
-  *
-  * Returns an error if precision backtracking fails.
+  * zero bytes.
   */
- static int mark_reg_stack_read(struct bpf_verifier_env *env,
- 			       /* func where src register points to */
- 			       struct bpf_func_state *ptr_state,
- 			       int min_off, int max_off, int dst_regno)
+ static void mark_reg_stack_read(struct bpf_verifier_env *env,
+ 				/* func where src register points to */
+ 				struct bpf_func_state *ptr_state,
+ 				int min_off, int max_off, int dst_regno)
  {
  	struct bpf_verifier_state *vstate = env->cur_state;
  	struct bpf_func_state *state = vstate->frame[vstate->curframe];
  	int i, slot, spi;
  	u8 *stype;
- 	int zeros = 0, zero_spills = 0;
+ 	int zeros = 0;
  
  	for (i = min_off; i < max_off; i++) {
  		slot = -i - 1;
@@@ -4215,7 -3934,6 +3934,6 @@@
  		}
  		if (stype[slot % BPF_REG_SIZE] == STACK_SPILL &&
  		    bpf_register_is_null(&bpf_stack_slot(ptr_state, spi)->spilled_ptr)) {
- 			zero_spills++;
  			zeros++;
  			continue;
  		}
@@@ -4225,23 -3943,11 +3943,11 @@@
  		/* Any access_size read into register is zero extended,
  		 * so the whole register == const_zero.
  		 */
- 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
- 		if (zero_spills) {
- 			for (i = min_off; i < max_off; i++) {
- 				slot = -i - 1;
- 				spi = slot / BPF_REG_SIZE;
- 				stype = bpf_stack_slot(ptr_state, spi)->slot_type;
- 				if (stype[slot % BPF_REG_SIZE] == STACK_SPILL)
- 					bpf_bt_set_frame_slot(&env->bt, ptr_state->frameno, spi);
- 			}
- 			return mark_chain_precision_batch(env, env->cur_state);
- 		}
+ 		__mark_reg_const_zero(&state->regs[dst_regno]);
  	} else {
  		/* have read misc data from the stack */
  		mark_reg_unknown(env, state->regs, dst_regno);
  	}
- 
- 	return 0;
  }
  
  static void bpf_diag_stack_read_invalid(struct bpf_verifier_env *env, int off, int i, int size,
@@@ -4305,9 -4011,6 +4011,6 @@@ static int check_stack_read_fixed_off(s
  	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
  	struct bpf_reg_state *reg;
  	u8 *stype, type;
- 	int err;
- 	int insn_flags = INSN_F_STACK_ACCESS;
- 	int hist_spi = spi, hist_frame = reg_state->frameno;
  	struct bpf_stack_state *ss = bpf_stack_slot(reg_state, spi);
  
  	stype = ss->slot_type;
@@@ -4336,22 -4039,19 +4039,19 @@@
  				if (dst_regno < 0)
  					return 0;
  
- 				if (env->bpf_capable && size == 4 && spill_size == 4 &&
- 				    get_reg_width(reg) <= 32)
- 					/* Ensure stack slot has an ID to build a relation
- 					 * with the destination register on fill.
- 					 */
- 					assign_scalar_id_before_mov(env, reg);
+ 				/* coerce_scalar_to_size will adjust the boundaries. */
  				state->regs[dst_regno] = *reg;
- 
- 				/* Break the relation on a narrowing fill.
- 				 * coerce_reg_to_size will adjust the boundaries.
- 				 */
- 				if (get_reg_width(reg) > size * BITS_PER_BYTE)
- 					clear_scalar_id(&state->regs[dst_regno]);
+ 				bpf_equations_fill(env, reg_state, spi, size);
  			} else {
+ 				/* the low bytes are from the spill */
+ 				bool fill_exceeds_spill =
+ 					size > spill_size && !(off % BPF_REG_SIZE) &&
+ 					!IS_ENABLED(CONFIG_CPU_BIG_ENDIAN);
  				int spill_cnt = 0, zero_cnt = 0;
  
+ 				if (fill_exceeds_spill)
+ 					bpf_equations_fill(env, reg_state, spi, spill_size);
+ 
  				for (i = 0; i < size; i++) {
  					type = stype[(slot - i) % BPF_REG_SIZE];
  					if (type == STACK_SPILL) {
@@@ -4382,32 -4082,23 +4082,23 @@@
  
  				if (spill_cnt == size &&
  				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
- 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
- 					/* this IS register fill, so keep insn_flags */
+ 					__mark_reg_const_zero(&state->regs[dst_regno]);
  				} else if (zero_cnt == size) {
  					/* similarly to mark_reg_stack_read(), preserve zeroes */
- 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
- 					insn_flags = 0; /* not restoring original register state */
+ 					__mark_reg_const_zero(&state->regs[dst_regno]);
  				} else {
- 					err = mark_reg_stack_read(env, reg_state, off, off + size,
- 								  dst_regno);
- 					if (err)
- 						return err;
- 					insn_flags = 0; /* not restoring original register state */
+ 					mark_reg_stack_read(env, reg_state, off, off + size,
+ 							    dst_regno);
+ 					if (fill_exceeds_spill)
+ 						scalar_intersect(scalar_of(&state->regs[dst_regno]),
+ 								 scalar_of(reg),
+ 								 spill_size * BITS_PER_BYTE);
  				}
  			}
  		} else if (dst_regno >= 0) {
  			/* restore register state from stack */
- 			if (env->bpf_capable)
- 				/* Ensure stack slot has an ID to build a relation
- 				 * with the destination register on fill.
- 				 */
- 				assign_scalar_id_before_mov(env, reg);
  			state->regs[dst_regno] = *reg;
- 			/* mark reg as written since spilled pointer state likely
- 			 * has its liveness marks cleared by is_state_visited()
- 			 * which resets stack/reg liveness for state transitions
- 			 */
+ 			bpf_equations_fill(env, reg_state, spi, size);
  		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
  			/* If dst_regno==-1, the caller is asking us whether
  			 * it is acceptable to use this value as a SCALAR_VALUE
@@@ -4438,16 -4129,9 +4129,9 @@@
  			}
  			return -EACCES;
  		}
- 		if (dst_regno >= 0) {
- 			err = mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
- 			if (err)
- 				return err;
- 		}
- 		insn_flags = 0; /* we are not restoring spilled register */
+ 		if (dst_regno >= 0)
+ 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
  	}
- 	if (insn_flags)
- 		return bpf_push_jmp_history(env, env->cur_state, insn_flags,
- 					    hist_spi, hist_frame, NULL, 0);
  	return 0;
  }
  
@@@ -4476,9 -4160,8 +4160,8 @@@ static struct bpf_reg_state *reg_state(
   * As opposed to check_stack_read_fixed_off, this function doesn't deal with
   * filling registers (i.e. reads of spilled register cannot be detected when
   * the offset is not fixed). We conservatively mark 'dst_regno' as containing
-  * SCALAR_VALUE. That's why we assert that the 'reg' has a variable
-  * offset; for a fixed offset check_stack_read_fixed_off should be used
-  * instead.
+  * SCALAR_VALUE. A fixed offset gets here only for a part of a spilled
+  * pointer, see check_stack_read().
   */
  static int check_stack_read_var_off(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
  				    argno_t ptr_argno, int off, int size, int dst_regno)
@@@ -4496,10 -4179,7 +4179,7 @@@
  
  	min_off = reg_smin(reg) + off;
  	max_off = reg_smax(reg) + off;
- 	err = mark_reg_stack_read(env, ptr_state, min_off, max_off + size,
- 				  dst_regno);
- 	if (err)
- 		return err;
+ 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
  	return 0;
  }
  
@@@ -4517,6 -4197,7 +4197,7 @@@ static int check_stack_read(struct bpf_
  			    int dst_regno)
  {
  	struct bpf_func_state *state = bpf_func(env, reg);
+ 	struct bpf_stack_state *ss;
  	int err;
  	/* Some accesses are only permitted with a static offset. */
  	bool var_off = !tnum_is_const(reg->var_off);
@@@ -4550,6 -4231,11 +4231,11 @@@
  	 * just checking it here would be insufficient as speculative stack
  	 * writes could still lead to unsafe speculative behaviour.
  	 */
+ 	if (!var_off && dst_regno >= 0 && size != BPF_REG_SIZE && env->allow_ptr_leaks) {
+ 		ss = bpf_stack_slot(state, (-off - reg->var_off.value - 1) / BPF_REG_SIZE);
+ 		/* a part of a pointer is a number, as with a variable offset */
+ 		var_off = bpf_is_spilled_reg(ss) && !bpf_is_spilled_scalar_reg(ss);
+ 	}
  	if (!var_off) {
  		off += reg->var_off.value;
  		err = check_stack_read_fixed_off(env, state, off, size,
@@@ -4625,6 -4311,23 +4311,23 @@@ static int check_stack_write(struct bpf
  	return err;
  }
  
+ /*
+  * The function that is verified on its own has no caller to look at. Its incoming
+  * arguments are in its stack_arg_regs until it is done with loading them.
+  */
+ static void end_stack_arg_loads(struct bpf_verifier_env *env, struct bpf_func_state *state)
+ {
+ 	int i;
+ 
+ 	if (state->no_stack_arg_load)
+ 		return;
+ 	state->no_stack_arg_load = true;
+ 	if (state->frameno)
+ 		return;
+ 	for (i = 0; i < state->out_stack_arg_cnt; i++)
+ 		bpf_mark_reg_not_init(env, &state->stack_arg_regs[i]);
+ }
+ 
  /*
   * Write a value to the outgoing stack arg area.
   * off is a negative offset from r11 (e.g. -8 for arg6, -16 for arg7).
@@@ -4632,24 -4335,31 +4335,31 @@@
  static int check_stack_arg_write(struct bpf_verifier_env *env, struct bpf_func_state *state,
  				 int off, struct bpf_reg_state *value_reg)
  {
- 	int max_stack_arg_regs = MAX_BPF_FUNC_ARGS - MAX_BPF_FUNC_REG_ARGS;
+ 	int max_stack_arg_regs = MAX_STACK_ARG_SLOTS;
  	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
  	int spi = -off / BPF_REG_SIZE - 1;
  	struct bpf_reg_state *arg;
  	int err;
  
+ 	/* BTF is not needed for stack arguments, so ask here. There is no load without a store. */
+ 	if (!bpf_jit_supports_stack_args()) {
+ 		verbose(env, "JIT does not support stack arguments\n");
+ 		return -EOPNOTSUPP;
+ 	}
+ 
  	if (spi >= max_stack_arg_regs) {
  		verbose(env, "stack arg write offset %d exceeds max %d stack args\n",
  			off, max_stack_arg_regs);
  		return -EINVAL;
  	}
  
+ 	end_stack_arg_loads(env, state);
  	err = grow_stack_arg_slots(env, state, spi + 1);
  	if (err)
  		return err;
  
  	/* Track the max outgoing stack arg slot count. */
- 	if (spi + 1 > subprog->max_out_stack_arg_cnt)
+ 	if (spi + 1 > subprog->max_out_stack_arg_cnt && !env->cur_state->speculative)
  		subprog->max_out_stack_arg_cnt = spi + 1;
  
  	arg = &state->stack_arg_regs[spi];
@@@ -4663,9 -4373,7 +4373,7 @@@
  		__mark_reg_known(arg, env->prog->insnsi[env->insn_idx].imm);
  	}
  	bpf_diag_mod_end(env);
- 	state->no_stack_arg_load = true;
- 	return bpf_push_jmp_history(env, env->cur_state,
- 				    INSN_F_STACK_ARG_ACCESS, spi, 0, NULL, 0);
+ 	return 0;
  }
  
  /*
@@@ -4692,7 -4400,7 +4400,7 @@@ static int check_stack_arg_read(struct 
  		return -EACCES;
  	}
  
- 	caller = vstate->frame[vstate->curframe - 1];
+ 	caller = vstate->frame[vstate->curframe ? vstate->curframe - 1 : 0];
  	arg = bpf_get_spilled_stack_arg(spi, caller);
  	if (!arg) {
  		verbose(env, "invalid read from uninitialized stack arg off %d\n", off);
@@@ -4703,26 -4411,7 +4411,7 @@@
  	bpf_diag_mod_begin(env, &cur->regs[dst_regno], arg, BPF_DIAG_MOD_WRITE);
  	cur->regs[dst_regno] = *arg;
  	bpf_diag_mod_end(env);
- 	return bpf_push_jmp_history(env, env->cur_state,
- 				    INSN_F_STACK_ARG_ACCESS, spi, 0, NULL, 0);
- }
- 
- static int mark_stack_arg_precision(struct bpf_verifier_env *env, int arg_idx)
- {
- 	struct bpf_func_state *caller = cur_func(env);
- 	int spi = arg_idx - MAX_BPF_FUNC_REG_ARGS;
- 
- 	bt_set_frame_stack_arg_slot(&env->bt, caller->frameno, spi);
- 	return mark_chain_precision_batch(env, env->cur_state);
- }
- 
- static int mark_arg_precision(struct bpf_verifier_env *env, argno_t argno)
- {
- 	int regno = reg_from_argno(argno);
- 
- 	if (regno >= 0)
- 		return mark_chain_precision(env, regno);
- 	return mark_stack_arg_precision(env, arg_idx_from_argno(argno));
+ 	return 0;
  }
  
  static int check_outgoing_stack_args(struct bpf_verifier_env *env, struct bpf_func_state *caller,
@@@ -4743,7 -4432,7 +4432,7 @@@
  				nargs, spi + 1);
  			bpf_diag_stack_arg_uninit(env, env->insn_idx, nargs, spi,
  						  callee_name, arg_name);
- 			return -EFAULT;
+ 			return -EINVAL;
  		}
  	}
  
@@@ -5027,6 -4716,7 +4716,7 @@@ bad_type
  	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
  		reg_type_str(env, reg->type), reg_name);
  	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
+ 	bpf_note_needs_ptr(env, reg);
  	if (kptr_field->type == BPF_KPTR_UNREF)
  		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
  			targ_name);
@@@ -5134,7 -4824,7 +4824,7 @@@ static int mark_uptr_ld_reg(struct bpf_
  	reg = reg_state(env, regno);
  	reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
  	reg->mem_size = t->size;
- 	reg->id = ++env->id_gen;
+ 	reg->id = bpf_new_id(env);
  
  	return 0;
  }
@@@ -5187,14 -4877,8 +4877,8 @@@ static int check_map_kptr_access(struc
  			return ret;
  	} else if (class == BPF_STX) {
  		val_reg = reg_state(env, value_regno);
- 		if (bpf_register_is_null(val_reg)) {
- 			/*
- 			 * This store is valid only because the scalar is known to be
- 			 * zero. Mark it precise so another scalar cannot be pruned
- 			 * against this state.
- 			 */
- 			return mark_chain_precision(env, value_regno);
- 		}
+ 		if (bpf_register_is_null(val_reg))
+ 			return 0;
  		if (map_kptr_match_type(env, kptr_field, val_reg, value_regno))
  			return -EACCES;
  	} else if (class == BPF_ST) {
@@@ -5239,48 -4923,43 +4923,43 @@@ static int check_map_access(struct bpf_
  	if (IS_ERR_OR_NULL(map->record))
  		return 0;
  	rec = map->record;
- 	for (i = 0; i < rec->cnt; i++) {
+ 	/* If any part of a field can be touched by load/store, reject this program. */
+ 	for (i = btf_record_first_field(rec, reg_smin(reg) + off);
+ 	     i < rec->cnt && rec->fields[i].offset < reg_umax(reg) + off + size; i++) {
  		struct btf_field *field = &rec->fields[i];
  		u32 p = field->offset;
  
- 		/* If any part of a field  can be touched by load/store, reject
- 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
- 		 * it is sufficient to check x1 < y2 && y1 < x2.
- 		 */
- 		if (reg_smin(reg) + off < p + field->size &&
- 		    p < reg_umax(reg) + off + size) {
- 			switch (field->type) {
- 			case BPF_KPTR_UNREF:
- 			case BPF_KPTR_REF:
- 			case BPF_KPTR_PERCPU:
- 			case BPF_UPTR:
- 				if (src != ACCESS_DIRECT) {
- 					verbose(env, "%s cannot be accessed indirectly by helper\n",
- 						btf_field_type_name(field->type));
- 					return -EACCES;
- 				}
- 				if (!tnum_is_const(reg->var_off)) {
- 					verbose(env, "%s access cannot have variable offset\n",
- 						btf_field_type_name(field->type));
- 					return -EACCES;
- 				}
- 				if (p != off + reg->var_off.value) {
- 					verbose(env, "%s access misaligned expected=%u off=%llu\n",
- 						btf_field_type_name(field->type),
- 						p, off + reg->var_off.value);
- 					return -EACCES;
- 				}
- 				if (size != bpf_size_to_bytes(BPF_DW)) {
- 					verbose(env, "%s access size must be BPF_DW\n",
- 						btf_field_type_name(field->type));
- 					return -EACCES;
- 				}
- 				break;
- 			default:
- 				verbose(env, "%s cannot be accessed directly by load/store\n",
+ 		switch (field->type) {
+ 		case BPF_KPTR_UNREF:
+ 		case BPF_KPTR_REF:
+ 		case BPF_KPTR_PERCPU:
+ 		case BPF_UPTR:
+ 			if (src != ACCESS_DIRECT) {
+ 				verbose(env, "%s cannot be accessed indirectly by helper\n",
  					btf_field_type_name(field->type));
  				return -EACCES;
  			}
+ 			if (!tnum_is_const(reg->var_off)) {
+ 				verbose(env, "%s access cannot have variable offset\n",
+ 					btf_field_type_name(field->type));
+ 				return -EACCES;
+ 			}
+ 			if (p != off + reg->var_off.value) {
+ 				verbose(env, "%s access misaligned expected=%u off=%llu\n",
+ 					btf_field_type_name(field->type),
+ 					p, off + reg->var_off.value);
+ 				return -EACCES;
+ 			}
+ 			if (size != bpf_size_to_bytes(BPF_DW)) {
+ 				verbose(env, "%s access size must be BPF_DW\n",
+ 					btf_field_type_name(field->type));
+ 				return -EACCES;
+ 			}
+ 			break;
+ 		default:
+ 			verbose(env, "%s cannot be accessed directly by load/store\n",
+ 				btf_field_type_name(field->type));
+ 			return -EACCES;
  		}
  	}
  	return 0;
@@@ -5361,6 -5040,17 +5040,17 @@@ static bool is_var_ctx_off_allowed(stru
  	return resolve_prog_type(prog) == BPF_PROG_TYPE_SYSCALL;
  }
  
+ /* The id of the reference that came with __ref argument @arg. 0 if there is none. */
+ static u32 ctx_arg_ref_id(const struct bpf_verifier_state *st, u32 arg)
+ {
+ 	u32 i;
+ 
+ 	for (i = 0; arg && i < st->acquired_refs; i++)
+ 		if (st->refs[i].type == REF_TYPE_PTR && st->refs[i].ctx_arg == arg)
+ 			return st->refs[i].id;
+ 	return 0;
+ }
+ 
  /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
  static int __check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
  			      enum bpf_access_type t, struct bpf_insn_access_aux *info)
@@@ -5375,8 -5065,7 +5065,7 @@@
  		 * type of narrower access.
  		 */
  		if (base_type(info->reg_type) == PTR_TO_BTF_ID) {
- 			if (info->ref_id &&
- 			    !find_reference_state(env->cur_state, info->ref_id)) {
+ 			if (info->ref_arg && !ctx_arg_ref_id(env->cur_state, info->ref_arg)) {
  				verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n",
  					off);
  				return -EACCES;
@@@ -5742,6 -5431,15 +5431,15 @@@ static enum priv_stack_mode bpf_enable_
  	 */
  	switch (prog->type) {
  	case BPF_PROG_TYPE_KPROBE:
+ 		/*
+ 		 * Uprobes are preemptible and lack recursion protection. Classic
+ 		 * kprobe and uprobe progs have no expected attach type, so enable
+ 		 * private stacks only for kprobe.multi and kprobe.session progs.
+ 		 */
+ 		if (prog->expected_attach_type != BPF_TRACE_KPROBE_MULTI &&
+ 		    prog->expected_attach_type != BPF_TRACE_KPROBE_SESSION)
+ 			return NO_PRIV_STACK;
+ 		fallthrough;
  	case BPF_PROG_TYPE_TRACEPOINT:
  	case BPF_PROG_TYPE_PERF_EVENT:
  	case BPF_PROG_TYPE_RAW_TRACEPOINT:
@@@ -5770,322 -5468,682 +5468,682 @@@ static int round_up_stack_depth(struct 
  	return round_up(max_t(u32, stack_depth, 1), 32);
  }
  
- /* temporary state used for call frame depth calculation */
- struct bpf_subprog_call_depth_info {
- 	int ret_insn; /* caller instruction where we return to. */
- 	int caller; /* caller subprogram idx */
- 	int frame; /* # of consecutive static call stack frames on top of stack */
- 	int callx_insn; /* callx instruction whose callees are being walked */
- 	int callx_next; /* next callee of callx_insn to walk */
- 	bool via_callx; /* the subprogram is entered via callx */
+ enum {
+ 	CG_LIVE		= BIT(0), /* what the kernel calls and what that gets to */
+ 	CG_IN_CB	= BIT(1), /* callbacks and what they get to */
+ 	CG_IN_ASYNC_CB	= BIT(2), /* async callbacks and what they get to */
+ 	CG_IN_RECURSION	= BIT(3), /* recursive subprogs and what they get to */
+ 	CG_TAIL_CALL	= BIT(4), /* subprogs that get to a tail call */
+ 	CG_ARENA_SP	= BIT(5), /* subprogs that get to r12 */
+ 	CG_CB		= BIT(6),
+ 	CG_GLOBAL	= BIT(7),
  };
  
- /* starting from main bpf function walk all instructions of the function
-  * and recursively walk all callees that given function can call.
-  * Ignore jump and exit insns.
+ #define for_each_marked_subprog(cg, s, mark) \
+ 	for (s = 0; s < (cg)->cnt; s++) if (!((cg)->marks[s] & (mark))) {} else
+ 
+ /*
+  * Who calls whom. It's known after the main verification pass, which finds out
+  * what callx and the helpers that take callbacks call, and what is dead code.
+  *
+  * What follows for a subprog from its callers, or from what it calls, is computed
+  * over this graph and not by a walk of one chain of calls after another: the
+  * number of chains grows exponentially, and there is no end to them when subprogs
+  * call themselves.
   */
- static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
- 					 struct bpf_subprog_call_depth_info *dinfo,
- 					 bool priv_stack_supported)
+ static int build_call_graph(struct bpf_verifier_env *env, struct bpf_call_graph *cg)
  {
- 	struct bpf_subprog_info *subprog = env->subprog_info;
+ 	struct bpf_subprog_info *si = env->subprog_info;
  	struct bpf_insn *insn = env->prog->insnsi;
- 	int depth = 0, frame = 0, i, subprog_end, subprog_depth;
- 	bool tail_call_reachable = false;
- 	int total;
- 	int tmp;
+ 	int cnt = env->subprog_cnt, i, s, err;
  
- 	/* no caller idx */
- 	dinfo[idx].caller = -1;
- 	dinfo[idx].via_callx = false;
+ 	err = bpf_call_graph_init(cg, cnt);
+ 	for (s = 0; s < cnt; s++) {
+ 		for (i = si[s].start; i < si[s + 1].start && !err; i++)
+ 			if (bpf_pseudo_call(insn + i) && env->insn_aux_data[i].seen)
+ 				err = bpf_call_graph_add(cg, s, bpf_find_subprog(env,
+ 							 i + insn[i].imm + 1));
+ 		/* the callees of callx and the callbacks of helpers */
+ 		for (i = si[s].callx_edge; i && !err; i = env->callx_edges[i - 1].next)
+ 			err = bpf_call_graph_add(cg, s, env->callx_edges[i - 1].callee);
+ 	}
+ 	if (err)
+ 		return err;
+ 	bpf_call_graph_sort(cg, 0);
  
- 	i = subprog[idx].start;
- 	if (!priv_stack_supported)
- 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
- process_func:
- 	dinfo[idx].callx_insn = -1;
- 	if (subprog[idx].has_ld_abs) {
- 		for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) {
- 			if (subprog[tmp].is_cb) {
- 				verbose(env, "cannot use BPF_LD_[ABS|IND] within callback\n");
+ 	for (s = 0; s < cnt; s++)
+ 		if (!s || si[s].is_async_cb)
+ 			cg->marks[s] = CG_LIVE;
+ 	bpf_call_graph_mark_callees(cg, CG_LIVE);
+ 	for_each_marked_subprog(cg, s, CG_LIVE)
+ 		cg->marks[s] |= (si[s].is_cb ? CG_CB | CG_IN_CB : 0) |
+ 				(si[s].is_async_cb ? CG_IN_ASYNC_CB : 0) |
+ 				(bpf_call_graph_recursive(cg, s) ? CG_IN_RECURSION : 0) |
+ 				(si[s].has_tail_call ? CG_TAIL_CALL : 0) |
+ 				(si[s].uses_arena_sp ? CG_ARENA_SP : 0) |
+ 				(bpf_subprog_is_global(env, s) ? CG_GLOBAL : 0);
+ 	bpf_call_graph_mark_callees(cg, CG_IN_CB | CG_IN_ASYNC_CB | CG_IN_RECURSION);
+ 	bpf_call_graph_mark_callers(cg, CG_TAIL_CALL, 0);
+ 	return 0;
+ }
+ 
+ static bool subprog_calls(struct bpf_call_graph *cg, u32 caller, u32 callee)
+ {
+ 	u32 j;
+ 
+ 	bpf_for_each_callee(cg, caller, j)
+ 		if (j == callee)
+ 			return true;
+ 	return false;
+ }
+ 
+ /* the insn of subprog 'caller' that is the edge to subprog 'callee' */
+ static int find_call_insn(struct bpf_verifier_env *env, int caller, int callee)
+ {
+ 	struct bpf_subprog_info *si = env->subprog_info;
+ 	struct bpf_insn *insn = env->prog->insnsi;
+ 	int i, end = si[caller + 1].start;
+ 
+ 	for (i = si[caller].start; i < end; i++)
+ 		if (bpf_pseudo_call(insn + i) && i + insn[i].imm + 1 == si[callee].start)
+ 			return i;
+ 	/* It's not recorded which callx or helper calls what. Take the first one. */
+ 	for (i = si[caller].start; i < end - 1; i++)
+ 		if (bpf_is_callx(insn + i) || bpf_calls_callback(env, i))
+ 			break;
+ 	return i;
+ }
+ 
+ /* The exception callback is an async callback, so only a call is an edge to it */
+ static int check_exception_cb(struct bpf_verifier_env *env, struct bpf_call_graph *cg)
+ {
+ 	int cb = env->exception_callback_subprog, s;
+ 
+ 	for_each_marked_subprog(cg, s, CG_LIVE) {
+ 		if (!cb || !subprog_calls(cg, s, cb))
+ 			continue;
+ 		verbose(env, "insn %d cannot call exception cb directly\n",
+ 			find_call_insn(env, s, cb));
+ 		return -EINVAL;
+ 	}
+ 	return 0;
+ }
+ 
+ static bool bpf_prog_reenters_datapath(const struct bpf_prog *prog);
+ 
+ /*
+  * Every subprog on a cycle has to check the stack at run time. mark_recursive_subprogs()
+  * didn't see the cycle coming when a helper got the callback from a table of
+  * functions, or from another subprog. A subprog that it marked for callx, which turned out
+  * to call something else, needs no check.
+  */
+ static int check_recursion(struct bpf_verifier_env *env, struct bpf_call_graph *cg)
+ {
+ 	bool reenters = bpf_prog_reenters_datapath(env->prog);
+ 	int j, s;
+ 
+ 	for_each_marked_subprog(cg, s, CG_LIVE) {
+ 		if (!bpf_call_graph_recursive(cg, s)) {
+ 			env->subprog_info[s].recursive = false;
+ 			continue;
+ 		}
+ 		if (env->subprog_info[s].recursive) {
+ 			/*
+ 			 * These progs run on top of other progs. Their frames belong in the
+ 			 * private stack, which has room for one frame of a subprog. A kprobe prog
+ 			 * that can be attached to a uprobe has no private stack, and is no better.
+ 			 */
+ 			if ((bpf_enable_priv_stack(env->prog) != NO_PRIV_STACK ||
+ 			     env->prog->type == BPF_PROG_TYPE_KPROBE) &&
+ 			    !env->prog->aux->priv_stack_requested) {
+ 				verbose(env, "recursive %s() in a tracing program\n",
+ 					bpf_subprog_name(env, s));
  				return -EINVAL;
  			}
- 		}
- 	}
- 
- 	/* protect against potential stack overflow that might happen when
- 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
- 	 * depth for such case down to 256 so that the worst case scenario
- 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
- 	 * 8k).
- 	 *
- 	 * To get the idea what might happen, see an example:
- 	 * func1 -> sub rsp, 128
- 	 *  subfunc1 -> sub rsp, 256
- 	 *  tailcall1 -> add rsp, 256
- 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
- 	 *   subfunc2 -> sub rsp, 64
- 	 *   subfunc22 -> sub rsp, 128
- 	 *   tailcall2 -> add rsp, 128
- 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
- 	 *
- 	 * tailcall will unwind the current stack frame but it will not get rid
- 	 * of caller's stack as shown on the example above.
- 	 */
- 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
- 		verbose(env,
- 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
- 			depth);
- 		return -EACCES;
- 	}
- 
- 	subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth);
- 	if (IS_ENABLED(CONFIG_X86_64) && subprog[idx].stack_arg_cnt) {
- 		/* x86-64 uses R9 for both private stack frame pointer and arg6. */
- 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
- 	} else if (priv_stack_supported) {
- 		/* Request private stack support only if the subprog stack
- 		 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to
- 		 * avoid jit penalty if the stack usage is small.
- 		 */
- 		if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN &&
- 		    subprog_depth >= BPF_PRIV_STACK_MIN_SIZE)
- 			subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE;
- 	}
- 
- 	if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
- 		if (subprog_depth > env->max_stack_depth)
- 			env->max_stack_depth = subprog_depth;
- 		if (subprog_depth > env->stack_limit) {
- 			verbose(env, "stack size of subprog %d is %d. Too large\n",
- 				idx, subprog_depth);
- 			return -EACCES;
- 		}
- 	} else {
- 		depth += subprog_depth;
- 		if (depth > env->max_stack_depth)
- 			env->max_stack_depth = depth;
- 		if (depth > env->stack_limit) {
- 			total = 0;
- 			for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller)
- 				total++;
- 
- 			verbose(env, "combined stack size of %d calls is %d. Too large\n",
- 				total, depth);
- 			return -EACCES;
- 		}
- 	}
- continue_func:
- 	subprog_end = subprog[idx + 1].start;
- 	for (; i < subprog_end; i++) {
- 		int next_insn, sidx;
- 
- 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off &&
- 		    bpf_is_throw_kfunc(insn + i)) {
- 			bool err = false;
- 
- 			for (tmp = idx; tmp >= 0 && !err; tmp = dinfo[tmp].caller) {
- 				if (subprog[tmp].is_cb) {
- 					err = true;
- 					break;
- 				}
+ 			/* It runs on top of its own frames. The half of the stack is not enough. */
+ 			if (reenters) {
+ 				verbose(env, "recursive %s() in a program that calls bpf_clone_redirect()\n",
+ 					bpf_subprog_name(env, s));
+ 				return -EINVAL;
  			}
- 			if (!err)
+ 			if (bpf_prog_has_invocation_budget(env->prog))
+ 				continue;
+ 			verbose(env, "JIT does not support recursive calls\n");
+ 			return -EOPNOTSUPP;
+ 		}
+ 		/* the last call of the cycle */
+ 		for (j = 0; cg->cycle[j] != cg->cycle[s] || !subprog_calls(cg, j, s); j++)
+ 			;
+ 		verbose(env, "recursive call from %s() to %s()\n",
+ 			bpf_subprog_name(env, j), bpf_subprog_name(env, s));
+ 		bpf_diag_program_structure(
+ 			env, find_call_insn(env, j, s), "recursive subprogram call",
+ 			"Load the address of the callback in the subprogram that passes it to the helper, or rewrite the recursion as a loop.",
+ 			"This call or callback closes a cycle of the call graph that was not seen before the main pass: "
+ 			"the callback comes from a table of functions or from another subprogram. Nothing checks the stack.");
+ 		return -EINVAL;
+ 	}
+ 	return 0;
+ }
+ 
+ static int check_callbacks(struct bpf_verifier_env *env, struct bpf_call_graph *cg)
+ {
+ 	struct bpf_subprog_info *si = env->subprog_info;
+ 	struct bpf_insn *insn = env->prog->insnsi;
+ 	int i, s;
+ 
+ 	for_each_marked_subprog(cg, s, CG_IN_CB) {
+ 		if (si[s].has_ld_abs) {
+ 			verbose(env, "cannot use BPF_LD_[ABS|IND] within callback\n");
+ 			return -EINVAL;
+ 		}
+ 		for (i = si[s].start; i < si[s + 1].start; i++) {
+ 			if (!bpf_is_throw_kfunc(insn + i) || !env->insn_aux_data[i].seen)
  				continue;
  			verbose(env,
  				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
- 				i, idx);
+ 				i, s);
  			return -EINVAL;
  		}
+ 	}
+ 	return 0;
+ }
  
- 		if (bpf_is_callx(insn + i) || bpf_calls_callback(env, i)) {
- 			/*
- 			 * Walk the callees and the callbacks recorded by
- 			 * the main verification pass one by one, returning to
- 			 * this insn after each.
- 			 */
- 			if (dinfo[idx].callx_insn != i) {
- 				dinfo[idx].callx_insn = i;
- 				dinfo[idx].callx_next = 0;
- 			}
- 			sidx = next_callx_callee(env, idx, dinfo[idx].callx_next);
- 			if (sidx < 0)
- 				continue;
- 			dinfo[idx].callx_next = sidx + 1;
- 			dinfo[idx].ret_insn = i;
- 			next_insn = subprog[sidx].start;
- 		} else if (bpf_pseudo_call(insn + i) || bpf_pseudo_func(insn + i)) {
- 			/* find the callee */
- 			next_insn = i + insn[i].imm + 1;
- 			sidx = bpf_find_subprog(env, next_insn);
- 			if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn))
- 				return -EFAULT;
- 			if (subprog[sidx].is_async_cb) {
- 				/* async callbacks don't increase bpf prog stack size unless called directly */
- 				if (!bpf_pseudo_call(insn + i))
- 					continue;
- 				if (subprog[sidx].is_exception_cb) {
- 					verbose(env, "insn %d cannot call exception cb directly", i);
- 					return -EINVAL;
- 				}
- 			}
- 			/* remember insn to return to */
- 			dinfo[idx].ret_insn = i + 1;
- 		} else {
+ /*
+  * Mark the subprogs that get to a tail call as tail call reachable subprogs;
+  * this info will be utilized by JIT so that we will be preserving the
+  * tail call counter throughout bpf2bpf calls combined with tailcalls
+  */
+ static int check_tail_calls(struct bpf_verifier_env *env, struct bpf_call_graph *cg)
+ {
+ 	struct bpf_subprog_info *si = env->subprog_info;
+ 	int s;
+ 
+ 	for_each_marked_subprog(cg, s, CG_LIVE) {
+ 		if (!(cg->marks[s] & CG_TAIL_CALL))
  			continue;
+ 		if (si[s].is_cb) {
+ 			verbose(env, "cannot tail call within callback\n");
+ 			return -EINVAL;
+ 		}
+ 		if (si[s].stack_arg_cnt) {
+ 			verbose(env, "tail_calls are not allowed in programs with stack args\n");
+ 			return -EINVAL;
+ 		}
+ 		/*
+ 		 * JITs pass tail call counter in a register that is
+ 		 * not available when the callee is called via callx.
+ 		 */
+ 		if (si[s].via_callx) {
+ 			verbose(env, "tail_calls are not allowed in functions called via callx\n");
+ 			return -EINVAL;
+ 		}
+ 		si[s].tail_call_reachable = true;
+ 	}
+ 	if (si[0].tail_call_reachable)
+ 		env->prog->aux->tail_call_reachable = true;
+ 	return 0;
+ }
+ 
+ /*
+  * The kernel calls a callback. It knows nothing about r12. So a callback takes a
+  * stack in arena, like the main prog does, when it uses r12 or calls what
+  * does. The callbacks below it are not its business: they take their own.
+  */
+ static void mark_arena_stack_entries(struct bpf_verifier_env *env, struct bpf_call_graph *cg)
+ {
+ 	int s;
+ 
+ 	bpf_call_graph_sort(cg, CG_CB);
+ 	bpf_call_graph_mark_callers(cg, CG_ARENA_SP, CG_CB);
+ 	for_each_marked_subprog(cg, s, CG_CB)
+ 		env->subprog_info[s].arena_stack_entry = cg->marks[s] & CG_ARENA_SP;
+ }
+ 
+ /* temporary state used for call frame depth calculation */
+ struct bpf_subprog_call_depth_info {
+ 	int calls; /* the number of frames that take the most on the stack */
+ 	int depth; /* the most that the frames of the callers take */
+ 	int arena_depth; /* the same in the stack in arena */
+ 	int frame; /* the most consecutive static call stack frames on top of stack */
+ };
+ 
+ /* what the frame of the subprog adds to the frames of its callers */
+ static int subprog_stack_size(struct bpf_verifier_env *env, int s)
+ {
+ 	struct bpf_subprog_info *sub = &env->subprog_info[s];
+ 
+ 	if (sub->priv_stack_mode == PRIV_STACK_ADAPTIVE)
+ 		return 0;
+ 	return round_up_stack_depth(env, sub->stack_depth);
+ }
+ 
+ static void max_call_depth(struct bpf_subprog_call_depth_info *to,
+ 			   const struct bpf_subprog_call_depth_info *from)
+ {
+ 	if (from->depth > to->depth || !to->calls) {
+ 		to->depth = max(to->depth, from->depth);
+ 		to->calls = from->calls;
+ 	}
+ 	to->arena_depth = max(to->arena_depth, from->arena_depth);
+ }
+ 
+ /*
+  * A subprog is entered with no more than what one of its callers is entered with plus
+  * the frame of that caller. Not when both are recursive: the callee checks the stack at run
+  * time. A cycle adds nothing: all subprogs on it have the same.
+  * The count of frames starts anew in a global subprog.
+  */
+ static void compute_call_depth(struct bpf_verifier_env *env, struct bpf_call_graph *cg,
+ 			       struct bpf_subprog_call_depth_info *dinfo)
+ {
+ 	struct bpf_subprog_call_depth_info in, out, *callee;
+ 	struct bpf_subprog_info *si = env->subprog_info;
+ 	u32 start, end, i, j, s;
+ 	int frame;
+ 
+ 	memset(dinfo, 0, cg->cnt * sizeof(*dinfo));
+ 	bpf_call_graph_sort(cg, 0);
+ 	for (end = cg->cnt; end; end = start) {
+ 		start = cg->cycle[cg->order[end - 1]];
+ 		for (i = start, in = dinfo[cg->order[i]]; i < end; i++)
+ 			max_call_depth(&in, &dinfo[cg->order[i]]);
+ 		for (i = start; i < end; i++) {
+ 			s = cg->order[i];
+ 			if (!(cg->marks[s] & CG_LIVE))
+ 				continue;
+ 			bpf_for_each_callee(cg, s, j) {
+ 				out = in;
+ 				out.calls++;
+ 				if (!si[s].recursive || !si[j].recursive) {
+ 					out.depth += subprog_stack_size(env, s);
+ 					out.arena_depth += si[s].arena_stack_depth;
+ 				}
+ 				max_call_depth(&dinfo[j], &out);
+ 			}
+ 		}
+ 	}
+ 
+ 	bpf_call_graph_sort(cg, CG_GLOBAL);
+ 	for (end = cg->cnt; end; end = start) {
+ 		start = cg->cycle[cg->order[end - 1]];
+ 		for (i = start, frame = 0; i < end; i++)
+ 			frame = max(frame, dinfo[cg->order[i]].frame);
+ 		for (i = start; i < end; i++) {
+ 			bpf_for_each_callee(cg, cg->order[i], j) {
+ 				callee = &dinfo[j];
+ 				if (!(cg->marks[cg->order[i]] & CG_LIVE) ||
+ 				    (cg->marks[j] & CG_GLOBAL))
+ 					continue;
+ 				callee->frame = max(callee->frame, frame + !si[j].recursive);
+ 			}
+ 		}
+ 	}
+ }
+ 
+ /*
+  * The stack in arena has no check of its own, see bpf_insert_recursion_checks(). A frame
+  * of a recursive subprog takes at least the same part of a half of the kernel stack as of the
+  * room in the stack in arena: there is room in arena for the frames that pass the check. The
+  * last of them and the one that doesn't pass come on top.
+  *
+  * Returns 1 when frames in the kernel stack grew.
+  */
+ static int pad_recursive_frames(struct bpf_verifier_env *env, struct bpf_call_graph *cg,
+ 				struct bpf_subprog_call_depth_info *dinfo)
+ {
+ 	struct bpf_subprog_info *si = env->subprog_info;
+ 	u32 arena_frame = 0, depth = 0, room, frame;
+ 	int s;
+ 
+ 	for_each_marked_subprog(cg, s, CG_LIVE) {
+ 		depth = max_t(u32, depth, dinfo[s].arena_depth + si[s].arena_stack_depth);
+ 		if (si[s].recursive)
+ 			arena_frame = max(arena_frame, si[s].arena_stack_depth);
+ 	}
+ 	if (!arena_frame)
+ 		return 0;
+ 	if (depth + 2 * arena_frame >= BPF_ARENA_STACK_MAX)
+ 		goto no_room;
+ 	room = BPF_ARENA_STACK_MAX - depth - 2 * arena_frame;
+ 	env->max_arena_stack_depth = BPF_ARENA_STACK_MAX;
+ 
+ 	for_each_marked_subprog(cg, s, CG_LIVE) {
+ 		if (!si[s].recursive)
+ 			continue;
+ 		frame = DIV_ROUND_UP(si[s].arena_stack_depth * (THREAD_SIZE / 2), room);
+ 		if (frame > env->stack_limit)
+ 			goto no_room;
+ 		si[s].stack_depth = max(si[s].stack_depth, frame);
+ 	}
+ 	return 1;
+ no_room:
+ 	verbose(env, "no room in the stack in arena for recursion\n");
+ 	return -EACCES;
+ }
+ 
+ static int check_call_depth(struct bpf_verifier_env *env, struct bpf_call_graph *cg)
+ {
+ 	struct bpf_subprog_info *si = env->subprog_info;
+ 	struct bpf_subprog_call_depth_info *dinfo;
+ 	int depth, s, err;
+ 
+ 	dinfo = kvzalloc_objs(*dinfo, cg->cnt, BPF_VERIFIER_GFP);
+ 	if (!dinfo)
+ 		return -ENOMEM;
+ 	compute_call_depth(env, cg, dinfo);
+ 	err = pad_recursive_frames(env, cg, dinfo);
+ 	if (err < 0)
+ 		goto out;
+ 	if (err)
+ 		compute_call_depth(env, cg, dinfo);
+ 
+ 	for_each_marked_subprog(cg, s, CG_LIVE) {
+ 		/* A caller of it is over a limit. That one is reported, not what it calls. */
+ 		if (dinfo[s].frame > MAX_CALL_FRAMES || dinfo[s].depth > env->stack_limit ||
+ 		    dinfo[s].arena_depth > BPF_ARENA_STACK_MAX)
+ 			continue;
+ 
+ 		err = -E2BIG;
+ 		if (dinfo[s].frame >= MAX_CALL_FRAMES) {
+ 			verbose(env, "the call stack of %d frames is too deep !\n",
+ 				dinfo[s].frame);
+ 			goto out;
+ 		}
+ 
+ 		err = -EOPNOTSUPP;
+ 		if (dinfo[s].frame >= MAX_CALL_FRAMES_INTERP) {
+ 			if (!env->prog->jit_requested) {
+ 				verbose(env, "JIT is required for a call stack of more than %d frames\n",
+ 					MAX_CALL_FRAMES_INTERP);
+ 				goto out;
+ 			}
+ 			env->prog->jit_required = true;
+ 		}
+ 
+ 		err = -EACCES;
+ 		depth = dinfo[s].arena_depth + si[s].arena_stack_depth;
+ 		if (depth > env->max_arena_stack_depth)
+ 			env->max_arena_stack_depth = depth;
+ 		if (depth > BPF_ARENA_STACK_MAX) {
+ 			verbose(env, "combined size of the frames in the stack in arena is %d. Too large\n",
+ 				depth);
+ 			goto out;
  		}
  
  		/*
- 		 * sort_subprogs_topo() tolerates cycles in the call graph that
- 		 * go through the address of a function being taken, since it
- 		 * doesn't know what it is taken for. Such cycle is a recursion
- 		 * unless it's an async callback, which are skipped above.
- 		 * The main verification pass limits the depth of the recursion,
- 		 * but it doesn't follow calls of global functions.
+ 		 * protect against potential stack overflow that might happen when
+ 		 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
+ 		 * depth for such case down to 256 so that the worst case scenario
+ 		 * would result in 8k stack size (32 which is tailcall limit * 256 =
+ 		 * 8k).
+ 		 *
+ 		 * To get the idea what might happen, see an example:
+ 		 * func1 -> sub rsp, 128
+ 		 *  subfunc1 -> sub rsp, 256
+ 		 *  tailcall1 -> add rsp, 256
+ 		 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
+ 		 *   subfunc2 -> sub rsp, 64
+ 		 *   subfunc22 -> sub rsp, 128
+ 		 *   tailcall2 -> add rsp, 128
+ 		 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
+ 		 *
+ 		 * tailcall will unwind the current stack frame but it will not get rid
+ 		 * of caller's stack as shown on the example above.
  		 */
- 		for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) {
- 			if (tmp != sidx)
- 				continue;
- 			verbose(env, "recursive call from %s() to %s()\n",
- 				bpf_subprog_name(env, idx), bpf_subprog_name(env, sidx));
- 			bpf_diag_program_structure(
- 				env, i, "recursive subprogram call",
- 				"Rewrite the recursion as an explicit bounded loop, or split the logic so subprogram calls do not form a cycle.",
- 				"This call or callback would make the subprogram call graph recursive. "
- 				"The verifier requires a finite, acyclic call graph so it can bound stack depth and analysis.");
- 			return -EINVAL;
+ 		depth = dinfo[s].depth;
+ 		/* nor of the frames of recursive subprogs, see bpf_insert_recursion_checks() */
+ 		si[s].in_recursion = cg->marks[s] & CG_IN_RECURSION;
+ 		if (si[s].in_recursion)
+ 			depth += THREAD_SIZE / 2;
+ 		if (s && si[s].has_tail_call && depth >= 256) {
+ 			verbose(env,
+ 				"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
+ 				depth);
+ 			goto out;
  		}
  
- 		/* store caller info for after we return from callee */
- 		dinfo[idx].frame = frame;
- 
- 		/* push caller idx into callee's dinfo */
- 		dinfo[sidx].caller = idx;
- 		dinfo[sidx].via_callx = bpf_is_callx(insn + i);
- 
- 		i = next_insn;
- 
- 		idx = sidx;
- 		if (!priv_stack_supported)
- 			subprog[idx].priv_stack_mode = NO_PRIV_STACK;
- 
- 		/* sync tail_call_reachable with callee state on entry */
- 		tail_call_reachable = subprog[idx].has_tail_call;
- 
- 		frame = bpf_subprog_is_global(env, idx) ? 0 : frame + 1;
- 		if (frame >= MAX_CALL_FRAMES) {
- 			verbose(env, "the call stack of %d frames is too deep !\n",
- 				frame);
- 			return -E2BIG;
+ 		if (si[s].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
+ 			depth = round_up_stack_depth(env, si[s].stack_depth);
+ 			if (depth > env->max_stack_depth)
+ 				env->max_stack_depth = depth;
+ 			if (depth > env->stack_limit) {
+ 				verbose(env, "stack size of subprog %d is %d. Too large\n",
+ 					s, depth);
+ 				goto out;
+ 			}
+ 			continue;
+ 		}
+ 		depth = dinfo[s].depth + subprog_stack_size(env, s);
+ 		if (depth > env->max_stack_depth)
+ 			env->max_stack_depth = depth;
+ 		if (depth > env->stack_limit) {
+ 			verbose(env, "combined stack size of %d calls is %d. Too large\n",
+ 				dinfo[s].calls + 1, depth);
+ 			goto out;
  		}
- 		goto process_func;
  	}
- 	/* if tail call got detected across bpf2bpf calls then mark each of the
- 	 * currently present subprog frames as tail call reachable subprogs;
- 	 * this info will be utilized by JIT so that we will be preserving the
- 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
- 	 */
- 	if (tail_call_reachable) {
- 		for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) {
- 			if (subprog[tmp].is_cb) {
- 				verbose(env, "cannot tail call within callback\n");
- 				return -EINVAL;
+ 	err = 0;
+ out:
+ 	kvfree(dinfo);
+ 	return err;
+ }
+ 
+ /*
+  * The address of the callback at @idx goes nowhere but to a helper that keeps it for
+  * later: a timer, a work queue, call_rcu.
+  */
+ static bool func_is_kept_for_later(struct bpf_verifier_env *env, int idx, int end)
+ {
+ 	struct bpf_insn *insn = env->prog->insnsi;
+ 	u8 class, reg = insn[idx].dst_reg;
+ 	int i;
+ 
+ 	if (reg < BPF_REG_1 || reg > BPF_REG_5)
+ 		return false;
+ 	for (i = idx + 2; i < end; i++) {
+ 		class = BPF_CLASS(insn[i].code);
+ 		if (class == BPF_JMP || class == BPF_JMP32)
+ 			return bpf_is_async_callback_calling_insn(&insn[i]);
+ 		if (insn[i].dst_reg == reg)
+ 			return false;
+ 		if (bpf_is_ldimm64(&insn[i]))
+ 			i++;
+ 		else if (insn[i].src_reg == reg)
+ 			return false;
+ 	}
+ 	return false;
+ }
+ 
+ /*
+  * Find the subprogs on cycles of the call graph. It is not known yet what callx
+  * calls: it may be any subprog whose address is taken. A subprog that is
+  * marked for no reason is treated like a recursive one all the same.
+  */
+ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
+ {
+ 	struct bpf_subprog_info *si = env->subprog_info;
+ 	struct bpf_insn *insn = env->prog->insnsi;
+ 	int cnt = env->subprog_cnt, i, j, s, err;
+ 	struct bpf_call_graph cg;
+ 	bool plain_callx = false;
+ 
+ 	/* callx calls node 'cnt', which calls each subprog whose address is taken */
+ 	err = bpf_call_graph_init(&cg, cnt + 1);
+ 	for (s = 0; s < cnt; s++) {
+ 		for (i = si[s].start; i < si[s + 1].start && !err; i++) {
+ 			if (bpf_is_callx(&insn[i])) {
+ 				err = bpf_call_graph_add(&cg, s, cnt);
+ 				if (!bpf_is_unwind_goto(&insn[i + 1]))
+ 					plain_callx = true;
  			}
- 			if (subprog[tmp].stack_arg_cnt) {
- 				verbose(env, "tail_calls are not allowed in programs with stack args\n");
- 				return -EINVAL;
+ 			if (bpf_pseudo_call(&insn[i]) || bpf_pseudo_func(&insn[i])) {
+ 				j = bpf_find_subprog(env, i + insn[i].imm + 1);
+ 				if (j < 0)
+ 					continue;
+ 				/*
+ 				 * The first insns of the main prog are for the kernel. A call from
+ 				 * an async callback is on no cycle.
+ 				 */
+ 				if (!j && bpf_pseudo_call(&insn[i])) {
+ 					verbose(env, "recursive call of the main program\n");
+ 					err = -EINVAL;
+ 					goto out;
+ 				}
+ 				/* the helper that calls a callback doesn't expect it to unwind */
+ 				if (bpf_pseudo_func(&insn[i]) || !bpf_is_unwind_goto(&insn[i + 1]))
+ 					si[j].plain_call = true;
+ 				/*
+ 				 * The helper that takes a callback calls it, or keeps it: the
+ 				 * callback that arms itself again doesn't call itself.
+ 				 */
+ 				if (bpf_pseudo_call(&insn[i]) ||
+ 				    !func_is_kept_for_later(env, i, si[s + 1].start))
+ 					err = bpf_call_graph_add(&cg, s, j);
+ 				if (bpf_pseudo_func(&insn[i]))
+ 					si[j].addr_taken = true;
  			}
- 			/*
- 			 * JITs pass tail call counter in a register that is
- 			 * not available when the callee is called via callx.
- 			 */
- 			if (dinfo[tmp].via_callx) {
- 				verbose(env, "tail_calls are not allowed in functions called via callx\n");
- 				return -EINVAL;
- 			}
- 			subprog[tmp].tail_call_reachable = true;
+ 			if (bpf_is_ldimm64(&insn[i]))
+ 				i++;
  		}
- 	} else if (!idx && subprog[0].has_tail_call && subprog[0].stack_arg_cnt) {
- 		verbose(env, "tail_calls are not allowed in programs with stack args\n");
- 		return -EINVAL;
+ 	}
+ 	for (i = 0; i < env->func_ptr_cnt; i++) {
+ 		j = bpf_find_subprog(env, env->func_ptrs[i].xlated_off);
+ 		if (j >= 0)
+ 			si[j].addr_taken = true;
+ 	}
+ 	for (s = 0; s < cnt && !err; s++)
+ 		if (si[s].addr_taken)
+ 			err = bpf_call_graph_add(&cg, cnt, s);
+ 	if (err)
+ 		goto out;
+ 
+ 	/*
+ 	 * Callers of a global subprog look at can_unwind before the subprog is verified.
+ 	 * The main prog returns to the kernel.
+ 	 */
+ 	for (s = 0; s < cnt; s++) {
+ 		if (plain_callx && si[s].addr_taken)
+ 			si[s].plain_call = true;
+ 		si[s].bail_unwinds = si[s].can_unwind ||
+ 				     (s && !si[s].plain_call && !bpf_subprog_is_global(env, s) &&
+ 				      bpf_jit_supports_unwind() &&
+ 				      !bpf_prog_is_offloaded(env->prog->aux));
  	}
  
- 	if (subprog[0].tail_call_reachable)
- 		env->prog->aux->tail_call_reachable = true;
+ 	bpf_call_graph_sort(&cg, 0);
  
- 	/* end of for() loop means the last insn of the 'subprog'
- 	 * was reached. Doesn't matter whether it was JA or EXIT
- 	 */
- 	if (frame == 0 && dinfo[idx].caller < 0)
- 		return 0;
- 	if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE)
- 		depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
- 
- 	/* pop caller idx from callee */
- 	idx = dinfo[idx].caller;
- 
- 	/* retrieve caller state from its frame */
- 	frame = dinfo[idx].frame;
- 	i = dinfo[idx].ret_insn;
- 
- 	/* reset tail_call_reachable to the parent's actual state */
- 	tail_call_reachable = subprog[idx].tail_call_reachable;
- 
- 	goto continue_func;
+ 	for (s = 0; s < cnt; s++) {
+ 		if (!bpf_call_graph_recursive(&cg, s))
+ 			continue;
+ 		err = -EINVAL;
+ 		if (!s) {
+ 			verbose(env, "recursive call of the main program\n");
+ 			break;
+ 		}
+ 		/*
+ 		 * Each call of the function that it replaces is an invocation of its own: a
+ 		 * loop in the prog that it extends gets a new time slice each time.
+ 		 */
+ 		if (env->prog->type == BPF_PROG_TYPE_EXT) {
+ 			verbose(env, "recursive %s() in an extension\n", bpf_subprog_name(env, s));
+ 			break;
+ 		}
+ 		/* the device runs the insns that the driver was given, without the checks */
+ 		if (bpf_prog_is_offloaded(env->prog->aux)) {
+ 			verbose(env, "recursive %s() in an offloaded program\n",
+ 				bpf_subprog_name(env, s));
+ 			break;
+ 		}
+ 		if (si[s].has_tail_call || si[s].has_ld_abs) {
+ 			verbose(env, "recursive %s() cannot have %s\n", bpf_subprog_name(env, s),
+ 				si[s].has_tail_call ? "tail calls" : "LD_ABS");
+ 			break;
+ 		}
+ 		if (si[s].bail_insn < 0) {
+ 			verbose(env, "recursive %s() has no exit\n", bpf_subprog_name(env, s));
+ 			break;
+ 		}
+ 		si[s].recursive = true;
+ 		j = cg.cycle[s];
+ 		si[s].cycle = cg.order[j] = min_t(u32, cg.order[j], s);
+ 		err = 0;
+ 	}
+ out:
+ 	bpf_call_graph_free(&cg);
+ 	return err;
  }
  
  static int check_max_stack_depth(struct bpf_verifier_env *env)
  {
  	enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN;
- 	struct bpf_subprog_call_depth_info *dinfo;
  	struct bpf_subprog_info *si = env->subprog_info;
- 	bool priv_stack_supported;
- 	int ret;
+ 	struct bpf_call_graph cg;
+ 	int s, ret;
  
- 	dinfo = kvzalloc_objs(*dinfo, env->subprog_cnt, GFP_KERNEL_ACCOUNT);
- 	if (!dinfo)
- 		return -ENOMEM;
+ 	find_subprog_properties(env, true);
+ 	/* see bpf_remove_fastcall_spills_fills() */
+ 	for (s = 0; s < env->subprog_cnt; s++)
+ 		for (int i = si[s].start; i < si[s + 1].start && !si[s].keep_fastcall_stack; i++)
+ 			if (env->insn_aux_data[i].fastcall_spills_num)
+ 				si[s].stack_depth = -si[s].fastcall_stack_off;
  
  	for (int i = 0; i < env->subprog_cnt; i++) {
  		if (si[i].has_tail_call) {
+ 			/* the stack in arena wouldn't be returned */
+ 			if (env->uses_arena_sp) {
+ 				verbose(env, "tail_calls are not allowed in programs that use R%d\n",
+ 					BPF_REG_ARENA_SP);
+ 				return -EINVAL;
+ 			}
  			priv_stack_mode = NO_PRIV_STACK;
  			break;
  		}
  	}
+ 	/* x86 JIT has one register for both */
+ 	if (env->uses_arena_sp)
+ 		priv_stack_mode = NO_PRIV_STACK;
  
  	if (priv_stack_mode == PRIV_STACK_UNKNOWN)
  		priv_stack_mode = bpf_enable_priv_stack(env->prog);
  
- 	/* All async_cb subprogs use normal kernel stack. If a particular
- 	 * subprog appears in both main prog and async_cb subtree, that
- 	 * subprog will use normal kernel stack to avoid potential nesting.
- 	 * The reverse subprog traversal ensures when main prog subtree is
- 	 * checked, the subprogs appearing in async_cb subtrees are already
- 	 * marked as using normal kernel stack, so stack size checking can
- 	 * be done properly.
- 	 */
- 	for (int i = env->subprog_cnt - 1; i >= 0; i--) {
- 		if (!i || si[i].is_async_cb) {
- 			priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE;
- 			ret = check_max_stack_depth_subprog(env, i, dinfo,
- 					priv_stack_supported);
- 			if (ret < 0) {
- 				kvfree(dinfo);
- 				return ret;
- 			}
- 		}
- 	}
+ 	ret = build_call_graph(env, &cg);
+ 	ret = ret ?: check_exception_cb(env, &cg);
+ 	ret = ret ?: check_recursion(env, &cg);
+ 	ret = ret ?: check_callbacks(env, &cg);
+ 	ret = ret ?: check_tail_calls(env, &cg);
+ 	if (ret)
+ 		goto out;
+ 	mark_arena_stack_entries(env, &cg);
  
- 	for (int i = 0; i < env->subprog_cnt; i++) {
- 		if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
+ 	for_each_marked_subprog(&cg, s, CG_LIVE) {
+ 		/*
+ 		 * All async_cb subprogs use normal kernel stack. If a particular
+ 		 * subprog appears in both main prog and async_cb subtree, that
+ 		 * subprog will use normal kernel stack to avoid potential nesting.
+ 		 * The private stack has room for one frame of a subprog.
+ 		 * x86-64 uses R9 for both private stack frame pointer and arg6.
+ 		 */
+ 		if (priv_stack_mode != PRIV_STACK_ADAPTIVE || (cg.marks[s] & CG_IN_ASYNC_CB) ||
+ 		    si[s].recursive || (IS_ENABLED(CONFIG_X86_64) && si[s].stack_arg_cnt)) {
+ 			si[s].priv_stack_mode = NO_PRIV_STACK;
+ 			continue;
+ 		}
+ 		/*
+ 		 * Request private stack support only if the subprog stack
+ 		 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to
+ 		 * avoid jit penalty if the stack usage is small.
+ 		 */
+ 		if (round_up_stack_depth(env, si[s].stack_depth) >= BPF_PRIV_STACK_MIN_SIZE) {
+ 			si[s].priv_stack_mode = PRIV_STACK_ADAPTIVE;
  			env->prog->aux->jits_use_priv_stack = true;
- 			break;
  		}
  	}
  
- 	kvfree(dinfo);
- 
- 	return 0;
+ 	ret = check_call_depth(env, &cg);
+ out:
+ 	bpf_call_graph_free(&cg);
+ 	return ret;
  }
  
  static int __check_buffer_access(struct bpf_verifier_env *env,
@@@ -6159,59 -6217,64 +6217,64 @@@ static int check_buffer_access(struct b
  	return 0;
  }
  
- /* BPF architecture zero extends alu32 ops into 64-bit registesr */
- static void zext_32_to_64(struct bpf_reg_state *reg)
+ /* s = (u32)s. BPF architecture zero extends alu32 ops into 64-bit registers. */
+ static void scalar_zext32(struct scalar *s)
  {
- 	reg_step_check_unsigned(reg, 32);
- 	reg->var_off = tnum_subreg(reg->var_off);
- 	reg_set_urange64(reg, reg_u32_min(reg), reg_u32_max(reg));
+ 	scalar_step_check_unsigned(s, 32);
+ 	s->var_off = tnum_subreg(s->var_off);
+ 	s->r64 = cnum64_zext32(s->r32);
  }
  
- /* truncate register to smaller size (in bytes)
+ /* truncate to smaller size (in bytes)
   * must be called with size < BPF_REG_SIZE
   */
- static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
+ static void coerce_scalar_to_size(struct scalar *s, int size)
  {
  	u64 mask = (1ULL << (size * 8)) - 1;
  
- 	reg_step_check_unsigned(reg, size * 8);
+ 	scalar_step_check_unsigned(s, size * 8);
  
  	/* clear high bits in bit representation */
- 	reg->var_off = tnum_cast(reg->var_off, size);
+ 	s->var_off = tnum_cast(s->var_off, size);
  
  	/* fix arithmetic bounds */
- 	if ((reg_umin(reg) & ~mask) == (reg_umax(reg) & ~mask))
- 		reg_set_urange64(reg, reg_umin(reg) & mask, reg_umax(reg) & mask);
+ 	if ((cnum64_umin(s->r64) & ~mask) == (cnum64_umax(s->r64) & ~mask))
+ 		s->r64 = cnum64_from_urange(cnum64_umin(s->r64) & mask, cnum64_umax(s->r64) & mask);
  	else
- 		reg_set_urange64(reg, 0, mask);
+ 		s->r64 = cnum64_from_urange(0, mask);
  
  	/* If size is smaller than 32bit register the 32bit register
  	 * values are also truncated so we push 64-bit bounds into
  	 * 32-bit bounds. Above were truncated < 32-bits already.
  	 */
  	if (size < 4)
- 		__mark_reg32_unbounded(reg);
+ 		__mark_scalar32_unbounded(s);
  
- 	reg_bounds_sync(reg);
+ 	scalar_bounds_sync(s);
  }
  
- static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
+ static void set_sext64_default_val(struct scalar *s, int size)
  {
  	if (size == 1) {
- 		reg_set_srange64(reg, S8_MIN, S8_MAX);
- 		reg_set_srange32(reg, S8_MIN, S8_MAX);
+ 		s->r64 = cnum64_from_srange(S8_MIN, S8_MAX);
+ 		s->r32 = cnum32_from_srange(S8_MIN, S8_MAX);
  	} else if (size == 2) {
- 		reg_set_srange64(reg, S16_MIN, S16_MAX);
- 		reg_set_srange32(reg, S16_MIN, S16_MAX);
+ 		s->r64 = cnum64_from_srange(S16_MIN, S16_MAX);
+ 		s->r32 = cnum32_from_srange(S16_MIN, S16_MAX);
  	} else {
  		/* size == 4 */
- 		reg_set_srange64(reg, S32_MIN, S32_MAX);
- 		reg_set_srange32(reg, S32_MIN, S32_MAX);
+ 		s->r64 = cnum64_from_srange(S32_MIN, S32_MAX);
+ 		s->r32 = cnum32_from_srange(S32_MIN, S32_MAX);
  	}
- 	reg->var_off = tnum_unknown;
  }
  
- static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
+ /* The low @num_bits bits do not change. The other bits are copies of the sign. */
+ static struct tnum tnum_sext(struct tnum t, u32 num_bits)
+ {
+ 	return tnum_arshift(tnum_lshift(t, 64 - num_bits), 64 - num_bits, 64);
+ }
+ 
+ static void coerce_scalar_to_size_sx(struct scalar *s, int size)
  {
  	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
  	u64 top_smax_value, top_smin_value;
@@@ -6220,44 -6283,45 +6283,45 @@@
  	struct cnum32 r32;
  
  	/* If every value fits the signed N-bit range sign extension is a noop. */
- 	if (reg_smin(reg) >= -limit && reg_smax(reg) < limit)
+ 	if (cnum64_smin(s->r64) >= -limit && cnum64_smax(s->r64) < limit)
  		return;
  
- 	/* See commen at reg_step_check_unsigned(). */
- 	reg_step_reset(reg);
+ 	/* See comment at scalar_step_check_unsigned(). */
+ 	scalar_step_reset(s);
  
- 	if (tnum_is_const(reg->var_off)) {
- 		u64_cval = reg->var_off.value;
+ 	if (tnum_is_const(s->var_off)) {
+ 		u64_cval = s->var_off.value;
  		if (size == 1)
- 			reg->var_off = tnum_const((s8)u64_cval);
+ 			s->var_off = tnum_const((s8)u64_cval);
  		else if (size == 2)
- 			reg->var_off = tnum_const((s16)u64_cval);
+ 			s->var_off = tnum_const((s16)u64_cval);
  		else
  			/* size == 4 */
- 			reg->var_off = tnum_const((s32)u64_cval);
+ 			s->var_off = tnum_const((s32)u64_cval);
  
- 		u64_cval = reg->var_off.value;
- 		reg->r64 = cnum64_from_urange(u64_cval, u64_cval);
- 		reg->r32 = cnum32_from_urange((u32)u64_cval, (u32)u64_cval);
+ 		u64_cval = s->var_off.value;
+ 		s->r64 = cnum64_const(u64_cval);
+ 		s->r32 = cnum32_const(u64_cval);
  		return;
  	}
  
- 	top_smax_value = ((u64)reg_smax(reg) >> num_bits) << num_bits;
- 	top_smin_value = ((u64)reg_smin(reg) >> num_bits) << num_bits;
+ 	s->var_off = tnum_sext(s->var_off, num_bits);
+ 	top_smax_value = ((u64)cnum64_smax(s->r64) >> num_bits) << num_bits;
+ 	top_smin_value = ((u64)cnum64_smin(s->r64) >> num_bits) << num_bits;
  
  	if (top_smax_value != top_smin_value)
  		goto out;
  
  	/* find the s64_min and s64_min after sign extension */
  	if (size == 1) {
- 		init_s64_max = (s8)reg_smax(reg);
- 		init_s64_min = (s8)reg_smin(reg);
+ 		init_s64_max = (s8)cnum64_smax(s->r64);
+ 		init_s64_min = (s8)cnum64_smin(s->r64);
  	} else if (size == 2) {
- 		init_s64_max = (s16)reg_smax(reg);
- 		init_s64_min = (s16)reg_smin(reg);
+ 		init_s64_max = (s16)cnum64_smax(s->r64);
+ 		init_s64_min = (s16)cnum64_smin(s->r64);
  	} else {
- 		init_s64_max = (s32)reg_smax(reg);
- 		init_s64_min = (s32)reg_smin(reg);
+ 		init_s64_max = (s32)cnum64_smax(s->r64);
+ 		init_s64_min = (s32)cnum64_smin(s->r64);
  	}
  
  	s64_max = max(init_s64_max, init_s64_min);
@@@ -6265,86 -6329,100 +6329,100 @@@
  
  	/* both of s64_max/s64_min positive or negative */
  	if ((s64_max >= 0) == (s64_min >= 0)) {
- 		reg_set_srange64(reg, s64_min, s64_max);
- 		reg_set_srange32(reg, s64_min, s64_max);
- 		reg->var_off = tnum_range(s64_min, s64_max);
+ 		s->r64 = cnum64_from_srange(s64_min, s64_max);
+ 		s->r32 = cnum32_from_srange(s64_min, s64_max);
+ 		scalar_bounds_sync(s);
  		return;
  	}
  
  out:
- 	r32 = reg->r32;
- 	set_sext64_default_val(reg, size);
+ 	r32 = s->r32;
+ 	set_sext64_default_val(s, size);
  	/* the low 32 bits fit, they do not change */
  	if (cnum32_smin(r32) >= -limit && cnum32_smax(r32) < limit) {
- 		reg->r32 = r32;
- 		reg->r64 = cnum64_from_srange(cnum32_smin(r32), cnum32_smax(r32));
+ 		s->r32 = r32;
+ 		s->r64 = cnum64_from_srange(cnum32_smin(r32), cnum32_smax(r32));
  	}
+ 	scalar_bounds_sync(s);
  }
  
- static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
+ static void set_sext32_default_val(struct scalar *s, int size)
  {
  	if (size == 1)
- 		reg_set_srange32(reg, S8_MIN, S8_MAX);
+ 		s->r32 = cnum32_from_srange(S8_MIN, S8_MAX);
  	else
  		/* size == 2 */
- 		reg_set_srange32(reg, S16_MIN, S16_MAX);
- 	reg->var_off = tnum_subreg(tnum_unknown);
+ 		s->r32 = cnum32_from_srange(S16_MIN, S16_MAX);
  }
  
- static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
+ static void coerce_subreg_to_size_sx(struct scalar *s, int size)
  {
  	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
+ 	s32 field_smin, field_smax;
  	u32 top_smax_value, top_smin_value;
  	u32 num_bits = size * 8;
  
+ 	if (size == 1) {
+ 		field_smin = S8_MIN;
+ 		field_smax = S8_MAX;
+ 	} else {
+ 		/* size == 2 */
+ 		field_smin = S16_MIN;
+ 		field_smax = S16_MAX;
+ 	}
+ 
  	/*
- 	 * If value fits the non-negative half of the signed N-bit range,
- 	 * sign extension is a noop.
+ 	 * The range already fits the signed N-bit range, so (sN)v == v for every
+ 	 * value of the low 32 bits and the sign extension is a no-op.
+ 	 *
+ 	 * This has to precede scalar_step_reset() below: the base/step line stays.
+ 	 * It is about all 64 bits: scalar_zext32() in the caller discards it
+ 	 * if the upper 32 bits are not zero.
  	 */
- 	if (reg_umax(reg) < (1ULL << (num_bits - 1)))
+ 	if (cnum32_smin(s->r32) >= field_smin && cnum32_smax(s->r32) <= field_smax)
  		return;
  
- 	/* See comment at reg_step_check_unsigned(). */
- 	reg_step_reset(reg);
+ 	/* See comment at scalar_step_check_unsigned(). */
+ 	scalar_step_reset(s);
  
- 	if (tnum_is_const(reg->var_off)) {
- 		u32_val = reg->var_off.value;
+ 	if (tnum_is_const(s->var_off)) {
+ 		u32_val = s->var_off.value;
  		if (size == 1)
- 			reg->var_off = tnum_const((s8)u32_val);
+ 			s->var_off = tnum_const((s8)u32_val);
  		else
- 			reg->var_off = tnum_const((s16)u32_val);
+ 			s->var_off = tnum_const((s16)u32_val);
  
- 		u32_val = reg->var_off.value;
- 		reg_set_srange32(reg, u32_val, u32_val);
+ 		u32_val = s->var_off.value;
+ 		s->r32 = cnum32_from_srange(u32_val, u32_val);
  		return;
  	}
  
- 	top_smax_value = ((u32)reg_s32_max(reg) >> num_bits) << num_bits;
- 	top_smin_value = ((u32)reg_s32_min(reg) >> num_bits) << num_bits;
+ 	s->var_off = tnum_sext(s->var_off, num_bits);
+ 	top_smax_value = ((u32)cnum32_smax(s->r32) >> num_bits) << num_bits;
+ 	top_smin_value = ((u32)cnum32_smin(s->r32) >> num_bits) << num_bits;
  
  	if (top_smax_value != top_smin_value)
  		goto out;
  
  	/* find the s32_min and s32_min after sign extension */
  	if (size == 1) {
- 		init_s32_max = (s8)reg_s32_max(reg);
- 		init_s32_min = (s8)reg_s32_min(reg);
+ 		init_s32_max = (s8)cnum32_smax(s->r32);
+ 		init_s32_min = (s8)cnum32_smin(s->r32);
  	} else {
  		/* size == 2 */
- 		init_s32_max = (s16)reg_s32_max(reg);
- 		init_s32_min = (s16)reg_s32_min(reg);
+ 		init_s32_max = (s16)cnum32_smax(s->r32);
+ 		init_s32_min = (s16)cnum32_smin(s->r32);
  	}
  	s32_max = max(init_s32_max, init_s32_min);
  	s32_min = min(init_s32_max, init_s32_min);
  
  	if ((s32_min >= 0) == (s32_max >= 0)) {
- 		reg_set_srange32(reg, s32_min, s32_max);
- 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
+ 		s->r32 = cnum32_from_srange(s32_min, s32_max);
  		return;
  	}
  
  out:
- 	set_sext32_default_val(reg, size);
+ 	set_sext32_default_val(s, size);
  }
  
  bool bpf_map_is_rdonly(const struct bpf_map *map)
@@@ -6400,17 -6478,6 +6478,6 @@@ int bpf_map_direct_read(struct bpf_map 
  	return 0;
  }
  
- static int cmp_func_ptrs(const void *_a, const void *_b)
- {
- 	const struct bpf_func_ptr *a = _a, *b = _b;
- 
- 	if (a->map != b->map)
- 		return a->map < b->map ? -1 : 1;
- 	if (a->map_off != b->map_off)
- 		return a->map_off < b->map_off ? -1 : 1;
- 	return 0;
- }
- 
  /* Find the first pointer to a function at or after 'off' in the value of 'map' */
  static u32 func_ptr_lower_bound(struct bpf_verifier_env *env, const struct bpf_map *map, u64 off)
  {
@@@ -6459,51 -6526,6 +6526,6 @@@ struct bpf_func_ptr *bpf_map_func_ptrs(
  	return bpf_map_range_func_ptrs(env, map, 0, (u64)map->value_size, cnt);
  }
  
- /* instructions [off, off + len) replaced the instruction at 'off' */
- void bpf_adjust_func_ptrs(struct bpf_verifier_env *env, u32 off, u32 len)
- {
- 	struct bpf_func_ptr *p;
- 	u32 i;
- 
- 	if (len <= 1)
- 		return;
- 
- 	for (i = 0; i < env->func_ptr_cnt; i++) {
- 		p = &env->func_ptrs[i];
- 		if (p->xlated_off <= off || p->xlated_off == BPF_FUNC_PTR_DELETED)
- 			continue;
- 		p->xlated_off += len - 1;
- 	}
- }
- 
- /*
-  * Instructions [off, off + len) are about to be removed. It's called before
-  * the starts of subprogs are adjusted. A subprog is gone when all of its
-  * instructions are. Otherwise, e.g. when its first instruction is a nop,
-  * it starts where the removed instructions did.
-  */
- void bpf_adjust_func_ptrs_after_remove(struct bpf_verifier_env *env, u32 off, u32 len)
- {
- 	struct bpf_func_ptr *p;
- 	int subprog;
- 	u32 i;
- 
- 	for (i = 0; i < env->func_ptr_cnt; i++) {
- 		p = &env->func_ptrs[i];
- 		if (p->xlated_off < off || p->xlated_off == BPF_FUNC_PTR_DELETED)
- 			continue;
- 		if (p->xlated_off >= off + len) {
- 			p->xlated_off -= len;
- 			continue;
- 		}
- 		subprog = bpf_find_subprog(env, p->xlated_off);
- 		if (subprog > 0 && env->subprog_info[subprog + 1].start > off + len)
- 			p->xlated_off = off;
- 		else
- 			p->xlated_off = BPF_FUNC_PTR_DELETED;
- 	}
- }
- 
  #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
  #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
  #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
@@@ -7012,8 -7034,7 +7034,7 @@@ static int check_stack_access_within_bo
  		min_off = (s64)reg->var_off.value + off;
  		max_off = min_off + access_size;
  	} else {
- 		if (reg_smax(reg) >= BPF_MAX_VAR_OFF ||
- 		    reg_smin(reg) <= -BPF_MAX_VAR_OFF) {
+ 		if (offset_is_far(reg)) {
  			verbose(env, "invalid unbounded variable-offset%s stack %s\n",
  				err_extra, reg_arg_name(env, argno));
  			return -EACCES;
@@@ -7045,27 -7066,33 +7066,33 @@@
  		return err;
  	}
  
+ 	/* the callers look at each byte */
+ 	bpf_add_cost(env, max_off - min_off, BPF_COST_COPY);
+ 
  	/*
  	 * Every stack access passes through here, including buffers passed to
  	 * helpers and kfuncs and accesses into a caller's frame, so check the
  	 * fastcall contract of the frame that owns the slots once for all of
- 	 * them. Zero-sized accesses touch no stack and keep the rewrite enabled.
+ 	 * them. An empty range touches no stack and keeps the rewrite enabled.
  	 */
- 	if (access_size)
- 		check_fastcall_stack_contract(env, state, env->insn_idx, min_off);
+ 	if (min_off < max_off)
+ 		check_fastcall_stack_contract(env, state, env->insn_idx, min_off,
+ 					      !tnum_is_const(reg->var_off) ||
+ 					      env->prev_insn_idx == env->insn_idx);
  
  	/* Note that there is no stack access with offset zero, so the needed stack
  	 * size is -min_off, not -min_off+1.
  	 */
- 	return bpf_grow_stack_state(env, state, -min_off /* size */);
+ 	return grow_stack_state(env, state, -min_off /* size */);
  }
  
  static bool get_func_retval_range(struct bpf_prog *prog,
  				  struct bpf_retval_range *range)
  {
- 	if (prog->type == BPF_PROG_TYPE_LSM &&
+ 	if (IS_ENABLED(CONFIG_BPF_LSM) && prog->type == BPF_PROG_TYPE_LSM &&
  		prog->expected_attach_type == BPF_LSM_MAC &&
- 		!bpf_lsm_get_retval_range(prog, range)) {
+ 		prog->aux->attach_func_proto->type) {
+ 		bpf_lsm_get_retval_range(prog, range);
  		return true;
  	}
  	return false;
@@@ -7073,19 -7100,13 +7100,13 @@@
  
  static void add_scalar_to_reg(struct bpf_reg_state *dst_reg, s64 val)
  {
- 	struct bpf_reg_state fake_reg;
+ 	struct scalar off;
  
  	if (!val)
  		return;
  
- 	fake_reg.type = SCALAR_VALUE;
- 	__mark_reg_known(&fake_reg, val);
- 
- 	scalar_step_add(dst_reg, dst_reg, &fake_reg);
- 	scalar32_min_max_add(dst_reg, &fake_reg);
- 	scalar_min_max_add(dst_reg, &fake_reg);
- 	dst_reg->var_off = tnum_add(dst_reg->var_off, fake_reg.var_off);
- 
+ 	scalar_set_const(&off, val);
+ 	scalar_add(scalar_of(dst_reg), scalar_of(dst_reg), &off);
  	reg_bounds_sync(dst_reg);
  }
  
@@@ -7112,10 -7133,47 +7133,47 @@@ static void mark_reg_func_ptr(struct bp
  	regs[regno].subprogno = subprog;
  }
  
- /* a read from a table of functions branches into that many states at most */
- #define BPF_MAX_FUNC_PTR_TARGETS 64
- /* and that many pointers at most are next to what is read at variable offset */
- #define BPF_MAX_FUNC_PTR_RANGE 4096
+ /*
+  * A load from a table of functions gives one register: a pointer to one of a set of functions.
+  * One state for each function would differ in nothing else up to the call, and there every
+  * function of the set is verified.
+  * Equal sets have the same number, so registers are compared as they are.
+  */
+ static int mark_reg_func_set(struct bpf_verifier_env *env, struct bpf_reg_state *regs, int regno,
+ 			     const u32 *subprogs, u32 n)
+ {
+ 	struct bpf_func_set *set;
+ 	u64 key;
+ 	int i;
+ 
+ 	mark_reg_func_ptr(env, regs, regno, n == 1 ? subprogs[0] : 0);
+ 	if (n == 1)
+ 		return 0;
+ 
+ 	/* sets with the same hash have keys in a row */
+ 	key = (u64)jhash2(subprogs, n, 0) << 32;
+ 	for (; (i = bpf_index_find(&env->func_set_index, key)) >= 0; key++) {
+ 		set = env->func_sets[i];
+ 		if (set->cnt == n && !memcmp(set->subprog, subprogs, n * sizeof(*subprogs)))
+ 			break;
+ 	}
+ 	if (i < 0) {
+ 		i = env->func_set_cnt;
+ 		set = kvzalloc_flex(*set, subprog, n, BPF_VERIFIER_GFP);
+ 		/* nothing fails between the entry of the index and the set that it stands for */
+ 		if (!set || !bpf_table_next(env->func_sets, i) ||
+ 		    bpf_index_add(&env->func_set_index, key, i)) {
+ 			kvfree(set);
+ 			return -ENOMEM;
+ 		}
+ 		env->mem += struct_size(set, subprog, n);
+ 		set->cnt = n;
+ 		memcpy(set->subprog, subprogs, n * sizeof(*subprogs));
+ 		env->func_sets[env->func_set_cnt++] = set;
+ 	}
+ 	regs[regno].func_set = i + 1;
+ 	return 0;
+ }
  
  /* Count up to 'limit' offsets in [min_off, max_off] that the read is possible at */
  static u32 count_read_offsets(struct tnum offs, u64 min_off, u64 max_off, u32 limit)
@@@ -7145,7 -7203,7 +7203,7 @@@
   * is possible at, e.g. var_off is the stride of the elements of an array.
   * A read of exactly one pointer yields PTR_TO_FUNC. When the offset is variable
   * and only pointers can be read, which is how an element of a table of
-  * functions is loaded, the verification continues with each of them. Other
+  * functions is loaded, it is one of them, see mark_reg_func_set(). Other
   * reads that overlap with a pointer are rejected, because their result is not
   * known until the program is jitted.
   *
@@@ -7158,20 -7216,27 +7216,27 @@@ static int check_func_ptr_read(struct b
  	struct tnum offs = tnum_add(reg->var_off, tnum_const(off));
  	struct bpf_reg_state *regs = cur_regs(env);
  	struct bpf_map *map = reg->map_ptr;
- 	struct bpf_verifier_state *branch;
- 	int subprog, targets[BPF_MAX_FUNC_PTR_TARGETS];
+ 	unsigned long *found __free(kvfree) = NULL;
+ 	u32 *targets __free(kvfree) = NULL;
  	struct bpf_func_ptr *ptrs;
  	u32 i, cnt, n = 0;
  	u64 o, lo, hi;
- 	int err;
+ 	int err, subprog;
  
  	ptrs = bpf_map_range_func_ptrs(env, map, min_off, max_off - min_off + size, &cnt);
  	if (!ptrs)
  		return -ENOENT;
- 	if (cnt > BPF_MAX_FUNC_PTR_RANGE)
- 		goto overlap;
+ 	err = bpf_add_cost_and_check(env, cnt * sizeof(u64), BPF_COST_COPY);
+ 	if (err)
+ 		return err;
+ 	targets = kvmalloc_array(min(cnt, env->subprog_cnt), sizeof(*targets), BPF_VERIFIER_GFP);
+ 	found = kvcalloc(BITS_TO_LONGS(env->subprog_cnt), sizeof(long), BPF_VERIFIER_GFP);
+ 	if (!targets || !found)
+ 		return -ENOMEM;
  
  	for (i = 0; i < cnt; i++) {
+ 		if (bpf_must_abort())
+ 			return -EINTR;
  		/* the offsets at which the read overlaps with the pointer */
  		lo = ptrs[i].map_off >= size ? ptrs[i].map_off - size + 1 : 0;
  		lo = max(lo, min_off);
@@@ -7181,17 -7246,13 +7246,13 @@@
  				continue;
  			if (o != ptrs[i].map_off || size != sizeof(u64) || value_regno < 0)
  				goto overlap;
- 			if (n == BPF_MAX_FUNC_PTR_TARGETS) {
- 				verbose(env, "read from map '%s' may yield more than %d pointers to functions\n",
- 					map->name, BPF_MAX_FUNC_PTR_TARGETS);
- 				return -E2BIG;
- 			}
  			subprog = bpf_find_subprog(env, ptrs[i].xlated_off);
  			if (verifier_bug_if(subprog <= 0, env,
  					    "no function at insn %u for map '%s' offset %u",
  					    ptrs[i].xlated_off, map->name, ptrs[i].map_off))
  				return -EFAULT;
- 			targets[n++] = subprog;
+ 			__set_bit(subprog, found);
+ 			n++;
  		}
  	}
  	/* pointers are next to what is read, e.g. the data of an array of vtables */
@@@ -7206,16 -7267,10 +7267,10 @@@
  	if (err)
  		return err;
  
- 	for (i = 0; i < n - 1; i++) {
- 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx,
- 				    env->cur_state->speculative);
- 		if (IS_ERR(branch))
- 			return PTR_ERR(branch);
- 		mark_reg_func_ptr(env, branch->frame[branch->curframe]->regs, value_regno,
- 				  targets[i]);
- 	}
- 	mark_reg_func_ptr(env, regs, value_regno, targets[n - 1]);
- 	return 0;
+ 	n = 0;
+ 	for_each_set_bit(subprog, found, env->subprog_cnt)
+ 		targets[n++] = subprog;
+ 	return mark_reg_func_set(env, regs, value_regno, targets, n);
  
  overlap:
  	verbose(env, "read of %d bytes at offset [%llu,%llu] of map '%s' overlaps with a pointer to a function\n",
@@@ -7293,8 -7348,10 +7348,10 @@@ static int check_mem_access(struct bpf_
  		return size;
  
  	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
- 	if (err)
+ 	if (err) {
+ 		bpf_note_needs_ptr(env, reg);
  		return err;
+ 	}
  
  	if (reg->type == PTR_TO_MAP_KEY) {
  		if (t == BPF_WRITE) {
@@@ -7410,12 -7467,13 +7467,13 @@@
  				if (base_type(info.reg_type) == PTR_TO_BTF_ID) {
  					regs[value_regno].btf = info.btf;
  					regs[value_regno].btf_id = info.btf_id;
- 					regs[value_regno].id = info.ref_id;
+ 					regs[value_regno].id =
+ 						ctx_arg_ref_id(env->cur_state, info.ref_arg);
  				} else if (base_type(info.reg_type) == PTR_TO_MEM) {
  					regs[value_regno].mem_size = info.mem_size;
  				}
  				if (type_may_be_null(info.reg_type) && !regs[value_regno].id)
- 					regs[value_regno].id = ++env->id_gen;
+ 					regs[value_regno].id = bpf_new_id(env);
  			}
  			regs[value_regno].type = info.reg_type;
  		}
@@@ -7506,6 -7564,7 +7564,7 @@@
  
  		verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno),
  			reg_type_str(env, reg->type));
+ 		bpf_note_needs_ptr(env, reg);
  		if (reg->type == SCALAR_VALUE)
  			kind = BPF_DIAG_DEREF_SCALAR;
  		else if (type_may_be_null(reg->type))
@@@ -7519,20 -7578,9 +7578,9 @@@
  	    regs[value_regno].type == SCALAR_VALUE) {
  		if (!is_ldsx) {
  			/* b/h/w load zero-extends, mark upper bits as known 0 */
- 			coerce_reg_to_size(&regs[value_regno], size);
+ 			coerce_scalar_to_size(scalar_of(&regs[value_regno]), size);
  		} else {
- 			/*
- 			 * Sign-extension can change the register value relative
- 			 * to a scalar it is linked with by id (e.g. a zero-
- 			 * extending fill of the same spilled stack slot), thus
- 			 * drop the shared id in that case.
- 			 */
- 			bool no_sext = reg_umax(&regs[value_regno]) <
- 					(1ULL << (size * BITS_PER_BYTE - 1));
- 
- 			coerce_reg_to_size_sx(&regs[value_regno], size);
- 			if (!no_sext)
- 				clear_scalar_id(&regs[value_regno]);
+ 			coerce_scalar_to_size_sx(scalar_of(&regs[value_regno]), size);
  		}
  	}
  
@@@ -7545,6 -7593,9 +7593,9 @@@
  static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
  			     bool allow_trust_mismatch);
  
+ static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env);
+ static int fixups_differ(struct bpf_verifier_env *env, const char *msg);
+ 
  static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn,
  			  bool strict_alignment_once, bool is_ldsx,
  			  bool allow_trust_mismatch, const char *ctx)
@@@ -7574,6 -7625,17 +7625,17 @@@
  		return err;
  
  	src_reg_type = regs[insn->src_reg].type;
+ 	/* A flexible array has no end, see btf_struct_access(). A far load from it can fault. */
+ 	if (base_type(src_reg_type) == PTR_TO_BTF_ID && offset_is_far(&regs[insn->src_reg])) {
+ 		if (BPF_CLASS(insn->code) != BPF_LDX) {
+ 			verbose(env, "BPF_ATOMIC loads from R%d with a far offset is not allowed\n",
+ 				insn->src_reg);
+ 			return -EACCES;
+ 		}
+ 		src_reg_type |= PTR_UNTRUSTED;
+ 	}
+ 	/* a fill copies it from the slot, see mark_from_unproven(); dst can be src */
+ 	regs[insn->dst_reg].from_unproven = regs[insn->src_reg].from_unproven;
  
  	/*
  	 * check_stack_read_fixed_off() may refine the modification's origin to
@@@ -7589,12 -7651,13 +7651,13 @@@
  	 * may share the insn, see save_aux_ptr_type(). Record a load that did
  	 * not produce an arena pointer from an __arena member, the only load
  	 * through a kernel struct pointer that does, next to the one
- 	 * check_arena_member_load() records, so that arena_member_fixup() can
- 	 * tell when the paths disagree.
+ 	 * check_arena_member_load() records. Fail if the insn has both.
  	 */
  	if (!err && !(base_type(src_reg_type) == PTR_TO_BTF_ID &&
  		      regs[insn->dst_reg].type == PTR_TO_ARENA))
- 		env->insn_aux_data[env->insn_idx].non_arena_load = true;
+ 		cur_aux(env)->non_arena_load = true;
+ 	if (!err && cur_aux(env)->arena_member && cur_aux(env)->non_arena_load)
+ 		return fixups_differ(env, "an insn loads an arena pointer member on one path and something else on another");
  	err = err ?: save_aux_ptr_type(env, src_reg_type,
  				       allow_trust_mismatch);
  	err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], ctx);
@@@ -7830,8 -7893,9 +7893,9 @@@ static int check_stack_range_initialize
  	u32 arg_slot = arg_slot_from_argno(argno);
  	bool uninit = clobber && meta && arg_slot < MAX_BPF_FUNC_ARGS &&
  		      (meta->arg_raw_mem.mask & BIT(arg_slot));
- 	bool raw_mode = uninit && env->allow_uninit_stack &&
- 			!(meta->arg_raw_mem.var_size_mask & BIT(arg_slot));
+ 	bool var_size = meta && arg_slot < MAX_BPF_FUNC_ARGS &&
+ 			(meta->arg_raw_mem.var_size_mask & BIT(arg_slot));
+ 	bool raw_mode = uninit && env->allow_uninit_stack && !var_size;
  
  	access_size = abs(access_size);
  
@@@ -7880,6 -7944,10 +7944,10 @@@
  		struct bpf_stack_state *ss;
  		u8 *stype;
  
+ 		/* The byte is between two accesses. See size_at_max_offset() for @var_size. */
+ 		if (reg->step > 1 && !var_size &&
+ 		    imod(i - off - reg->base, reg->step) >= access_size)
+ 			continue;
  		slot = -i - 1;
  		spi = slot / BPF_REG_SIZE;
  		if (state->allocated_stack <= slot) {
@@@ -7909,7 -7977,7 +7977,7 @@@
  		    (ss->spilled_ptr.type == SCALAR_VALUE ||
  		     env->allow_ptr_leaks)) {
  			if (clobber) {
- 				__mark_reg_unknown(env, &ss->spilled_ptr);
+ 				bpf_mark_reg_unknown(&ss->spilled_ptr);
  				for (j = 0; j < BPF_REG_SIZE; j++)
  					scrub_spilled_slot(&ss->slot_type[j]);
  			}
@@@ -7970,10 -8038,6 +8038,10 @@@ static int check_helper_mem_access(stru
  		return check_mem_region_access(env, reg, argno, 0, access_size,
  					       reg->map_ptr->key_size, false);
  	case PTR_TO_MAP_VALUE:
 +		if (reg->map_ptr->map_type == BPF_MAP_TYPE_INSN_ARRAY && !env->allow_ptr_leaks) {
 +			verbose(env, "%s leaks addr from insn_array\n", reg_arg_name(env, argno));
 +			return -EACCES;
 +		}
  		if (check_map_access_type(env, reg, 0, access_size, access_type))
  			return -EACCES;
  		return check_map_access(env, reg, argno, 0, access_size,
@@@ -8035,6 -8099,7 +8103,7 @@@
  		verbose(env, "%s type=%s ", reg_arg_name(env, argno),
  			reg_type_str(env, reg->type));
  		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
+ 		bpf_note_needs_ptr(env, reg);
  		return -EACCES;
  	}
  }
@@@ -8045,6 -8110,28 +8114,28 @@@ enum bpf_mem_size_failure 
  	BPF_MEM_SIZE_FAIL_SIZE,
  };
  
+ /*
+  * The check looks at the bytes from the smallest offset to the largest offset plus the size.
+  * The largest offset and the largest size do not have to go together:
+  *	read(buf + off, 64 - off);
+  * So the result is not the size of the access. It is 0 for off = 0..64.
+  * The checked bytes of a packet pointer are relative to the pointer. It needs the largest size.
+  */
+ static u32 size_at_max_offset(struct bpf_verifier_env *env, struct bpf_reg_state *mem_reg,
+ 			      struct bpf_reg_state *size_reg, argno_t mem_argno, argno_t size_argno)
+ {
+ 	u32 type = base_type(mem_reg->type);
+ 	s64 end;
+ 
+ 	if ((type != PTR_TO_MAP_VALUE && type != PTR_TO_MEM && type != PTR_TO_STACK) ||
+ 	    reg_smin(mem_reg) <= -BPF_MAX_VAR_OFF || reg_smax(mem_reg) >= BPF_MAX_VAR_OFF)
+ 		return reg_umax(size_reg);
+ 	end = bpf_equations_max_sum(env, reg_from_argno(mem_argno), reg_from_argno(size_argno));
+ 	end = clamp(end, reg_smax(mem_reg) + (s64)reg_umin(size_reg),
+ 		    reg_smax(mem_reg) + (s64)reg_umax(size_reg));
+ 	return end - reg_smax(mem_reg);
+ }
+ 
  /* verify arguments to helpers or kfuncs consisting of a pointer and an access
   * size.
   *
@@@ -8059,6 -8146,7 +8150,7 @@@ static int check_mem_size_reg(struct bp
  			      enum bpf_mem_size_failure *failure)
  {
  	int err = 0;
+ 	u32 size;
  
  	if (failure)
  		*failure = BPF_MEM_SIZE_FAIL_NONE;
@@@ -8102,18 -8190,16 +8194,16 @@@
  		goto size_error;
  	}
  
+ 	size = size_at_max_offset(env, mem_reg, size_reg, mem_argno, size_argno);
  	if (access_type & BPF_READ)
- 		err = check_helper_mem_access(env, mem_reg, mem_argno, reg_umax(size_reg),
+ 		err = check_helper_mem_access(env, mem_reg, mem_argno, size,
  					      BPF_READ, zero_size_allowed, meta, NULL);
  	if (!err && access_type & BPF_WRITE)
- 		err = check_helper_mem_access(env, mem_reg, mem_argno, reg_umax(size_reg),
+ 		err = check_helper_mem_access(env, mem_reg, mem_argno, size,
  					      BPF_WRITE, zero_size_allowed, meta, NULL);
  	if (err && failure)
  		*failure = BPF_MEM_SIZE_FAIL_MEMORY;
  
- 	if (!err)
- 		err = mark_arg_precision(env, size_argno);
- 
  	return err;
  
  size_error:
@@@ -8134,7 -8220,7 +8224,7 @@@ static int check_mem_reg(struct bpf_ver
  	int size, err = 0;
  
  	if (bpf_register_is_null(reg))
- 		return mark_arg_precision(env, argno);
+ 		return 0;
  	if (known_memory)
  		*known_memory = true;
  
@@@ -8164,9 -8250,6 +8254,6 @@@
  static int process_const_alloc_mem_size(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
  					argno_t argno, struct ret_mem_desc *ret_mem)
  {
- 	int regno = reg_from_argno(argno);
- 	int err;
- 
  	if (ret_mem->found) {
  		verifier_bug(env, "only one allocation size argument permitted");
  		return -EFAULT;
@@@ -8182,13 -8265,6 +8269,6 @@@
  		return -EINVAL;
  	}
  
- 	if (regno >= 0)
- 		err = mark_chain_precision(env, regno);
- 	else
- 		err = mark_stack_arg_precision(env, arg_idx_from_argno(argno));
- 	if (err)
- 		return err;
- 
  	ret_mem->size = reg->var_off.value;
  	ret_mem->found = true;
  
@@@ -8198,9 -8274,6 +8278,6 @@@
  static int process_const_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
  			     argno_t argno, struct bpf_call_arg_meta *meta)
  {
- 	int regno = reg_from_argno(argno);
- 	int err;
- 
  	if (meta->arg_constant.found) {
  		verifier_bug(env, "only one constant argument permitted");
  		return -EFAULT;
@@@ -8211,13 -8284,6 +8288,6 @@@
  		return -EINVAL;
  	}
  
- 	if (regno >= 0)
- 		err = mark_chain_precision(env, regno);
- 	else
- 		err = mark_stack_arg_precision(env, arg_idx_from_argno(argno));
- 	if (err < 0)
- 		return err;
- 
  	meta->arg_constant.found = true;
  	meta->arg_constant.value = reg->var_off.value;
  
@@@ -8806,85 -8872,6 +8876,6 @@@ static int process_iter_arg(struct bpf_
  	return 0;
  }
  
- /* Look for a previous loop entry at insn_idx: nearest parent state
-  * stopped at insn_idx with callsites matching those in cur->frame.
-  */
- static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
- 						  struct bpf_verifier_state *cur,
- 						  int insn_idx)
- {
- 	struct bpf_verifier_state_list *sl;
- 	struct bpf_verifier_state *st;
- 	struct list_head *pos, *head;
- 
- 	/* Explored states are pushed in stack order, most recent states come first */
- 	head = bpf_explored_state(env, insn_idx);
- 	list_for_each(pos, head) {
- 		sl = container_of(pos, struct bpf_verifier_state_list, node);
- 		/* If st->branches != 0 state is a part of current DFS verification path,
- 		 * hence cur & st for a loop.
- 		 */
- 		st = &sl->state;
- 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
- 		    st->dfs_depth < cur->dfs_depth)
- 			return st;
- 	}
- 
- 	return NULL;
- }
- 
- /*
-  * Check if scalar registers are exact for the purpose of not widening.
-  * More lenient than regs_exact()
-  */
- static bool scalars_exact_for_widen(const struct bpf_reg_state *rold,
- 				    const struct bpf_reg_state *rcur)
- {
- 	return !memcmp(rold, rcur, offsetof(struct bpf_reg_state, id));
- }
- 
- static void maybe_widen_reg(struct bpf_verifier_env *env,
- 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur)
- {
- 	if (rold->type != SCALAR_VALUE)
- 		return;
- 	if (rold->type != rcur->type)
- 		return;
- 	if (rold->precise || rcur->precise || scalars_exact_for_widen(rold, rcur))
- 		return;
- 	__mark_reg_unknown(env, rcur);
- }
- 
- static int widen_imprecise_scalars(struct bpf_verifier_env *env,
- 				   struct bpf_verifier_state *old,
- 				   struct bpf_verifier_state *cur)
- {
- 	struct bpf_func_state *fold, *fcur;
- 	int i, fr, num_slots;
- 
- 	for (fr = old->curframe; fr >= 0; fr--) {
- 		fold = old->frame[fr];
- 		fcur = cur->frame[fr];
- 
- 		for (i = 0; i < MAX_BPF_REG; i++)
- 			maybe_widen_reg(env,
- 					&fold->regs[i],
- 					&fcur->regs[i]);
- 
- 		num_slots = min(bpf_stack_nr_slots(fold), bpf_stack_nr_slots(fcur));
- 		for (i = 0; i < num_slots; i++) {
- 			struct bpf_stack_state *old_ss = bpf_stack_slot(fold, i);
- 			struct bpf_stack_state *cur_ss = bpf_stack_slot(fcur, i);
- 
- 			if (!bpf_is_spilled_reg(old_ss) || !bpf_is_spilled_reg(cur_ss))
- 				continue;
- 
- 			maybe_widen_reg(env, &old_ss->spilled_ptr, &cur_ss->spilled_ptr);
- 		}
- 	}
- 	return 0;
- }
- 
  static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
  						 struct bpf_call_arg_meta *meta)
  {
@@@ -8894,6 -8881,37 +8885,37 @@@
  	return &bpf_stack_slot(cur_st->frame[iter_frameno], iter_spi)->spilled_ptr;
  }
  
+ /*
+  * Every trip of a loop goes through bpf_iter_*_next(). It stops the loop if the iterator is older
+  * than the loop: every trip takes an element, and the number of elements is finite.
+  * It does not stop
+  * - the loop that makes the iterator. The iterator starts again in every trip:
+  *	while (v->x) { bpf_for(i, 0, 10) ...; }
+  *   The loops that the program entered before it made the iterator are among the first
+  *   iter.loops loops.
+  * - any loop, if no element was left already. The program knew that and did not leave.
+  */
+ static void iter_stops_loops(struct bpf_verifier_env *env, int insn_idx,
+ 			     const struct bpf_reg_state *iter)
+ {
+ 	const struct bpf_verifier_state *st = env->cur_state;
+ 	struct bpf_func_state *frame = st->frame[st->curframe];
+ 	u32 below = nr_loops_below(st, st->curframe);
+ 	struct loop_stack_entry *entry;
+ 	bool stops;
+ 	int i;
+ 
+ 	/* the loops of this subprog: flow_is_bound() doesn't look into the functions it calls */
+ 	for (i = frame->loop_stack_cnt - 1; i >= 0 && !st->speculative; i--) {
+ 		entry = &frame->loop_stack[i];
+ 		stops = iter->iter.state != BPF_ITER_STATE_DRAINED && below + i >= iter->iter.loops;
+ 		if (entry->loop->kind != BPF_LOOP_JUMPS || stops)
+ 			continue;
+ 		bpf_flow_next_is_no_bound(env, insn_idx, entry->loop->header);
+ 		return;
+ 	}
+ }
+ 
  /* process_iter_next_call() is called when verifier gets to iterator's next
   * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
   * to it as just "iter_next()" in comments below.
@@@ -8908,74 -8926,18 +8930,18 @@@
   * without having to simulate infinite amount of iterations.
   *
   * In current state, we first assume that iter_next() returned NULL and
-  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
-  * conditions we should not form an infinite loop and should eventually reach
-  * exit.
+  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED).
   *
-  * Besides that, we also fork current state and enqueue it for later
-  * verification. In a forked state we keep iterator state as ACTIVE
-  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
-  * also bump iteration depth to prevent erroneous infinite loop detection
-  * later on (see iter_active_depths_differ() comment for details). In this
-  * state we assume that we'll eventually loop back to another iter_next()
-  * calls (it could be in exactly same location or in some other instruction,
-  * it doesn't matter, we don't make any unnecessary assumptions about this,
-  * everything revolves around iterator state in a stack slot, not which
-  * instruction is calling iter_next()). When that happens, we either will come
-  * to iter_next() with equivalent state and can conclude that next iteration
-  * will proceed in exactly the same way as we just verified, so it's safe to
-  * assume that loop converges. If not, we'll go on another iteration
-  * simulation with a different input state, until all possible starting states
-  * are validated or we reach maximum number of instructions limit.
-  *
-  * This way, we will either exhaustively discover all possible input states
-  * that iterator loop can start with and eventually will converge, or we'll
-  * effectively regress into bounded loop simulation logic and either reach
-  * maximum number of instructions if loop is not provably convergent, or there
-  * is some statically known limit on number of iterations (e.g., if there is
-  * an explicit `if n > 100 then break;` statement somewhere in the loop).
-  *
-  * Iteration convergence logic in is_state_visited() relies on exact
-  * states comparison, which ignores read and precision marks.
-  * This is necessary because read and precision marks are not finalized
-  * while in the loop. Exact comparison might preclude convergence for
-  * simple programs like below:
-  *
-  *     i = 0;
-  *     while(iter_next(&it))
-  *       i++;
-  *
-  * At each iteration step i++ would produce a new distinct state and
-  * eventually instruction processing limit would be reached.
-  *
-  * To avoid such behavior speculatively forget (widen) range for
-  * imprecise scalar registers, if those registers were not precise at the
-  * end of the previous iteration and do not match exactly.
-  *
-  * This is a conservative heuristic that allows to verify wide range of programs,
-  * however it precludes verification of programs that conjure an
-  * imprecise value on the first loop iteration and use it as precise on a second.
-  * For example, the following safe program would fail to verify:
-  *
-  *     struct bpf_num_iter it;
-  *     int arr[10];
-  *     int i = 0, a = 0;
-  *     bpf_iter_num_new(&it, 0, 10);
-  *     while (bpf_iter_num_next(&it)) {
-  *       if (a == 0) {
-  *         a = 1;
-  *         i = 7; // Because i changed verifier would forget
-  *                // it's range on second loop entry.
-  *       } else {
-  *         arr[i] = 42; // This would fail to verify.
-  *       }
-  *     }
-  *     bpf_iter_num_destroy(&it);
+  * Besides that, we also fork current state. In a forked state we keep iterator
+  * state as ACTIVE (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from
+  * iter_next(). This state goes around the loop like in any other loop: what
+  * comes back to the head of the loop is joined with what is there until
+  * nothing changes, see flow.c.
   */
  static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
  				  struct bpf_call_arg_meta *meta)
  {
- 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
+ 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st;
  	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
  	struct bpf_reg_state *cur_iter, *queued_iter;
  
@@@ -8990,20 -8952,9 +8956,9 @@@
  		return -EFAULT;
  	}
  
+ 	iter_stops_loops(env, insn_idx, cur_iter);
+ 
  	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
- 		/* Because iter_next() call is a checkpoint is_state_visitied()
- 		 * should guarantee parent state with same call sites and insn_idx.
- 		 */
- 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
- 		    !same_callsites(cur_st->parent, cur_st)) {
- 			verifier_bug(env, "bad parent state for iter next call");
- 			return -EFAULT;
- 		}
- 		/* Note cur_st->parent in the call below, it is necessary to skip
- 		 * checkpoint created for cur_st by is_state_visited()
- 		 * right at this instruction.
- 		 */
- 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
  		/* branch out active iter state */
  		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
  		if (IS_ERR(queued_st))
@@@ -9011,18 -8962,14 +8966,14 @@@
  
  		queued_iter = get_iter_from_state(queued_st, meta);
  		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
- 		queued_iter->iter.depth++;
- 		if (prev_st)
- 			widen_imprecise_scalars(env, prev_st, queued_st);
  
  		queued_fr = queued_st->frame[queued_st->curframe];
  		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
  	}
  
- 	/* switch to DRAINED state, but keep the depth unchanged */
  	/* mark current iter state as drained and assume returned NULL */
  	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
- 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
+ 	__mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
  
  	return 0;
  }
@@@ -9148,7 -9095,6 +9099,6 @@@ static bool is_bpf_obj_drop_kfunc(u32 f
  static bool is_bpf_percpu_obj_drop_kfunc(u32 func_id);
  static bool is_bpf_rbtree_add_kfunc(u32 func_id);
  static int get_bpf_res_spin_lock_kfunc_flags(const struct bpf_call_arg_meta *meta);
- static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env);
  static int process_irq_flag(struct bpf_verifier_env *env,
  			    struct bpf_reg_state *reg, argno_t argno,
  			    struct bpf_call_arg_meta *meta);
@@@ -9509,6 -9455,7 +9459,7 @@@ static int check_reg_type(struct bpf_ve
  	for (j = 0; j + 1 < i; j++)
  		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
  	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
+ 	bpf_note_needs_ptr(env, reg);
  	actual = bpf_diag_fmt(env, "%s", reg_type_str(env, reg->type));
  	accepted = bpf_diag_expected_reg_types(env, compatible->types, i);
  	bpf_diag_call_arg_fmt(env, env->insn_idx, argno, meta->func_name,
@@@ -9650,7 -9597,8 +9601,8 @@@ static int check_arg_const_str(struct b
  		return -EACCES;
  	}
  
- 	if (!tnum_is_const(reg->var_off)) {
+ 	/* the cpu can speculate past the test of a variable offset */
+ 	if (!tnum_is_const(reg->var_off) && !env->bypass_spec_v1) {
  		verbose(env, "%s is not a constant address'\n", reg_arg_name(env, argno));
  		return -EACCES;
  	}
@@@ -9660,13 -9608,12 +9612,12 @@@
  		return -EACCES;
  	}
  
- 	err = check_map_access(env, reg, argno, 0,
- 			       map->value_size - reg->var_off.value, false,
- 			       ACCESS_HELPER);
+ 	err = check_map_access(env, reg, argno, 0, 1, false, ACCESS_HELPER);
  	if (err)
  		return err;
  
- 	map_off = reg->var_off.value;
+ 	/* the zero of the last string ends all strings that start before it */
+ 	map_off = reg_umax(reg);
  	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
  	if (err) {
  		verbose(env, "direct value access on string failed\n");
@@@ -9679,18 -9626,22 +9630,22 @@@
  		return -EINVAL;
  	}
  	/* the bytes of a pointer to a function are not known until the program is jitted */
- 	if (bpf_map_range_func_ptrs(env, map, map_off, strlen(str_ptr + map_off) + 1, &cnt)) {
+ 	map_off += strlen(str_ptr + map_off) + 1;
+ 	if (bpf_map_range_func_ptrs(env, map, reg_umin(reg), map_off - reg_umin(reg), &cnt)) {
  		verbose(env, "string overlaps with a pointer to a function\n");
  		return -EACCES;
  	}
  	return 0;
  }
  
- /* Returns constant key value in `value` if possible, else negative error */
- static int get_constant_map_key(struct bpf_verifier_env *env,
- 				struct bpf_reg_state *key,
- 				u32 key_size,
- 				s64 *value)
+ /*
+  * Returns the largest value of the key in `value` if it is below `max_entries`,
+  * else negative error
+  */
+ static int get_max_map_key(struct bpf_verifier_env *env,
+ 			   struct bpf_reg_state *key,
+ 			   u32 key_size, u32 max_entries,
+ 			   u64 *value)
  {
  	struct bpf_func_state *state = bpf_func(env, key);
  	struct bpf_stack_state *ss;
@@@ -9699,7 -9650,7 +9654,7 @@@
  	int spill_size = 0;
  	int zero_size = 0;
  	int stack_off;
- 	int i, err;
+ 	int i;
  	u8 *stype;
  
  	if (!env->bpf_capable)
@@@ -9732,20 -9683,16 +9687,16 @@@
  	if (spill_size != key_size)
  		return -EOPNOTSUPP;
  
+ 	/*
+ 	 * The slot has the range of the 64-bit register that was spilled. A value
+ 	 * below max_entries fits in the 4 bytes of the key.
+ 	 */
  	reg = &ss->spilled_ptr;
- 	if (!tnum_is_const(reg->var_off))
- 		/* Stack value not statically known */
+ 	if (reg_umax(reg) >= max_entries)
+ 		/* The lookup can return NULL: nothing depends on the key */
  		return -EOPNOTSUPP;
  
- 	/* We are relying on a constant value. So mark as precise
- 	 * to prevent pruning on it.
- 	 */
- 	bpf_bt_set_frame_slot(&env->bt, key->frameno, spi);
- 	err = mark_chain_precision_batch(env, env->cur_state);
- 	if (err < 0)
- 		return err;
- 
- 	*value = reg->var_off.value;
+ 	*value = reg_umax(reg);
  	return 0;
  }
  
@@@ -9862,12 -9809,8 +9813,8 @@@ static int check_func_arg(struct bpf_ve
  	if (arg_type_is_raw_mem(arg_type))
  		meta->arg_raw_mem.mask |= BIT(slot);
  
- 	if (bpf_register_is_null(reg) && type_may_be_null(arg_type)) {
- 		err = mark_arg_precision(env, argno);
- 		if (err)
- 			return err;
+ 	if (bpf_register_is_null(reg) && type_may_be_null(arg_type))
  		return 0;
- 	}
  
  	err = check_func_arg_nullability(env, reg, arg, argno, arg_type, meta, insn_idx);
  	if (err)
@@@ -9928,9 -9871,10 +9875,10 @@@
  		if (err)
  			return err;
  		if (can_elide_value_nullness(meta->map.ptr)) {
- 			err = get_constant_map_key(env, reg, key_size, &meta->const_map_key);
+ 			err = get_max_map_key(env, reg, key_size, meta->map.ptr->max_entries,
+ 					      &meta->max_map_key);
  			if (err < 0) {
- 				meta->const_map_key = -1;
+ 				meta->max_map_key = U64_MAX;
  				if (err == -EOPNOTSUPP)
  					err = 0;
  				else
@@@ -10465,8 -10409,10 +10413,10 @@@ static int check_func_args(struct bpf_v
  		err = check_outgoing_stack_args(env, caller, proto_slots, meta->func_name,
  						meta->btf, proto_slots == nargs ? args : NULL);
  		if (err)
- 			return err;
+ 			return meta->subprog_is_static ? -ENODATA : err;
  	}
+ 	/* the other errors only make BTF unreliable, see btf_check_subprog_call() */
+ 	env->no_report |= meta->subprog_is_static;
  
  	for (arg = 0; arg < nargs; arg++, prev_slot = slot, slot += nslots) {
  		const struct btf_type *t;
@@@ -11035,6 -10981,8 +10985,8 @@@ static void clear_all_pkt_pointers(stru
  			mark_reg_invalid(env, reg);
  		}
  	}));
+ 	if (env->cur_state->instance_id)
+ 		env->cur_state->changed_pkt_data = true;
  }
  
  static bool holds_pkt_pointers(struct bpf_verifier_env *env)
@@@ -11077,7 -11025,7 +11029,7 @@@ static void mark_pkt_end(struct bpf_ver
  		reg->range = AT_PKT_END;
  }
  
- static int __release_reference_nomark(struct bpf_verifier_state *state, int id)
+ static int release_reference_nomark(struct bpf_verifier_state *state, int id)
  {
  	int i;
  
@@@ -11092,16 -11040,6 +11044,6 @@@
  	return -EINVAL;
  }
  
- static int release_reference_nomark(struct bpf_verifier_env *env, int id)
- {
- 	int err;
- 
- 	err = __release_reference_nomark(env->cur_state, id);
- 	if (!err)
- 		bpf_diag_record_ref_release(env, env->insn_idx, id);
- 	return err;
- }
- 
  static int idstack_push(struct bpf_idmap *idmap, u32 id)
  {
  	int i;
@@@ -11198,7 -11136,7 +11140,7 @@@ static int invalidate_reference(struct 
  static int release_reference(struct bpf_verifier_env *env, int id)
  {
  	if (find_reference_state(env->cur_state, id))
- 		WARN_ON_ONCE(release_reference_nomark(env, id));
+ 		WARN_ON_ONCE(release_reference_nomark(env->cur_state, id));
  
  	return invalidate_reference(env, id);
  }
@@@ -11239,7 -11177,7 +11181,7 @@@ static int ref_convert_alloc_rcu_protec
  	struct bpf_reg_state *reg;
  	int err;
  
- 	err = release_reference_nomark(env, id);
+ 	err = release_reference_nomark(env->cur_state, id);
  	if (err)
  		return err;
  
@@@ -11303,8 -11241,13 +11245,13 @@@ static int setup_func_entry(struct bpf_
  	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
  		verbose(env, "the call stack of %d frames is too deep\n",
  			state->curframe + 2);
+ 		/* drop the path: a pass possibly does not have these calls in frames */
+ 		env->cur_state->infeasible |= env->path_sensitive;
  		return -E2BIG;
  	}
+ 	/* in the frames of the callers it has no end */
+ 	if (state->speculative && env->subprog_info[subprog].recursive)
+ 		return -EACCES;
  
  	if (state->frame[state->curframe + 1]) {
  		verifier_bug(env, "Frame %d already allocated", state->curframe + 1);
@@@ -11312,7 -11255,7 +11259,7 @@@
  	}
  
  	caller = state->frame[state->curframe];
- 	callee = kzalloc_obj(*callee, GFP_KERNEL_ACCOUNT);
+ 	callee = kzalloc_obj(*callee, BPF_VERIFIER_GFP);
  	if (!callee)
  		return -ENOMEM;
  	state->frame[state->curframe + 1] = callee;
@@@ -11326,6 -11269,9 +11273,9 @@@
  			callsite,
  			state->curframe + 1 /* frameno within this callchain */,
  			subprog /* subprog number within this prog */);
+ 	callee->entry_refs = state->acquired_refs;
+ 	callee->entry_rcu_locks = state->active_rcu_locks;
+ 	callee->entry_preempt_locks = state->active_preempt_locks;
  	err = set_callee_state_cb(env, caller, callee, callsite);
  	if (err)
  		goto err_out;
@@@ -11373,6 -11319,23 +11323,23 @@@ static void gen_subprog_arg_proto(cons
  	}
  }
  
+ /*
+  * The argument slots that the code of a static subprog takes, whatever its BTF says.
+  * Liveness errs on the safe side: a callx in the subprog counts as a read of all that the subprogs
+  * whose address is taken read or declare.
+  * But it misses r3-r5 of bpf_trace_printk() and the flags of bpf_get_branch_snapshot(), which
+  * their protos do not declare. Such a subprog prints or passes a wrong number under a tracer.
+  * The helpers are safe with any value there: the verifier never checks these registers.
+  */
+ static u32 code_arg_slots(struct bpf_verifier_env *env, struct bpf_subprog_info *sub)
+ {
+ 	u32 live_regs = env->insn_aux_data[sub->start].live_regs_before;
+ 
+ 	if (bpf_in_stack_arg_cnt(sub))
+ 		return MAX_BPF_FUNC_REG_ARGS + bpf_in_stack_arg_cnt(sub);
+ 	return fls((live_regs & GENMASK(BPF_REG_5, BPF_REG_1)) >> BPF_REG_1);
+ }
+ 
  static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, struct btf *btf)
  {
  	struct bpf_subprog_info *sub = subprog_info(env, subprog);
@@@ -11380,25 -11343,18 +11347,18 @@@
  	const struct btf_type *func, *func_proto;
  	struct bpf_call_arg_meta meta;
  	struct bpf_func_proto *fn;
- 	int ret, err;
+ 	int ret;
  	u32 i;
  
  	memset(&meta, 0, sizeof(meta));
  	meta.btf = btf;
  	meta.subprog_may_change_pkt = sub->changes_pkt_data;
+ 	meta.subprog_is_static = !bpf_subprog_is_global(env, subprog);
  	meta.func_name = bpf_subprog_name(env, subprog);
  
  	ret = btf_prepare_func_args(env, subprog);
- 	if (ret) {
- 		if (bpf_in_stack_arg_cnt(sub) > 0) {
- 			err = check_outgoing_stack_args(env, caller, sub->arg_slot_cnt,
- 							bpf_subprog_name(env, subprog),
- 							NULL, NULL);
- 			if (err)
- 				return err;
- 		}
+ 	if (ret)
  		return ret;
- 	}
  
  	func = btf_type_by_id(btf, env->prog->aux->func_info[subprog].type_id);
  	func_proto = btf_type_by_id(btf, func->type);
@@@ -11409,13 -11365,20 +11369,20 @@@
  	meta.func_proto = func_proto;
  
  	/*
- 	 * Check if all register arguments declared in BTF are initialized.
- 	 * If they aren't the BTF is unreliable.
+ 	 * Check if all arguments declared in BTF are initialized,
+ 	 * and if the code takes no other arguments: a trampoline keeps only
+ 	 * what BTF declares. If not, the BTF is unreliable.
  	 */
  	if (!bpf_subprog_is_global(env, subprog)) {
+ 		if (code_arg_slots(env, sub) > sub->arg_slot_cnt)
+ 			return -EINVAL;
  		for (i = 0; i < min_t(u32, sub->arg_slot_cnt, MAX_BPF_FUNC_REG_ARGS); i++)
  			if (caller->regs[BPF_REG_1 + i].type == NOT_INIT)
  				return -EINVAL;
+ 		/* check_func_args() reports a missing slot that the code loads: it has the name */
+ 		for (i = max(i, code_arg_slots(env, sub)); i < sub->arg_slot_cnt; i++)
+ 			if (!bpf_get_spilled_stack_arg(i - MAX_BPF_FUNC_REG_ARGS, caller))
+ 				return -EINVAL;
  	}
  	return check_func_args(env, &meta, env->insn_idx);
  }
@@@ -11425,6 -11388,7 +11392,7 @@@
   *
   * Returns:
   * EFAULT - there is a verifier bug. Abort verification.
+  * ENODATA - a static function loads a stack argument that is not there.
   * Other errors - there is a type mismatch or BTF is not available.
   * 0 - BTF matches with what bpf_reg_state expects.
   */
@@@ -11432,6 -11396,7 +11400,7 @@@ static int btf_check_subprog_call(struc
  {
  	struct bpf_prog *prog = env->prog;
  	struct btf *btf = prog->aux->btf;
+ 	bool no_report = env->no_report;
  	u32 btf_id;
  	int err;
  
@@@ -11446,15 -11411,26 +11415,26 @@@
  		return -EINVAL;
  
  	err = btf_check_func_arg_match(env, subprog, btf);
+ 	env->no_report = no_report;
  	/* Compiler optimizations can remove arguments from static functions
  	 * or mismatched type can be passed into a global function.
- 	 * In such cases mark the function as unreliable from BTF point of view.
+ 	 * Mark a static function as unreliable from BTF point of view. The other call is unproven.
  	 */
- 	if (err)
+ 	if (err && !bpf_subprog_is_global(env, subprog))
  		prog->aux->func_info_aux[subprog].unreliable = true;
  	return err;
  }
  
+ /* The helper returns */
+ static void leave_callback(struct bpf_func_state *caller)
+ {
+ 	struct loop_stack_entry *entry = bpf_top_loop(caller);
+ 
+ 	caller->callback_depth = 0;
+ 	if (entry && entry->loop->kind == BPF_LOOP_CALLBACK)
+ 		leave_loops(caller, caller->loop_stack_cnt - 1);
+ }
+ 
  static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
  			      int insn_idx, int subprog,
  			      set_callee_state_fn set_callee_state_cb)
@@@ -11492,6 -11468,8 +11472,8 @@@
  	if (bpf_is_async_callback_calling_insn(insn)) {
  		struct bpf_verifier_state *async_cb;
  
+ 		if (state->speculative)
+ 			return 0;
  		/* there is no real recursion here. timer and workqueue callbacks are async */
  		env->subprog_info[subprog].is_async_cb = true;
  		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
@@@ -11500,9 -11478,8 +11482,8 @@@
  		if (IS_ERR(async_cb))
  			return PTR_ERR(async_cb);
  		if (is_async_cb_sleepable(env, insn))
- 			mark_sleepable_async_cb(env);
+ 			env->sleepable_async_cb = true;
  		callee = async_cb->frame[0];
- 		callee->async_entry_cnt = state->frame[0]->async_entry_cnt + 1;
  
  		/* Convert bpf_timer_set_callback() args into timer callback args */
  		err = set_callee_state_cb(env, caller, callee, insn_idx);
@@@ -11525,7 -11502,7 +11506,7 @@@
  	    (insn->imm == BPF_FUNC_loop || insn->imm == BPF_FUNC_for_each_map_elem))
  		env->subprog_info[subprog].is_loop_cb = true;
  	else
- 		env->subprog_info[subprog].is_called = true;
+ 		env->subprog_info[subprog].is_other_cb = true;
  
  	/* for callback functions enqueue entry to callback and
  	 * proceed with next instruction within current frame.
@@@ -11539,25 -11516,284 +11520,284 @@@
  	if (err)
  		return err;
  
- 	callback_state->callback_unroll_depth++;
  	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
- 	caller->callback_depth = 0;
+ 	leave_callback(caller);
  	return 0;
  }
  
+ enum {
+ 	PROCESS_BPF_EXIT = 1,
+ 	INSN_IDX_UPDATED = 2,
+ };
+ 
  static int process_bpf_exit_full(struct bpf_verifier_env *env,
  				 bool *do_print_state, bool exception_exit);
+ static void account_current_path(struct bpf_verifier_env *env);
  
  /*
-  * Call of a static subprog. The callee is verified in the context of
-  * the caller, hence set up a new frame and continue from the first
-  * instruction of the callee.
+  * The function can be verified on its own, for the state at its entry, when
+  * what it does depends on its arguments only and it cannot get to what its
+  * callers have: nothing points to their stack.
+  *
+  * What the callers hold, references, locks and so on, is a part of that state:
+  * it matters for what the function can do.
+  */
+ 
+ /* What func_is_on_its_own() asks of an argument, be it in a register or on the stack */
+ static bool arg_needs_caller(struct bpf_verifier_env *env, const struct bpf_verifier_state *state,
+ 			     const struct bpf_subprog_info *sub, const struct bpf_reg_state *reg)
+ {
+ 	/* it can load a __ref argument from the context and release it */
+ 	if (reg->type == PTR_TO_CTX && state->acquired_refs &&
+ 	    env->prog->type == BPF_PROG_TYPE_STRUCT_OPS)
+ 		return true;
+ 	/* only the ids of what is held mean something without the caller */
+ 	if (bpf_id_is_xreg(reg->id | reg->parent_id | reg->map_uid))
+ 		return true;
+ 	/*
+ 	 * Packet pointers that share an id have ranges of the same size, see
+ 	 * find_good_pkt_pointers(). The result has the range of all calls of the instance.
+ 	 */
+ 	if (reg_is_pkt_pointer(reg) && reg->id)
+ 		return true;
+ 	/* it checks how much of the packet is there, for the caller */
+ 	if ((reg->type == PTR_TO_PACKET_END ||
+ 	     (reg->type == PTR_TO_PACKET && sub->loads_pkt_end)) && !sub->recursive)
+ 		return true;
+ 	/* or whether there is something to point to */
+ 	return type_may_be_null(reg->type) && !sub->recursive;
+ }
+ 
+ static bool func_is_on_its_own(struct bpf_verifier_env *env, struct bpf_verifier_state *state,
+ 			       int subprog)
+ {
+ 	struct bpf_func_state *caller = state->frame[state->curframe];
+ 	struct bpf_subprog_info *sub = &env->subprog_info[subprog];
+ 	u16 live = env->insn_aux_data[sub->start].live_regs_before;
+ 	u32 i;
+ 
+ 	if (sub->changes_pkt_data || sub->has_tail_call || sub->has_ld_abs ||
+ 	    sub->is_cb || sub->is_async_cb || sub->is_exception_cb)
+ 		return false;
+ 	if (env->path_sensitive)
+ 		return false;
+ 	if (sub->releases_inherited &&
+ 	    (state->acquired_refs || state->active_rcu_locks || state->active_preempt_locks))
+ 		return false;
+ 	/* what must not be done in that callback is refused by looking at the frames */
+ 	if (in_rbtree_lock_required_cb(env))
+ 		return false;
+ 	for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
+ 		if (!(live & BIT(i)))
+ 			continue;
+ 		if (caller->regs[i].type == PTR_TO_STACK ||
+ 		    base_type(caller->regs[i].type) == CONST_PTR_TO_DYNPTR)
+ 			return false;
+ 		if (arg_needs_caller(env, state, sub, &caller->regs[i]))
+ 			return false;
+ 	}
+ 	/* callx of one function of a set asks before it is checked that the arguments are there */
+ 	for (i = 0; i < bpf_in_stack_arg_cnt(sub) && i < caller->out_stack_arg_cnt; i++) {
+ 		if (caller->stack_arg_regs[i].type == PTR_TO_STACK ||
+ 		    base_type(caller->stack_arg_regs[i].type) == CONST_PTR_TO_DYNPTR)
+ 			return false;
+ 		if (arg_needs_caller(env, state, sub, &caller->stack_arg_regs[i]))
+ 			return false;
+ 	}
+ 	return sub->recursive || !bpf_call_needs_frames(env, state, live);
+ }
+ 
+ static int enter_recursion(struct bpf_verifier_env *env, struct bpf_func_state *callee);
+ static int check_held_in_leftover(struct bpf_verifier_env *env,
+ 				  const struct loop_stack_entry *entry);
+ 
+ static int call_func_on_its_own(struct bpf_verifier_env *env, int subprog, int insn_idx)
+ {
+ 	u16 live = env->insn_aux_data[env->subprog_info[subprog].start].live_regs_before;
+ 	struct bpf_verifier_state *state = env->cur_state;
+ 	struct bpf_func_state *caller = state->frame[state->curframe], *callee, *frame;
+ 	struct bpf_verifier_state entry = {};
+ 	struct bpf_reg_state *reg;
+ 	int i, err;
+ 
+ 	callee = kzalloc_obj(*callee, BPF_VERIFIER_GFP);
+ 	if (!callee)
+ 		return -ENOMEM;
+ 	entry.frame[0] = callee;
+ 	entry.speculative = state->speculative;
+ 	entry.in_sleepable = state->in_sleepable;
+ 	entry.suspect_loops = state->suspect_loops;
+ 	entry.callers_unknown = state->callers_unknown;
+ 	init_func_state(env, callee, BPF_MAIN_FUNC, 0, subprog);
+ 	/* the frame that says so is not there when the function is verified */
+ 	callee->in_rcu_callback_fn = in_rcu_callback(env);
+ 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
+ 		if (live & BIT(i))
+ 			callee->regs[i] = caller->regs[i];
+ 	i = bpf_in_stack_arg_cnt(&env->subprog_info[subprog]);
+ 	err = grow_stack_arg_slots(env, callee, i) ?: enter_recursion(env, callee);
+ 	if (err) {
+ 		bpf_free_verifier_state(env, &entry, false);
+ 		return err;
+ 	}
+ 	for (i = 0; i < callee->out_stack_arg_cnt; i++)
+ 		callee->stack_arg_regs[i] = caller->stack_arg_regs[i];
+ 
+ 	err = copy_reference_state(&entry, state);
+ 	if (err) {
+ 		bpf_free_verifier_state(env, &entry, false);
+ 		return err;
+ 	}
+ 	bpf_for_each_reg_in_vstate(&entry, frame, reg, reg->grew_once = false);
+ 	entry.max_held_cnt = state->max_held_cnt;
+ 	callee->entry_refs = entry.acquired_refs;
+ 	callee->entry_rcu_locks = entry.active_rcu_locks;
+ 	callee->entry_preempt_locks = entry.active_preempt_locks;
+ 
+ 	account_current_path(env);
+ 	env->subprog_info[subprog].on_its_own = true;
+ 	err = bpf_flow_call(env, state, &entry, subprog, insn_idx);
+ 	bpf_free_verifier_state(env, &entry, false);
+ 	/* the call waits, there is nothing to go on with */
+ 	return err ?: PROCESS_BPF_EXIT;
+ }
+ 
+ /*
+  * A void function can leave a pointer to the stack in r0. The caller cannot read it. That holds
+  * for the stack of a caller too: for stack liveness a call returns no pointer to the stack.
+  */
+ static void hide_returned_stack_ptrs(struct bpf_verifier_env *env, int subprog,
+ 				     struct bpf_reg_state *regs)
+ {
+ 	u32 i, nregs = bpf_ret_reg_pair(env, subprog) ? 2 : 1;
+ 
+ 	for (i = 0; i < nregs; i++) {
+ 		if (regs[ret_regs[i]].type != PTR_TO_STACK)
+ 			continue;
+ 		verbose(env, "the caller cannot read the stack pointer in R%d\n", ret_regs[i]);
+ 		bpf_diag_record_scrub(env, &regs[ret_regs[i]], BPF_DIAG_MOD_RET_STACK_PTR);
+ 		bpf_mark_reg_not_init(env, &regs[ret_regs[i]]);
+ 	}
+ }
+ 
+ /* The current state is at exit of a function that is verified on its own. */
+ static int exit_func_on_its_own(struct bpf_verifier_env *env)
+ {
+ 	struct bpf_verifier_state *state = env->cur_state;
+ 	struct bpf_func_state *callee = state->frame[0];
+ 	int err;
+ 
+ 	hide_returned_stack_ptrs(env, callee->subprogno, callee->regs);
+ 	state->unwound |= bpf_is_unwind_exit(&env->prog->insnsi[env->insn_idx]);
+ 
+ 	/* Invalidate callee-local dynptrs and their slices before the frame goes away. */
+ 	err = destroy_dynptrs_in_stack_slots(env, callee, 0,
+ 					     callee->allocated_stack / BPF_REG_SIZE - 1);
+ 	/* what comes out of a recursion goes around too */
+ 	if (!err && env->subprog_info[callee->subprogno].recursive)
+ 		err = check_held_in_leftover(env, callee->loop_stack);
+ 	if (err)
+ 		return err;
+ 
+ 	account_current_path(env);
+ 	err = bpf_flow_exit(env, state, env->insn_idx);
+ 	return err ?: PROCESS_BPF_EXIT;
+ }
+ 
+ static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, bool is_null);
+ 
+ static u32 returned_id(u32 id)
+ {
+ 	return bpf_id_is_xreg(id) ? BPF_RETURNED_ID(id) : id;
+ }
+ 
+ /*
+  * @caller waits at the call at @call_idx. @exit is the state at the exit of the
+  * function. Make @caller the state after the call.
+  */
+ int bpf_flow_return(struct bpf_verifier_env *env, struct bpf_verifier_state *caller,
+ 		    const struct bpf_verifier_state *exit, int call_idx)
+ {
+ 	struct bpf_func_state *frame = caller->frame[caller->curframe];
+ 	const struct bpf_func_state *callee = exit->frame[0];
+ 	u32 i, nregs, nheld = caller->acquired_refs;
+ 	struct bpf_reg_state *reg;
+ 	int err;
+ 
+ 	caller->speculative |= exit->speculative;
+ 	/*
+ 	 * Keep only what the function held all the time. The state at its exit looks the same if
+ 	 * the function released a lock and acquired it again. Else verify the function in the
+ 	 * instance of the caller.
+ 	 */
+ 	if (callee->entry_refs < nheld || callee->entry_rcu_locks < caller->active_rcu_locks ||
+ 	    callee->entry_preempt_locks < caller->active_preempt_locks) {
+ 		if (exit->speculative)
+ 			return -EACCES;
+ 		if (env->log.level & BPF_LOG_LEVEL2)
+ 			verbose(env, "func#%d releases what its caller holds at insn %d\n",
+ 				callee->subprogno, call_idx);
+ 		env->subprog_info[callee->subprogno].releases_inherited = true;
+ 		return BPF_EXIT_NEEDS_CALLER;
+ 	}
+ 	if (exit->unwound && !bpf_is_unwind_goto(&env->prog->insnsi[call_idx + 1])) {
+ 		verbose(env, "unwind_exit, but no unwind_goto after the call at insn %d\n",
+ 			call_idx);
+ 		return -EINVAL;
+ 	}
+ 	caller->unwound = exit->unwound;
+ 	caller->max_held_cnt = max(caller->max_held_cnt, exit->max_held_cnt);
+ 	caller->suspect_loops |= exit->suspect_loops;
+ 
+ 	/*
+ 	 * bpf_check_cfg() takes the subprog that loads the address of a function for the
+ 	 * one that calls it. This one got the address from its caller. What it means for
+ 	 * the packet pointers of the caller is found out in the context of the caller.
+ 	 */
+ 	if (exit->changed_pkt_data) {
+ 		if (exit->speculative)
+ 			return -EACCES;
+ 		env->subprog_info[callee->subprogno].changes_pkt_data = true;
+ 		return BPF_EXIT_NEEDS_CALLER;
+ 	}
+ 
+ 	for (i = 0; i < CALLER_SAVED_REGS; i++)
+ 		bpf_mark_reg_not_init(env, &frame->regs[caller_saved[i]]);
+ 	for (i = 0; i < frame->out_stack_arg_cnt; i++)
+ 		bpf_mark_reg_not_init(env, &frame->stack_arg_regs[i]);
+ 
+ 	/* what is held now is what was held at the call and what the function took */
+ 	err = resize_reference_state(caller, exit->acquired_refs);
+ 	if (err)
+ 		return err;
+ 	for (i = nheld; i < exit->acquired_refs; i++)
+ 		caller->refs[i] = exit->refs[i];
+ 	caller->held = exit->held;
+ 
+ 	nregs = bpf_ret_reg_pair(env, callee->subprogno) ? 2 : 1;
+ 	for (i = 0; i < nregs; i++) {
+ 		reg = &frame->regs[ret_regs[i]];
+ 		*reg = callee->regs[ret_regs[i]];
+ 		reg->id = returned_id(reg->id);
+ 		reg->parent_id = returned_id(reg->parent_id);
+ 		reg->map_uid = returned_id(reg->map_uid);
+ 		/* the function saw that a reference of the caller is not NULL */
+ 		if (reg->id && !type_may_be_null(reg->type))
+ 			mark_ptr_or_null_regs(caller, ret_regs[i], false);
+ 	}
+ 	return 0;
+ }
+ 
+ /*
+  * Call of a static subprog. Unless the callee is verified on its own it is
+  * verified in the context of the caller, hence set up a new frame and
+  * continue from the first instruction of the callee.
   */
  static int check_static_func_call(struct bpf_verifier_env *env, int subprog,
  				  int *insn_idx)
  {
+ 	struct bpf_subprog_info *caller_info, *callee_info = &env->subprog_info[subprog];
  	struct bpf_verifier_state *state = env->cur_state;
- 	struct bpf_subprog_info *caller_info;
  	u16 callee_incoming, stack_arg_cnt;
  	struct bpf_func_state *caller;
  	int err;
@@@ -11568,12 -11804,26 +11808,26 @@@
  	/*
  	 * Track caller's total stack arg count (incoming + max outgoing).
  	 * This is needed so the JIT knows how much stack arg space to allocate.
+ 	 * The callee can load less than its prototype has, and the caller can still store
+ 	 * all of it. Count the slots of the prototype only as far as the caller has stored
+ 	 * them: compilers store before the call. check_after_pass() fails for the rest.
  	 */
  	caller_info = &env->subprog_info[caller->subprogno];
- 	callee_incoming = bpf_in_stack_arg_cnt(&env->subprog_info[subprog]);
- 	stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + callee_incoming;
+ 	callee_incoming = bpf_in_stack_arg_cnt(callee_info);
+ 	stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) +
+ 			max_t(int, callee_incoming,
+ 			      min_t(int, caller_info->max_out_stack_arg_cnt,
+ 				    callee_info->arg_slot_cnt - MAX_BPF_FUNC_REG_ARGS));
  	if (stack_arg_cnt > caller_info->stack_arg_cnt)
  		caller_info->stack_arg_cnt = stack_arg_cnt;
+ 	/* btf_check_subprog_call() doesn't get to it when BTF is not reliable */
+ 	err = check_outgoing_stack_args(env, caller, MAX_BPF_FUNC_REG_ARGS + callee_incoming,
+ 					bpf_subprog_name(env, subprog), NULL, NULL);
+ 	if (err)
+ 		return err;
+ 
+ 	if (func_is_on_its_own(env, state, subprog))
+ 		return call_func_on_its_own(env, subprog, *insn_idx);
  
  	/*
  	 * For regular function entry setup new frame and continue
@@@ -11617,6 -11867,8 +11871,8 @@@ static int check_func_call(struct bpf_v
  	err = btf_check_subprog_call(env, subprog);
  	if (err == -EFAULT)
  		return err;
+ 	if (err == -ENODATA)
+ 		return -EINVAL;
  	if (bpf_subprog_is_global(env, subprog)) {
  		struct bpf_func_info_aux *sub_aux = subprog_aux(env, subprog);
  		const char *sub_name = bpf_subprog_name(env, subprog);
@@@ -11736,13 -11988,106 +11992,106 @@@
   * PTR_TO_FUNC register identifies the callee, so from here on callx is verified
   * as a direct call of that static subprog.
   */
+ static int check_func_callx_one(struct bpf_verifier_env *env, int subprog, int *insn_idx)
+ {
+ 	int err;
+ 
+ 	err = btf_check_subprog_call(env, subprog);
+ 	if (err == -EFAULT)
+ 		return err;
+ 	if (err == -ENODATA)
+ 		return -EINVAL;
+ 
+ 	/* bpf_compute_live_registers() counts on it */
+ 	if (verifier_bug_if(!env->subprog_info[subprog].addr_taken, env,
+ 			    "callx of %s() whose address is not taken",
+ 			    bpf_subprog_name(env, subprog)))
+ 		return -EFAULT;
+ 
+ 	err = record_callx_edge(env, cur_func(env)->subprogno, subprog);
+ 	if (err)
+ 		return err;
+ 	env->subprog_info[subprog].via_callx = true;
+ 
+ 	return check_static_func_call(env, subprog, insn_idx);
+ }
+ 
+ /* The insn needs to know the function: go on with each function of the set. */
+ static int split_func_set(struct bpf_verifier_env *env, int regno)
+ {
+ 	struct bpf_reg_state *reg = reg_state(env, regno);
+ 	struct bpf_verifier_state *branch;
+ 	struct bpf_func_set *set;
+ 	u32 i;
+ 
+ 	if (reg->type != PTR_TO_FUNC || !reg->func_set)
+ 		return 0;
+ 	set = env->func_sets[reg->func_set - 1];
+ 	reg->func_set = 0;
+ 	for (i = 0; i < set->cnt; i++) {
+ 		reg->subprogno = set->subprog[i];
+ 		if (i == set->cnt - 1)
+ 			break;
+ 		branch = push_stack(env, env->insn_idx, env->insn_idx, false);
+ 		if (IS_ERR(branch))
+ 			return PTR_ERR(branch);
+ 		env->head->again = true;
+ 	}
+ 	return 0;
+ }
+ 
+ /*
+  * callx of one of the functions of a set. A function that is verified on its own
+  * gets a copy of the state that waits for it. Nothing meets at an insn.
+  */
+ static int check_func_callx_set(struct bpf_verifier_env *env, int regno, int *insn_idx)
+ {
+ 	struct bpf_verifier_state *cur = env->cur_state, *copy, *branch;
+ 	struct bpf_reg_state *reg = reg_state(env, regno);
+ 	struct bpf_func_set *set = env->func_sets[reg->func_set - 1];
+ 	int err = 0;
+ 	u32 i;
+ 
+ 	/* once, and not in every copy */
+ 	account_current_path(env);
+ 	reg->func_set = 0;
+ 	for (i = 0; i < set->cnt && !err; i++) {
+ 		reg->subprogno = set->subprog[i];
+ 		if (!func_is_on_its_own(env, cur, set->subprog[i])) {
+ 			branch = push_stack(env, *insn_idx, *insn_idx, false);
+ 			if (IS_ERR(branch))
+ 				return PTR_ERR(branch);
+ 			env->head->again = true;
+ 			continue;
+ 		}
+ 		copy = kzalloc_obj(*copy, BPF_VERIFIER_GFP);
+ 		if (!copy)
+ 			return -ENOMEM;
+ 		err = bpf_copy_verifier_state(env, copy, cur);
+ 		if (!err) {
+ 			env->cur_state = copy;
+ 			err = check_func_callx_one(env, set->subprog[i], insn_idx);
+ 			env->cur_state = cur;
+ 			/* do_check_block() looks at the state that failed */
+ 			if (err < 0)
+ 				swap(*cur, *copy);
+ 		}
+ 		bpf_free_verifier_state(env, copy, true);
+ 		if (err == PROCESS_BPF_EXIT)
+ 			err = 0;
+ 		else if (verifier_bug_if(!err, env, "callx: func#%d doesn't wait", set->subprog[i]))
+ 			err = -EFAULT;
+ 	}
+ 	/* all that is to be done has a state of its own */
+ 	return err ?: PROCESS_BPF_EXIT;
+ }
+ 
  static int check_func_callx(struct bpf_verifier_env *env, struct bpf_insn *insn,
  			    int *insn_idx)
  {
- 	struct bpf_func_state *caller = cur_func(env);
  	struct bpf_reg_state *reg;
  	const char *reason;
- 	int err, subprog;
+ 	int err;
  
  	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  	if (err)
@@@ -11750,6 -12095,7 +12099,7 @@@
  
  	reg = reg_state(env, insn->dst_reg);
  	if (reg->type != PTR_TO_FUNC) {
+ 		bpf_note_needs_ptr(env, reg);
  		verbose(env, "R%d has type %s, expected func\n", insn->dst_reg,
  			reg_type_str(env, reg->type));
  		reason = bpf_diag_fmt(
@@@ -11775,16 -12121,19 +12125,19 @@@
  		return err;
  
  	/* PTR_TO_FUNC is a pointer to a static subprog */
- 	subprog = reg->subprogno;
- 	err = btf_check_subprog_call(env, subprog);
- 	if (err == -EFAULT)
- 		return err;
+ 	if (reg->func_set)
+ 		return check_func_callx_set(env, insn->dst_reg, insn_idx);
+ 	return check_func_callx_one(env, reg->subprogno, insn_idx);
+ }
  
- 	err = record_callx_edge(env, caller->subprogno, subprog);
- 	if (err)
- 		return err;
- 
- 	return check_static_func_call(env, subprog, insn_idx);
+ static void mark_map_callback_reg(struct bpf_reg_state *reg,
+ 				  const struct bpf_reg_state *map_reg,
+ 				  enum bpf_reg_type type)
+ {
+ 	reg->type = type;
+ 	__mark_reg_known_zero(reg);
+ 	reg->map_ptr = map_reg->map_ptr;
+ 	reg->map_uid = map_reg->map_uid;
  }
  
  int map_set_for_each_callback_args(struct bpf_verifier_env *env,
@@@ -11798,25 -12147,25 +12151,25 @@@
  	 */
  	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
  
- 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
- 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
- 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
- 	callee->regs[BPF_REG_2].map_uid = caller->regs[BPF_REG_1].map_uid;
- 
- 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
- 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
- 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
- 	callee->regs[BPF_REG_3].map_uid = caller->regs[BPF_REG_1].map_uid;
- 	callee->regs[BPF_REG_3].id = ++env->id_gen;
+ 	mark_map_callback_reg(&callee->regs[BPF_REG_2], &caller->regs[BPF_REG_1], PTR_TO_MAP_KEY);
+ 	mark_map_callback_reg(&callee->regs[BPF_REG_3], &caller->regs[BPF_REG_1], PTR_TO_MAP_VALUE);
+ 	callee->regs[BPF_REG_3].id = bpf_new_id(env);
  
  	/* pointer to stack or null */
  	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
- 
- 	/* unused */
- 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
  	return 0;
  }
  
+ /* The arg points into the stack frame of the helper that calls the callback */
+ void mark_frame_scoped_arg(struct bpf_verifier_env *env,
+ 			   struct bpf_func_state *callee, u32 regno)
+ {
+ 	if (!callee->frame_id)
+ 		callee->frame_id = bpf_new_id(env);
+ 	callee->regs[regno].id = callee->frame_id;
+ 	callee->regs[regno].parent_id = callee->frame_id;
+ }
+ 
  static int set_callee_state(struct bpf_verifier_env *env,
  			    struct bpf_func_state *caller,
  			    struct bpf_func_state *callee, int insn_idx)
@@@ -11882,11 -12231,6 +12235,6 @@@ static int set_loop_callback_state(stru
  	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
  	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
  
- 	/* unused */
- 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
- 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
- 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
- 
  	callee->in_callback_fn = true;
  	callee->callback_ret_range = retval_range(0, 1);
  	return 0;
@@@ -11897,33 -12241,15 +12245,15 @@@ static int set_timer_callback_state(str
  				    struct bpf_func_state *callee,
  				    int insn_idx)
  {
- 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
- 	u32 map_uid = caller->regs[BPF_REG_1].map_uid;
- 
  	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
  	 * callback_fn(struct bpf_map *map, void *key, void *value);
  	 */
- 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
- 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
- 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
- 	callee->regs[BPF_REG_1].map_uid = map_uid;
+ 	mark_map_callback_reg(&callee->regs[BPF_REG_1], &caller->regs[BPF_REG_1], CONST_PTR_TO_MAP);
+ 	mark_map_callback_reg(&callee->regs[BPF_REG_2], &caller->regs[BPF_REG_1], PTR_TO_MAP_KEY);
+ 	mark_map_callback_reg(&callee->regs[BPF_REG_3], &caller->regs[BPF_REG_1], PTR_TO_MAP_VALUE);
+ 	callee->regs[BPF_REG_3].id = bpf_new_id(env);
  
- 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
- 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
- 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
- 	callee->regs[BPF_REG_2].map_uid = map_uid;
- 
- 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
- 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
- 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
- 	callee->regs[BPF_REG_3].map_uid = map_uid;
- 	callee->regs[BPF_REG_3].id = ++env->id_gen;
- 
- 	/* unused */
- 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
- 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
  	callee->in_async_callback_fn = true;
- 	callee->callback_ret_range = retval_range(0, 0);
  	return 0;
  }
  
@@@ -11946,10 -12272,6 +12276,6 @@@ static int set_find_vma_callback_state(
  
  	/* pointer to stack or null */
  	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
- 
- 	/* unused */
- 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
- 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
  	callee->in_callback_fn = true;
  	/* bpf_find_vma() runs the callback under mmap_lock and RCU. */
  	callee->in_rcu_callback_fn = true;
@@@ -11966,15 -12288,10 +12292,10 @@@ static int set_user_ringbuf_callback_st
  	 *			  callback_ctx, u64 flags);
  	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
  	 */
- 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
  	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
+ 	mark_frame_scoped_arg(env, callee, BPF_REG_1);
  	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
  
- 	/* unused */
- 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
- 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
- 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
- 
  	callee->in_callback_fn = true;
  	callee->callback_ret_range = retval_range(0, 1);
  	return 0;
@@@ -12005,9 -12322,6 +12326,6 @@@ static int set_rbtree_add_callback_stat
  	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
  	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
  
- 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
- 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
- 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
  	callee->in_callback_fn = true;
  	callee->callback_ret_range = retval_range(0, 1);
  	return 0;
@@@ -12018,31 -12332,14 +12336,14 @@@ static int set_task_work_schedule_callb
  						 struct bpf_func_state *callee,
  						 int insn_idx)
  {
- 	struct bpf_map *map_ptr = caller->regs[BPF_REG_3].map_ptr;
- 	u32 map_uid = caller->regs[BPF_REG_3].map_uid;
- 
  	/*
  	 * callback_fn(struct bpf_map *map, void *key, void *value);
  	 */
- 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
- 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
- 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
- 	callee->regs[BPF_REG_1].map_uid = map_uid;
+ 	mark_map_callback_reg(&callee->regs[BPF_REG_1], &caller->regs[BPF_REG_3], CONST_PTR_TO_MAP);
+ 	mark_map_callback_reg(&callee->regs[BPF_REG_2], &caller->regs[BPF_REG_3], PTR_TO_MAP_KEY);
+ 	mark_map_callback_reg(&callee->regs[BPF_REG_3], &caller->regs[BPF_REG_3], PTR_TO_MAP_VALUE);
+ 	callee->regs[BPF_REG_3].id = bpf_new_id(env);
  
- 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
- 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
- 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
- 	callee->regs[BPF_REG_2].map_uid = map_uid;
- 
- 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
- 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
- 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
- 	callee->regs[BPF_REG_3].map_uid = map_uid;
- 	callee->regs[BPF_REG_3].id = ++env->id_gen;
- 
- 	/* unused */
- 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
- 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
  	callee->in_async_callback_fn = true;
  	callee->callback_ret_range = retval_range(S32_MIN, S32_MAX);
  	return 0;
@@@ -12053,30 -12350,13 +12354,13 @@@ static int set_rcu_callback_state(struc
  				  struct bpf_func_state *callee,
  				  int insn_idx)
  {
- 	struct bpf_map *map_ptr = caller->regs[BPF_REG_2].map_ptr;
- 	u32 map_uid = caller->regs[BPF_REG_2].map_uid;
- 
  	/*
  	 * callback_fn(struct bpf_map *map, void *key, void *value);
  	 */
- 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
- 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
- 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
- 	callee->regs[BPF_REG_1].map_uid = map_uid;
+ 	mark_map_callback_reg(&callee->regs[BPF_REG_1], &caller->regs[BPF_REG_2], CONST_PTR_TO_MAP);
+ 	mark_map_callback_reg(&callee->regs[BPF_REG_2], &caller->regs[BPF_REG_2], PTR_TO_MAP_KEY);
+ 	mark_map_callback_reg(&callee->regs[BPF_REG_3], &caller->regs[BPF_REG_2], PTR_TO_MAP_VALUE);
  
- 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
- 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
- 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
- 	callee->regs[BPF_REG_2].map_uid = map_uid;
- 
- 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
- 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
- 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
- 	callee->regs[BPF_REG_3].map_uid = map_uid;
- 
- 	/* unused */
- 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
- 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
  	callee->in_async_callback_fn = true;
  	callee->callback_ret_range = retval_range(S32_MIN, S32_MAX);
  	return 0;
@@@ -12089,6 -12369,7 +12373,7 @@@ static void account_processed_insn(stru
  	struct bpf_func_state *frame = cur_func(env);
  
  	env->insn_processed++;
+ 	bpf_add_cost(env, 1, BPF_COST_INSN);
  	frame->insns_subtotal++;
  	env->subprog_info[frame->subprogno].insns_self++;
  }
@@@ -12156,31 -12437,18 +12441,18 @@@ static bool retval_range_within(struct 
  
  static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
  {
- 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
+ 	struct bpf_verifier_state *state = env->cur_state;
  	struct bpf_func_state *caller, *callee;
  	struct bpf_reg_state *r0;
- 	bool in_callback_fn;
  	u32 i, nregs;
  	int err;
  
  	callee = state->frame[state->curframe];
  	r0 = &callee->regs[BPF_REG_0];
  	nregs = bpf_ret_reg_pair(env, callee->subprogno) ? 2 : 1;
- 	for (i = 0; i < nregs; i++) {
- 		if (callee->regs[ret_regs[i]].type != PTR_TO_STACK)
- 			continue;
- 		/* technically it's ok to return caller's stack pointer
- 		 * (or caller's caller's pointer) back to the caller,
- 		 * since these pointers are valid. Only current stack
- 		 * pointer will be invalid as soon as function exits,
- 		 * but let's be conservative
- 		 */
- 		verbose(env, "cannot return stack pointer to the caller\n");
- 		return -EINVAL;
- 	}
  
  	caller = state->frame[state->curframe - 1];
- 	if (bpf_is_unwind_exit(&env->prog->insnsi[*insn_idx])) {
+ 	if (bpf_is_unwind_exit(&env->prog->insnsi[*insn_idx]) || state->unwound) {
  		/* the helper or the kfunc that called it doesn't expect that */
  		if (callee->in_callback_fn) {
  			verbose(env, "callback cannot unwind\n");
@@@ -12194,15 -12462,23 +12466,23 @@@
  		state->unwound = true;
  	}
  	if (callee->in_callback_fn) {
+ 		/* the helper continues after the barrier of its call */
+ 		if (state->speculative)
+ 			return -EACCES;
  		if (r0->type != SCALAR_VALUE) {
  			verbose(env, "R0 not a scalar value\n");
  			return -EACCES;
  		}
  
- 		/* we are going to rely on register's precise value */
- 		err = mark_chain_precision(env, BPF_REG_0);
- 		if (err)
- 			return err;
+ 		/* It's called any number of times: what it takes it has to release. */
+ 		for (i = callee->entry_refs; i < state->acquired_refs; i++) {
+ 			if (state->refs[i].type != REF_TYPE_PTR)
+ 				continue;
+ 			verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
+ 				state->refs[i].id, state->refs[i].insn_idx);
+ 			bpf_diag_leak(env, &state->refs[i], *insn_idx);
+ 			return -EINVAL;
+ 		}
  
  		/* enforce R0 return value range, and bpf_callback_t returns 64bit */
  		if (!retval_range_within(callee->callback_ret_range, r0)) {
@@@ -12228,6 -12504,7 +12508,7 @@@
  			caller->regs[regno] = callee->regs[regno];
  			bpf_diag_mod_end(env);
  		}
+ 		hide_returned_stack_ptrs(env, callee->subprogno, caller->regs);
  	}
  
  	/* Invalidate callee-local dynptrs and their slices before the frame goes away. */
@@@ -12236,13 -12513,16 +12517,16 @@@
  	if (err)
  		return err;
  	invalidate_stack_slices(env, callee->frameno, INT_MIN, 0);
+ 	if (callee->frame_id) {
+ 		err = invalidate_reference(env, callee->frame_id);
+ 		if (err)
+ 			return err;
+ 	}
  
  	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
- 	 * there function call logic would reschedule callback visit. If iteration
- 	 * converges is_state_visited() would prune that visit eventually.
+ 	 * there function call logic would reschedule callback visit.
  	 */
- 	in_callback_fn = callee->in_callback_fn;
- 	if (in_callback_fn)
+ 	if (callee->in_callback_fn)
  		*insn_idx = callee->callsite;
  	else
  		*insn_idx = callee->callsite + 1;
@@@ -12255,28 -12535,10 +12539,10 @@@
  	}
  	account_processed_insns(env, callee, caller);
  	/* clear everything in the callee. In case of exceptional exits using
- 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
+ 	 * bpf_throw, this will be done by do_check_block() for extra frames. */
  	free_func_state(callee);
  	state->frame[state->curframe--] = NULL;
  	invalidate_outgoing_stack_args(env, caller);
- 
- 	/* for callbacks widen imprecise scalars to make programs like below verify:
- 	 *
- 	 *   struct ctx { int i; }
- 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
- 	 *   ...
- 	 *   struct ctx = { .i = 0; }
- 	 *   bpf_loop(100, cb, &ctx, 0);
- 	 *
- 	 * This is similar to what is done in process_iter_next_call() for open
- 	 * coded iterators.
- 	 */
- 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
- 	if (prev_st) {
- 		err = widen_imprecise_scalars(env, prev_st, state);
- 		if (err)
- 			return err;
- 	}
  	return 0;
  }
  
@@@ -12316,10 -12578,6 +12582,10 @@@ static int do_refine_retval_range(struc
  		    env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT)
  			break;
  
 +		/* It is what the previous struct bpf_tcp_ops returned, any int */
 +		if (prog_type == BPF_PROG_TYPE_STRUCT_OPS)
 +			break;
 +
  		if (prog_type == BPF_PROG_TYPE_LSM &&
  		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
  			if (!env->prog->aux->attach_func_proto->type)
@@@ -12339,12 -12597,43 +12605,43 @@@
  	return reg_bounds_sanity_check(env, ret_reg, "retval");
  }
  
+ /*
+  * The call is rewritten with @num and @meta. One call has one rewrite:
+  *
+  *   if (...) p = type1; else p = type2;
+  *   bpf_obj_drop(p);                      <- the check fails if the special fields differ
+  */
+ static int record_call_fixup(struct bpf_verifier_env *env, u64 num, struct btf_struct_meta *meta)
+ {
+ 	struct bpf_insn_aux_data *aux = cur_aux(env);
+ 	struct btf_struct_meta *first = aux->kptr_struct_meta;
+ 
+ 	if (!aux->call_recorded) {
+ 		aux->call_recorded = true;
+ 		aux->call_num = num;
+ 		aux->kptr_struct_meta = meta;
+ 		return 0;
+ 	}
+ 	if (aux->call_num == num &&
+ 	    btf_record_equal(first ? first->record : NULL, meta ? meta->record : NULL))
+ 		return 0;
+ 	bpf_diag_program_structure(
+ 		env, env->insn_idx, "one call for two types",
+ 		"Use one call for each type. "
+ 		"If the call is in a static function, inline that function. "
+ 		"If a compiler merged two calls, mark the callee with __attribute__((nomerge)).",
+ 		"This call gets objects with different sizes, special fields or offsets, "
+ 		"or two kinds of percpu pointers.");
+ 	return fixups_differ(env, "same call cannot be used with different types");
+ }
+ 
  static int
  record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
  		int func_id, int insn_idx)
  {
  	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
  	struct bpf_map *map = meta->map.ptr;
+ 	bool other;
  
  	if (func_id != BPF_FUNC_tail_call &&
  	    func_id != BPF_FUNC_map_lookup_elem &&
@@@ -12376,12 -12665,13 +12673,13 @@@
  		return -EACCES;
  	}
  
- 	if (!aux->map_ptr_state.map_ptr)
- 		bpf_map_ptr_store(aux, meta->map.ptr,
- 				  !meta->map.ptr->bypass_spec_v1, false);
- 	else if (aux->map_ptr_state.map_ptr != meta->map.ptr)
- 		bpf_map_ptr_store(aux, meta->map.ptr,
- 				  !meta->map.ptr->bypass_spec_v1, true);
+ 	other = aux->map_ptr_state.map_ptr && aux->map_ptr_state.map_ptr != map;
+ 	/* the index is masked for one map */
+ 	if (func_id == BPF_FUNC_tail_call && other &&
+ 	    (bpf_map_ptr_unpriv(aux) || !map->bypass_spec_v1))
+ 		return fixups_differ(env, "tail_call abusing map_ptr");
+ 	if (other || !aux->map_ptr_state.map_ptr)
+ 		bpf_map_ptr_store(aux, map, !map->bypass_spec_v1, other);
  	return 0;
  }
  
@@@ -12393,7 -12683,6 +12691,6 @@@ record_func_key(struct bpf_verifier_en
  	struct bpf_reg_state *reg;
  	struct bpf_map *map = meta->map.ptr;
  	u64 val, max;
- 	int err;
  
  	if (func_id != BPF_FUNC_tail_call)
  		return 0;
@@@ -12411,9 -12700,6 +12708,6 @@@
  		return 0;
  	}
  
- 	err = mark_chain_precision(env, BPF_REG_3);
- 	if (err)
- 		return err;
  	if (bpf_map_key_unseen(aux))
  		bpf_map_key_store(aux, val);
  	else if (!bpf_map_key_poisoned(aux) &&
@@@ -12444,7 -12730,7 +12738,7 @@@ static int check_reference_leak(struct 
  			continue;
  		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
  			state->refs[i].id, state->refs[i].insn_idx);
- 		bpf_diag_leak(env, state->refs[i].id, state->refs[i].insn_idx, env->insn_idx);
+ 		bpf_diag_leak(env, &state->refs[i], env->insn_idx);
  		refs_lingering = true;
  	}
  	return refs_lingering ? -EINVAL : 0;
@@@ -12508,9 -12794,12 +12802,12 @@@ static int check_bpf_snprintf_call(stru
  		return -EINVAL;
  	num_args = data_len_reg->var_off.value / 8;
  
- 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
- 	 * and map_direct_value_addr is set.
- 	 */
+ 	if (!tnum_is_const(fmt_reg->var_off)) {
+ 		verbose(env, "R3 is not a constant address\n");
+ 		return -EACCES;
+ 	}
+ 
+ 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that map_direct_value_addr is set */
  	fmt_map_off = fmt_reg->var_off.value;
  	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
  						  fmt_map_off);
@@@ -12556,50 -12845,40 +12853,40 @@@ static struct bpf_insn_aux_data *cur_au
  	return &env->insn_aux_data[env->insn_idx];
  }
  
- /* Returns 1 if R4 is a known zero, 0 if it is not, a negative errno on error. */
- static int loop_flag_is_zero(struct bpf_verifier_env *env)
+ /* An insn has one fixup for all states. The state that was here first can be wrong too. */
+ static int fixups_differ(struct bpf_verifier_env *env, const char *msg)
  {
- 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_4);
- 	int err;
- 
- 	if (!bpf_register_is_null(reg))
- 		return 0;
- 
- 	err = mark_chain_precision(env, BPF_REG_4);
- 	if (err)
- 		return err;
- 	return 1;
+ 	verbose(env, "%s\n", msg);
+ 	bpf_note_fixups_differ(env);
+ 	return -EINVAL;
  }
  
- static int update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
+ static bool loop_flag_is_zero(struct bpf_verifier_env *env)
+ {
+ 	return bpf_register_is_null(reg_state(env, BPF_REG_4));
+ }
+ 
+ static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
  {
  	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
- 	int flag_is_zero;
  
  	if (!state->initialized) {
- 		flag_is_zero = loop_flag_is_zero(env);
- 		if (flag_is_zero < 0)
- 			return flag_is_zero;
  		state->initialized = 1;
- 		state->fit_for_inline = flag_is_zero;
+ 		state->fit_for_inline = loop_flag_is_zero(env);
  		state->callback_subprogno = subprogno;
- 		return 0;
+ 		return;
  	}
  
  	if (!state->fit_for_inline)
- 		return 0;
+ 		return;
  
- 	flag_is_zero = loop_flag_is_zero(env);
- 	if (flag_is_zero < 0)
- 		return flag_is_zero;
- 	state->fit_for_inline = (flag_is_zero &&
+ 	state->fit_for_inline = (loop_flag_is_zero(env) &&
  				 state->callback_subprogno == subprogno);
- 	return 0;
  }
  
  /* Returns whether or not the given map can potentially elide
-  * lookup return value nullness check. This is possible if the key
-  * is statically known.
+  * lookup return value nullness check. This is possible if the largest
+  * value of the key is statically known.
   */
  static bool can_elide_value_nullness(const struct bpf_map *map)
  {
@@@ -12813,9 -13092,6 +13100,6 @@@ static int check_helper_call(struct bpf
  			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
  			return -EINVAL;
  		}
- 		err = mark_chain_precision(env, BPF_REG_2);
- 		if (err)
- 			return err;
  		break;
  	case BPF_FUNC_for_each_map_elem:
  		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
@@@ -12833,20 -13109,12 +13117,12 @@@
  		err = check_bpf_snprintf_call(env, regs);
  		break;
  	case BPF_FUNC_loop:
- 		err = update_loop_inline_state(env, meta.subprogno);
- 		if (err)
- 			return err;
- 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
- 		 * is finished, thus mark it precise.
- 		 */
- 		err = mark_chain_precision(env, BPF_REG_1);
- 		if (err)
- 			return err;
+ 		update_loop_inline_state(env, meta.subprogno);
  		if (cur_func(env)->callback_depth < reg_umax(&regs[BPF_REG_1])) {
  			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
  						 set_loop_callback_state);
  		} else {
- 			cur_func(env)->callback_depth = 0;
+ 			leave_callback(cur_func(env));
  			if (env->log.level & BPF_LOG_LEVEL2)
  				verbose(env, "frame%d bpf_loop iteration limit reached\n",
  					env->cur_state->curframe);
@@@ -12890,10 -13158,6 +13166,6 @@@
  			bpf_lsm_get_retval_range(env->prog, &range);
  		}
  
- 		err = mark_chain_precision(env, BPF_REG_1);
- 		if (err)
- 			return err;
- 
  		if (!retval_range_within(range, r1)) {
  			verbose_invalid_scalar(env, r1, range, "At bpf_set_retval", "R1");
  			return -EINVAL;
@@@ -12916,6 -13180,15 +13188,15 @@@
  
  		break;
  	}
+ 	case BPF_FUNC_override_return:
+ 		/* see bpf_check_tail_call() */
+ 		for (i = 0; i < env->used_map_cnt; i++) {
+ 			if (!map_type_contains_progs(env->used_maps[i]))
+ 				continue;
+ 			verbose(env, "bpf_override_return() and a map of programs are used\n");
+ 			return -EINVAL;
+ 		}
+ 		break;
  	case BPF_FUNC_per_cpu_ptr:
  	case BPF_FUNC_this_cpu_ptr:
  	{
@@@ -12929,8 -13202,8 +13210,8 @@@
  				return -EFAULT;
  			}
  			returns_cpu_specific_alloc_ptr = true;
- 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
  		}
+ 		err = record_call_fixup(env, returns_cpu_specific_alloc_ptr, NULL);
  		break;
  	}
  	case BPF_FUNC_user_ringbuf_drain:
@@@ -12977,8 -13250,7 +13258,7 @@@
  
  		if (func_id == BPF_FUNC_map_lookup_elem &&
  		    can_elide_value_nullness(meta.map.ptr) &&
- 		    meta.const_map_key >= 0 &&
- 		    meta.const_map_key < meta.map.ptr->max_entries)
+ 		    meta.max_map_key < meta.map.ptr->max_entries)
  			ret_flag &= ~PTR_MAYBE_NULL;
  
  		regs[BPF_REG_0].map_ptr = meta.map.ptr;
@@@ -12986,7 -13258,7 +13266,7 @@@
  		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
  		if (type_may_be_null(ret_flag) ||
  		    btf_record_has_field(meta.map.ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
- 			regs[BPF_REG_0].id = ++env->id_gen;
+ 			regs[BPF_REG_0].id = bpf_new_id(env);
  		}
  		/* requires regs[BPF_REG_0].id to be set because of the map-in-map case */
  		refine_map_lookup_value(&regs[BPF_REG_0]);
@@@ -13088,7 -13360,7 +13368,7 @@@
  	}
  
  	if (type_may_be_null(regs[BPF_REG_0].type) && !regs[BPF_REG_0].id)
- 		regs[BPF_REG_0].id = ++env->id_gen;
+ 		regs[BPF_REG_0].id = bpf_new_id(env);
  
  	if (is_ptr_cast_function(func_id) &&
  	    find_reference_state(env->cur_state, meta.ref_obj.id)) {
@@@ -13171,7 -13443,28 +13451,28 @@@
  		env->prog->call_get_func_ip = true;
  	}
  
+ 	/* a call that only a speculative state reaches is dead code */
+ 	if (func_id == BPF_FUNC_override_return && !env->cur_state->speculative)
+ 		env->prog->kprobe_override = 1;
+ 
+ 	if (func_id == BPF_FUNC_tail_call && !env->cur_state->speculative) {
+ 		/* the other program can access all of it */
+ 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
+ 			env->prog->aux->max_rdonly_access =
+ 				env->prog->aux->max_rdwr_access = U32_MAX;
+ 		if (env->prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE)
+ 			env->prog->aux->max_tp_access = U32_MAX;
+ 	}
+ 
  	if (func_id == BPF_FUNC_tail_call) {
+ 		/*
+ 		 * The program which a tail call jumps to returns for this one,
+ 		 * and a program array does not check the values it may return.
+ 		 */
+ 		if (env->fmodret_retvals) {
+ 			verbose(env, "tail calls are not allowed in fmod_ret programs with restricted return values\n");
+ 			return -EINVAL;
+ 		}
  		if (env->cur_state->curframe) {
  			struct bpf_verifier_state *branch;
  
@@@ -13291,6 -13584,22 +13592,22 @@@ static bool is_kfunc_arg_const_mem_size
  	return btf_param_match_suffix(btf, arg, "__szk");
  }
  
+ /* A kfunc only reads through 'const T *arg'. The compiler enforces it. */
+ static enum bpf_type_flag kfunc_arg_mem_flag(const struct btf *btf,
+ 					     const struct btf_param *arg)
+ {
+ 	const struct btf_type *t = btf_type_skip_modifiers(btf, arg->type, NULL);
+ 	u32 id, ref_id;
+ 
+ 	btf_type_skip_modifiers(btf, t->type, &ref_id);
+ 	for (id = t->type; id != ref_id; id = t->type) {
+ 		t = btf_type_by_id(btf, id);
+ 		if (btf_kind(t) == BTF_KIND_CONST)
+ 			return MEM_RDONLY;
+ 	}
+ 	return MEM_WRITE;
+ }
+ 
  static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
  {
  	return btf_param_match_suffix(btf, arg, "__k");
@@@ -13672,7 -13981,8 +13989,8 @@@ static int resolve_func_arg_type(struc
  			PTR_ERR(resolve_ret));
  		return -EINVAL;
  	}
- 	*arg_type = ARG_PTR_TO_MEM | MEM_FIXED_SIZE | MEM_WRITE |
+ 	*arg_type = ARG_PTR_TO_MEM | MEM_FIXED_SIZE |
+ 		    kfunc_arg_mem_flag(meta->btf, &args[arg]) |
  		    (*arg_type & (PTR_MAYBE_NULL | MEM_UNINIT));
  
  	return 0;
@@@ -14224,7 -14534,7 +14542,7 @@@ get_kfunc_arg_type(struct bpf_verifier_
  				reg_arg_name(env, argno), btf_type_str(ref_t), ref_tname);
  			return -EINVAL;
  		}
- 		arg_type = ARG_PTR_TO_MEM | MEM_WRITE;
+ 		arg_type = ARG_PTR_TO_MEM | kfunc_arg_mem_flag(meta->btf, &args[arg]);
  	} else if (btf_type_is_struct(ref_t))
  		/* A pointer to a struct without a size argument is classified as ARG_PTR_TO_BTF_ID */
  		arg_type = ARG_PTR_TO_BTF_ID;
@@@ -14249,7 -14559,8 +14567,8 @@@
  			return -EINVAL;
  		}
  		proto->arg_size[arg] = type_size;
- 		arg_type = ARG_PTR_TO_MEM | MEM_FIXED_SIZE | MEM_WRITE;
+ 		arg_type = ARG_PTR_TO_MEM | MEM_FIXED_SIZE |
+ 			   kfunc_arg_mem_flag(meta->btf, &args[arg]);
  	}
  
  	if (is_kfunc_arg_uninit(meta->btf, &args[arg]))
@@@ -14532,7 -14843,7 +14851,7 @@@ static void ref_convert_owning_non_owni
  	struct bpf_reg_state *reg;
  	int err;
  
- 	err = release_reference_nomark(env, id);
+ 	err = release_reference_nomark(env->cur_state, id);
  	WARN_ON_ONCE(err);
  
  	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
@@@ -14669,55 -14980,6 +14988,6 @@@ static bool kfunc_spin_allowed(struct b
  	return *kfunc.flags & KF_SPINLOCK_SAFE;
  }
  
- /*
-  * True if insn calls a helper/kfunc that requires one of its arguments to
-  * be a stack pointer with a constant offset.
-  */
- bool bpf_needs_fixed_stack_off(struct bpf_verifier_env *env, int insn_idx)
- {
- 	const struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
- 	const struct bpf_func_proto *fn;
- 	struct bpf_kfunc_desc *desc;
- 	u32 *flags, btf_id;
- 	int i;
- 
- 	if (bpf_helper_call(insn)) {
- 		if (bpf_get_helper_proto(env, insn->imm, &fn) < 0)
- 			return false;
- 	} else if (bpf_pseudo_kfunc_call(insn)) {
- 		desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
- 		if (!desc)
- 			return false;
- 		fn = &desc->proto;
- 	} else {
- 		return false;
- 	}
- 
- 	/* Both initialized and uninitialized stack dynptrs need a fixed offset. */
- 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++)
- 		if (arg_type_is_dynptr(fn->arg_type[i]))
- 			return true;
- 
- 	/* vmlinux kfuncs only */
- 	if (!bpf_pseudo_kfunc_call(insn) || insn->off != 0)
- 		return false;
- 	btf_id = insn->imm;
- 
- 	flags = btf_kfunc_flags(btf_vmlinux, btf_id, env->prog);
- 	if (flags && (*flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY)))
- 		return true;
- 
- 	if (btf_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
- 	    btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] ||
- 	    btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
- 	    btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore] ||
- 	    btf_id == special_kfunc_list[KF_bpf_local_irq_save] ||
- 	    btf_id == special_kfunc_list[KF_bpf_local_irq_restore])
- 		return true;
- 
- 	return false;
- }
- 
  static bool is_sync_callback_calling_kfunc(u32 btf_id)
  {
  	return is_bpf_rbtree_add_kfunc(btf_id);
@@@ -15016,7 -15278,7 +15286,7 @@@ int bpf_fetch_kfunc_arg_meta(struct bpf
   * Describe a helper's stack access through argument @arg (0-based, R1-R5).
   * must_write means the verifier destroys prior state throughout size bytes.
   * In other words, must_write follows the verifier's model of the
-  * function's behaviour, which is safe to use for is_state_visited() pruning.
+  * function's behaviour, which is safe to use when states are cleaned and compared.
   */
  struct arg_access_info
  bpf_helper_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn,
@@@ -15044,7 -15306,6 +15314,6 @@@
  	case ARG_PTR_TO_MAP_KEY:
  	case ARG_PTR_TO_MAP_VALUE: {
  		bool is_key = base_type(at) == ARG_PTR_TO_MAP_KEY;
- 		u64 val;
  		int i, map_reg;
  
  		for (i = 0; i < arg; i++) {
@@@ -15080,23 -15341,9 +15349,9 @@@ scan_all_maps
  		 */
  		exact_size = false;
  		access_type |= BPF_READ;
- 		val = 0;
- 		for (i = 0; i < env->used_map_cnt; i++) {
- 			struct bpf_map *map = env->used_maps[i];
- 			u32 sz = is_key ? map->key_size : map->value_size;
- 
- 			if (sz > val)
- 				val = sz;
- 			if (map->inner_map_meta) {
- 				sz = is_key ? map->inner_map_meta->key_size
- 					    : map->inner_map_meta->value_size;
- 				if (sz > val)
- 					val = sz;
- 			}
- 		}
- 		if (!val)
+ 		size = is_key ? env->max_key_size : env->max_value_size;
+ 		if (!size)
  			return info;
- 		size = val;
  		goto out;
  	}
  	case ARG_PTR_TO_MEM:
@@@ -15125,6 -15372,14 +15380,14 @@@
  		 * analyzed separately.
  		 */
  		return (struct arg_access_info) {};
+ 	case ARG_ANYTHING:
+ 		/*
+ 		 * A number that the program is free to choose. bpf_probe_read_kernel() and
+ 		 * the like may read what it points to. check_func_arg() does not look at
+ 		 * the number: do_check() keeps what it knows about the stack over the call.
+ 		 */
+ 		info.may_write = false;
+ 		return info;
  	default:
  		return info;
  	}
@@@ -15141,6 -15396,15 +15404,15 @@@ out
  	return info;
  }
  
+ bool bpf_insn_is_iter_next(struct bpf_verifier_env *env, struct bpf_insn *insn)
+ {
+ 	struct bpf_call_arg_meta meta;
+ 
+ 	return bpf_pseudo_kfunc_call(insn) &&
+ 	       !bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta) &&
+ 	       bpf_is_iter_next_kfunc(&meta);
+ }
+ 
  /*
   * Describe a kfunc's stack access through argument slot @arg (0-based).
   * As for helpers, must_write describes destruction of prior verifier state,
@@@ -15249,12 -15513,29 +15521,29 @@@ static bool try_btf_prepare_func_args(s
  /* Prepare argument metadata for liveness; the main program is handled separately. */
  static void prepare_subprog_args(struct bpf_verifier_env *env)
  {
- 	int i;
+ 	struct bpf_subprog_info *sub;
+ 	struct bpf_insn *insn;
+ 	int i, j, cnt;
  
  	for (i = 1; i < env->subprog_cnt; i++) {
+ 		sub = &env->subprog_info[i];
  		if (!try_btf_prepare_func_args(env, i) && bpf_subprog_is_global(env, i))
  			/* Keep all argument registers live if the prototype is unavailable. */
- 			env->subprog_info[i].arg_slot_cnt = MAX_BPF_FUNC_REG_ARGS;
+ 			sub->arg_slot_cnt = MAX_BPF_FUNC_REG_ARGS;
+ 		if (bpf_subprog_is_global(env, i))
+ 			continue;
+ 		cnt = 0;
+ 		for (j = sub->start; j < (sub + 1)->start; j++) {
+ 			insn = &env->prog->insnsi[j];
+ 			if (is_stack_arg_ldx(insn))
+ 				cnt = max(cnt, insn->off / BPF_REG_SIZE);
+ 		}
+ 		sub->stack_args_from_code = true;
+ 		sub->code_stack_args = min(cnt, MAX_STACK_ARG_SLOTS);
+ 		/* incoming + max outgoing. Calls add the latter. */
+ 		sub->stack_arg_cnt = sub->code_stack_args;
+ 		if (env->prog->aux->func_info_aux)
+ 			env->prog->aux->func_info_aux[i].stack_args = sub->code_stack_args;
  	}
  }
  
@@@ -15314,9 -15595,10 +15603,10 @@@ bpf_global_subprog_stack_access_bytes(s
   * < 0 - not fall-through to 'else' branch, return error
   */
  static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
- 			       struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux,
- 			       const struct btf_type *ptr_type, struct btf *desc_btf)
+ 			       struct bpf_reg_state *regs, const struct btf_type *ptr_type,
+ 			       struct btf *desc_btf)
  {
+ 	struct btf_struct_meta *struct_meta;
  	const struct btf_type *ret_t;
  	int err = 0;
  
@@@ -15324,7 -15606,6 +15614,6 @@@
  		return 0;
  
  	if (is_bpf_obj_new_kfunc(meta->func_id) || is_bpf_percpu_obj_new_kfunc(meta->func_id)) {
- 		struct btf_struct_meta *struct_meta;
  		struct btf *ret_btf;
  		u32 ret_btf_id;
  
@@@ -15400,17 -15681,21 +15689,21 @@@
  		if (is_bpf_percpu_obj_new_kfunc(meta->func_id))
  			regs[BPF_REG_0].type |= MEM_PERCPU;
  
- 		insn_aux->obj_new_size = ret_t->size;
- 		insn_aux->kptr_struct_meta = struct_meta;
+ 		err = record_call_fixup(env, ret_t->size, struct_meta);
+ 		if (err)
+ 			return err;
  	} else if (is_bpf_refcount_acquire_kfunc(meta->func_id)) {
  		mark_reg_known_zero(env, regs, BPF_REG_0);
  		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
  		regs[BPF_REG_0].btf = meta->arg_btf;
  		regs[BPF_REG_0].btf_id = meta->arg_btf_id;
  
- 		insn_aux->kptr_struct_meta =
- 			btf_find_struct_meta(meta->arg_btf,
- 					     meta->arg_btf_id);
+ 		/* The call reads only the offset of the refcount. The other fields can differ. */
+ 		struct_meta = btf_find_struct_meta(meta->arg_btf, meta->arg_btf_id);
+ 		err = record_call_fixup(env, struct_meta->record->refcount_off,
+ 					cur_aux(env)->kptr_struct_meta ?: struct_meta);
+ 		if (err)
+ 			return err;
  	} else if (is_list_node_type(ptr_type)) {
  		struct btf_field *field = meta->arg_list_head.field;
  
@@@ -15497,6 -15782,7 +15790,7 @@@ static int check_kfunc_call(struct bpf_
  	const struct btf_type *t, *ptr_type;
  	struct bpf_call_arg_meta meta;
  	struct bpf_insn_aux_data *insn_aux;
+ 	struct btf_struct_meta *struct_meta;
  	const char *operation;
  	int err, insn_idx = *insn_idx_p;
  	u32 i, proto_slots, ptr_type_id, ret_nregs = 1;
@@@ -15504,9 -15790,10 +15798,10 @@@
  	struct btf *desc_btf;
  	int id;
  
- 	/* skip for now, but return error when we find this in fixup_kfunc_call */
- 	if (!insn->imm)
- 		return 0;
+ 	if (!insn->imm) {
+ 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
+ 		return -EINVAL;
+ 	}
  
  	err = bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta);
  	if (err == -EACCES && meta.func_name) {
@@@ -15522,14 -15809,13 +15817,13 @@@
  	func_name = meta.func_name;
  	insn_aux = &env->insn_aux_data[insn_idx];
  
- 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
+ 	desc = find_kfunc_desc(env, insn->imm, insn->off);
  	if (!desc) {
  		verifier_bug(env, "kfunc descriptor not found for func_id %u", insn->imm);
  		return -EFAULT;
  	}
  	meta.fn = &desc->proto;
  
- 	insn_aux->is_iter_next = bpf_is_iter_next_kfunc(&meta);
  
  	if (!insn->off &&
  	    (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] ||
@@@ -15549,10 -15835,12 +15843,10 @@@
  		for (i = 0; i < CALLER_SAVED_REGS; i++)
  			bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
  
 +		/* The kfunc returns int, the upper half of r0 is not known */
  		mark_reg_unknown(env, regs, BPF_REG_0);
 -		err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1);
 -		if (err) {
 -			verbose(env, "failed to mark s32 range for retval in forked state for lock\n");
 -			return err;
 -		}
 +		reg_set_srange32(&regs[BPF_REG_0], -MAX_ERRNO, -1);
 +		reg_bounds_sync(&regs[BPF_REG_0]);
  	} else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) {
  		verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n");
  		return -EFAULT;
@@@ -15612,8 -15900,6 +15906,6 @@@
  	     /* is_tracing_prog_type() for now doesn't cover non-iterator tracing progs. */
  	     (prog_type == BPF_PROG_TYPE_TRACING && env->prog->expected_attach_type != BPF_TRACE_ITER
  	      && !env->prog->sleepable))) {
- 		struct btf_struct_meta *struct_meta;
- 
  		struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
  		if (struct_meta && btf_record_has_nmi_unsafe_fields(struct_meta->record)) {
  			verbose(env, "%s cannot be used in tracing programs on types with NMI unsafe fields\n",
@@@ -15681,6 -15967,7 +15973,7 @@@
  			return -EINVAL;
  		}
  		env->cur_state->active_rcu_locks--;
+ 		release_context_state(env->cur_state);
  		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_RCU, false,
  					env->cur_state->active_rcu_locks);
  		if (!in_rcu_cs(env))
@@@ -15698,6 -15985,7 +15991,7 @@@
  			return -EINVAL;
  		}
  		env->cur_state->active_preempt_locks--;
+ 		release_context_state(env->cur_state);
  		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_PREEMPT, false,
  					env->cur_state->active_preempt_locks);
  		if (!in_rcu_cs(env))
@@@ -15727,10 -16015,11 +16021,11 @@@
  	}
  
  	if (is_bpf_list_push_kfunc(meta.func_id) || is_bpf_rbtree_add_kfunc(meta.func_id)) {
- 		id = regs[BPF_REG_2].id;
- 		insn_aux->insert_off = regs[BPF_REG_2].var_off.value;
- 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
- 		ref_convert_owning_non_owning(env, id);
+ 		ref_convert_owning_non_owning(env, regs[BPF_REG_2].id);
+ 		struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
+ 		err = record_call_fixup(env, regs[BPF_REG_2].var_off.value, struct_meta);
+ 		if (err)
+ 			return err;
  	}
  
  	if ((is_kfunc_call(&meta, special_kfunc_list[KF_bpf_dynptr_slice]) ||
@@@ -15793,7 -16082,7 +16088,7 @@@
  		ret_nregs = mark_kfunc_ret_regs(env, regs, t->size);
  		if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
  		    meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]))
- 			__mark_reg_const_zero(env, &regs[BPF_REG_0]);
+ 			__mark_reg_const_zero(&regs[BPF_REG_0]);
  	} else if (btf_type_is_struct(t)) {
  		struct btf_member_path path = {};
  		const char *member_note = "";
@@@ -15849,18 -16138,12 +16144,18 @@@
  		ret_nregs = mark_kfunc_ret_regs(env, regs, t->size);
  	} else if (btf_type_is_ptr(t)) {
  		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
- 		err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf);
+ 		err = check_special_kfunc(env, &meta, regs, ptr_type, desc_btf);
  		if (err) {
  			if (err < 0)
  				return err;
  		} else if (btf_type_is_void(ptr_type)) {
  			/* kfunc returning 'void *' is equivalent to returning scalar */
 +			if (!env->allow_ptr_leaks) {
 +				verbose(env,
 +					"%s is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
 +					func_name);
 +				return -EPERM;
 +			}
  			mark_reg_unknown(env, regs, BPF_REG_0);
  		} else if (!__btf_type_is_struct(ptr_type)) {
  			if (!meta.ret_mem.found) {
@@@ -15943,7 -16226,7 +16238,7 @@@
  		if (is_kfunc_ret_null(&meta)) {
  			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
  			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
- 			regs[BPF_REG_0].id = ++env->id_gen;
+ 			regs[BPF_REG_0].id = bpf_new_id(env);
  		}
  		if (is_kfunc_acquire(&meta)) {
  			id = acquire_reference(env, insn_idx, 0);
@@@ -15955,14 -16238,15 +16250,15 @@@
  		}
  
  		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
- 			regs[BPF_REG_0].id = ++env->id_gen;
+ 			regs[BPF_REG_0].id = bpf_new_id(env);
  	} else if (btf_type_is_void(t)) {
  		if (meta.btf == btf_vmlinux) {
  			if (is_bpf_obj_drop_kfunc(meta.func_id) ||
  			    is_bpf_percpu_obj_drop_kfunc(meta.func_id)) {
- 				insn_aux->kptr_struct_meta =
- 					btf_find_struct_meta(meta.arg_btf,
- 							     meta.arg_btf_id);
+ 				struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
+ 				err = record_call_fixup(env, 0, struct_meta);
+ 				if (err)
+ 					return err;
  			}
  		}
  	}
@@@ -16021,7 -16305,7 +16317,7 @@@ static bool check_reg_sane_offset_scala
  	s64 val = reg->var_off.value;
  	s64 smin = reg_smin(reg);
  
- 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
+ 	if (known && val <= -BPF_MAX_VAR_OFF) {
  		verbose(env, "math between %s pointer and %lld is not allowed\n",
  			reg_type_str(env, type), val);
  		return false;
@@@ -16033,7 -16317,7 +16329,7 @@@
  		return false;
  	}
  
- 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
+ 	if (smin <= -BPF_MAX_VAR_OFF) {
  		verbose(env, "value %lld makes %s pointer be out of bounds\n",
  			smin, reg_type_str(env, type));
  		return false;
@@@ -16042,36 -16326,29 +16338,29 @@@
  	return true;
  }
  
- static bool check_reg_sane_offset_ptr(struct bpf_verifier_env *env,
- 				      const struct bpf_reg_state *reg,
- 				      enum bpf_reg_type type)
+ /*
+  * A far pointer is no error: a state with near offsets gets here, so this one does too.
+  * An access through it is unproven or gets a fault handler, see check_load_mem().
+  * But a constant offset has to fit in an int.
+  */
+ void bpf_blur_far_offset(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
  {
- 	bool known = tnum_is_const(reg->var_off);
- 	s64 val = reg->var_off.value;
- 	s64 smin = reg_smin(reg);
+ 	s64 smin = reg_smin(reg), smax = reg_smax(reg);
  
- 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
- 		verbose(env, "%s pointer offset %lld is not allowed\n",
- 			reg_type_str(env, type), val);
- 		return false;
+ 	/* an id and a range need an offset that does not wrap around */
+ 	if (reg_is_pkt_pointer(reg) && offset_is_far(reg)) {
+ 		reg->id = bpf_new_id(env);
+ 		reg->range = 0;
  	}
- 
- 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
- 		verbose(env, "%s pointer offset %lld is not allowed\n",
- 			reg_type_str(env, type), smin);
- 		return false;
- 	}
- 
- 	return true;
+ 	if (reg->type == SCALAR_VALUE || (smin < BPF_MAX_VAR_OFF && smax > -BPF_MAX_VAR_OFF))
+ 		return;
+ 	scalar_set_unknown(scalar_of(reg));
+ 	reg->r64 = cnum64_from_srange(min(smin, BPF_MAX_VAR_OFF - 1),
+ 				      max(smax, 1 - BPF_MAX_VAR_OFF));
+ 	reg_bounds_sync(reg);
  }
  
- enum {
- 	REASON_BOUNDS	= -1,
- 	REASON_TYPE	= -2,
- 	REASON_PATHS	= -3,
- 	REASON_LIMIT	= -4,
- 	REASON_STACK	= -5,
- };
+ #define NO_MASK_FITS	1
  
  static int retrieve_ptr_limit(const struct bpf_verifier_env *env,
  			      const struct bpf_reg_state *ptr_reg,
@@@ -16094,11 -16371,11 +16383,11 @@@
  		ptr_limit = mask_to_left ? reg_smin(ptr_reg) : reg_umax(ptr_reg);
  		break;
  	default:
- 		return REASON_TYPE;
+ 		return NO_MASK_FITS;
  	}
  
  	if (ptr_limit >= max)
- 		return REASON_LIMIT;
+ 		return NO_MASK_FITS;
  	*alu_limit = ptr_limit;
  	return 0;
  }
@@@ -16106,7 -16383,7 +16395,7 @@@
  static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
  				    const struct bpf_insn *insn)
  {
- 	return env->bypass_spec_v1 ||
+ 	return env->bypass_spec_v1 || env->path_sensitive ||
  		BPF_SRC(insn->code) == BPF_K ||
  		cur_aux(env)->nospec;
  }
@@@ -16120,7 -16397,7 +16409,7 @@@ static int update_alu_sanitation_state(
  	if (aux->alu_state &&
  	    (aux->alu_state != alu_state ||
  	     aux->alu_limit != alu_limit))
- 		return REASON_PATHS;
+ 		return NO_MASK_FITS;
  
  	/* Corresponding fixup done in do_misc_fixups(). */
  	aux->alu_state = alu_state;
@@@ -16147,6 -16424,7 +16436,7 @@@ static bool sanitize_needed(u8 opcode
  struct bpf_sanitize_info {
  	struct bpf_insn_aux_data aux;
  	bool mask_to_left;
+ 	u64 max_off;
  };
  
  static int sanitize_speculative_path(struct bpf_verifier_env *env,
@@@ -16178,8 -16456,7 +16468,7 @@@ static int sanitize_ptr_alu(struct bpf_
  			    const bool commit_window)
  {
  	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
- 	struct bpf_verifier_state *vstate = env->cur_state;
- 	bool off_is_imm = tnum_is_const(off_reg->var_off);
+ 	bool off_is_imm = cnum64_is_const(off_reg->r64);
  	bool off_is_neg = reg_smin(off_reg) < 0;
  	bool ptr_is_dst_reg = ptr_reg == dst_reg;
  	u8 opcode = BPF_OP(insn->code);
@@@ -16190,24 -16467,18 +16479,18 @@@
  	if (can_skip_alu_sanitation(env, insn))
  		return 0;
  
- 	/* We already marked aux for masking from non-speculative
- 	 * paths, thus we got here in the first place. We only care
- 	 * to explore bad access from here.
- 	 */
- 	if (vstate->speculative)
- 		goto do_sim;
- 
  	if (!commit_window) {
- 		if (!tnum_is_const(off_reg->var_off) &&
+ 		if (!off_is_imm &&
  		    (reg_smin(off_reg) < 0) != (reg_smax(off_reg) < 0))
- 			return REASON_BOUNDS;
+ 			return NO_MASK_FITS;
  
+ 		info->max_off = off_is_neg ? -(u64)reg_smin(off_reg) : reg_umax(off_reg);
  		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
  				     (opcode == BPF_SUB && !off_is_neg);
  	}
  
  	err = retrieve_ptr_limit(env, ptr_reg, &alu_limit, info->mask_to_left);
- 	if (err < 0)
+ 	if (err)
  		return err;
  
  	if (commit_window) {
@@@ -16216,23 -16487,24 +16499,24 @@@
  		 */
  		alu_state = info->aux.alu_state;
  		alu_limit = abs(info->aux.alu_limit - alu_limit);
+ 		/*
+ 		 * The mask passes what was checked: it cuts no real offset and adds no other one.
+ 		 * It passes all smaller offsets too. The slots of the stack are not alike.
+ 		 * A stack pointer plus a range gets here if the step makes the sum a constant.
+ 		 */
+ 		if (alu_limit != info->max_off ||
+ 		    (ptr_reg->type == PTR_TO_STACK && !(alu_state & BPF_ALU_IMMEDIATE)))
+ 			return NO_MASK_FITS;
  	} else {
  		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
  		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
  		alu_state |= ptr_is_dst_reg ?
  			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
- 
- 		/* Limit pruning on unknown scalars to enable deep search for
- 		 * potential masking differences from other program paths.
- 		 */
- 		if (!off_is_imm)
- 			env->explore_alu_limits = true;
  	}
  
  	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
- 	if (err < 0)
+ 	if (err)
  		return err;
- do_sim:
  	/* If we're in commit phase, we're done here given we already
  	 * pushed the truncated dst_reg into the speculative verification
  	 * stack.
@@@ -16259,7 -16531,7 +16543,7 @@@
  	}
  	err = sanitize_speculative_path(env, NULL, env->insn_idx + 1, env->insn_idx);
  	if (err < 0)
- 		return REASON_STACK;
+ 		return err;
  	if (!ptr_is_dst_reg)
  		*dst_reg = tmp;
  	return 0;
@@@ -16275,43 -16547,41 +16559,41 @@@ static void sanitize_mark_insn_seen(str
  	 * rewrite/sanitize them.
  	 */
  	if (!vstate->speculative)
- 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
+ 		env->insn_aux_data[env->insn_idx].seen = env->check_cnt;
  }
  
- static int sanitize_err(struct bpf_verifier_env *env, const struct bpf_insn *insn, int reason)
+ /*
+  * The insn at @idx gets a barrier, and no mask. A fall-through, a jump, a call or a return to
+  * @idx runs the barrier first. So it ends a speculative state that comes that way. The other
+  * edges have their own barrier, and a speculative state does not take them:
+  *
+  *	exit of a callback --> call of the helper	barrier at the exit
+  *	may_goto --> r0 = 0; exit			see emit_unwind_exit()
+  *	return --> dead code				see bpf_opt_hard_wire_dead_code_branches()
+  */
+ static void need_nospec(struct bpf_verifier_env *env, u32 idx)
  {
- 	static const char *err = "pointer arithmetic with it prohibited for !root";
- 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
- 	u32 dst = insn->dst_reg, src = insn->src_reg;
- 	struct bpf_reg_state *regs = cur_regs(env);
+ 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[idx];
+ 	struct bpf_insn *insn = &env->prog->insnsi[idx];
  
- 	switch (reason) {
- 	case REASON_BOUNDS:
- 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
- 			regs[src].type == SCALAR_VALUE ? src : dst, err);
- 		break;
- 	case REASON_TYPE:
- 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
- 			regs[src].type == SCALAR_VALUE ? dst : src, err);
- 		break;
- 	case REASON_PATHS:
- 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
- 			dst, op, err);
- 		break;
- 	case REASON_LIMIT:
- 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
- 			dst, op, err);
- 		break;
- 	case REASON_STACK:
- 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
- 			dst, err);
- 		return -ENOMEM;
- 	default:
- 		verifier_bug(env, "unknown reason (%d)", reason);
- 		break;
+ 	/* nothing fits between it and the call */
+ 	if (bpf_is_unwind_goto(insn)) {
+ 		need_nospec(env, idx + 1);
+ 		return need_nospec(env, idx + insn->off + 1);
  	}
+ 	note_pessimized_insn(env, idx);
+ 	aux->nospec = true;
+ 	aux->alu_state = 0;
+ }
  
- 	return -EACCES;
+ static int sanitize_err(struct bpf_verifier_env *env, int err)
+ {
+ 	if (err != NO_MASK_FITS)
+ 		return err;
+ 	if (env->cur_state->speculative)
+ 		return -EACCES;
+ 	need_nospec(env, env->insn_idx);
+ 	return 0;
  }
  
  /* check that stack access falls within stack limits and that 'reg' doesn't
@@@ -16377,22 -16647,22 +16659,22 @@@ static int sanitize_check_bounds(struc
  	return 0;
  }
  
- static void scalar_step_mul(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg)
+ static void scalar_step_mul(struct scalar *dst, const struct scalar *src)
  {
- 	if (tnum_is_const(src_reg->var_off))
- 		scalar_step_scale(dst_reg, src_reg->var_off.value);
+ 	if (tnum_is_const(src->var_off))
+ 		scalar_step_scale(dst, src->var_off.value);
  	else
- 		reg_step_reset(dst_reg);
+ 		scalar_step_reset(dst);
  }
  
- static void scalar_step_lsh(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg)
+ static void scalar_step_lsh(struct scalar *dst, const struct scalar *src)
  {
- 	u64 amount = src_reg->var_off.value;
+ 	u64 amount = src->var_off.value;
  
- 	if (tnum_is_const(src_reg->var_off) && amount < 64)
- 		scalar_step_scale(dst_reg, 1ULL << amount);
+ 	if (tnum_is_const(src->var_off) && amount < 64)
+ 		scalar_step_scale(dst, 1ULL << amount);
  	else
- 		reg_step_reset(dst_reg);
+ 		scalar_step_reset(dst);
  }
  
  /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
@@@ -16414,12 -16684,13 +16696,13 @@@ static int adjust_ptr_min_max_vals(stru
  	u8 opcode = BPF_OP(insn->code);
  	u32 dst = insn->dst_reg;
  	const char *reason;
- 	int ret, bounds_ret;
+ 	int ret, bounds_ret, min_len;
  	bool to_scalar;
+ 	s64 smax;
  
  	dst_reg = &regs[dst];
  	/*
- 	 * Only += and -= keep a pointer. Any other op makes a number of it,
+ 	 * Only 64-bit += and -= keep a pointer. Any other op makes a number of it,
  	 * which is fine when the program may see values of pointers anyway.
  	 */
  	to_scalar = opcode != BPF_ADD && opcode != BPF_SUB && env->allow_ptr_leaks;
@@@ -16429,14 -16700,14 +16712,14 @@@
  		/* Taint dst register if offset had invalid bounds derived from
  		 * e.g. dead branches.
  		 */
- 		__mark_reg_unknown(env, dst_reg);
+ 		bpf_mark_reg_unknown(dst_reg);
  		return 0;
  	}
  
  	if (BPF_CLASS(insn->code) != BPF_ALU64 && !to_scalar) {
  		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
- 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
- 			__mark_reg_unknown(env, dst_reg);
+ 		if (env->allow_ptr_leaks) {
+ 			bpf_mark_reg_unknown(dst_reg);
  			return 0;
  		}
  
@@@ -16500,7 -16771,7 +16783,7 @@@
  	}
  
  	if (to_scalar) {
- 		__mark_reg_unknown(env, dst_reg);
+ 		bpf_mark_reg_unknown(dst_reg);
  		return 0;
  	}
  
@@@ -16510,6 -16781,8 +16793,8 @@@
  	 */
  	if (dst_reg != ptr_reg)
  		*dst_reg = *ptr_reg;
+ 	/* a far pointer that comes back leaves its copies */
+ 	bpf_blur_far_offset(env, dst_reg);
  
  	/*
  	 * Accesses to untrusted PTR_TO_MEM are done through probe
@@@ -16520,29 -16793,19 +16805,19 @@@
  
  	if (!check_reg_sane_offset_scalar(env, off_reg, ptr_reg->type)) {
  		reason = bpf_diag_fmt(
- 			env, "The scalar offset used with R%d is unbounded or outside the verifier's safe pointer-offset range [-%u, %u].",
- 			ptr_regno, BPF_MAX_VAR_OFF, BPF_MAX_VAR_OFF);
+ 			env, "The scalar offset used with R%d can be -%u or less.",
+ 			ptr_regno, BPF_MAX_VAR_OFF);
  		bpf_diag_register_type(
  			env, env->insn_idx, ptr_regno, "pointer offset is not safe", reason,
  			"Clamp or bounds-check the scalar offset before applying it to the pointer.");
  		return -EINVAL;
  	}
- 	if (!check_reg_sane_offset_ptr(env, ptr_reg, ptr_reg->type)) {
- 		reason = bpf_diag_fmt(
- 			env, "R%d already has an offset outside the verifier's safe range [-%u, %u] for %s.",
- 			ptr_regno, BPF_MAX_VAR_OFF, BPF_MAX_VAR_OFF,
- 			bpf_diag_reg_type_plain(env, ptr_reg->type));
- 		bpf_diag_register_type(
- 			env, env->insn_idx, ptr_regno, "pointer offset is not safe", reason,
- 			"Keep the base pointer within the verifier's allowed offset range before applying more arithmetic.");
- 		return -EINVAL;
- 	}
  
  	if (sanitize_needed(opcode)) {
- 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
- 				       &info, false);
- 		if (ret < 0)
- 			return sanitize_err(env, insn, ret);
+ 		ret = sanitize_err(env, sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
+ 							 &info, false));
+ 		if (ret)
+ 			return ret;
  	}
  
  	/*
@@@ -16551,7 -16814,8 +16826,8 @@@
  	 * speculative path: otherwise reg_bounds_sanity_check() might hit some
  	 * constraints violations.
  	 */
- 	__mark_reg32_unbounded(dst_reg);
+ 	__mark_scalar32_unbounded(scalar_of(dst_reg));
+ 	min_len = pkt_min_len(ptr_reg);
  
  	switch (opcode) {
  	case BPF_ADD:
@@@ -16563,21 -16827,25 +16839,25 @@@
  		 * added into the variable offset, and we copy the fixed offset
  		 * from ptr_reg.
  		 */
- 		scalar_step_add(dst_reg, ptr_reg, off_reg);
- 		dst_reg->r64 = cnum64_add(ptr_reg->r64, off_reg->r64);
- 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
+ 		scalar_add(scalar_of(dst_reg), scalar_of(dst_reg), scalar_of(off_reg));
  		dst_reg->raw = ptr_reg->raw;
  		if (reg_is_pkt_pointer(ptr_reg)) {
  			if (!known)
- 				dst_reg->id = ++env->id_gen;
+ 				dst_reg->id = bpf_new_id(env);
  			/*
- 			 * Clear range for unknown addends since we can't know
- 			 * where the pkt pointer ended up. Also clear AT_PKT_END /
+ 			 * The range is what umax of the pointer may get to, see
+ 			 * check_packet_access(). umax of the addend was added to it
+ 			 * and the pointer moved by that much at most, so the range
+ 			 * holds. Clear it if the addend may be negative: umax says
+ 			 * nothing then. Clear it if umax got to it: it permits no
+ 			 * byte at or after the pointer, and it would only keep equal
+ 			 * states apart in regsafe(). Also clear AT_PKT_END /
  			 * BEYOND_PKT_END from prior comparison as any pointer
  			 * arithmetic invalidates them.
  			 */
- 			if (!known || dst_reg->range < 0)
- 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
+ 			if (dst_reg->range < 0 ||
+ 			    (!known && (smin_val < 0 || reg_umax(dst_reg) >= dst_reg->range)))
+ 				dst_reg->range = 0;
  		}
  		break;
  	case BPF_SUB:
@@@ -16609,12 -16877,12 +16889,12 @@@
  				"Use addition from R10 to form stack addresses within the tracked stack frame.");
  			return -EACCES;
  		}
- 		dst_reg->r64 = cnum64_add(ptr_reg->r64, cnum64_negate(off_reg->r64));
+ 		dst_reg->r64 = cnum64_sub(ptr_reg->r64, off_reg->r64);
  		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
  		dst_reg->raw = ptr_reg->raw;
  		if (reg_is_pkt_pointer(ptr_reg)) {
  			if (!known)
- 				dst_reg->id = ++env->id_gen;
+ 				dst_reg->id = bpf_new_id(env);
  			/*
  			 * Clear range if the subtrahend may be negative since
  			 * pkt pointer could move past its bounds. A positive
@@@ -16623,9 -16891,9 +16903,9 @@@
  			 * prior comparison as arithmetic invalidates them.
  			 */
  			if ((!known && smin_val < 0) || dst_reg->range < 0)
- 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
+ 				dst_reg->range = 0;
  		}
- 		reg_step_reset(dst_reg);
+ 		scalar_step_reset(scalar_of(dst_reg));
  		break;
  	case BPF_AND:
  	case BPF_OR:
@@@ -16655,25 -16923,24 +16935,24 @@@
  		return -EACCES;
  	}
  
- 	if (!check_reg_sane_offset_ptr(env, dst_reg, ptr_reg->type)) {
- 		reason = bpf_diag_fmt(
- 			env, "After this arithmetic, R%d would be outside the verifier's safe offset range [-%u, %u] for %s.",
- 			dst, BPF_MAX_VAR_OFF, BPF_MAX_VAR_OFF,
- 			bpf_diag_reg_type_plain(env, ptr_reg->type));
- 		bpf_diag_register_type(
- 			env, env->insn_idx, ptr_regno, "pointer offset is not safe", reason,
- 			"Tighten the scalar bounds before the arithmetic so the resulting pointer remains within the allowed range.");
- 		return -EINVAL;
- 	}
  	/*
  	 * A packet pointer that keeps its id or range is checked against a
  	 * range set from the checked pointer's umax, so var_off must not tighten
  	 * its umax. r32 must still match var_off for reg_bounds_sanity_check().
+ 	 * A sum with a new id is different: progs rely on what var_off and the
+ 	 * step tell about it (alignment, umin). No other pointer has its id, so
+ 	 * it is enough that its range loses what its umax loses.
  	 */
- 	if (reg_is_pkt_pointer(dst_reg) && (known || dst_reg->range > 0))
- 		__update_reg32_bounds(dst_reg);
+ 	smax = reg_smax(dst_reg);
+ 	if (reg_is_pkt_pointer(dst_reg) &&
+ 	    (known || (opcode == BPF_SUB && dst_reg->range > 0)))
+ 		__update_scalar32_bounds(scalar_of(dst_reg));
  	else
  		reg_bounds_sync(dst_reg);
+ 	if (reg_is_pkt_pointer(dst_reg))
+ 		dst_reg->pkt_min_len = min_len;
+ 	bpf_trim_pkt_range(dst_reg, smax);
+ 	bpf_blur_far_offset(env, dst_reg);
  	bounds_ret = sanitize_check_bounds(env, insn, dst_reg);
  	if (bounds_ret == -EACCES)
  		return bounds_ret;
@@@ -16681,62 -16948,45 +16960,45 @@@
  		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
  				       &info, true);
  		if (verifier_bug_if(!can_skip_alu_sanitation(env, insn)
- 				    && !env->cur_state->speculative
  				    && bounds_ret
  				    && !ret,
  				    env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) {
  			return -EFAULT;
  		}
- 		if (ret < 0)
- 			return sanitize_err(env, insn, ret);
+ 		return sanitize_err(env, ret);
  	}
  
  	return 0;
  }
  
- static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
- 				 struct bpf_reg_state *src_reg)
+ static void scalar32_min_max_sub(struct scalar *dst, const struct scalar *src)
  {
- 	dst_reg->r32 = cnum32_add(dst_reg->r32, src_reg->r32);
+ 	dst->r32 = cnum32_sub(dst->r32, src->r32);
  }
  
- static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
- 			       struct bpf_reg_state *src_reg)
+ static void scalar_min_max_sub(struct scalar *dst, const struct scalar *src)
  {
- 	dst_reg->r64 = cnum64_add(dst_reg->r64, src_reg->r64);
+ 	dst->r64 = cnum64_sub(dst->r64, src->r64);
  }
  
- static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
- 				 struct bpf_reg_state *src_reg)
+ static void scalar32_min_max_mul(struct scalar *dst, const struct scalar *src)
  {
- 	dst_reg->r32 = cnum32_add(dst_reg->r32, cnum32_negate(src_reg->r32));
- }
- 
- static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
- 			       struct bpf_reg_state *src_reg)
- {
- 	dst_reg->r64 = cnum64_add(dst_reg->r64, cnum64_negate(src_reg->r64));
- }
- 
- static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
- 				 struct bpf_reg_state *src_reg)
- {
- 	s32 smin = reg_s32_min(dst_reg);
- 	s32 smax = reg_s32_max(dst_reg);
- 	u32 umin = reg_u32_min(dst_reg);
- 	u32 umax = reg_u32_max(dst_reg);
+ 	s32 smin = cnum32_smin(dst->r32);
+ 	s32 smax = cnum32_smax(dst->r32);
+ 	u32 umin = cnum32_umin(dst->r32);
+ 	u32 umax = cnum32_umax(dst->r32);
  	s32 tmp_prod[4];
  
- 	if (check_mul_overflow(umax, reg_u32_max(src_reg), &umax) ||
- 	    check_mul_overflow(umin, reg_u32_min(src_reg), &umin)) {
+ 	if (check_mul_overflow(umax, cnum32_umax(src->r32), &umax) ||
+ 	    check_mul_overflow(umin, cnum32_umin(src->r32), &umin)) {
  		/* Overflow possible, we know nothing */
  		umin = 0;
  		umax = U32_MAX;
  	}
- 	if (check_mul_overflow(smin, reg_s32_min(src_reg), &tmp_prod[0]) ||
- 	    check_mul_overflow(smin, reg_s32_max(src_reg), &tmp_prod[1]) ||
- 	    check_mul_overflow(smax, reg_s32_min(src_reg), &tmp_prod[2]) ||
- 	    check_mul_overflow(smax, reg_s32_max(src_reg), &tmp_prod[3])) {
+ 	if (check_mul_overflow(smin, cnum32_smin(src->r32), &tmp_prod[0]) ||
+ 	    check_mul_overflow(smin, cnum32_smax(src->r32), &tmp_prod[1]) ||
+ 	    check_mul_overflow(smax, cnum32_smin(src->r32), &tmp_prod[2]) ||
+ 	    check_mul_overflow(smax, cnum32_smax(src->r32), &tmp_prod[3])) {
  		/* Overflow possible, we know nothing */
  		smin = S32_MIN;
  		smax = S32_MAX;
@@@ -16745,29 -16995,28 +17007,28 @@@
  		smax = max_array(tmp_prod, 4);
  	}
  
- 	dst_reg->r32 = cnum32_intersect(cnum32_from_urange(umin, umax),
- 					cnum32_from_srange(smin, smax));
+ 	dst->r32 = cnum32_intersect(cnum32_from_urange(umin, umax),
+ 				    cnum32_from_srange(smin, smax));
  }
  
- static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
- 			       struct bpf_reg_state *src_reg)
+ static void scalar_min_max_mul(struct scalar *dst, const struct scalar *src)
  {
- 	s64 smin = reg_smin(dst_reg);
- 	s64 smax = reg_smax(dst_reg);
- 	u64 umin = reg_umin(dst_reg);
- 	u64 umax = reg_umax(dst_reg);
+ 	s64 smin = cnum64_smin(dst->r64);
+ 	s64 smax = cnum64_smax(dst->r64);
+ 	u64 umin = cnum64_umin(dst->r64);
+ 	u64 umax = cnum64_umax(dst->r64);
  	s64 tmp_prod[4];
  
- 	if (check_mul_overflow(umax, reg_umax(src_reg), &umax) ||
- 	    check_mul_overflow(umin, reg_umin(src_reg), &umin)) {
+ 	if (check_mul_overflow(umax, cnum64_umax(src->r64), &umax) ||
+ 	    check_mul_overflow(umin, cnum64_umin(src->r64), &umin)) {
  		/* Overflow possible, we know nothing */
  		umin = 0;
  		umax = U64_MAX;
  	}
- 	if (check_mul_overflow(smin, reg_smin(src_reg), &tmp_prod[0]) ||
- 	    check_mul_overflow(smin, reg_smax(src_reg), &tmp_prod[1]) ||
- 	    check_mul_overflow(smax, reg_smin(src_reg), &tmp_prod[2]) ||
- 	    check_mul_overflow(smax, reg_smax(src_reg), &tmp_prod[3])) {
+ 	if (check_mul_overflow(smin, cnum64_smin(src->r64), &tmp_prod[0]) ||
+ 	    check_mul_overflow(smin, cnum64_smax(src->r64), &tmp_prod[1]) ||
+ 	    check_mul_overflow(smax, cnum64_smin(src->r64), &tmp_prod[2]) ||
+ 	    check_mul_overflow(smax, cnum64_smax(src->r64), &tmp_prod[3])) {
  		/* Overflow possible, we know nothing */
  		smin = S64_MIN;
  		smax = S64_MAX;
@@@ -16776,40 -17025,55 +17037,55 @@@
  		smax = max_array(tmp_prod, 4);
  	}
  
- 	dst_reg->r64 = cnum64_intersect(cnum64_from_urange(umin, umax),
- 					cnum64_from_srange(smin, smax));
+ 	dst->r64 = cnum64_intersect(cnum64_from_urange(umin, umax),
+ 				    cnum64_from_srange(smin, smax));
  }
  
- static void scalar32_min_max_udiv(struct bpf_reg_state *dst_reg,
- 				  struct bpf_reg_state *src_reg)
+ static void scalar_min_max_uhmul(struct scalar *dst, const struct scalar *src)
  {
- 	u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */
+ 	u64 a = scalar_const_value(dst, false);
+ 	u64 b = scalar_const_value(src, false);
  
- 	reg_set_urange32(dst_reg, reg_u32_min(dst_reg) / src_val,
- 			 reg_u32_max(dst_reg) / src_val);
+ 	scalar_set_const(dst, bpf_uhmul64(a, b));
+ }
+ 
+ static void scalar_min_max_shmul(struct scalar *dst, const struct scalar *src)
+ {
+ 	s64 a = scalar_const_value(dst, false);
+ 	s64 b = scalar_const_value(src, false);
+ 
+ 	scalar_set_const(dst, bpf_shmul64(a, b));
+ }
+ 
+ static void scalar32_min_max_udiv(struct scalar *dst, const struct scalar *src)
+ {
+ 	u32 src_min = cnum32_umin(src->r32), src_max = cnum32_umax(src->r32); /* src_max isn't 0 */
+ 
+ 	/* The largest divisor gives the smallest result, but for x / 0 = 0 */
+ 	dst->r32 = cnum32_from_urange(src_min ? cnum32_umin(dst->r32) / src_max : 0,
+ 				      cnum32_umax(dst->r32) / (src_min ?: 1));
  
  	/* Reset other ranges/tnum to unbounded/unknown. */
- 	reset_reg64_and_tnum(dst_reg);
+ 	reset_scalar64_and_tnum(dst);
  }
  
- static void scalar_min_max_udiv(struct bpf_reg_state *dst_reg,
- 				struct bpf_reg_state *src_reg)
+ static void scalar_min_max_udiv(struct scalar *dst, const struct scalar *src)
  {
- 	u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */
+ 	u64 src_min = cnum64_umin(src->r64), src_max = cnum64_umax(src->r64); /* src_max isn't 0 */
  
- 	reg_set_urange64(dst_reg, div64_u64(reg_umin(dst_reg), src_val),
- 			 div64_u64(reg_umax(dst_reg), src_val));
+ 	/* The largest divisor gives the smallest result, but for x / 0 = 0 */
+ 	dst->r64 = cnum64_from_urange(src_min ? div64_u64(cnum64_umin(dst->r64), src_max) : 0,
+ 				      div64_u64(cnum64_umax(dst->r64), src_min ?: 1));
  
  	/* Reset other ranges/tnum to unbounded/unknown. */
- 	reset_reg32_and_tnum(dst_reg);
+ 	reset_scalar32_and_tnum(dst);
  }
  
- static void scalar32_min_max_sdiv(struct bpf_reg_state *dst_reg,
- 				  struct bpf_reg_state *src_reg)
+ static void scalar32_min_max_sdiv(struct scalar *dst, const struct scalar *src)
  {
- 	s32 smin = reg_s32_min(dst_reg);
- 	s32 smax = reg_s32_max(dst_reg);
- 	s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */
+ 	s32 smin = cnum32_smin(dst->r32);
+ 	s32 smax = cnum32_smax(dst->r32);
+ 	s32 src_val = cnum32_smin(src->r32); /* non-zero, const divisor */
  	s32 res1, res2;
  
  	/* BPF div specification: S32_MIN / -1 = S32_MIN */
@@@ -16835,17 -17099,16 +17111,16 @@@
  	smax = max(res1, res2);
  
  reset:
- 	reg_set_srange32(dst_reg, smin, smax);
+ 	dst->r32 = cnum32_from_srange(smin, smax);
  	/* Reset other ranges/tnum to unbounded/unknown. */
- 	reset_reg64_and_tnum(dst_reg);
+ 	reset_scalar64_and_tnum(dst);
  }
  
- static void scalar_min_max_sdiv(struct bpf_reg_state *dst_reg,
- 				struct bpf_reg_state *src_reg)
+ static void scalar_min_max_sdiv(struct scalar *dst, const struct scalar *src)
  {
- 	s64 smin = reg_smin(dst_reg);
- 	s64 smax = reg_smax(dst_reg);
- 	s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */
+ 	s64 smin = cnum64_smin(dst->r64);
+ 	s64 smax = cnum64_smax(dst->r64);
+ 	s64 src_val = cnum64_smin(src->r64); /* non-zero, const divisor */
  	s64 res1, res2;
  
  	/* BPF div specification: S64_MIN / -1 = S64_MIN */
@@@ -16871,53 -17134,52 +17146,52 @@@
  	smax = max(res1, res2);
  
  reset:
- 	reg_set_srange64(dst_reg, smin, smax);
+ 	dst->r64 = cnum64_from_srange(smin, smax);
  	/* Reset other ranges/tnum to unbounded/unknown. */
- 	reset_reg32_and_tnum(dst_reg);
+ 	reset_scalar32_and_tnum(dst);
  }
  
- static void scalar32_min_max_umod(struct bpf_reg_state *dst_reg,
- 				  struct bpf_reg_state *src_reg)
+ static void scalar32_min_max_umod(struct scalar *dst, const struct scalar *src)
  {
- 	u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */
- 	u32 res_max = src_val - 1;
+ 	u32 src_min = cnum32_umin(src->r32), src_max = cnum32_umax(src->r32); /* src_max isn't 0 */
  
  	/*
- 	 * If dst_umax <= res_max, the result remains unchanged.
- 	 * e.g., [2, 5] % 10 = [2, 5].
+ 	 * If dst_umax < src_min, the result remains unchanged.
+ 	 * e.g., [2, 5] % [10, 20] = [2, 5].
  	 */
- 	if (reg_u32_max(dst_reg) <= res_max)
+ 	if (cnum32_umax(dst->r32) < src_min)
  		return;
  
- 	reg_set_urange32(dst_reg, 0, min(reg_u32_max(dst_reg), res_max));
+ 	/* The result is below the divisor and not above x, and x % 0 = x */
+ 	dst->r32 = cnum32_from_urange(0, min(cnum32_umax(dst->r32),
+ 					     src_min ? src_max - 1 : U32_MAX));
  
  	/* Reset other ranges/tnum to unbounded/unknown. */
- 	reset_reg64_and_tnum(dst_reg);
+ 	reset_scalar64_and_tnum(dst);
  }
  
- static void scalar_min_max_umod(struct bpf_reg_state *dst_reg,
- 				struct bpf_reg_state *src_reg)
+ static void scalar_min_max_umod(struct scalar *dst, const struct scalar *src)
  {
- 	u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */
- 	u64 res_max = src_val - 1;
+ 	u64 src_min = cnum64_umin(src->r64), src_max = cnum64_umax(src->r64); /* src_max isn't 0 */
  
  	/*
- 	 * If dst_umax <= res_max, the result remains unchanged.
- 	 * e.g., [2, 5] % 10 = [2, 5].
+ 	 * If dst_umax < src_min, the result remains unchanged.
+ 	 * e.g., [2, 5] % [10, 20] = [2, 5].
  	 */
- 	if (reg_umax(dst_reg) <= res_max)
+ 	if (cnum64_umax(dst->r64) < src_min)
  		return;
  
- 	reg_set_urange64(dst_reg, 0, min(reg_umax(dst_reg), res_max));
+ 	/* The result is below the divisor and not above x, and x % 0 = x */
+ 	dst->r64 = cnum64_from_urange(0, min(cnum64_umax(dst->r64),
+ 					     src_min ? src_max - 1 : U64_MAX));
  
  	/* Reset other ranges/tnum to unbounded/unknown. */
- 	reset_reg32_and_tnum(dst_reg);
+ 	reset_scalar32_and_tnum(dst);
  }
  
- static void scalar32_min_max_smod(struct bpf_reg_state *dst_reg,
- 				  struct bpf_reg_state *src_reg)
+ static void scalar32_min_max_smod(struct scalar *dst, const struct scalar *src)
  {
- 	s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */
+ 	s32 src_val = cnum32_smin(src->r32); /* non-zero, const divisor */
  
  	/*
  	 * Safe absolute value calculation:
@@@ -16937,26 -17199,25 +17211,25 @@@
  	 * If the dividend is already within the result range,
  	 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5].
  	 */
- 	if (reg_s32_min(dst_reg) >= -res_max_abs && reg_s32_max(dst_reg) <= res_max_abs)
+ 	if (cnum32_smin(dst->r32) >= -res_max_abs && cnum32_smax(dst->r32) <= res_max_abs)
  		return;
  
  	/* General case: result has the same sign as the dividend. */
- 	if (reg_s32_min(dst_reg) >= 0) {
- 		reg_set_srange32(dst_reg, 0, min(reg_s32_max(dst_reg), res_max_abs));
- 	} else if (reg_s32_max(dst_reg) <= 0) {
- 		reg_set_srange32(dst_reg, max(reg_s32_min(dst_reg), -res_max_abs), 0);
+ 	if (cnum32_smin(dst->r32) >= 0) {
+ 		dst->r32 = cnum32_from_srange(0, min(cnum32_smax(dst->r32), res_max_abs));
+ 	} else if (cnum32_smax(dst->r32) <= 0) {
+ 		dst->r32 = cnum32_from_srange(max(cnum32_smin(dst->r32), -res_max_abs), 0);
  	} else {
- 		reg_set_srange32(dst_reg, -res_max_abs, res_max_abs);
+ 		dst->r32 = cnum32_from_srange(-res_max_abs, res_max_abs);
  	}
  
  	/* Reset other ranges/tnum to unbounded/unknown. */
- 	reset_reg64_and_tnum(dst_reg);
+ 	reset_scalar64_and_tnum(dst);
  }
  
- static void scalar_min_max_smod(struct bpf_reg_state *dst_reg,
- 				struct bpf_reg_state *src_reg)
+ static void scalar_min_max_smod(struct scalar *dst, const struct scalar *src)
  {
- 	s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */
+ 	s64 src_val = cnum64_smin(src->r64); /* non-zero, const divisor */
  
  	/*
  	 * Safe absolute value calculation:
@@@ -16976,178 -17237,164 +17249,164 @@@
  	 * If the dividend is already within the result range,
  	 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5].
  	 */
- 	if (reg_smin(dst_reg) >= -res_max_abs && reg_smax(dst_reg) <= res_max_abs)
+ 	if (cnum64_smin(dst->r64) >= -res_max_abs && cnum64_smax(dst->r64) <= res_max_abs)
  		return;
  
  	/* General case: result has the same sign as the dividend. */
- 	if (reg_smin(dst_reg) >= 0) {
- 		reg_set_srange64(dst_reg, 0, min(reg_smax(dst_reg), res_max_abs));
- 	} else if (reg_smax(dst_reg) <= 0) {
- 		reg_set_srange64(dst_reg, max(reg_smin(dst_reg), -res_max_abs), 0);
+ 	if (cnum64_smin(dst->r64) >= 0) {
+ 		dst->r64 = cnum64_from_srange(0, min(cnum64_smax(dst->r64), res_max_abs));
+ 	} else if (cnum64_smax(dst->r64) <= 0) {
+ 		dst->r64 = cnum64_from_srange(max(cnum64_smin(dst->r64), -res_max_abs), 0);
  	} else {
- 		reg_set_srange64(dst_reg, -res_max_abs, res_max_abs);
+ 		dst->r64 = cnum64_from_srange(-res_max_abs, res_max_abs);
  	}
  
  	/* Reset other ranges/tnum to unbounded/unknown. */
- 	reset_reg32_and_tnum(dst_reg);
+ 	reset_scalar32_and_tnum(dst);
  }
  
- static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
- 				 struct bpf_reg_state *src_reg)
+ static void scalar32_min_max_and(struct scalar *dst, const struct scalar *src)
  {
- 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
- 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
- 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
- 	u32 umax_val = reg_u32_max(src_reg);
+ 	bool src_known = tnum_subreg_is_const(src->var_off);
+ 	bool dst_known = tnum_subreg_is_const(dst->var_off);
+ 	struct tnum var32_off = tnum_subreg(dst->var_off);
+ 	u32 umax_val = cnum32_umax(src->r32);
  
  	if (src_known && dst_known) {
- 		__mark_reg32_known(dst_reg, var32_off.value);
+ 		__mark_scalar32_known(dst, var32_off.value);
  		return;
  	}
  
  	/* We get our minimum from the var_off, since that's inherently
  	 * bitwise.  Our maximum is the minimum of the operands' maxima.
  	 */
- 	reg_set_urange32(dst_reg,
- 			 var32_off.value,
- 			 min(reg_u32_max(dst_reg), umax_val));
+ 	dst->r32 = cnum32_from_urange(var32_off.value,
+ 				      min(cnum32_umax(dst->r32), umax_val));
  }
  
- static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
- 			       struct bpf_reg_state *src_reg)
+ static void scalar_min_max_and(struct scalar *dst, const struct scalar *src)
  {
- 	bool src_known = tnum_is_const(src_reg->var_off);
- 	bool dst_known = tnum_is_const(dst_reg->var_off);
- 	u64 umax_val = reg_umax(src_reg);
+ 	bool src_known = tnum_is_const(src->var_off);
+ 	bool dst_known = tnum_is_const(dst->var_off);
+ 	u64 umax_val = cnum64_umax(src->r64);
  
  	if (src_known && dst_known) {
- 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
+ 		scalar_set_const(dst, dst->var_off.value);
  		return;
  	}
  
  	/* We get our minimum from the var_off, since that's inherently
  	 * bitwise.  Our maximum is the minimum of the operands' maxima.
  	 */
- 	reg_set_urange64(dst_reg,
- 			 dst_reg->var_off.value,
- 			 min(reg_umax(dst_reg), umax_val));
+ 	dst->r64 = cnum64_from_urange(dst->var_off.value,
+ 				      min(cnum64_umax(dst->r64), umax_val));
  
  	/* We may learn something more from the var_off */
- 	__update_reg_bounds(dst_reg);
+ 	__update_scalar_bounds(dst);
  }
  
- static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
- 				struct bpf_reg_state *src_reg)
+ static void scalar32_min_max_or(struct scalar *dst, const struct scalar *src)
  {
- 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
- 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
- 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
- 	u32 umin_val = reg_u32_min(src_reg);
+ 	bool src_known = tnum_subreg_is_const(src->var_off);
+ 	bool dst_known = tnum_subreg_is_const(dst->var_off);
+ 	struct tnum var32_off = tnum_subreg(dst->var_off);
+ 	u32 umin_val = cnum32_umin(src->r32);
  
  	if (src_known && dst_known) {
- 		__mark_reg32_known(dst_reg, var32_off.value);
+ 		__mark_scalar32_known(dst, var32_off.value);
  		return;
  	}
  
  	/* We get our maximum from the var_off, and our minimum is the
  	 * maximum of the operands' minima
  	 */
- 	reg_set_urange32(dst_reg,
- 			 max(reg_u32_min(dst_reg), umin_val),
- 			 var32_off.value | var32_off.mask);
+ 	dst->r32 = cnum32_from_urange(max(cnum32_umin(dst->r32), umin_val),
+ 				      var32_off.value | var32_off.mask);
  }
  
- static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
- 			      struct bpf_reg_state *src_reg)
+ static void scalar_min_max_or(struct scalar *dst, const struct scalar *src)
  {
- 	bool src_known = tnum_is_const(src_reg->var_off);
- 	bool dst_known = tnum_is_const(dst_reg->var_off);
- 	u64 umin_val = reg_umin(src_reg);
+ 	bool src_known = tnum_is_const(src->var_off);
+ 	bool dst_known = tnum_is_const(dst->var_off);
+ 	u64 umin_val = cnum64_umin(src->r64);
  
  	if (src_known && dst_known) {
- 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
+ 		scalar_set_const(dst, dst->var_off.value);
  		return;
  	}
  
  	/* We get our maximum from the var_off, and our minimum is the
  	 * maximum of the operands' minima
  	 */
- 	reg_set_urange64(dst_reg,
- 			 max(reg_umin(dst_reg), umin_val),
- 			 dst_reg->var_off.value | dst_reg->var_off.mask);
+ 	dst->r64 = cnum64_from_urange(max(cnum64_umin(dst->r64), umin_val),
+ 				      dst->var_off.value | dst->var_off.mask);
  
  	/* We may learn something more from the var_off */
- 	__update_reg_bounds(dst_reg);
+ 	__update_scalar_bounds(dst);
  }
  
- static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
- 				 struct bpf_reg_state *src_reg)
+ static void scalar32_min_max_xor(struct scalar *dst, const struct scalar *src)
  {
- 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
- 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
- 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
+ 	bool src_known = tnum_subreg_is_const(src->var_off);
+ 	bool dst_known = tnum_subreg_is_const(dst->var_off);
+ 	struct tnum var32_off = tnum_subreg(dst->var_off);
  
  	if (src_known && dst_known) {
- 		__mark_reg32_known(dst_reg, var32_off.value);
+ 		__mark_scalar32_known(dst, var32_off.value);
  		return;
  	}
  
  	/* We get both minimum and maximum from the var32_off. */
- 	reg_set_urange32(dst_reg, var32_off.value, var32_off.value | var32_off.mask);
+ 	dst->r32 = cnum32_from_urange(var32_off.value, var32_off.value | var32_off.mask);
  }
  
- static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
- 			       struct bpf_reg_state *src_reg)
+ static void scalar_min_max_xor(struct scalar *dst, const struct scalar *src)
  {
- 	bool src_known = tnum_is_const(src_reg->var_off);
- 	bool dst_known = tnum_is_const(dst_reg->var_off);
+ 	bool src_known = tnum_is_const(src->var_off);
+ 	bool dst_known = tnum_is_const(dst->var_off);
  
  	if (src_known && dst_known) {
- 		/* dst_reg->var_off.value has been updated earlier */
- 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
+ 		/* dst->var_off.value has been updated earlier */
+ 		scalar_set_const(dst, dst->var_off.value);
  		return;
  	}
  
  	/* We get both minimum and maximum from the var_off. */
- 	reg_set_urange64(dst_reg,
- 			 dst_reg->var_off.value,
- 			 dst_reg->var_off.value | dst_reg->var_off.mask);
+ 	dst->r64 = cnum64_from_urange(dst->var_off.value,
+ 				      dst->var_off.value | dst->var_off.mask);
  }
  
- static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
- 				   u64 umin_val, u64 umax_val)
+ static void __scalar32_min_max_lsh(struct scalar *dst, u64 umin_val, u64 umax_val)
  {
  	/* If we might shift our top bit out, then we know nothing */
- 	if (umax_val > 31 || reg_u32_max(dst_reg) > 1ULL << (31 - umax_val))
- 		reg_set_urange32(dst_reg, 0, U32_MAX);
+ 	if (umax_val > 31 || cnum32_umax(dst->r32) > 1ULL << (31 - umax_val))
+ 		dst->r32 = cnum32_from_urange(0, U32_MAX);
  	else
  		/* We lose all sign bit information (except what we can pick
  		 * up from var_off)
  		 */
- 		reg_set_urange32(dst_reg, reg_u32_min(dst_reg) << umin_val,
- 				 reg_u32_max(dst_reg) << umax_val);
+ 		dst->r32 = cnum32_from_urange(cnum32_umin(dst->r32) << umin_val,
+ 					      cnum32_umax(dst->r32) << umax_val);
  }
  
- static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
- 				 struct bpf_reg_state *src_reg)
+ static void scalar32_min_max_lsh(struct scalar *dst, const struct scalar *src)
  {
- 	u32 umax_val = reg_u32_max(src_reg);
- 	u32 umin_val = reg_u32_min(src_reg);
+ 	u32 umax_val = cnum32_umax(src->r32);
+ 	u32 umin_val = cnum32_umin(src->r32);
  	/* u32 alu operation will zext upper bits */
- 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
+ 	struct tnum subreg = tnum_subreg(dst->var_off);
  
- 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
- 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
+ 	__scalar32_min_max_lsh(dst, umin_val, umax_val);
+ 	dst->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
  	/* Not required but being careful mark reg64 bounds as unknown so
  	 * that we are forced to pick them up from tnum and zext later and
  	 * if some path skips this step we are still safe.
  	 */
- 	__mark_reg64_unbounded(dst_reg);
- 	__update_reg32_bounds(dst_reg);
+ 	__mark_scalar64_unbounded(dst);
+ 	__update_scalar32_bounds(dst);
  }
  
- static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
- 				   u64 umin_val, u64 umax_val)
+ static void __scalar64_min_max_lsh(struct scalar *dst, u64 umin_val, u64 umax_val)
  {
  	struct cnum64 u, s;
  
@@@ -17157,140 -17404,139 +17416,139 @@@
  	 * 32bits.
  	 */
  	if (umin_val == 32 && umax_val == 32)
- 		s = cnum64_from_srange((s64)reg_s32_min(dst_reg) << 32,
- 				       (s64)reg_s32_max(dst_reg) << 32);
+ 		s = cnum64_from_srange((s64)cnum32_smin(dst->r32) << 32,
+ 				       (s64)cnum32_smax(dst->r32) << 32);
  	else
  		s = CNUM64_UNBOUNDED;
  
  	/* If we might shift our top bit out, then we know nothing */
- 	if (reg_umax(dst_reg) > 1ULL << (63 - umax_val))
+ 	if (cnum64_umax(dst->r64) > 1ULL << (63 - umax_val))
  		u = CNUM64_UNBOUNDED;
  	else
- 		u = cnum64_from_urange(reg_umin(dst_reg) << umin_val,
- 				       reg_umax(dst_reg) << umax_val);
+ 		u = cnum64_from_urange(cnum64_umin(dst->r64) << umin_val,
+ 				       cnum64_umax(dst->r64) << umax_val);
  
- 	dst_reg->r64 = cnum64_intersect(u, s);
+ 	dst->r64 = cnum64_intersect(u, s);
  }
  
- static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
- 			       struct bpf_reg_state *src_reg)
+ static void scalar_min_max_lsh(struct scalar *dst, const struct scalar *src)
  {
- 	u64 umax_val = reg_umax(src_reg);
- 	u64 umin_val = reg_umin(src_reg);
+ 	u64 umax_val = cnum64_umax(src->r64);
+ 	u64 umin_val = cnum64_umin(src->r64);
  
  	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
- 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
- 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
+ 	__scalar64_min_max_lsh(dst, umin_val, umax_val);
+ 	__scalar32_min_max_lsh(dst, umin_val, umax_val);
  
- 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
+ 	dst->var_off = tnum_lshift(dst->var_off, umin_val);
  	/* We may learn something more from the var_off */
- 	__update_reg_bounds(dst_reg);
+ 	__update_scalar_bounds(dst);
  }
  
- static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
- 				 struct bpf_reg_state *src_reg)
+ static void scalar32_min_max_rsh(struct scalar *dst, const struct scalar *src)
  {
- 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
- 	u32 umax_val = reg_u32_max(src_reg);
- 	u32 umin_val = reg_u32_min(src_reg);
+ 	struct tnum subreg = tnum_subreg(dst->var_off);
+ 	u32 umax_val = cnum32_umax(src->r32);
+ 	u32 umin_val = cnum32_umin(src->r32);
  
- 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
+ 	/* BPF_RSH is an unsigned shift.  If the value in dst might
  	 * be negative, then either:
- 	 * 1) src_reg might be zero, so the sign bit of the result is
+ 	 * 1) src might be zero, so the sign bit of the result is
  	 *    unknown, so we lose our signed bounds
  	 * 2) it's known negative, thus the unsigned bounds capture the
  	 *    signed bounds
  	 * 3) the signed bounds cross zero, so they tell us nothing
  	 *    about the result
- 	 * If the value in dst_reg is known nonnegative, then again the
+ 	 * If the value in dst is known nonnegative, then again the
  	 * unsigned bounds capture the signed bounds.
  	 * Thus, in all cases it suffices to blow away our signed bounds
  	 * and rely on inferring new ones from the unsigned bounds and
  	 * var_off of the result.
  	 */
  
- 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
- 	reg_set_urange32(dst_reg, reg_u32_min(dst_reg) >> umax_val,
- 			 reg_u32_max(dst_reg) >> umin_val);
+ 	dst->var_off = tnum_rshift(subreg, umin_val);
+ 	dst->r32 = cnum32_from_urange(cnum32_umin(dst->r32) >> umax_val,
+ 				      cnum32_umax(dst->r32) >> umin_val);
  
- 	__mark_reg64_unbounded(dst_reg);
- 	__update_reg32_bounds(dst_reg);
+ 	__mark_scalar64_unbounded(dst);
+ 	__update_scalar32_bounds(dst);
  }
  
- static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
- 			       struct bpf_reg_state *src_reg)
+ static void scalar_min_max_rsh(struct scalar *dst, const struct scalar *src)
  {
- 	u64 umax_val = reg_umax(src_reg);
- 	u64 umin_val = reg_umin(src_reg);
+ 	u64 umax_val = cnum64_umax(src->r64);
+ 	u64 umin_val = cnum64_umin(src->r64);
  
- 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
+ 	/* BPF_RSH is an unsigned shift.  If the value in dst might
  	 * be negative, then either:
- 	 * 1) src_reg might be zero, so the sign bit of the result is
+ 	 * 1) src might be zero, so the sign bit of the result is
  	 *    unknown, so we lose our signed bounds
  	 * 2) it's known negative, thus the unsigned bounds capture the
  	 *    signed bounds
  	 * 3) the signed bounds cross zero, so they tell us nothing
  	 *    about the result
- 	 * If the value in dst_reg is known nonnegative, then again the
+ 	 * If the value in dst is known nonnegative, then again the
  	 * unsigned bounds capture the signed bounds.
  	 * Thus, in all cases it suffices to blow away our signed bounds
  	 * and rely on inferring new ones from the unsigned bounds and
  	 * var_off of the result.
  	 */
- 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
- 	reg_set_urange64(dst_reg, reg_umin(dst_reg) >> umax_val,
- 			 reg_umax(dst_reg) >> umin_val);
+ 	dst->var_off = tnum_rshift(dst->var_off, umin_val);
+ 	dst->r64 = cnum64_from_urange(cnum64_umin(dst->r64) >> umax_val,
+ 				      cnum64_umax(dst->r64) >> umin_val);
  
  	/* Its not easy to operate on alu32 bounds here because it depends
  	 * on bits being shifted in. Take easy way out and mark unbounded
  	 * so we can recalculate later from tnum.
  	 */
- 	__mark_reg32_unbounded(dst_reg);
- 	__update_reg_bounds(dst_reg);
+ 	__mark_scalar32_unbounded(dst);
+ 	__update_scalar_bounds(dst);
  }
  
- static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
- 				  struct bpf_reg_state *src_reg)
+ static void scalar32_min_max_arsh(struct scalar *dst, const struct scalar *src)
  {
- 	u64 umin_val = reg_u32_min(src_reg);
+ 	u32 umin_val = cnum32_umin(src->r32), umax_val = cnum32_umax(src->r32);
+ 	struct cnum32 known = cnum32_from_tnum(dst->var_off);
+ 	s32 smin = max(cnum32_smin(dst->r32), cnum32_smin(known));
+ 	s32 smax = min(cnum32_smax(dst->r32), cnum32_smax(known));
  
- 	/* Upon reaching here, src_known is true and
- 	 * umax_val is equal to umin_val.
- 	 * Blow away the dst_reg umin_value/umax_value and rely on
- 	 * dst_reg var_off to refine the result.
+ 	/*
+ 	 * A larger count brings the result closer to 0, or to -1.
+ 	 * Blow away the dst umin_value/umax_value and rely on
+ 	 * dst var_off to refine the result.
  	 */
- 	reg_set_srange32(dst_reg,
- 			 (u32)(((s32)reg_s32_min(dst_reg)) >> umin_val),
- 			 (u32)(((s32)reg_s32_max(dst_reg)) >> umin_val));
+ 	dst->r32 = cnum32_from_srange(smin >> (smin < 0 ? umin_val : umax_val),
+ 				      smax >> (smax < 0 ? umax_val : umin_val));
  
- 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
+ 	dst->var_off = tnum_arshift(tnum_subreg(dst->var_off), umin_val, 32);
  
- 	__mark_reg64_unbounded(dst_reg);
- 	__update_reg32_bounds(dst_reg);
+ 	__mark_scalar64_unbounded(dst);
+ 	__update_scalar32_bounds(dst);
  }
  
- static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
- 				struct bpf_reg_state *src_reg)
+ static void scalar_min_max_arsh(struct scalar *dst, const struct scalar *src)
  {
- 	u64 umin_val = reg_umin(src_reg);
+ 	u64 umin_val = cnum64_umin(src->r64), umax_val = cnum64_umax(src->r64);
+ 	struct cnum64 known = cnum64_from_tnum(dst->var_off);
+ 	/* a range that crosses S64_MAX has no signed bounds, the known bits have: 0..0xf0 << 56 */
+ 	s64 smin = max(cnum64_smin(dst->r64), cnum64_smin(known));
+ 	s64 smax = min(cnum64_smax(dst->r64), cnum64_smax(known));
  
- 	/* Upon reaching here, src_known is true and umax_val is equal
- 	 * to umin_val.
- 	 */
- 	reg_set_srange64(dst_reg, reg_smin(dst_reg) >> umin_val,
- 			 reg_smax(dst_reg) >> umin_val);
+ 	/* A larger count brings the result closer to 0, or to -1 */
+ 	dst->r64 = cnum64_from_srange(smin >> (smin < 0 ? umin_val : umax_val),
+ 				      smax >> (smax < 0 ? umax_val : umin_val));
  
- 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
+ 	dst->var_off = tnum_arshift(dst->var_off, umin_val, 64);
  
  	/* Its not easy to operate on alu32 bounds here because it depends
  	 * on bits being shifted in from upper 32-bits. Take easy way out
  	 * and mark unbounded so we can recalculate later from tnum.
  	 */
- 	__mark_reg32_unbounded(dst_reg);
- 	__update_reg_bounds(dst_reg);
+ 	__mark_scalar32_unbounded(dst);
+ 	__update_scalar_bounds(dst);
  }
  
- static void scalar_byte_swap(struct bpf_reg_state *dst_reg, struct bpf_insn *insn)
+ static void scalar_byte_swap(struct scalar *dst, const struct bpf_insn *insn)
  {
  	/*
  	 * Byte swap operation - update var_off using tnum_bswap.
@@@ -17314,51 -17560,45 +17572,45 @@@
  	/* Apply bswap if alu64 or switch between big-endian and little-endian machines */
  	bool need_bswap = alu64 || (to_le == is_big_endian);
  
- 	/*
- 	 * If the register is mutated, manually reset its scalar ID to break
- 	 * any existing ties and avoid incorrect bounds propagation.
- 	 */
- 	if (need_bswap || insn->imm == 16 || insn->imm == 32)
- 		clear_scalar_id(dst_reg);
- 
  	if (need_bswap) {
  		if (insn->imm == 16)
- 			dst_reg->var_off = tnum_bswap16(dst_reg->var_off);
+ 			dst->var_off = tnum_bswap16(dst->var_off);
  		else if (insn->imm == 32)
- 			dst_reg->var_off = tnum_bswap32(dst_reg->var_off);
+ 			dst->var_off = tnum_bswap32(dst->var_off);
  		else if (insn->imm == 64)
- 			dst_reg->var_off = tnum_bswap64(dst_reg->var_off);
+ 			dst->var_off = tnum_bswap64(dst->var_off);
  		/*
  		 * Byteswap scrambles the range, so we must reset bounds.
  		 * Bounds will be re-derived from the new tnum later.
  		 */
- 		__mark_reg_unbounded(dst_reg);
- 		reg_step_reset(dst_reg);
+ 		__mark_scalar_unbounded(dst);
+ 		scalar_step_reset(dst);
  	}
  	/* For bswap16/32, truncate dst register to match the swapped size */
  	if (insn->imm == 16 || insn->imm == 32)
- 		coerce_reg_to_size(dst_reg, insn->imm / 8);
+ 		coerce_scalar_to_size(dst, insn->imm / 8);
  }
  
- static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
- 					     const struct bpf_reg_state *src_reg)
+ static bool is_safe_to_compute_dst_reg_range(const struct bpf_insn *insn,
+ 					     const struct scalar *src)
  {
  	bool src_is_const = false;
  	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
  
  	if (insn_bitness == 32) {
- 		if (tnum_subreg_is_const(src_reg->var_off)
- 		    && reg_s32_min(src_reg) == reg_s32_max(src_reg)
- 		    && reg_u32_min(src_reg) == reg_u32_max(src_reg))
+ 		if (tnum_subreg_is_const(src->var_off)
+ 		    && cnum32_smin(src->r32) == cnum32_smax(src->r32)
+ 		    && cnum32_umin(src->r32) == cnum32_umax(src->r32))
  			src_is_const = true;
  	} else {
- 		if (tnum_is_const(src_reg->var_off)
- 		    && reg_smin(src_reg) == reg_smax(src_reg)
- 		    && reg_umin(src_reg) == reg_umax(src_reg))
+ 		if (tnum_is_const(src->var_off)
+ 		    && cnum64_smin(src->r64) == cnum64_smax(src->r64)
+ 		    && cnum64_umin(src->r64) == cnum64_umax(src->r64))
  			src_is_const = true;
  	}
  
  	switch (BPF_OP(insn->code)) {
+ 	case BPF_MOV:
  	case BPF_ADD:
  	case BPF_SUB:
  	case BPF_NEG:
@@@ -17369,32 -17609,29 +17621,29 @@@
  	case BPF_END:
  		return true;
  
- 	/*
- 	 * Division and modulo operators range is only safe to compute when the
- 	 * divisor is a constant.
- 	 */
+ 	/* The range of a signed division or modulo is computed for a constant divisor only */
  	case BPF_DIV:
  	case BPF_MOD:
- 		return src_is_const;
+ 		return src_is_const || !insn->off;
  
- 	/* Shift operators range is only computable if shift dimension operand
- 	 * is a constant. Shifts greater than 31 or 63 are undefined. This
- 	 * includes shifts by a negative number.
+ 	/*
+ 	 * Shifts greater than 31 or 63 are undefined. This includes shifts by
+ 	 * a negative number.
  	 */
  	case BPF_LSH:
  	case BPF_RSH:
  	case BPF_ARSH:
- 		return (src_is_const && reg_umax(src_reg) < insn_bitness);
+ 		return cnum64_umax(src->r64) < insn_bitness;
  	default:
  		return false;
  	}
  }
  
  static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn,
- 				      struct bpf_reg_state *dst_reg, struct bpf_reg_state src_reg);
+ 				      struct bpf_reg_state *dst_reg, struct scalar src_val);
  
  static int maybe_fork_scalars(struct bpf_verifier_env *env, struct bpf_insn *insn,
- 			      struct bpf_reg_state *dst_reg, const struct bpf_reg_state *src_reg)
+ 			      struct bpf_reg_state *dst_reg, const struct scalar *src)
  {
  	struct bpf_verifier_state *branch;
  	struct bpf_reg_state *reg;
@@@ -17407,51 -17644,55 +17656,55 @@@
  	else
  		return 0;
  
+ 	/* with a step only a later insn can find that a part has no value */
+ 	scalar_step_reset(scalar_of(dst_reg));
  	branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
  	if (IS_ERR(branch))
  		return PTR_ERR(branch);
  
  	reg = &branch->frame[branch->curframe]->regs[insn->dst_reg];
  	if (alu32) {
- 		__mark_reg32_known(reg, 0);
- 		__mark_reg32_known(dst_reg, -1ull);
+ 		__mark_scalar32_known(scalar_of(reg), 0);
+ 		__mark_scalar32_known(scalar_of(dst_reg), -1ull);
  	} else {
  		__mark_reg_known(reg, 0);
  		__mark_reg_known(dst_reg, -1ull);
  	}
+ 	bpf_equations_fork(env, branch, scalar_of(reg));
+ 	bpf_equations_fork(env, env->cur_state, scalar_of(dst_reg));
  	/*
  	 * The insn is done with in the branch too, and what gets to the next insn is a state
  	 * like any other. At this insn the branch is a part of the state that is looked at:
  	 * it must not be compared with it.
  	 */
- 	clear_scalar_id(reg);
- 	return adjust_scalar_min_max_vals(env, insn, reg, *src_reg);
+ 	return adjust_scalar_min_max_vals(env, insn, reg, *src);
  }
  
- /* WARNING: This function does calculations on 64-bit values, but the actual
+ /*
+  * dst = dst <op> src: the transfer function of the ALU insn @insn.
+  * @src can't be @dst. BPF_NEG and BPF_END ignore its value: any valid scalar will do.
+  *
+  * WARNING: This function does calculations on 64-bit values, but the actual
   * execution may occur on 32-bit values. Therefore, things like bitshifts
   * need extra checks in the 32-bit case.
   */
- static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
- 				      struct bpf_insn *insn,
- 				      struct bpf_reg_state *dst_reg,
- 				      struct bpf_reg_state src_reg)
+ void scalar_alu(struct scalar *dst, const struct scalar *src, const struct bpf_insn *insn)
  {
  	u8 opcode = BPF_OP(insn->code);
  	s16 off = insn->off;
  	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
- 	int ret;
+ 	struct scalar tmp;
+ 	u64 cleared;
  
- 	if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
- 		__mark_reg_unknown(env, dst_reg);
- 		return 0;
+ 	if (!is_safe_to_compute_dst_reg_range(insn, src)) {
+ 		scalar_set_unknown(dst);
+ 		return;
  	}
  
- 	if (sanitize_needed(opcode)) {
- 		ret = sanitize_val_alu(env, insn);
- 		if (ret < 0)
- 			return sanitize_err(env, insn, ret);
- 	}
+ 	/* The count of a shift is a range: a bit of dst can end up in more than one place */
+ 	if ((opcode == BPF_LSH || opcode == BPF_RSH || opcode == BPF_ARSH) &&
+ 	    cnum64_umin(src->r64) != cnum64_umax(src->r64))
+ 		dst->var_off = tnum_unknown;
  
  	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
  	 * There are two classes of instructions: The first class we track both
@@@ -17468,118 -17709,141 +17721,141 @@@
  	 * tnum to calculate an approximation of the sign/unsigned bounds.
  	 */
  	switch (opcode) {
+ 	case BPF_MOV:
+ 		*dst = *src;
+ 		if (off && alu32)
+ 			coerce_subreg_to_size_sx(dst, off >> 3);
+ 		else if (off)
+ 			coerce_scalar_to_size_sx(dst, off >> 3);
+ 		break;
  	case BPF_ADD:
- 		scalar_step_add(dst_reg, dst_reg, &src_reg);
- 		scalar32_min_max_add(dst_reg, &src_reg);
- 		scalar_min_max_add(dst_reg, &src_reg);
- 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
+ 		scalar_add(dst, dst, src);
  		break;
  	case BPF_SUB:
- 		scalar32_min_max_sub(dst_reg, &src_reg);
- 		scalar_min_max_sub(dst_reg, &src_reg);
- 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
- 		reg_step_reset(dst_reg);
+ 		scalar32_min_max_sub(dst, src);
+ 		scalar_min_max_sub(dst, src);
+ 		dst->var_off = tnum_sub(dst->var_off, src->var_off);
+ 		scalar_step_reset(dst);
  		break;
  	case BPF_NEG:
- 		env->fake_reg[0] = *dst_reg;
- 		__mark_reg_known(dst_reg, 0);
- 		scalar32_min_max_sub(dst_reg, &env->fake_reg[0]);
- 		scalar_min_max_sub(dst_reg, &env->fake_reg[0]);
- 		dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off);
- 		reg_step_reset(dst_reg);
+ 		tmp = *dst;
+ 		scalar_set_const(dst, 0);
+ 		scalar32_min_max_sub(dst, &tmp);
+ 		scalar_min_max_sub(dst, &tmp);
+ 		dst->var_off = tnum_neg(tmp.var_off);
+ 		scalar_step_reset(dst);
  		break;
  	case BPF_MUL:
- 		scalar_step_mul(dst_reg, &src_reg);
- 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
- 		scalar32_min_max_mul(dst_reg, &src_reg);
- 		scalar_min_max_mul(dst_reg, &src_reg);
+ 		/*
+ 		 * Range analysis for UHMUL/SHMUL is not implemented yet.
+ 		 * Compute an exact result only when both operands are constants.
+ 		 * Ordinary low-half MUL continues to use the analysis below.
+ 		 */
+ 		if (bpf_insn_is_hmul(insn) &&
+ 		    (!scalar_is_const(dst, false) ||
+ 		     !scalar_is_const(src, false))) {
+ 			scalar_set_unknown(dst);
+ 			break;
+ 		}
+ 		if (!alu32 && insn->off == BPF_UHMUL) {
+ 			scalar_min_max_uhmul(dst, src);
+ 			break;
+ 		}
+ 		if (!alu32 && insn->off == BPF_SHMUL) {
+ 			scalar_min_max_shmul(dst, src);
+ 			break;
+ 		}
+ 		scalar_step_mul(dst, src);
+ 		dst->var_off = tnum_mul(dst->var_off, src->var_off);
+ 		scalar32_min_max_mul(dst, src);
+ 		scalar_min_max_mul(dst, src);
  		break;
  	case BPF_DIV:
  		/* BPF div specification: x / 0 = 0 */
- 		if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0)) {
- 			___mark_reg_known(dst_reg, 0);
+ 		if ((alu32 && cnum32_umax(src->r32) == 0) ||
+ 		    (!alu32 && cnum64_umax(src->r64) == 0)) {
+ 			scalar_set_const(dst, 0);
  			break;
  		}
  		if (alu32)
  			if (off == 1)
- 				scalar32_min_max_sdiv(dst_reg, &src_reg);
+ 				scalar32_min_max_sdiv(dst, src);
  			else
- 				scalar32_min_max_udiv(dst_reg, &src_reg);
+ 				scalar32_min_max_udiv(dst, src);
  		else
  			if (off == 1)
- 				scalar_min_max_sdiv(dst_reg, &src_reg);
+ 				scalar_min_max_sdiv(dst, src);
  			else
- 				scalar_min_max_udiv(dst_reg, &src_reg);
- 		reg_step_reset(dst_reg);
+ 				scalar_min_max_udiv(dst, src);
+ 		scalar_step_reset(dst);
  		break;
  	case BPF_MOD:
  		/* BPF mod specification: x % 0 = x */
- 		if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0))
+ 		if ((alu32 && cnum32_umax(src->r32) == 0) ||
+ 		    (!alu32 && cnum64_umax(src->r64) == 0))
  			break;
  		if (alu32)
  			if (off == 1)
- 				scalar32_min_max_smod(dst_reg, &src_reg);
+ 				scalar32_min_max_smod(dst, src);
  			else
- 				scalar32_min_max_umod(dst_reg, &src_reg);
+ 				scalar32_min_max_umod(dst, src);
  		else
  			if (off == 1)
- 				scalar_min_max_smod(dst_reg, &src_reg);
+ 				scalar_min_max_smod(dst, src);
  			else
- 				scalar_min_max_umod(dst_reg, &src_reg);
- 		reg_step_reset(dst_reg);
+ 				scalar_min_max_umod(dst, src);
+ 		scalar_step_reset(dst);
  		break;
  	case BPF_AND:
- 		if (tnum_is_const(src_reg.var_off)) {
- 			ret = maybe_fork_scalars(env, insn, dst_reg, &src_reg);
- 			if (ret)
- 				return ret;
- 		}
- 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
- 		scalar32_min_max_and(dst_reg, &src_reg);
- 		scalar_min_max_and(dst_reg, &src_reg);
- 		reg_step_reset(dst_reg);
+ 		cleared = (dst->var_off.value | dst->var_off.mask) & ~src->var_off.value;
+ 		tmp = *dst;
+ 		dst->var_off = tnum_and(dst->var_off, src->var_off);
+ 		scalar32_min_max_and(dst, src);
+ 		scalar_min_max_and(dst, src);
+ 		scalar_step_reset(dst);
+ 		/*
+ 		 * If no bit is cleared, the old ranges hold too.
+ 		 * A part from maybe_fork_scalars() can have no value.
+ 		 */
+ 		if (!(u32)cleared && !scalar_is_empty(&tmp))
+ 			scalar_intersect(dst, &tmp, cleared ? 32 : 64);
  		break;
  	case BPF_OR:
- 		if (tnum_is_const(src_reg.var_off)) {
- 			ret = maybe_fork_scalars(env, insn, dst_reg, &src_reg);
- 			if (ret)
- 				return ret;
- 		}
- 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
- 		scalar32_min_max_or(dst_reg, &src_reg);
- 		scalar_min_max_or(dst_reg, &src_reg);
- 		reg_step_reset(dst_reg);
+ 		dst->var_off = tnum_or(dst->var_off, src->var_off);
+ 		scalar32_min_max_or(dst, src);
+ 		scalar_min_max_or(dst, src);
+ 		scalar_step_reset(dst);
  		break;
  	case BPF_XOR:
- 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
- 		scalar32_min_max_xor(dst_reg, &src_reg);
- 		scalar_min_max_xor(dst_reg, &src_reg);
- 		reg_step_reset(dst_reg);
+ 		dst->var_off = tnum_xor(dst->var_off, src->var_off);
+ 		scalar32_min_max_xor(dst, src);
+ 		scalar_min_max_xor(dst, src);
+ 		scalar_step_reset(dst);
  		break;
  	case BPF_LSH:
- 		scalar_step_lsh(dst_reg, &src_reg);
+ 		scalar_step_lsh(dst, src);
  		if (alu32)
- 			scalar32_min_max_lsh(dst_reg, &src_reg);
+ 			scalar32_min_max_lsh(dst, src);
  		else
- 			scalar_min_max_lsh(dst_reg, &src_reg);
+ 			scalar_min_max_lsh(dst, src);
  		break;
  	case BPF_RSH:
  		if (alu32)
- 			scalar32_min_max_rsh(dst_reg, &src_reg);
+ 			scalar32_min_max_rsh(dst, src);
  		else
- 			scalar_min_max_rsh(dst_reg, &src_reg);
- 		reg_step_reset(dst_reg);
+ 			scalar_min_max_rsh(dst, src);
+ 		scalar_step_reset(dst);
  		break;
  	case BPF_ARSH:
  		if (alu32)
- 			scalar32_min_max_arsh(dst_reg, &src_reg);
+ 			scalar32_min_max_arsh(dst, src);
  		else
- 			scalar_min_max_arsh(dst_reg, &src_reg);
- 		reg_step_reset(dst_reg);
+ 			scalar_min_max_arsh(dst, src);
+ 		scalar_step_reset(dst);
  		break;
  	case BPF_END:
- 		scalar_byte_swap(dst_reg, insn);
- 		reg_step_reset(dst_reg);
+ 		scalar_byte_swap(dst, insn);
+ 		scalar_step_reset(dst);
  		break;
  	default:
  		break;
@@@ -17595,8 -17859,29 +17871,29 @@@
  	 * but we should not zero extend the result.
  	 */
  	if (alu32 && opcode != BPF_END)
- 		zext_32_to_64(dst_reg);
- 	reg_bounds_sync(dst_reg);
+ 		scalar_zext32(dst);
+ 	scalar_bounds_sync(dst);
+ }
+ 
+ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn,
+ 				      struct bpf_reg_state *dst_reg, struct scalar src_val)
+ {
+ 	u8 opcode = BPF_OP(insn->code);
+ 	int ret;
+ 
+ 	if (sanitize_needed(opcode)) {
+ 		ret = sanitize_err(env, sanitize_val_alu(env, insn));
+ 		if (ret)
+ 			return ret;
+ 	}
+ 
+ 	if ((opcode == BPF_AND || opcode == BPF_OR) && tnum_is_const(src_val.var_off)) {
+ 		ret = maybe_fork_scalars(env, insn, dst_reg, &src_val);
+ 		if (ret)
+ 			return ret;
+ 	}
+ 
+ 	scalar_alu(scalar_of(dst_reg), &src_val, insn);
  	return 0;
  }
  
@@@ -17610,10 -17895,8 +17907,8 @@@ static int adjust_reg_min_max_vals(stru
  	struct bpf_func_state *state = vstate->frame[vstate->curframe];
  	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
  	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
- 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
  	struct bpf_insn_aux_data *aux = cur_aux(env);
  	u8 opcode = BPF_OP(insn->code);
- 	int err;
  
  	dst_reg = &regs[insn->dst_reg];
  	if (BPF_SRC(insn->code) == BPF_X)
@@@ -17624,6 -17907,11 +17919,11 @@@
  	/* Case where at least one operand is an arena. */
  	if (dst_reg->type == PTR_TO_ARENA || (src_reg && src_reg->type == PTR_TO_ARENA)) {
  
+ 		if (bpf_insn_is_hmul(insn)) {
+ 			verbose(env, "UHMUL/SHMUL with arena pointers are not supported\n");
+ 			return -EOPNOTSUPP;
+ 		}
+ 
  		if (dst_reg->type != PTR_TO_ARENA)
  			*dst_reg = *src_reg;
  
@@@ -17635,10 -17923,8 +17935,8 @@@
  			 * prevent zext from being set if the instruction has
  			 * been previously called with non-arena registers.
  			 */
- 			if (aux->prevent_zext) {
- 				verbose(env, "same insn cannot be used with and without arena pointer\n");
- 				return -EINVAL;
- 			}
+ 			if (aux->prevent_zext)
+ 				return fixups_differ(env, "same insn cannot be used with and without arena pointer");
  
  			/*
  			 * 32-bit operations zero upper bits automatically.
@@@ -17654,10 -17940,8 +17952,8 @@@
  
  	/* Prevent the instruction from being used with arena pointers (see above). */
  	if (env->prog->aux->arena && BPF_CLASS(insn->code) == BPF_ALU64) {
- 		if (aux->needs_zext) {
- 			verbose(env, "same insn cannot be used with and without arena pointer\n");
- 			return -EINVAL;
- 		}
+ 		if (aux->needs_zext)
+ 			return fixups_differ(env, "same insn cannot be used with and without arena pointer");
  
  		aux->prevent_zext = true;
  	}
@@@ -17668,11 -17952,11 +17964,11 @@@
  	if (BPF_SRC(insn->code) == BPF_X) {
  		if (src_reg->type != SCALAR_VALUE) {
  			if (dst_reg->type != SCALAR_VALUE) {
- 				/* Combining two pointers by any ALU op yields
- 				 * an arbitrary scalar. Disallow all math except
- 				 * pointer subtraction
+ 				/*
+ 				 * Combining two pointers by any ALU op yields
+ 				 * an arbitrary scalar.
  				 */
- 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
+ 				if (env->allow_ptr_leaks) {
  					mark_reg_unknown(env, regs, insn->dst_reg);
  					return 0;
  				}
@@@ -17685,24 -17969,13 +17981,13 @@@
  				 * This is legal, but we have to reverse our
  				 * src/dest handling in computing the range
  				 */
- 				err = mark_chain_precision(env, insn->dst_reg);
- 				if (err)
- 					return err;
  				off_reg = *dst_reg;
  				return adjust_ptr_min_max_vals(env, insn, insn->src_reg, src_reg,
  							       &off_reg);
  			}
  		} else if (ptr_reg) {
  			/* pointer += scalar */
- 			err = mark_chain_precision(env, insn->src_reg);
- 			if (err)
- 				return err;
  			return adjust_ptr_min_max_vals(env, insn, insn->dst_reg, dst_reg, src_reg);
- 		} else if (dst_reg->precise) {
- 			/* if dst_reg is precise, src_reg should be precise as well */
- 			err = mark_chain_precision(env, insn->src_reg);
- 			if (err)
- 				return err;
  		}
  	} else {
  		/* Pretend the src is a reg with a known value, since we only
@@@ -17726,69 -17999,7 +18011,7 @@@
  		verbose(env, "verifier internal error: no src_reg\n");
  		return -EFAULT;
  	}
- 	/*
- 	 * For alu32 linked register tracking, we need to check dst_reg's
- 	 * umax_value before the ALU operation. After adjust_scalar_min_max_vals(),
- 	 * alu32 ops will have zero-extended the result, making umax_value <= U32_MAX.
- 	 */
- 	u64 dst_umax = reg_umax(dst_reg);
- 
- 	err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
- 	if (err)
- 		return err;
- 	/*
- 	 * Compilers can generate the code
- 	 * r1 = r2
- 	 * r1 += 0x1
- 	 * if r2 < 1000 goto ...
- 	 * use r1 in memory access
- 	 * So remember constant delta between r2 and r1 and update r1 after
- 	 * 'if' condition.
- 	 */
- 	if (env->bpf_capable &&
- 	    (BPF_OP(insn->code) == BPF_ADD || BPF_OP(insn->code) == BPF_SUB) &&
- 	    dst_reg->id && is_reg_const(src_reg, alu32) &&
- 	    !(BPF_SRC(insn->code) == BPF_X && insn->src_reg == insn->dst_reg)) {
- 		u64 val = reg_const_value(src_reg, alu32);
- 		s32 off;
- 
- 		if (!alu32 && ((s64)val < S32_MIN || (s64)val > S32_MAX))
- 			goto clear_id;
- 
- 		if (alu32 && (dst_umax > U32_MAX))
- 			goto clear_id;
- 
- 		off = (s32)val;
- 
- 		if (BPF_OP(insn->code) == BPF_SUB) {
- 			/* Negating S32_MIN would overflow */
- 			if (off == S32_MIN)
- 				goto clear_id;
- 			off = -off;
- 		}
- 
- 		if (dst_reg->id & BPF_ADD_CONST) {
- 			/*
- 			 * If the register already went through rX += val
- 			 * we cannot accumulate another val into rx->off.
- 			 */
- clear_id:
- 			clear_scalar_id(dst_reg);
- 		} else {
- 			if (alu32)
- 				dst_reg->id |= BPF_ADD_CONST32;
- 			else
- 				dst_reg->id |= BPF_ADD_CONST64;
- 			dst_reg->delta = off;
- 		}
- 	} else {
- 		/*
- 		 * Make sure ID is cleared otherwise dst_reg min/max could be
- 		 * incorrectly propagated into other registers by sync_linked_regs()
- 		 */
- 		clear_scalar_id(dst_reg);
- 	}
- 	return 0;
+ 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *scalar_of(src_reg));
  }
  
  /*
@@@ -17844,70 -18055,157 +18067,157 @@@ bool bpf_same_memory_origin(const struc
   * 'range - smax' bytes from a packet pointer are in the packet. reg_bounds_sync() can make smax
   * smaller than @smax: with a step of 8, or with 3 zero bits in var_off, 58 becomes 56. Make the
   * range smaller by the same number, so that the number of bytes does not grow. umax is not
-  * sufficient: it is U64_MAX when the offset can be negative.
+  * sufficient: it is U64_MAX when the offset can be negative. A jump can take smax from S64_MAX
+  * to -3: the difference does not fit in s64. If smax is larger than @smax the range is lost.
+  * If smax is below pkt_min_len, the range is at least pkt_min_len.
   */
  void bpf_trim_pkt_range(struct bpf_reg_state *reg, s64 smax)
  {
- 	if (type_is_pkt_pointer(reg->type) && reg->range > 0)
- 		reg->range = max_t(s64, reg->range - (smax - reg_smax(reg)), 0);
- }
+ 	u64 lost = (u64)smax - reg_smax(reg);
  
- int bpf_set_reg_range(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
- 		      struct cnum64 r64, struct cnum32 r32, u16 base, u16 step)
- {
- 	reg->r64 = r64;
- 	reg->r32 = r32;
- 	reg->step = step;
- 	reg->base = base;
- 	reg->var_off = tnum_unknown;
- 	reg_bounds_sync(reg); /* this should infer the tnum alignment */
- 	bpf_trim_pkt_range(reg, cnum64_smax(r64));
- 	return reg_bounds_sanity_check(env, reg, "bpf_set_reg_range");
+ 	if (!type_is_pkt_pointer(reg->type) || reg->range < 0)
+ 		return;
+ 	reg->range = lost < reg->range ? reg->range - lost : 0;
+ 	if (reg->pkt_min_len > reg_smax(reg))
+ 		reg->range = max(reg->range, reg->pkt_min_len);
  }
  
  /*
-  * Checks if pointer and packet metadata matches between two registers.
-  * For use with bpf_reg_union().
+  * @s is what @old became after a trip around a cycle, @old included. The end
+  * of the range that moved will move again. Move it to a threshold where it
+  * can stop. @min_threshold, @max_threshold: the caller guesses that it stops there.
+  * Take the nearest threshold. Each value between the range and the threshold is made up,
+  * and the program is checked with it. With each threshold the range only gets larger.
   */
- bool bpf_reg_union_compatible(const struct bpf_reg_state *a, const struct bpf_reg_state *b)
+ void scalar_widen(struct scalar *s, const struct scalar *old, s64 min_threshold, s64 max_threshold)
  {
- 	if (a->type != b->type)
- 		return false;
- 	if (a->type == SCALAR_VALUE)
- 		return true;
- 	return !memcmp(a, b, offsetof(struct bpf_reg_state, var_off)) &&
- 	       a->id == b->id && a->parent_id == b->parent_id && a->map_uid == b->map_uid;
- }
+ 	bool moved = s->r64.base != old->r64.base || s->r64.size != old->r64.size ||
+ 		     s->r32.base != old->r32.base || s->r32.size != old->r32.size;
+ 	s64 min = cnum64_smin(s->r64), max = cnum64_smax(s->r64), threshold;
  
- /*
-  * Extends acc's scalar range to include src's scalar range.
-  * Caller must ensure that other kinds of metadata is compatible.
-  * Caller must clear acc's scalar ID.
-  */
- int bpf_reg_union(struct bpf_verifier_env *env, struct bpf_reg_state *acc,
- 		  const struct bpf_reg_state *src)
- {
- 	u16 base, step;
+ 	/* Only the step got weaker. It comes to rest without help, see below. */
+ 	if (!moved && s->var_off.value == old->var_off.value &&
+ 	    s->var_off.mask == old->var_off.mask)
+ 		return;
  
- 	if (!bpf_reg_union_compatible(acc, src)) {
- 		verifier_bug(env, "union of incompatible registers");
- 		return -EFAULT;
+ 	if (max > cnum64_smax(old->r64)) {
+ 		threshold = max <= 0 ? 0 :
+ 			    max <= S32_MAX ? S32_MAX :
+ 			    max <= U32_MAX ? U32_MAX : S64_MAX;
+ 		max = min(threshold, max_threshold);
  	}
+ 	if (min < cnum64_smin(old->r64)) {
+ 		threshold = min >= 0 ? 0 :
+ 			    min >= S32_MIN ? S32_MIN : S64_MIN;
+ 		min = max(threshold, min_threshold);
+ 	}
+ 	if (min == S64_MIN && max == S64_MAX) {
+ 		scalar_set_unknown(s);
+ 		return;
+ 	}
+ 	/*
+ 	 * A fixed threshold is a guess. A number of 32 bits that gets past S32_MAX stops at
+ 	 * U32_MAX. No threshold stops what gets past S32_MAX, U32_MAX or S32_MIN and out of
+ 	 * 32 bits:
+ 	 *	sum += a[i]; if (sum == 77) ...
+ 	 * It wraps in the next trip, and the other bound is gone as well.
+ 	 */
+ 	if ((max == S64_MAX &&
+ 	     (cnum64_smax(old->r64) == S32_MAX || cnum64_smax(old->r64) == U32_MAX)) ||
+ 	    (min == S64_MIN && cnum64_smin(old->r64) == S32_MIN)) {
+ 		scalar_set_unknown(s);
+ 		return;
+ 	}
+ 	/* every part has to include what it did before, hence no scalar_bounds_sync() */
+ 	s->r64 = cnum64_union(s->r64, cnum64_from_srange(min, max));
+ 	if (min >= 0 && max <= U32_MAX) {
+ 		s->r32 = cnum32_union(s->r32, cnum32_from_urange(min, max));
+ 		s->var_off = tnum_union(s->var_off, tnum_range(min, max));
+ 	} else if (min >= S32_MIN && max <= S32_MAX) {
+ 		s->r32 = cnum32_union(s->r32, cnum32_from_srange(min, max));
+ 		s->var_off = tnum_unknown;
+ 	} else {
+ 		s->r32 = CNUM32_UNBOUNDED;
+ 		s->var_off = min >= 0 ? tnum_union(s->var_off, tnum_range(min, max))
+ 					: tnum_unknown;
+ 	}
+ 	/*
+ 	 * No range moved: the known bits or the step got weaker. The step comes to rest without
+ 	 * help: it gives way to one of its divisors only.
+ 	 *	off = n * 4; do { sum += *(u32 *)(a + off); off -= 4; } while (off != -4);
+ 	 * counts on "a multiple of 4".
+ 	 */
+ 	if (moved)
+ 		scalar_step_reset(s);
+ }
+ 
+ void scalar_union(struct scalar *acc, const struct scalar *src)
+ {
+ 	bool acc_const = cnum64_is_const(acc->r64), src_const = cnum64_is_const(src->r64);
+ 	/* A constant is its own base. Its step is 0: every number divides 0. */
+ 	s64 a = acc_const ? cnum64_smin(acc->r64) : acc->base;
+ 	s64 b = src_const ? cnum64_smin(src->r64) : src->base;
+ 	u16 step = gcd(acc_const ? 0 : acc->step, src_const ? 0 : src->step);
+ 	s64 diff;
+ 
  	acc->r64 = cnum64_union(acc->r64, src->r64);
  	acc->r32 = cnum32_union(acc->r32, src->r32);
  	acc->var_off = tnum_union(acc->var_off, src->var_off);
  
- 	/* Retain a common congruence if the bases agree modulo the gcd. */
- 	step = gcd(acc->step, src->step);
- 	base = acc->base % step;
- 	if (base != src->base % step) {
- 		reg_step_reset(acc);
- 	} else {
- 		acc->base = base;
- 		acc->step = step;
+ 	/* a + s * k and b + t * k are both of the form a + gcd(s, t, a - b) * k */
+ 	if (check_sub_overflow(a, b, &diff) || (!step && (diff > U16_MAX || diff < -U16_MAX)))
+ 		step = 1;
+ 	else
+ 		step = (step ? gcd(step, imod(diff, step)) : abs(diff)) ?: 1;
+ 	acc->step = step;
+ 	acc->base = imod(a, step);
+ 	/*
+ 	 * No reg_bounds_sync(): every part of the result has to include that
+ 	 * part of both inputs, and an input is not always in sync.
+ 	 */
+ }
+ 
+ /*
+  * There are no address spaces in Rust. The compiler doesn't cast a pointer that
+  * comes from the kernel. But it can't always tell, and then it casts the pointer
+  * to as(0) before the access, like an address in arena.
+  * A pointer that the verifier knows is in as(0) already, so the cast is a move.
+  * arg_track_xfer() does the same for pointers to stack.
+  */
+ static bool is_cast_mov(const struct bpf_insn *insn, const struct bpf_reg_state *src_reg)
+ {
+ 	/* cast from as(1) to as(0) */
+ 	if (insn->imm != 1)
+ 		return false;
+ 
+ 	switch (base_type(src_reg->type)) {
+ 	case SCALAR_VALUE:
+ 	case PTR_TO_ARENA:
+ 		return false;
+ 	default:
+ 		return true;
  	}
- 	reg_bounds_sync(acc);
- 	return reg_bounds_sanity_check(env, acc, "bpf_reg_union");
+ }
+ 
+ static int check_addr_space_cast(struct bpf_verifier_env *env, struct bpf_insn *insn,
+ 				 struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg)
+ {
+ 	struct bpf_insn_aux_data *aux = cur_aux(env);
+ 
+ 	if (is_cast_mov(insn, src_reg)) {
+ 		aux->cast_mov = true;
+ 		*dst_reg = *src_reg;
+ 	} else {
+ 		aux->cast_arena = true;
+ 		mark_reg_unknown(env, cur_regs(env), insn->dst_reg);
+ 		if (insn->imm == 1) /* cast from as(1) to as(0) */
+ 			dst_reg->type = PTR_TO_ARENA;
+ 	}
+ 
+ 	/* it's either wX = wY or rX = rY, see bpf_lower_cast_mov() */
+ 	if (aux->cast_mov && aux->cast_arena)
+ 		return fixups_differ(env, "same addr_space_cast insn cannot be used with a number and with a pointer");
+ 	return 0;
  }
  
  /* check validity of 32-bit and 64-bit arithmetic operations */
@@@ -17936,7 -18234,7 +18246,7 @@@ static int check_alu_op(struct bpf_veri
  			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
  			err = err ?: adjust_scalar_min_max_vals(env, insn,
  							 &regs[insn->dst_reg],
- 							 regs[insn->dst_reg]);
+ 							 *scalar_of(&regs[insn->dst_reg]));
  		} else {
  			err = check_reg_arg(env, insn->dst_reg, DST_OP);
  		}
@@@ -17971,14 -18269,13 +18281,13 @@@
  			if (BPF_CLASS(insn->code) == BPF_ALU64) {
  				if (insn->imm) {
  					/* off == BPF_ADDR_SPACE_CAST */
- 					mark_reg_unknown(env, regs, insn->dst_reg);
- 					if (insn->imm == 1) /* cast from as(1) to as(0) */
- 						dst_reg->type = PTR_TO_ARENA;
+ 					err = check_addr_space_cast(env, insn, dst_reg, src_reg);
+ 					if (err)
+ 						return err;
  				} else if (insn->off == 0) {
  					/* case: R1 = R2
  					 * copy register state to dest reg
  					 */
- 					assign_scalar_id_before_mov(env, src_reg);
  					*dst_reg = *src_reg;
  				} else {
  					/* case: R1 = (s8, s16 s32)R2 */
@@@ -17988,15 -18285,9 +18297,9 @@@
  							insn->src_reg);
  						return -EACCES;
  					} else if (src_reg->type == SCALAR_VALUE) {
- 						bool no_sext;
- 
- 						no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1));
- 						if (no_sext)
- 							assign_scalar_id_before_mov(env, src_reg);
  						*dst_reg = *src_reg;
- 						if (!no_sext)
- 							clear_scalar_id(dst_reg);
- 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
+ 						coerce_scalar_to_size_sx(scalar_of(dst_reg),
+ 									 insn->off >> 3);
  					} else {
  						mark_reg_unknown(env, regs, insn->dst_reg);
  					}
@@@ -18009,34 -18300,16 +18312,16 @@@
  						insn->src_reg);
  					return -EACCES;
  				} else if (src_reg->type == SCALAR_VALUE) {
- 					if (insn->off == 0) {
- 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
- 
- 						if (is_src_reg_u32)
- 							assign_scalar_id_before_mov(env, src_reg);
- 						*dst_reg = *src_reg;
- 						/* Make sure ID is cleared if src_reg is not in u32
- 						 * range otherwise dst_reg min/max could be incorrectly
- 						 * propagated into src_reg by sync_linked_regs()
- 						 */
- 						if (!is_src_reg_u32)
- 							clear_scalar_id(dst_reg);
- 					} else {
- 						/* case: W1 = (s8, s16)W2 */
- 						bool no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1));
- 
- 						if (no_sext)
- 							assign_scalar_id_before_mov(env, src_reg);
- 						*dst_reg = *src_reg;
- 						if (!no_sext)
- 							clear_scalar_id(dst_reg);
- 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
- 					}
+ 					*dst_reg = *src_reg;
+ 					/* case: W1 = (s8, s16)W2 */
+ 					if (insn->off)
+ 						coerce_subreg_to_size_sx(scalar_of(dst_reg),
+ 									 insn->off >> 3);
  				} else {
  					mark_reg_unknown(env, regs,
  							 insn->dst_reg);
  				}
- 				zext_32_to_64(dst_reg);
+ 				scalar_zext32(scalar_of(dst_reg));
  				reg_bounds_sync(dst_reg);
  			}
  		} else {
@@@ -18177,37 -18450,37 +18462,37 @@@ static void find_good_pkt_pointers(stru
  	}));
  }
  
- static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
- 				u8 opcode, bool is_jmp32);
  /*
   * Learn more information about live branches by simulating refinement on both branches.
-  * regs_refine_cond_op() is sound, so producing ill-formed register bounds for the branch means
+  * scalars_refine_cond_op() is sound, so producing ill-formed register bounds for the branch means
   * that branch is dead.
   */
  static int simulate_both_branches_taken(struct bpf_verifier_env *env, u8 opcode, bool is_jmp32)
  {
  	/* Fallthrough (FALSE) branch */
- 	regs_refine_cond_op(&env->false_reg1, &env->false_reg2, bpf_rev_opcode(opcode), is_jmp32);
+ 	scalars_refine_cond_op(scalar_of(&env->false_reg1), scalar_of(&env->false_reg2),
+ 			       bpf_rev_opcode(opcode), is_jmp32);
  	reg_bounds_sync(&env->false_reg1);
  	reg_bounds_sync(&env->false_reg2);
+ 	/* Jump (TRUE) branch. If FALSE is dead refine_live_branch() takes these registers. */
+ 	scalars_refine_cond_op(scalar_of(&env->true_reg1), scalar_of(&env->true_reg2), opcode,
+ 			       is_jmp32);
+ 	reg_bounds_sync(&env->true_reg1);
+ 	reg_bounds_sync(&env->true_reg2);
  	/*
  	 * If there is a range bounds violation in *any* of the abstract values in either
  	 * reg_states in the FALSE branch (i.e. reg1, reg2), the FALSE branch must be dead. Only
  	 * TRUE branch will be taken.
  	 */
- 	if (range_bounds_violation(&env->false_reg1) || range_bounds_violation(&env->false_reg2))
+ 	if (reg_is_empty(&env->false_reg1) || reg_is_empty(&env->false_reg2))
  		return 1;
  
- 	/* Jump (TRUE) branch */
- 	regs_refine_cond_op(&env->true_reg1, &env->true_reg2, opcode, is_jmp32);
- 	reg_bounds_sync(&env->true_reg1);
- 	reg_bounds_sync(&env->true_reg2);
  	/*
  	 * If there is a range bounds violation in *any* of the abstract values in either
  	 * reg_states in the TRUE branch (i.e. true_reg1, true_reg2), the TRUE branch must be dead.
  	 * Only FALSE branch will be taken.
  	 */
- 	if (range_bounds_violation(&env->true_reg1) || range_bounds_violation(&env->true_reg2))
+ 	if (reg_is_empty(&env->true_reg1) || reg_is_empty(&env->true_reg2))
  		return 0;
  
  	/* Both branches are possible, we can't determine which one will be taken. */
@@@ -18447,6 -18720,18 +18732,18 @@@ static int is_branch_taken(struct bpf_v
  	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
  		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
  
+ 	/* Two pointers to one object have the order of their offsets */
+ 	if (reg1->type != SCALAR_VALUE && !is_jmp32 && opcode != BPF_JSET && env->bypass_spec_v1 &&
+ 	    !(reg1->type & PTR_UNTRUSTED) && bpf_same_memory_origin(reg1, reg2)) {
+ 		/* an object can be at a low address, but not in the first page */
+ 		struct cnum64 lim = cnum64_from_srange(opcode == BPF_JEQ || opcode == BPF_JNE ?
+ 						       -BPF_MAX_VAR_OFF : -SZ_4K, BPF_MAX_VAR_OFF);
+ 
+ 		if (!cnum64_is_subset(lim, reg1->r64) || !cnum64_is_subset(lim, reg2->r64))
+ 			return -1;
+ 		return is_scalar_branch_taken(env, reg1, reg2, bpf_signed_opcode(opcode), false);
+ 	}
+ 
  	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
  		u64 val;
  
@@@ -18472,7 -18757,7 +18769,7 @@@
  		/* If pointer is valid tests against zero will fail so we can
  		 * use this to direct branch taken.
  		 */
- 		val = reg_const_value(reg2, is_jmp32);
+ 		val = scalar_const_value(scalar_of(reg2), is_jmp32);
  		if (val != 0)
  			return -1;
  
@@@ -18515,9 -18800,8 +18812,8 @@@ u8 bpf_rev_opcode(u8 opcode
  	}
  }
  
- /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
- static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
- 				u8 opcode, bool is_jmp32)
+ /* Refine range knowledge for <a> <op> <b> conditional operation. */
+ void scalars_refine_cond_op(struct scalar *a, struct scalar *b, u8 opcode, bool is_jmp32)
  {
  	struct tnum t;
  	u64 val;
@@@ -18529,7 -18813,7 +18825,7 @@@
  	case BPF_JSGE:
  	case BPF_JSGT:
  		opcode = bpf_flip_opcode(opcode);
- 		swap(reg1, reg2);
+ 		swap(a, b);
  		break;
  	default:
  		break;
@@@ -18538,44 -18822,44 +18834,44 @@@
  	switch (opcode) {
  	case BPF_JEQ:
  		if (is_jmp32) {
- 			reg1->r32 = cnum32_intersect(reg1->r32, reg2->r32);
- 			reg2->r32 = reg1->r32;
+ 			a->r32 = cnum32_intersect(a->r32, b->r32);
+ 			b->r32 = a->r32;
  
- 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
- 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
- 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
+ 			t = tnum_intersect(tnum_subreg(a->var_off), tnum_subreg(b->var_off));
+ 			a->var_off = tnum_with_subreg(a->var_off, t);
+ 			b->var_off = tnum_with_subreg(b->var_off, t);
  		} else {
- 			reg1->r64 = cnum64_intersect(reg1->r64, reg2->r64);
- 			reg2->r64 = reg1->r64;
+ 			a->r64 = cnum64_intersect(a->r64, b->r64);
+ 			b->r64 = a->r64;
  
- 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
- 			reg2->var_off = reg1->var_off;
+ 			a->var_off = tnum_intersect(a->var_off, b->var_off);
+ 			b->var_off = a->var_off;
  		}
  		break;
  	case BPF_JNE:
- 		if (!is_reg_const(reg2, is_jmp32))
- 			swap(reg1, reg2);
- 		if (!is_reg_const(reg2, is_jmp32))
+ 		if (!scalar_is_const(b, is_jmp32))
+ 			swap(a, b);
+ 		if (!scalar_is_const(b, is_jmp32))
  			break;
  
- 		/* try to recompute the bound of reg1 if reg2 is a const and
- 		 * is exactly the edge of reg1.
+ 		/* try to recompute the bound of a if b is a const and
+ 		 * is exactly the edge of a.
  		 */
- 		val = reg_const_value(reg2, is_jmp32);
+ 		val = scalar_const_value(b, is_jmp32);
  		if (is_jmp32) {
  			/* Complement of the range [val, val] as cnum32. */
- 			cnum32_intersect_with(&reg1->r32, (struct cnum32){ val + 1, U32_MAX - 1 });
+ 			cnum32_intersect_with(&a->r32, (struct cnum32){ val + 1, U32_MAX - 1 });
  		} else {
  			/* Complement of the range [val, val] as cnum64. */
- 			cnum64_intersect_with(&reg1->r64, (struct cnum64){ val + 1, U64_MAX - 1 });
+ 			cnum64_intersect_with(&a->r64, (struct cnum64){ val + 1, U64_MAX - 1 });
  		}
  		break;
  	case BPF_JSET:
- 		if (!is_reg_const(reg2, is_jmp32))
- 			swap(reg1, reg2);
- 		if (!is_reg_const(reg2, is_jmp32))
+ 		if (!scalar_is_const(b, is_jmp32))
+ 			swap(a, b);
+ 		if (!scalar_is_const(b, is_jmp32))
  			break;
- 		val = reg_const_value(reg2, is_jmp32);
+ 		val = scalar_const_value(b, is_jmp32);
  		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
  		 * requires single bit to learn something useful. E.g., if we
  		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
@@@ -18589,64 -18873,64 +18885,64 @@@
  		if (hweight64(val) != 1)
  			break;
  		if (is_jmp32) {
- 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
- 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
+ 			t = tnum_or(tnum_subreg(a->var_off), tnum_const(val));
+ 			a->var_off = tnum_with_subreg(a->var_off, t);
  		} else {
- 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
+ 			a->var_off = tnum_or(a->var_off, tnum_const(val));
  		}
  		break;
  	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see bpf_rev_opcode() */
- 		if (!is_reg_const(reg2, is_jmp32))
- 			swap(reg1, reg2);
- 		if (!is_reg_const(reg2, is_jmp32))
+ 		if (!scalar_is_const(b, is_jmp32))
+ 			swap(a, b);
+ 		if (!scalar_is_const(b, is_jmp32))
  			break;
- 		val = reg_const_value(reg2, is_jmp32);
+ 		val = scalar_const_value(b, is_jmp32);
  		/* Forget the ranges before narrowing tnums, to avoid invariant
  		 * violations if we're on a dead branch.
  		 */
- 		__mark_reg_unbounded(reg1);
- 		reg_step_reset(reg1);
+ 		__mark_scalar_unbounded(a);
+ 		scalar_step_reset(a);
  		if (is_jmp32) {
- 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
- 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
+ 			t = tnum_and(tnum_subreg(a->var_off), tnum_const(~val));
+ 			a->var_off = tnum_with_subreg(a->var_off, t);
  		} else {
- 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
+ 			a->var_off = tnum_and(a->var_off, tnum_const(~val));
  		}
  		break;
  	case BPF_JLE:
  		if (is_jmp32) {
- 			cnum32_intersect_with_urange(&reg1->r32, 0, reg_u32_max(reg2));
- 			cnum32_intersect_with_urange(&reg2->r32, reg_u32_min(reg1), U32_MAX);
+ 			cnum32_intersect_with_urange(&a->r32, 0, cnum32_umax(b->r32));
+ 			cnum32_intersect_with_urange(&b->r32, cnum32_umin(a->r32), U32_MAX);
  		} else {
- 			cnum64_intersect_with_urange(&reg1->r64, 0, reg_umax(reg2));
- 			cnum64_intersect_with_urange(&reg2->r64, reg_umin(reg1), U64_MAX);
+ 			cnum64_intersect_with_urange(&a->r64, 0, cnum64_umax(b->r64));
+ 			cnum64_intersect_with_urange(&b->r64, cnum64_umin(a->r64), U64_MAX);
  		}
  		break;
  	case BPF_JLT:
  		if (is_jmp32) {
- 			cnum32_intersect_with_urange(&reg1->r32, 0, reg_u32_max(reg2) - 1);
- 			cnum32_intersect_with_urange(&reg2->r32, reg_u32_min(reg1) + 1, U32_MAX);
+ 			cnum32_intersect_with_urange(&a->r32, 0, cnum32_umax(b->r32) - 1);
+ 			cnum32_intersect_with_urange(&b->r32, cnum32_umin(a->r32) + 1, U32_MAX);
  		} else {
- 			cnum64_intersect_with_urange(&reg1->r64, 0, reg_umax(reg2) - 1);
- 			cnum64_intersect_with_urange(&reg2->r64, reg_umin(reg1) + 1, U64_MAX);
+ 			cnum64_intersect_with_urange(&a->r64, 0, cnum64_umax(b->r64) - 1);
+ 			cnum64_intersect_with_urange(&b->r64, cnum64_umin(a->r64) + 1, U64_MAX);
  		}
  		break;
  	case BPF_JSLE:
  		if (is_jmp32) {
- 			cnum32_intersect_with_srange(&reg1->r32, S32_MIN, reg_s32_max(reg2));
- 			cnum32_intersect_with_srange(&reg2->r32, reg_s32_min(reg1), S32_MAX);
+ 			cnum32_intersect_with_srange(&a->r32, S32_MIN, cnum32_smax(b->r32));
+ 			cnum32_intersect_with_srange(&b->r32, cnum32_smin(a->r32), S32_MAX);
  		} else {
- 			cnum64_intersect_with_srange(&reg1->r64, S64_MIN, reg_smax(reg2));
- 			cnum64_intersect_with_srange(&reg2->r64, reg_smin(reg1), S64_MAX);
+ 			cnum64_intersect_with_srange(&a->r64, S64_MIN, cnum64_smax(b->r64));
+ 			cnum64_intersect_with_srange(&b->r64, cnum64_smin(a->r64), S64_MAX);
  		}
  		break;
  	case BPF_JSLT:
  		if (is_jmp32) {
- 			cnum32_intersect_with_srange(&reg1->r32, S32_MIN, reg_s32_max(reg2) - 1);
- 			cnum32_intersect_with_srange(&reg2->r32, reg_s32_min(reg1) + 1, S32_MAX);
+ 			cnum32_intersect_with_srange(&a->r32, S32_MIN, cnum32_smax(b->r32) - 1);
+ 			cnum32_intersect_with_srange(&b->r32, cnum32_smin(a->r32) + 1, S32_MAX);
  		} else {
- 			cnum64_intersect_with_srange(&reg1->r64, S64_MIN, reg_smax(reg2) - 1);
- 			cnum64_intersect_with_srange(&reg2->r64, reg_smin(reg1) + 1, S64_MAX);
+ 			cnum64_intersect_with_srange(&a->r64, S64_MIN, cnum64_smax(b->r64) - 1);
+ 			cnum64_intersect_with_srange(&b->r64, cnum64_smin(a->r64) + 1, S64_MAX);
  		}
  		break;
  	default:
@@@ -18686,7 -18970,7 +18982,7 @@@ static void mark_ptr_or_null_reg(struc
  		if (is_null) {
  			/* We don't need id from this point
  			 * onwards anymore, thus we should better reset it,
- 			 * so that state pruning has chances to take effect.
+ 			 * so that states have chances to be equal.
  			 */
  			__mark_reg_known_zero(reg);
  			reg->type = SCALAR_VALUE;
@@@ -18718,7 -19002,7 +19014,7 @@@ static void mark_ptr_or_null_regs(struc
  		 * No one could have freed the reference state before
  		 * doing the NULL check.
  		 */
- 		WARN_ON_ONCE(__release_reference_nomark(vstate, id));
+ 		WARN_ON_ONCE(release_reference_nomark(vstate, id));
  
  	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
  		mark_ptr_or_null_reg(state, reg, id, is_null);
@@@ -18830,130 -19114,164 +19126,164 @@@ static bool try_match_pkt_pointers(cons
  	return true;
  }
  
- static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
- 				  u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
+ /* a == b (mod 2^N) implies a == b if both fit in uN or both fit in sN. N is @bits. */
+ bool scalars_fit_in_bits(const struct scalar *a, const struct scalar *b, u32 bits)
  {
- 	struct linked_reg *e;
+ 	u64 umax = GENMASK_ULL(bits - 1, 0);
+ 	s64 smax = umax >> 1;
  
- 	if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
- 		return;
+ 	return (cnum64_umax(a->r64) <= umax && cnum64_umax(b->r64) <= umax) ||
+ 	       (cnum64_smin(a->r64) >= -smax - 1 && cnum64_smax(a->r64) <= smax &&
+ 		cnum64_smin(b->r64) >= -smax - 1 && cnum64_smax(b->r64) <= smax);
+ }
  
- 	e = linked_regs_push(reg_set);
- 	if (e) {
- 		e->frameno = frameno;
- 		e->is_reg = is_reg;
- 		e->regno = spi_or_reg;
+ /*
+  * The values of @dst and @src are equal in their low @bits bits: @dst becomes the intersection.
+  * Fewer than 32 bits say nothing about a range. Returns false if the intersection is empty.
+  * Then no execution gets here with these values, and @dst does not change.
+  */
+ bool scalar_intersect(struct scalar *dst, const struct scalar *src, u32 bits)
+ {
+ 	struct tnum a = dst->var_off, b = src->var_off;
+ 	struct scalar s = *dst;
+ 
+ 	if (scalars_fit_in_bits(dst, src, bits))
+ 		bits = 64;
+ 	if (bits < 64)
+ 		b = tnum_or(tnum_cast(b, bits / BITS_PER_BYTE), tnum_lshift(tnum_unknown, bits));
+ 	/* tnum_intersect() of two tnums that don't overlap is not empty */
+ 	if (!tnum_overlap(a, b))
+ 		return false;
+ 	s.var_off = tnum_intersect(a, b);
+ 	/*
+ 	 * Equal in 64 bits is equal in the low 32 bits too. 'if w1 s> 200' on a zero extended int
+ 	 * refines nothing but the 32-bit range.
+ 	 */
+ 	if (bits >= 32)
+ 		s.r32 = cnum32_intersect(dst->r32, src->r32);
+ 	if (bits == 64) {
+ 		s.r64 = cnum64_intersect(dst->r64, src->r64);
+ 		if (src->step % dst->step == 0) {
+ 			if (src->base % dst->step != dst->base)
+ 				return false;
+ 			s.step = src->step;
+ 			s.base = src->base;
+ 		}
+ 		s.r64 = cnum64_intersect_linear(s.r64, s.base, s.step);
+ 	}
+ 	scalar_bounds_sync(&s);
+ 	if (scalar_is_empty(&s) || const_tnum_range_mismatch(&s) ||
+ 	    const_tnum_range_mismatch_32(&s))
+ 		return false;
+ 	*dst = s;
+ 	return true;
+ }
+ 
+ /*
+  * One branch of the jump @insn is dead, the current state takes the other one. @reg1 and @reg2 are
+  * the operands as that branch refines them. They hold every value that takes it, whether the other
+  * branch is dead or not.
+  */
+ static int refine_live_branch(struct bpf_verifier_env *env, struct bpf_insn *insn,
+ 			      struct bpf_reg_state *reg1, struct bpf_reg_state *reg2)
+ {
+ 	struct bpf_reg_state *regs = cur_regs(env);
+ 	bool empty;
+ 	int err;
+ 
+ 	/* is_branch_taken() knew the branch before it refined anything */
+ 	if (reg_value_equal(reg1, &regs[insn->dst_reg]) &&
+ 	    (BPF_SRC(insn->code) == BPF_K || reg_value_equal(reg2, &regs[insn->src_reg])))
+ 		return 0;
+ 	/*
+ 	 * The fall-through branch of JSET forgets the ranges. Or this branch is dead too: the path
+ 	 * is infeasible. The registers are left as they are.
+ 	 */
+ 	empty = reg_is_empty(reg1) || reg_is_empty(reg2);
+ 	env->cur_state->infeasible |= empty;
+ 	if (BPF_OP(insn->code) == BPF_JSET || empty)
+ 		return 0;
+ 	err = reg_bounds_sanity_check(env, reg1, "live_reg1");
+ 	err = err ?: reg_bounds_sanity_check(env, reg2, "live_reg2");
+ 	if (err)
+ 		return err;
+ 
+ 	regs[insn->dst_reg] = *reg1;
+ 	if (BPF_SRC(insn->code) == BPF_X)
+ 		regs[insn->src_reg] = *reg2;
+ 	return 0;
+ }
+ 
+ /* How many values of @reg are before the end of the order of @insn? 0 if all of them are. */
+ static u64 values_to_end(const struct bpf_insn *insn, const struct bpf_reg_state *reg)
+ {
+ 	u8 op = BPF_OP(insn->code);
+ 	bool sign = op == BPF_JSGT || op == BPF_JSGE || op == BPF_JSLT || op == BPF_JSLE;
+ 	u64 first = sign ? S64_MIN : 0;
+ 	u32 cnt32 = (first >> 32) - reg->r32.base;
+ 	u64 cnt = first - reg->r64.base;
+ 
+ 	if (BPF_CLASS(insn->code) == BPF_JMP32)
+ 		return cnt32 <= reg->r32.size && reg->r32.size != U32_MAX ? cnt32 : 0;
+ 	return cnt <= reg->r64.size && reg->r64.size != U64_MAX ? cnt : 0;
+ }
+ 
+ /*
+  * A jump can cut a range in two: 'x u>= 3' leaves -4..-1 and 3 of -4..3. One range has both and
+  * all values between them. So a state that knows less is proven where this one is not.
+  * Do the jump for the values before the end of the order, then again for the values after it.
+  * Returns 1 if the current state has fewer values now.
+  */
+ static int cut_range(struct bpf_verifier_env *env, const struct bpf_insn *insn, u32 regno,
+ 		     const struct bpf_reg_state *taken, const struct bpf_reg_state *not_taken)
+ {
+ 	struct bpf_verifier_state *st = env->cur_state, *other;
+ 	struct bpf_reg_state *reg = &cur_regs(env)[regno], front = *reg, back = *reg;
+ 	u64 cnt = values_to_end(insn, reg);
+ 	u8 op = BPF_OP(insn->code);
+ 	const struct bpf_reg_state *equal = op == BPF_JEQ ? taken : not_taken;
+ 
+ 	/* 'x != 0' is 'x u> 0' */
+ 	if ((op == BPF_JEQ || op == BPF_JNE) && !tnum_equals_const(tnum_subreg(equal->var_off), 0))
+ 		return 0;
+ 	if (op == BPF_JSET || reg->type != SCALAR_VALUE || !cnt ||
+ 	    !(values_to_end(insn, taken) || values_to_end(insn, not_taken)))
+ 		return 0;
+ 	env->imprecise |= !env->err;
+ 	if (!env->path_sensitive && !bpf_xreg_in_deps(env, st, st->curframe, regno))
+ 		return 0;
+ 	if (BPF_CLASS(insn->code) == BPF_JMP32) {
+ 		front.r32.size = cnt - 1;
+ 		back.r32.base += cnt;
+ 		back.r32.size -= cnt;
  	} else {
- 		clear_scalar_id(reg);
- 	}
- }
- 
- /* For all R being scalar registers or spilled scalar registers
-  * in verifier state, save R in linked_regs if R->id == id.
-  * If there are too many Rs sharing same id, reset id for leftover Rs.
-  */
- static void collect_linked_regs(struct bpf_verifier_env *env,
- 				struct bpf_verifier_state *vstate,
- 				u32 id,
- 				struct linked_regs *linked_regs)
- {
- 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
- 	struct bpf_func_state *func;
- 	struct bpf_reg_state *reg;
- 	u16 live_regs;
- 	int i, j;
- 
- 	id = id & ~BPF_ADD_CONST;
- 	for (i = vstate->curframe; i >= 0; i--) {
- 		live_regs = aux[bpf_frame_insn_idx(vstate, i)].live_regs_before;
- 		func = vstate->frame[i];
- 		for (j = 0; j < BPF_REG_FP; j++) {
- 			if (!(live_regs & BIT(j)))
- 				continue;
- 			reg = &func->regs[j];
- 			__collect_linked_regs(linked_regs, reg, id, i, j, true);
- 		}
- 		for (j = 0; j < bpf_stack_nr_slots(func); j++) {
- 			struct bpf_stack_state *ss = bpf_stack_slot(func, j);
- 
- 			if (!bpf_is_spilled_reg(ss))
- 				continue;
- 			reg = &ss->spilled_ptr;
- 			__collect_linked_regs(linked_regs, reg, id, i, j, false);
- 		}
- 	}
- }
- 
- /* For all R in linked_regs, copy known_reg range into R
-  * if R->id == known_reg->id.
-  */
- static void sync_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate,
- 			     struct bpf_reg_state *known_reg, struct linked_regs *linked_regs)
- {
- 	struct bpf_reg_state fake_reg;
- 	struct bpf_reg_state *reg;
- 	struct linked_reg *e;
- 	int i;
- 
- 	for (i = 0; i < linked_regs->cnt; ++i) {
- 		e = &linked_regs->entries[i];
- 		reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
- 				: &bpf_stack_slot(vstate->frame[e->frameno], e->spi)->spilled_ptr;
- 		if (reg->type != SCALAR_VALUE || reg == known_reg)
- 			continue;
- 		if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
- 			continue;
- 		/*
- 		 * Skip mixed 32/64-bit links: the delta relationship doesn't
- 		 * hold across different ALU widths.
- 		 */
- 		if (((reg->id ^ known_reg->id) & BPF_ADD_CONST) == BPF_ADD_CONST)
- 			continue;
- 		if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
- 		    reg->delta == known_reg->delta) {
- 			*reg = *known_reg;
- 		} else {
- 			s32 saved_off = reg->delta;
- 			u32 saved_id = reg->id;
- 
- 			fake_reg.type = SCALAR_VALUE;
- 			__mark_reg_known(&fake_reg, (s64)reg->delta - (s64)known_reg->delta);
- 
- 			/* reg = known_reg; reg += delta */
- 			*reg = *known_reg;
- 			/*
- 			 * Must preserve off and id, otherwise another sync_linked_regs()
- 			 * will be incorrect.
- 			 */
- 			reg->delta = saved_off;
- 			reg->id = saved_id;
- 
- 			scalar_step_add(reg, reg, &fake_reg);
- 			scalar32_min_max_add(reg, &fake_reg);
- 			scalar_min_max_add(reg, &fake_reg);
- 			reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
- 			if ((reg->id | known_reg->id) & BPF_ADD_CONST32)
- 				zext_32_to_64(reg);
- 			reg_bounds_sync(reg);
- 		}
- 		if (e->is_reg)
- 			mark_reg_scratched(env, e->regno);
- 		else
- 			mark_stack_slot_scratched(env, e->spi);
+ 		front.r64.size = cnt - 1;
+ 		back.r64.base += cnt;
+ 		back.r64.size -= cnt;
  	}
+ 	reg_bounds_sync(&front);
+ 	reg_bounds_sync(&back);
+ 	if (reg_is_empty(&front) || reg_is_empty(&back))
+ 		return 0;
+ 	other = push_stack(env, env->insn_idx, env->insn_idx, false);
+ 	if (IS_ERR(other))
+ 		return PTR_ERR(other);
+ 	env->head->again = true;
+ 	other->frame[other->curframe]->regs[regno] = back;
+ 	*reg = front;
+ 	return 1;
  }
  
  static int check_cond_jmp_op(struct bpf_verifier_env *env,
  			     struct bpf_insn *insn, int *insn_idx)
  {
+ 	struct cnum64 near = cnum64_from_srange(-MAX_PACKET_OFF, 2 * MAX_PACKET_OFF);
  	struct bpf_verifier_state *this_branch = env->cur_state;
  	struct bpf_verifier_state *other_branch;
  	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
  	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
  	struct bpf_reg_state *eq_branch_regs;
- 	struct linked_regs linked_regs = {};
  	u8 opcode = BPF_OP(insn->code);
- 	int insn_flags = 0;
  	bool is_jmp32;
  	int pred = -1;
  	int err;
@@@ -18982,19 -19300,14 +19312,14 @@@
  	}
  
  	if (opcode == BPF_JCOND) {
- 		struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
+ 		struct bpf_verifier_state *queued_st;
  		int idx = *insn_idx;
  
- 		prev_st = find_prev_entry(env, cur_st->parent, idx);
- 
  		/* branch out 'fallthrough' insn as a new state to explore */
  		queued_st = push_stack(env, idx + 1, idx, false);
  		if (IS_ERR(queued_st))
  			return PTR_ERR(queued_st);
  
- 		queued_st->may_goto_depth++;
- 		if (prev_st)
- 			widen_imprecise_scalars(env, prev_st, queued_st);
  		*insn_idx += insn->off;
  		return 0;
  	}
@@@ -19012,62 -19325,31 +19337,31 @@@
  			return err;
  
  		src_reg = &regs[insn->src_reg];
- 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
+ 		/* A header and a 16-bit length fit. If a pointer wraps, it leaks the address. */
+ 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg) &&
+ 		      cnum64_is_subset(near, dst_reg->r64) &&
+ 		      cnum64_is_subset(near, src_reg->r64)) &&
  		    is_pointer_value(env, insn->src_reg)) {
  			verbose(env, "R%d pointer comparison prohibited\n",
  				insn->src_reg);
  			return -EACCES;
  		}
  
- 		if (src_reg->type == PTR_TO_STACK)
- 			insn_flags |= INSN_F_SRC_REG_STACK;
- 		if (dst_reg->type == PTR_TO_STACK)
- 			insn_flags |= INSN_F_DST_REG_STACK;
  	} else {
  		src_reg = &env->fake_reg[0];
  		memset(src_reg, 0, sizeof(*src_reg));
  		src_reg->type = SCALAR_VALUE;
  		__mark_reg_known(src_reg, insn->imm);
- 
- 		if (dst_reg->type == PTR_TO_STACK)
- 			insn_flags |= INSN_F_DST_REG_STACK;
  	}
  
- 	if (insn_flags) {
- 		err = bpf_push_jmp_history(env, this_branch, insn_flags, 0, 0, NULL, 0);
- 		if (err)
- 			return err;
- 	}
- 
- 	/*
- 	 * Collect the linked registers before env->{true,false}_reg{1,2} setup,
- 	 * otherwise ids dropped by collect_linked_regs() would be resurrected
- 	 * when env->{true,false}_reg{1,2} are copied back.
- 	 */
- 	if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
- 		collect_linked_regs(env, this_branch, src_reg->id, &linked_regs);
- 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
- 		collect_linked_regs(env, this_branch, dst_reg->id, &linked_regs);
- 
  	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
+ again:
  	env->false_reg1 = *dst_reg;
  	env->false_reg2 = *src_reg;
  	env->true_reg1 = *dst_reg;
  	env->true_reg2 = *src_reg;
+ 	bpf_collect_iv_thresholds(env);
  	pred = is_branch_taken(env, dst_reg, src_reg, opcode, is_jmp32);
- 	if (pred >= 0) {
- 		/* If we get here with a dst_reg pointer type it is because
- 		 * above is_branch_taken() special cased the 0 comparison.
- 		 */
- 		if (!__is_pointer_value(false, dst_reg))
- 			err = mark_chain_precision(env, insn->dst_reg);
- 		if (BPF_SRC(insn->code) == BPF_X && !err &&
- 		    !__is_pointer_value(false, src_reg))
- 			err = mark_chain_precision(env, insn->src_reg);
- 		if (err)
- 			return err;
- 	}
- 
  	if (pred == 1) {
  		/* Only follow the goto, ignore fall-through. If needed, push
  		 * the fall-through branch for simulation under speculative
@@@ -19078,6 -19360,10 +19372,10 @@@
  			if (err < 0)
  				return err;
  		}
+ 		err = refine_live_branch(env, insn, &env->true_reg1, &env->true_reg2);
+ 		if (err)
+ 			return err;
+ 		bpf_equations_jump(env, this_branch, *insn_idx, true);
  		if (env->log.level & BPF_LOG_LEVEL)
  			print_insn_state(env, this_branch, this_branch->curframe);
  		*insn_idx += insn->off;
@@@ -19093,24 -19379,22 +19391,22 @@@
  			if (err < 0)
  				return err;
  		}
+ 		err = refine_live_branch(env, insn, &env->false_reg1, &env->false_reg2);
+ 		if (err)
+ 			return err;
+ 		bpf_equations_jump(env, this_branch, *insn_idx, false);
  		if (env->log.level & BPF_LOG_LEVEL)
  			print_insn_state(env, this_branch, this_branch->curframe);
  		return 0;
  	}
  
- 	/* Push scalar registers sharing same ID to jump history,
- 	 * do this before creating 'other_branch', so that both
- 	 * 'this_branch' and 'other_branch' share this history
- 	 * if parent state is created.
- 	 */
- 	if (linked_regs.cnt > 1) {
- 		u16 packed[LINKED_REGS_MAX];
- 
- 		linked_regs_pack(&linked_regs, packed);
- 		err = bpf_push_jmp_history(env, this_branch, 0, 0, 0, packed, linked_regs.cnt);
- 		if (err)
- 			return err;
- 	}
+ 	err = cut_range(env, insn, insn->dst_reg, &env->true_reg1, &env->false_reg1);
+ 	if (!err && BPF_SRC(insn->code) == BPF_X)
+ 		err = cut_range(env, insn, insn->src_reg, &env->true_reg2, &env->false_reg2);
+ 	if (err > 0)
+ 		goto again;
+ 	if (err)
+ 		return err;
  
  	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false);
  	if (IS_ERR(other_branch))
@@@ -19127,20 -19411,6 +19423,6 @@@
  	if (BPF_SRC(insn->code) == BPF_X)
  		other_branch_regs[insn->src_reg] = env->true_reg2;
  
- 	if (BPF_SRC(insn->code) == BPF_X &&
- 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
- 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
- 		sync_linked_regs(env, this_branch, src_reg, &linked_regs);
- 		sync_linked_regs(env, other_branch, &other_branch_regs[insn->src_reg],
- 				 &linked_regs);
- 	}
- 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
- 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
- 		sync_linked_regs(env, this_branch, dst_reg, &linked_regs);
- 		sync_linked_regs(env, other_branch, &other_branch_regs[insn->dst_reg],
- 				 &linked_regs);
- 	}
- 
  	/* if one pointer register is compared to another pointer
  	 * register check if PTR_MAYBE_NULL could be lifted.
  	 * E.g. register A - maybe null
@@@ -19189,15 -19459,6 +19471,6 @@@
  	    type_may_be_null(dst_reg->type) &&
  	    ((BPF_SRC(insn->code) == BPF_K && insn->imm == 0) ||
  	     (BPF_SRC(insn->code) == BPF_X && bpf_register_is_null(src_reg)))) {
- 		/*
- 		 * For BPF_X the zero is a property of this execution path,
- 		 * hence src_reg has to be precise.
- 		 */
- 		if (BPF_SRC(insn->code) == BPF_X) {
- 			err = mark_chain_precision(env, insn->src_reg);
- 			if (err)
- 				return err;
- 		}
  		/* Mark all identical registers in each branch as either
  		 * safe or unknown depending R == 0 or R != 0 conditional.
  		 */
@@@ -19212,6 -19473,9 +19485,9 @@@
  			insn->dst_reg);
  		return -EACCES;
  	}
+ 	/* last: the code above takes the operands of one branch for both */
+ 	bpf_equations_jump(env, this_branch, *insn_idx, false);
+ 	bpf_equations_jump(env, other_branch, *insn_idx, true);
  	if (env->log.level & BPF_LOG_LEVEL)
  		print_insn_state(env, this_branch, this_branch->curframe);
  	return 0;
@@@ -19304,8 -19568,7 +19580,7 @@@ static int check_ld_imm(struct bpf_veri
  	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
  	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
  		if (map->map_type == BPF_MAP_TYPE_ARENA) {
- 			__mark_reg_unknown(env, dst_reg);
- 			dst_reg->map_ptr = map;
+ 			bpf_mark_reg_unknown(dst_reg);
  			bpf_diag_mod_end(env);
  			return 0;
  		}
@@@ -19587,6 -19850,64 +19862,64 @@@ static bool program_returns_void(struc
  	return false;
  }
  
+ static bool fmodret_retval_allowed(const char *list, s64 value)
+ {
+ 	char *end;
+ 
+ 	if (!value)
+ 		return true;
+ 	for (; *list; list = *end ? end + 1 : end) {
+ 		if (simple_strtoll(list, &end, 10) == value)
+ 			return true;
+ 	}
+ 	return false;
+ }
+ 
+ /*
+  * The build tags the functions which return errors: "bpf_fmodret_retval:-22,-12",
+  * see tools/bpf/resolve_btfids/fmodret.c. An fmod_ret program can attach to such
+  * a function. A caller can get each of these errors today: the function returns
+  * them itself. So the program must return one of them, or 0 to call the function.
+  */
+ static int check_fmodret_retval(struct bpf_verifier_env *env, int regno,
+ 				const char *exit_ctx, const char *reg_name)
+ {
+ 	const struct bpf_prog_aux *aux = env->prog->aux;
+ 	struct bpf_reg_state *reg = reg_state(env, regno);
+ 	s64 smin = reg_smin(reg), smax = reg_smax(reg), v;
+ 	const struct btf_type *t;
+ 
+ 	if (reg->type != SCALAR_VALUE) {
+ 		verbose(env, "%s the register %s is not a known value (%s)\n",
+ 			exit_ctx, reg_name, reg_type_str(env, reg->type));
+ 		return -EINVAL;
+ 	}
+ 
+ 	/*
+ 	 * "w0 = -22" zero-extends. The trampoline sign-extends the low 32 bits of
+ 	 * the value for an int function, so its caller sees -22. The low 32 bits
+ 	 * decide if the high ones are 0. Else the 64 bits have to be in the list.
+ 	 *
+ 	 * The trampolines of x86-64, arm64 and s390x do that: look here before
+ 	 * another architecture is added to CONFIG_BPF_FMODRET_SCAN.
+ 	 */
+ 	t = btf_type_skip_modifiers(aux->attach_btf, aux->attach_func_proto->type, NULL);
+ 	if (t->size == 4 && reg_umax(reg) <= U32_MAX) {
+ 		smin = reg_s32_min(reg);
+ 		smax = reg_s32_max(reg);
+ 	}
+ 
+ 	/* Stops at the first value which is not in the list, however wide the range is */
+ 	for (v = smin; v <= smax; v++) {
+ 		if (!fmodret_retval_allowed(env->fmodret_retvals, v)) {
+ 			verbose(env, "%s the register %s should be 0 or one of %s\n",
+ 				exit_ctx, reg_name, env->fmodret_retvals);
+ 			return -EINVAL;
+ 		}
+ 	}
+ 	return 0;
+ }
+ 
  static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
  {
  	const char *exit_ctx = "At program exit";
@@@ -19608,8 -19929,7 +19941,8 @@@
  		 * matches the operator's return type and is in its unmodified
  		 * form. A scalar zero (i.e., a null pointer) is also allowed.
  		 */
 -		reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL;
 +		reg_type = base_type(reg->type) == PTR_TO_BTF_ID ?
 +			   btf_type_by_id(reg->btf, reg->btf_id) : NULL;
  		ret_type = btf_type_resolve_ptr(prog->aux->attach_btf,
  						prog->aux->attach_func_proto->type,
  						NULL);
@@@ -19644,6 -19964,9 +19977,9 @@@
  	if (prog_type == BPF_PROG_TYPE_CGROUP_SKB && (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS))
  		enforce_attach_type_range = tnum_range(2, 3);
  
+ 	if (env->fmodret_retvals)
+ 		return check_fmodret_retval(env, regno, exit_ctx, reg_name);
+ 
  	if (!return_retval_range(env, &range))
  		return 0;
  
@@@ -19654,10 -19977,6 +19990,6 @@@ enforce_retval
  		return -EINVAL;
  	}
  
- 	err = mark_chain_precision(env, regno);
- 	if (err)
- 		return err;
- 
  	if (!retval_range_within(range, reg)) {
  		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
  		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
@@@ -19668,7 -19987,7 +20000,7 @@@
  	}
  
  	if (!tnum_is_unknown(enforce_attach_type_range) &&
- 	    tnum_in(enforce_attach_type_range, reg->var_off))
+ 	    reg_smax(reg) > 1)
  		env->prog->enforce_expected_attach_type = 1;
  	return 0;
  }
@@@ -19763,10 -20082,12 +20095,12 @@@ bool bpf_get_call_summary(struct bpf_ve
  				bpf_jit_inlines_helper_call(call->imm));
  		cs->is_void = fn->ret_type == RET_VOID;
  		cs->arg_slot_cnt = 0;
+ 		cs->implicit_slot_cnt = 0;
  		for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) {
  			if (fn->arg_type[i] == ARG_UNUSED)
  				break;
  			cs->arg_slot_cnt++;
+ 			cs->implicit_slot_cnt += fn->arg_type[i] == ARG_PTR_TO_PROG_AUX;
  		}
  		return true;
  	}
@@@ -19779,6 -20100,14 +20113,14 @@@
  			/* error would be reported later */
  			return false;
  		cs->arg_slot_cnt = btf_proto_slots(meta.btf, meta.func_proto);
+ 		cs->implicit_slot_cnt = 0;
+ 		if (meta.kfunc_flags & KF_IMPLICIT_ARGS) {
+ 			const struct btf_type *func = btf_type_by_id(meta.btf, meta.func_id);
+ 
+ 			/* the prototype without implicit args, see is_kfunc_arg_implicit() */
+ 			cs->implicit_slot_cnt = cs->arg_slot_cnt -
+ 				btf_proto_slots(meta.btf, btf_type_by_id(meta.btf, func->type));
+ 		}
  		cs->fastcall = meta.kfunc_flags & KF_FASTCALL;
  		cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type));
  		return true;
@@@ -19953,11 -20282,7 +20295,11 @@@ static void mark_fastcall_pattern_for_c
  		env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1;
  	else
  		subprog->keep_fastcall_stack = 1;
 -	subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off);
 +	/*
 +	 * The upper end of the longest pattern: no slot of a pattern is above it. Code that never
 +	 * runs may have a pattern that ends above the frame pointer.
 +	 */
 +	subprog->fastcall_stack_off = max(subprog->fastcall_stack_off, min_t(s16, off, 0));
  }
  
  static int mark_fastcall_patterns(struct bpf_verifier_env *env)
@@@ -19968,7 -20293,6 +20310,7 @@@
  	int s, i;
  
  	for (s = 0; s < env->subprog_cnt; ++s, ++subprog) {
 +		subprog->fastcall_stack_off = S16_MIN;
  		/* find lowest stack spill offset used in this subprog */
  		lowest_off = 0;
  		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
@@@ -20002,69 -20326,6 +20344,6 @@@ static void adjust_btf_func(struct bpf_
  		aux->func_info[i].insn_off = env->subprog_info[i].start;
  }
  
- /* Find id in idset and increment its count, or add new entry */
- static void idset_cnt_inc(struct bpf_idset *idset, u32 id)
- {
- 	u32 i;
- 
- 	for (i = 0; i < idset->num_ids; i++) {
- 		if (idset->entries[i].id == id) {
- 			idset->entries[i].cnt++;
- 			return;
- 		}
- 	}
- 	/* New id */
- 	if (idset->num_ids < BPF_ID_MAP_SIZE) {
- 		idset->entries[idset->num_ids].id = id;
- 		idset->entries[idset->num_ids].cnt = 1;
- 		idset->num_ids++;
- 	}
- }
- 
- /* Find id in idset and return its count, or 0 if not found */
- static u32 idset_cnt_get(struct bpf_idset *idset, u32 id)
- {
- 	u32 i;
- 
- 	for (i = 0; i < idset->num_ids; i++) {
- 		if (idset->entries[i].id == id)
- 			return idset->entries[i].cnt;
- 	}
- 	return 0;
- }
- 
- /*
-  * Clear singular scalar ids in a state.
-  * A register with a non-zero id is called singular if no other register shares
-  * the same base id. Such registers can be treated as independent (id=0).
-  */
- void bpf_clear_singular_ids(struct bpf_verifier_env *env,
- 			    struct bpf_verifier_state *st)
- {
- 	struct bpf_idset *idset = &env->idset_scratch;
- 	struct bpf_func_state *func;
- 	struct bpf_reg_state *reg;
- 
- 	idset->num_ids = 0;
- 
- 	bpf_for_each_reg_in_vstate(st, func, reg, ({
- 		if (reg->type != SCALAR_VALUE)
- 			continue;
- 		if (!reg->id)
- 			continue;
- 		idset_cnt_inc(idset, reg->id & ~BPF_ADD_CONST);
- 	}));
- 
- 	bpf_for_each_reg_in_vstate(st, func, reg, ({
- 		if (reg->type != SCALAR_VALUE)
- 			continue;
- 		if (!reg->id)
- 			continue;
- 		if (idset_cnt_get(idset, reg->id & ~BPF_ADD_CONST) == 1)
- 			clear_scalar_id(reg);
- 	}));
- }
- 
  /* Return true if it's OK to have the same insn return a different type. */
  static bool reg_type_mismatch_ok(enum bpf_reg_type type)
  {
@@@ -20152,18 -20413,13 +20431,13 @@@ static int save_aux_ptr_type(struct bpf
  			 */
  			*prev_type = merge_ptr_types(type, *prev_type);
  		} else {
- 			verbose(env, "same insn cannot be used with different pointers\n");
- 			return -EINVAL;
+ 			return fixups_differ(env, "same insn cannot be used with different pointers");
  		}
  	}
  
  	return 0;
  }
  
- enum {
- 	PROCESS_BPF_EXIT = 1,
- 	INSN_IDX_UPDATED = 2,
- };
  
  static int process_bpf_exit_full(struct bpf_verifier_env *env,
  				 bool *do_print_state,
@@@ -20171,6 -20427,9 +20445,9 @@@
  {
  	struct bpf_func_state *cur_frame = cur_func(env);
  
+ 	if (!exception_exit && !env->cur_state->curframe && env->cur_state->instance_id)
+ 		return exit_func_on_its_own(env);
+ 
  	/* We must do check_reference_leak here before
  	 * prepare_func_exit to handle the case when
  	 * state->curframe > 0, it may be a callback function,
@@@ -20187,8 -20446,8 +20464,8 @@@
  	/* The side effect of the prepare_func_exit which is
  	 * being skipped is that it frees bpf_func_state.
  	 * Typically, process_bpf_exit will only be hit with
- 	 * outermost exit. copy_verifier_state in pop_stack will
- 	 * handle freeing of any extra bpf_func_state left over
+ 	 * outermost exit. do_check_block() frees the state with
+ 	 * any extra bpf_func_state left over
  	 * from not processing all nested function exits. We
  	 * also skip return code checks as they are not needed
  	 * for exceptional exits.
@@@ -20300,6 -20559,11 +20577,11 @@@ static int check_indirect_jump(struct b
  		return -EFAULT;
  
  	err = indirect_jump_min_max_index(env, insn->dst_reg, map, &min_index, &max_index);
+ 	if (err)
+ 		return err;
+ 	/* the targets are sorted */
+ 	n = max_index - min_index + 1;
+ 	err = bpf_add_cost_and_check(env, (u64)n * ilog2(n), BPF_COST_COPY);
  	if (err)
  		return err;
  
@@@ -20334,6 -20598,11 +20616,11 @@@
  	if (env->gotox_tmp_buf->items[0] < subprog_start)
  		return reject_gotox_out_of_subprog(env, env->gotox_tmp_buf->items[0],
  						   subprog_start, subprog_end);
+ 	/* it's the first insn of a function, it would be executed again */
+ 	if (is_arena_sp_adj(&env->prog->insnsi[env->gotox_tmp_buf->items[0]])) {
+ 		verbose(env, "jump to the insn that changes R%d\n", BPF_REG_ARENA_SP);
+ 		return -EINVAL;
+ 	}
  	if (env->gotox_tmp_buf->items[n - 1] >= subprog_end)
  		return reject_gotox_out_of_subprog(env, env->gotox_tmp_buf->items[n - 1],
  						   subprog_start, subprog_end);
@@@ -20350,12 -20619,64 +20637,64 @@@
  	return INSN_IDX_UPDATED;
  }
  
+ /*
+  * r12 is not in regs[]. Only the kernel and 'r12 += N' change it, so it points
+  * to the stack in arena. What is there is not tracked, like the rest of arena.
+  */
+ static int check_arena_sp_insn(struct bpf_verifier_env *env, struct bpf_insn *insn)
+ {
+ 	struct bpf_reg_state arena = { .type = PTR_TO_ARENA };
+ 	argno_t argno = argno_from_reg(BPF_REG_ARENA_SP);
+ 	struct bpf_reg_state *regs = cur_regs(env);
+ 	int size = BPF_SIZE(insn->code);
+ 	int err, value_regno = -1;
+ 
+ 	if (is_arena_sp_adj(insn))
+ 		return 0;
+ 
+ 	/* the address of the frame is a number */
+ 	if (is_arena_sp_mov(insn)) {
+ 		bpf_diag_mod_begin(env, &regs[insn->dst_reg], NULL, BPF_DIAG_MOD_WRITE);
+ 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
+ 		if (!err)
+ 			bpf_diag_mod_end(env);
+ 		return err;
+ 	}
+ 
+ 	if (is_arena_sp_ldx(insn)) {
+ 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
+ 		if (err)
+ 			return err;
+ 		bpf_diag_mod_begin(env, &regs[insn->dst_reg], NULL, BPF_DIAG_MOD_WRITE);
+ 		err = check_mem_access(env, env->insn_idx, &arena, argno, insn->off, size,
+ 				       BPF_READ, insn->dst_reg, false,
+ 				       BPF_MODE(insn->code) == BPF_MEMSX);
+ 		err = err ?: save_aux_ptr_type(env, PTR_TO_ARENA, false);
+ 		if (!err)
+ 			bpf_diag_mod_end(env);
+ 		return err;
+ 	}
+ 
+ 	if (BPF_CLASS(insn->code) == BPF_STX) {
+ 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
+ 		if (err)
+ 			return err;
+ 		value_regno = insn->src_reg;
+ 	}
+ 	err = check_mem_access(env, env->insn_idx, &arena, argno, insn->off, size,
+ 			       BPF_WRITE, value_regno, false, false);
+ 	return err ?: save_aux_ptr_type(env, PTR_TO_ARENA, false);
+ }
+ 
  static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
  {
- 	int err;
+ 	int err, i;
  	struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx];
  	u8 class = BPF_CLASS(insn->code);
  
+ 	if (is_arena_sp_insn(insn))
+ 		return check_arena_sp_insn(env, insn);
+ 
  	switch (class) {
  	case BPF_ALU:
  	case BPF_ALU64:
@@@ -20401,7 -20722,6 +20740,6 @@@
  	case BPF_JMP32: {
  		u8 opcode = BPF_OP(insn->code);
  
- 		env->jmps_processed++;
  		if (opcode == BPF_CALL) {
  			if (env->cur_state->active_locks) {
  				/* similar to static subprog calls callx is allowed under a lock */
@@@ -20422,11 -20742,20 +20760,20 @@@
  			}
  			mark_reg_scratched(env, BPF_REG_0);
  			if (bpf_in_stack_arg_cnt(&env->subprog_info[cur_func(env)->subprogno]))
- 				cur_func(env)->no_stack_arg_load = true;
+ 				end_stack_arg_loads(env, cur_func(env));
+ 			/* func_is_on_its_own() uses the names of the ids */
  			if (bpf_is_callx(insn))
- 				return check_func_callx(env, insn, &env->insn_idx);
+ 				return bpf_renumber_ids(env, env->cur_state) ?:
+ 				       check_func_callx(env, insn, &env->insn_idx);
  			if (insn->src_reg == BPF_PSEUDO_CALL)
- 				return check_func_call(env, insn, &env->insn_idx);
+ 				return bpf_renumber_ids(env, env->cur_state) ?:
+ 				       check_func_call(env, insn, &env->insn_idx);
+ 			/* a callback is one function */
+ 			for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
+ 				err = split_func_set(env, i);
+ 				if (err)
+ 					return err;
+ 			}
  			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
  				return check_kfunc_call(env, insn, &env->insn_idx);
  			return check_helper_call(env, insn, &env->insn_idx);
@@@ -20465,6 -20794,106 +20812,106 @@@
  	return -EFAULT;
  }
  
+ /* Does the insn read what an unproven insn made up? Then what it writes is made up too. */
+ static bool reads_from_unproven(struct bpf_verifier_env *env)
+ {
+ 	struct bpf_reg_state *regs = cur_regs(env);
+ 	int i;
+ 
+ 	for (i = BPF_REG_0; env->err && i < BPF_REG_FP; i++)
+ 		if ((cur_aux(env)->use_regs & BIT(i)) && regs[i].from_unproven)
+ 			return true;
+ 	return false;
+ }
+ 
+ /* The operands of @insn that have more than one value, without the number that is stored */
+ static unsigned long operands_with_range(struct bpf_verifier_env *env, const struct bpf_insn *insn)
+ {
+ 	unsigned long use = cur_aux(env)->use_regs & GENMASK(BPF_REG_9, BPF_REG_0), ranges = 0;
+ 	struct bpf_reg_state *regs = cur_regs(env);
+ 	int i;
+ 
+ 	if (BPF_CLASS(insn->code) == BPF_STX && !bpf_atomic_is_load_acq(insn))
+ 		use &= BIT(insn->dst_reg);
+ 	for_each_set_bit(i, &use, BPF_REG_FP)
+ 		if (regs[i].r64.size)
+ 			ranges |= BIT(i);
+ 	return ranges;
+ }
+ 
+ static void mark_from_unproven(struct bpf_verifier_env *env, int idx, bool from_unproven)
+ {
+ 	struct bpf_reg_state *regs = cur_regs(env);
+ 	int i;
+ 
+ 	/* a fill has what was spilled */
+ 	if (!from_unproven && BPF_CLASS(env->prog->insnsi[idx].code) == BPF_LDX)
+ 		return;
+ 	for (i = BPF_REG_0; env->err && i < BPF_REG_FP; i++)
+ 		if (env->insn_aux_data[idx].def_regs & BIT(i))
+ 			regs[i].from_unproven = from_unproven;
+ }
+ 
+ static void note_error(struct bpf_verifier_env *env, int err);
+ 
+ static u32 held_cnt(const struct bpf_verifier_state *st)
+ {
+ 	return st->acquired_refs + st->active_rcu_locks + st->active_preempt_locks;
+ }
+ 
+ /* The current state enters @loop in @frame. It is in trip 0. */
+ static struct loop_stack_entry *push_loop(struct bpf_verifier_env *env,
+ 					  struct bpf_func_state *frame, struct bpf_loop *loop)
+ {
+ 	u32 cnt = frame->loop_stack_cnt;
+ 	struct loop_stack_entry *stack;
+ 
+ 	stack = krealloc(frame->loop_stack, kmalloc_size_roundup((cnt + 1) * sizeof(*stack)),
+ 			 BPF_VERIFIER_GFP);
+ 	if (!stack)
+ 		return NULL;
+ 	frame->loop_stack = stack;
+ 	stack[cnt] = (struct loop_stack_entry){
+ 		.loop = loop,
+ 		.held_cnt = held_cnt(env->cur_state),
+ 		.entry_id = ++env->loop_entry_cnt,
+ 		.peeled = true,
+ 		.exit_threshold = U64_MAX,
+ 	};
+ 	scalar_set_const(&frame->loop_stack[cnt].trip_index, 0);
+ 	frame->loop_stack_cnt++;
+ 	return &frame->loop_stack[cnt];
+ }
+ 
+ static bool try_peel_trip(const struct loop_stack_entry *entry)
+ {
+ 	struct bpf_loop *loop = entry->loop;
+ 
+ 	if (entry->trip >= loop->peel_cnt &&
+ 	    (entry->trip >= loop->max_peel_cnt || !bpf_loop_partition_is_active(loop)))
+ 		return false;
+ 	loop->this_pass.peeled_cnt = max(loop->this_pass.peeled_cnt, entry->trip + 1);
+ 	return true;
+ }
+ 
+ /* The loop of @entry starts its leftover. Nothing grew in it so far. */
+ static void leave_peeled_trips(struct bpf_verifier_env *env, struct loop_stack_entry *entry)
+ {
+ 	struct bpf_func_state *frame;
+ 	struct bpf_reg_state *reg;
+ 	u32 i;
+ 
+ 	entry->peeled = false;
+ 	entry->loop->this_pass.has_leftover = true;
+ 	entry->loop->leftover_epoch++;
+ 	/* the leftover of the last pass had no trip count */
+ 	entry->loop->guarded |= entry->loop->last_pass.needs_guard && !env->cur_state->speculative;
+ 	entry->trip_index.grew_once = entry->trip_widened = false;
+ 	bpf_for_each_reg_in_vstate(env->cur_state, frame, reg, reg->grew_once = false);
+ 	for (i = 0; i < env->cur_state->equations.sym_cnt; i++)
+ 		env->cur_state->equations.syms[i].grew_once = false;
+ }
+ 
  /*
   * Push the loop entered at insn_idx onto the stack. Usually this adds a single
   * entry on top of its enclosing loop. However, an edge may enter an inner loop
@@@ -20478,8 -20907,6 +20925,6 @@@
   *
   * Such a bypass makes the enclosing loop irreducible, so its header is missing
   * from the stack and both headers (1) and (2) need to be pushed onto stack.
-  * Only the innermost loop (the one actually entered at insn_idx) carries SCEV bounds;
-  * the bypassed ancestors are irreducible and pushed as non-terminating.
   *
   * Assumes loop_stack_pop() has already truncated the stack to the common ancestor
   * of the bpf_loop_at_index(env->insn_idx) and whatever was at the top of the loop stack.
@@@ -20488,45 -20915,33 +20933,33 @@@ static int loop_stack_push(struct bpf_v
  {
  	struct bpf_insn_aux_data *aux = env->insn_aux_data;
  	struct bpf_func_state *frame = cur_func(env);
- 	struct loop_stack_entry *loop_stack = frame->loop_stack;
+ 	struct loop_stack_entry *entry = bpf_top_loop(frame);
  	u32 missing_headers[LOOP_STACK_SIZE];
- 	u32 cnt = frame->loop_stack_cnt;
  	u32 num_missing = 0;
  	int h;
  
- 	*pushed = false;
+ 	/* bpf_compute_loops() checked how deep loops nest */
+ 	for (h = bpf_loop_at_index(env, env->insn_idx);
+ 	     h >= 0 && !(entry && entry->loop == aux[h].loop); h = aux[h].loop_header)
+ 		missing_headers[num_missing++] = h;
  
- 	for (h = bpf_loop_at_index(env, env->insn_idx); h >= 0; h = aux[h].loop_header, num_missing++) {
- 		if (cnt && loop_stack[cnt - 1].loop_id == h)
- 			break;
- 		if (num_missing == LOOP_STACK_SIZE)
- 			goto e2big;
- 		missing_headers[num_missing] = h;
- 	}
- 
- 	if (num_missing == 0)
- 		return 0;
- 	if (cnt + num_missing > LOOP_STACK_SIZE)
- 		goto e2big;
- 	frame->loop_stack = realloc_array(frame->loop_stack, cnt, cnt + num_missing,
- 					 sizeof(*frame->loop_stack));
- 	if (!frame->loop_stack)
- 		return -ENOMEM;
- 	loop_stack = frame->loop_stack;
- 
- 	for (; num_missing; num_missing--, cnt++) {
- 		h = missing_headers[num_missing - 1];
- 		loop_stack[cnt] = (struct loop_stack_entry){ .loop_id = h };
+ 	*pushed = num_missing;
+ 	while (num_missing--) {
+ 		h = missing_headers[num_missing];
+ 		/* wherever it is entered: a loop can have more than one entry */
+ 		if (aux[h].loop->exit_to < 0) {
+ 			verbose(env, "loop at insn %d never exits\n", h);
+ 			return -EINVAL;
+ 		}
+ 		entry = push_loop(env, frame, aux[h].loop);
+ 		if (!entry)
+ 			return -ENOMEM;
  		if (env->log.level & BPF_LOG_LEVEL2)
  			verbose(env, "entering loop %d\n", h);
- 		*pushed = true;
+ 		if (h != env->insn_idx && !env->path_sensitive && !try_peel_trip(entry))
+ 			leave_peeled_trips(env, entry);
  	}
- 	frame->loop_stack_cnt = cnt;
  	return 0;
- 
- e2big:
- 	verbose(env, "Too many nested loops (%d/%d) at %d\n", cnt, num_missing, env->insn_idx);
- 	return -E2BIG;
  }
  
  /*
@@@ -20538,13 -20953,15 +20971,15 @@@
   *            if ...:    // before goto the loop stack is [1, 2, 3 <top>]
   *              goto 1b; // after goto it should become [1]
   */
- static int loop_stack_pop(struct bpf_verifier_env *env)
+ static void loop_stack_pop(struct bpf_verifier_env *env)
  {
  	struct bpf_insn_aux_data *aux = env->insn_aux_data;
  	struct bpf_func_state *frame = cur_func(env);
- 	int new_cnt = 0;
+ 	int cnt = frame->loop_stack_cnt, new_cnt;
  	int h, i;
  
+ 	/* the function stays in its recursion */
+ 	new_cnt = cnt && frame->loop_stack[0].loop->kind == BPF_LOOP_RECURSION;
  	/*
  	 * Walk the loop nest of insn_idx outwards (innermost first) and stop at
  	 * the first loop that is present on the stack - that loop is the common
@@@ -20552,8 -20969,8 +20987,8 @@@
  	 * stack, drop all loops.
  	 */
  	for (h = bpf_loop_at_index(env, env->insn_idx); h >= 0; h = aux[h].loop_header) {
- 		for (i = frame->loop_stack_cnt - 1; i >= 0; i--) {
- 			if (frame->loop_stack[i].loop_id == h) {
+ 		for (i = cnt - 1; i >= 0; i--) {
+ 			if (frame->loop_stack[i].loop == aux[h].loop) {
  				new_cnt = i + 1;
  				goto pop;
  			}
@@@ -20562,102 -20979,746 +20997,746 @@@
  
  pop:
  	if (env->log.level & BPF_LOG_LEVEL2)
- 		for (i = frame->loop_stack_cnt - 1; i >= new_cnt; i--)
- 			verbose(env, "exiting loop %d\n", frame->loop_stack[i].loop_id);
- 	frame->loop_stack_cnt = new_cnt;
+ 		for (i = cnt - 1; i >= new_cnt; i--)
+ 			if (frame->loop_stack[i].loop->kind == BPF_LOOP_JUMPS)
+ 				verbose(env, "exiting loop %d\n",
+ 					frame->loop_stack[i].loop->header);
+ 	leave_loops(frame, new_cnt);
+ 	if (new_cnt != cnt)
+ 		bpf_equations_clean(env, env->cur_state);
+ }
+ 
+ static bool xreg_has_id(struct bpf_verifier_state *st, u32 id)
+ {
+ 	u32 mask = BIT(STACK_SPILL) | BIT(STACK_DYNPTR) | BIT(STACK_ITER) | BIT(STACK_IRQ_FLAG);
+ 	struct bpf_stack_state *slot;
+ 	struct bpf_func_state *frame;
+ 	struct bpf_reg_state *reg;
+ 
+ 	bpf_for_each_reg_in_vstate_mask(st, frame, reg, slot, mask, ({
+ 		if (reg->id == id || reg->parent_id == id)
+ 			return true;
+ 	}));
+ 	return false;
+ }
+ 
+ /*
+  * The current state went around a loop. If it holds more than the states at the header, none of
+  * them subsumes it, and it has no join. It goes around again:
+  *	bpf_for(i, 0, n) { if (prev) release(prev); prev = cur; cur = acquire(); }
+  * The number of xregs limits the references: a reference that is in no xreg is a leak. The
+  * number of peeled trips limits the rest. The state continues until it holds more, so it is
+  * unproven where a check fails on a path. Returns 1 if it ends here.
+  */
+ static int check_held_in_leftover(struct bpf_verifier_env *env,
+ 				  const struct loop_stack_entry *entry)
+ {
+ 	struct bpf_verifier_state *st = env->cur_state;
+ 	u32 held = held_cnt(st), i;
+ 	bool leak = false;
+ 
+ 	if (entry->peeled || held <= entry->held_cnt)
+ 		return 0;
+ 	/* the callers have xregs for the first ones */
+ 	for (i = st->frame[0]->entry_refs; i < st->acquired_refs && !leak; i++) {
+ 		if (st->refs[i].type != REF_TYPE_PTR || st->refs[i].ctx_arg)
+ 			continue;
+ 		bpf_add_cost(env, bpf_xreg_cnt(st), BPF_COST_SCAN);
+ 		leak = !xreg_has_id(st, st->refs[i].id);
+ 		held--;
+ 	}
+ 	if (!leak && held <= entry->held_cnt + entry->loop->this_pass.peeled_cnt)
+ 		return 0;
+ 	if (st->speculative)
+ 		return -EINVAL;
+ 	verbose(env, "loop at insn %d acquires more than it releases\n", entry->loop->header);
+ 	env->imprecise |= !env->err;
+ 	st->suspect_loops |= entry->loop->suspect_bit;
+ 	st->holds_too_much = true;
+ 	if (bpf_same_insns_unproven(env))
+ 		return -EINVAL;
+ 	note_error(env, -EINVAL);
+ 	st->holds_too_much = false;
+ 	st->max_held_cnt = st->max_held_cnt ?: held_cnt(st);
+ 	return held_cnt(st) > st->max_held_cnt;
+ }
+ 
+ /*
+  * A path-sensitive run is in a loop with a trip count. If only the jump on the iv depends on
+  * the xregs that moved, the path can take the same edges again and again:
+  *	for (i = 0; i < 100000; i++) { if (rnd() && n < 8) n++; }
+  * Two trips show a step also for 'sum += i', and more than 2^32 trips also for a ring index.
+  * If the steps are not constant, the skip or "infinite" is a guess.
+  * If the bound moved, there is no skip. A later saved trip can have the same bound.
+  * Returns 1 if it skipped these trips.
+  */
+ static int fast_forward_trips(struct bpf_verifier_env *env, struct loop_stack_entry *entry)
+ {
+ 	struct bpf_verifier_state *cur = env->cur_state, *old = &entry->header_state->st;
+ 	const struct loop_stack_entry *saved = bpf_top_loop(old->frame[old->curframe]);
+ 	u32 period = entry->trip - saved->trip;
+ 	bool infinite = entry->trips_left > BPF_MAX_TRIPS, guess;
+ 	u64 factor = div_u64(entry->trips_left - 1, period);
+ 	DECLARE_BITMAP(iv_xregs, MAX_BPF_XREG) = {};
+ 	int err;
+ 
+ 	/* the answer needs a walk over the program */
+ 	if ((infinite ? entry->loop->infinite : entry->trips_left <= period) ||
+ 	    (!infinite && saved->exit_threshold != entry->exit_threshold) ||
+ 	    (u64)entry->trip * entry->loop->nr_insns < env->prog->len)
+ 		return 0;
+ 	bpf_fast_forward_xregs(env, old, cur, 0, iv_xregs);
+ 	err = bpf_jumps_see_same(env, old, cur, entry->iv_jump_idx, infinite ? NULL : iv_xregs);
+ 	if (err <= 0)
+ 		return err;
+ 	guess = !bpf_steps_are_constant(env, entry, iv_xregs, infinite, factor);
+ 	if (infinite) {
+ 		entry->loop->infinite = true;
+ 		entry->loop->infinite_is_guess = guess || env->run_has_guess;
+ 		return 0;
+ 	}
+ 	env->run_has_guess |= guess;
+ 	bpf_fast_forward_xregs(env, old, cur, factor, iv_xregs);
+ 	entry->iv_jump_idx = 0;
+ 	entry->trips_left = 1;
+ 	return 1;
+ }
+ 
+ /*
+  * A path of a path-sensitive run starts a trip. Compare it with the state in which it started
+  * trip 0, 1, 2, 4, ...
+  * If the jumps see the same values, the loop is infinite and needs may_goto.
+  * With a trip count the path makes that many trips. Else it makes up to
+  * env->failing_path_max_trips. Returns 1 if it ends here.
+  */
+ static int failing_path_trip(struct bpf_verifier_env *env, struct loop_stack_entry *entry)
+ {
+ 	struct bpf_verifier_state *cur = env->cur_state, *old = &entry->header_state->st;
+ 	struct bpf_loop *loop = entry->loop;
+ 	struct loop_stack_entry mine;
+ 	int err;
+ 
+ 	if (entry->trip > env->failing_path_max_trips &&
+ 	    (!entry->trips_left || entry->trips_left > BPF_MAX_TRIPS)) {
+ 		env->too_deep = true;
+ 		return 1;
+ 	}
+ 	if (entry->header_state) {
+ 		mine = *entry;
+ 		*entry = *bpf_top_loop(old->frame[old->curframe]);
+ 		err = bpf_same_join_key(old, cur);
+ 		*entry = mine;
+ 		if (err)
+ 			err = entry->trips_left ? fast_forward_trips(env, entry) :
+ 						  bpf_jumps_see_same(env, old, cur, -1, NULL);
+ 		if (err < 0)
+ 			return err;
+ 		if (err && entry->trips_left)
+ 			return bpf_flow_save_header_state(env, entry);
+ 		if (err && !loop->infinite && !loop->rt_bounded) {
+ 			loop->infinite = true;
+ 			/* the next runs keep it */
+ 			loop->infinite_is_guess = env->run_has_guess;
+ 			return bpf_flow_needs_guard(env, loop);
+ 		} else if (err && !bpf_values_grew_in_deps(env, old, cur)) {
+ 			return 1;
+ 		}
+ 	}
+ 	return bpf_trip_is_saved(entry) ? bpf_flow_save_header_state(env, entry) : 0;
+ }
+ 
+ /*
+  * The cpu can speculate past the jump that the equations decide.
+  * The removal of dead code can delete an edge only from a conditional jump.
+  */
+ static bool infeasible_state_ends(struct bpf_verifier_env *env)
+ {
+ 	int from = env->cur_state->last_insn_idx;
+ 
+ 	return env->cur_state->equations.infeasible && env->bypass_spec_v1 && from >= 0 &&
+ 	       bpf_insn_is_cond_jump(env->prog->insnsi[from].code);
+ }
+ 
+ /* The current state came back to the header of the loop of @entry. Returns 1 if it ends here. */
+ static int next_trip(struct bpf_verifier_env *env, struct loop_stack_entry *entry,
+ 		     bool *starts_leftover)
+ {
+ 	entry->trip++;
+ 	if (entry->loop->kind != BPF_LOOP_RECURSION) {
+ 		bpf_equations_next_trip(env, env->cur_state, entry - cur_func(env)->loop_stack);
+ 		/* No run makes 2^63 trips. The header is not dead code: a trip started there. */
+ 		if (infeasible_state_ends(env) ||
+ 		    (env->bypass_spec_v1 && cnum64_is_empty(entry->trip_index.r64)))
+ 			return 1;
+ 	}
+ 	if (env->path_sensitive)
+ 		return failing_path_trip(env, entry);
+ 	if (!entry->peeled)
+ 		return check_held_in_leftover(env, entry);
+ 	*starts_leftover = !bpf_flow_trip_is_new(env, entry) || !try_peel_trip(entry);
+ 	if (*starts_leftover)
+ 		entry->entry_id = ++env->loop_entry_cnt;
  	return 0;
  }
  
- static int maybe_clamp_scev_regs(struct bpf_verifier_env *env)
+ /* @callee is the frame of a function that is verified on its own */
+ static int enter_recursion(struct bpf_verifier_env *env, struct bpf_func_state *callee)
  {
- 	struct bpf_func_state *frame = cur_func(env);
- 	struct loop_stack_entry *entry;
+ 	u32 cycle = env->subprog_info[callee->subprogno].cycle;
+ 	struct bpf_loop *loop = env->insn_aux_data[env->subprog_info[cycle].start].recursion_loop;
+ 	struct loop_stack_entry *entry, *from = env->cur_state->frame[0]->loop_stack;
+ 	bool starts_leftover;
+ 	int err = 0;
  
- 	if (frame->loop_stack_cnt == 0) {
- 		verifier_bug(env, "%s: loop stack empty at %d", __FUNCTION__, env->insn_idx);
- 		return -EFAULT;
- 	}
- 
- 	entry = &frame->loop_stack[frame->loop_stack_cnt - 1];
- 	if (!entry->terminates)
+ 	if (!loop)
  		return 0;
- 
- 	return bpf_clamp_scev_regs(env, frame, env->insn_idx, entry->entry_state,
- 				   entry->max_header_count);
+ 	entry = push_loop(env, callee, loop);
+ 	if (!entry)
+ 		return -ENOMEM;
+ 	starts_leftover = !try_peel_trip(entry);
+ 	if (env->cur_state->frame[0]->loop_stack_cnt && from->loop == loop) {
+ 		*entry = *from;
+ 		starts_leftover = false;
+ 		err = next_trip(env, entry, &starts_leftover);
+ 	}
+ 	if (starts_leftover)
+ 		leave_peeled_trips(env, entry);
+ 	return err;
  }
  
- static int handle_loop_entry_exit(struct bpf_verifier_env *env)
+ /* The helper at env->insn_idx calls the callback again and again. @back: the callback returned. */
+ static int enter_callback(struct bpf_verifier_env *env, bool back, struct bpf_loop **backedge_loop)
  {
- 	struct bpf_verifier_state *cur = env->cur_state;
+ 	struct bpf_loop *loop = cur_aux(env)->callback_loop;
  	struct bpf_func_state *frame = cur_func(env);
  	struct loop_stack_entry *entry;
- 	struct bpf_loop_iters iters;
- 	bool pushed, terminates;
+ 	bool starts_leftover = false;
+ 	int err = 0;
+ 
+ 	if (!loop)
+ 		return 0;
+ 	if (back) {
+ 		entry = bpf_top_loop(frame);
+ 		err = next_trip(env, entry, &starts_leftover);
+ 		*backedge_loop = starts_leftover ? NULL : loop;
+ 	} else {
+ 		entry = push_loop(env, frame, loop);
+ 		if (!entry)
+ 			return -ENOMEM;
+ 		if (env->path_sensitive)
+ 			return failing_path_trip(env, entry);
+ 		starts_leftover = !try_peel_trip(entry);
+ 	}
+ 	if (starts_leftover)
+ 		leave_peeled_trips(env, entry);
+ 	return err;
+ }
+ 
+ /* The current state is at the header of a loop and starts its leftover */
+ int bpf_flow_start_leftover(struct bpf_verifier_env *env)
+ {
+ 	leave_peeled_trips(env, bpf_top_loop(cur_func(env)));
+ 	return enter_callback(env, false, NULL);
+ }
+ 
+ /*
+  * The current state gets to env->insn_idx. Leave the loops that the insn is not in. Enter
+  * the loops that it is in. Returns 1 if the state ends here.
+  * @backedge_loop: the state came back to the header of that loop.
+  * @starts_leftover: see bpf_flow_start_leftover()
+  */
+ int bpf_flow_loop_enter(struct bpf_verifier_env *env, struct bpf_loop **backedge_loop,
+ 			bool *starts_leftover)
+ {
+ 	struct bpf_func_state *frame = cur_func(env);
+ 	struct loop_stack_entry *entry;
+ 	bool pushed;
  	int err;
  
- 	err = loop_stack_pop(env);
- 	if (err)
- 		return err;
+ 	if (infeasible_state_ends(env))
+ 		return 1;
+ 
+ 	/* The callback came back to the helper that calls it, in the same trip. */
+ 	if (frame->callback_depth)
+ 		return enter_callback(env, true, backedge_loop);
+ 
+ 	loop_stack_pop(env);
+ 	if (infeasible_state_ends(env))
+ 		return 1;
  
  	err = loop_stack_push(env, &pushed);
  	if (err)
  		return err;
  
- 	if (frame->loop_stack_cnt == 0)
- 		return 0;
+ 	entry = bpf_top_loop(frame);
+ 	if (!entry || entry->loop != cur_aux(env)->loop)
+ 		return enter_callback(env, false, NULL);
+ 	if (env->path_sensitive)
+ 		return (pushed ? failing_path_trip(env, entry) :
+ 			next_trip(env, entry, starts_leftover)) ?:
+ 		       enter_callback(env, false, NULL);
+ 	if (pushed) {
+ 		*starts_leftover = !try_peel_trip(entry);
+ 		return *starts_leftover ? 0 : enter_callback(env, false, NULL);
+ 	}
  
- 	entry = &frame->loop_stack[frame->loop_stack_cnt - 1];
- 	if (env->insn_idx != entry->loop_id)
- 		return 0;
- 
- 	/* If nothing was pushed and env->insn_idx is a loop header, we've taken a backedge. */
- 	if (!pushed)
- 		return maybe_clamp_scev_regs(env);
- 
- 	err = bpf_compute_loop_iters(env, env->cur_state, &iters);
- 	if (err < 0)
+ 	*backedge_loop = entry->loop;
+ 	err = next_trip(env, entry, starts_leftover);
+ 	if (err || *starts_leftover)
  		return err;
+ 	return enter_callback(env, false, NULL);
+ }
  
- 	terminates = err == 1;
- 	if (!terminates)
+ /* Can the main program return 0? */
+ static bool zero_is_valid_retval(struct bpf_verifier_env *env)
+ {
+ 	struct bpf_retval_range range;
+ 
+ 	if (program_returns_void(env) || !return_retval_range(env, &range))
+ 		return true;
+ 	return range.minval <= 0 && range.maxval >= 0;
+ }
+ 
+ /*
+  * A loop or a recursion is out of budget in the current frame of @st. What the
+  * program computed so far is not what it was meant to compute, so it's better
+  * not to go on. The way to stop is to unwind: 'r0 = 0; unwind_exit'. The landing
+  * pads of the callers are code like any other. They release what the callers
+  * hold, or the program is rejected.
+  *
+  * False when it cannot:
+  * - There is no landing pad for what this frame took itself.
+  * - There is a call of the subprog that unwind_goto doesn't follow. That is every
+  *   program that is compiled without unwinding.
+  * - A helper that calls a callback doesn't expect it to unwind.
+  * Then the program goes on along a path that it has, like after may_goto of
+  * its own. It releases what it holds there.
+  *
+  * @or_exit: there is no such path. 'r0 = 0; exit' has to do where the subprog
+  * cannot unwind, and the caller goes on with 0 in place of the result.
+  */
+ static bool state_can_unwind(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
+ 			     bool or_exit)
+ {
+ 	const struct bpf_func_state *frame = st->frame[st->curframe];
+ 	const struct bpf_subprog_info *sub = &env->subprog_info[frame->subprogno];
+ 	bool top;
+ 
+ 	if (sub->bail_insn < 0)
+ 		return false;
+ 	if (st->acquired_refs != frame->entry_refs ||
+ 	    st->active_rcu_locks != frame->entry_rcu_locks ||
+ 	    st->active_preempt_locks != frame->entry_preempt_locks)
+ 		return false;
+ 	if (frame->in_callback_fn || frame->in_exception_callback_fn)
+ 		return false;
+ 	/* the kernel called it: either exit ends it */
+ 	top = !st->curframe && !st->callers_unknown &&
+ 	      (!frame->subprogno || frame->in_async_callback_fn);
+ 	if (top && !frame->subprogno && !zero_is_valid_retval(env))
+ 		return false;
+ 	return top || sub->bail_unwinds || or_exit;
+ }
+ 
+ /* May_goto at the head of a loop skips the body. Does it go to code that reads what is not set? */
+ static bool guard_reads_unset_reg(struct bpf_verifier_env *env,
+ 				  const struct bpf_insn_aux_data *aux)
+ {
+ 	u16 live = env->insn_aux_data[aux->guard_to].live_regs_before;
+ 	int r;
+ 
+ 	for (r = BPF_REG_0; r < BPF_REG_FP; r++)
+ 		if ((live & BIT(r)) && cur_regs(env)[r].type == NOT_INIT)
+ 			return true;
+ 	return false;
+ }
+ 
+ /*
+  * The current frame leaves with 0 in place of the result: with unwind_exit if the subprog
+  * can do that, with exit otherwise. The insns are added when the main pass is over. Until
+  * then an exit that the subprog has stands for them.
+  */
+ static int push_unwind_exit(struct bpf_verifier_env *env)
+ {
+ 	struct bpf_subprog_info *sub = &env->subprog_info[cur_func(env)->subprogno];
+ 	struct bpf_verifier_state *branch;
+ 	struct bpf_reg_state *regs;
+ 
+ 	if (env->cur_state->speculative)
  		return 0;
- 
- 	/* Create a loop_entry checkpoint before widening */
- 	err = bpf_split_cur_state(env);
- 	if (err)
- 		return err;
- 
- 	entry->min_header_count = iters.min_header_count;
- 	entry->max_header_count = iters.max_header_count;
- 	entry->entry_state = cur->parent;
- 	entry->terminates = true;
- 	err = bpf_widen_scev_regs(env, cur, cur->parent, &iters);
- 	if (err < 0)
- 		return err;
+ 	branch = push_stack(env, sub->bail_insn, env->insn_idx, false);
+ 	if (IS_ERR(branch))
+ 		return PTR_ERR(branch);
+ 	branch->unwound = sub->bail_unwinds;
+ 	regs = branch->frame[branch->curframe]->regs;
+ 	__mark_reg_const_zero(&regs[BPF_REG_0]);
+ 	if (bpf_ret_reg_pair(env, cur_func(env)->subprogno))
+ 		__mark_reg_const_zero(&regs[BPF_REG_2]);
+ 	bpf_equations_forget_xreg(env, branch, bpf_xreg(branch->curframe, BPF_REG_0));
+ 	bpf_equations_forget_xreg(env, branch, bpf_xreg(branch->curframe, BPF_REG_2));
  	return 0;
  }
  
- static int do_check(struct bpf_verifier_env *env)
+ /*
+  * A loop has no trip count, and nothing stops it at run time. It gets may_goto
+  * before this insn. When may_goto is out of budget, the program goes to its
+  * target with the registers and the stack that it has here.
+  * Every state that goes through the loop does that, see bpf_flow_needs_guard().
+  */
+ static int check_loop_guard(struct bpf_verifier_env *env)
+ {
+ 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[env->insn_idx];
+ 	struct bpf_loop *loop;
+ 	int err;
+ 
+ 	/* The callback came back to the helper that calls it: the program is not in front of it. */
+ 	if (!aux->guard_place || cur_func(env)->callback_depth)
+ 		return 0;
+ 	loop = env->insn_aux_data[bpf_loop_at_index(env, env->insn_idx)].loop;
+ 	if (loop->rt_bounded)
+ 		return 0;
+ 	if (!(env->path_sensitive ? loop->infinite : loop->guarded)) {
+ 		loop->this_pass.no_guard_edges = true;
+ 		return 0;
+ 	}
+ 
+ 	env->imprecise |= !env->err;
+ 	env->run_has_guess |= loop->infinite_is_guess;
+ 	/* the device runs the insns that the driver was given, without may_goto */
+ 	if (bpf_prog_is_offloaded(env->prog->aux)) {
+ 		verbose(env, "loop at insn %d has no known bound in an offloaded program\n",
+ 			loop->header);
+ 		env->cur_state->suspect_loops |= loop->suspect_bit;
+ 		return -EINVAL;
+ 	}
+ 
+ 	/*
+ 	 * A guard has one way out, and only that one is verified.
+ 	 *
+ 	 * Leave the subprog, if that is possible every time the program gets here:
+ 	 *	do { p = lookup(); } while (!p); *p
+ 	 * The code after the loop relies on the result of the jump that leaves it.
+ 	 *
+ 	 * Otherwise leave the loop:
+ 	 *	lock(); do { ... } while (...); unlock();
+ 	 * The code after the loop releases what is held.
+ 	 *
+ 	 * The program has no edge from the header of a loop to the exit of the loop:
+ 	 *	for (;;) { c = *s++; if (!c) return 0; if (c == '*') return 1; }
+ 	 * The loop is left to 'exit', and only its body sets r0. Then leave the subprog. Use
+ 	 * a plain exit if it cannot unwind, like check_recursion_guard().
+ 	 *
+ 	 * All states that get here take the same way, or the pass starts again.
+ 	 * A speculative state does not select the way.
+ 	 */
+ 	if (env->cur_state->speculative)
+ 		goto out;
+ 	if (aux->guard_at_header && !aux->guard_unset_reg && guard_reads_unset_reg(env, aux)) {
+ 		aux->guard_unset_reg = true;
+ 		env->guards_late |= aux->guard_no_unwind && aux->loop_guard;
+ 		aux->guard_no_unwind = false;
+ 	}
+ 	if (!aux->guard_no_unwind &&
+ 	    !state_can_unwind(env, env->cur_state, aux->guard_unset_reg)) {
+ 		env->guards_late |= aux->loop_guard;
+ 		aux->guard_no_unwind = true;
+ 	}
+ 	/* another state selected the target, possibly a state that only a join makes */
+ 	env->run_has_guess |= aux->guard_no_unwind &&
+ 			      state_can_unwind(env, env->cur_state, aux->guard_unset_reg);
+ out:
+ 	aux->loop_guard = true;
+ 	aux->guard_unwinds = !aux->guard_no_unwind;
+ 	if (aux->guard_no_unwind)
+ 		err = PTR_ERR_OR_ZERO(push_stack(env, aux->guard_to, env->insn_idx, false));
+ 	else
+ 		err = push_unwind_exit(env);
+ 	/* more peeled trips can show that the edge is dead */
+ 	if (!err && env->head)
+ 		env->head->st.suspect_loops |= loop->suspect_bit;
+ 	return err;
+ }
+ 
+ /* The states that the insn pushed go where they were pushed to. */
+ static int flow_drain(struct bpf_verifier_env *env)
+ {
+ 	struct bpf_verifier_stack_elem *elem;
+ 	int err = 0;
+ 
+ 	while ((elem = env->head)) {
+ 		env->head = elem->next;
+ 		if (!err)
+ 			err = bpf_flow_deliver(env, &elem->st, elem->insn_idx,
+ 					       elem->prev_insn_idx, elem->again);
+ 		bpf_free_verifier_state(env, &elem->st, false);
+ 		kfree(elem);
+ 	}
+ 	return err;
+ }
+ 
+ /*
+  * A subprog on a cycle of the call graph checks the stack at run time, see
+  * bpf_insert_recursion_checks(). When there is no room, or the time slice is over, it leaves
+  * at once with 0 in place of the result: it unwinds if it can, see bail_unwinds, otherwise
+  * it returns and callers have to be fine with that.
+  */
+ static int check_recursion_guard(struct bpf_verifier_env *env)
+ {
+ 	struct bpf_subprog_info *sub = &env->subprog_info[cur_func(env)->subprogno];
+ 
+ 	if (!sub->recursive || env->insn_idx != sub->start)
+ 		return 0;
+ 	return push_unwind_exit(env);
+ }
+ 
+ static bool is_error_of_state(struct bpf_verifier_env *env, int err)
+ {
+ 	return err != -ENOMEM && err != -EINTR && !env->over_limit && !env->bug;
+ }
+ 
+ /* The pass has an error. The log ends with the first error. */
+ static void note_error(struct bpf_verifier_env *env, int err)
+ {
+ 	if (!is_error_of_state(env, err))
+ 		return;
+ 	if (!env->err) {
+ 		env->err = err;
+ 		env->err_insn = env->insn_idx;
+ 		env->log.level = 0;
+ 		env->pass_max_cost = min(env->pass_max_cost, bpf_pass_max_cost(env));
+ 	}
+ 	if (!env->path_sensitive)
+ 		bpf_note_unproven_insn(env, env->cur_state, env->insn_idx);
+ }
+ 
+ /* An error in a speculative state is no error */
+ static bool nospec_ends_path(struct bpf_verifier_env *env,
+ 			     const struct bpf_verifier_state *st, int err)
+ {
+ 	return st->speculative && err < 0 && is_error_of_state(env, err);
+ }
+ 
+ /* @st cannot take the edge to or from @idx. Returns 1 if only its path ends. */
+ int bpf_flow_edge_unproven(struct bpf_verifier_env *env, struct bpf_verifier_state *st, u32 idx,
+ 			   int err)
+ {
+ 	bool last;
+ 
+ 	if (nospec_ends_path(env, st, err)) {
+ 		need_nospec(env, idx);
+ 		return 1;
+ 	}
+ 	swap(env->insn_idx, idx);
+ 	last = !error_is_recoverable(err) || env->path_sensitive || bpf_same_insns_unproven(env);
+ 	swap(env->cur_state, st);
+ 	if (!env->path_sensitive)
+ 		note_error(env, err);
+ 	env->cur_state = st;
+ 	if (last)
+ 		return err;
+ 	env->insn_idx = idx;
+ 	return 1;
+ }
+ 
+ /* The call releases, locks, or makes a dynptr, an iterator or an irq flag */
+ static bool call_writes_held(struct bpf_verifier_env *env, const struct bpf_insn *insn)
+ {
+ 	const struct bpf_func_proto *fn = NULL;
+ 	struct bpf_kfunc_desc *desc;
+ 	enum bpf_arg_type type;
+ 	int i;
+ 
+ 	if (bpf_helper_call(insn)) {
+ 		bpf_get_helper_proto(env, insn->imm, &fn);
+ 	} else {
+ 		desc = find_kfunc_desc(env, insn->imm, insn->off);
+ 		fn = desc ? &desc->proto : NULL;
+ 	}
+ 	for (i = 0; fn && i < MAX_BPF_FUNC_REG_ARGS; i++) {
+ 		/* nothing is held for a pointer that an unproven insn made up */
+ 		if (cur_regs(env)[BPF_REG_1 + i].type == SCALAR_VALUE)
+ 			continue;
+ 		type = fn->arg_type[i];
+ 		if (arg_type_is_release(type) || (arg_type_is_dynptr(type) && (type & MEM_UNINIT)))
+ 			return true;
+ 		switch (base_type(type)) {
+ 		case ARG_PTR_TO_SPIN_LOCK:
+ 		case ARG_PTR_TO_RES_SPIN_LOCK:
+ 		case ARG_PTR_TO_IRQ_FLAG:
+ 		case ARG_PTR_TO_ITER:
+ 		case ARG_PTR_TO_LIST_NODE:
+ 		case ARG_PTR_TO_RB_NODE:
+ 			return true;
+ 		default:
+ 			break;
+ 		}
+ 	}
+ 	return false;
+ }
+ 
+ /*
+  * Continue as if @insn is proven, to find the other unproven insns of the pass.
+  * If it changes what is held, the next errors follow from this one, so the path ends.
+  * Returns 0 if the path continues.
+  */
+ static int skip_unproven_insn(struct bpf_verifier_env *env, const struct bpf_insn *insn)
+ {
+ 	struct bpf_func_state *frame = cur_func(env);
+ 	struct bpf_reg_state *regs = cur_regs(env);
+ 	u16 def = cur_aux(env)->def_regs;
+ 	u8 class = BPF_CLASS(insn->code), *type;
+ 	int i, spi;
+ 
+ 	if (bpf_insn_is_cond_jump(insn->code))
+ 		return PTR_ERR_OR_ZERO(push_stack(env, env->insn_idx + insn->off + 1,
+ 						  env->insn_idx, false));
+ 	if (class == BPF_LD || ((class == BPF_JMP || class == BPF_JMP32) &&
+ 				!bpf_helper_call(insn) && !bpf_pseudo_kfunc_call(insn)))
+ 		return PROCESS_BPF_EXIT;
+ 	if (class == BPF_JMP && call_writes_held(env, insn))
+ 		return PROCESS_BPF_EXIT;
+ 	/* what it stores can be read */
+ 	for_each_set_bit(spi, cur_aux(env)->may_write_mask, bpf_stack_nr_slots(frame)) {
+ 		type = bpf_stack_slot(frame, spi)->slot_type;
+ 		for (i = 0; i < BPF_REG_SIZE; i++)
+ 			if (type[i] == STACK_INVALID || type[i] == STACK_POISON)
+ 				type[i] = STACK_MISC;
+ 	}
+ 	for (i = BPF_REG_0; i < BPF_REG_FP; i++) {
+ 		if (!(def & BIT(i)))
+ 			continue;
+ 		if (class == BPF_JMP && i)
+ 			bpf_mark_reg_not_init(env, &regs[i]);
+ 		else
+ 			mark_reg_unknown(env, regs, i);
+ 	}
+ 	leave_callback(frame);
+ 	return 0;
+ }
+ 
+ /* These decide where the program can be attached, or what it reads */
+ struct prog_requirements {
+ 	u32 val[12];
+ };
+ 
+ static struct prog_requirements get_prog_requirements(struct bpf_verifier_env *env)
+ {
+ 	const struct bpf_prog *prog = env->prog;
+ 	const struct bpf_prog_aux *aux = prog->aux;
+ 
+ 	return (struct prog_requirements){{
+ 		env->ops->convert_ctx_access ? 0 : aux->max_ctx_offset,
+ 		aux->max_tp_access, aux->max_rdonly_access, aux->max_rdwr_access,
+ 		aux->min_rdwr_write, aux->max_rdwr_write, aux->kprobe_write_ctx,
+ 		prog->type == BPF_PROG_TYPE_EXT && env->seen_direct_write,
+ 		prog->type == BPF_PROG_TYPE_PERF_EVENT && prog->call_get_stack,
+ 		prog->tstamp_type_access, prog->kprobe_override, prog->enforce_expected_attach_type,
+ 	}};
+ }
+ 
+ static void free_pushed_states(struct bpf_verifier_env *env)
+ {
+ 	struct bpf_verifier_stack_elem *elem;
+ 
+ 	while ((elem = env->head)) {
+ 		env->head = elem->next;
+ 		bpf_free_verifier_state(env, &elem->st, false);
+ 		kfree(elem);
+ 	}
+ }
+ 
+ /*
+  * A load with a range of offsets makes a number of the pointers that are spilled there. If an
+  * insn needed a pointer and got that number, load each slot in its own state:
+  *	char *p[2] = { a, b };
+  *	return p[i & 1][63];
+  * Other loads keep the number: 'sum += word[i]' fails for a pointer.
+  */
+ static int fork_stack_load(struct bpf_verifier_env *env, const struct bpf_insn *insn,
+ 			   unsigned long ranges)
+ {
+ 	struct bpf_verifier_state *st = env->cur_state, *part;
+ 	DECLARE_BITMAP(slots, MAX_BPF_XREG) = {};
+ 	u32 regno = insn->src_reg, xregno, last;
+ 	struct bpf_stack_state *slot;
+ 	struct bpf_func_state *frame;
+ 	struct bpf_reg_state *reg;
+ 	struct scalar value = {};
+ 	bool has_ptr = false, needs_ptr;
+ 	s64 min_off, max_off;
+ 	int spi;
+ 
+ 	/* the cpu can speculate with the address of another state */
+ 	if (insn->code != (BPF_LDX | BPF_MEM | BPF_DW) || !(ranges & BIT(regno)) ||
+ 	    cur_regs(env)[regno].type != PTR_TO_STACK || !env->bypass_spec_v1)
+ 		return 0;
+ 	/* without allow_ptr_leaks the load fails */
+ 	needs_ptr = !env->allow_ptr_leaks || bpf_insn_makes_ptr(env);
+ 	reg = &cur_regs(env)[regno];
+ 	frame = bpf_func(env, reg);
+ 	min_off = reg_smin(reg) + insn->off;
+ 	max_off = reg_smax(reg) + insn->off;
+ 	if (offset_is_far(reg) || min_off < -frame->allocated_stack || max_off >= 0 ||
+ 	    !tnum_is_aligned(tnum_add(reg->var_off, tnum_const(insn->off)), BPF_REG_SIZE))
+ 		return 0;
+ 	bpf_add_cost(env, (max_off - min_off) / BPF_REG_SIZE, BPF_COST_XREG);
+ 	for (spi = bpf_get_spi(max_off); spi <= bpf_get_spi(min_off); spi++) {
+ 		scalar_set_const(&value, -(spi + 1) * BPF_REG_SIZE - insn->off);
+ 		if (!scalar_subsumes(scalar_of(reg), &value))
+ 			continue;
+ 		slot = bpf_stack_slot(frame, spi);
+ 		__set_bit(bpf_spi_to_xreg(spi), slots);
+ 		has_ptr |= bpf_is_spilled_reg(slot) && !bpf_is_spilled_scalar_reg(slot);
+ 	}
+ 	if (!has_ptr)
+ 		return 0;
+ 	env->imprecise |= !env->err;
+ 	if (!needs_ptr)
+ 		return 0;
+ 	/* no run has to load from all slots */
+ 	env->extra_values = true;
+ 	if (env->log.level & BPF_LOG_LEVEL)
+ 		verbose(env, "fork R%d\n", regno);
+ 	mark_reg_scratched(env, regno);
+ 	last = find_last_bit(slots, MAX_BPF_XREG);
+ 	for_each_set_bit(xregno, slots, MAX_BPF_XREG) {
+ 		part = xregno == last ? st : push_stack(env, env->insn_idx, env->insn_idx, false);
+ 		if (IS_ERR(part))
+ 			return PTR_ERR(part);
+ 		spi = bpf_xreg_to_spi(xregno);
+ 		scalar_set_const(scalar_of(&part->frame[part->curframe]->regs[regno]),
+ 				 -(spi + 1) * BPF_REG_SIZE - insn->off);
+ 		bpf_equations_refine_by_reg(env, part, regno);
+ 		if (part != st)
+ 			env->head->again = true;
+ 	}
+ 	return 0;
+ }
+ 
+ /* Process the current state until it gets to the start of a basic block. */
+ static int do_check_block(struct bpf_verifier_env *env, int prev_insn_idx)
  {
- 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
  	struct bpf_verifier_state *state = env->cur_state;
+ 	struct bpf_verifier_stack_elem *elem;
  	struct bpf_insn *insns = env->prog->insnsi;
  	int insn_cnt = env->prog->len;
- 	bool do_print_state = false;
- 	int prev_insn_idx = -1;
+ 	bool do_print_state = true, from_unproven;
+ 	struct prog_requirements prog_requirements, new_requirements;
+ 	bool again = prev_insn_idx == env->insn_idx;
+ 	unsigned long ranges;
+ 	bool stack_args;
+ 	u32 held;
  
+ 	mark_verifier_state_scratched(env);
  	for (;;) {
  		struct bpf_insn *insn;
  		struct bpf_insn_aux_data *insn_aux;
+ 		struct bpf_insn_fixups fixups;
  		int err;
  
- 		if (signal_pending(current))
- 			return -EAGAIN;
- 
- 		cond_resched_tasks_rcu_qs();
- 
- 		/* reset current history entry on each new instruction */
- 		env->cur_hist_ent = NULL;
+ 		err = bpf_check_limits(env);
+ 		if (err)
+ 			return err;
  
  		env->prev_insn_idx = prev_insn_idx;
  		if (env->insn_idx >= insn_cnt) {
@@@ -20671,18 -21732,10 +21750,10 @@@
  
  		account_processed_insn(env);
  
- 		if (env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
- 			verbose(env,
- 				"BPF program is too large. Processed %d insn\n",
- 				env->insn_processed);
- 			return -E2BIG;
- 		}
- 
  		state->last_insn_idx = env->prev_insn_idx;
  		state->insn_idx = env->insn_idx;
  		/*
- 		 * Record the incoming edge so active and queued paths use the same
- 		 * branch-recording path. A zero-offset conditional has identical
+ 		 * Record the incoming edge. A zero-offset conditional has identical
  		 * successors, so its outcome cannot be reconstructed from the edge.
  		 */
  		if (!state->speculative && prev_insn_idx >= 0 && prev_insn_idx < insn_cnt) {
@@@ -20702,40 -21755,6 +21773,6 @@@
  			}
  		}
  
- 		/*
- 		 * Possibly widen the registers before creating a checkpoint
- 		 * in bpf_is_state_visited(). The next loop iteration will
- 		 * have a chance to hit this checkpoint and converge.
- 		 */
- 		err = handle_loop_entry_exit(env);
- 		if (err)
- 			return err;
- 
- 		if (bpf_is_prune_point(env, env->insn_idx)) {
- 			err = bpf_is_state_visited(env, env->insn_idx);
- 			if (err < 0)
- 				return err;
- 			if (err == 1) {
- 				/* found equivalent state, can prune the search */
- 				if (env->log.level & BPF_LOG_LEVEL) {
- 					if (do_print_state)
- 						verbose(env, "\nfrom %d to %d%s: safe\n",
- 							env->prev_insn_idx, env->insn_idx,
- 							env->cur_state->speculative ?
- 							" (speculative execution)" : "");
- 					else
- 						verbose(env, "%d: safe\n", env->insn_idx);
- 				}
- 				goto process_bpf_exit;
- 			}
- 		}
- 
- 		if (bpf_is_jmp_point(env, env->insn_idx)) {
- 			err = bpf_push_jmp_history(env, state, 0, 0, 0, NULL, 0);
- 			if (err)
- 				return err;
- 		}
- 
  		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
  			verbose(env, "\nfrom %d to %d%s:",
  				env->prev_insn_idx, env->insn_idx,
@@@ -20745,13 -21764,6 +21782,6 @@@
  			do_print_state = false;
  		}
  
- 		if (bpf_loop_at_index(env, env->insn_idx) >= 0 &&
- 		    cur_func(env)->loop_stack_cnt == 0) {
- 			verifier_bug(env, "loop stack empty at %d, while inside the loop %d\n",
- 				     env->insn_idx, bpf_loop_at_index(env, env->insn_idx));
- 			return -EFAULT;
- 		}
- 
  		if (env->log.level & BPF_LOG_LEVEL) {
  			if (verifier_state_scratched(env))
  				print_insn_state(env, state, state->curframe);
@@@ -20765,18 -21777,23 +21795,23 @@@
  			env->prev_log_pos = env->log.end_pos;
  		}
  
- 		if (bpf_prog_is_offloaded(env->prog->aux)) {
+ 		if (env->replay) {
  			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
  							   env->prev_insn_idx);
  			if (err)
  				return err;
+ 		} else if (bpf_prog_is_offloaded(env->prog->aux)) {
+ 			/* the driver cannot forget what an imprecise state shows */
+ 			note_pessimized_insn(env, env->insn_idx);
  		}
  
  		sanitize_mark_insn_seen(env);
+ 		insn_aux->suspect_loops |= state->suspect_loops;
  		prev_insn_idx = env->insn_idx;
  
  		/* Sanity check: precomputed constants must match verifier state */
- 		if (!state->speculative && insn_aux->const_reg_mask) {
+ 		if (!state->speculative && !env->err && !env->extra_values &&
+ 		    insn_aux->const_reg_mask) {
  			struct bpf_reg_state *regs = cur_regs(env);
  			u16 mask = insn_aux->const_reg_mask;
  
@@@ -20799,69 -21816,178 +21834,178 @@@
  		/* Reduce verification complexity by stopping speculative path
  		 * verification when a nospec is encountered.
  		 */
+ 		if (state->speculative && insn_aux->non_speculative_first)
+ 			need_nospec(env, env->insn_idx);
  		if (state->speculative && insn_aux->nospec)
  			goto process_bpf_exit;
+ 		insn_aux->speculative_first |= !insn_aux->seen;
  
- 		err = do_check_insn(env, &do_print_state);
- 		if (error_recoverable_with_nospec(err) && state->speculative) {
+ 		ranges = operands_with_range(env, insn);
+ 		stack_args = cur_func(env)->out_stack_arg_cnt;
+ 
+ 		err = check_loop_guard(env) ?: check_recursion_guard(env);
+ 		err = err ?: fork_stack_load(env, insn, ranges);
+ 		if (err)
+ 			return err;
+ 
+ 		bpf_equations_before_insn(env);
+ 		held = held_cnt(state);
+ 		from_unproven = reads_from_unproven(env);
+ 		fixups = insn_aux->fixups;
+ 		prog_requirements = get_prog_requirements(env);
+ 		env->no_report = state->speculative;
+ 		err = do_check_insn(env, &do_print_state) ?: bpf_equations_after_insn(env);
+ 		env->no_report = false;
+ 		new_requirements = get_prog_requirements(env);
+ 		/* a join adds values only to a range */
+ 		if ((ranges || stack_args || again) &&
+ 		    memcmp(&prog_requirements, &new_requirements, sizeof(new_requirements)))
+ 			note_pessimized_insn(env, prev_insn_idx);
+ 		/* a call or an exit gave the state to the flow, the error is from there */
+ 		if (err < 0 && !state->frame[0])
+ 			return err;
+ 		insn_aux->releases |= held_cnt(state) < held && err != PROCESS_BPF_EXIT;
+ 		insn_aux->acquires |= held_cnt(state) > held;
+ 		if (nospec_ends_path(env, state, err)) {
  			/* Prevent this speculative path from ever reaching the
  			 * insn that would have been unsafe to execute.
+ 			 * What it noted does not apply to the other paths.
+ 			 * check_fastcall_stack_contract() clears the pattern only once.
  			 */
- 			insn_aux->nospec = true;
- 			/* If it was an ADD/SUB insn, potentially remove any
- 			 * markings for alu sanitization.
- 			 */
- 			insn_aux->alu_state = 0;
+ 			fixups.fastcall_spills_num = insn_aux->fastcall_spills_num;
+ 			insn_aux->fixups = fixups;
+ 			need_nospec(env, prev_insn_idx);
+ 			free_pushed_states(env);
  			goto process_bpf_exit;
+ 		} else if (error_is_recoverable(err) && !env->path_sensitive) {
+ 			env->insn_idx = prev_insn_idx;
+ 			if (bpf_same_insns_unproven(env))
+ 				return err;
+ 			if (from_unproven)
+ 				bpf_note_reads_from_unproven(env, prev_insn_idx);
+ 			else
+ 				note_error(env, err);
+ 			err = skip_unproven_insn(env, insn);
+ 			if (err < 0)
+ 				return err;
+ 			if (err)
+ 				goto process_bpf_exit;
+ 			mark_from_unproven(env, prev_insn_idx, true);
+ 			env->insn_idx++;
  		} else if (err < 0) {
  			return err;
  		} else if (err == PROCESS_BPF_EXIT) {
  			goto process_bpf_exit;
  		} else if (err == INSN_IDX_UPDATED) {
  		} else if (err == 0) {
+ 			if (!bpf_pseudo_call(insn) && !bpf_is_callx(insn))
+ 				mark_from_unproven(env, prev_insn_idx, from_unproven);
  			env->insn_idx++;
  		}
  
- 		if (state->speculative && insn_aux->nospec_result) {
- 			/* If we are on a path that performed a jump-op, this
- 			 * may skip a nospec patched-in after the jump. This can
- 			 * currently never happen because nospec_result is only
- 			 * used for the write-ops
- 			 * `*(size*)(dst_reg+off)=src_reg|imm32` and helper
- 			 * calls. These must never skip the following insn
- 			 * (i.e., bpf_insn_successors()'s opcode_info.can_jump
- 			 * is false). Still, add a warning to document this in
- 			 * case nospec_result is used elsewhere in the future.
- 			 *
- 			 * All non-branch instructions have a single
- 			 * fall-through edge. For these, nospec_result should
- 			 * already work.
- 			 */
- 			if (verifier_bug_if((BPF_CLASS(insn->code) == BPF_JMP ||
- 					     BPF_CLASS(insn->code) == BPF_JMP32) &&
- 					    BPF_OP(insn->code) != BPF_CALL, env,
- 					    "speculation barrier after jump instruction may not have the desired effect"))
- 				return -EFAULT;
+ 		/* only a store that stays gets it, see bpf_convert_ctx_accesses() */
+ 		if (state->speculative && insn_aux->nospec_result && !insn_aux->fastcall_pattern &&
+ 		    bpf_is_mem_insn(insn) && BPF_MODE(insn->code) == BPF_MEM) {
  process_bpf_exit:
  			account_current_path(env);
- 			mark_verifier_state_scratched(env);
- 			err = bpf_update_branch_counts(env, env->cur_state);
- 			if (err)
- 				return err;
- 			err = pop_stack(env, &prev_insn_idx, &env->insn_idx,
- 					pop_log);
- 			if (err < 0) {
- 				if (err != -ENOENT)
- 					return err;
- 				break;
- 			} else {
- 				do_print_state = true;
- 				continue;
- 			}
+ 			bpf_free_verifier_state(env, state, false);
+ 			memset(state, 0, sizeof(*state));
+ 			return flow_drain(env);
+ 		}
+ 
+ 		/* if the insn pushed a part, the current state is a part too */
+ 		for (elem = env->head; elem; elem = elem->next)
+ 			again |= elem->again;
+ 		err = flow_drain(env);
+ 		if (err)
+ 			return err;
+ 
+ 		/* the parts of a state meet at the next insn */
+ 		if (env->insn_idx < insn_cnt &&
+ 		    (again || bpf_flow_is_bb_start(env, env->insn_idx))) {
+ 			account_current_path(env);
+ 			return bpf_flow_deliver(env, state, env->insn_idx, prev_insn_idx, false);
  		}
  	}
+ }
  
- 	return 0;
+ /* What the pass assumed about loops does not hold, see do_check_all() */
+ static bool pass_needs_restart(struct bpf_verifier_env *env)
+ {
+ 	return (env->restart && bpf_flow_loops_lost_bound(env)) || env->guards_late;
+ }
+ 
+ /*
+  * The loops that keep the current state apart pay for the work since the last state, but not
+  * a loop that the state enters. A trip that is peeled on the budget of a loop belongs to that
+  * loop. Such trips can use up the budget of an inner loop.
+  */
+ static void charge_loops(struct bpf_verifier_env *env, u64 cost)
+ {
+ 	const struct bpf_verifier_state *st = env->cur_state;
+ 	const struct loop_stack_entry *e;
+ 	struct bpf_loop *starved_loop = NULL;
+ 	int fr, i;
+ 
+ 	for (fr = st->curframe; env->pass && fr >= 0; fr--) {
+ 		for (i = st->frame[fr]->loop_stack_cnt - 1; i >= 0; i--) {
+ 			e = &st->frame[fr]->loop_stack[i];
+ 			if ((e->peeled || e->loop->disjoint_apart) &&
+ 			    (e->trip || e->loop->header != st->insn_idx))
+ 				e->loop->this_pass.cost += cost;
+ 			if (e->peeled && e->trip >= e->loop->peel_cnt) {
+ 				if (starved_loop && e->loop->partitioned)
+ 					starved_loop->this_pass.starved =
+ 						e->loop->this_pass.starves = true;
+ 				return;
+ 			}
+ 			if (e->loop->partitioned && !bpf_loop_has_budget(e->loop))
+ 				starved_loop = e->loop;
+ 		}
+ 	}
+ }
+ 
+ static int do_check(struct bpf_verifier_env *env)
+ {
+ 	bool level2 = env->log.level & BPF_LOG_LEVEL2;
+ 	u64 log_pos = env->log.end_pos, diag_pos = 0;
+ 	u64 cost = env->cost;
+ 	int prev_insn_idx, err;
+ 
+ 	err = bpf_flow_deliver(env, env->cur_state, env->insn_idx, -1, false);
+ 	while (!err && !(env->path_sensitive && env->cost >= env->failing_path_max_cost)) {
+ 		err = bpf_flow_next(env, &prev_insn_idx, &log_pos, &diag_pos);
+ 		/* at the limit the work on equations is not complete, such a pass proves nothing */
+ 		if (err == -ENOENT)
+ 			return bpf_check_limits(env);
+ 		if (err)
+ 			break;
+ 		charge_loops(env, env->cost - cost);
+ 		cost = env->cost;
+ 		/* A pass logs one basic block at a time. A path-sensitive run logs a full path. */
+ 		bpf_diag_event_log_restore(env, diag_pos);
+ 		if (!level2) {
+ 			bpf_vlog_reset(&env->log, log_pos);
+ 			env->prev_linfo = NULL;
+ 		}
+ 		err = do_check_block(env, prev_insn_idx);
+ 		if (env->bug)
+ 			return -EFAULT;
+ 		/* a pass had no error at this insn, possibly with a state that has more values */
+ 		if (err && env->path_sensitive && is_error_of_state(env, err) &&
+ 		    (env->cur_state->infeasible || env->cur_state->equations.infeasible ||
+ 		     !bpf_failing_path_may_end_at(env, env->insn_idx))) {
+ 			bpf_free_verifier_state(env, env->cur_state, false);
+ 			memset(env->cur_state, 0, sizeof(*env->cur_state));
+ 			free_pushed_states(env);
+ 			err = 0;
+ 		}
+ 	}
+ 	/* bpf_flow_edge_unproven() noted it with the state that failed */
+ 	if (err && !bpf_insn_is_unproven(env))
+ 		note_error(env, err);
+ 	env->run_over_budget |= !err;
+ 	return err;
  }
  
  static int find_btf_percpu_datasec(struct btf *btf)
@@@ -20899,26 -22025,21 +22043,21 @@@ static int __add_used_btf(struct bpf_ve
  {
  	struct btf_mod_pair *btf_mod;
  	int ret = 0;
- 	int i;
  
  	/* check whether we recorded this BTF (and maybe module) already */
- 	for (i = 0; i < env->used_btf_cnt; i++)
- 		if (env->used_btfs[i].btf == btf)
- 			goto ret_put;
+ 	if (bpf_index_find(&env->used_index, (unsigned long)btf) >= 0)
+ 		goto ret_put;
  
  	if (env->signature) {
  		verbose(env, "signed program cannot bind any BTF\n");
  		ret = -EACCES;
  		goto ret_put;
  	}
- 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
- 		verbose(env, "The total number of btfs per program has reached the limit of %u\n",
- 			MAX_USED_BTFS);
- 		ret = -E2BIG;
+ 	btf_mod = bpf_table_next(env->used_btfs, env->used_btf_cnt);
+ 	if (!btf_mod) {
+ 		ret = -ENOMEM;
  		goto ret_put;
  	}
- 
- 	btf_mod = &env->used_btfs[env->used_btf_cnt];
  	btf_mod->btf = btf;
  	btf_mod->module = NULL;
  
@@@ -20931,8 -22052,7 +22070,7 @@@
  		}
  	}
  
- 	env->used_btf_cnt++;
- 	return 0;
+ 	return bpf_index_add(&env->used_index, (unsigned long)btf, env->used_btf_cnt++);
  
  ret_put:
  	/* Either error or this BTF was already added */
@@@ -20994,12 -22114,6 +22132,12 @@@ static int __check_pseudo_btf_id(struc
  		}
  	}
  
 +	if (!percpu && !env->allow_ptr_leaks) {
 +		verbose(env, "access to '%s' is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
 +			sym_name);
 +		return -EPERM;
 +	}
 +
  	type = t->type;
  	t = btf_type_skip_modifiers(btf, type, NULL);
  	if (percpu) {
@@@ -21045,11 -22159,6 +22183,11 @@@ static int check_pseudo_btf_id(struct b
  			verbose(env, "invalid module BTF object FD specified.\n");
  			return -EINVAL;
  		}
 +		if (!btf_is_kernel(btf)) {
 +			verbose(env, "BTF fd for ksym is not a kernel BTF\n");
 +			btf_put(btf);
 +			return -EINVAL;
 +		}
  	} else {
  		if (!btf_vmlinux) {
  			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
@@@ -21236,6 -22345,8 +22374,8 @@@ static int claim_used_maps(struct bpf_v
  
  		if (map->map_type != BPF_MAP_TYPE_INSN_ARRAY)
  			continue;
+ 		if (!bpf_table_next(env->insn_array_maps, env->insn_array_map_cnt))
+ 			return -ENOMEM;
  		err = bpf_insn_array_init(map, env->prog);
  		if (err) {
  			verbose(env, "Failed to properly initialize insn array\n");
@@@ -21249,12 -22360,13 +22389,13 @@@
  
  static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map)
  {
+ 	struct bpf_map *inner = map->inner_map_meta ?: map;
  	int i, err;
  
  	/* check whether we recorded this map already */
- 	for (i = 0; i < env->used_map_cnt; i++)
- 		if (env->used_maps[i] == map)
- 			return i;
+ 	i = bpf_index_find(&env->used_index, (unsigned long)map);
+ 	if (i >= 0)
+ 		return i;
  
  	if (env->signature &&
  	    env->prog->aux->sig.verdict == BPF_SIG_VERIFIED) {
@@@ -21262,16 -22374,17 +22403,17 @@@
  			map->name);
  		return -EACCES;
  	}
- 	if (env->used_map_cnt >= MAX_USED_MAPS) {
- 		verbose(env, "The total number of maps per program has reached the limit of %u\n",
- 			MAX_USED_MAPS);
- 		return -E2BIG;
- 	}
  
  	err = check_map_prog_compatibility(env, map, env->prog);
  	if (err)
  		return err;
  
+ 	if (!bpf_table_next(env->used_maps, env->used_map_cnt) ||
+ 	    bpf_index_add(&env->used_index, (unsigned long)map, env->used_map_cnt))
+ 		return -ENOMEM;
+ 	env->max_key_size = max3(env->max_key_size, map->key_size, inner->key_size);
+ 	env->max_value_size = max3(env->max_value_size, map->value_size, inner->value_size);
+ 
  	if (bpf_prog_runs_sleepable(env->prog))
  		atomic64_inc(&map->sleepable_refcnt);
  
@@@ -21347,6 -22460,31 +22489,31 @@@ static int fd_array_get_map_idx(struct 
  	return -EPROTO;
  }
  
+ static bool is_valid_alu_variant(const struct bpf_insn *insn)
+ {
+ 	switch (BPF_OP(insn->code)) {
+ 	case BPF_MUL:
+ 		return insn->off == 0 || bpf_insn_is_hmul(insn);
+ 	case BPF_DIV:
+ 	case BPF_MOD:
+ 		/* off == 1 selects SDIV/SMOD. */
+ 		return insn->off == 0 || insn->off == 1;
+ 	default:
+ 		return insn->off == 0;
+ 	}
+ }
+ 
+ /* The interpreter supports uhmul and shmul. JITs opt in. */
+ static int check_hmul_jit(struct bpf_verifier_env *env)
+ {
+ 	if (bpf_prog_is_offloaded(env->prog->aux) ||
+ 	    (env->prog->jit_requested && !bpf_jit_supports_hmul())) {
+ 		verbose(env, "JIT doesn't support uhmul and shmul\n");
+ 		return -EOPNOTSUPP;
+ 	}
+ 	return 0;
+ }
+ 
  static int check_alu_fields(struct bpf_verifier_env *env, struct bpf_insn *insn)
  {
  	u8 class = BPF_CLASS(insn->code);
@@@ -21402,18 -22540,14 +22569,14 @@@
  	case BPF_MUL:
  	case BPF_DIV:
  	case BPF_MOD:
- 		if (BPF_SRC(insn->code) == BPF_X) {
- 			if (insn->imm != 0 || (insn->off != 0 && insn->off != 1) ||
- 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
- 				verbose(env, "BPF_ALU uses reserved fields\n");
- 				return -EINVAL;
- 			}
- 		} else if (insn->src_reg != BPF_REG_0 ||
- 			   (insn->off != 0 && insn->off != 1) ||
- 			   (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
+ 		if (!is_valid_alu_variant(insn) ||
+ 		    (BPF_SRC(insn->code) == BPF_X && insn->imm != 0) ||
+ 		    (BPF_SRC(insn->code) == BPF_K && insn->src_reg != BPF_REG_0)) {
  			verbose(env, "BPF_ALU uses reserved fields\n");
  			return -EINVAL;
  		}
+ 		if (bpf_insn_is_hmul(insn))
+ 			return check_hmul_jit(env);
  		return 0;
  	default:
  		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
@@@ -21539,6 -22673,86 +22702,86 @@@ static int check_insn_fields(struct bpf
  	}
  }
  
+ static bool jumps_to_arena_sp_adj(struct bpf_insn *insn)
+ {
+ 	u8 class = BPF_CLASS(insn->code), op = BPF_OP(insn->code);
+ 
+ 	if (class != BPF_JMP && class != BPF_JMP32)
+ 		return false;
+ 	if (op == BPF_CALL || op == BPF_EXIT || insn->code == (BPF_JMP | BPF_JA | BPF_X))
+ 		return false;
+ 	return is_arena_sp_adj(insn + bpf_jmp_offset(insn) + 1);
+ }
+ 
+ /*
+  * Find the insns with BPF_REG_ARENA_SP. The sizes of the frames are in the text
+  * of the program.
+  */
+ static int check_arena_stack(struct bpf_verifier_env *env)
+ {
+ 	struct bpf_subprog_info *sub = env->subprog_info;
+ 	struct bpf_insn *insn = env->prog->insnsi;
+ 	int i;
+ 
+ 	for (i = 0; i < env->prog->len; i++, insn++) {
+ 		if (i == (sub + 1)->start)
+ 			sub++;
+ 		/* it would be executed again */
+ 		if (jumps_to_arena_sp_adj(insn)) {
+ 			verbose(env, "jump to the insn that changes R%d\n", BPF_REG_ARENA_SP);
+ 			return -EINVAL;
+ 		}
+ 		if (!is_arena_sp_insn(insn))
+ 			continue;
+ 		sub->uses_arena_sp = true;
+ 		env->uses_arena_sp = true;
+ 		if (!is_arena_sp_adj(insn))
+ 			continue;
+ 		if (i != sub->start) {
+ 			verbose(env, "R%d can be changed by the first insn of a function only\n",
+ 				BPF_REG_ARENA_SP);
+ 			return -EINVAL;
+ 		}
+ 		if (insn->imm <= 0 || insn->imm % 16 || insn->imm > BPF_ARENA_STACK_MAX) {
+ 			verbose(env, "invalid size of the frame in the stack in arena %d\n",
+ 				insn->imm);
+ 			return -EINVAL;
+ 		}
+ 		sub->arena_stack_depth = insn->imm;
+ 	}
+ 	if (!env->uses_arena_sp)
+ 		return 0;
+ 
+ 	if (!env->prog->aux->arena) {
+ 		verbose(env, "R%d can only be used in a program that has an associated arena\n",
+ 			BPF_REG_ARENA_SP);
+ 		return -EINVAL;
+ 	}
+ 	if (!bpf_jit_supports_arena_stack() || !bpf_jit_supports_percpu_insn() ||
+ 	    bpf_prog_is_offloaded(env->prog->aux)) {
+ 		verbose(env, "JIT doesn't support R%d\n", BPF_REG_ARENA_SP);
+ 		return -EOPNOTSUPP;
+ 	}
+ 	/* bpf_insert_arena_stack() relies on r2-r5 being free when the program starts */
+ 	if (env->prog->type == BPF_PROG_TYPE_EXT) {
+ 		verbose(env, "R%d is not supported in extension programs\n", BPF_REG_ARENA_SP);
+ 		return -EINVAL;
+ 	}
+ 	/*
+ 	 * It ends the function when the offset is out of the packet. bpf_do_misc_fixups()
+ 	 * emits that exit, after bpf_insert_arena_stack(): the frame wouldn't be dropped
+ 	 * and the stack wouldn't be returned.
+ 	 */
+ 	for (i = 0; i < env->subprog_cnt; i++) {
+ 		if (!env->subprog_info[i].has_ld_abs)
+ 			continue;
+ 		verbose(env, "BPF_LD_[ABS|IND] is not allowed in programs that use R%d\n",
+ 			BPF_REG_ARENA_SP);
+ 		return -EINVAL;
+ 	}
+ 	return bpf_arena_stack_init(env->prog->aux->arena);
+ }
+ 
  /*
   * Check that insns are sane and rewrite pseudo imm in ld_imm64 instructions:
   *
@@@ -21559,11 -22773,13 +22802,13 @@@ static int check_and_resolve_insns(stru
  
  	for (i = 0; i < insn_cnt; i++, insn++) {
  		if (insn->dst_reg >= MAX_BPF_REG &&
- 		    !is_stack_arg_st(insn) && !is_stack_arg_stx(insn)) {
+ 		    !is_stack_arg_st(insn) && !is_stack_arg_stx(insn) &&
+ 		    !is_arena_sp_adj(insn) && !is_arena_sp_st(insn)) {
  			verbose(env, "R%d is invalid\n", insn->dst_reg);
  			return -EINVAL;
  		}
- 		if (insn->src_reg >= MAX_BPF_REG && !is_stack_arg_ldx(insn)) {
+ 		if (insn->src_reg >= MAX_BPF_REG && !is_stack_arg_ldx(insn) &&
+ 		    !is_arena_sp_mov(insn) && !is_arena_sp_ldx(insn)) {
  			verbose(env, "R%d is invalid\n", insn->src_reg);
  			return -EINVAL;
  		}
@@@ -21693,29 -22909,11 +22938,11 @@@ next_insn
  	return claim_used_maps(env);
  }
  
- /* that many pointers to functions are recognized in the maps of a program at most */
- #define BPF_MAX_FUNC_PTRS (1 << 20)
- 
  static int add_func_ptr(struct bpf_verifier_env *env, struct bpf_map *map, u32 map_off,
  			u32 xlated_off)
  {
- 	struct bpf_func_ptr *ptrs;
- 
- 	if (env->func_ptr_cnt == BPF_MAX_FUNC_PTRS) {
- 		verbose(env, "too many pointers to functions in maps, the limit is %d\n",
- 			BPF_MAX_FUNC_PTRS);
- 		return -E2BIG;
- 	}
- 
- 	/* grow by doubling, the array is sorted and searched later */
- 	if (!(env->func_ptr_cnt & (env->func_ptr_cnt - 1))) {
- 		ptrs = kvrealloc(env->func_ptrs,
- 				 array_size(max(2 * env->func_ptr_cnt, 16U), sizeof(*ptrs)),
- 				 GFP_KERNEL_ACCOUNT);
- 		if (!ptrs)
- 			return -ENOMEM;
- 		env->func_ptrs = ptrs;
- 	}
+ 	if (!bpf_table_next(env->func_ptrs, env->func_ptr_cnt))
+ 		return -ENOMEM;
  	env->func_ptrs[env->func_ptr_cnt++] = (struct bpf_func_ptr){
  		.map = map,
  		.map_off = map_off,
@@@ -21725,6 -22923,11 +22952,11 @@@
  	return 0;
  }
  
+ static int cmp_maps(const void *a, const void *b)
+ {
+ 	return cmp_int(*(const unsigned long *)a, *(const unsigned long *)b);
+ }
+ 
  /*
   * Compilers put pointers to functions into read-only data: tables of functions,
   * structures of operations, vtables, where they are mixed with other data.
@@@ -21749,17 -22952,24 +22981,24 @@@
   */
  static int resolve_func_ptrs(struct bpf_verifier_env *env)
  {
+ 	struct bpf_map *map, **maps __free(kvfree) = NULL;
  	int insn_cnt = env->prog->len;
  	int i, err, subprog;
- 	struct bpf_map *map;
  	u64 addr, val;
  	u32 off;
  
- 	if (!env->has_callx || !env->allow_ptr_leaks)
+ 	if (!env->has_callx || !env->allow_ptr_leaks || !env->used_map_cnt)
  		return 0;
  
+ 	/* with the maps in order the pointers are in order */
+ 	maps = kvmalloc_objs(*maps, env->used_map_cnt, BPF_VERIFIER_GFP);
+ 	if (!maps)
+ 		return -ENOMEM;
+ 	memcpy(maps, env->used_maps, env->used_map_cnt * sizeof(*maps));
+ 	sort(maps, env->used_map_cnt, sizeof(*maps), cmp_maps, NULL);
+ 
  	for (i = 0; i < env->used_map_cnt; i++) {
- 		map = env->used_maps[i];
+ 		map = maps[i];
  		/* coincidences in maps that are shared with other programs don't matter */
  		if (READ_ONCE(map->user) != (unsigned long)env->prog->aux)
  			continue;
@@@ -21771,8 -22981,8 +23010,8 @@@
  			continue;
  
  		for (off = 0; off + sizeof(u64) <= map->value_size; off += sizeof(u64)) {
- 			if (!(off % SZ_64K))
- 				cond_resched();
+ 			if (bpf_must_abort())
+ 				return -EINTR;
  			val = *(u64 *)(unsigned long)(addr + off);
  			if (!val || val % sizeof(struct bpf_insn) ||
  			    val / sizeof(struct bpf_insn) >= insn_cnt)
@@@ -21785,9 -22995,6 +23024,6 @@@
  				return err;
  		}
  	}
- 	if (env->func_ptr_cnt)
- 		sort(env->func_ptrs, env->func_ptr_cnt, sizeof(*env->func_ptrs),
- 		     cmp_func_ptrs, NULL);
  	return 0;
  }
  
@@@ -21796,12 -23003,14 +23032,14 @@@ static void release_maps(struct bpf_ver
  {
  	__bpf_free_used_maps(env->prog->aux, env->used_maps,
  			     env->used_map_cnt);
+ 	kvfree(env->used_maps);
  }
  
  /* drop refcnt of maps used by the rejected program */
  static void release_btfs(struct bpf_verifier_env *env)
  {
  	__bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
+ 	kvfree(env->used_btfs);
  }
  
  /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
@@@ -21857,45 -23066,20 +23095,20 @@@ static void sanitize_dead_code(struct b
  
  static void free_states(struct bpf_verifier_env *env)
  {
- 	struct bpf_verifier_state_list *sl;
- 	struct list_head *head, *pos, *tmp;
- 	struct bpf_scc_info *info;
- 	int i, j;
- 
- 	bpf_free_verifier_state(env->cur_state, true);
+ 	bpf_free_verifier_state(env, env->cur_state, true);
  	env->cur_state = NULL;
- 	while (!pop_stack(env, NULL, NULL, false));
+ 	free_pushed_states(env);
+ 	bpf_flow_reset(env);
+ }
  
- 	list_for_each_safe(pos, tmp, &env->free_list) {
- 		sl = container_of(pos, struct bpf_verifier_state_list, node);
- 		bpf_free_verifier_state(&sl->state, false);
- 		kfree(sl);
- 	}
- 	INIT_LIST_HEAD(&env->free_list);
+ /* A multiple of the shortest path. It doubles with each pass. A function gets half. */
+ static u64 func_failing_path_budget(struct bpf_verifier_env *env)
+ {
+ 	u64 hops = (bpf_failing_path_hops(env, env->cur_state) + 1ULL) * BPF_COST_STATE;
  
- 	for (i = 0; i < env->scc_cnt; ++i) {
- 		info = env->scc_info[i];
- 		if (!info)
- 			continue;
- 		for (j = 0; j < info->num_visits; j++)
- 			bpf_free_backedges(&info->visits[j]);
- 		kvfree(info);
- 		env->scc_info[i] = NULL;
- 	}
- 
- 	if (!env->explored_states)
- 		return;
- 
- 	for (i = 0; i < state_htab_size(env); i++) {
- 		head = &env->explored_states[i];
- 
- 		list_for_each_safe(pos, tmp, head) {
- 			sl = container_of(pos, struct bpf_verifier_state_list, node);
- 			bpf_free_verifier_state(&sl->state, false);
- 			kfree(sl);
- 		}
- 		INIT_LIST_HEAD(&env->explored_states[i]);
- 	}
+ 	env->failing_path_budget = min(hops << env->failing_path_budget_shift,
+ 				       env->failing_path_budget);
+ 	return env->failing_path_budget / 2;
  }
  
  static int do_check_common(struct bpf_verifier_env *env, int subprog,
@@@ -21911,17 -23095,18 +23124,18 @@@
  	int ret, i;
  
  	env->prev_linfo = NULL;
- 	env->pass_cnt++;
+ 	env->check_cnt++;
  
- 	state = kzalloc_obj(struct bpf_verifier_state, GFP_KERNEL_ACCOUNT);
+ 	state = kzalloc_obj(struct bpf_verifier_state, BPF_VERIFIER_GFP);
  	if (!state)
  		return -ENOMEM;
  	state->curframe = 0;
  	state->speculative = false;
- 	state->branches = 1;
  	state->in_sleepable = context == BPF_FUNC_CTX_SLEEPABLE;
+ 	/* nobody knows what the callers of a global function or of an extension hold */
+ 	state->callers_unknown = subprog || env->prog->type == BPF_PROG_TYPE_EXT;
  	env->no_rcu_read_lock = context == BPF_FUNC_CTX_NO_RCU_LOCK;
- 	state->frame[0] = kzalloc_obj(struct bpf_func_state, GFP_KERNEL_ACCOUNT);
+ 	state->frame[0] = kzalloc_obj(struct bpf_func_state, BPF_VERIFIER_GFP);
  	if (!state->frame[0]) {
  		kfree(state);
  		return -ENOMEM;
@@@ -21931,7 -23116,6 +23145,6 @@@
  			BPF_MAIN_FUNC /* callsite */,
  			0 /* frameno */,
  			subprog);
- 	state->first_insn_idx = env->subprog_info[subprog].start;
  	state->last_insn_idx = -1;
  
  	regs = state->frame[state->curframe]->regs;
@@@ -21983,7 -23167,8 +23196,8 @@@
  				 * Take it for that of an skb, so that a write
  				 * through it and its slices are treated with care.
  				 */
- 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_SKB, true, ++env->id_gen, 0);
+ 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_SKB, true,
+ 						  bpf_new_id(env), 0);
  			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
  				reg->type = PTR_TO_MEM;
  				reg->type |= arg->arg_type &
@@@ -21991,7 -23176,7 +23205,7 @@@
  				mark_reg_known_zero(env, regs, i);
  				reg->mem_size = arg->mem_size;
  				if (arg->arg_type & PTR_MAYBE_NULL)
- 					reg->id = ++env->id_gen;
+ 					reg->id = bpf_new_id(env);
  			} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
  				reg->type = PTR_TO_BTF_ID;
  				if (arg->arg_type & PTR_MAYBE_NULL)
@@@ -22003,7 -23188,7 +23217,7 @@@
  				mark_reg_known_zero(env, regs, i);
  				reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
  				reg->btf_id = arg->btf_id;
- 				reg->id = ++env->id_gen;
+ 				reg->id = bpf_new_id(env);
  			} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
  				/* caller can pass either PTR_TO_ARENA or SCALAR */
  				mark_reg_unknown(env, regs, i);
@@@ -22026,13 -23211,12 +23240,12 @@@
  		 * it's matching expected signature, and otherwise mark BTF
  		 * info for main program as unreliable
  		 */
- 		if (env->prog->aux->func_info_aux) {
+ 		if (env->prog->aux->func_info_aux && !env->prog->aux->func_info_aux[0].unreliable) {
  			ret = btf_prepare_func_args(env, 0);
  			if (ret || sub->arg_slot_cnt != 1 ||
  			    sub->args[0].arg_type != ARG_PTR_TO_CTX) {
  				env->prog->aux->func_info_aux[0].unreliable = true;
  				sub->arg_slot_cnt = 1;
- 				sub->stack_arg_cnt = 0;
  			}
  		}
  
@@@ -22048,18 -23232,23 +23261,23 @@@
  			if (ret < 0)
  				goto out;
  
- 			aux->ctx_arg_info[i].ref_id = ret;
+ 			aux->ctx_arg_info[i].ref_arg = ret ? i + 1 : 0;
+ 			if (ret)
+ 				state->refs[state->acquired_refs - 1].ctx_arg = i + 1;
  		}
  	}
  
+ 	state->insn_idx = sub->start;
+ 	if (env->path_sensitive)
+ 		env->failing_path_max_cost = env->cost + func_failing_path_budget(env);
  	ret = do_check(env);
  out:
+ 	if (ret && !env->err)
+ 		note_error(env, ret);
  	account_current_path(env);
- 	if (!ret) {
- 		if (pop_log)
- 			bpf_vlog_reset(&env->log, 0);
- 		bpf_diag_event_log_restore(env, 0);
- 	}
+ 	if (!ret && pop_log)
+ 		bpf_vlog_reset(&env->log, 0);
+ 	bpf_diag_event_log_restore(env, 0);
  	free_states(env);
  
  	/*
@@@ -22069,7 -23258,7 +23287,7 @@@
  	 * Accumulate their total counts as total counts of the main or
  	 * global subprog hosting the async call.
  	 * Start from the saved total of earlier contexts: adding to the current
- 	 * total would count this pass's synchronous paths twice.
+ 	 * total would count the synchronous paths of this check twice.
  	 */
  	sub->insns_total = old_insns_total + (env->insn_processed - insn_processed);
  	return ret;
@@@ -22160,6 -23349,475 +23378,475 @@@ static int do_check_main(struct bpf_ver
  	return ret;
  }
  
+ /* What a pass writes outside of the states */
+ struct bpf_snapshot {
+ 	struct bpf_env_per_pass env;
+ 	struct bpf_prog_aux aux;
+ 	struct bpf_insn_fixups *insns;
+ 	struct bpf_subprog_info *subprogs;
+ 	struct bpf_func_info_aux *funcs;
+ 	struct bpf_prog prog;
+ };
+ 
+ static void copy_snapshot(struct bpf_verifier_env *env, struct bpf_snapshot *snapshot, bool save)
+ {
+ 	bool has_callchain_buf = env->prog->has_callchain_buf;
+ 	struct bpf_prog_aux *aux = env->prog->aux;
+ 	struct bpf_subprog_info *sub;
+ 	int i;
+ 
+ #define COPY(kept, live)	(save ? ((kept) = (live)) : ((live) = (kept)))
+ #define COPY_AUX(field)		COPY(snapshot->aux.field, aux->field)
+ 	COPY(snapshot->env, env->per_pass);
+ 	COPY(snapshot->prog, *env->prog);
+ 	/* it is taken once */
+ 	env->prog->has_callchain_buf = has_callchain_buf;
+ 	COPY_AUX(max_ctx_offset);
+ 	COPY_AUX(max_pkt_offset);
+ 	COPY_AUX(max_tp_access);
+ 	COPY_AUX(max_rdonly_access);
+ 	COPY_AUX(max_rdwr_access);
+ 	COPY_AUX(min_rdwr_write);
+ 	COPY_AUX(max_rdwr_write);
+ 	COPY_AUX(stack_depth);
+ 	COPY_AUX(tail_call_reachable);
+ 	COPY_AUX(jits_use_priv_stack);
+ 	COPY_AUX(kprobe_write_ctx);
+ 	for (i = 0; i < env->prog->len; i++)
+ 		COPY(snapshot->insns[i], env->insn_aux_data[i].fixups);
+ 	for (i = 0, sub = env->subprog_info; i < env->subprog_cnt; i++, sub++) {
+ 		/* the sum over all passes */
+ 		snapshot->subprogs[i].insns_total = sub->insns_total;
+ 		snapshot->subprogs[i].insns_self = sub->insns_self;
+ 		COPY(snapshot->subprogs[i], *sub);
+ 	}
+ 	for (i = 0; aux->func_info_aux && i < aux->func_info_cnt; i++)
+ 		COPY(snapshot->funcs[i], aux->func_info_aux[i]);
+ #undef COPY_AUX
+ #undef COPY
+ 	bpf_add_cost(env, env->prog->len, BPF_COST_XREG);
+ }
+ 
+ static struct bpf_snapshot *save_snapshot(struct bpf_verifier_env *env,
+ 					  struct bpf_snapshot *snapshot)
+ {
+ 	size_t insns = array_size(env->prog->len, sizeof(*snapshot->insns));
+ 	size_t subprogs = env->subprog_cnt * sizeof(*snapshot->subprogs);
+ 
+ 	if (!snapshot) {
+ 		snapshot = kvmalloc(sizeof(*snapshot) + insns + subprogs +
+ 				    env->prog->aux->func_info_cnt * sizeof(*snapshot->funcs),
+ 				    BPF_VERIFIER_GFP);
+ 		if (!snapshot)
+ 			return NULL;
+ 		env->mem += insns + subprogs;
+ 		snapshot->insns = (void *)(snapshot + 1);
+ 		snapshot->subprogs = (void *)snapshot->insns + insns;
+ 		snapshot->funcs = (void *)snapshot->subprogs + subprogs;
+ 	}
+ 	copy_snapshot(env, snapshot, true);
+ 	return snapshot;
+ }
+ 
+ static void restore_snapshot(struct bpf_verifier_env *env, struct bpf_snapshot *snapshot)
+ {
+ 	copy_snapshot(env, snapshot, false);
+ }
+ 
+ /*
+  * The prologue takes the context from R1, and it can clobber R2-R5. An
+  * extension gets the arguments of the function that it replaces.
+  */
+ static int check_ext_takes_prologue(struct bpf_verifier_env *env)
+ {
+ 	const struct bpf_subprog_info *sub = &env->subprog_info[0];
+ 	int i, cnt = min_t(int, sub->arg_slot_cnt, MAX_BPF_FUNC_REG_ARGS);
+ 	struct bpf_prog *prog = env->prog;
+ 
+ 	if (prog->type != BPF_PROG_TYPE_EXT || !env->ops->gen_prologue ||
+ 	    !env->ops->gen_prologue(env->insn_buf, env->seen_direct_write, prog))
+ 		return 0;
+ 	for (i = 0; i < cnt; i++)
+ 		if (sub->args[i].arg_type != (i ? ARG_SCALAR : ARG_PTR_TO_CTX))
+ 			break;
+ 	if (!cnt || i < cnt) {
+ 		verbose(env, "Extension writing packet data must take ctx and scalars only\n");
+ 		return -EINVAL;
+ 	}
+ 	if (bpf_check_ext_prologue(&env->log, prog->aux->dst_prog, prog->aux->attach_btf_id))
+ 		return -EINVAL;
+ 	return 0;
+ }
+ 
+ /* What the pass found about functions and about the program has to be consistent */
+ static int check_after_pass(struct bpf_verifier_env *env)
+ {
+ 	struct bpf_subprog_info *sub = env->subprog_info;
+ 	u16 outgoing;
+ 	int i, err;
+ 
+ 	err = check_max_stack_depth(env) ?: check_ext_takes_prologue(env);
+ 	if (err)
+ 		return err;
+ 	for (i = 0; i < env->subprog_cnt; i++, sub++) {
+ 		/* the caller would get r12 of the callee back */
+ 		if (env->uses_arena_sp && (!i || sub->arena_stack_entry) && sub->is_called) {
+ 			verbose(env, "%s() uses R%d and is both called and a callback\n",
+ 				bpf_subprog_name(env, i), BPF_REG_ARENA_SP);
+ 			return -EINVAL;
+ 		}
+ 		outgoing = sub->stack_arg_cnt - bpf_in_stack_arg_cnt(sub);
+ 		if (sub->max_out_stack_arg_cnt > outgoing) {
+ 			verbose(env,
+ 				"func#%d writes %u stack arg slots, but calls only require %u\n",
+ 				i, sub->max_out_stack_arg_cnt, outgoing);
+ 			return -EINVAL;
+ 		}
+ 	}
+ 	return 0;
+ }
+ 
+ /* Returns the first error */
+ static int check_funcs(struct bpf_verifier_env *env, struct bpf_snapshot *initial)
+ {
+ 	u32 level = env->log.level;
+ 	int ret;
+ 
+ 	restore_snapshot(env, initial);
+ 	kvfree(env->callx_edges);
+ 	kvfree(env->callx_index.slots);
+ 	env->callx_edges = NULL;
+ 	env->callx_index = (struct bpf_index){};
+ 	bpf_flow_new_pass(env);
+ 	ret = do_check_main(env) ?: do_check_subprogs(env) ?: bpf_check_limits(env);
+ 	env->log.level = level;
+ 	env->pass_max_cost = U64_MAX;
+ 	return ret == -EINTR ? ret : env->err ?: ret;
+ }
+ 
+ static int check_pass(struct bpf_verifier_env *env, struct bpf_snapshot *initial)
+ {
+ 	int ret;
+ 
+ 	if (env->pass && (env->log.level & BPF_LOG_LEVEL2))
+ 		verbose(env, "pass %u\n", env->pass);
+ 	bpf_precision_new_pass(env);
+ 	ret = check_funcs(env, initial);
+ 	if (ret || pass_needs_restart(env))
+ 		return ret;
+ 	ret = check_after_pass(env);
+ 	if (ret)
+ 		bpf_find_unproven_after_pass(env);
+ 	env->err = ret;
+ 	return ret;
+ }
+ 
+ /*
+  * If the error of a pass is real, do_check_all() limits the next passes and logs a path to it.
+  * To see if it is real, reproduce it with no joins. Check one path after another, depth first
+  * from the entry of the function, until the check of an insn in err_insns fails:
+  * - there are no joins, a call stays in the instance of its caller, each trip is peeled
+  * - a state is dropped if a state with the same values in the deps was at the insn
+  * - only a loop that is found to be infinite gets may_goto, see failing_path_trip()
+  * That path is the failing path. The run accepts nothing. It is not the verdict: a path has
+  * ranges too, and a check can fail on it where the joined state is proven.
+  * run_has_guess: the run made a guess, on any of its paths. Then the failing path can be false,
+  * see fast_forward_trips() and check_loop_guard().
+  * @repeat: see log_failing_path()
+  * Returns the error on the path, 0 if there is none.
+  */
+ static int run_path_sensitive(struct bpf_verifier_env *env, struct bpf_snapshot *initial,
+ 			      bool repeat)
+ {
+ 	u64 budget = env->failing_path_budget;
+ 	int ret;
+ 
+ 	env->path_sensitive = true;
+ 	env->run_has_guess = false;
+ 	env->err = 0;
+ 	ret = bpf_failing_path_prepare(env, repeat) ?: check_funcs(env, initial);
+ 	env->path_sensitive = false;
+ 	/* for the repeat */
+ 	if (env->err)
+ 		env->failing_path_budget = budget;
+ 	if (env->err && env->run_has_guess)
+ 		verbose(env, "this path has a guess, its values can be wrong\n");
+ 	return ret == -EINTR ? ret : env->err;
+ }
+ 
+ /*
+  * The path-sensitive runs, in their order:
+  *
+  *	trips of a loop without a trip count	1, any number, 3, 7, ...
+  *	which edge goes first			the shortest path; if over budget, the fall-through
+  *
+  * A function gets half of the budget that is left. @last: the budget is twice the cost so far.
+  */
+ static int find_failing_path(struct bpf_verifier_env *env, struct bpf_snapshot *initial, bool last)
+ {
+ 	u32 trips;
+ 	u64 start;
+ 	int ret;
+ 
+ 	if (env->log.level & BPF_LOG_LEVEL2)
+ 		verbose(env, "path-sensitive run after pass %u\n", env->pass);
+ 	env->failing_path_budget_shift = last ? 20 : min(env->pass + 3, 20);
+ 	env->failing_path_budget = last ? 2 * env->cost : bpf_precision_budget(env) / 4;
+ 	env->failing_path_max_trips = trips = 1;
+ 	env->fallthrough_first = false;
+ 	for (;;) {
+ 		start = env->cost;
+ 		ret = run_path_sensitive(env, initial, false);
+ 		if (ret || env->over_limit || env->bug ||
+ 		    env->cost - start >= env->failing_path_budget)
+ 			return ret;
+ 		env->failing_path_budget -= env->cost - start;
+ 		env->fallthrough_first = !env->fallthrough_first && env->run_over_budget;
+ 		if (env->fallthrough_first)
+ 			continue;
+ 		if (env->no_mem || (!env->run_over_budget && !env->too_deep))
+ 			return 0;
+ 		if (env->failing_path_max_trips == 1)
+ 			env->failing_path_max_trips = U32_MAX;
+ 		else
+ 			env->failing_path_max_trips = trips = 2 * trips + 1;
+ 	}
+ }
+ 
+ /* Level 2 has the log of all passes. Else the log has one pass, or the failing path. */
+ struct pass_log {
+ 	u32 level, len_max;
+ 	u64 pos;
+ };
+ 
+ static void restart_log(struct bpf_verifier_env *env, struct pass_log *log)
+ {
+ 	env->log.level = log->level;
+ 	/* the log is dropped when a function is found to be safe */
+ 	log->pos = min(log->pos, env->log.end_pos);
+ 	if (log->level & BPF_LOG_LEVEL2)
+ 		return;
+ 	bpf_vlog_reset(&env->log, log->pos);
+ 	env->log.len_max = log->len_max;
+ }
+ 
+ /* Repeat the last run. The verdict does not depend on the log, so it has no cost. */
+ static int log_failing_path(struct bpf_verifier_env *env, struct bpf_snapshot *initial,
+ 			    struct pass_log *log)
+ {
+ 	u32 insns = env->insn_processed, states = env->total_states;
+ 	u64 cost = env->cost;
+ 	int i, ret;
+ 
+ 	restart_log(env, log);
+ 	ret = run_path_sensitive(env, initial, true);
+ 	env->log.level = 0;
+ 	env->cost = cost;
+ 	env->insn_processed = insns;
+ 	env->total_states = states;
+ 	/* @initial has the sums from before the run, see copy_snapshot() */
+ 	for (i = 0; i < env->subprog_cnt; i++) {
+ 		env->subprog_info[i].insns_total = initial->subprogs[i].insns_total;
+ 		env->subprog_info[i].insns_self = initial->subprogs[i].insns_self;
+ 	}
+ 	return ret;
+ }
+ 
+ /*
+  *          pass 0: join all numbers
+  *                    |
+  *    +---------> run a pass
+  *    |               |
+  *    |            error ? --- no ---> pessimized ? --- no ---> ACCEPT
+  *    |               | yes                 | yes
+  *    |               v                     v
+  *    |       good pass before ?      save the good pass,
+  *    |          | no      | yes      partition, cut the budget
+  *    |          |         v                |
+  *    |          |   ACCEPT, use that pass  +---> run a pass
+  *    |          v
+  *    |      partition
+  *    |          |
+  *    |  failing path ? --- yes ---> log it; if no guess, cut the budget
+  *    |          | no                       |
+  *    |          +<-------------------------+
+  *    |          v
+  *    +- yes - is more kept apart ? --- no ---> REJECT
+  *
+  * Each pass starts from the snapshot @initial. The good pass is in the snapshot @good_pass.
+  * The path-sensitive run needs the deps, so it comes after the partition.
+  * There is no more precision when the budget is used up, or when no state was imprecise.
+  *
+  * A pass assumes what stops each loop, and checks it, see pass_needs_restart(). If the
+  * assumption is wrong, the pass starts again.
+  *
+  * The log has the failing path. If there is none, or if it has a guess and the error of a pass
+  * is real, the log has the basic block of an error. Below level 2 the later passes and the
+  * path-sensitive runs write no log. The one that gives the log runs once more.
+  */
+ static int do_check_all(struct bpf_verifier_env *env)
+ {
+ 	bool offload = bpf_prog_is_offloaded(env->prog->aux), limit = false, last, replay;
+ 	struct pass_log log = { env->log.level, env->log.len_max, env->log.end_pos };
+ 	bool quiet = log.level && !(log.level & BPF_LOG_LEVEL2), logged = false, replayed = false;
+ 	struct bpf_snapshot *initial, *good_pass = NULL;
+ 	int ret, more, path_err = 0, err = 0;
+ 	bool guess = false, real;
+ 	u64 max_cost = 0;
+ 
+ 	initial = save_snapshot(env, NULL);
+ 	if (!initial || bpf_precision_init(env)) {
+ 		bpf_precision_free(env);
+ 		kvfree(initial);
+ 		return -ENOMEM;
+ 	}
+ 	env->max_mem = min(env->max_mem, env->mem + BPF_PASS_MEM_BASE +
+ 			   (u64)BPF_PASS_MEM_PER_INSN * env->prog->len);
+ 	for (;; env->pass += !env->for_log) {
+ 		if (!env->pass || !quiet)
+ 			restart_log(env, &log);
+ 		ret = check_pass(env, initial);
+ 		if (quiet)
+ 			env->log.level = 0;
+ 		replay = env->replay;
+ 		env->replay = false;
+ 		if (ret == -EINTR || env->bug || env->no_mem) {
+ 			err = ret;
+ 			break;
+ 		}
+ 		more = bpf_undo_precision(env);
+ 		if (more > 0)
+ 			continue;
+ 		if (more == -ENOMEM && !good_pass) {
+ 			err = more;
+ 			break;
+ 		}
+ 		if (ret && good_pass) {
+ 			restore_snapshot(env, good_pass);
+ 			err = 0;
+ 			if (!offload)
+ 				break;
+ 			bpf_restore_precision(env);
+ 		} else if (!ret) {
+ 			bpf_flow_drop_guards(env);
+ 			if (pass_needs_restart(env))
+ 				continue;
+ 			if (env->for_log && (!offload || replay))
+ 				break;
+ 			max_cost = good_pass ? max_cost : env->max_cost;
+ 			if (!replayed && !env->for_log && bpf_partition_for_pessimized(env) > 0) {
+ 				env->max_cost = min(env->max_cost, env->cost + BPF_MIN_BUDGET);
+ 				good_pass = save_snapshot(env, good_pass);
+ 				if (good_pass)
+ 					continue;
+ 			}
+ 			if (!offload || replay) {
+ 				err = 0;
+ 				break;
+ 			}
+ 		}
+ 		if (!ret || good_pass) {
+ 			/* The driver sees a pass without errors. It can refuse an insn. */
+ 			kvfree(good_pass);
+ 			good_pass = NULL;
+ 			env->max_cost = max_cost;
+ 			env->replay = replayed = true;
+ 			ret = bpf_prog_offload_verifier_prep(env->prog);
+ 			if (!ret)
+ 				continue;
+ 			err = ret;
+ 			break;
+ 		}
+ 		if (env->for_log)
+ 			break;
+ 		err = path_err ?: ret;
+ 		limit = !env->err;
+ 		if (limit)
+ 			goto reject;
+ 		/* a valid program that no precision can prove must not use up the limit */
+ 		env->max_cost = min(env->max_cost, max(2 * env->cost, BPF_PARTITION_BUDGET));
+ 		last = real = !env->imprecise;
+ 		more = bpf_partition_more(env);
+ 		if (more < 0 && more != -E2BIG)
+ 			err = more;
+ 		limit = more < 0;
+ 		last |= more != 1;
+ 		if (!limit && !path_err && (last || bpf_failing_path_is_due(env))) {
+ 			path_err = find_failing_path(env, initial, last);
+ 			if (path_err) {
+ 				err = path_err;
+ 				guess = env->run_has_guess;
+ 				logged = quiet && log_failing_path(env, initial, &log) == err;
+ 			}
+ 			if (path_err && !guess)
+ 				env->max_cost = min(env->max_cost, env->cost +
+ 						    2 * bpf_precision_first_budget(env));
+ 		}
+ 		if (real && guess && err == path_err && err != -EINTR) {
+ 			err = ret;
+ 			logged = false;
+ 		}
+ 		if (err == -EINTR || env->bug)
+ 			break;
+ 		if (!last)
+ 			continue;
+ reject:
+ 		if (logged || !quiet || (limit && !env->pass))
+ 			break;
+ 		/* Run a pass with an error once more, for the log. It has a limit of its own. */
+ 		env->for_log = true;
+ 		quiet = false;
+ 		env->max_cost = 2 * env->cost;
+ 	}
+ 	env->log.level = log.level;
+ 	/* after an abort the error and the log can be wrong */
+ 	if (err && env->aborted)
+ 		err = -EINTR;
+ 	if (env->bug)
+ 		err = -EFAULT;
+ 	if (!err)
+ 		restart_log(env, &log);
+ 	if (err && (!path_err || guess) && (limit || (env->for_log && !env->err)))
+ 		verbose(env, "the limit on cost or memory ended pass %u\n", env->pass);
+ 	if (!err && env->sleepable_async_cb)
+ 		mark_sleepable_async_cb(env);
+ 	bpf_precision_free(env);
+ 	kvfree(initial);
+ 	kvfree(good_pass);
+ 	return err;
+ }
+ 
+ /*
+  * What it took to verify a static subprog on its own is not in insns_total of its callers.
+  * Add it, once per caller. The main prog and global subprogs have all of it already.
+  */
+ static void add_insns_of_callees(struct bpf_verifier_env *env)
+ {
+ 	struct bpf_subprog_info *si = env->subprog_info;
+ 	struct bpf_insn *insn = env->prog->insnsi;
+ 	int *added, i, j, s, c;
+ 
+ 	added = kvcalloc(env->subprog_cnt, sizeof(*added), BPF_VERIFIER_GFP);
+ 	if (!added)
+ 		return;
+ 	/* callees first */
+ 	for (i = 0; i < env->subprog_cnt; i++) {
+ 		s = env->subprog_topo_order[i];
+ 		if (!s || bpf_subprog_is_global(env, s))
+ 			continue;
+ 		for (j = si[s].start; j < si[s + 1].start; j++) {
+ 			if (!bpf_pseudo_call(&insn[j]))
+ 				continue;
+ 			c = bpf_find_subprog(env, j + insn[j].imm + 1);
+ 			if (c <= 0 || c == s || !si[c].on_its_own || added[c] == s)
+ 				continue;
+ 			added[c] = s;
+ 			si[s].insns_total += si[c].insns_total;
+ 		}
+ 	}
+ 	kvfree(added);
+ }
+ 
  static void print_verification_stats(struct bpf_verifier_env *env)
  {
  	/* Skip over hidden subprogs which are not verified. */
@@@ -22183,17 -23841,18 +23870,18 @@@
  				env->subprog_info[i].stack_depth);
  		}
  	}
- 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
- 		"total_states %d peak_states %d mark_read %d\n",
- 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
+ 	/* user space parses this line. There is no limit and there are no read marks. */
+ 	verbose(env, "processed %d insns (limit 0) max_states_per_insn %d "
+ 		"total_states %d peak_states %d mark_read 0\n",
+ 		env->insn_processed,
  		env->max_states_per_insn, env->total_states,
- 		env->peak_states, env->longest_mark_read_walk);
+ 		env->peak_states);
  }
  
  int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog,
  			       const struct bpf_ctx_arg_aux *info, u32 cnt)
  {
- 	prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT);
+ 	prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), BPF_VERIFIER_GFP);
  	prog->aux->ctx_arg_info_size = cnt;
  
  	return prog->aux->ctx_arg_info ? 0 : -ENOMEM;
@@@ -22312,6 -23971,12 +24000,12 @@@ static int check_struct_ops_btf_id(stru
  		}
  	}
  
+ 	/* A run that gets no stack in arena is skipped. Nobody would release the argument. */
+ 	if (has_refcounted_arg && env->uses_arena_sp) {
+ 		verbose(env, "program with __ref argument cannot use R%d\n", BPF_REG_ARENA_SP);
+ 		return -EINVAL;
+ 	}
+ 
  	prog->aux->st_ops = st_ops;
  	prog->aux->attach_st_ops_member_off = member_off;
  
@@@ -22553,33 -24218,6 +24247,6 @@@ static int flatten_bpf_func_model(struc
  	return 0;
  }
  
- /*
-  * The verifier lets a static function use stack arguments counted from its
-  * BTF, even if that BTF turns out unreliable. A trampoline on the function is
-  * then given only MAX_BPF_FUNC_REG_ARGS u64 arguments and would lose the
-  * stack arguments, so such a function cannot be attached to.
-  */
- static int check_unreliable_func_args(struct bpf_verifier_log *log, struct btf *btf,
- 				      const struct btf_type *func_proto, const char *tname)
- {
- 	struct btf_func_model m;
- 	u32 i, nslots = 0;
- 
- 	if (btf_distill_func_proto(NULL, btf, func_proto, tname, &m)) {
- 		/* at least a slot for each argument */
- 		nslots = btf_type_vlen(func_proto);
- 	} else {
- 		for (i = 0; i < m.nr_args; i++)
- 			nslots += btf_func_model_arg_slots(&m, i);
- 	}
- 	if (nslots <= MAX_BPF_FUNC_REG_ARGS)
- 		return 0;
- 
- 	bpf_log(log, "Cannot attach to static function %s: unreliable BTF and stack arguments\n",
- 		tname);
- 	return -EINVAL;
- }
- 
  /* Functions may share a type id. The first of them is attached to. */
  static int find_tgt_subprog(const struct bpf_prog *tgt_prog, u32 btf_id)
  {
@@@ -22702,7 -24340,6 +24369,7 @@@ int bpf_check_attach_target(struct bpf_
  	}
  	if (tgt_prog) {
  		struct bpf_prog_aux *aux = tgt_prog->aux;
 +		enum bpf_cgroup_storage_type stype;
  		bool tgt_changes_pkt_data;
  		bool tgt_might_sleep;
  		bool tgt_can_unwind;
@@@ -22728,6 -24365,12 +24395,12 @@@
  			bpf_log(log, "Cannot attach to a target with arena context arguments\n");
  			return -EOPNOTSUPP;
  		}
+ 		/* x86: the trampoline and the extension don't preserve BPF_REG_ARENA_SP */
+ 		if (subprog && aux->arena_stack_size) {
+ 			bpf_log(log, "Cannot attach to a subprog of a program that uses R%d\n",
+ 				BPF_REG_ARENA_SP);
+ 			return -EOPNOTSUPP;
+ 		}
  		if (aux->func && aux->func[subprog]->aux->exception_cb) {
  			bpf_log(log,
  				"%s programs cannot attach to exception callback\n",
@@@ -22744,6 -24387,11 +24417,11 @@@
  			bpf_log(log, "Only fentry can attach to %s, which can unwind\n", tname);
  			return -EINVAL;
  		}
+ 		/* What it takes of the stack is not counted, see bpf_insert_recursion_checks() */
+ 		if (aux->func && aux->func[subprog]->aux->in_recursion) {
+ 			bpf_log(log, "Cannot attach to %s, which is called in a recursion\n", tname);
+ 			return -EINVAL;
+ 		}
  		conservative = aux->func_info_aux[subprog].unreliable;
  		if (prog_extension) {
  			if (aux->func_info_aux[subprog].linkage != BTF_FUNC_GLOBAL ||
@@@ -22757,16 -24405,6 +24435,16 @@@
  					"Extension programs should be JITed\n");
  				return -EINVAL;
  			}
 +			/* bpf_get_local_storage() returns the storage of the target */
 +			for_each_cgroup_storage_type(stype) {
 +				struct bpf_map *storage = prog->aux->cgroup_storage[stype];
 +
 +				if (storage && storage != aux->cgroup_storage[stype]) {
 +					bpf_log(log,
 +						"Extension program has another cgroup storage than original\n");
 +					return -EINVAL;
 +				}
 +			}
  			/*
  			 * How much of the buffer of the tracepoint is used
  			 * is checked for the program that is attached to it.
@@@ -22831,14 -24469,16 +24509,14 @@@
  			bpf_log(log, "Cannot recursively attach\n");
  			return -EINVAL;
  		}
 -		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
 -		    prog_extension &&
 -		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
 -		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT ||
 -		     tgt_prog->expected_attach_type == BPF_TRACE_FENTRY_MULTI ||
 -		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT_MULTI ||
 -		     tgt_prog->expected_attach_type == BPF_TRACE_FSESSION ||
 -		     tgt_prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) {
 -			/* Program extensions can extend all program types
 -			 * except fentry/fexit. The reason is the following.
 +		if (prog_extension &&
 +		    (tgt_prog->type == BPF_PROG_TYPE_TRACING ||
 +		     tgt_prog->type == BPF_PROG_TYPE_LSM ||
 +		     tgt_prog->type == BPF_PROG_TYPE_STRUCT_OPS)) {
 +			/*
 +			 * These types are checked against the BTF of their hook,
 +			 * and an extension has the BTF of its target instead.
 +			 * There is one more reason for fentry/fexit.
  			 * The fentry/fexit programs are used for performance
  			 * analysis, stats and can be attached to any program
  			 * type. When extension program is replacing XDP function
@@@ -22851,7 -24491,7 +24529,7 @@@
  			 * beyond reasonable stack size. Hence extending fentry
  			 * is not allowed.
  			 */
 -			bpf_log(log, "Cannot extend fentry/fexit/fsession\n");
 +			bpf_log(log, "Cannot extend tracing, LSM and struct_ops programs\n");
  			return -EINVAL;
  		}
  	} else {
@@@ -22970,10 -24610,16 +24648,16 @@@
  			return -EINVAL;
  
  		if (tgt_prog && conservative) {
- 			if (subprog > 0) {
- 				ret = check_unreliable_func_args(log, btf, t, tname);
- 				if (ret)
- 					return ret;
+ 			/*
+ 			 * The verifier lets a static function use the stack arguments that
+ 			 * its code loads, whatever its BTF says. The trampoline is given
+ 			 * MAX_BPF_FUNC_REG_ARGS u64 arguments and would lose them.
+ 			 */
+ 			if (tgt_prog->aux->func_info_aux[subprog].stack_args) {
+ 				bpf_log(log,
+ 					"Cannot attach to static function %s: unreliable BTF and stack arguments\n",
+ 					tname);
+ 				return -EINVAL;
  			}
  			t = NULL;
  		}
@@@ -22987,7 -24633,9 +24671,9 @@@
  				return ret;
  		}
  
- 		if (tgt_info->fmodel.ret_size > 8 &&
+ 		/* The model for unreliable BTF has a u64. The function still returns R0:R2. */
+ 		if ((tgt_info->fmodel.ret_size > 8 ||
+ 		     (tgt_prog && tgt_prog->aux->func_info_aux[subprog].ret_reg_pair)) &&
  		    attach_uses_trampoline_retval(prog->expected_attach_type)) {
  			bpf_log(log,
  				"Attach to function %s with a >8 byte return value is not supported for this attach type\n",
@@@ -23047,6 -24695,13 +24733,13 @@@
  			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
  			    !check_attach_modify_return(addr, tname))
  				ret = 0;
+ 			if (ret) {
+ 				/* Nobody declared it as a target. Has the build tagged it? */
+ 				tgt_info->fmodret_retvals =
+ 					btf_find_func_tag_value(btf, btf_id, "bpf_fmodret_retval:");
+ 				if (tgt_info->fmodret_retvals)
+ 					ret = 0;
+ 			}
  			if (ret) {
  				module_put(mod);
  				bpf_log(log, "%s() is not modifiable\n", tname);
@@@ -23199,13 -24854,10 +24892,13 @@@ static int check_attach_btf_id(struct b
  		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
  	}
  
 -	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
 +	/* An extension has expected_attach_type of its target, it can be any value */
 +	if (prog->type != BPF_PROG_TYPE_EXT &&
 +	    prog->expected_attach_type == BPF_TRACE_RAW_TP) {
  		prog->aux->attach_btf_trace = true;
  		return 0;
 -	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
 +	} else if (prog->type != BPF_PROG_TYPE_EXT &&
 +		   prog->expected_attach_type == BPF_TRACE_ITER) {
  		return bpf_iter_prog_supported(prog);
  	}
  
@@@ -23228,6 -24880,11 +24921,11 @@@
  		return -EINVAL;
  	}
  
+ 	env->fmodret_retvals = tgt_info.fmodret_retvals;
+ 	/* The interpreter returns only 32 bits */
+ 	if (env->fmodret_retvals && tgt_info.fmodel.ret_size == 8)
+ 		prog->jit_required = 1;
+ 
  	/*
  	 * We don't get trampoline for tracing_multi programs at this point,
  	 * it's done when tracing_multi link is created.
@@@ -23363,39 -25020,31 +25061,31 @@@ static int add_fd_from_fd_array(struct 
  	return PTR_ERR(map);
  }
  
- /*
-  * A continuous fd_array is resolved into an in-memory cache with one slot
-  * per entry. The bound here is deliberately generous and not derived from
-  * the per-program object limits: Duplicate entries /are/ permitted, and
-  * the number of distinct maps and BTFs a program can bind is enforced when
-  * each entry is resolved by __add_used_map() and __add_used_btf().
-  */
- #define MAX_FD_ARRAY_CNT 4096
- 
+ /* A continuous fd_array is resolved into an in-memory cache with one slot per entry. */
  static int process_fd_array_continuous(struct bpf_verifier_env *env,
  				       bpfptr_t fd_array, u32 cnt)
  {
  	int fd, ret;
  	u32 i;
  
- 	if (cnt > MAX_FD_ARRAY_CNT) {
- 		verbose(env, "fd_array has too many entries (%u, max %u)\n",
- 			cnt, MAX_FD_ARRAY_CNT);
+ 	if (!env->bpf_capable && cnt > BPF_MAXINSNS) {
+ 		verbose(env, "fd_array has too many entries (%u, max %u)\n", cnt, BPF_MAXINSNS);
  		return -E2BIG;
  	}
  
- 	env->fd_array = kvzalloc_objs(*env->fd_array, cnt, GFP_KERNEL_ACCOUNT);
- 	if (!env->fd_array)
- 		return -ENOMEM;
- 	env->fd_array_cnt = cnt;
  	for (i = 0; i < cnt; i++) {
+ 		if (bpf_must_abort())
+ 			return -EINTR;
  		if (copy_from_bpfptr_offset(&fd, fd_array,
  					    (size_t)i * sizeof(fd), sizeof(fd)))
  			return -EFAULT;
+ 		if (!bpf_table_next(env->fd_array, i))
+ 			return -ENOMEM;
  		ret = add_fd_from_fd_array(env, i, fd);
  		if (ret)
  			return ret;
  	}
+ 	env->fd_array_cnt = cnt;
  	return 0;
  }
  
@@@ -23474,64 -25123,21 +25164,21 @@@ static int specialize_kfunc(struct bpf_
  	return 0;
  }
  
- static int add_kfunc_desc_target(struct bpf_verifier_env *env,
- 				 const struct bpf_kfunc_desc *target_desc,
- 				 u16 base_desc_idx, u16 *desc_idx)
+ /* A kfunc has at most one specialized target. Returns the index of its descriptor. */
+ static int add_specialized_kfunc(struct bpf_verifier_env *env, const struct bpf_kfunc_desc *desc)
  {
- 	struct bpf_kfunc_desc desc = *target_desc;
- 	struct bpf_kfunc_desc_tab *new_tab;
- 	struct bpf_kfunc_desc_tab *tab;
- 	struct bpf_prog_aux *prog_aux;
- 	u32 i;
+ 	struct bpf_kfunc_desc_tab *tab = env->prog->aux->kfunc_tab;
+ 	u64 key = kfunc_key(desc->func_id, desc->offset, true);
+ 	int i = bpf_index_find(&env->kfunc_index, key);
  
- 	prog_aux = env->prog->aux;
- 	tab = prog_aux->kfunc_tab;
- 
- 	if (base_desc_idx >= tab->nr_base_descs) {
- 		verifier_bug(env, "kfunc desc_idx %d out of bounds (%d descriptors)",
- 				base_desc_idx, tab->nr_base_descs);
- 		return -EFAULT;
- 	}
- 	if (tab->descs[base_desc_idx].func_id != desc.func_id) {
- 		verifier_bug(env, "kfunc desc %d has invalid id (expected %d, got %d)",
- 				base_desc_idx, tab->descs[base_desc_idx].func_id, desc.func_id);
- 		return -EFAULT;
- 	}
- 	if (tab->descs[base_desc_idx].offset != desc.offset) {
- 		verifier_bug(env, "kfunc desc %d has invalid offset (expected %d, got %d)",
- 				base_desc_idx, tab->descs[base_desc_idx].offset, desc.offset);
- 		return -EFAULT;
- 	}
- 
- 	if (tab->descs[base_desc_idx].addr == desc.addr) {
- 		*desc_idx = base_desc_idx;
- 		return 0;
- 	}
- 
- 	for (i = tab->nr_base_descs; i < tab->nr_descs; i++) {
- 		if (tab->descs[i].func_id == desc.func_id &&
- 		    tab->descs[i].offset == desc.offset &&
- 		    tab->descs[i].addr == desc.addr) {
- 			*desc_idx = i;
- 			return 0;
- 		}
- 	}
- 
- 	if (tab->nr_descs == MAX_KFUNC_CALL_DESCS) {
- 		verbose(env, "too many different kernel function call targets\n");
- 		return -E2BIG;
- 	}
- 
- 	new_tab = krealloc(tab, struct_size(tab, descs, tab->nr_descs + 1),
- 			   GFP_KERNEL_ACCOUNT);
- 	if (!new_tab)
+ 	if (i >= 0)
+ 		return verifier_bug_if(tab->descs[i].addr != desc->addr, env,
+ 				       "two targets of kfunc %u", desc->func_id) ? -EFAULT : i;
+ 	if (!bpf_table_next(tab->descs, tab->nr_descs) ||
+ 	    bpf_index_add(&env->kfunc_index, key, tab->nr_descs))
  		return -ENOMEM;
- 	tab = new_tab;
- 	prog_aux->kfunc_tab = tab;
- 
- 	*desc_idx = tab->nr_descs;
- 	tab->descs[tab->nr_descs++] = desc;
- 	return 0;
+ 	tab->descs[tab->nr_descs] = *desc;
+ 	return tab->nr_descs++;
  }
  
  static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
@@@ -23557,14 -25163,8 +25204,8 @@@ int bpf_fixup_kfunc_call(struct bpf_ver
  	struct bpf_kfunc_desc desc_copy;
  	struct bpf_kfunc_desc *desc;
  	unsigned long call_imm;
- 	u16 base_desc_idx, desc_idx;
+ 	int err, desc_idx;
  	bool near_call;
- 	int err;
- 
- 	if (!insn->imm) {
- 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
- 		return -EINVAL;
- 	}
  
  	*cnt = 0;
  
@@@ -23572,13 -25172,13 +25213,13 @@@
  	 * __bpf_call_base, unless the JIT needs to call functions that are
  	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
  	 */
- 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
+ 	desc = find_kfunc_desc(env, insn->imm, insn->off);
  	if (!desc) {
  		verifier_bug(env, "kernel function descriptor not found for func_id %u",
  			     insn->imm);
  		return -EFAULT;
  	}
- 	base_desc_idx = desc - env->prog->aux->kfunc_tab->descs;
+ 	desc_idx = desc - env->prog->aux->kfunc_tab->descs;
  
  	near_call = !bpf_jit_supports_far_kfunc_call();
  	desc_copy = *desc;
@@@ -23598,9 -25198,15 +25239,15 @@@
  		insn->imm = call_imm;
  	}
  
- 	err = add_kfunc_desc_target(env, desc, base_desc_idx, &desc_idx);
- 	if (err)
- 		return err;
+ 	if (desc->addr != env->prog->aux->kfunc_tab->descs[desc_idx].addr)
+ 		desc_idx = add_specialized_kfunc(env, desc);
+ 	if (desc_idx < 0)
+ 		return desc_idx;
+ 	/* JITs find the descriptor by insn->off */
+ 	if (desc_idx > U16_MAX) {
+ 		verbose(env, "too many different kernel function calls\n");
+ 		return -E2BIG;
+ 	}
  	insn->off = desc_idx;
  
  	if (is_bpf_obj_new_kfunc(desc->func_id) || is_bpf_percpu_obj_new_kfunc(desc->func_id)) {
@@@ -23877,13 -25483,6 +25524,13 @@@ static int bpf_prog_verify_signature(st
  			err = -EPERM;
  			goto out;
  		}
 +		/* The freeze is not final for it, see bpf_map_mmap() */
 +		if ((map->map_flags & BPF_F_MMAPABLE) && !(map->map_flags & BPF_F_RDONLY_PROG)) {
 +			verbose(env, "signed program metadata map '%s' must not be mmapable\n",
 +				map->name);
 +			err = -EPERM;
 +			goto out;
 +		}
  		data_sz += map->value_size;
  	}
  	if (bpf_dynptr_check_size(data_sz)) {
@@@ -23891,7 -25490,7 +25538,7 @@@
  		err = -E2BIG;
  		goto out;
  	}
- 	data = kvmalloc(data_sz, GFP_KERNEL_ACCOUNT | __GFP_ZERO);
+ 	data = kvmalloc(data_sz, BPF_VERIFIER_GFP | __GFP_ZERO);
  	if (!data) {
  		err = -ENOMEM;
  		goto out;
@@@ -23963,13 -25562,9 +25610,9 @@@ static void log_program(struct bpf_veri
  	u64 pos, insn_pos;
  	u32 i, j;
  
- 	verbose(env, "Program dump (scc? loop_header? idom insn#: live_regs_before):\n");
+ 	verbose(env, "Program dump (loop_header? idom insn#: live_regs_before):\n");
  	for (i = 0; i < insn_cnt; ++i) {
  		verbose_linfo(env, i, "    ; ");
- 		if (env->insn_aux_data[i].scc)
- 			verbose(env, "%3d ", env->insn_aux_data[i].scc);
- 		else
- 			verbose(env, "    ");
  		if (env->insn_aux_data[i].loop_header >= 0)
  			verbose(env, "%3d ", env->insn_aux_data[i].loop_header);
  		else
@@@ -24010,11 -25605,10 +25653,10 @@@ int bpf_check(struct bpf_prog **prog, u
  	/* 'struct bpf_verifier_env' can be global, but since it's not small,
  	 * allocate/free it every time bpf_check() is called
  	 */
- 	env = kvzalloc_obj(struct bpf_verifier_env, GFP_KERNEL_ACCOUNT);
+ 	env = kvzalloc_obj(struct bpf_verifier_env, BPF_VERIFIER_GFP);
  	if (!env)
  		return -ENOMEM;
  
- 	env->bt.env = env;
  	env->prog = *prog;
  	env->ops = bpf_verifier_ops[env->prog->type];
  	env->stack_limit = bpf_prog_stack_limit(env->prog);
@@@ -24026,12 -25620,17 +25668,17 @@@
  	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
  	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
  	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
+ 	env->max_cost = BPF_MAX_COST >> (is_priv ? 0 : BPF_LIMITS_SHIFT_UNPRIV);
+ 	env->pass_max_cost = U64_MAX;
+ 	env->max_mem = BPF_MAX_MEM >> (is_priv ? 0 : BPF_LIMITS_SHIFT_UNPRIV);
+ 	env->hash_seed = get_random_u64();
  	env->signature = attr->signature;
  
  	/* user could have requested verbose verifier output
  	 * and supplied buffer to store the verification trace
  	 */
  	ret = bpf_vlog_init(&env->log, attr_log->level, attr_log->ubuf, attr_log->size);
+ 	env->log_level = env->log.level;
  	if (ret)
  		goto err_free_env;
  	ret = bpf_diag_init(env);
@@@ -24063,14 -25662,20 +25710,20 @@@
  	/* Serialize verification of unprivileged programs. */
  	if (!is_priv)
  		mutex_lock(&bpf_verifier_lock);
+ 	ret = -EINTR;
+ 	if (bpf_must_abort())
+ 		goto skip_full_check;
  
  	len = env->insn_aux_data_len = env->prog->len;
  	env->insn_aux_data =
  		__vmalloc(array_size(sizeof(struct bpf_insn_aux_data), len),
- 			  GFP_KERNEL_ACCOUNT | __GFP_ZERO);
+ 			  BPF_VERIFIER_GFP | __GFP_ZERO);
  	ret = -ENOMEM;
  	if (!env->insn_aux_data)
  		goto skip_full_check;
+ 	env->mem = len * sizeof(struct bpf_insn_aux_data);
+ 	/* the analyses that look at an insn once */
+ 	bpf_add_cost(env, len, BPF_COST_INSN);
  	for (i = 0; i < len; i++)
  		env->insn_aux_data[i].orig_idx = i;
  	env->succ = bpf_iarray_realloc(NULL, 2);
@@@ -24092,21 -25697,8 +25745,8 @@@
  	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
  		env->strict_alignment = false;
  
- 	if (is_priv)
- 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
  	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
  
- 	env->explored_states = kvzalloc_objs(struct list_head,
- 					     state_htab_size(env),
- 					     GFP_KERNEL_ACCOUNT);
- 	ret = -ENOMEM;
- 	if (!env->explored_states)
- 		goto skip_full_check;
- 
- 	for (i = 0; i < state_htab_size(env); i++)
- 		INIT_LIST_HEAD(&env->explored_states[i]);
- 	INIT_LIST_HEAD(&env->free_list);
- 
  	/* Prepare BTF and func_info needed to discover all subprograms. */
  	ret = bpf_prepare_btf_info(env, attr, uattr);
  	if (ret < 0)
@@@ -24122,7 -25714,7 +25762,7 @@@
  	if (ret < 0)
  		goto skip_full_check;
  
- 	find_subprog_properties(env);
+ 	find_subprog_properties(env, false);
  
  	/* Validate BTF before reporting subprogram layout errors. */
  	ret = bpf_check_btf_info(env, attr, uattr);
@@@ -24138,6 -25730,10 +25778,10 @@@
  	if (ret < 0)
  		goto skip_full_check;
  
+ 	ret = check_arena_stack(env);
+ 	if (ret < 0)
+ 		goto skip_full_check;
+ 
  	/* Find pointers to functions in the read-only maps of the program. */
  	ret = resolve_func_ptrs(env);
  	if (ret < 0)
@@@ -24148,12 -25744,6 +25792,6 @@@
  	if (ret < 0)
  		goto skip_full_check;
  
- 	if (bpf_prog_is_offloaded(env->prog->aux)) {
- 		ret = bpf_prog_offload_verifier_prep(env->prog);
- 		if (ret)
- 			goto skip_full_check;
- 	}
- 
  	ret = bpf_check_cfg(env);
  	if (ret < 0)
  		goto skip_full_check;
@@@ -24186,7 -25776,8 +25824,8 @@@
  	if (ret < 0)
  		goto skip_full_check;
  
- 	ret = bpf_compute_scc(env);
+ 	/* what no JIT can run is reported first */
+ 	ret = mark_recursive_subprogs(env);
  	if (ret < 0)
  		goto skip_full_check;
  
@@@ -24205,6 -25796,17 +25844,17 @@@
  	if (ret < 0)
  		goto skip_full_check;
  
+ 	/*
+ 	 * It took the constants to remove dead branches and find the loops. Now it's known
+ 	 * which edges the verifier may add, see bpf_head_guard_target(). What follows
+ 	 * believes the constants.
+ 	 */
+ 	ret = bpf_flow_place_guards(env);
+ 	if (ret > 0)
+ 		ret = bpf_compute_const_regs(env);
+ 	if (ret < 0)
+ 		goto skip_full_check;
+ 
  	ret = bpf_compute_live_registers(env);
  	if (ret < 0)
  		goto skip_full_check;
@@@ -24212,46 -25814,46 +25862,46 @@@
  	if (env->log.level & BPF_LOG_LEVEL2)
  		log_program(env);
  
- 	ret = bpf_init_scev(env);
+ 	ret = bpf_equation_env_init(env);
  	if (ret < 0)
  		goto skip_full_check;
  
- 	ret = bpf_compute_scev(env);
+ 	ret = bpf_flow_prepare(env);
  	if (ret < 0)
  		goto skip_full_check;
  
+ 	/* the device runs the insns that the driver was given */
+ 	ret = bpf_prog_is_offloaded(env->prog->aux) ? 0 : mark_fastcall_patterns(env);
+ 	if (ret < 0)
+ 		goto skip_full_check;
+ 
+ 	ret = do_check_all(env);
  	bpf_free_subprog_jts(env);
+ 	/* while the calls are what they are in the program */
+ 	if (env->log.level & BPF_LOG_STATS)
+ 		add_insns_of_callees(env);
  
- 	ret = mark_fastcall_patterns(env);
- 	if (ret < 0)
- 		goto skip_full_check;
- 
- 	ret = do_check_main(env);
- 	ret = ret ?: do_check_subprogs(env);
- 
- 	/* reject recursion through the callx edges found by the main pass */
- 	if (ret == 0 && env->callx_edges)
- 		ret = sort_subprogs_topo(env);
- 
+ 	/* the driver numbers the insns like the program that it was given */
  	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
  		ret = bpf_prog_offload_finalize(env);
  
- skip_full_check:
- 	kvfree(env->explored_states);
+ 	if (ret == 0)
+ 		ret = bpf_insert_loop_guards(env);
  
- 	/* might decrease stack depth, keep it before passes that
- 	 * allocate additional slots.
- 	 */
+ skip_full_check:
+ 	/* instruction rewrites happen after this point */
  	if (ret == 0)
  		ret = bpf_remove_fastcall_spills_fills(env);
  
- 	if (ret == 0)
- 		ret = check_max_stack_depth(env);
- 
- 	/* instruction rewrites happen after this point */
  	if (ret == 0)
  		ret = bpf_optimize_bpf_loop(env);
  
+ 	if (ret == 0)
+ 		ret = bpf_insert_recursion_checks(env);
+ 
+ 	if (ret == 0)
+ 		bpf_lower_cast_mov(env);
+ 
  	if (is_priv) {
  		if (ret == 0)
  			bpf_opt_hard_wire_dead_code_branches(env);
@@@ -24264,6 -25866,9 +25914,9 @@@
  			sanitize_dead_code(env);
  	}
  
+ 	if (ret == 0)
+ 		ret = bpf_insert_arena_stack(env);
+ 
  	if (ret == 0)
  		/* program is valid, convert *(u32*)(ctx + off) accesses */
  		ret = bpf_convert_ctx_accesses(env);
@@@ -24287,43 -25892,14 +25940,14 @@@
  	print_verification_stats(env);
  	env->prog->aux->verified_insns = env->insn_processed;
  
- 	/* preserve original error even if log finalization is successful */
- 	err = bpf_log_attr_finalize(attr_log, &env->log);
- 	if (err)
- 		ret = err;
- 
  	if (ret)
  		goto err_release_maps;
  
- 	if (env->used_map_cnt) {
- 		/* if program passed verifier, update used_maps in bpf_prog_info */
- 		env->prog->aux->used_maps = kmalloc_objs(env->used_maps[0],
- 							 env->used_map_cnt,
- 							 GFP_KERNEL_ACCOUNT);
- 
- 		if (!env->prog->aux->used_maps) {
- 			ret = -ENOMEM;
- 			goto err_release_maps;
- 		}
- 
- 		memcpy(env->prog->aux->used_maps, env->used_maps,
- 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
- 		env->prog->aux->used_map_cnt = env->used_map_cnt;
- 	}
- 	if (env->used_btf_cnt) {
- 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
- 		env->prog->aux->used_btfs = kmalloc_objs(env->used_btfs[0],
- 							 env->used_btf_cnt,
- 							 GFP_KERNEL_ACCOUNT);
- 		if (!env->prog->aux->used_btfs) {
- 			ret = -ENOMEM;
- 			goto err_release_maps;
- 		}
- 
- 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
- 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
- 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
- 	}
+ 	/* if program passed verifier, it gets the tables */
+ 	env->prog->aux->used_maps = env->used_maps;
+ 	env->prog->aux->used_map_cnt = env->used_map_cnt;
+ 	env->prog->aux->used_btfs = env->used_btfs;
+ 	env->prog->aux->used_btf_cnt = env->used_btf_cnt;
  	if (env->used_map_cnt || env->used_btf_cnt) {
  		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
  		 * bpf_ld_imm64 instructions
@@@ -24342,6 -25918,14 +25966,14 @@@
  	env->prog = __bpf_prog_select_runtime(env, env->prog, &ret);
  
  err_release_maps:
+ 	/*
+ 	 * Finalize the log after the runtime is selected, which blinds the
+ 	 * constants of a prog of one function and can log an error. Preserve
+ 	 * the original error even if log finalization is successful.
+ 	 */
+ 	err = bpf_log_attr_finalize(attr_log, &env->log);
+ 	if (err)
+ 		ret = err;
  	if (ret)
  		release_insn_arrays(env);
  	if (!env->prog->aux->used_maps)
@@@ -24370,18 -25954,30 +26002,30 @@@ err_free_env
  	if (env->insn_aux_data)
  		bpf_clear_insn_aux_data(env, 0, env->insn_aux_data_len);
  	vfree(env->insn_aux_data);
+ 	bpf_patch_list_free(env);
  	kvfree(env->fd_array);
- 	bpf_free_scev(env);
+ 	kvfree(env->used_index.slots);
+ 	kvfree(env->kfunc_index.slots);
+ 	kvfree(env->insn_array_maps);
+ 	bpf_equation_env_free(env);
+ 	bpf_flow_free(env);
  	bpf_stack_liveness_free(env);
  	kvfree(env->cfg.postorder_nums);
  	kvfree(env->cfg.insn_postorder);
- 	kvfree(env->scc_info);
  	kvfree(env->succ);
  	kvfree(env->gotox_tmp_buf);
+ 	kvfree(env->pkt_pairs);
  	kvfree(env->callx_edges);
+ 	kvfree(env->callx_index.slots);
  	kvfree(env->func_ptrs);
+ 	for (i = 0; i < env->func_set_cnt; i++)
+ 		kvfree(env->func_sets[i]);
+ 	kvfree(env->func_sets);
+ 	kvfree(env->func_set_index.slots);
  	bpf_diag_free(env);
  	kvfree(env->idoms);
+ 	kvfree(env->subprog_info);
+ 	kvfree(env->subprog_topo_order);
  	kvfree(env);
  	return ret;
  }

[-- Attachment #2: signature.asc --]
[-- Type: application/pgp-signature, Size: 488 bytes --]

^ permalink raw reply	[flat|nested] 69+ messages in thread

end of thread, other threads:[~2026-11-26 14:43 UTC | newest]

Thread overview: 69+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2025-02-14  5:07 linux-next: manual merge of the bpf-next tree with the bpf tree Stephen Rothwell
2025-02-14  5:33 ` Alexei Starovoitov
2025-02-14  5:40   ` Stephen Rothwell
2025-02-14  9:12   ` Jiri Olsa
2025-02-14 18:50     ` Alexei Starovoitov
  -- strict thread matches above, loose matches on Subject: below --
2026-11-26 14:42 Mark Brown
2026-11-17 21:39 Mark Brown
2026-11-17 21:36 Mark Brown
2026-11-18 15:47 ` J4f J4f
2026-11-19  1:17   ` Alexei Starovoitov
2026-11-03 14:08 Mark Brown
2026-11-03 17:40 ` Alexei Starovoitov
2026-11-03 17:50   ` Mark Brown
2026-09-29 14:56 Mark Brown
2026-09-29 16:31 ` Alexei Starovoitov
2026-09-30  7:07 ` Jiri Olsa
2026-09-29 12:15 Mark Brown
2026-09-24 12:39 Mark Brown
2026-09-24 16:12 ` Ihor Solodrai
2026-09-24 16:22   ` Alexei Starovoitov
2026-09-22 10:05 Mark Brown
2026-09-21  9:49 Mark Brown
2026-09-21 12:12 ` Daniel Borkmann
2026-09-18 11:05 Mark Brown
2026-09-14 11:31 Mark Brown
2026-09-14 11:34 ` Daniel Borkmann
2026-09-03 14:10 Mark Brown
2026-09-06 23:18 ` Alexei Starovoitov
2026-04-01 12:29 Mark Brown
2026-04-01 15:27 ` Alexei Starovoitov
2026-02-24 12:39 Mark Brown
2026-02-24 16:22 ` Alexei Starovoitov
2025-11-06  0:35 Stephen Rothwell
2025-11-06 17:57 ` Andrii Nakryiko
2024-03-07  1:40 Stephen Rothwell
2023-03-06 22:58 Stephen Rothwell
2023-03-10  0:38 ` Stephen Rothwell
2023-03-10  3:18 ` Bagas Sanjaya
2022-11-21  1:27 Stephen Rothwell
2022-08-26  1:46 Stephen Rothwell
2022-08-25  0:50 Stephen Rothwell
2022-08-22  1:01 Stephen Rothwell
2021-12-05 23:39 Stephen Rothwell
2020-09-30  4:07 Stephen Rothwell
2020-10-02  3:59 ` Stephen Rothwell
2020-06-26  0:05 Stephen Rothwell
2020-07-06  1:43 ` Stephen Rothwell
2020-05-15  3:18 Stephen Rothwell
2019-10-08 22:47 Stephen Rothwell
2019-10-15 23:29 ` Stephen Rothwell
2019-10-07 22:48 Stephen Rothwell
2019-10-15 23:27 ` Stephen Rothwell
2019-04-17  1:08 Stephen Rothwell
2019-04-24  3:12 ` Stephen Rothwell
2018-12-04  1:09 Stephen Rothwell
2018-12-04  1:05 Stephen Rothwell
2018-11-12  0:54 Stephen Rothwell
2018-05-14  1:57 Stephen Rothwell
2018-05-14 20:41 ` Jakub Kicinski
2018-05-14 21:57   ` Stephen Rothwell
2018-05-02  2:09 Stephen Rothwell
2018-05-02  4:40 ` Song Liu
2018-05-02  5:50   ` Stephen Rothwell
2018-05-02  6:05     ` Song Liu
2018-04-26  0:53 Stephen Rothwell
2018-04-26  7:57 ` Daniel Borkmann
2018-02-26  0:41 Stephen Rothwell
2018-02-26  9:03 ` Daniel Borkmann
2018-02-26 23:28 ` Stephen Rothwell

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox