BPF syscall, maps, verifier, samples, llvm
Subsystems (23)
v4 cover BPF syscall, maps, verifier, samples, llvm
Hi All,
one more RFC...
Major difference vs previous set is a new 'load 64-bit immediate' eBPF insn. Which is first 16-byte instruction. It shows how eBPF ISA can be extended while maintaining backward compatibility, but mainly it cleans up eBPF program access to maps and improves run-time performance.
In V3 I've been using 'fixup' section in eBPF program to tell kernel which instructions are accessing maps. With new instruction 'fixup' is gone and map IDR (internal map_ids) are removed.
To understand the logic behind new insn, I need to explain two main eBPF design constraints:
1. eBPF interpreter must be generic. It should know nothing about maps or any custom instructions or functions.
2. llvm compiler backend must be generic. It also should know nothing about maps, helper functions, sockets, tracing, etc. LLVM just takes normal C and compiles it for some 'fake' HW that happened to be called eBPF ISA.
patch #1 implements BPF_LD_IMM64 insn. It's just a move of 64-bit immediate value into a register. Nothing fancy.
The reason it improved eBPF program run-time is the following:
in V3 the program used to look like:
bpf_mov r1, const_internal_map_id
bpf_call bpf_map_lookup
so in-kernel bpf_map_lookup() helper would do map_id->map_ptr conversion via
map = idr_find(&bpf_map_id_idr, map_id);
For the life of the program map_id is constant and that lookup was returning the same value, but there was no easy way to store pointer inside eBPF insn.
With new insn the programs look like:
bpf_ld_imm64 r1, const_internal_map_ptr
bpf_call bpf_map_lookup
and the bpf_map_lookup() helper does:
struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
Though it's a small performance gain, every nsec counts. Also new insn allows further optimizations in JIT compilers.
How does it help to cleanup program interface towards maps? Obviously user space doesn't know what kernel map pointer is associated with process-local map-FD.
So it's using pseudo BPF_LD_IMM64 instruction.BPF_LD_IMM64 with src_reg == 0 -> generic move 64-bit immediate into dst_reg BPF_LD_IMM64 with src_reg == BPF_PSEUDO_MAP_FD -> mov map_fd into dst_reg Other values are reserved for now. (They will be used to implement global variables, strings and other constants and per-cpu areas in the future) So the programs look like:
BPF_LD_MAP_FD(BPF_REG_1, process_local_map_fd), BPF_CALL(BPF_FUNC_map_lookup_elem),
eBPF verifier scans the program for such pseudo instructions, converts process_local_map_fd -> in-kernel map pointer
and drops 'pseudo' flag of BPF_LD_IMM64 instruction.
eBPF interpreter stays generic and LLVM stays generic, since they know nothing about pseudo instructions.
Another pseudo instruction is BPF_CALL. User space encodes one of BPF_FUNC_xxx function ids as part of 'imm' field of the instruction and eBPF program loader converts it to in-kernel helper function pointer.
The idea to use special instructions to access maps was suggested by Jonathan ;) It took awhile to figure out how to do it within above two design constraints, but the end result I think is much cleaner than what I had in V2/V3.
Another difference vs previous set is verifier split into 6 patches and verifier testsuite is added. Beyond old checks verifier got 'tidiness' checks to make sure all unused fields of instructions are zero. Unfortunately classic BPF doesn't check for this. Lesson learned.
Tracing use case got some improvements as well. Now eBPF programs can be attached to tracepoint, syscall, kprobe and C examples are more usable:ex1_kern.c - demonstrate how programs can walk in-kernel data structures ex2_kern.c - in-kernel event accounting and user space histograms See patch #25
TODO:
- verifier is safe, but not secure, since it allows kernel address leaking. fix that before lifting root-only restriction
- allow seecomp to use eBPF
- write manpage for eBPF syscall
As always all patches are available at:
git://git.kernel.org/pub/scm/linux/kernel/git/ast/bpf master
V3->V4:
- introduced 'load 64-bit immediate' eBPF instruction
- use BPF_LD_IMM64 in LLVM, verifier, programs
- got rid of 'fixup' section in eBPF programs
- got rid of map IDR and internal map_id
- split verifier into 6 patches and added verifier testsuite
- add verifier check for reserved instruction fields
- fixed bug in LLVM eBPF backend (it was miscompiling __builtin_expect)
- fixed race condition in htab_map_update_elem()
- tracing filters can now attach to tracepoint, syscall, kprobe events
- improved C examples
V2->V3:
- fixed verifier register range bug and addressed other comments (Thanks Kees!)
- re-added LLVM eBPF backend
- added two examples in C
- user space ELF parser and loader example
V1->V2:
- got rid of global id, everything now FD based (Thanks Andy!)
- split type enum in verifier (as suggested by Andy and Namhyung)
- switched gpl enforcement to be kmod like (as suggested by Andy and David)
- addressed feedback from Namhyung, Chema, Joe
- added more comments to verifier
- renamed sock_filter_int -> bpf_insn
- rebased on net-next
FD approach made eBPF user interface much cleaner for sockets/seccomp/tracing use cases. Now socket and tracing examples (patch 15 and 16) can be Ctrl-C in the middle and kernel will auto cleanup everything including tracing filters.
----
Old V1 cover letter:
'maps' is a generic storage of different types for sharing data between kernel and userspace. Maps are referrenced by file descriptor. Root process can create multiple maps of different types where key/value are opaque bytes of data. It's up to user space and eBPF program to decide what they store in the maps.
eBPF programs are similar to kernel modules. They are loaded by the user space program and unload on closing of fd. Each program is a safe run-to-completion set of instructions. eBPF verifier statically determines that the program terminates and safe to execute. During verification the program takes a hold of maps that it intends to use, so selected maps cannot be removed until program is unloaded. The program can be attached to different events. These events can be packets, tracepoint events and other types in the future. New event triggers execution of the program which may store information about the event in the maps. Beyond storing data the programs may call into in-kernel helper functions which may, for example, dump stack, do trace_printk or other forms of live kernel debugging. Same program can be attached to multiple events. Different programs can access the same map:
tracepoint tracepoint tracepoint sk_buff sk_buff
event A event B event C on eth0 on eth1
| | | | |
| | | | |
--> tracing <-- tracing socket socket
prog_1 prog_2 prog_3 prog_4
| | | |
|--- -----| |-------| map_3
map_1 map_2User space (via syscall) and eBPF programs access maps concurrently.
------
Alexei Starovoitov (26):
net: filter: add "load 64-bit immediate" eBPF instruction
net: filter: split filter.h and expose eBPF to user space
bpf: introduce syscall(BPF, ...) and BPF maps
bpf: enable bpf syscall on x64
bpf: add lookup/update/delete/iterate methods to BPF maps
bpf: add hashtable type of BPF maps
bpf: expand BPF syscall with program load/unload
bpf: handle pseudo BPF_CALL insn
bpf: verifier (add docs)
bpf: verifier (add ability to receive verification log)
bpf: handle pseudo BPF_LD_IMM64 insn
bpf: verifier (add branch/goto checks)
bpf: verifier (add verifier core)
bpf: verifier (add state prunning optimization)
bpf: allow eBPF programs to use maps
net: sock: allow eBPF programs to be attached to sockets
tracing: allow eBPF programs to be attached to events
tracing: allow eBPF programs to be attached to kprobe/kretprobe
samples: bpf: add mini eBPF library to manipulate maps and programs
samples: bpf: example of stateful socket filtering
samples: bpf: example of tracing filters with eBPF
bpf: llvm backend
samples: bpf: elf file loader
samples: bpf: eBPF example in C
samples: bpf: counting eBPF example in C
bpf: verifier test
Signature · 1 line
1.7.9.5
RFC PATCH v4 1/26 net: filter: add "load 64-bit immediate" eBPF instruction
add BPF_LD_IMM64 instruction to load 64-bit immediate value into register. All previous instructions were 8-byte. This is first 16-byte instruction. Two consecutive 'struct bpf_insn' blocks are interpreted as single instruction:
insn[0/1].code = BPF_LD | BPF_DW | BPF_IMM
insn[0/1].dst_reg = destination register
insn[0].imm = lower 32-bit
insn[1].imm = upper 32-bit
Classic BPF has similar instruction: BPF_LD | BPF_W | BPF_IMM which loads 32-bit immediate value into a register.
x64 JITs it as single 'movabsq %rax, imm64'
arm64 may JIT as sequence of four 'movk x0, #imm16, lsl #shift' insn
Note that old eBPF programs are binary compatible with new interpreter.
--- Documentation/networking/filter.txt | 8 +++++++- arch/x86/net/bpf_jit_comp.c | 9 +++++++++ include/linux/filter.h | 11 +++++++++++ kernel/bpf/core.c | 5 +++++ lib/test_bpf.c | 22 ++++++++++++++++++++++ 5 files changed, 54 insertions(+), 1 deletion(-)
Documentation/networking/filter.txt +7 -1
@@ -951,7 +951,7 @@ Size modifier is one of ... Mode modifier is one of: - BPF_IMM 0x00 /* classic BPF only, reserved in eBPF */ + BPF_IMM 0x00 /* used for 32-bit mov in classic BPF and 64-bit in eBPF */ BPF_ABS 0x20 BPF_IND 0x40 BPF_MEM 0x60
@@ -995,6 +995,12 @@ BPF_XADD | BPF_DW | BPF_STX: lock xadd *(u64 *)(dst_reg + off16) += src_reg Where size is one of: BPF_B or BPF_H or BPF_W or BPF_DW. Note that 1 and 2 byte atomic increments are not supported. +eBPF has one 16-byte instruction: BPF_LD | BPF_DW | BPF_IMM which consists +of two consecutive 'struct bpf_insn' 8-byte blocks and interpreted as single +instruction that loads 64-bit immediate value into a dst_reg. +Classic BPF has similar instruction: BPF_LD | BPF_W | BPF_IMM which loads +32-bit immediate value into a register. + Testing -------
arch/x86/net/bpf_jit_comp.c +9 -0
@@ -393,6 +393,15 @@ static int do_jit(struct bpf_prog *bpf_prog, int *addrs, u8 *image,EMIT1_off32 (add_1reg (0xB8 , dst_reg), imm32);break ; +case BPF_LD |BPF_IMM |BPF_DW : +/* movabsq %rax, imm64 */ +EMIT2 (add_1mod (0x48 , dst_reg),add_1reg (0xB8 , dst_reg)); +EMIT (insn->imm,4 ); + insn++; + i++; +EMIT (insn->imm,4 ); +break ; +/* dst %= src, dst /= src, dst %= imm32, dst /= imm32 */ case BPF_ALU |BPF_MOD |BPF_X :case BPF_ALU |BPF_DIV |BPF_X :
include/linux/filter.h +11 -0
@@ -161,6 +161,17 @@ enum { .off = 0, \ .imm = IMM }) +/* use two of BPF_LD_IMM64 to encode single move 64-bit insn +* first macro to carry lower 32-bits and second for higher 32-bits +*/ +#define BPF_LD_IMM64 (DST ,IMM ) \ + ((struct bpf_insn) { \ + .code = BPF_LD | BPF_DW | BPF_IMM, \ + .dst_reg = DST, \ + .src_reg = 0, \ + .off = 0, \ + .imm = IMM }) +/* Short form of mov based on type, BPF_X: dst_reg = src_reg, BPF_K: dst_reg = imm32 */ #define BPF_MOV64_RAW (TYPE ,DST ,SRC ,IMM ) \
kernel/bpf/core.c +5 -0
@@ -180,6 +180,7 @@ static unsigned int __bpf_prog_run(void *ctx, const struct bpf_insn *insn) [BPF_LD | BPF_IND | BPF_W] = &&LD_IND_W, [BPF_LD | BPF_IND | BPF_H] = &&LD_IND_H, [BPF_LD | BPF_IND | BPF_B] = &&LD_IND_B, + [BPF_LD | BPF_IMM | BPF_DW] = &&LD_IMM_DW, };void *ptr;int off;
@@ -239,6 +240,10 @@ select_insn: ALU64_MOV_K:DST =IMM ;CONT ; + LD_IMM_DW: +DST = (u64 ) (u32 ) insn[0 ].imm | ((u64 ) (u32 ) insn[1 ].imm) <<32 ; + insn++; +CONT ; ALU64_ARSH_X: (*(s64 *) &DST ) >>=SRC ;CONT ;
lib/test_bpf.c +22 -0
@@ -1697,6 +1697,28 @@ static struct bpf_test tests[] = { { }, { { 1, 0 } }, }, + { + "load 64-bit immediate", + .u.insns_int = { +BPF_LD_IMM64 (R1 ,0x1234 ),/* lower 32-bit */ +BPF_LD_IMM64 (R1 ,0x5678 ),/* higher 32-bit */ +BPF_MOV64_REG (R2 ,R1 ), +BPF_MOV64_REG (R3 ,R2 ), +BPF_ALU64_IMM (BPF_RSH ,R2 ,32 ), +BPF_ALU64_IMM (BPF_LSH ,R3 ,32 ), +BPF_ALU64_IMM (BPF_RSH ,R3 ,32 ), +BPF_ALU64_IMM (BPF_MOV ,R0 ,0 ), +BPF_JMP_IMM (BPF_JEQ ,R2 ,0x5678 ,1 ), +BPF_EXIT_INSN (), +BPF_JMP_IMM (BPF_JEQ ,R3 ,0x1234 ,1 ), +BPF_EXIT_INSN (), +BPF_ALU64_IMM (BPF_MOV ,R0 ,1 ), +BPF_EXIT_INSN (), + }, +INTERNAL , + { }, + { { 0, 1 } } + }, };static struct net_device dev;
Signature · 1 line
1.7.9.5
Re: [PATCH RFC v4 net-next 01/26] net: filter: add "load 64-bit immediate" eBPF instruction
Quoted 11 lines · Alexei Starovoitov
add
BPF_LD_IMM64instruction to load 64-bit immediate value into register. All previous instructions were 8-byte. This is first 16-byte instruction. Two consecutive 'structbpf_insn' blocks are interpreted as single instruction:
insn[0/1].code =BPF_LD|BPF_DW|BPF_IMM
insn[0/1].dst_reg = destination register
insn[0].imm = lower 32-bit
insn[1].imm = upper 32-bitClassic BPF has similar instruction:
BPF_LD|BPF_W|BPF_IMMwhich loads 32-bit immediate value into a register.
Quoted 6 lines
x64 JITs it as single 'movabsq %rax, imm64'
arm64 may JIT as sequence of four 'movk x0, #imm16, lsl #shift' insnNote that old eBPF programs are binary compatible with new interpreter.
For follow-ups on this series, can you put the actual motivation for this change from the cover letter into this commit log as it otherwise doesn't say anything clearly why it is needed. Code and test case looks good to me.
Re: [PATCH RFC v4 net-next 01/26] net: filter: add "load 64-bit immediate" eBPF instruction
Quoted 19 lines · Daniel Borkmann
Quoted 18 lines · Alexei Starovoitov
add
BPF_LD_IMM64instruction to load 64-bit immediate value into register. All previous instructions were 8-byte. This is first 16-byte instruction. Two consecutive 'structbpf_insn' blocks are interpreted as single instruction:
insn[0/1].code =BPF_LD|BPF_DW|BPF_IMM
insn[0/1].dst_reg = destination register
insn[0].imm = lower 32-bit
insn[1].imm = upper 32-bitClassic BPF has similar instruction:
BPF_LD|BPF_W|BPF_IMMwhich loads 32-bit immediate value into a register.x64 JITs it as single 'movabsq %rax, imm64'
arm64 may JIT as sequence of four 'movk x0, #imm16, lsl #shift' insnNote that old eBPF programs are binary compatible with new interpreter.
Quoted 7 lines
Quoted 1 line
For follow-ups on this series, can you put the actual motivation for this change from the cover letter into this commit log as it otherwise doesn't say anything clearly why it is needed. Code and test case looks good to me.
ok. As you saw the full explanation is long, so I opted for 'it_does_this' commit log. In the next rev will add more reasons to this log. Sure.
Re: [PATCH RFC v4 net-next 01/26] net: filter: add "load 64-bit immediate" eBPF instruction
Quoted 23 lines · Alexei Starovoitov
Quoted 22 lines · Daniel Borkmann
Quoted 19 lines · Alexei Starovoitov
add
BPF_LD_IMM64instruction to load 64-bit immediate value into register. All previous instructions were 8-byte. This is first 16-byte instruction. Two consecutive 'structbpf_insn' blocks are interpreted as single instruction:
insn[0/1].code =BPF_LD|BPF_DW|BPF_IMM
insn[0/1].dst_reg = destination register
insn[0].imm = lower 32-bit
insn[1].imm = upper 32-bitClassic BPF has similar instruction:
BPF_LD|BPF_W|BPF_IMMwhich loads 32-bit immediate value into a register.x64 JITs it as single 'movabsq %rax, imm64'
arm64 may JIT as sequence of four 'movk x0, #imm16, lsl #shift' insnNote that old eBPF programs are binary compatible with new interpreter.
Quoted 7 lines
Quoted 4 lines
For follow-ups on this series, can you put the actual motivation for this change from the cover letter into this commit log as it otherwise doesn't say anything clearly why it is needed. Code and test case looks good to me.
ok. As you saw the full explanation is long, so I opted for '
it_does_this' commit log. In the next rev will add more reasons to this log. Sure.
Great, thanks.
Re: [PATCH RFC v4 net-next 01/26] net: filter: add "load 64-bit immediate" eBPF instruction
In reply to Alexei StarovoitovQuoted 7 lines · Alexei Starovoitov
add
BPF_LD_IMM64instruction to load 64-bit immediate value into register. All previous instructions were 8-byte. This is first 16-byte instruction. Two consecutive 'structbpf_insn' blocks are interpreted as single instruction:
insn[0/1].code =BPF_LD|BPF_DW|BPF_IMM
insn[0/1].dst_reg = destination register
insn[0].imm = lower 32-bit
insn[1].imm = upper 32-bit
This might be unnecessarily difficult for fancy static analysis tools to reason about. Would it make sense to assign two different codes for this? For example, insn[0].code = code_for_load_low, insns[1].code = code_for_load_high, along with a verifier check that they come in matched pairs and that code_for_load_high isn't a jump target?
(Something else that I find confusing about eBPF: the instruction mnemonics are very strange. Have you considered giving them real names? For example, load.imm.low instead of BPF_LD | BPF_DW | BPF_IMM is easier to read and pronounce.)
--Andy
Re: [PATCH RFC v4 net-next 01/26] net: filter: add "load 64-bit immediate" eBPF instruction
Quoted 9 lines · Andy Lutomirski
Quoted 7 lines · Alexei Starovoitov
add
BPF_LD_IMM64instruction to load 64-bit immediate value into register. All previous instructions were 8-byte. This is first 16-byte instruction. Two consecutive 'structbpf_insn' blocks are interpreted as single instruction:
insn[0/1].code =BPF_LD|BPF_DW|BPF_IMM
insn[0/1].dst_reg = destination register
insn[0].imm = lower 32-bit
insn[1].imm = upper 32-bit
Quoted 6 lines
This might be unnecessarily difficult for fancy static analysis tools to reason about. Would it make sense to assign two different codes for this? For example, insn[0].code =
code_for_load_low, insns[1].code =code_for_load_high, along with a verifier check that they come in matched pairs and thatcode_for_load_highisn't a jump target?
see my reply to David for the same thing. Short answer is that sequence of instructions (even if it is a pair of instructions like this) is very hard to detect in verifier and JITs.
As soon as we give compiler two instructions instead of one, compiler may optimize them in a fancy ways. Like two loads of 64-bit immediate with upper 32-bit the same, may came out as 4 instructions: load_high, load_low, load_low, mov.
Or in some cases as single load_low, etc.
load 64-bit imm has to stay as single instruction to be verifiable and patch-able easily.
One can argue: force compiler to emit load_low and load_hi always together, but then that's exactly what I have. It's a single insn.
Quoted 4 lines
(Something else that I find confusing about eBPF: the instruction mnemonics are very strange. Have you considered giving them real names? For example, load.imm.low instead of
BPF_LD|BPF_DW|BPF_IMMis easier to read and pronounce.)
BPF_LD | BPF_DW | BPF_IMM is not really a name. It's macro for cases when instructions are generated from inside the kernel. Instructions mnemonics are not defined yet.
llvm emits assembler code like:bpf_prog2:
ldw r1, 16(r1)
std -8(r10), r1
mov r1, 1
std -16(r10), r1
ld_64 r1, 1
mov r2, r10
addi r2, -8
call 4
jeqi r0, 0 goto .LBB1_2
ldd r1, 0(r0)
addi r1, 1
std 0(r0), r1
.LBB1_3:
mov r0, 0
ret
...
I'm open to change assembler/disassembler mnemonics.
Re: [PATCH RFC v4 net-next 01/26] net: filter: add "load 64-bit immediate" eBPF instruction
Quoted 17 lines · Alexei Starovoitov
Quoted 9 lines · Andy Lutomirski
Quoted 7 lines · Alexei Starovoitov
add
BPF_LD_IMM64instruction to load 64-bit immediate value into register. All previous instructions were 8-byte. This is first 16-byte instruction. Two consecutive 'structbpf_insn' blocks are interpreted as single instruction:
insn[0/1].code =BPF_LD|BPF_DW|BPF_IMM
insn[0/1].dst_reg = destination register
insn[0].imm = lower 32-bit
insn[1].imm = upper 32-bitQuoted 6 lines
This might be unnecessarily difficult for fancy static analysis tools to reason about. Would it make sense to assign two different codes for this? For example, insn[0].code =
code_for_load_low, insns[1].code =code_for_load_high, along with a verifier check that they come in matched pairs and thatcode_for_load_highisn't a jump target?
Quoted 12 lines
see my reply to David for the same thing. Short answer is that sequence of instructions (even if it is a pair of instructions like this) is very hard to detect in verifier and JITs.
As soon as we give compiler two instructions instead of one, compiler may optimize them in a fancy ways. Like two loads of 64-bit immediate with upper 32-bit the same, may came out as 4 instructions:load_high,load_low,load_low, mov.
Or in some cases as singleload_low, etc.
load 64-bit imm has to stay as single instruction to be verifiable and patch-able easily.
One can argue: force compiler to emitload_lowandload_hialways together, but then that's exactly what I have. It's a single insn.
The compiler can still think of it as a single insn, though, but some future compiler might not. In any case, I think that, if you use the same code for high and for low, you need logic in the JIT that's at least as complicated. For example, what happens if you have two consecutive 64-bit immediate loads to the same register? Now you have four consecutive 8-byte insn words that differ only in their immediate values, and you need to split them correctly.
Quoted 20 lines
Quoted 5 lines
(Something else that I find confusing about eBPF: the instruction mnemonics are very strange. Have you considered giving them real names? For example, load.imm.low instead of
BPF_LD|BPF_DW|BPF_IMMis easier to read and pronounce.)
BPF_LD|BPF_DW|BPF_IMMis not really a name. It's macro for cases when instructions are generated from inside the kernel. Instructions mnemonics are not defined yet.
llvm emits assembler code like:bpf_prog2:
ldw r1, 16(r1)
std -8(r10), r1
mov r1, 1
std -16(r10), r1
ld_64r1, 1
mov r2, r10
addi r2, -8
call 4
jeqi r0, 0 goto .LBB1_2
Quoted 8 lines
ldd r1, 0(r0)
addi r1, 1
std 0(r0), r1
.LBB1_3:
mov r0, 0
ret
...
I'm open to change assembler/disassembler mnemonics.
Ah, ok. I didn't realize that there were mnemonics at all.
--Andy
Signature · 2 lines
Andy Lutomirski AMA Capital Management, LLC
Re: [PATCH RFC v4 net-next 01/26] net: filter: add "load 64-bit immediate" eBPF instruction
Quoted 3 lines · Andy Lutomirski
The compiler can still think of it as a single insn, though, but some future compiler might not.
I think that would be very dangerous.
compiler (user space) and kernel interpreter must have the same understanding of ISA.
Quoted 3 lines
In any case, I think that, if you use the
same code for high and for low, you need logic in the JIT that's at least as complicated.
why do you think so? Handling of pseudo BPF_LD_IMM64 is done in single patch #11 which is one of the smallest...
Quoted 4 lines
For example, what happens if you have two
consecutive 64-bit immediate loads to the same register? Now you have four consecutive 8-byte insn words that differ only in their immediate values, and you need to split them correctly.
I don't need to do anything special in this case.
Two 16-byte instructions back to back is not a problem. Interpreter or JIT don't care whether they move the same or different immediates into the same or different register. Interpreter and JITs are dumb on purpose.
when verifier sees two back to back ld_imm64, the 2nd will simply override the value loaded by first one. It's not any different than two back to back 'mov dst_reg, imm32' instructions.
H. Peter Anvin
reviewerRe: [PATCH RFC v4 net-next 01/26] net: filter: add "load 64-bit immediate" eBPF instruction
Quoted 9 lines · Alexei Starovoitov
Quoted 3 lines · Andy Lutomirski
The compiler can still think of it as a single insn, though, but some future compiler might not.
I think that would be very dangerous.
compiler (user space) and kernel interpreter must have the same understanding of ISA.
Only at the point of the interface layer. The compiler can treat it as a single instruction internally, the JIT can do peephole optimization, but as long as the instruction stream at the boundary matches the official ISA spec everything is fine.
-hpa
Re: [PATCH RFC v4 net-next 01/26] net: filter: add "load 64-bit immediate" eBPF instruction
In reply to Alexei StarovoitovQuoted 21 lines · Alexei Starovoitov
Quoted 3 lines · Andy Lutomirski
The compiler can still think of it as a single insn, though, but some future compiler might not.
I think that would be very dangerous.
compiler (user space) and kernel interpreter must have the same understanding of ISA.Quoted 3 lines
In any case, I think that, if you use the
same code for high and for low, you need logic in the JIT that's at least as complicated.why do you think so? Handling of pseudo
BPF_LD_IMM64is done in single patch #11 which is one of the smallest...Quoted 4 lines
For example, what happens if you have two
consecutive 64-bit immediate loads to the same register? Now you have four consecutive 8-byte insn words that differ only in their immediate values, and you need to split them correctly.
Quoted 8 lines
I don't need to do anything special in this case.
Two 16-byte instructions back to back is not a problem. Interpreter or JIT don't care whether they move the same or different immediates into the same or different register. Interpreter and JITs are dumb on purpose.
when verifier sees two back to backld_imm64, the 2nd will simply override the value loaded by first one. It's not any different than two back to back 'movdst_reg, imm32' instructions.
But this patch makes the JIT code (and any interpreter) weirdly stateful. You have:
+ case BPF_LD | BPF_IMM | BPF_DW:
+ /* movabsq %rax, imm64 */ + EMIT2(add_1mod(0x48, dst_reg), add_1reg(0xB8, dst_reg)); + EMIT(insn->imm, 4); + insn++; + i++; + EMIT(insn->imm, 4); + break;
If you have more than two BPF_LD | BPF_IMM | BPF_DW instructions in a row, then the way in which they pair up depends on where you start.
I think it would be a lot clearer if you made these be "load low" and "load high", with JIT code like:
+ case BPF_LOAD_LOW:
+ /* movabsq %rax, imm64 */
+ if (next insn is BPF_LOAD_HIGH) {
+ EMIT2(add_1mod(0x48, dst_reg),add_1reg(0xB8, dst_reg));
+ EMIT(insn->imm, 4); + insn++; + i++; + EMIT(insn->imm, 4);
+ } else {
+ emit a real load low;
+ }
+ break;
(and you'd have to deal with whether load low by itself is illegal, zero extends, sign extends, or preserves high bits).
Alternatively, and possibly better, you could have a real encoding for multiword instructions. Reserve a bit in the opcode to mark a continuation of the previous instruction, and do:
+ case BPF_LD | BPF_IMM | BPF_DW:
+ assert(insn[1] in bounds && insn[1].code == BPF_CONT); + /* movabsq %rax, imm64 */ + EMIT2(add_1mod(0x48, dst_reg), add_1reg(0xB8, dst_reg)); + EMIT(insn->imm, 4); + insn++; + i++; + EMIT(insn->imm, 4); + break;
This has a nice benefit for future-proofing: it gives you 119 bits of payload for 16-byte instructions.
On the other hand, a u8 for the opcode is kind of small, and killing half of that space like this is probably bad. Maybe reserve two high bits, with:
0: normal opcode or start of a multiword sequence
1: continuation of a multiword sequence
2, 3: reserved for future longer opcode numbers (e.g. 2 could indicate that "code" is actually 16 bits)
--Andy
Signature · 2 lines
Andy Lutomirski AMA Capital Management, LLC
H. Peter Anvin
reviewerRe: [PATCH RFC v4 net-next 01/26] net: filter: add "load 64-bit immediate" eBPF instruction
One thing about this that may be a serious concern: allowing the user to control 8 contiguous bytes of kernel memory may be a security hazard.
-hpa
Re: [PATCH RFC v4 net-next 01/26] net: filter: add "load 64-bit immediate" eBPF instruction
Quoted 2 lines · H. Peter Anvin
One thing about this that may be a serious concern: allowing the user to control 8 contiguous bytes of kernel memory may be a security hazard.
I'm confused. What kind of memory? I can control a lot more than 8 bytes of stack very easily.
Or are you concerned about 8 contiguous bytes of *executable* memory?
--Andy
H. Peter Anvin
reviewerRe: [PATCH RFC v4 net-next 01/26] net: filter: add "load 64-bit immediate" eBPF instruction
Quoted 9 lines · Andy Lutomirski
Quoted 2 lines · H. Peter Anvin
One thing about this that may be a serious concern: allowing the user to control 8 contiguous bytes of kernel memory may be a security hazard.
I'm confused. What kind of memory? I can control a lot more than 8 bytes of stack very easily.
Or are you concerned about 8 contiguous bytes of *executable* memory?
Yes. Useful for some kinds of ROP custom gadgets.
-hpa
Re: [PATCH RFC v4 net-next 01/26] net: filter: add "load 64-bit immediate" eBPF instruction
Quoted 5 lines · H. Peter Anvin
Quoted 4 lines · Andy Lutomirski
Quoted 2 lines · H. Peter Anvin
One thing about this that may be a serious concern: allowing the user to control 8 contiguous bytes of kernel memory may be a security hazard.
Quoted 7 lines
Quoted 5 lines
I'm confused. What kind of memory? I can control a lot more than 8 bytes of stack very easily.
Or are you concerned about 8 contiguous bytes of *executable* memory?
Yes. Useful for some kinds of ROP custom gadgets.
I don't get it. What is ROP ?
What is the concern about 8 bytes ?
Re: [PATCH RFC v4 net-next 01/26] net: filter: add "load 64-bit immediate" eBPF instruction
Quoted 9 lines · Alexei Starovoitov
Quoted 8 lines · H. Peter Anvin
Quoted 7 lines · Andy Lutomirski
Quoted 2 lines · H. Peter Anvin
One thing about this that may be a serious concern: allowing the user to control 8 contiguous bytes of kernel memory may be a security hazard.
I'm confused. What kind of memory? I can control a lot more than 8 bytes of stack very easily.
Quoted 7 lines
Quoted 4 lines
Quoted 2 lines
Or are you concerned about 8 contiguous bytes of *executable* memory?
Yes. Useful for some kinds of ROP custom gadgets.
I don't get it. What is ROP ?
What is the concern about 8 bytes ?
looked it up. too many abbreviations now days.
x64 jit spraying was fixed by Eric some time ago, so JIT emitting movabsq doesn't increase attack surface. various movs of 32-bit immediates can be used for 'custom gadget' just as well. Worst case JIT won't be enabled.
In classic BPF we allow junk to be stored in used fields of 'struct sock_filter' and so far that wasn't a problem. eBPF is more paranoid regarding verification.
Re: [PATCH RFC v4 net-next 01/26] net: filter: add "load 64-bit immediate" eBPF instruction
In reply to H. Peter AnvinQuoted 5 lines · H. Peter Anvin
Quoted 4 lines · Andy Lutomirski
Quoted 2 lines · H. Peter Anvin
One thing about this that may be a serious concern: allowing the user to control 8 contiguous bytes of kernel memory may be a security hazard.
Quoted 7 lines
Quoted 5 lines
I'm confused. What kind of memory? I can control a lot more than 8 bytes of stack very easily.
Or are you concerned about 8 contiguous bytes of *executable* memory?
Yes. Useful for some kinds of ROP custom gadgets.
Hmm.
I think this is moot on non-SMEP machines. And I'm not entirely convinced that it's worth worrying about in general, especially if we take some care to randomize the location of the JIT mapping.
But yes, gadgets like jumps relative to gs or something along those lines could make for interesting ROP tools. But someone will probably figure out how to turn JIT output into a NOP slide + ROP gadget regardless, at least on x86.
--Andy
Re: [PATCH RFC v4 net-next 01/26] net: filter: add "load 64-bit immediate" eBPF instruction
Quoted 4 lines · Andy Lutomirski
I think this is moot on non-SMEP machines. And I'm not entirely convinced that it's worth worrying about in general, especially if we take some care to randomize the location of the JIT mapping.
JIT start address is already randomized...
Re: [PATCH RFC v4 net-next 01/26] net: filter: add "load 64-bit immediate" eBPF instruction
In reply to Andy LutomirskiQuoted 43 lines · Andy Lutomirski
Quoted 21 lines · Alexei Starovoitov
Quoted 3 lines · Andy Lutomirski
The compiler can still think of it as a single insn, though, but some future compiler might not.
I think that would be very dangerous.
compiler (user space) and kernel interpreter must have the same understanding of ISA.Quoted 3 lines
In any case, I think that, if you use the
same code for high and for low, you need logic in the JIT that's at least as complicated.why do you think so? Handling of pseudo
BPF_LD_IMM64is done in single patch #11 which is one of the smallest...Quoted 4 lines
For example, what happens if you have two
consecutive 64-bit immediate loads to the same register? Now you have four consecutive 8-byte insn words that differ only in their immediate values, and you need to split them correctly.Quoted 8 lines
I don't need to do anything special in this case.
Two 16-byte instructions back to back is not a problem. Interpreter or JIT don't care whether they move the same or different immediates into the same or different register. Interpreter and JITs are dumb on purpose.
when verifier sees two back to backld_imm64, the 2nd will simply override the value loaded by first one. It's not any different than two back to back 'movdst_reg, imm32' instructions.But this patch makes the JIT code (and any interpreter) weirdly stateful. You have:
arch/x86/net/bpf_jit_comp.c +8
-0+case BPF_LD |BPF_IMM |BPF_DW : +/* movabsq %rax, imm64 */ +EMIT2 (add_1mod (0x48 , dst_reg),add_1reg (0xB8 , dst_reg)); +EMIT (insn->imm,4 ); + insn++; + i++; +EMIT (insn->imm,4 ); +break ;
Quoted 2 lines
If you have more than two
BPF_LD|BPF_IMM|BPF_DWinstructions in a row, then the way in which they pair up depends on where you start.
For JIT it's not a problem, since it's doing a linear scan. So it always starts at instruction boundary.
But thinking about it further you're right that it's a bug in verifier. I've tried it and indeed depending on type of branch verifier doesn't catch a case of two 16-byte instructions back to back and jump goes into 2nd half of 1st insn. I need to fix that.
Review
Quoted 6 lines
I think it would be a lot clearer if you made these be "load low" and "load high", with JIT code like:
(quoted diff) +3
-0+ case BPF_LOAD_LOW: + /* movabsq %rax, imm64 */ + if (next insn is BPF_LOAD_HIGH) {
such 'if' will be costly in interpreter. I want to avoid it.
Quoted 2 lines
(and you'd have to deal with whether load low by itself is illegal, zero extends, sign extends, or preserves high bits).
I don't need an instruction that loads low 32-bit. It already exists. It's called 'mov'.
I'm going to try encoding:
insn[0].code = LD | IMM | DW
insn[1].code = 0
zero is invalid opcode, so it's your 'continuation'.
and it is still single 16-byte instructions without any interpreter overhead.
Quoted 2 lines
This has a nice benefit for future-proofing: it gives you 119 bits of payload for 16-byte instructions.
It's already future proofed. We can add 24 byte instructions and so on just as well. There is no point to reserve 119 bits when no one is using them.
Quoted 3 lines
On the other hand, a u8 for the opcode is kind of small, and killing half of that space like this is probably bad. Maybe reserve two high bits, with:
That's an overkill. We use ~80 opcodes out of 256.
There is plenty of room. I see no reason to switch to 16-bit opcodes until we get even close to half of u8 space.
It feels that we're starting to bikeshed.
Re: [PATCH RFC v4 net-next 01/26] net: filter: add "load 64-bit immediate" eBPF instruction
Quoted 7 lines · Alexei Starovoitov
I don't need an instruction that loads low 32-bit. It already exists. It's called 'mov'.
I'm going to try encoding:
insn[0].code = LD | IMM | DW
insn[1].code = 0
zero is invalid opcode, so it's your 'continuation'.
and it is still single 16-byte instructions without any interpreter overhead.
Works for me.
--Andy
RFC PATCH v4 2/26 net: filter: split filter.h and expose eBPF to user space
In reply to Alexei StarovoitoveBPF can be used from user space.
uapi/linux/bpf.h: eBPF instruction set definition
linux/filter.h: the rest
This patch only moves macro definitions, but practically it freezes existing eBPF instruction set, though new instructions can still be added in the future.
These eBPF definitions cannot go into uapi/linux/filter.h, since the names may conflict with existing applications.
--- include/linux/filter.h | 305 +------------------------------------------ include/uapi/linux/Kbuild | 1 + include/uapi/linux/bpf.h | 314 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 316 insertions(+), 304 deletions(-) create mode 100644 include/uapi/linux/bpf.h
include/linux/filter.h +1 -304
@@ -9,315 +9,12 @@#include <linux/skbuff.h> #include <linux/workqueue.h> #include <uapi/linux/filter.h> - -/* Internally used and optimized filter representation with extended -* instruction set based on top of classic BPF. -*/ - -/* instruction classes */ -#define BPF_ALU64 0x07/* alu mode in double word width */ - -/* ld/ldx fields */ -#define BPF_DW 0x18/* double word */ -#define BPF_XADD 0xc0/* exclusive add */ - -/* alu/jmp fields */ -#define BPF_MOV 0xb0/* mov reg to reg */ -#define BPF_ARSH 0xc0/* sign extending arithmetic shift right */ - -/* change endianness of a register */ -#define BPF_END 0xd0/* flags for endianness conversion: */ -#define BPF_TO_LE 0x00/* convert to little-endian */ -#define BPF_TO_BE 0x08/* convert to big-endian */ -#define BPF_FROM_LE BPF_TO_LE -#define BPF_FROM_BE BPF_TO_BE - -#define BPF_JNE 0x50/* jump != */ -#define BPF_JSGT 0x60/* SGT is signed '>', GT in x86 */ -#define BPF_JSGE 0x70/* SGE is signed '>=', GE in x86 */ -#define BPF_CALL 0x80/* function call */ -#define BPF_EXIT 0x90/* function return */ - -/* Register numbers */ -enum { -BPF_REG_0 =0 , -BPF_REG_1 , -BPF_REG_2 , -BPF_REG_3 , -BPF_REG_4 , -BPF_REG_5 , -BPF_REG_6 , -BPF_REG_7 , -BPF_REG_8 , -BPF_REG_9 , -BPF_REG_10 , - __MAX_BPF_REG, -}; - -/* BPF has 10 general purpose 64-bit registers and stack frame. */ -#define MAX_BPF_REG __MAX_BPF_REG - -/* ArgX, context and stack frame pointer register positions. Note, -* Arg1, Arg2, Arg3, etc are used as argument mappings of function -* calls in BPF_CALL instruction. -*/ -#define BPF_REG_ARG1 BPF_REG_1 -#define BPF_REG_ARG2 BPF_REG_2 -#define BPF_REG_ARG3 BPF_REG_3 -#define BPF_REG_ARG4 BPF_REG_4 -#define BPF_REG_ARG5 BPF_REG_5 -#define BPF_REG_CTX BPF_REG_6 -#define BPF_REG_FP BPF_REG_10 - -/* Additional register mappings for converted user programs. */ -#define BPF_REG_A BPF_REG_0 -#define BPF_REG_X BPF_REG_7 -#define BPF_REG_TMP BPF_REG_8 - -/* BPF program can access up to 512 bytes of stack space. */ -#define MAX_BPF_STACK 512 - -/* Helper macros for filter block array initializers. */ - -/* ALU ops on registers, bpf_add|sub|...: dst_reg += src_reg */ - -#define BPF_ALU64_REG (OP ,DST ,SRC ) \ - ((struct bpf_insn) { \ - .code = BPF_ALU64 | BPF_OP(OP) | BPF_X, \ - .dst_reg = DST, \ - .src_reg = SRC, \ - .off = 0, \ - .imm = 0 }) - -#define BPF_ALU32_REG (OP ,DST ,SRC ) \ - ((struct bpf_insn) { \ - .code = BPF_ALU | BPF_OP(OP) | BPF_X, \ - .dst_reg = DST, \ - .src_reg = SRC, \ - .off = 0, \ - .imm = 0 }) - -/* ALU ops on immediates, bpf_add|sub|...: dst_reg += imm32 */ - -#define BPF_ALU64_IMM (OP ,DST ,IMM ) \ - ((struct bpf_insn) { \ - .code = BPF_ALU64 | BPF_OP(OP) | BPF_K, \ - .dst_reg = DST, \ - .src_reg = 0, \ - .off = 0, \ - .imm = IMM }) - -#define BPF_ALU32_IMM (OP ,DST ,IMM ) \ - ((struct bpf_insn) { \ - .code = BPF_ALU | BPF_OP(OP) | BPF_K, \ - .dst_reg = DST, \ - .src_reg = 0, \ - .off = 0, \ - .imm = IMM }) - -/* Endianess conversion, cpu_to_{l,b}e(), {l,b}e_to_cpu() */ - -#define BPF_ENDIAN (TYPE ,DST ,LEN ) \ - ((struct bpf_insn) { \ - .code = BPF_ALU | BPF_END | BPF_SRC(TYPE), \ - .dst_reg = DST, \ - .src_reg = 0, \ - .off = 0, \ - .imm = LEN }) - -/* Short form of mov, dst_reg = src_reg */ - -#define BPF_MOV64_REG (DST ,SRC ) \ - ((struct bpf_insn) { \ - .code = BPF_ALU64 | BPF_MOV | BPF_X, \ - .dst_reg = DST, \ - .src_reg = SRC, \ - .off = 0, \ - .imm = 0 }) - -#define BPF_MOV32_REG (DST ,SRC ) \ - ((struct bpf_insn) { \ - .code = BPF_ALU | BPF_MOV | BPF_X, \ - .dst_reg = DST, \ - .src_reg = SRC, \ - .off = 0, \ - .imm = 0 }) - -/* Short form of mov, dst_reg = imm32 */ - -#define BPF_MOV64_IMM (DST ,IMM ) \ - ((struct bpf_insn) { \ - .code = BPF_ALU64 | BPF_MOV | BPF_K, \ - .dst_reg = DST, \ - .src_reg = 0, \ - .off = 0, \ - .imm = IMM }) - -#define BPF_MOV32_IMM (DST ,IMM ) \ - ((struct bpf_insn) { \ - .code = BPF_ALU | BPF_MOV | BPF_K, \ - .dst_reg = DST, \ - .src_reg = 0, \ - .off = 0, \ - .imm = IMM }) - -/* use two of BPF_LD_IMM64 to encode single move 64-bit insn -* first macro to carry lower 32-bits and second for higher 32-bits -*/ -#define BPF_LD_IMM64 (DST ,IMM ) \ - ((struct bpf_insn) { \ - .code = BPF_LD | BPF_DW | BPF_IMM, \ - .dst_reg = DST, \ - .src_reg = 0, \ - .off = 0, \ - .imm = IMM }) - -/* Short form of mov based on type, BPF_X: dst_reg = src_reg, BPF_K: dst_reg = imm32 */ - -#define BPF_MOV64_RAW (TYPE ,DST ,SRC ,IMM ) \ - ((struct bpf_insn) { \ - .code = BPF_ALU64 | BPF_MOV | BPF_SRC(TYPE), \ - .dst_reg = DST, \ - .src_reg = SRC, \ - .off = 0, \ - .imm = IMM }) - -#define BPF_MOV32_RAW (TYPE ,DST ,SRC ,IMM ) \ - ((struct bpf_insn) { \ - .code = BPF_ALU | BPF_MOV | BPF_SRC(TYPE), \ - .dst_reg = DST, \ - .src_reg = SRC, \ - .off = 0, \ - .imm = IMM }) - -/* Direct packet access, R0 = *(uint *) (skb->data + imm32) */ - -#define BPF_LD_ABS (SIZE ,IMM ) \ - ((struct bpf_insn) { \ - .code = BPF_LD | BPF_SIZE(SIZE) | BPF_ABS, \ - .dst_reg = 0, \ - .src_reg = 0, \ - .off = 0, \ - .imm = IMM }) - -/* Indirect packet access, R0 = *(uint *) (skb->data + src_reg + imm32) */ - -#define BPF_LD_IND (SIZE ,SRC ,IMM ) \ - ((struct bpf_insn) { \ - .code = BPF_LD | BPF_SIZE(SIZE) | BPF_IND, \ - .dst_reg = 0, \ - .src_reg = SRC, \ - .off = 0, \ - .imm = IMM }) - -/* Memory load, dst_reg = *(uint *) (src_reg + off16) */ - -#define BPF_LDX_MEM (SIZE ,DST ,SRC ,OFF ) \ - ((struct bpf_insn) { \ - .code = BPF_LDX | BPF_SIZE(SIZE) | BPF_MEM, \ - .dst_reg = DST, \ - .src_reg = SRC, \ - .off = OFF, \ - .imm = 0 }) - -/* Memory store, *(uint *) (dst_reg + off16) = src_reg */ - -#define BPF_STX_MEM (SIZE ,DST ,SRC ,OFF ) \ - ((struct bpf_insn) { \ - .code = BPF_STX | BPF_SIZE(SIZE) | BPF_MEM, \ - .dst_reg = DST, \ - .src_reg = SRC, \ - .off = OFF, \ - .imm = 0 }) - -/* Memory store, *(uint *) (dst_reg + off16) = imm32 */ - -#define BPF_ST_MEM (SIZE ,DST ,OFF ,IMM ) \ - ((struct bpf_insn) { \ - .code = BPF_ST | BPF_SIZE(SIZE) | BPF_MEM, \ - .dst_reg = DST, \ - .src_reg = 0, \ - .off = OFF, \ - .imm = IMM }) - -/* Conditional jumps against registers, if (dst_reg 'op' src_reg) goto pc + off16 */ - -#define BPF_JMP_REG (OP ,DST ,SRC ,OFF ) \ - ((struct bpf_insn) { \ - .code = BPF_JMP | BPF_OP(OP) | BPF_X, \ - .dst_reg = DST, \ - .src_reg = SRC, \ - .off = OFF, \ - .imm = 0 }) - -/* Conditional jumps against immediates, if (dst_reg 'op' imm32) goto pc + off16 */ - -#define BPF_JMP_IMM (OP ,DST ,IMM ,OFF ) \ - ((struct bpf_insn) { \ - .code = BPF_JMP | BPF_OP(OP) | BPF_K, \ - .dst_reg = DST, \ - .src_reg = 0, \ - .off = OFF, \ - .imm = IMM }) - -/* Function call */ - -#define BPF_EMIT_CALL (FUNC ) \ - ((struct bpf_insn) { \ - .code = BPF_JMP | BPF_CALL, \ - .dst_reg = 0, \ - .src_reg = 0, \ - .off = 0, \ - .imm = ((FUNC) - __bpf_call_base) }) - -/* Raw code statement block */ - -#define BPF_RAW_INSN (CODE ,DST ,SRC ,OFF ,IMM ) \ - ((struct bpf_insn) { \ - .code = CODE, \ - .dst_reg = DST, \ - .src_reg = SRC, \ - .off = OFF, \ - .imm = IMM }) - -/* Program exit */ - -#define BPF_EXIT_INSN () \ - ((struct bpf_insn) { \ - .code = BPF_JMP | BPF_EXIT, \ - .dst_reg = 0, \ - .src_reg = 0, \ - .off = 0, \ - .imm = 0 }) - -#define bytes_to_bpf_size (bytes) \ -({ \ - int bpf_size = -EINVAL; \ - \ - if (bytes == sizeof(u8)) \ - bpf_size = BPF_B; \ - else if (bytes == sizeof(u16)) \ - bpf_size = BPF_H; \ - else if (bytes == sizeof(u32)) \ - bpf_size = BPF_W; \ - else if (bytes == sizeof(u64)) \ - bpf_size = BPF_DW; \ - \ - bpf_size; \ -}) +#include <uapi/linux/bpf.h> /* Macro to invoke filter function. */ #define SK_RUN_FILTER (filter, ctx) \ (*filter->prog->bpf_func)(ctx, filter->prog->insnsi) -struct bpf_insn { -__u8 code;/* opcode */ -__u8 dst_reg:4 ;/* dest register */ -__u8 src_reg:4 ;/* source register */ -__s16 off;/* signed offset */ -__s32 imm;/* signed immediate constant */ -}; -#ifdef CONFIG_COMPAT /* A struct sock_filter is architecture independent. */ struct compat_sock_fprog {
include/uapi/linux/Kbuild +1 -0
@@ -67,6 +67,7 @@ header-y += bfs_fs.h header-y += binfmts.h header-y += blkpg.h header-y += blktrace_api.h +header-y += bpf.h header-y += bpqether.h header-y += bsg.h header-y += btrfs.h
include/uapi/linux/bpf.h new file +314 -0
314 lines not on this page · raw message
Signature · 1 line
1.7.9.5
RFC PATCH v4 3/26 bpf: introduce syscall(BPF, ...) and BPF maps
In reply to Alexei StarovoitovBPF syscall is a demux for different BPF releated commands.
'maps' is a generic storage of different types for sharing data between kernel and userspace.
The maps can be created from user space via BPF syscall:
- create a map with given type and attributes
fd = bpf_map_create(map_type, struct nlattr *attr, int len) returns fd or negative error
- close(fd) deletes the map
Next patch allows userspace programs to populate/read maps that eBPF programs are concurrently updating.
maps can have different types: hash, bloom filter, radix-tree, etc.
The map is defined by:
. type
. max number of elements
. key size in bytes
. value size in bytes
This patch establishes core infrastructure for BPF maps. Next patches implement lookup/update and hashtable type. More map types can be added in the future.
syscall is using type-length-value style of passing arguments to be backwards compatible with future extensions to map attributes. Different map types may use different attributes as well.
The concept of type-lenght-value is borrowed from netlink, but netlink itself is not applicable here, since BPF programs and maps can be used in NET-less configurations.
--- Documentation/networking/filter.txt | 71 ++++++++++++++++ include/linux/bpf.h | 42 ++++++++++ include/uapi/linux/bpf.h | 24 ++++++ kernel/bpf/Makefile | 2 +- kernel/bpf/syscall.c | 156 +++++++++++++++++++++++++++++++++++ 5 files changed, 294 insertions(+), 1 deletion(-) create mode 100644 include/linux/bpf.h create mode 100644 kernel/bpf/syscall.c
Documentation/networking/filter.txt +71 -0
@@ -1001,6 +1001,77 @@ instruction that loads 64-bit immediate value into a dst_reg. Classic BPF has similar instruction: BPF_LD | BPF_W | BPF_IMM which loads 32-bit immediate value into a register. +eBPF maps +--------- +'maps' is a generic storage of different types for sharing data between kernel +and userspace. + +The maps are accessed from user space via BPF syscall, which has commands: +- create a map with given type and attributes + map_fd = bpf_map_create(map_type, struct nlattr *attr, int len) + returns process-local file descriptor or negative error + +- lookup key in a given map + err = bpf_map_lookup_elem(int fd, void *key, void *value) + returns zero and stores found elem into value or negative error + +- create or update key/value pair in a given map + err = bpf_map_update_elem(int fd, void *key, void *value) + returns zero or negative error + +- find and delete element by key in a given map + err = bpf_map_delete_elem(int fd, void *key) + +- to delete map: close(fd) + Exiting process will delete maps automatically + +userspace programs uses this API to create/populate/read maps that eBPF programs +are concurrently updating. + +maps can have different types: hash, array, bloom filter, radix-tree, etc. + +The map is defined by: + . type + . max number of elements + . key size in bytes + . value size in bytes + +The maps are accesible from eBPF program with API: + void * bpf_map_lookup_elem(u32 map_fd, void *key); + int bpf_map_update_elem(u32 map_fd, void *key, void *value); + int bpf_map_delete_elem(u32 map_fd, void *key); + +The kernel replaces process-local map_fd with kernel internal map pointer, +while loading eBPF program. + +If eBPF verifier is configured to recognize extra calls in the program +bpf_map_lookup_elem() and bpf_map_update_elem() then access to maps looks like: + ... + ptr_to_value = bpf_map_lookup_elem(map_fd, key) + access memory range [ptr_to_value, ptr_to_value + value_size_in_bytes) + ... + prepare key2 and value2 on stack of key_size and value_size + err = bpf_map_update_elem(map_fd, key2, value2) + ... + +eBPF program cannot create or delete maps +(such calls will be unknown to verifier) + +During program loading the refcnt of used maps is incremented, so they don't get +deleted while program is running + +bpf_map_update_elem() can fail if maximum number of elements reached. +if key2 already exists, bpf_map_update_elem() replaces it with value2 atomically + +bpf_map_lookup_elem() returns NULL or ptr_to_value, so program must do +if (ptr_to_value != NULL) check before accessing it. +NULL means that element with given 'key' was not found. + +The verifier will check that the program accesses map elements within specified +size. It will not let programs pass junk values to bpf_map_*_elem() functions, +so these functions (implemented in C inside kernel) can safely access +the pointers in all cases. + Testing -------
include/linux/bpf.h new file +42 -0
42 lines not on this page · raw message
include/uapi/linux/bpf.h +24 -0
@@ -311,4 +311,28 @@ struct bpf_insn { __s32 imm; /* signed immediate constant */ }; +/* BPF syscall commands */ +enum bpf_cmd { +/* create a map with given type and attributes +* fd = bpf_map_create(bpf_map_type, struct nlattr *attr, int len) +* returns fd or negative error +* map is deleted when fd is closed +*/ +BPF_MAP_CREATE , +}; + +enum bpf_map_attributes { +BPF_MAP_UNSPEC , +BPF_MAP_KEY_SIZE ,/* size of key in bytes */ +BPF_MAP_VALUE_SIZE ,/* size of value in bytes */ +BPF_MAP_MAX_ENTRIES ,/* maximum number of entries in a map */ + __BPF_MAP_ATTR_MAX, +}; +#define BPF_MAP_ATTR_MAX (__BPF_MAP_ATTR_MAX - 1) +#define BPF_MAP_MAX_ATTR_SIZE 65535 + +enum bpf_map_type { +BPF_MAP_TYPE_UNSPEC , +}; +#endif /* _UAPI__LINUX_BPF_H__ */
kernel/bpf/Makefile +1 -1
@@ -1 +1 @@ -obj-y := core.o +obj-y := core.o syscall.o
kernel/bpf/syscall.c new file +156 -0
156 lines not on this page · raw message
Signature · 1 line
1.7.9.5
Re: [PATCH RFC v4 net-next 03/26] bpf: introduce syscall(BPF, ...) and BPF maps
On Wed, Aug 13, 2014 at 12:57 AM, Alexei Starovoitov <ast-uqk4Ao+rVK5Wk0Htik3J/[email protected]> wrote:
[...]
Quoted 7 lines
maps can have different types: hash, bloom filter, radix-tree, etc.
The map is defined by:
. type
. max number of elements
. key size in bytes
. value size in bytes
Can values be strings or byte arrays? How would user-level bpf read them? The two types of uses I'm thinking are:
A. Constructing a custom string in kernel-context, and using that as the value. Eg, a truncated filename, or a dotted quad IP address, or the raw contents of a packet.
B. I have a pointer to an existing buffer or string, eg a filename, that will likely be around for some time (>1s). Instead of the value storing the string, it could just be a ptr, so long as user-level bpf has a way to read it.
Also, can keys be strings? I'd ask about multiple keys, but if they can be a string, I can delimit in the key (eg, "PID:filename"). Thanks,
Brendan
Signature · 1 line
http://www.brendangregg.com
Re: [PATCH RFC v4 net-next 03/26] bpf: introduce syscall(BPF, ...) and BPF maps
Quoted 21 lines · Brendan Gregg
On Wed, Aug 13, 2014 at 12:57 AM, Alexei Starovoitov <ast-uqk4Ao+rVK5Wk0Htik3J/[email protected]> wrote:
[...]Quoted 7 lines
maps can have different types: hash, bloom filter, radix-tree, etc.
The map is defined by:
. type
. max number of elements
. key size in bytes
. value size in bytesCan values be strings or byte arrays? How would user-level bpf read them? The two types of uses I'm thinking are:
A. Constructing a custom string in kernel-context, and using that as the value. Eg, a truncated filename, or a dotted quad IP address, or the raw contents of a packet.
B. I have a pointer to an existing buffer or string, eg a filename, that will likely be around for some time (>1s). Instead of the value storing the string, it could just be a ptr, so long as user-level bpf has a way to read it.
Quoted 2 lines
Also, can keys be strings? I'd ask about multiple keys, but if they can be a string, I can delimit in the key (eg, "PID:filename").
Both map keys and values are opaque byte arrays. eBPF program can decide to store strings in there. Or concatenate multiple strings as long as sizes are bounded.
High level scripting languages are dazzling with native strings support, but I'm trying to stay away from it in the kernel. Scripting languages should be able to convert string operations into low level eBPF primitives which are being worked on. So far I've been able to use ids and pointers and concatenations of binary things as keys and values, and have user space interpret them. I agree that having a script that does map[probe_name()]++ is definitely more human readable than storing probe ip into ebpf map and converting addresses to names in userspace. I'm hoping that the urge to make cool scripting language will push somebody to have a dtrace/ktap/stap language compiler into eBPF :) That will also address your concern of embedded setup where full llvm is too big, but dtrace_into_ebpf compiler may be just right. At the same time people who care about last bit of performance will be using C and llvm or ebpf assembler directly.
Anyway will share string related ebpf helpers soon (not in V5 though)
RFC PATCH v4 4/26 bpf: enable bpf syscall on x64
In reply to Alexei Starovoitovdone as separate commit to ease conflict resolution
--- arch/x86/syscalls/syscall_64.tbl | 1 + include/linux/syscalls.h | 3 ++- include/uapi/asm-generic/unistd.h | 4 +++- kernel/sys_ni.c | 3 +++ 4 files changed, 9 insertions(+), 2 deletions(-)
arch/x86/syscalls/syscall_64.tbl +1 -0
@@ -325,6 +325,7 @@ 316 common renameat2 sys_renameat2 317 common seccomp sys_seccomp 318 common getrandom sys_getrandom +319 common bpf sys_bpf # # x32-specific system call numbers start at 512 to avoid cache impact
include/linux/syscalls.h +2 -1
@@ -870,5 +870,6 @@ asmlinkage long sys_seccomp(unsigned int op, unsigned int flags, const char __user *uargs);asmlinkage long sys_getrandom (char __user *buf,size_t count,unsigned int flags); - +asmlinkage long sys_bpf (int cmd,unsigned long arg2,unsigned long arg3, +unsigned long arg4,unsigned long arg5);#endif
include/uapi/asm-generic/unistd.h +3 -1
@@ -703,9 +703,11 @@ __SYSCALL(__NR_renameat2, sys_renameat2) __SYSCALL(__NR_seccomp, sys_seccomp)#define __NR_getrandom 278 __SYSCALL(__NR_getrandom, sys_getrandom) +#define __NR_bpf 279 +__SYSCALL(__NR_bpf, sys_bpf)#undef __NR_syscalls -#define __NR_syscalls 279 +#define __NR_syscalls 280/* * All syscalls below here should go away really,
kernel/sys_ni.c +3 -0
@@ -216,3 +216,6 @@ cond_syscall(sys_kcmp);/* operate on Secure Computing state */ cond_syscall (sys_seccomp); + +/* access BPF programs and maps */ +cond_syscall (sys_bpf);
Signature · 1 line
1.7.9.5
RFC PATCH v4 5/26 bpf: add lookup/update/delete/iterate methods to BPF maps
In reply to Alexei Starovoitov'maps' is a generic storage of different types for sharing data between kernel and userspace.
The maps are accessed from user space via BPF syscall, which has commands:
- create a map with given type and attributes
fd = bpf_map_create(map_type, struct nlattr *attr, int len) returns fd or negative error
- lookup key in a given map referenced by fd
err = bpf_map_lookup_elem(int fd, void *key, void *value) returns zero and stores found elem into value or negative error
- create or update key/value pair in a given map err = bpf_map_update_elem(int fd, void *key, void *value) returns zero or negative error
- find and delete element by key in a given map
err = bpf_map_delete_elem(int fd, void *key)
- iterate map elements (based on input key return next_key) err = bpf_map_get_next_key(int fd, void *key, void *next_key)
- close(fd) deletes the map
--- include/linux/bpf.h | 8 ++ include/uapi/linux/bpf.h | 25 ++++++ kernel/bpf/syscall.c | 198 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 231 insertions(+)
include/linux/bpf.h +8 -0
@@ -9,6 +9,7 @@#include <uapi/linux/bpf.h> #include <linux/workqueue.h> +#include <linux/file.h> struct bpf_map ;struct nlattr ;
@@ -18,6 +19,12 @@ struct bpf_map_ops {/* funcs callable from userspace (via syscall) */ struct bpf_map *(*map_alloc)(struct nlattr *attrs[BPF_MAP_ATTR_MAX +1 ]);void (*map_free)(struct bpf_map *); +int (*map_get_next_key)(struct bpf_map *map,void *key,void *next_key); + +/* funcs callable from userspace and from eBPF programs */ +void *(*map_lookup_elem)(struct bpf_map *map,void *key); +int (*map_update_elem)(struct bpf_map *map,void *key,void *value); +int (*map_delete_elem)(struct bpf_map *map,void *key); };struct bpf_map {
@@ -38,5 +45,6 @@ struct bpf_map_type_list {void bpf_register_map_type (struct bpf_map_type_list *tl);void bpf_map_put (struct bpf_map *map); +struct bpf_map *bpf_map_get (struct fd f);#endif /* _LINUX_BPF_H */
include/uapi/linux/bpf.h +25 -0
@@ -319,6 +319,31 @@ enum bpf_cmd {* map is deleted when fd is closed */ BPF_MAP_CREATE , + +/* lookup key in a given map +* err = bpf_map_lookup_elem(int fd, void *key, void *value) +* returns zero and stores found elem into value +* or negative error +*/ +BPF_MAP_LOOKUP_ELEM , + +/* create or update key/value pair in a given map +* err = bpf_map_update_elem(int fd, void *key, void *value) +* returns zero or negative error +*/ +BPF_MAP_UPDATE_ELEM , + +/* find and delete elem by key in a given map +* err = bpf_map_delete_elem(int fd, void *key) +* returns zero or negative error +*/ +BPF_MAP_DELETE_ELEM , + +/* lookup key in a given map and return next key +* err = bpf_map_get_elem(int fd, void *key, void *next_key) +* returns zero and stores next key or negative error +*/ + BPF_MAP_GET_NEXT_KEY, }; enum bpf_map_attributes {
kernel/bpf/syscall.c +198 -0
216 lines not on this page · raw message
Signature · 1 line
1.7.9.5
RFC PATCH v4 6/26 bpf: add hashtable type of BPF maps
In reply to Alexei Starovoitovadd new map type: BPF_MAP_TYPE_HASH
and its simple (not auto resizeable) hash table implementation
--- include/uapi/linux/bpf.h | 1 + kernel/bpf/Makefile | 2 +- kernel/bpf/hashtab.c | 372 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 374 insertions(+), 1 deletion(-) create mode 100644 kernel/bpf/hashtab.c
include/uapi/linux/bpf.h +1 -0
@@ -358,6 +358,7 @@ enum bpf_map_attributes {enum bpf_map_type {BPF_MAP_TYPE_UNSPEC , +BPF_MAP_TYPE_HASH , };#endif /* _UAPI__LINUX_BPF_H__ */
kernel/bpf/Makefile +1 -1
@@ -1 +1 @@ -obj-y := core.o syscall.o +obj-y := core.o syscall.o hashtab.o
kernel/bpf/hashtab.c new file +372 -0
372 lines not on this page · raw message
Signature · 1 line
1.7.9.5
RFC PATCH v4 7/26 bpf: expand BPF syscall with program load/unload
In reply to Alexei StarovoitoveBPF programs are safe run-to-completion functions with load/unload methods from userspace similar to kernel modules.
User space API:
- load eBPF program
fd = bpf_prog_load(bpf_prog_type, struct nlattr *prog, int len)
where 'prog' is a sequence of sections (TEXT, LICENSE)
TEXT - array of eBPF instructions
LICENSE - must be GPL compatible to call helper functions marked gpl_only
- unload eBPF program
close(fd)
User space example of syscall(__NR_bpf, BPF_PROG_LOAD, prog_type, ...) follows in later patches
--- include/linux/bpf.h | 36 +++++++++ include/linux/filter.h | 9 ++- include/uapi/linux/bpf.h | 28 +++++++ kernel/bpf/syscall.c | 196 ++++++++++++++++++++++++++++++++++++++++++++++ net/core/filter.c | 2 + 5 files changed, 269 insertions(+), 2 deletions(-)
include/linux/bpf.h +36 -0
@@ -47,4 +47,40 @@ void bpf_register_map_type(struct bpf_map_type_list *tl);void bpf_map_put (struct bpf_map *map);struct bpf_map *bpf_map_get (struct fd f); +/* eBPF function prototype used by verifier to allow BPF_CALLs from eBPF programs +* to in-kernel helper functions and for adjusting imm32 field in BPF_CALL +* instructions after verifying +*/ +struct bpf_func_proto { +u64 (*func)(u64 r1,u64 r2,u64 r3,u64 r4,u64 r5); +bool gpl_only; +}; + +struct bpf_verifier_ops { +/* return eBPF function prototype for verification */ +const struct bpf_func_proto *(*get_func_proto)(enum bpf_func_id func_id); +}; + +struct bpf_prog_type_list { +struct list_head list_node; +struct bpf_verifier_ops *ops; +enum bpf_prog_type type; +}; + +void bpf_register_prog_type (struct bpf_prog_type_list *tl); + +struct bpf_prog_info { +atomic_t refcnt; +bool is_gpl_compatible; +enum bpf_prog_type prog_type; +struct bpf_verifier_ops *ops; +struct bpf_map **used_maps; +u32 used_map_cnt; +}; + +struct bpf_prog ; + +void bpf_prog_put (struct bpf_prog *prog); +struct bpf_prog *bpf_prog_get (u32 ufd); +#endif /* _LINUX_BPF_H */
include/linux/filter.h +7 -2
@@ -31,11 +31,16 @@ struct sock_fprog_kern {struct sk_buff ;struct sock ;struct seccomp_data ; +struct bpf_prog_info ;struct bpf_prog {u32 jited:1 ,/* Is our filter JIT'ed? */ - len:31 ;/* Number of filter blocks */ -struct sock_fprog_kern *orig_prog;/* Original BPF program */ + has_info:1 ,/* whether 'info' is valid */ + len:30 ;/* Number of filter blocks */ +union { +struct sock_fprog_kern *orig_prog;/* Original BPF program */ +struct bpf_prog_info *info; + };unsigned int (*bpf_func)(const struct sk_buff *skb,const struct bpf_insn *filter);union {
include/uapi/linux/bpf.h +28 -0
@@ -344,6 +344,13 @@ enum bpf_cmd {* returns zero and stores next key or negative error */ BPF_MAP_GET_NEXT_KEY , + +/* verify and load eBPF program +* prog_id = bpf_prog_load(bpf_prog_type, struct nlattr *prog, int len) +* prog is a sequence of sections +* returns fd or negative error +*/ + BPF_PROG_LOAD, }; enum bpf_map_attributes {
@@ -361,4 +368,25 @@ enum bpf_map_type { BPF_MAP_TYPE_HASH, }; +enum bpf_prog_attributes { +BPF_PROG_UNSPEC , +BPF_PROG_TEXT ,/* array of eBPF instructions */ +BPF_PROG_LICENSE ,/* license string */ + __BPF_PROG_ATTR_MAX, +}; +#define BPF_PROG_ATTR_MAX (__BPF_PROG_ATTR_MAX - 1) +#define BPF_PROG_MAX_ATTR_SIZE 65535 + +enum bpf_prog_type { +BPF_PROG_TYPE_UNSPEC , +}; + +/* integer value in 'imm' field of BPF_CALL instruction selects which helper +* function eBPF program intends to call +*/ +enum bpf_func_id { + BPF_FUNC_unspec, + __BPF_FUNC_MAX_ID, +}; +#endif /* _UAPI__LINUX_BPF_H__ */
kernel/bpf/syscall.c +196 -0
214 lines not on this page · raw message
net/core/filter.c +2 -0
@@ -835,6 +835,7 @@ static void bpf_release_orig_filter(struct bpf_prog *fp) {struct sock_fprog_kern *fprog = fp->orig_prog; +BUG_ON (fp->has_info);if (fprog) {kfree (fprog->filter);kfree (fprog);
@@ -973,6 +974,7 @@ static struct bpf_prog *bpf_prepare_filter(struct bpf_prog *fp) fp->bpf_func =NULL ; fp->jited =0 ; + fp->has_info =0 ; err =bpf_check_classic (fp->insns, fp->len);if (err) {
Signature · 1 line
1.7.9.5
RFC PATCH v4 8/26 bpf: handle pseudo BPF_CALL insn
In reply to Alexei Starovoitovin native eBPF programs userspace is using pseudo BPF_CALL instructions which encode one of 'enum bpf_func_id' inside insn->imm field. Verifier checks that program using correct function arguments to given func_id. If all checks passed, kernel needs to fixup BPF_CALL->imm fields by replacing func_id with in-kernel function pointer.
eBPF interpreter just calls the function.
In-kernel eBPF users continue to use generic BPF_CALL.
--- kernel/bpf/syscall.c | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+)
kernel/bpf/syscall.c +37 -0
@@ -338,6 +338,40 @@ void bpf_register_prog_type(struct bpf_prog_type_list *tl)list_add (&tl->list_node, &bpf_prog_types); } +/* fixup insn->imm field of bpf_call instructions: +* if (insn->imm == BPF_FUNC_map_lookup_elem) +* insn->imm = bpf_map_lookup_elem - __bpf_call_base; +* else if (insn->imm == BPF_FUNC_map_update_elem) +* insn->imm = bpf_map_update_elem - __bpf_call_base; +* else ... +* +* this function is called after eBPF program passed verification +*/ +static void fixup_bpf_calls (struct bpf_prog *prog) +{ +const struct bpf_func_proto *fn; +int i; + +for (i =0 ; i < prog->len; i++) { +struct bpf_insn *insn = &prog->insnsi[i]; + +if (insn->code == (BPF_JMP |BPF_CALL )) { +/* we reach here when program has bpf_call instructions +* and it passed bpf_check(), means that +* ops->get_func_proto must have been supplied, check it +*/ +BUG_ON (!prog->info->ops->get_func_proto); + + fn = prog->info->ops->get_func_proto (insn->imm); +/* all functions that have prototype and verifier allowed +* programs to call them, must be real in-kernel functions +*/ +BUG_ON (!fn->func); + insn->imm = fn->func - __bpf_call_base; + } + } +} +/* drop refcnt on maps used by eBPF program and free auxilary data */ static void free_bpf_prog_info (struct bpf_prog_info *info) {
@@ -485,6 +519,9 @@ static int bpf_prog_load(enum bpf_prog_type type, struct nlattr __user *uattr,if (err <0 ) goto free_prog_info; +/* fixup BPF_CALL->imm field */ +fixup_bpf_calls (prog); +/* eBPF program is ready to be JITed */ bpf_prog_select_runtime (prog);
Signature · 1 line
1.7.9.5
RFC PATCH v4 9/26 bpf: verifier (add docs)
In reply to Alexei Starovoitovthis patch adds all of eBPF verfier documentation and empty bpf_check()
The end goal for the verifier is to statically check safety of the program.
Verifier will catch:
- loops
- out of range jumps
- unreachable instructions
- invalid instructions
- uninitialized register access
- uninitialized stack access
- misaligned stack access
- out of range stack access
- invalid calling convention
More details in Documentation/networking/filter.txt
--- Documentation/networking/filter.txt | 230 +++++++++++++++++++++++++++++++++++ include/linux/bpf.h | 2 + kernel/bpf/Makefile | 2 +- kernel/bpf/syscall.c | 2 +- kernel/bpf/verifier.c | 151 +++++++++++++++++++++++ 5 files changed, 385 insertions(+), 2 deletions(-) create mode 100644 kernel/bpf/verifier.c
Documentation/networking/filter.txt +230 -0
@@ -1001,6 +1001,105 @@ instruction that loads 64-bit immediate value into a dst_reg. Classic BPF has similar instruction: BPF_LD | BPF_W | BPF_IMM which loads 32-bit immediate value into a register. +eBPF verifier +------------- +The safety of the eBPF program is determined in two steps. + +First step does DAG check to disallow loops and other CFG validation. +In particular it will detect programs that have unreachable instructions. +(though classic BPF checker allows them) + +Second step starts from the first insn and descends all possible paths. +It simulates execution of every insn and observes the state change of +registers and stack. + +At the start of the program the register R1 contains a pointer to context +and has type PTR_TO_CTX. +If verifier sees an insn that does R2=R1, then R2 has now type +PTR_TO_CTX as well and can be used on the right hand side of expression. +If R1=PTR_TO_CTX and insn is R2=R1+R1, then R2=UNKNOWN_VALUE, +since addition of two valid pointers makes invalid pointer. +(In 'secure' mode verifier will reject any type of pointer arithmetic to make +sure that kernel addresses don't leak to unprivileged users) + +If register was never written to, it's not readable: + bpf_mov R0 = R2 + bpf_exit +will be rejected, since R2 is unreadable at the start of the program. + +After kernel function call, R1-R5 are reset to unreadable and +R0 has a return type of the function. + +Since R6-R9 are callee saved, their state is preserved across the call. + bpf_mov R6 = 1 + bpf_call foo + bpf_mov R0 = R6 + bpf_exit +is a correct program. If there was R1 instead of R6, it would have +been rejected. + +Classic BPF register X is mapped to eBPF register R7 inside sk_convert_filter(), +so that its state is preserved across calls. + +load/store instructions are allowed only with registers of valid types, which +are PTR_TO_CTX, PTR_TO_MAP, FRAME_PTR. They are bounds and alignment checked. +For example: + bpf_mov R1 = 1 + bpf_mov R2 = 2 + bpf_xadd *(u32 *)(R1 + 3) += R2 + bpf_exit +will be rejected, since R1 doesn't have a valid pointer type at the time of +execution of instruction bpf_xadd. + +At the start R1 contains pointer to ctx and R1 type is PTR_TO_CTX. +ctx is generic. verifier is configured to known what context is for particular +class of bpf programs. For example, context == skb (for socket filters) and +ctx == seccomp_data for seccomp filters. +A callback is used to customize verifier to restrict eBPF program access to only +certain fields within ctx structure with specified size and alignment. + +For example, the following insn: + bpf_ld R0 = *(u32 *)(R6 + 8) +intends to load a word from address R6 + 8 and store it into R0 +If R6=PTR_TO_CTX, via is_valid_access() callback the verifier will know +that offset 8 of size 4 bytes can be accessed for reading, otherwise +the verifier will reject the program. +If R6=FRAME_PTR, then access should be aligned and be within +stack bounds, which are [-MAX_BPF_STACK, 0). In this example offset is 8, +so it will fail verification, since it's out of bounds. + +The verifier will allow eBPF program to read data from stack only after +it wrote into it. +Classic BPF verifier does similar check with M[0-15] memory slots. +For example: + bpf_ld R0 = *(u32 *)(R10 - 4) + bpf_exit +is invalid program. +Though R10 is correct read-only register and has type FRAME_PTR +and R10 - 4 is within stack bounds, there were no stores into that location. + +Pointer register spill/fill is tracked as well, since four (R6-R9) +callee saved registers may not be enough for some programs. + +Allowed function calls are customized with bpf_verifier_ops->get_func_proto() +The eBPF verifier will check that registers match argument constraints. +After the call register R0 will be set to return type of the function. + +Function calls is a main mechanism to extend functionality of eBPF programs. +Socket filters may let programs to call one set of functions, whereas tracing +filters may allow completely different set. + +If a function made accessible to eBPF program, it needs to be thought through +from security point of view. The verifier will guarantee that the function is +called with valid arguments. + +seccomp vs socket filters have different security restrictions for classic BPF. +Seccomp solves this by two stage verifier: classic BPF verifier is followed +by seccomp verifier. In case of eBPF one configurable verifier is shared for +all use cases. + +See details of eBPF verifier in kernel/bpf/verifier.c + eBPF maps --------- 'maps' is a generic storage of different types for sharing data between kernel
@@ -1072,6 +1171,137 @@ size. It will not let programs pass junk values to bpf_map_*_elem() functions, so these functions (implemented in C inside kernel) can safely access the pointers in all cases. +Understanding eBPF verifier messages +------------------------------------ + +The following are few examples of invalid eBPF programs and verifier error +messages as seen in the log: + +Program with unreachable instructions: +static struct bpf_insn prog[] = { + BPF_EXIT_INSN(), + BPF_EXIT_INSN(), +}; +Error: + unreachable insn 1 + +Program that reads uninitialized register: + BPF_MOV64_REG(BPF_REG_0, BPF_REG_2), + BPF_EXIT_INSN(), +Error: + 0: (bf) r0 = r2 + R2 !read_ok + +Program that doesn't initialize R0 before exiting: + BPF_MOV64_REG(BPF_REG_2, BPF_REG_1), + BPF_EXIT_INSN(), +Error: + 0: (bf) r2 = r1 + 1: (95) exit + R0 !read_ok + +Program that accesses stack out of bounds: + BPF_ST_MEM(BPF_DW, BPF_REG_10, 8, 0), + BPF_EXIT_INSN(), +Error: + 0: (7a) *(u64 *)(r10 +8) = 0 + invalid stack off=8 size=8 + +Program that doesn't initialize stack before passing its address into function: + 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_EXIT_INSN(), +Error: + 0: (bf) r2 = r10 + 1: (07) r2 += -8 + 2: (b7) r1 = 0x0 + 3: (85) call 1 + invalid indirect read from stack off -8+0 size 8 + +Program that uses invalid map_fd=0 while calling to map_lookup_elem() function: + 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_EXIT_INSN(), +Error: + 0: (7a) *(u64 *)(r10 -8) = 0 + 1: (bf) r2 = r10 + 2: (07) r2 += -8 + 3: (b7) r1 = 0x0 + 4: (85) call 1 + fd 0 is not pointing to valid bpf_map + +Program that doesn't check return value of map_lookup_elem() before accessing +map element: + 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_ST_MEM(BPF_DW, BPF_REG_0, 0, 0), + BPF_EXIT_INSN(), +Error: + 0: (7a) *(u64 *)(r10 -8) = 0 + 1: (bf) r2 = r10 + 2: (07) r2 += -8 + 3: (b7) r1 = 0x0 + 4: (85) call 1 + 5: (7a) *(u64 *)(r0 +0) = 0 + R0 invalid mem access 'map_value_or_null' + +Program that correctly checks map_lookup_elem() returned value for NULL, but +accesses the memory with incorrect alignment: + 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_JEQ, BPF_REG_0, 0, 1), + BPF_ST_MEM(BPF_DW, BPF_REG_0, 4, 0), + BPF_EXIT_INSN(), +Error: + 0: (7a) *(u64 *)(r10 -8) = 0 + 1: (bf) r2 = r10 + 2: (07) r2 += -8 + 3: (b7) r1 = 1 + 4: (85) call 1 + 5: (15) if r0 == 0x0 goto pc+1 + R0=map_ptr R10=fp + 6: (7a) *(u64 *)(r0 +4) = 0 + misaligned access off 4 size 8 + +Program that correctly checks map_lookup_elem() returned value for NULL and +accesses memory with correct alignment in one side of 'if' branch, but fails +to do so in the other side of 'if' branch: + 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_JEQ, BPF_REG_0, 0, 2), + BPF_ST_MEM(BPF_DW, BPF_REG_0, 0, 0), + BPF_EXIT_INSN(), + BPF_ST_MEM(BPF_DW, BPF_REG_0, 0, 1), + BPF_EXIT_INSN(), +Error: + 0: (7a) *(u64 *)(r10 -8) = 0 + 1: (bf) r2 = r10 + 2: (07) r2 += -8 + 3: (b7) r1 = 1 + 4: (85) call 1 + 5: (15) if r0 == 0x0 goto pc+2 + R0=map_ptr R10=fp + 6: (7a) *(u64 *)(r0 +0) = 0 + 7: (95) exit + + from 5 to 8: R0=imm0 R10=fp + 8: (7a) *(u64 *)(r0 +0) = 1 + R0 invalid mem access 'imm' + Testing -------
include/linux/bpf.h +2 -0
@@ -82,5 +82,7 @@ struct bpf_prog;void bpf_prog_put (struct bpf_prog *prog);struct bpf_prog *bpf_prog_get (u32 ufd); +/* verify correctness of eBPF program */ +int bpf_check (struct bpf_prog *fp,struct nlattr *tb[BPF_PROG_ATTR_MAX +1 ]);#endif /* _LINUX_BPF_H */
kernel/bpf/Makefile +1 -1
@@ -1 +1 @@ -obj-y := core.o syscall.o hashtab.o +obj-y := core.o syscall.o hashtab.o verifier.o
kernel/bpf/syscall.c +1 -1
@@ -514,7 +514,7 @@ static int bpf_prog_load(enum bpf_prog_type type, struct nlattr __user *uattr, goto free_prog_info;/* run eBPF verifier */ -/* err = bpf_check(prog, tb); */ + err =bpf_check (prog, tb);if (err <0 ) goto free_prog_info;
kernel/bpf/verifier.c new file +151 -0
151 lines not on this page · raw message
Signature · 1 line
1.7.9.5
RFC PATCH v4 10/26 bpf: verifier (add ability to receive verification log)
In reply to Alexei Starovoitovadd optional attributes for BPF_PROG_LOAD syscall:
BPF_PROG_LOG_LEVEL, /* verbosity level of eBPF verifier */ BPF_PROG_LOG_BUF, /* user supplied buffer */ BPF_PROG_LOG_SIZE, /* size of user buffer */
In such case the verifier will return its verification log in the user supplied buffer which can be used by humans to analyze why verifier rejected given program
--- include/uapi/linux/bpf.h | 4 + kernel/bpf/syscall.c | 3 + kernel/bpf/verifier.c | 236 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 243 insertions(+)
include/uapi/linux/bpf.h +4 -0
@@ -372,6 +372,10 @@ enum bpf_prog_attributes {BPF_PROG_UNSPEC ,BPF_PROG_TEXT ,/* array of eBPF instructions */ BPF_PROG_LICENSE ,/* license string */ +/* optional program attributes */ +BPF_PROG_LOG_LEVEL ,/* verbosity level of eBPF verifier */ +BPF_PROG_LOG_BUF ,/* user supplied buffer */ +BPF_PROG_LOG_SIZE ,/* size of user buffer */ __BPF_PROG_ATTR_MAX, };#define BPF_PROG_ATTR_MAX (__BPF_PROG_ATTR_MAX - 1)
kernel/bpf/syscall.c +3 -0
@@ -443,6 +443,9 @@ struct bpf_prog *bpf_prog_get(u32 ufd)static const struct nla_policy prog_policy[BPF_PROG_ATTR_MAX +1 ] = { [BPF_PROG_TEXT ] = { .type =NLA_BINARY }, [BPF_PROG_LICENSE ] = { .type =NLA_NUL_STRING }, + [BPF_PROG_LOG_LEVEL ] = { .type =NLA_U32 }, + [BPF_PROG_LOG_BUF ] = { .len =sizeof (void *) }, + [BPF_PROG_LOG_SIZE ] = { .type =NLA_U32 }, }; static int bpf_prog_load(enum bpf_prog_type type, struct nlattr __user *uattr,
kernel/bpf/verifier.c +236 -0
245 lines not on this page · raw message
Signature · 1 line
1.7.9.5
RFC PATCH v4 11/26 bpf: handle pseudo BPF_LD_IMM64 insn
In reply to Alexei StarovoitoveBPF programs passed from userspace are using pseudo BPF_LD_IMM64 instructions to refer to process-local map_fd. Scan the program for such instructions and if FDs are valid, convert them to 'struct bpf_map' pointers which will be used by verifier to check access to maps in bpf_map_lookup/update() calls. If program passes verifier, convert pseudo BPF_LD_IMM64 into generic by dropping BPF_PSEUDO_MAP_FD flag.
Note that eBPF interpreter is generic and knows nothing about pseudo insns.
--- include/uapi/linux/bpf.h | 12 ++++ kernel/bpf/verifier.c | 146 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 158 insertions(+)
include/uapi/linux/bpf.h +12 -0
@@ -169,6 +169,18 @@ enum { .off = 0, \ .imm = IMM }) +#define BPF_PSEUDO_MAP_FD 1 + +/* pseudo BPF_LD_IMM64 insn used to refer to process-local map_fd */ +#define BPF_LD_MAP_FD (DST ,MAP_FD ) \ + ((struct bpf_insn) { \ + .code = BPF_LD | BPF_DW | BPF_IMM, \ + .dst_reg = DST, \ + .src_reg = BPF_PSEUDO_MAP_FD, \ + .off = 0, \ + .imm = MAP_FD }), \ + BPF_LD_IMM64(DST, 0) +/* Short form of mov based on type, BPF_X: dst_reg = src_reg, BPF_K: dst_reg = imm32 */ #define BPF_MOV64_RAW (TYPE ,DST ,SRC ,IMM ) \
kernel/bpf/verifier.c +146 -0
187 lines not on this page · raw message
Signature · 1 line
1.7.9.5
RFC PATCH v4 12/26 bpf: verifier (add branch/goto checks)
In reply to Alexei Starovoitovcheck that control flow graph of eBPF program is a directed acyclic graph
check_cfg() does:
- detect loops
- detect unreachable instructions
- check that program terminates with BPF_EXIT insn
- check that all branches are within program boundary
--- kernel/bpf/verifier.c | 183 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 183 insertions(+)
kernel/bpf/verifier.c +183 -0
@@ -331,6 +331,185 @@ static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)return (struct bpf_map *) (unsigned long ) imm64; } +/* non-recursive DFS pseudo code +* 1 procedure DFS-iterative(G,v): +* 2 label v as discovered +* 3 let S be a stack +* 4 S.push(v) +* 5 while S is not empty +* 6 t <- S.pop() +* 7 if t is what we're looking for: +* 8 return t +* 9 for all edges e in G.adjacentEdges(t) do +* 10 if edge e is already labelled +* 11 continue with the next edge +* 12 w <- G.adjacentVertex(t,e) +* 13 if vertex w is not discovered and not explored +* 14 label e as tree-edge +* 15 label w as discovered +* 16 S.push(w) +* 17 continue at 5 +* 18 else if vertex w is discovered +* 19 label e as back-edge +* 20 else +* 21 // vertex w is explored +* 22 label e as forward- or cross-edge +* 23 label t as explored +* 24 S.pop() +* +* convention: +* 0x10 - discovered +* 0x11 - discovered and fall-through edge labelled +* 0x12 - discovered and fall-through and branch edges labelled +* 0x20 - explored +*/ + +enum { +DISCOVERED =0x10 , +EXPLORED =0x20 , +FALLTHROUGH =1 , +BRANCH =2 , +}; + +#define PUSH_INT (I ) \ + do { \ + if (cur_stack >= insn_cnt) { \ + ret = -E2BIG; \ + goto free_st; \ + } \ + stack[cur_stack++] = I; \ + } while (0) + +#define PEEK_INT () \ + ({ \ + int _ret; \ + if (cur_stack == 0) \ + _ret = -1; \ + else \ + _ret = stack[cur_stack - 1]; \ + _ret; \ + }) + +#define POP_INT () \ + ({ \ + int _ret; \ + if (cur_stack == 0) \ + _ret = -1; \ + else \ + _ret = stack[--cur_stack]; \ + _ret; \ + }) + +#define PUSH_INSN (T ,W ,E ) \ + do { \ + int w = W; \ + if (E == FALLTHROUGH && st[T] >= (DISCOVERED | FALLTHROUGH)) \ + break; \ + if (E == BRANCH && st[T] >= (DISCOVERED | BRANCH)) \ + break; \ + if (w < 0 || w >= insn_cnt) { \ + verbose("jump out of range from insn %d to %d\n", T, w); \ + ret = -EINVAL; \ + goto free_st; \ + } \ + if (st[w] == 0) { \ +/* tree-edge */ \ + st[T ] =DISCOVERED |E ; \ + st[w] =DISCOVERED ; \ +PUSH_INT (w); \ + goto peek_stack; \ + } else if ((st[w] & 0xF0) == DISCOVERED) { \ +verbose ("back-edge from insn %d to %d\n" ,T , w); \ + ret = -EINVAL ; \ + goto free_st; \ + }else if (st[w] ==EXPLORED ) { \ +/* forward- or cross-edge */ \ + st[T ] =DISCOVERED |E ; \ + }else { \ +verbose ("insn state internal bug\n" ); \ + ret = -EFAULT ; \ + goto free_st; \ + } \ + } while (0) + +/* non-recursive depth-first-search to detect loops in BPF program +* loop == back-edge in directed graph +*/ +static int check_cfg(struct verifier_env *env) +{ +struct bpf_insn *insns = env->prog->insnsi; +int insn_cnt = env->prog->len; +int cur_stack =0 ; +int *stack; +int ret =0 ; +int *st; +int i, t; + + st =kzalloc (sizeof (int ) * insn_cnt,GFP_KERNEL ); +if (!st) +return -ENOMEM ; + + stack =kzalloc (sizeof (int ) * insn_cnt,GFP_KERNEL ); +if (!stack) { +kfree (st); +return -ENOMEM ; + } + + st[0 ] =DISCOVERED ;/* mark 1st insn as discovered */ +PUSH_INT (0 ); + +peek_stack: +while ((t =PEEK_INT ()) !=-1 ) { +if (BPF_CLASS (insns[t].code) ==BPF_JMP ) { +u8 opcode =BPF_OP (insns[t].code); + +if (opcode ==BPF_EXIT ) { + goto mark_explored; + }else if (opcode ==BPF_CALL ) { +PUSH_INSN (t, t +1 ,FALLTHROUGH ); + }else if (opcode ==BPF_JA ) { +if (BPF_SRC (insns[t].code) !=BPF_K ) { + ret = -EINVAL ; + goto free_st; + } +/* unconditional jump with single edge */ +PUSH_INSN (t, t + insns[t].off +1 ,FALLTHROUGH ); + }else { +/* conditional jump with two edges */ +PUSH_INSN (t, t +1 ,FALLTHROUGH ); +PUSH_INSN (t, t + insns[t].off +1 ,BRANCH ); + } + }else { +/* all other non-branch instructions with single +* fall-through edge +*/ +PUSH_INSN (t, t +1 ,FALLTHROUGH ); + } + +mark_explored: + st[t] =EXPLORED ; +if (POP_INT () ==-1 ) { +verbose ("pop_int internal bug\n" ); + ret = -EFAULT ; + goto free_st; + } + } + + +for (i =0 ; i < insn_cnt; i++) { +if (st[i] !=EXPLORED ) { +verbose ("unreachable insn %d\n" , i); + ret = -EINVAL ; + goto free_st; + } + } + +free_st: +kfree (st); +kfree (stack); +return ret; +} +/* look for pseudo eBPF instructions that access map FDs and * replace them with actual map pointers */
@@ -480,6 +659,10 @@ int bpf_check(struct bpf_prog *prog, struct nlattr *tb[BPF_PROG_ATTR_MAX + 1])if (ret <0 ) goto skip_full_check; + ret =check_cfg (env); +if (ret <0 ) + goto skip_full_check; +/* ret = do_check(env); */ skip_full_check:
Signature · 1 line
1.7.9.5
RFC PATCH v4 13/26 bpf: verifier (add verifier core)
In reply to Alexei StarovoitovThis patch adds verifier core which simulates execution of every insn and records the state of registers and program stack. Every branch instruction seen during simulation is pushed into state stack. When verifier reaches BPF_EXIT, it pops the state from the stack and continues until it reaches BPF_EXIT again. For program:
1: bpf_mov r1, xxx
2: if (r1 == 0) goto 5
3: bpf_mov r0, 1
4: goto 6
5: bpf_mov r0, 2
6: bpf_exit
The verifier will walk insns: 1, 2, 3, 4, 6
then it will pop the state recorded at insn#2 and will continue: 5, 6
This way it walks all possible paths through the program and checks all possible values of registers. While doing so, it checks for:
- invalid instructions
- uninitialized register access
- uninitialized stack access
- misaligned stack access
- out of range stack access
- invalid calling convention
- BPF_LD_ABS|IND instructions are only used in socket filters
- instruction encoding is not using reserved fields
Kernel subsystem configures the verifier with two callbacks:
- bool (*is_valid_access)(int off, int size, enum bpf_access_type type); that provides information to the verifer which fields of 'ctx' are accessible (remember 'ctx' is the first argument to eBPF program)
- const struct bpf_func_proto *(*get_func_proto)(enum bpf_func_id func_id); returns argument constraints of kernel helper functions that eBPF program may call, so that verifier can checks that R1-R5 types match the prototype
More details in Documentation/networking/filter.txt and in kernel/bpf/verifier.c
--- include/linux/bpf.h | 47 +++ include/uapi/linux/bpf.h | 1 + kernel/bpf/verifier.c | 990 +++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 1037 insertions(+), 1 deletion(-)
include/linux/bpf.h +47 -0
@@ -47,6 +47,31 @@ void bpf_register_map_type(struct bpf_map_type_list *tl);void bpf_map_put (struct bpf_map *map);struct bpf_map *bpf_map_get (struct fd f); +/* function argument constraints */ +enum bpf_arg_type { +ARG_ANYTHING =0 ,/* any argument is ok */ + +/* the following constraints used to prototype +* bpf_map_lookup/update/delete_elem() functions +*/ +ARG_CONST_MAP_PTR ,/* const argument used as pointer to bpf_map */ +ARG_PTR_TO_MAP_KEY ,/* pointer to stack used as map key */ +ARG_PTR_TO_MAP_VALUE ,/* pointer to stack used as map value */ + +/* the following constraints used to prototype bpf_memcmp() and other +* functions that access data on eBPF program stack +*/ +ARG_PTR_TO_STACK ,/* any pointer to eBPF program stack */ +ARG_CONST_STACK_SIZE ,/* number of bytes accessed from stack */ +}; + +/* type of values returned from helper functions */ +enum bpf_return_type { +RET_INTEGER ,/* function returns integer */ +RET_VOID ,/* function doesn't return anything */ +RET_PTR_TO_MAP_VALUE_OR_NULL ,/* returns a pointer to map elem value or NULL */ +}; +/* eBPF function prototype used by verifier to allow BPF_CALLs from eBPF programs * to in-kernel helper functions and for adjusting imm32 field in BPF_CALL * instructions after verifying
@@ -54,11 +79,33 @@ struct bpf_map *bpf_map_get(struct fd f);struct bpf_func_proto {u64 (*func)(u64 r1,u64 r2,u64 r3,u64 r4,u64 r5);bool gpl_only; +enum bpf_return_type ret_type; +enum bpf_arg_type arg1_type; +enum bpf_arg_type arg2_type; +enum bpf_arg_type arg3_type; +enum bpf_arg_type arg4_type; +enum bpf_arg_type arg5_type; +}; + +/* bpf_context is intentionally undefined structure. Pointer to bpf_context is +* the first argument to eBPF programs. +* For socket filters: 'struct bpf_context *' == 'struct sk_buff *' +*/ +struct bpf_context ; + +enum bpf_access_type { +BPF_READ =1 , +BPF_WRITE =2 };struct bpf_verifier_ops {/* return eBPF function prototype for verification */ const struct bpf_func_proto *(*get_func_proto)(enum bpf_func_id func_id); + +/* return true if 'size' wide access at offset 'off' within bpf_context +* with 'type' (read or write) is allowed +*/ +bool (*is_valid_access)(int off,int size,enum bpf_access_type type); };struct bpf_prog_type_list {
include/uapi/linux/bpf.h +1 -0
@@ -395,6 +395,7 @@ enum bpf_prog_attributes {enum bpf_prog_type {BPF_PROG_TYPE_UNSPEC , +BPF_PROG_TYPE_SOCKET_FILTER , };/* integer value in 'imm' field of BPF_CALL instruction selects which helper
kernel/bpf/verifier.c +989 -1
1,034 lines not on this page · raw message
Signature · 1 line
1.7.9.5
RFC PATCH v4 14/26 bpf: verifier (add state prunning optimization)
In reply to Alexei Starovoitovsince verifier walks all possible paths it's important to recognize equivalent verifier states to speed up verification.
If one of the old states is more strict than the current state, it means the current state doesn't need to be explored further, since verifier already concluded that more strict state leads to valid bpf_exit.
--- kernel/bpf/verifier.c | 134 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 134 insertions(+)
kernel/bpf/verifier.c +134 -0
@@ -219,6 +219,7 @@ struct verifier_env {struct verifier_stack_elem *head;/* stack of verifier states to be processed */ int stack_size;/* number of states to be processed */ struct verifier_state cur_state;/* current verifier state */ +struct verifier_state_list **branch_landing;/* search prunning optimization */ struct bpf_map *used_maps[MAX_USED_MAPS ];/* array of map's used by eBPF program */ u32 used_map_cnt;/* number of used maps */ };
@@ -1207,6 +1208,8 @@ enum { BRANCH = 2, }; +#define STATE_END ((struct verifier_state_list *) -1L) +#define PUSH_INT (I ) \ do { \ if (cur_stack >= insn_cnt) { \
@@ -1248,6 +1251,9 @@ enum { ret = -EINVAL ; \ goto free_st; \ } \ +if (E ==BRANCH ) \ +/* mark branch target for state pruning */ \ + env->branch_landing[w] =STATE_END ; \if (st[w] ==0 ) { \/* tree-edge */ \ st[T ] =DISCOVERED |E ; \
@@ -1315,6 +1321,10 @@ peek_stack:PUSH_INSN (t, t +1 ,FALLTHROUGH );PUSH_INSN (t, t + insns[t].off +1 ,BRANCH ); } +/* tell verifier to check for equivalent verifier states +* after every call and jump +*/ + env->branch_landing[t +1 ] =STATE_END ; }else {/* all other non-branch instructions with single * fall-through edge
@@ -1346,6 +1356,88 @@ free_st:return ret; } +/* compare two verifier states +* +* all states stored in state_list are known to be valid, since +* verifier reached 'bpf_exit' instruction through them +* +* this function is called when verifier exploring different branches of +* execution popped from the state stack. If it sees an old state that has +* more strict register state and more strict stack state then this execution +* branch doesn't need to be explored further, since verifier already +* concluded that more strict state leads to valid finish. +* +* Therefore two states are equivalent if register state is more conservative +* and explored stack state is more conservative than the current one. +* Example: +* explored current +* (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) +* (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) +* +* In other words if current stack state (one being explored) has more +* valid slots than old one that already passed validation, it means +* the verifier can stop exploring and conclude that current state is valid too +* +* Similarly with registers. If explored state has register type as invalid +* whereas register type in current state is meaningful, it means that +* the current state will reach 'bpf_exit' instruction safely +*/ +static bool states_equal (struct verifier_state *old,struct verifier_state *cur) +{ +int i; + +for (i =0 ; i <MAX_BPF_REG ; i++) { +if (memcmp (&old->regs[i], &cur->regs[i], +sizeof (old->regs[0 ])) !=0 ) { +if (old->regs[i].type ==NOT_INIT || + old->regs[i].type ==UNKNOWN_VALUE ) +continue ; +return false; + } + } + +for (i =0 ; i <MAX_BPF_STACK ; i++) { +if (memcmp (&old->stack[i], &cur->stack[i], +sizeof (old->stack[0 ])) !=0 ) { +if (old->stack[i].stype ==STACK_INVALID ) +continue ; +return false; + } + } +return true; +} + +static int is_state_visited (struct verifier_env *env,int insn_idx) +{ +struct verifier_state_list *new_sl; +struct verifier_state_list *sl; + + sl = env->branch_landing[insn_idx]; +if (!sl) +/* no branch jump to this insn, ignore it */ +return 0 ; + +while (sl !=STATE_END ) { +if (states_equal (&sl->state, &env->cur_state)) +/* reached equivalent register/stack state, +* prune the search +*/ +return 1 ; + sl = sl->next; + } + new_sl =kmalloc (sizeof (struct verifier_state_list ),GFP_KERNEL ); + +if (!new_sl) +/* ignore ENOMEM, it doesn't affect correctness */ +return 0 ; + +/* add new state to the head of linked list */ +memcpy (&new_sl->state, &env->cur_state,sizeof (env->cur_state)); + new_sl->next = env->branch_landing[insn_idx]; + env->branch_landing[insn_idx] = new_sl; +return 0 ; +} +static int do_check (struct verifier_env *env) {struct verifier_state *state = &env->cur_state;
@@ -1377,6 +1469,17 @@ static int do_check(struct verifier_env *env)return -E2BIG ; } +if (is_state_visited (env, insn_idx)) { +if (log_level) { +if (do_print_state) +verbose ("\nfrom %d to %d: safe\n" , + prev_insn_idx, insn_idx); +else +verbose ("%d: safe\n" , insn_idx); + } + goto process_bpf_exit; + } +if (log_level && do_print_state) {verbose ("\nfrom %d to %d:" , prev_insn_idx, insn_idx);print_verifier_state (env);
@@ -1464,6 +1567,7 @@ static int do_check(struct verifier_env *env)* something into it earlier */ _ (check_reg_arg (regs,BPF_REG_0 ,1 )); +process_bpf_exit: insn_idx =pop_stack (env, &prev_insn_idx);if (insn_idx <0 ) {break ;
@@ -1597,6 +1701,28 @@ static void convert_pseudo_ld_imm64(struct verifier_env *env) insn->src_reg =0 ; } +static void free_states (struct verifier_env *env) +{ +struct verifier_state_list *sl, *sln; +int i; + +if (!env->branch_landing) +return ; + +for (i =0 ; i < env->prog->len; i++) { + sl = env->branch_landing[i]; + +if (sl) +while (sl !=STATE_END ) { + sln = sl->next; +kfree (sl); + sl = sln; + } + } + +kfree (env->branch_landing); +} +int bpf_check (struct bpf_prog *prog,struct nlattr *tb[BPF_PROG_ATTR_MAX +1 ]) {void __user *log_ubuf =NULL ;
@@ -1646,6 +1772,13 @@ int bpf_check(struct bpf_prog *prog, struct nlattr *tb[BPF_PROG_ATTR_MAX + 1])if (ret <0 ) goto skip_full_check; + env->branch_landing =kcalloc (prog->len, +sizeof (struct verifier_state_list *), +GFP_KERNEL ); + ret = -ENOMEM ; +if (!env->branch_landing) + goto skip_full_check; + ret =check_cfg (env);if (ret <0 ) goto skip_full_check;
@@ -1654,6 +1787,7 @@ int bpf_check(struct bpf_prog *prog, struct nlattr *tb[BPF_PROG_ATTR_MAX + 1]) skip_full_check:while (pop_stack (env,NULL ) >=0 ); +free_states (env);if (log_level && log_len >= log_size -1 ) {BUG_ON (log_len >= log_size);
Signature · 1 line
1.7.9.5
RFC PATCH v4 15/26 bpf: allow eBPF programs to use maps
In reply to Alexei Starovoitovexpose bpf_map_lookup_elem(), bpf_map_update_elem(), bpf_map_delete_elem() map accessors to eBPF programs
--- include/linux/bpf.h | 5 ++++ include/uapi/linux/bpf.h | 3 ++ kernel/bpf/syscall.c | 68 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 76 insertions(+)
include/linux/bpf.h +5 -0
@@ -132,4 +132,9 @@ struct bpf_prog *bpf_prog_get(u32 ufd);/* verify correctness of eBPF program */ int bpf_check (struct bpf_prog *fp,struct nlattr *tb[BPF_PROG_ATTR_MAX +1 ]); +/* in-kernel helper functions called from eBPF programs */ +u64 bpf_map_lookup_elem (u64 r1,u64 r2,u64 r3,u64 r4,u64 r5); +u64 bpf_map_update_elem (u64 r1,u64 r2,u64 r3,u64 r4,u64 r5); +u64 bpf_map_delete_elem (u64 r1,u64 r2,u64 r3,u64 r4,u64 r5); +#endif /* _LINUX_BPF_H */
include/uapi/linux/bpf.h +3 -0
@@ -403,6 +403,9 @@ enum bpf_prog_type {*/ enum bpf_func_id { BPF_FUNC_unspec, + BPF_FUNC_map_lookup_elem,/* void *map_lookup_elem(&map, &key) */ + BPF_FUNC_map_update_elem,/* int map_update_elem(&map, &key, &value) */ + BPF_FUNC_map_delete_elem,/* int map_delete_elem(&map, &key) */ __BPF_FUNC_MAX_ID, };
kernel/bpf/syscall.c +68 -0
71 lines not on this page · raw message
Signature · 1 line
1.7.9.5
RFC PATCH v4 16/26 net: sock: allow eBPF programs to be attached to sockets
In reply to Alexei Starovoitovintroduce new setsockopt() command:
int fd;setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER_EBPF, &fd, sizeof(fd))
fd is associated with eBPF program priorly loaded via:
fd = syscall(__NR_bpf, BPF_PROG_LOAD, BPF_PROG_TYPE_SOCKET_FILTER,
&prog, sizeof(prog));
setsockopt() calls bpf_prog_get() which increment refcnt of the program, so it doesn't get unloaded while socket is using the program.
The same eBPF program can be attached to different sockets.
Program exit automatically closes socket which calls sk_filter_uncharge() which decrements refcnt of eBPF program
--- arch/alpha/include/uapi/asm/socket.h | 2 + arch/avr32/include/uapi/asm/socket.h | 2 + arch/cris/include/uapi/asm/socket.h | 2 + arch/frv/include/uapi/asm/socket.h | 2 + arch/ia64/include/uapi/asm/socket.h | 2 + arch/m32r/include/uapi/asm/socket.h | 2 + arch/mips/include/uapi/asm/socket.h | 2 + arch/mn10300/include/uapi/asm/socket.h | 2 + arch/parisc/include/uapi/asm/socket.h | 2 + arch/powerpc/include/uapi/asm/socket.h | 2 + arch/s390/include/uapi/asm/socket.h | 2 + arch/sparc/include/uapi/asm/socket.h | 2 + arch/xtensa/include/uapi/asm/socket.h | 2 + include/linux/filter.h | 1 + include/uapi/asm-generic/socket.h | 2 + net/core/filter.c | 135 +++++++++++++++++++++++++++++++- net/core/sock.c | 13 +++ 17 files changed, 175 insertions(+), 2 deletions(-)
arch/alpha/include/uapi/asm/socket.h +2 -0
@@ -87,4 +87,6 @@#define SO_BPF_EXTENSIONS 48 +#define SO_ATTACH_FILTER_EBPF 49 +#endif /* _UAPI_ASM_SOCKET_H */
arch/avr32/include/uapi/asm/socket.h +2 -0
@@ -80,4 +80,6 @@#define SO_BPF_EXTENSIONS 48 +#define SO_ATTACH_FILTER_EBPF 49 +#endif /* _UAPI__ASM_AVR32_SOCKET_H */
arch/cris/include/uapi/asm/socket.h +2 -0
@@ -82,6 +82,8 @@#define SO_BPF_EXTENSIONS 48 +#define SO_ATTACH_FILTER_EBPF 49 +#endif /* _ASM_SOCKET_H */
arch/frv/include/uapi/asm/socket.h +2 -0
@@ -80,5 +80,7 @@#define SO_BPF_EXTENSIONS 48 +#define SO_ATTACH_FILTER_EBPF 49 +#endif /* _ASM_SOCKET_H */
arch/ia64/include/uapi/asm/socket.h +2 -0
@@ -89,4 +89,6 @@#define SO_BPF_EXTENSIONS 48 +#define SO_ATTACH_FILTER_EBPF 49 +#endif /* _ASM_IA64_SOCKET_H */
arch/m32r/include/uapi/asm/socket.h +2 -0
@@ -80,4 +80,6 @@#define SO_BPF_EXTENSIONS 48 +#define SO_ATTACH_FILTER_EBPF 49 +#endif /* _ASM_M32R_SOCKET_H */
arch/mips/include/uapi/asm/socket.h +2 -0
@@ -98,4 +98,6 @@#define SO_BPF_EXTENSIONS 48 +#define SO_ATTACH_FILTER_EBPF 49 +#endif /* _UAPI_ASM_SOCKET_H */
arch/mn10300/include/uapi/asm/socket.h +2 -0
@@ -80,4 +80,6 @@#define SO_BPF_EXTENSIONS 48 +#define SO_ATTACH_FILTER_EBPF 49 +#endif /* _ASM_SOCKET_H */
arch/parisc/include/uapi/asm/socket.h +2 -0
@@ -79,4 +79,6 @@#define SO_BPF_EXTENSIONS 0x4029 +#define SO_ATTACH_FILTER_EBPF 0x402a +#endif /* _UAPI_ASM_SOCKET_H */
arch/powerpc/include/uapi/asm/socket.h +2 -0
@@ -87,4 +87,6 @@#define SO_BPF_EXTENSIONS 48 +#define SO_ATTACH_FILTER_EBPF 49 +#endif /* _ASM_POWERPC_SOCKET_H */
arch/s390/include/uapi/asm/socket.h +2 -0
@@ -86,4 +86,6 @@#define SO_BPF_EXTENSIONS 48 +#define SO_ATTACH_FILTER_EBPF 49 +#endif /* _ASM_SOCKET_H */
arch/sparc/include/uapi/asm/socket.h +2 -0
@@ -76,6 +76,8 @@#define SO_BPF_EXTENSIONS 0x0032 +#define SO_ATTACH_FILTER_EBPF 0x0033 +/* Security levels - as per NRL IPv6 - don't actually do anything */ #define SO_SECURITY_AUTHENTICATION 0x5001#define SO_SECURITY_ENCRYPTION_TRANSPORT 0x5002
arch/xtensa/include/uapi/asm/socket.h +2 -0
@@ -91,4 +91,6 @@#define SO_BPF_EXTENSIONS 48 +#define SO_ATTACH_FILTER_EBPF 49 +#endif /* _XTENSA_SOCKET_H */
include/linux/filter.h +1 -0
@@ -78,6 +78,7 @@ int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog);void bpf_prog_destroy (struct bpf_prog *fp);int sk_attach_filter (struct sock_fprog *fprog,struct sock *sk); +int sk_attach_filter_ebpf (u32 ufd,struct sock *sk);int sk_detach_filter (struct sock *sk);int bpf_check_classic (const struct sock_filter *filter,unsigned int flen);
include/uapi/asm-generic/socket.h +2 -0
@@ -82,4 +82,6 @@#define SO_BPF_EXTENSIONS 48 +#define SO_ATTACH_FILTER_EBPF 49 +#endif /* __ASM_GENERIC_SOCKET_H */
net/core/filter.c +133 -2
153 lines not on this page · raw message
net/core/sock.c +13 -0
@@ -896,6 +896,19 @@ set_rcvbuf: }break ; +case SO_ATTACH_FILTER_EBPF : + ret = -EINVAL ; +if (optlen ==sizeof (u32)) { +u32 ufd; + + ret = -EFAULT ; +if (copy_from_user (&ufd, optval,sizeof (ufd))) +break ; + + ret =sk_attach_filter_ebpf (ufd, sk); + } +break ; +case SO_DETACH_FILTER : ret =sk_detach_filter (sk);break ;
Signature · 1 line
1.7.9.5
RFC PATCH v4 17/26 tracing: allow eBPF programs to be attached to events
In reply to Alexei StarovoitovUser interface:
fd = open("/sys/kernel/debug/tracing/__event__/filter")
write(fd, "bpf_123")
where 123 is process local FD associated with eBPF program previously loaded. __event__ is static tracepoint event or syscall.
(kprobe support is in next patch)
Once program is successfully attached to tracepoint event, the tracepoint will be auto-enabled
close(fd)
auto-disables tracepoint event and detaches eBPF program from it
eBPF programs can call in-kernel helper functions to:
- lookup/update/delete elements in maps
- memcmp
- trace_printk
- dump_stack
- fetch_ptr/u64/u32/u16/u8 values from unsafe address via probe_kernel_read(), so that eBPF program can walk any kernel data structures
--- include/linux/ftrace_event.h | 5 + include/trace/bpf_trace.h | 30 +++++ include/trace/ftrace.h | 10 ++ include/uapi/linux/bpf.h | 9 ++ kernel/trace/Kconfig | 1 + kernel/trace/Makefile | 1 + kernel/trace/bpf_trace.c | 241 ++++++++++++++++++++++++++++++++++++ kernel/trace/trace.h | 3 + kernel/trace/trace_events.c | 36 +++++- kernel/trace/trace_events_filter.c | 72 ++++++++++- kernel/trace/trace_syscalls.c | 18 +++ 11 files changed, 424 insertions(+), 2 deletions(-) create mode 100644 include/trace/bpf_trace.h create mode 100644 kernel/trace/bpf_trace.c
include/linux/ftrace_event.h +5 -0
@@ -237,6 +237,7 @@ enum {TRACE_EVENT_FL_WAS_ENABLED_BIT ,TRACE_EVENT_FL_USE_CALL_FILTER_BIT ,TRACE_EVENT_FL_TRACEPOINT_BIT , + TRACE_EVENT_FL_BPF_BIT, };/*
@@ -259,6 +260,7 @@ enum {TRACE_EVENT_FL_WAS_ENABLED = (1 <<TRACE_EVENT_FL_WAS_ENABLED_BIT ),TRACE_EVENT_FL_USE_CALL_FILTER = (1 <<TRACE_EVENT_FL_USE_CALL_FILTER_BIT ),TRACE_EVENT_FL_TRACEPOINT = (1 <<TRACE_EVENT_FL_TRACEPOINT_BIT ), + TRACE_EVENT_FL_BPF = (1 << TRACE_EVENT_FL_BPF_BIT), }; struct ftrace_event_call {
@@ -533,6 +535,9 @@ event_trigger_unlock_commit_regs(struct ftrace_event_file *file,event_triggers_post_call (file, tt); } +struct bpf_context ; +void trace_filter_call_bpf (struct event_filter *filter,struct bpf_context *ctx); +enum {FILTER_OTHER =0 ,FILTER_STATIC_STRING ,
include/trace/bpf_trace.h new file +30 -0
@@ -0,0 +1,30 @@ +/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of version 2 of the GNU General Public +* License as published by the Free Software Foundation. +*/ +#ifndef _LINUX_KERNEL_BPF_TRACE_H +#define _LINUX_KERNEL_BPF_TRACE_H + +/* For tracing filters save first six arguments of tracepoint events. +* On 64-bit architectures argN fields will match one to one to arguments passed +* to tracepoint events. +* On 32-bit architectures u64 arguments to events will be seen into two +* consecutive argN, argN+1 fields. Pointers, u32, u16, u8, bool types will +* match one to one +*/ +struct bpf_context { +unsigned long arg1; +unsigned long arg2; +unsigned long arg3; +unsigned long arg4; +unsigned long arg5; +unsigned long arg6; +unsigned long ret; +}; + +/* call from ftrace_raw_event_*() to copy tracepoint arguments into ctx */ +void populate_bpf_context (struct bpf_context *ctx, ...); + +#endif /* _LINUX_KERNEL_BPF_TRACE_H */
include/trace/ftrace.h +10 -0
@@ -17,6 +17,7 @@*/ #include <linux/ftrace_event.h> +#include <trace/bpf_trace.h> /* * DECLARE_EVENT_CLASS can be used to add a generic function
@@ -634,6 +635,15 @@ ftrace_raw_event_##call(void *__data, proto) \if (ftrace_trigger_soft_disabled (ftrace_file)) \return ; \ \ +if (unlikely (ftrace_file->flags &FTRACE_EVENT_FL_FILTERED ) && \ +unlikely (ftrace_file->event_call->flags &TRACE_EVENT_FL_BPF )) { \ +struct bpf_context __ctx; \ + \ +populate_bpf_context (&__ctx, args,0 ,0 ,0 ,0 ,0 ); \ +trace_filter_call_bpf (ftrace_file->filter, &__ctx); \ +return ; \ + } \ + \ __data_size = ftrace_get_offsets_##call(&__data_offsets, args); \ \ entry = ftrace_event_buffer_reserve(&fbuffer, ftrace_file, \
include/uapi/linux/bpf.h +9 -0
@@ -396,6 +396,7 @@ enum bpf_prog_attributes {enum bpf_prog_type {BPF_PROG_TYPE_UNSPEC ,BPF_PROG_TYPE_SOCKET_FILTER , +BPF_PROG_TYPE_TRACING_FILTER , };/* integer value in 'imm' field of BPF_CALL instruction selects which helper
@@ -406,6 +407,14 @@ enum bpf_func_id { BPF_FUNC_map_lookup_elem,/* void *map_lookup_elem(&map, &key) */ BPF_FUNC_map_update_elem,/* int map_update_elem(&map, &key, &value) */ BPF_FUNC_map_delete_elem,/* int map_delete_elem(&map, &key) */ + BPF_FUNC_fetch_ptr,/* void *bpf_fetch_ptr(void *unsafe_ptr) */ + BPF_FUNC_fetch_u64,/* u64 bpf_fetch_u64(void *unsafe_ptr) */ + BPF_FUNC_fetch_u32,/* u32 bpf_fetch_u32(void *unsafe_ptr) */ + BPF_FUNC_fetch_u16,/* u16 bpf_fetch_u16(void *unsafe_ptr) */ + BPF_FUNC_fetch_u8,/* u8 bpf_fetch_u8(void *unsafe_ptr) */ + BPF_FUNC_memcmp,/* int bpf_memcmp(void *unsafe_ptr, void *safe_ptr, int size) */ + BPF_FUNC_dump_stack,/* void bpf_dump_stack(void) */ + BPF_FUNC_printk,/* int bpf_printk(const char *fmt, int fmt_size, ...) */ __BPF_FUNC_MAX_ID, };
kernel/trace/Kconfig +1 -0
@@ -75,6 +75,7 @@ config FTRACE_NMI_ENTER config EVENT_TRACING select CONTEXT_SWITCH_TRACER + depends on NET bool config CONTEXT_SWITCH_TRACER
kernel/trace/Makefile +1 -0
@@ -53,6 +53,7 @@ obj-$(CONFIG_EVENT_TRACING) += trace_event_perf.o endif obj-$(CONFIG_EVENT_TRACING) += trace_events_filter.o obj-$(CONFIG_EVENT_TRACING) += trace_events_trigger.o +obj-$(CONFIG_EVENT_TRACING) += bpf_trace.o obj-$(CONFIG_KPROBE_EVENT) += trace_kprobe.o obj-$(CONFIG_TRACEPOINTS) += power-traces.o ifeq ($(CONFIG_PM_RUNTIME),y)
kernel/trace/bpf_trace.c new file +241 -0
241 lines not on this page · raw message
kernel/trace/trace.h +3 -0
@@ -986,12 +986,15 @@ struct ftrace_event_field {int is_signed; }; +struct bpf_prog ; +struct event_filter {int n_preds;/* Number assigned */ int a_preds;/* allocated */ struct filter_pred *preds;struct filter_pred *root;char *filter_string; +struct bpf_prog *prog; };struct event_subsystem {
kernel/trace/trace_events.c +35 -1
@@ -1051,6 +1051,26 @@ event_filter_read(struct file *filp, char __user *ubuf, size_t cnt,return r; } +static int event_filter_release (struct inode *inode,struct file *filp) +{ +struct ftrace_event_file *file; +char buf[2 ] ="0" ; + +mutex_lock (&event_mutex); + file =event_file_data (filp); +if (file) { +if (file->event_call->flags &TRACE_EVENT_FL_BPF ) { +/* auto-disable the filter */ +ftrace_event_enable_disable (file,0 ); + +/* if BPF filter was used, clear it on fd close */ +apply_event_filter (file, buf); + } + } +mutex_unlock (&event_mutex); +return 0 ; +} +static ssize_t event_filter_write (struct file *filp,const char __user *ubuf,size_t cnt,loff_t *ppos)
@@ -1074,10 +1094,23 @@ event_filter_write(struct file *filp, const char __user *ubuf, size_t cnt,mutex_lock (&event_mutex); file =event_file_data (filp); -if (file) +if (file) { err =apply_event_filter (file, buf); +if (!err && file->event_call->flags &TRACE_EVENT_FL_BPF ) +/* once filter is applied, auto-enable it */ +ftrace_event_enable_disable (file,1 ); + } +mutex_unlock (&event_mutex); +if (file && file->event_call->flags &TRACE_EVENT_FL_BPF ) { +/* +* allocate per-cpu printk buffers, since eBPF program +* might be calling bpf_trace_printk +*/ +trace_printk_init_buffers (); + } +free_page ((unsigned long ) buf);if (err <0 )return err;
@@ -1328,6 +1361,7 @@ static const struct file_operations ftrace_event_filter_fops = { .open = tracing_open_generic, .read = event_filter_read, .write = event_filter_write, + .release = event_filter_release, .llseek = default_llseek, };
kernel/trace/trace_events_filter.c +71 -1
102 lines not on this page · raw message
kernel/trace/trace_syscalls.c +18 -0
@@ -7,6 +7,7 @@#include <linux/ftrace.h> #include <linux/perf_event.h> #include <asm/syscall.h> +#include <trace/bpf_trace.h> #include "trace_output.h" #include "trace.h"
@@ -328,6 +329,14 @@ static void ftrace_syscall_enter(void *data, struct pt_regs *regs, long id)if (!sys_data)return ; +if (ftrace_file->event_call->flags &TRACE_EVENT_FL_BPF ) { +struct bpf_context __ctx; +syscall_get_arguments (current, regs,0 , sys_data->nb_args, + &__ctx.arg1); +trace_filter_call_bpf (ftrace_file->filter, &__ctx); +return ; + } + size =sizeof (*entry) +sizeof (unsigned long ) * sys_data->nb_args;local_save_flags (irq_flags);
@@ -375,6 +384,15 @@ static void ftrace_syscall_exit(void *data, struct pt_regs *regs, long ret)if (!sys_data)return ; +if (ftrace_file->event_call->flags &TRACE_EVENT_FL_BPF ) { +struct bpf_context __ctx; +syscall_get_arguments (current, regs,0 , sys_data->nb_args, + &__ctx.arg1); + __ctx.ret =syscall_get_return_value (current, regs); +trace_filter_call_bpf (ftrace_file->filter, &__ctx); +return ; + } +local_save_flags (irq_flags); pc =preempt_count ();
Signature · 1 line
1.7.9.5
Re: [PATCH RFC v4 net-next 17/26] tracing: allow eBPF programs to be attached to events
On Wed, Aug 13, 2014 at 12:57 AM, Alexei Starovoitov <[email protected]> wrote:
[...]
Quoted 6 lines
include/trace/bpf_trace.h new file +6
-0+/* For tracing filters save first six arguments of tracepoint events. +* On 64-bit architectures argN fields will match one to one to arguments passed +* to tracepoint events. +* On 32-bit architectures u64 arguments to events will be seen into two +* consecutive argN, argN+1 fields. Pointers, u32, u16, u8, bool types will +* match one to one
include/trace/bpf_trace.h line 25
Quoted 10 lines
include/trace/bpf_trace.h new file +10
-0+*/ +struct bpf_context { +unsigned long arg1; +unsigned long arg2; +unsigned long arg3; +unsigned long arg4; +unsigned long arg5; +unsigned long arg6; +unsigned long ret; +};
While this works, the argN+1 shift for 32-bit is a gotcha to learn. Lets say arg1 was 64-bit, and my program only examined arg2. I'd need two programs, one for 64-bit (using arg2) and 32-bit (arg3). If there was a way not to shift arguments, I could have one program for both. Eg, additional arg1hi, arg2hi, ... for the higher order u32s.
Brendan
Re: [PATCH RFC v4 net-next 17/26] tracing: allow eBPF programs to be attached to events
Quoted 14 lines · Brendan Gregg
On Wed, Aug 13, 2014 at 12:57 AM, Alexei Starovoitov <ast-uqk4Ao+rVK5Wk0Htik3J/[email protected]> wrote:
[...]Quoted 12 lines
include/trace/bpf_trace.h new file +12
-0+/* For tracing filters save first six arguments of tracepoint events. +* On 64-bit architectures argN fields will match one to one to arguments passed +* to tracepoint events. +* On 32-bit architectures u64 arguments to events will be seen into two +* consecutive argN, argN+1 fields. Pointers, u32, u16, u8, bool types will +* match one to one +*/ +struct bpf_context { +unsigned long arg1; +unsigned long arg2; +unsigned long arg3; +unsigned long arg4;
Quoted 8 lines
include/trace/bpf_trace.h line 25
Quoted 4 lines
include/trace/bpf_trace.h new file +4
-0+unsigned long arg5; +unsigned long arg6; +unsigned long ret; +};While this works, the argN+1 shift for 32-bit is a gotcha to learn. Lets say arg1 was 64-bit, and my program only examined arg2. I'd need two programs, one for 64-bit (using arg2) and 32-bit (arg3). If there
correct.
I've picked 'long' type for these tracepoint 'arguments' to match what is going on at assembler level.
32-bit archs are passing 64-bit values in two consecutive registers or two stack slots. So it's partially exposing architectural details. I've tried to use u64 here, but it complicated tracepoint+ebpf patch a lot, since I need per-architecture support for moving C arguments into u64 variables and hacking tracepoint event definitions in a nasty ways. This 'long' type approach is the least intrusive I could find. Also out of 1842 total tracepoint fields, only 144 fields are 64-bit, so rarely one would need to deal with u64. Most of the tracepoint arguments are either longs, ints or pointers, which fits this approach the best.
In general the eBPF design approach is to keep kernel bits as simple as possible and move complexity to user space.
In this case some higher language than C for writing scripts can hide this oddity.
Re: [PATCH RFC v4 net-next 17/26] tracing: allow eBPF programs to be attached to events
Quoted 34 lines · Alexei Starovoitov
Quoted 14 lines · Brendan Gregg
On Wed, Aug 13, 2014 at 12:57 AM, Alexei Starovoitov <ast-uqk4Ao+rVK5Wk0Htik3J/[email protected]> wrote:
[...]Quoted 12 lines
include/trace/bpf_trace.h new file +12
-0+/* For tracing filters save first six arguments of tracepoint events. +* On 64-bit architectures argN fields will match one to one to arguments passed +* to tracepoint events. +* On 32-bit architectures u64 arguments to events will be seen into two +* consecutive argN, argN+1 fields. Pointers, u32, u16, u8, bool types will +* match one to one +*/ +struct bpf_context { +unsigned long arg1; +unsigned long arg2; +unsigned long arg3; +unsigned long arg4;Quoted 8 lines
include/trace/bpf_trace.h line 25
Quoted 4 lines
include/trace/bpf_trace.h new file +4
-0+unsigned long arg5; +unsigned long arg6; +unsigned long ret; +};While this works, the argN+1 shift for 32-bit is a gotcha to learn. Lets say arg1 was 64-bit, and my program only examined arg2. I'd need two programs, one for 64-bit (using arg2) and 32-bit (arg3). If there
correct.
I've picked 'long' type for these tracepoint 'arguments' to match what is going on at assembler level.
32-bit archs are passing 64-bit values in two consecutive registers or two stack slots. So it's partially exposing architectural details. I've tried to use u64 here, but it complicated tracepoint+ebpf patch a lot, since I need per-architecture support for moving C arguments into u64 variables and hacking tracepoint event definitions in a nasty ways. This 'long' type approach is the least intrusive I could find.
Quoted 8 lines
Also out of 1842 total tracepoint fields, only 144 fields are 64-bit, so rarely one would need to deal with u64. Most of the tracepoint arguments are either longs, ints or pointers, which fits this approach the best.
In general the eBPF design approach is to keep kernel bits as simple as possible and move complexity to user space.
In this case some higher language than C for writing scripts can hide this oddity.
The downside of this approach is that compat support might be difficult or impossible.
--Andy
Signature · 2 lines
Andy Lutomirski AMA Capital Management, LLC
Re: [PATCH RFC v4 net-next 17/26] tracing: allow eBPF programs to be attached to events
Quoted 2 lines · Andy Lutomirski
The downside of this approach is that compat support might be difficult or impossible.
Would do you mean by compat? 32-bit programs on 64-bit kernels? There is no such concept for eBPF. All eBPF programs are always operating on 64-bit registers.
Re: [PATCH RFC v4 net-next 17/26] tracing: allow eBPF programs to be attached to events
Quoted 8 lines · Alexei Starovoitov
Quoted 2 lines · Andy Lutomirski
The downside of this approach is that compat support might be difficult or impossible.
Would do you mean by compat? 32-bit programs on 64-bit kernels? There is no such concept for eBPF. All eBPF programs are always operating on 64-bit registers.
Doesn't the eBPF program need to know sizeof(long) to read these fields correctly? Or am I misunderstanding what the code does?
--Andy
Re: [PATCH RFC v4 net-next 17/26] tracing: allow eBPF programs to be attached to events
Quoted 6 lines · Andy Lutomirski
Quoted 5 lines · Alexei Starovoitov
Quoted 2 lines · Andy Lutomirski
The downside of this approach is that compat support might be difficult or impossible.
Quoted 6 lines
Quoted 3 lines
Would do you mean by compat? 32-bit programs on 64-bit kernels? There is no such concept for eBPF. All eBPF programs are always operating on 64-bit registers.
Doesn't the eBPF program need to know sizeof(long) to read these fields correctly? Or am I misunderstanding what the code does?
correct. eBPF program would be using 8-byte read on 64-bit kernel and 4-byte read on 32-bit kernel. Same with access to ptrace fields and pretty much all other fields in the kernel. The program will be different on different kernels.
Say, this bpf_context struct doesn't exist at all. The programs would still need to be different to walk in-kernel data structures...
Re: [PATCH RFC v4 net-next 17/26] tracing: allow eBPF programs to be attached to events
Quoted 14 lines · Alexei Starovoitov
Quoted 6 lines · Andy Lutomirski
Quoted 5 lines · Alexei Starovoitov
Quoted 2 lines · Andy Lutomirski
The downside of this approach is that compat support might be difficult or impossible.
Quoted 6 lines
Quoted 3 lines
Would do you mean by compat? 32-bit programs on 64-bit kernels? There is no such concept for eBPF. All eBPF programs are always operating on 64-bit registers.
Doesn't the eBPF program need to know sizeof(long) to read these fields correctly? Or am I misunderstanding what the code does?
Quoted 6 lines
correct. eBPF program would be using 8-byte read on 64-bit kernel and 4-byte read on 32-bit kernel. Same with access to ptrace fields and pretty much all other fields in the kernel. The program will be different on different kernels.
Say, thisbpf_contextstruct doesn't exist at all. The programs would still need to be different to walk in-kernel data structures...
Hmm. I guess this isn't so bad.
What's the actual difficulty with using u64? ISTM that, if the clang front-end can't deal with u64, there's a bigger problem. Or is it something else I don't understand.
--Andy
Re: [PATCH RFC v4 net-next 17/26] tracing: allow eBPF programs to be attached to events
Quoted 8 lines · Andy Lutomirski
Quoted 7 lines
correct. eBPF program would be using 8-byte read on 64-bit kernel and 4-byte read on 32-bit kernel. Same with access to ptrace fields and pretty much all other fields in the kernel. The program will be different on different kernels.
Say, thisbpf_contextstruct doesn't exist at all. The programs would still need to be different to walk in-kernel data structures...
Quoted 5 lines
Hmm. I guess this isn't so bad.
What's the actual difficulty with using u64? ISTM that, if the clang front-end can't deal with u64, there's a bigger problem. Or is it something else I don't understand.
clang/llvm has no problem with u64 :)
This bpf_context struct for tracing is trying to answer the question:
'what's the most convenient way to access tracepoint arguments
from a script'.
When kernel code has something like:
trace_kfree_skb(skb, net_tx_action);
the script needs to be able to access this 'skb' and 'net_tx_action' values through _single_ data structure.
In this proposal they are ctx->arg1 and ctx->arg2.
I've considered having different bpf_context's for every event, but the complexity explodes. I need to hack all event definitions and so on. imo it's better to move complexity to userspace, so program author or high level language abstracts these details.
Re: [PATCH RFC v4 net-next 17/26] tracing: allow eBPF programs to be attached to events
Quoted 15 lines · Alexei Starovoitov
Quoted 8 lines · Andy Lutomirski
Quoted 7 lines
correct. eBPF program would be using 8-byte read on 64-bit kernel and 4-byte read on 32-bit kernel. Same with access to ptrace fields and pretty much all other fields in the kernel. The program will be different on different kernels.
Say, thisbpf_contextstruct doesn't exist at all. The programs would still need to be different to walk in-kernel data structures...Quoted 5 lines
Hmm. I guess this isn't so bad.
What's the actual difficulty with using u64? ISTM that, if the clang front-end can't deal with u64, there's a bigger problem. Or is it something else I don't understand.
Quoted 13 lines
clang/llvm has no problem with u64 :)
Thisbpf_contextstruct for tracing is trying to answer the question:
'what's the most convenient way to access tracepoint arguments
from a script'.
When kernel code has something like:
trace_kfree_skb(skb, net_tx_action);
the script needs to be able to access this 'skb' and 'net_tx_action' values through _single_ data structure.
In this proposal they arectx->arg1andctx->arg2.
I've considered having different bpf_context's for every event, but the complexity explodes. I need to hack all event definitions and so on. imo it's better to move complexity to userspace, so program author or high level language abstracts these details.
I still don't understand why making them long instead of u64 is helpful, though. I feel like I'm missing obvious here.
Signature · 2 lines
Andy Lutomirski AMA Capital Management, LLC
Re: [PATCH RFC v4 net-next 17/26] tracing: allow eBPF programs to be attached to events
Quoted 15 lines · Andy Lutomirski
Quoted 14 lines
clang/llvm has no problem with u64 :)
Thisbpf_contextstruct for tracing is trying to answer the question:
'what's the most convenient way to access tracepoint arguments
from a script'.
When kernel code has something like:
trace_kfree_skb(skb, net_tx_action);
the script needs to be able to access this 'skb' and 'net_tx_action' values through _single_ data structure.
In this proposal they arectx->arg1andctx->arg2.
I've considered having different bpf_context's for every event, but the complexity explodes. I need to hack all event definitions and so on. imo it's better to move complexity to userspace, so program author or high level language abstracts these details.
Quoted 2 lines
I still don't understand why making them long instead of u64 is helpful, though. I feel like I'm missing obvious here.
I promise to come back to this... Have to go off grid... will think of it in the mean time... Appreciate this discussion!!
Re: [PATCH RFC v4 net-next 17/26] tracing: allow eBPF programs to be attached to events
In reply to Andy LutomirskiQuoted 14 lines · Andy Lutomirski
Quoted 4 lines · Alexei Starovoitov
This
bpf_contextstruct for tracing is trying to answer the question:
'what's the most convenient way to access tracepoint arguments
from a script'.
When kernel code has something like:Quoted 8 lines
trace_kfree_skb(skb, net_tx_action);
the script needs to be able to access this 'skb' and 'net_tx_action' values through _single_ data structure.
In this proposal they arectx->arg1andctx->arg2.
I've considered having different bpf_context's for every event, but the complexity explodes. I need to hack all event definitions and so on. imo it's better to move complexity to userspace, so program author or high level language abstracts these details.
Quoted 2 lines
I still don't understand why making them long instead of u64 is helpful, though. I feel like I'm missing obvious here.
The problem statement:
- tracepoint events are defined as:
TRACE_EVENT(sock_exceed_buf_limit,
TP_PROTO(struct sock *sk, struct proto *prot, long allocated), TP_ARGS(sk, prot, allocated),
- from eBPF C program (or higher level language) I would like to access these tracepoint arguments as ctx->arg1, ctx->arg2, ctx->arg3
- accessing tracepoint fields after buffer copy is not an option, since it's unnecessary alloc/copy/free of a lot of values (including strings) per event that programs will mostly ignore. If needed, programs can fetch them on demand.
Bad approach #1
- define different bpf_context per event and customize eBPF verifier to have different program types per event, so particular program can be attached to one particular event only
Cons: quite complex, require trace/events/*.h hacking,
one ebpf program cannot be used to attach to multiple events
So #1 is no go.
Approach #2
- define bpf_context once for all tracepoint events as:
struct bpf_context {
unsigned long arg1, arg2, arg3, ...
};
and main ftrace.h macro as:
struct bpf_context ctx;
populate_bpf_context(&ctx, args, 0, 0, 0, 0, 0);
trace_filter_call_bpf(ftrace_file->filter, &ctx);
where 'args' is a macro taken from TP_ARGS above and
/* called from ftrace_raw_event_*() to copy args */
void populate_bpf_context(struct bpf_context *ctx, ...)
{
va_start(args, ctx);
ctx->arg1 = va_arg(args, unsigned long);
ctx->arg2 = va_arg(args, unsigned long);this approach relies on type promotion when args are passed into vararg function.
On 64-bit arch our tracepoint arguments 'sk, prot, allocated' will get stored into arg1, arg2, arg3 and the rest of argX will be zeros. On 32-bit 'u64' types will be passed in two 'long' slots of vararg. Obviously changing 'long' to 'u64' in bpf_context and in populate_bpf_context() will not work, because types
are promoted to 'long'.
Disadvantage of this approach is that 32 vs 64 bit archs need to deal with argX differently.
That's what you saw in this patch.
New approach #3
just discovered __MAPx() macro used by syscalls.h which can be massaged for this use case, so define:
struct bpf_context {
u64 arg1, arg2, arg3,...
};
and argument casting macro as:
#define __BPF_CAST1(a,...) __CAST_TO_U64(a)
#define __BPF_CAST2(a,...) __CAST_TO_U64(a), __BPF_CAST1(__VA_ARGS__) ..
#define __BPF_CAST(a,...) __CAST_TO_U64(a), __BPF_CAST6(__VA_ARGS__)
so main ftrace.h macro becomes:
struct bpf_context __ctx = ((struct bpf_context) {
__BPF_CAST(args, 0, 0, 0, 0, 0, 0)
}); trace_filter_call_bpf(ftrace_file->filter, &__ctx);
where 'args' is still the same 'sk, prot, allocated' from TP_ARGS. Casting macro will cast 'sk' to u64 and will assign into arg1, 'prot' will be casted to u64 and assigned to arg2, etc
All good, but the tricky part is how to cast all arguments passed into tracepoint events into u64 without warnings on 32-bit and 64-bit architectures.
The following:
#define __CAST_TO_U64(expr) (u64) expr
will not work, since compiler will be spewing warnings about casting pointer to integer...
The following
#define __CAST_TO_U64(expr) (u64) (long) expr
will work fine on 64-bit architectures, since all integer and pointer types will be warning-free casted and stored
in arg1, arg2, arg3, ...
but it won't work on 32-bit architectures, since full u64 tracepoint arguments will be chopped to 'long'.
It took a lot of macro wizardry to come up with the following:
/* cast any interger or pointer type to u64 without warnings */
#define __CAST_TO_U64(expr) \
__builtin_choose_expr(sizeof(long) < sizeof(expr), \
(u64) (expr - ((typeof(expr))0)), \
(u64) (long) expr)the tricky part is that GCC syntax-parses and warns
in both sides of __builtin_choose_expr(), so u64 case in 32-bit archs needs to be fancy, so all types can go through it warning free.
Though it's tricky the end result is nice.
The disadvantages of approach #2 are solved and tracepoint arguments are stored into 'u64 argX' on both 32 and 64-bit archs. The extra benefit is that this casting macro is way faster than vararg approach #2.
So in V5 of this series I'm planning to use this new approach unless there are better ideas.
full diff of this approach:
https://git.kernel.org/cgit/linux/kernel/git/ast/bpf.git/commit/?id=235d87dd7afd8d5262556cba7882d6efb25d8305
Re: [PATCH RFC v4 net-next 17/26] tracing: allow eBPF programs to be attached to events
In reply to Alexei StarovoitovQuoted 4 lines · Alexei Starovoitov
User interface:
fd =open("/sys/kernel/debug/tracing/__event__/filter")
write(fd, "bpf_123")
I didn't follow all the code flow leading to parsing the "bpf_123" string, but if it works the way I imagine it does, it's a security problem. In general, write(2) should never do anything that involves any security-relevant context of the caller.
Ideally, you would look up fd 123 in the file table of whomever called open. If that's difficult to implement efficiently, then it would be nice to have some check that the callers of write(2) and open(2) are the same task and that exec wasn't called in between.
This isn't a very severe security issue because you need privilege to open the thing in the first place, but it would still be nice to address.
--Andy
Re: [PATCH RFC v4 net-next 17/26] tracing: allow eBPF programs to be attached to events
Quoted 11 lines · Andy Lutomirski
Quoted 4 lines · Alexei Starovoitov
User interface:
fd =open("/sys/kernel/debug/tracing/__event__/filter")
write(fd, "bpf_123")I didn't follow all the code flow leading to parsing the "
bpf_123" string, but if it works the way I imagine it does, it's a security problem. In general, write(2) should never do anything that involves any security-relevant context of the caller.
Quoted 8 lines
Ideally, you would look up fd 123 in the file table of whomever called open. If that's difficult to implement efficiently, then it would be nice to have some check that the callers of write(2) and open(2) are the same task and that exec wasn't called in between.
This isn't a very severe security issue because you need privilege to open the thing in the first place, but it would still be nice to address.
hmm. you need to be root to open the events anyway. pretty much the whole tracing for root only, since any kernel data structures can be printed, stored into maps and so on. So I don't quite follow your security concern here.
Even say root opens a tracepoint and does exec() of another app that uploads ebpf program, gets program_fd and does write into tracepoint fd. The root app that did this open() is doing exec() on purpose. It's not like it's exec-ing something it doesn't know about.
Remember, FDs was your idea in the first place ;)
I had global ids and everything root initially.
Re: [PATCH RFC v4 net-next 17/26] tracing: allow eBPF programs to be attached to events
Quoted 26 lines · Alexei Starovoitov
Quoted 11 lines · Andy Lutomirski
Quoted 4 lines · Alexei Starovoitov
User interface:
fd =open("/sys/kernel/debug/tracing/__event__/filter")
write(fd, "bpf_123")I didn't follow all the code flow leading to parsing the "
bpf_123" string, but if it works the way I imagine it does, it's a security problem. In general, write(2) should never do anything that involves any security-relevant context of the caller.Quoted 8 lines
Ideally, you would look up fd 123 in the file table of whomever called open. If that's difficult to implement efficiently, then it would be nice to have some check that the callers of write(2) and open(2) are the same task and that exec wasn't called in between.
This isn't a very severe security issue because you need privilege to open the thing in the first place, but it would still be nice to address.
hmm. you need to be root to open the events anyway. pretty much the whole tracing for root only, since any kernel data structures can be printed, stored into maps and so on. So I don't quite follow your security concern here.
Quoted 5 lines
Even say root opens a tracepoint and does
exec()of another app that uploads ebpf program, getsprogram_fdand does write into tracepoint fd. The root app that did thisopen()is doingexec()on purpose. It's not like it's exec-ing something it doesn't know about.
As long as everyone who can debugfs/tracing/whatever has all privileges, then this is fine.
If not, then it's a minor capability or MAC bypass. Suppose you only have one capability or, more realistically, limited MAC permissions. You can still open the tracing file, pass it to an unwitting program with elevated permission (e.g. using selinux's entrypoint mechanism), and trick that program into writing bpf_123.
Admittedly, it's unlikely that fd 123 will be an *eBPF* fd, but the attack is possible.
I don't think that fixing this should be a prerequisite for merging, since the risk is so small. Nonetheless, it would be nice. (This family of attacks has lead to several root vulnerabilities in the past.)
--Andy
Quoted 3 lines
Remember, FDs was your idea in the first place ;)
I had global ids and everything root initially.
Signature · 2 lines
Andy Lutomirski AMA Capital Management, LLC
Re: [PATCH RFC v4 net-next 17/26] tracing: allow eBPF programs to be attached to events
Quoted 33 lines · Andy Lutomirski
Quoted 26 lines · Alexei Starovoitov
Quoted 11 lines · Andy Lutomirski
Quoted 4 lines · Alexei Starovoitov
User interface:
fd =open("/sys/kernel/debug/tracing/__event__/filter")
write(fd, "bpf_123")I didn't follow all the code flow leading to parsing the "
bpf_123" string, but if it works the way I imagine it does, it's a security problem. In general, write(2) should never do anything that involves any security-relevant context of the caller.Quoted 8 lines
Ideally, you would look up fd 123 in the file table of whomever called open. If that's difficult to implement efficiently, then it would be nice to have some check that the callers of write(2) and open(2) are the same task and that exec wasn't called in between.
This isn't a very severe security issue because you need privilege to open the thing in the first place, but it would still be nice to address.
hmm. you need to be root to open the events anyway. pretty much the whole tracing for root only, since any kernel data structures can be printed, stored into maps and so on. So I don't quite follow your security concern here.
Quoted 5 lines
Even say root opens a tracepoint and does
exec()of another app that uploads ebpf program, getsprogram_fdand does write into tracepoint fd. The root app that did thisopen()is doingexec()on purpose. It's not like it's exec-ing something it doesn't know about.
Quoted 5 lines
As long as everyone who can debugfs/tracing/whatever has all privileges, then this is fine.
If not, then it's a minor capability or MAC bypass. Suppose you only have one capability or, more realistically, limited MAC permissions.
Hard to think of MAC abbreviation other than in networking way... ;) MAC bypass... kinda sounds like L3 networking without L2... ;)
Quoted 3 lines
You can still open the tracing file, pass it to an unwitting program with elevated permission (e.g. using selinux's entrypoint mechanism), and trick that program into writing
bpf_123.
hmm, but to open tracing file you'd need to be root already... otherwise yeah, if non-root could open it and pass it, then it would be nasty.
Quoted 7 lines
Admittedly, it's unlikely that fd 123 will be an *eBPF* fd, but the attack is possible.
I don't think that fixing this should be a prerequisite for merging, since the risk is so small. Nonetheless, it would be nice. (This family of attacks has lead to several root vulnerabilities in the past.)
Ok. I think keeping a track of pid between open and write is kinda ugly. Should we add some new CAP flag and check it for all file ops? Another option is to conditionally make open() of tracing files as cloexec...
Re: [PATCH RFC v4 net-next 17/26] tracing: allow eBPF programs to be attached to events
Quoted 54 lines · Alexei Starovoitov
Quoted 33 lines · Andy Lutomirski
Quoted 26 lines · Alexei Starovoitov
Quoted 11 lines · Andy Lutomirski
Quoted 4 lines · Alexei Starovoitov
User interface:
fd =open("/sys/kernel/debug/tracing/__event__/filter")
write(fd, "bpf_123")I didn't follow all the code flow leading to parsing the "
bpf_123" string, but if it works the way I imagine it does, it's a security problem. In general, write(2) should never do anything that involves any security-relevant context of the caller.Quoted 8 lines
Ideally, you would look up fd 123 in the file table of whomever called open. If that's difficult to implement efficiently, then it would be nice to have some check that the callers of write(2) and open(2) are the same task and that exec wasn't called in between.
This isn't a very severe security issue because you need privilege to open the thing in the first place, but it would still be nice to address.
hmm. you need to be root to open the events anyway. pretty much the whole tracing for root only, since any kernel data structures can be printed, stored into maps and so on. So I don't quite follow your security concern here.
Quoted 5 lines
Even say root opens a tracepoint and does
exec()of another app that uploads ebpf program, getsprogram_fdand does write into tracepoint fd. The root app that did thisopen()is doingexec()on purpose. It's not like it's exec-ing something it doesn't know about.Quoted 5 lines
As long as everyone who can debugfs/tracing/whatever has all privileges, then this is fine.
If not, then it's a minor capability or MAC bypass. Suppose you only have one capability or, more realistically, limited MAC permissions.
Hard to think of MAC abbreviation other than in networking way... ;) MAC bypass... kinda sounds like L3 networking without L2... ;)
Quoted 3 lines
You can still open the tracing file, pass it to an unwitting program with elevated permission (e.g. using selinux's entrypoint mechanism), and trick that program into writing
bpf_123.hmm, but to open tracing file you'd need to be root already... otherwise yeah, if non-root could open it and pass it, then it would be nasty.
Quoted 3 lines
Admittedly, it's unlikely that fd 123 will be an *eBPF* fd, but the attack is possible.
Quoted 7 lines
Quoted 4 lines
I don't think that fixing this should be a prerequisite for merging, since the risk is so small. Nonetheless, it would be nice. (This family of attacks has lead to several root vulnerabilities in the past.)
Ok. I think keeping a track of pid between open and write is kinda ugly.
Agreed.
TBH, I would just add a comment to the open implementation saying that, if unprivileged or less privileged open is allowed, then this needs to be fixed.
Quoted 3 lines
Should we add some new CAP flag and check it for all file ops? Another option is to conditionally make
open()of tracing files as cloexec...
That won't help. The same attack can be done with SCM_RIGHTS, and cloexec can be cleared.
Signature · 2 lines
Andy Lutomirski AMA Capital Management, LLC
Re: [PATCH RFC v4 net-next 17/26] tracing: allow eBPF programs to be attached to events
Quoted 6 lines · Andy Lutomirski
Quoted 6 lines
Quoted 5 lines
I don't think that fixing this should be a prerequisite for merging, since the risk is so small. Nonetheless, it would be nice. (This family of attacks has lead to several root vulnerabilities in the past.)
Quoted 8 lines
Quoted 2 lines
Ok. I think keeping a track of pid between open and write is kinda ugly.
Agreed.
TBH, I would just add a comment to the open implementation saying that, if unprivileged or less privileged open is allowed, then this needs to be fixed.
ok. will do.
Quoted 6 lines
Quoted 3 lines
Should we add some new CAP flag and check it for all file ops? Another option is to conditionally make
open()of tracing files as cloexec...That won't help. The same attack can be done with
SCM_RIGHTS, and cloexec can be cleared.
ouch, can we then make ebpf FDs and may be debugfs FDs not passable at all? Otherwise it feels that generality and flexibility of FDs is becoming a burden.
Re: [PATCH RFC v4 net-next 17/26] tracing: allow eBPF programs to be attached to events
Quoted 22 lines · Alexei Starovoitov
Quoted 6 lines · Andy Lutomirski
Quoted 6 lines
Quoted 5 lines
I don't think that fixing this should be a prerequisite for merging, since the risk is so small. Nonetheless, it would be nice. (This family of attacks has lead to several root vulnerabilities in the past.)
Quoted 8 lines
Quoted 2 lines
Ok. I think keeping a track of pid between open and write is kinda ugly.
Agreed.
TBH, I would just add a comment to the open implementation saying that, if unprivileged or less privileged open is allowed, then this needs to be fixed.
ok. will do.
Quoted 4 lines
Quoted 3 lines
Should we add some new CAP flag and check it for all file ops? Another option is to conditionally make
open()of tracing files as cloexec...
Quoted 6 lines
Quoted 2 lines
That won't help. The same attack can be done with
SCM_RIGHTS, and cloexec can be cleared.ouch, can we then make ebpf FDs and may be debugfs FDs not passable at all? Otherwise it feels that generality and flexibility of FDs is becoming a burden.
I'm not sure there's much of a general problem. The issue is when there's an fd for which write(2) (or other assumed-to-not-check-permissions calls like read, pread, pwrite, etc) depend on context. This is historically an issue for netlink and various /proc files.
--Andy
RFC PATCH v4 18/26 tracing: allow eBPF programs to be attached to kprobe/kretprobe
In reply to Alexei Starovoitov--- kernel/trace/trace_kprobe.c | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+)
kernel/trace/trace_kprobe.c +24 -0
@@ -19,6 +19,7 @@#include <linux/module.h> #include <linux/uaccess.h> +#include <trace/bpf_trace.h> #include "trace_probe.h"
@@ -930,6 +931,18 @@ __kprobe_trace_func(struct trace_kprobe *tk, struct pt_regs *regs,if (ftrace_trigger_soft_disabled (ftrace_file))return ; +if (call->flags &TRACE_EVENT_FL_BPF ) { +struct bpf_context __ctx = {}; +/* get first 3 arguments of the function. x64 syscall ABI uses +* the same 3 registers as x64 calling convention. +* todo: implement it cleanly via arch specific +* regs_get_argument_nth() helper +*/ +syscall_get_arguments (current, regs,0 ,3 , &__ctx.arg1); +trace_filter_call_bpf (ftrace_file->filter, &__ctx); +return ; + } +local_save_flags (irq_flags); pc =preempt_count ();
@@ -978,6 +991,17 @@ __kretprobe_trace_func(struct trace_kprobe *tk, struct kretprobe_instance *ri,if (ftrace_trigger_soft_disabled (ftrace_file))return ; +if (call->flags &TRACE_EVENT_FL_BPF ) { +struct bpf_context __ctx = {}; +/* assume that register used to return a value from syscall is +* the same as register used to return a value from a function +* todo: provide arch specific helper +*/ + __ctx.ret =syscall_get_return_value (current, regs); +trace_filter_call_bpf (ftrace_file->filter, &__ctx); +return ; + } +local_save_flags (irq_flags); pc =preempt_count ();
Signature · 1 line
1.7.9.5
RFC PATCH v4 19/26 samples: bpf: add mini eBPF library to manipulate maps and programs
In reply to Alexei Starovoitovthe library includes a trivial set of BPF syscall wrappers:
int bpf_create_map(int key_size, int value_size, int max_entries);
int bpf_update_elem(int fd, void *key, void *value);
int bpf_lookup_elem(int fd, void *key, void *value);
int bpf_delete_elem(int fd, void *key);
int bpf_get_next_key(int fd, void *key, void *next_key);
int bpf_prog_load(enum bpf_prog_type prog_type,
const struct sock_filter_int *insns, int insn_len, const char *license);
bpf_prog_load() stores verifier log into global bpf_log_buf[] array
--- samples/bpf/libbpf.c | 138 ++++++++++++++++++++++++++++++++++++++++++++++++++ samples/bpf/libbpf.h | 21 ++++++++ 2 files changed, 159 insertions(+) create mode 100644 samples/bpf/libbpf.c create mode 100644 samples/bpf/libbpf.h
samples/bpf/libbpf.c new file +138 -0
@@ -0,0 +1,138 @@ +/* eBPF mini library */ +#include <stdlib.h> +#include <stdio.h> +#include <linux/unistd.h> +#include <unistd.h> +#include <string.h> +#include <linux/netlink.h> +#include <linux/bpf.h> +#include <errno.h> +#include "libbpf.h" + +struct nlattr_u32 { +__u16 nla_len; +__u16 nla_type; +__u32 val; +}; + +int bpf_create_map (enum bpf_map_type map_type,int key_size,int value_size, +int max_entries) +{ +struct nlattr_u32 attr[] = { + { + .nla_len =sizeof (struct nlattr_u32 ), + .nla_type =BPF_MAP_KEY_SIZE , + .val = key_size, + }, + { + .nla_len =sizeof (struct nlattr_u32 ), + .nla_type =BPF_MAP_VALUE_SIZE , + .val = value_size, + }, + { + .nla_len =sizeof (struct nlattr_u32 ), + .nla_type =BPF_MAP_MAX_ENTRIES , + .val = max_entries, + }, + }; + +return syscall (__NR_bpf,BPF_MAP_CREATE , map_type, attr,sizeof (attr),0 ); +} + + +int bpf_update_elem (int fd,void *key,void *value) +{ +return syscall (__NR_bpf,BPF_MAP_UPDATE_ELEM , fd, key, value,0 ); +} + +int bpf_lookup_elem (int fd,void *key,void *value) +{ +return syscall (__NR_bpf,BPF_MAP_LOOKUP_ELEM , fd, key, value,0 ); +} + +int bpf_delete_elem (int fd,void *key) +{ +return syscall (__NR_bpf,BPF_MAP_DELETE_ELEM , fd, key,0 ,0 ); +} + +int bpf_get_next_key (int fd,void *key,void *next_key) +{ +return syscall (__NR_bpf,BPF_MAP_GET_NEXT_KEY , fd, key, next_key,0 ); +} + +#define ROUND_UP (x, n) (((x) + (n) - 1u) & ~((n) - 1u)) + +char bpf_log_buf[LOG_BUF_SIZE ]; + +int bpf_prog_load (enum bpf_prog_type prog_type, +const struct bpf_insn *insns,int prog_len, +const char *license) +{ +int nlattr_size, license_len, err; +void *nlattr, *ptr; +char *log_buf = bpf_log_buf; +int log_size =LOG_BUF_SIZE ; +int log_level =1 ; + + log_buf[0 ] =0 ; + + license_len =strlen (license) +1 ; + nlattr_size =sizeof (struct nlattr ) + prog_len +sizeof (struct nlattr ) + +ROUND_UP (license_len,4 ) + +sizeof (struct nlattr ) +sizeof (log_level) + +sizeof (struct nlattr ) +sizeof (log_buf) + +sizeof (struct nlattr ) +sizeof (log_size); + + ptr = nlattr =malloc (nlattr_size); +if (!ptr) { + errno =ENOMEM ; +return -1 ; + } + + *(struct nlattr *) ptr = (struct nlattr ) { + .nla_len = prog_len +sizeof (struct nlattr ), + .nla_type =BPF_PROG_TEXT , + }; + ptr +=sizeof (struct nlattr ); + +memcpy (ptr, insns, prog_len); + ptr += prog_len; + + *(struct nlattr *) ptr = (struct nlattr ) { + .nla_len =ROUND_UP (license_len,4 ) +sizeof (struct nlattr ), + .nla_type =BPF_PROG_LICENSE , + }; + ptr +=sizeof (struct nlattr ); + +memcpy (ptr, license, license_len); + ptr +=ROUND_UP (license_len,4 ); + + *(struct nlattr *) ptr = (struct nlattr ) { + .nla_len =sizeof (log_level) +sizeof (struct nlattr ), + .nla_type =BPF_PROG_LOG_LEVEL , + }; + ptr +=sizeof (struct nlattr ); +memcpy (ptr, &log_level,sizeof (log_level)); + ptr +=sizeof (log_level); + + *(struct nlattr *) ptr = (struct nlattr ) { + .nla_len =sizeof (log_buf) +sizeof (struct nlattr ), + .nla_type =BPF_PROG_LOG_BUF , + }; + ptr +=sizeof (struct nlattr ); +memcpy (ptr, &log_buf,sizeof (log_buf)); + ptr +=sizeof (log_buf); + + *(struct nlattr *) ptr = (struct nlattr ) { + .nla_len =sizeof (log_size) +sizeof (struct nlattr ), + .nla_type =BPF_PROG_LOG_SIZE , + }; + ptr +=sizeof (struct nlattr ); +memcpy (ptr, &log_size,sizeof (log_size)); + ptr +=sizeof (log_size); + + err =syscall (__NR_bpf,BPF_PROG_LOAD , prog_type, nlattr, nlattr_size,0 ); + +free (nlattr); +return err; +}
samples/bpf/libbpf.h new file +21 -0
@@ -0,0 +1,21 @@ +/* eBPF mini library */ +#ifndef __LIBBPF_H +#define __LIBBPF_H + +struct bpf_insn ; + +int bpf_create_map (enum bpf_map_type map_type,int key_size,int value_size, +int max_entries); +int bpf_update_elem (int fd,void *key,void *value); +int bpf_lookup_elem (int fd,void *key,void *value); +int bpf_delete_elem (int fd,void *key); +int bpf_get_next_key (int fd,void *key,void *next_key); + +int bpf_prog_load (enum bpf_prog_type prog_type, +const struct bpf_insn *insns,int insn_len, +const char *license); + +#define LOG_BUF_SIZE 8192 +extern char bpf_log_buf[LOG_BUF_SIZE ]; + +#endif
Signature · 1 line
1.7.9.5
RFC PATCH v4 20/26 samples: bpf: example of stateful socket filtering
In reply to Alexei Starovoitovthis socket filter example does:
- creates a hashtable in kernel with key 4 bytes and value 8 bytes
- populates map[6] = 0; map[17] = 0; // 6 - tcp_proto, 17 - udp_proto
- loads eBPF program:
r0 = skb[14 + 9]; // load one byte of ip->proto
*(u32*)(fp - 4) = r0;
value = bpf_map_lookup_elem(map_fd, fp - 4);
if (value)
(*(u64*)value) += 1;
- attaches this program to eth0 raw socket
- every second user space reads map[6] and map[17] to see how many TCP and UDP packets were seen on eth0
--- samples/bpf/.gitignore | 1 + samples/bpf/Makefile | 12 ++++ samples/bpf/sock_example.c | 158 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 171 insertions(+) create mode 100644 samples/bpf/.gitignore create mode 100644 samples/bpf/Makefile create mode 100644 samples/bpf/sock_example.c
samples/bpf/.gitignore new file +1 -0
@@ -0,0 +1 @@ +sock_example
samples/bpf/Makefile new file +12 -0
@@ -0,0 +1,12 @@ +# kbuild trick to avoid linker error. Can be omitted if a module is built. +obj- := dummy.o + +# List of programs to build +hostprogs-y := sock_example + +sock_example-objs := sock_example.o libbpf.o + +# Tell kbuild to always build the programs +always := $(hostprogs-y) + +HOSTCFLAGS += -I$(objtree)/usr/include
samples/bpf/sock_example.c new file +158 -0
158 lines not on this page · raw message
Signature · 1 line
1.7.9.5
RFC PATCH v4 21/26 samples: bpf: example of tracing filters with eBPF
In reply to Alexei Starovoitovsimple packet drop monitor:
- in-kernel eBPF program attaches to kfree_skb() event and records number of packet drops at given location
- userspace iterates over the map every second and prints stats
--- samples/bpf/Makefile | 3 +- samples/bpf/dropmon.c | 131 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 133 insertions(+), 1 deletion(-) create mode 100644 samples/bpf/dropmon.c
samples/bpf/Makefile +2 -1
@@ -2,9 +2,10 @@ obj- := dummy.o # List of programs to build -hostprogs-y := sock_example +hostprogs-y := sock_example dropmon sock_example-objs := sock_example.o libbpf.o +dropmon-objs := dropmon.o libbpf.o # Tell kbuild to always build the programs always := $(hostprogs-y)
samples/bpf/dropmon.c new file +131 -0
131 lines not on this page · raw message
Signature · 1 line
1.7.9.5
RFC PATCH v4 22/26 bpf: llvm backend
In reply to Alexei Starovoitovllvm backend that generated eBPF and emits either
binary ELF or human readable eBPF assembler
---
the body of the patch is removed to prevent spam.
I doubt too many falks are interested in reading llvm diffs on lkml. The backend is available in the tree:
https://git.kernel.org/cgit/linux/kernel/git/ast/bpf.git/commit/?id=4afc9f0b5890c0020a7d70c42bd4f0fa55d33cb0
tools/bpf/llvm/.gitignore | 54 ++ tools/bpf/llvm/LICENSE.TXT | 70 ++ tools/bpf/llvm/Makefile.rules | 641 ++++++++++++++++++ tools/bpf/llvm/README.txt | 23 + tools/bpf/llvm/bld/Makefile | 27 + tools/bpf/llvm/bld/Makefile.common | 14 + tools/bpf/llvm/bld/Makefile.config | 124 ++++ .../llvm/bld/include/llvm/Config/AsmParsers.def | 8 + .../llvm/bld/include/llvm/Config/AsmPrinters.def | 9 + .../llvm/bld/include/llvm/Config/Disassemblers.def | 8 + tools/bpf/llvm/bld/include/llvm/Config/Targets.def | 9 + .../bpf/llvm/bld/include/llvm/Support/DataTypes.h | 96 +++ tools/bpf/llvm/bld/lib/Makefile | 11 + .../llvm/bld/lib/Target/BPF/InstPrinter/Makefile | 10 + .../llvm/bld/lib/Target/BPF/MCTargetDesc/Makefile | 11 + tools/bpf/llvm/bld/lib/Target/BPF/Makefile | 17 + .../llvm/bld/lib/Target/BPF/TargetInfo/Makefile | 10 + tools/bpf/llvm/bld/lib/Target/Makefile | 11 + tools/bpf/llvm/bld/tools/Makefile | 12 + tools/bpf/llvm/bld/tools/llc/Makefile | 15 + tools/bpf/llvm/lib/Target/BPF/BPF.h | 28 + tools/bpf/llvm/lib/Target/BPF/BPF.td | 29 + tools/bpf/llvm/lib/Target/BPF/BPFAsmPrinter.cpp | 100 +++ tools/bpf/llvm/lib/Target/BPF/BPFCallingConv.td | 24 + tools/bpf/llvm/lib/Target/BPF/BPFFrameLowering.cpp | 36 ++ tools/bpf/llvm/lib/Target/BPF/BPFFrameLowering.h | 35 + tools/bpf/llvm/lib/Target/BPF/BPFISelDAGToDAG.cpp | 182 ++++++ tools/bpf/llvm/lib/Target/BPF/BPFISelLowering.cpp | 683 ++++++++++++++++++++ tools/bpf/llvm/lib/Target/BPF/BPFISelLowering.h | 105 +++ tools/bpf/llvm/lib/Target/BPF/BPFInstrFormats.td | 29 + tools/bpf/llvm/lib/Target/BPF/BPFInstrInfo.cpp | 162 +++++ tools/bpf/llvm/lib/Target/BPF/BPFInstrInfo.h | 53 ++ tools/bpf/llvm/lib/Target/BPF/BPFInstrInfo.td | 498 ++++++++++++++ tools/bpf/llvm/lib/Target/BPF/BPFMCInstLower.cpp | 77 +++ tools/bpf/llvm/lib/Target/BPF/BPFMCInstLower.h | 40 ++ tools/bpf/llvm/lib/Target/BPF/BPFRegisterInfo.cpp | 122 ++++ tools/bpf/llvm/lib/Target/BPF/BPFRegisterInfo.h | 65 ++ tools/bpf/llvm/lib/Target/BPF/BPFRegisterInfo.td | 39 ++ tools/bpf/llvm/lib/Target/BPF/BPFSubtarget.cpp | 23 + tools/bpf/llvm/lib/Target/BPF/BPFSubtarget.h | 33 + tools/bpf/llvm/lib/Target/BPF/BPFTargetMachine.cpp | 66 ++ tools/bpf/llvm/lib/Target/BPF/BPFTargetMachine.h | 69 ++ .../lib/Target/BPF/InstPrinter/BPFInstPrinter.cpp | 81 +++ .../lib/Target/BPF/InstPrinter/BPFInstPrinter.h | 34 + .../lib/Target/BPF/MCTargetDesc/BPFAsmBackend.cpp | 89 +++ .../llvm/lib/Target/BPF/MCTargetDesc/BPFBaseInfo.h | 33 + .../Target/BPF/MCTargetDesc/BPFELFObjectWriter.cpp | 56 ++ .../lib/Target/BPF/MCTargetDesc/BPFMCAsmInfo.h | 34 + .../Target/BPF/MCTargetDesc/BPFMCCodeEmitter.cpp | 167 +++++ .../Target/BPF/MCTargetDesc/BPFMCTargetDesc.cpp | 115 ++++ .../lib/Target/BPF/MCTargetDesc/BPFMCTargetDesc.h | 56 ++ .../lib/Target/BPF/TargetInfo/BPFTargetInfo.cpp | 13 + tools/bpf/llvm/tools/llc/llc.cpp | 381 +++++++++++ 53 files changed, 4737 insertions(+) create mode 100644 tools/bpf/llvm/.gitignore create mode 100644 tools/bpf/llvm/LICENSE.TXT create mode 100644 tools/bpf/llvm/Makefile.rules create mode 100644 tools/bpf/llvm/README.txt create mode 100644 tools/bpf/llvm/bld/Makefile create mode 100644 tools/bpf/llvm/bld/Makefile.common create mode 100644 tools/bpf/llvm/bld/Makefile.config create mode 100644 tools/bpf/llvm/bld/include/llvm/Config/AsmParsers.def create mode 100644 tools/bpf/llvm/bld/include/llvm/Config/AsmPrinters.def create mode 100644 tools/bpf/llvm/bld/include/llvm/Config/Disassemblers.def create mode 100644 tools/bpf/llvm/bld/include/llvm/Config/Targets.def create mode 100644 tools/bpf/llvm/bld/include/llvm/Support/DataTypes.h create mode 100644 tools/bpf/llvm/bld/lib/Makefile create mode 100644 tools/bpf/llvm/bld/lib/Target/BPF/InstPrinter/Makefile create mode 100644 tools/bpf/llvm/bld/lib/Target/BPF/MCTargetDesc/Makefile create mode 100644 tools/bpf/llvm/bld/lib/Target/BPF/Makefile create mode 100644 tools/bpf/llvm/bld/lib/Target/BPF/TargetInfo/Makefile create mode 100644 tools/bpf/llvm/bld/lib/Target/Makefile create mode 100644 tools/bpf/llvm/bld/tools/Makefile create mode 100644 tools/bpf/llvm/bld/tools/llc/Makefile create mode 100644 tools/bpf/llvm/lib/Target/BPF/BPF.h create mode 100644 tools/bpf/llvm/lib/Target/BPF/BPF.td create mode 100644 tools/bpf/llvm/lib/Target/BPF/BPFAsmPrinter.cpp create mode 100644 tools/bpf/llvm/lib/Target/BPF/BPFCallingConv.td create mode 100644 tools/bpf/llvm/lib/Target/BPF/BPFFrameLowering.cpp create mode 100644 tools/bpf/llvm/lib/Target/BPF/BPFFrameLowering.h create mode 100644 tools/bpf/llvm/lib/Target/BPF/BPFISelDAGToDAG.cpp create mode 100644 tools/bpf/llvm/lib/Target/BPF/BPFISelLowering.cpp create mode 100644 tools/bpf/llvm/lib/Target/BPF/BPFISelLowering.h create mode 100644 tools/bpf/llvm/lib/Target/BPF/BPFInstrFormats.td create mode 100644 tools/bpf/llvm/lib/Target/BPF/BPFInstrInfo.cpp create mode 100644 tools/bpf/llvm/lib/Target/BPF/BPFInstrInfo.h create mode 100644 tools/bpf/llvm/lib/Target/BPF/BPFInstrInfo.td create mode 100644 tools/bpf/llvm/lib/Target/BPF/BPFMCInstLower.cpp create mode 100644 tools/bpf/llvm/lib/Target/BPF/BPFMCInstLower.h create mode 100644 tools/bpf/llvm/lib/Target/BPF/BPFRegisterInfo.cpp create mode 100644 tools/bpf/llvm/lib/Target/BPF/BPFRegisterInfo.h create mode 100644 tools/bpf/llvm/lib/Target/BPF/BPFRegisterInfo.td create mode 100644 tools/bpf/llvm/lib/Target/BPF/BPFSubtarget.cpp create mode 100644 tools/bpf/llvm/lib/Target/BPF/BPFSubtarget.h create mode 100644 tools/bpf/llvm/lib/Target/BPF/BPFTargetMachine.cpp create mode 100644 tools/bpf/llvm/lib/Target/BPF/BPFTargetMachine.h create mode 100644 tools/bpf/llvm/lib/Target/BPF/InstPrinter/BPFInstPrinter.cpp create mode 100644 tools/bpf/llvm/lib/Target/BPF/InstPrinter/BPFInstPrinter.h create mode 100644 tools/bpf/llvm/lib/Target/BPF/MCTargetDesc/BPFAsmBackend.cpp create mode 100644 tools/bpf/llvm/lib/Target/BPF/MCTargetDesc/BPFBaseInfo.h create mode 100644 tools/bpf/llvm/lib/Target/BPF/MCTargetDesc/BPFELFObjectWriter.cpp create mode 100644 tools/bpf/llvm/lib/Target/BPF/MCTargetDesc/BPFMCAsmInfo.h create mode 100644 tools/bpf/llvm/lib/Target/BPF/MCTargetDesc/BPFMCCodeEmitter.cpp create mode 100644 tools/bpf/llvm/lib/Target/BPF/MCTargetDesc/BPFMCTargetDesc.cpp create mode 100644 tools/bpf/llvm/lib/Target/BPF/MCTargetDesc/BPFMCTargetDesc.h create mode 100644 tools/bpf/llvm/lib/Target/BPF/TargetInfo/BPFTargetInfo.cpp create mode 100644 tools/bpf/llvm/tools/llc/llc.cpp
Signature · 1 line
1.7.9.5
RFC PATCH v4 23/26 samples: bpf: elf file loader
In reply to Alexei Starovoitovsimple .o parser and loader using BPF syscall.
.o is a standard ELF generated by LLVM backend
It parses elf file compiled by llvm .c->.o
- parses 'maps' section and creates maps via BPF syscall
- parses 'license' section and passes it to syscall
- parses elf relocations for BPF maps and adjusts BPF_LD_IMM64 insns by storing map_fd into insn->imm and marking such insns as BPF_PSEUDO_MAP_FD
- loads eBPF program via BPF syscall
- attaches program FD to tracepoint events
One ELF file can contain multiple BPF programs attached to multiple tracepoint events
int load_bpf_file(char *path);
bpf_helpers.h is a set of in-kernel helper functions available to eBPF programs
--- samples/bpf/bpf_helpers.h | 25 +++++ samples/bpf/bpf_load.c | 232 +++++++++++++++++++++++++++++++++++++++++++++ samples/bpf/bpf_load.h | 26 +++++ 3 files changed, 283 insertions(+) create mode 100644 samples/bpf/bpf_helpers.h create mode 100644 samples/bpf/bpf_load.c create mode 100644 samples/bpf/bpf_load.h
samples/bpf/bpf_helpers.h new file +25 -0
@@ -0,0 +1,25 @@ +#ifndef __BPF_HELPERS_H +#define __BPF_HELPERS_H + +#define SEC (NAME ) __attribute__((section(NAME), used)) + +static void *(*bpf_fetch_ptr)(void *unsafe_ptr) = (void *) BPF_FUNC_fetch_ptr; +static unsigned long long (*bpf_fetch_u64)(void *unsafe_ptr) = (void *) BPF_FUNC_fetch_u64; +static unsigned int (*bpf_fetch_u32)(void *unsafe_ptr) = (void *) BPF_FUNC_fetch_u32; +static unsigned short (*bpf_fetch_u16)(void *unsafe_ptr) = (void *) BPF_FUNC_fetch_u16; +static unsigned char (*bpf_fetch_u8)(void *unsafe_ptr) = (void *) BPF_FUNC_fetch_u8; +static int (*bpf_printk)(const char *fmt,int fmt_size, ...) = (void *) BPF_FUNC_printk; +static int (*bpf_memcmp)(void *unsafe_ptr,void *safe_ptr,int size) = (void *) BPF_FUNC_memcmp; +static void *(*bpf_map_lookup_elem)(void *map,void *key) = (void *) BPF_FUNC_map_lookup_elem; +static int (*bpf_map_update_elem)(void *map,void *key,void *value) = (void *) BPF_FUNC_map_update_elem; +static int (*bpf_map_delete_elem)(void *map,void *key) = (void *) BPF_FUNC_map_delete_elem; +static void (*bpf_dump_stack)(void ) = (void *) BPF_FUNC_dump_stack; + +struct bpf_map_def { +int type; +int key_size; +int value_size; +int max_entries; +}; + +#endif
samples/bpf/bpf_load.c new file +232 -0
232 lines not on this page · raw message
samples/bpf/bpf_load.h new file +26 -0
@@ -0,0 +1,26 @@ +#ifndef __BPF_LOAD_H +#define __BPF_LOAD_H + +#define MAX_MAPS 64 + +extern int map_fd[MAX_MAPS ]; + +/* parses elf file compiled by llvm .c->.o +* . parses 'maps' section and creates maps via BPF syscall +* . parses 'license' section and passes it to syscall +* . parses elf relocations for BPF maps and adjusts BPF_LD_IMM64 insns by +* storing map_fd into insn->imm and marking such insns as BPF_PSEUDO_MAP_FD +* . loads eBPF program via BPF syscall +* . attaches program FD to tracepoint events +* +* One ELF file can contain multiple BPF programs attached to multiple +* tracepoint events +* +* returns zero on success +*/ +int load_bpf_file (char *path); + +/* forever reads /sys/.../trace_pipe */ +void read_trace_pipe (void ); + +#endif
Signature · 1 line
1.7.9.5
Re: [PATCH RFC v4 net-next 23/26] samples: bpf: elf file loader
On Wed, Aug 13, 2014 at 12:57 AM, Alexei Starovoitov <ast-uqk4Ao+rVK5Wk0Htik3J/[email protected]> wrote:
[...]
samples/bpf/bpf_load.c line 34
Quoted 12 lines
samples/bpf/bpf_load.c new file +12
-0+static int load_and_attach (const char *event,struct bpf_insn *prog,int size) +{ +int fd, event_fd, err; +char fmt[32 ]; +char path[256 ] =DEBUGFS ; + + fd =bpf_prog_load (BPF_PROG_TYPE_TRACING_FILTER , prog, size, license); + +if (fd <0 ) { +printf ("err %d errno %d\n" , fd, errno); +return fd; + }
Minor suggestion: since this is sample code, I'd always print the bpf log after this this printf() error message:
printf("%s", bpf_log_buf);
Which has helped me debug my eBPF programs, as will be the case for anyone hacking on the examples. Or have a function for logdie(), if the log buffer may be populated with useful messages from other error paths as well.
Brendan
Re: [PATCH RFC v4 net-next 23/26] samples: bpf: elf file loader
Quoted 18 lines · Brendan Gregg
On Wed, Aug 13, 2014 at 12:57 AM, Alexei Starovoitov <ast-uqk4Ao+rVK5Wk0Htik3J/[email protected]> wrote:
[...]samples/bpf/bpf_load.c line 34
Quoted 12 lines
samples/bpf/bpf_load.c new file +12
-0+static int load_and_attach (const char *event,struct bpf_insn *prog,int size) +{ +int fd, event_fd, err; +char fmt[32 ]; +char path[256 ] =DEBUGFS ; + + fd =bpf_prog_load (BPF_PROG_TYPE_TRACING_FILTER , prog, size, license); + +if (fd <0 ) { +printf ("err %d errno %d\n" , fd, errno); +return fd; + }Minor suggestion: since this is sample code, I'd always print the bpf log after this this
printf()error message:
Quoted 4 lines
printf("%s", bpf_log_buf);Which has helped me debug my eBPF programs, as will be the case for anyone hacking on the examples.
Good point. Will do in V5.
Quoted 3 lines
Or have a function for
logdie(), if
the log buffer may be populated with useful messages from other error paths as well.
This log buffer is an optional buffer that eBPF verifier is using to store its messages. Mainly for humans to understand why verifier rejected the program. It's also used by verifier testsuite to check that reject reason actually matches the test intent.
RFC PATCH v4 24/26 samples: bpf: eBPF example in C
In reply to Alexei Starovoitovex1_kern.c - C program which will be compiled into eBPF to filter netif_receive_skb events on skb->dev->name == "lo"
ex1_user.c - corresponding user space component that forever reads /sys/.../trace_pipe
Usage:
$ sudo ex1
should see:
writing bpf-4 -> /sys/kernel/debug/tracing/events/net/netif_receive_skb/filter
ping-25476 [001] ..s3 5639.718218: __netif_receive_skb_core: skb 4d51700 dev b9e6000 ping-25476 [001] ..s3 5639.718262: __netif_receive_skb_core: skb 4d51400 dev b9e6000
ping-25476 [002] ..s3 5640.716233: __netif_receive_skb_core: skb 5d06500 dev b9e6000 ping-25476 [002] ..s3 5640.716272: __netif_receive_skb_core: skb 5d06300 dev b9e6000
Ctrl-C at any time, kernel will auto cleanup
--- samples/bpf/Makefile | 15 +++++++++++++-- samples/bpf/ex1_kern.c | 27 +++++++++++++++++++++++++++ samples/bpf/ex1_user.c | 24 ++++++++++++++++++++++++ 3 files changed, 64 insertions(+), 2 deletions(-) create mode 100644 samples/bpf/ex1_kern.c create mode 100644 samples/bpf/ex1_user.c
samples/bpf/Makefile +13 -2
@@ -2,12 +2,23 @@ obj- := dummy.o # List of programs to build -hostprogs-y := sock_example dropmon +hostprogs-y := sock_example dropmon ex1 sock_example-objs := sock_example.o libbpf.o dropmon-objs := dropmon.o libbpf.o +ex1-objs := bpf_load.o libbpf.o ex1_user.o # Tell kbuild to always build the programs -always := $(hostprogs-y) +always := $(hostprogs-y) ex1_kern.o HOSTCFLAGS += -I$(objtree)/usr/include + +HOSTCFLAGS_bpf_load.o += -I$(objtree)/usr/include -Wno-unused-variable +HOSTLOADLIBES_ex1 += -lelf + +LLC=$(srctree)/tools/bpf/llvm/bld/Debug+Asserts/bin/llc + +%.o: %.c + clang $(NOSTDINC_FLAGS) $(LINUXINCLUDE) $(EXTRA_CFLAGS) \ + -D__KERNEL__ -Wno-unused-value -Wno-pointer-sign \ + -O2 -emit-llvm -c $< -o -| $(LLC) -o $@
samples/bpf/ex1_kern.c new file +27 -0
@@ -0,0 +1,27 @@ +#include <linux/skbuff.h> +#include <linux/netdevice.h> +#include <uapi/linux/bpf.h> +#include <trace/bpf_trace.h> +#include "bpf_helpers.h" + +SEC("events/net/netif_receive_skb") +int bpf_prog1 (struct bpf_context *ctx) +{ +/* +* attaches to /sys/kernel/debug/tracing/events/net/netif_receive_skb +* prints events for loobpack device only +*/ +char devname[] ="lo" ; +struct net_device *dev; +struct sk_buff *skb =0 ; + + skb = (struct sk_buff *) ctx->arg1; + dev =bpf_fetch_ptr (&skb->dev); +if (bpf_memcmp (dev->name, devname,2 ) ==0 ) { +char fmt[] ="skb %x dev %x\n" ; +bpf_printk (fmt,sizeof (fmt), skb, dev); + } +return 0 ; +} + +char license[] SEC("license") = "GPL";
samples/bpf/ex1_user.c new file +24 -0
@@ -0,0 +1,24 @@ +#include <stdio.h> +#include <linux/bpf.h> +#include "libbpf.h" +#include "bpf_load.h" + +int main (int ac,char **argv) +{ +FILE *f; +char filename[256 ]; + +snprintf (filename,sizeof (filename),"%s_kern.o" , argv[0 ]); + +if (load_bpf_file (filename)) { +printf ("%s" , bpf_log_buf); +return 1 ; + } + + f =popen ("ping -c5 localhost" ,"r" ); + (void ) f; + +read_trace_pipe (); + +return 0 ; +}
Signature · 1 line
1.7.9.5
RFC PATCH v4 25/26 samples: bpf: counting eBPF example in C
In reply to Alexei Starovoitovthis example has two probes in C that use two different maps.
1st probe is the similar to dropmon.c. It attaches to kfree_skb tracepoint and count number of packet drops at different locations
2nd probe attaches to kprobe/sys_write and computes a histogram of different write sizes
Usage:
$ sudo ex2
Should see:
writing bpf-5 -> /sys/kernel/debug/tracing/events/skb/kfree_skb/filter writing bpf-8 -> /sys/kernel/debug/tracing/events/kprobes/sys_write/filter location 0xffffffff816efc67 count 1
location 0xffffffff815d8030 count 1
location 0xffffffff816efc67 count 3
location 0xffffffff815d8030 count 4
location 0xffffffff816efc67 count 9
syscall write() stats
byte_size : count distribution
1 -> 1 : 3141 |**** |
2 -> 3 : 2 | |
4 -> 7 : 14 | |
8 -> 15 : 3268 |***** |
16 -> 31 : 732 | |
32 -> 63 : 20042 |************************************* |
64 -> 127 : 12154 |********************** |
128 -> 255 : 2215 |*** |
256 -> 511 : 9 | |
512 -> 1023 : 0 | |
1024 -> 2047 : 1 | |Ctrl-C at any time. Kernel will auto cleanup maps and programs
--- samples/bpf/Makefile | 6 ++-- samples/bpf/ex2_kern.c | 73 +++++++++++++++++++++++++++++++++++++ samples/bpf/ex2_user.c | 94 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 171 insertions(+), 2 deletions(-) create mode 100644 samples/bpf/ex2_kern.c create mode 100644 samples/bpf/ex2_user.c
samples/bpf/Makefile +4 -2
@@ -2,19 +2,21 @@ obj- := dummy.o # List of programs to build -hostprogs-y := sock_example dropmon ex1 +hostprogs-y := sock_example dropmon ex1 ex2 sock_example-objs := sock_example.o libbpf.o dropmon-objs := dropmon.o libbpf.o ex1-objs := bpf_load.o libbpf.o ex1_user.o +ex2-objs := bpf_load.o libbpf.o ex2_user.o # Tell kbuild to always build the programs -always := $(hostprogs-y) ex1_kern.o +always := $(hostprogs-y) ex1_kern.o ex2_kern.o HOSTCFLAGS += -I$(objtree)/usr/include HOSTCFLAGS_bpf_load.o += -I$(objtree)/usr/include -Wno-unused-variable HOSTLOADLIBES_ex1 += -lelf +HOSTLOADLIBES_ex2 += -lelf LLC=$(srctree)/tools/bpf/llvm/bld/Debug+Asserts/bin/llc
samples/bpf/ex2_kern.c new file +73 -0
73 lines not on this page · raw message
samples/bpf/ex2_user.c new file +94 -0
94 lines not on this page · raw message
Signature · 1 line
1.7.9.5
Re: [PATCH RFC v4 net-next 25/26] samples: bpf: counting eBPF example in C
Quoted 22 lines · Alexei Starovoitov
this example has two probes in C that use two different maps.
1st probe is the similar to
dropmon.c. It attaches tokfree_skbtracepoint and count number of packet drops at different locations2nd probe attaches to kprobe/sys_write and computes a histogram of different write sizes
Usage:
$ sudo ex2Should see:
writing bpf-5 ->/sys/kernel/debug/tracing/events/skb/kfree_skb/filterwriting bpf-8 ->/sys/kernel/debug/tracing/events/kprobes/sys_write/filterlocation0xffffffff816efc67count 1location
0xffffffff815d8030count 1
location0xffffffff816efc67count 3location
0xffffffff815d8030count 4
location0xffffffff816efc67count 9
Quoted 13 lines
syscall write() stats
byte_size : count distribution
1 -> 1 : 3141 |**** |
2 -> 3 : 2 | |
4 -> 7 : 14 | |
8 -> 15 : 3268 |***** |
16 -> 31 : 732 | |
32 -> 63 : 20042 |************************************* |
64 -> 127 : 12154 |********************** |
128 -> 255 : 2215 |*** |
256 -> 511 : 9 | |
512 -> 1023 : 0 | |
1024 -> 2047 : 1 | |This is pretty awesome.
Given that this is tracing two tracepoints at once, I'd like to see a similar example where time is stored on the first tracepoint, retrieved on the second for a delta calculation, then presented with a similar histogram as seen above.
Brendan
Re: [PATCH RFC v4 net-next 25/26] samples: bpf: counting eBPF example in C
Quoted 37 lines · Brendan Gregg
Quoted 22 lines · Alexei Starovoitov
this example has two probes in C that use two different maps.
1st probe is the similar to
dropmon.c. It attaches tokfree_skbtracepoint and count number of packet drops at different locations2nd probe attaches to kprobe/sys_write and computes a histogram of different write sizes
Usage:
$ sudo ex2Should see:
writing bpf-5 ->/sys/kernel/debug/tracing/events/skb/kfree_skb/filterwriting bpf-8 ->/sys/kernel/debug/tracing/events/kprobes/sys_write/filterlocation0xffffffff816efc67count 1location
0xffffffff815d8030count 1
location0xffffffff816efc67count 3location
0xffffffff815d8030count 4
location0xffffffff816efc67count 9Quoted 13 lines
syscall write() stats byte_size : count distribution 1 -> 1 : 3141 |**** | 2 -> 3 : 2 | | 4 -> 7 : 14 | | 8 -> 15 : 3268 |***** | 16 -> 31 : 732 | | 32 -> 63 : 20042 |************************************* | 64 -> 127 : 12154 |********************** | 128 -> 255 : 2215 |*** | 256 -> 511 : 9 | | 512 -> 1023 : 0 | | 1024 -> 2047 : 1 | |
Quoted 6 lines
This is pretty awesome.
Given that this is tracing two tracepoints at once, I'd like to see a similar example where time is stored on the first tracepoint, retrieved on the second for a delta calculation, then presented with a similar histogram as seen above.
Very good point. The time related helpers are missing. In V5 I'm thinking to add something like bpf_ktime_get_ns().
To associate begin and end events I think bpf_gettid() would be needed, but that doesn't feel generic enough for helper function, so I'm leaning toward 'bpf_get_current()' helper that will return 'current' task pointer. eBPF program can use this pointer for correlation of events or can go exploring task fields with bpf_fetch_() helpers...
Thank you very much for trying things out and for your feedback!
RFC PATCH v4 26/26 bpf: verifier test
In reply to Alexei Starovoitovsimple verifier test from user space. Tests valid and invalid programs and expects predefined error log messages from kernel
--- samples/bpf/Makefile | 3 +- samples/bpf/test_verifier.c | 354 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 356 insertions(+), 1 deletion(-) create mode 100644 samples/bpf/test_verifier.c
samples/bpf/Makefile +2 -1
@@ -2,12 +2,13 @@ obj- := dummy.o # List of programs to build -hostprogs-y := sock_example dropmon ex1 ex2 +hostprogs-y := sock_example dropmon ex1 ex2 test_verifier sock_example-objs := sock_example.o libbpf.o dropmon-objs := dropmon.o libbpf.o ex1-objs := bpf_load.o libbpf.o ex1_user.o ex2-objs := bpf_load.o libbpf.o ex2_user.o +test_verifier-objs := test_verifier.o libbpf.o # Tell kbuild to always build the programs always := $(hostprogs-y) ex1_kern.o ex2_kern.o
samples/bpf/test_verifier.c new file +354 -0
354 lines not on this page · raw message
Signature · 1 line
1.7.9.5
From: Of Alexei Starovoitov
Quoted 6 lines
one more RFC...
Major difference vs previous set is a new 'load 64-bit immediate' eBPF insn. Which is first 16-byte instruction. It shows how eBPF ISA can be extended while maintaining backward compatibility, but mainly it cleans up eBPF program access to maps and improves run-time performance.
Wouldn't it be more sensible to follow the scheme used by a lot of cpus and add a 'load high' instruction (follow with 'add' or 'or'). It still takes 16 bytes to load a 64bit immediate value, but the instruction size remains constant.
There is nothing to stop any JIT software detecting the instruction pair.
David
Quoted 10 lines · David Laight
From: Of Alexei Starovoitov
Quoted 6 lines
one more RFC...
Major difference vs previous set is a new 'load 64-bit immediate' eBPF insn. Which is first 16-byte instruction. It shows how eBPF ISA can be extended while maintaining backward compatibility, but mainly it cleans up eBPF program access to maps and improves run-time performance.
Wouldn't it be more sensible to follow the scheme used by a lot of cpus and add a 'load high' instruction (follow with 'add' or 'or').
that was what I used before in pred_tree_walker->ebpf patch (4 existing instructions (2 movs, shift, or) to load 'pred' pointer) It's slower in interpreter than single instruction.
Quoted 2 lines
It still takes 16 bytes to load a 64bit immediate value, but the instruction size remains constant.
size of instruction is not important. 99% of instructions are 8 byte long and one is 16 byte. Big deal. It doesn't affect interpreter performance, easy for verifier and was straightforward to do in LLVM as well.
Quoted 1 line
There is nothing to stop any JIT software detecting the instruction pair.
well, it's actually very complicated to detect a sequence of instructions that compute single 64-bit value.
Patch #11 detects and patches pseudo BPF_LD_IMM64 in
a single 'for' loop (see replace_map_fd_with_map_ptr), because it's _single_ instruction. Any sequence of insns would require building control and data flow graphs for verifier and JIT. If you remember I resisted initially when Chema proposed 'load 64-bit immediate' equivalent, since back then the use cases didn't require it. With maps done via FDs, the need has arisen.
Quoted 25 lines · Alexei Starovoitov
Quoted 10 lines · David Laight
From: Of Alexei Starovoitov
Quoted 6 lines
one more RFC...
Major difference vs previous set is a new 'load 64-bit immediate' eBPF insn. Which is first 16-byte instruction. It shows how eBPF ISA can be extended while maintaining backward compatibility, but mainly it cleans up eBPF program access to maps and improves run-time performance.
Wouldn't it be more sensible to follow the scheme used by a lot of cpus and add a 'load high' instruction (follow with 'add' or 'or').
that was what I used before in
pred_tree_walker->ebpfpatch (4 existing instructions (2 movs, shift, or) to load 'pred' pointer) It's slower in interpreter than single instruction.Quoted 2 lines
It still takes 16 bytes to load a 64bit immediate value, but the instruction size remains constant.
size of instruction is not important. 99% of instructions are 8 byte long and one is 16 byte. Big deal. It doesn't affect interpreter performance, easy for verifier and was straightforward to do in LLVM as well.
Quoted 1 line
There is nothing to stop any JIT software detecting the instruction pair.
Quoted 9 lines
well, it's actually very complicated to detect a sequence of instructions that compute single 64-bit value.
Patch #11 detects and patches pseudoBPF_LD_IMM64in
a single 'for' loop (seereplace_map_fd_with_map_ptr), because it's _single_ instruction. Any sequence of insns would require building control and data flow graphs for verifier and JIT. If you remember I resisted initially when Chema proposed 'load 64-bit immediate' equivalent, since back then the use cases didn't require it. With maps done via FDs, the need has arisen.
But don't you need some kind of detection anyway to handle the case where something jumps to the middle of the "load 64-bit immediate"? I think it would be fine to require a particular sequence to load 64-bit immediates if you want the JIT to optimize it well, though.
--Andy
Quoted 3 lines · Andy Lutomirski
But don't you need some kind of detection anyway to handle the case where something jumps to the middle of the "load 64-bit immediate"? I
added few test cases to test_verifier to see that this case is caught and it looks ok, but you got me worried. May be few more checks needed. Thanks!
David Miller
maintainerFrom: David Laight <David.Laight-ZS65k/[email protected]>
Date: Wed, 13 Aug 2014 08:52:30 +0000
Quoted 8 lines
From: Of Alexei Starovoitov
Quoted 6 lines
one more RFC...
Major difference vs previous set is a new 'load 64-bit immediate' eBPF insn. Which is first 16-byte instruction. It shows how eBPF ISA can be extended while maintaining backward compatibility, but mainly it cleans up eBPF program access to maps and improves run-time performance.
Quoted 5 lines
Wouldn't it be more sensible to follow the scheme used by a lot of cpus and add a 'load high' instruction (follow with 'add' or 'or'). It still takes 16 bytes to load a 64bit immediate value, but the instruction size remains constant.
There is nothing to stop any JIT software detecting the instruction pair.
The opposite argument is that JITs can expand the IMM64 load into whatever sequence of instructions is most optimal.
My only real gripe with IMM64 loads is that it's not mainly for loading an immediate, it's for loading a pointer. And this distinction is important for some JITs.
For example, on sparc64 all symbol based addresses are actually 32-bit because of the code model we use to compile the kernel and all modules. So if we knew this is a pointer load and it's to a symbol in a kernel or module image, we could do a 32-bit load.
Quoted 20 lines · David Miller
From: David Laight <[email protected]>
Date: Wed, 13 Aug 2014 08:52:30 +0000Quoted 8 lines
From: Of Alexei Starovoitov
Quoted 6 lines
one more RFC...
Major difference vs previous set is a new 'load 64-bit immediate' eBPF insn. Which is first 16-byte instruction. It shows how eBPF ISA can be extended while maintaining backward compatibility, but mainly it cleans up eBPF program access to maps and improves run-time performance.
Quoted 5 lines
Wouldn't it be more sensible to follow the scheme used by a lot of cpus and add a 'load high' instruction (follow with 'add' or 'or'). It still takes 16 bytes to load a 64bit immediate value, but the instruction size remains constant.
There is nothing to stop any JIT software detecting the instruction pair.The opposite argument is that JITs can expand the IMM64 load into whatever sequence of instructions is most optimal.
Quoted 8 lines
My only real gripe with IMM64 loads is that it's not mainly for loading an immediate, it's for loading a pointer. And this distinction is important for some JITs.
For example, on sparc64 all symbol based addresses are actually 32-bit because of the code model we use to compile the kernel and all modules. So if we knew this is a pointer load and it's to a symbol in a kernel or module image, we could do a 32-bit load.
This is true for x86_64 as well, I think.
(Almost. For x86_64 we have a choice between a sign-extended load of a value in the top 2GB of the address space and lea reg,offset(%rip).)
--Andy
Quoted 30 lines · Andy Lutomirski
Quoted 20 lines · David Miller
From: David Laight <David.Laight-ZS65k/[email protected]>
Date: Wed, 13 Aug 2014 08:52:30 +0000Quoted 8 lines
From: Of Alexei Starovoitov
Quoted 6 lines
one more RFC...
Major difference vs previous set is a new 'load 64-bit immediate' eBPF insn. Which is first 16-byte instruction. It shows how eBPF ISA can be extended while maintaining backward compatibility, but mainly it cleans up eBPF program access to maps and improves run-time performance.
Quoted 5 lines
Wouldn't it be more sensible to follow the scheme used by a lot of cpus and add a 'load high' instruction (follow with 'add' or 'or'). It still takes 16 bytes to load a 64bit immediate value, but the instruction size remains constant.
There is nothing to stop any JIT software detecting the instruction pair.The opposite argument is that JITs can expand the IMM64 load into whatever sequence of instructions is most optimal.
Quoted 8 lines
My only real gripe with IMM64 loads is that it's not mainly for loading an immediate, it's for loading a pointer. And this distinction is important for some JITs.
For example, on sparc64 all symbol based addresses are actually 32-bit because of the code model we use to compile the kernel and all modules. So if we knew this is a pointer load and it's to a symbol in a kernel or module image, we could do a 32-bit load.
Quoted 4 lines
This is true for
x86_64as well, I think.(Almost. For
x86_64we have a choice between a sign-extended load of a value in the top 2GB of the address space and lea reg,offset(%rip).)
That would be an interesting optimization. I did movabsq just because it was straightforward. JITs can play interesting tricks here. Since it's really a constant value, there is no difference whether it's a pointer or a constant. If JIT can use $rip trick on x64 or reduce number of sethi insns on sparc, it should try to do it regardless of how value in dst_reg will be used later on by the program. JITs can also allocate some read-only area for constants and do a relative load from there. Not sure that it will be faster though. JITs can get more complex and smarter as time goes by. They can even randomly do some ld_imm64 via movabsq and some via a sequence of mov, shift, or. That will through away JIT spraying attacks. If JITed code itself is random, that would be nice defense.
Quoted 36 lines · Alexei Starovoitov
Quoted 30 lines · Andy Lutomirski
Quoted 20 lines · David Miller
From: David Laight <[email protected]>
Date: Wed, 13 Aug 2014 08:52:30 +0000Quoted 8 lines
From: Of Alexei Starovoitov
Quoted 6 lines
one more RFC...
Major difference vs previous set is a new 'load 64-bit immediate' eBPF insn. Which is first 16-byte instruction. It shows how eBPF ISA can be extended while maintaining backward compatibility, but mainly it cleans up eBPF program access to maps and improves run-time performance.
Quoted 5 lines
Wouldn't it be more sensible to follow the scheme used by a lot of cpus and add a 'load high' instruction (follow with 'add' or 'or'). It still takes 16 bytes to load a 64bit immediate value, but the instruction size remains constant.
There is nothing to stop any JIT software detecting the instruction pair.The opposite argument is that JITs can expand the IMM64 load into whatever sequence of instructions is most optimal.
Quoted 8 lines
My only real gripe with IMM64 loads is that it's not mainly for loading an immediate, it's for loading a pointer. And this distinction is important for some JITs.
For example, on sparc64 all symbol based addresses are actually 32-bit because of the code model we use to compile the kernel and all modules. So if we knew this is a pointer load and it's to a symbol in a kernel or module image, we could do a 32-bit load.
Quoted 4 lines
This is true for
x86_64as well, I think.(Almost. For
x86_64we have a choice between a sign-extended load of a value in the top 2GB of the address space and lea reg,offset(%rip).)
Quoted 12 lines
That would be an interesting optimization. I did movabsq just because it was straightforward. JITs can play interesting tricks here. Since it's really a constant value, there is no difference whether it's a pointer or a constant. If JIT can use $rip trick on x64 or reduce number of sethi insns on sparc, it should try to do it regardless of how value in
dst_regwill be used later on by the program. JITs can also allocate some read-only area for constants and do a relative load from there. Not sure that it will be faster though. JITs can get more complex and smarter as time goes by. They can even randomly do someld_imm64via movabsq and some via a sequence of mov, shift, or. That will through away JIT spraying attacks. If JITed code itself is random, that would be nice defense.
You can be even fancier on x86_64: if the JIT code ends up being allocated withing 2GB of the maps, then you can access kernel code using absolute addresses and the maps using rip-relative addresses.
Depending on exactly what's going on, though, the best option may be to use x86's fancy addressing modes for calls and loads. That will be harder.
--Andy
On Wed, Aug 13, 2014 at 12:57 AM, Alexei Starovoitov <ast-uqk4Ao+rVK5Wk0Htik3J/[email protected]> wrote:
[...]
Quoted 5 lines
Tracing use case got some improvements as well. Now eBPF programs can be attached to tracepoint, syscall, kprobe and C examples are more usable:
ex1_kern.c- demonstrate how programs can walk in-kernel data structuresex2_kern.c- in-kernel event accounting and user space histograms See patch #25
This is great, thanks! I've been using this new support, and successfully ported an an older tool of mine (bitesize) to eBPF. I was using the block:block_rq_issue tracepoint, and performing a custom in-kernel histogram, like in the ex2_kern.c example, for I/O size.
I also did some quick overhead testing and found eBPF with JIT to be relatively fast. (I'd share numbers but it's platform specific.) The syscall tracepoints were a bit slower than hoped, for what I think is a well known issue.
Are there thoughts in general for how this might be used for embedded devices, where installing clang/llvm might be prohibitive? Compile on another system and move the binaries over? thanks,
Brendan