From: Jiri Olsa <hidden> Date: 2021-08-26 19:39:28
hi,
sending new version of batch attach support, previous post
is in here [1].
The previous post could not assign multi trampoline on top
of regular trampolines. This patchset is trying to address
that, plus it has other fixes from last post.
This patchset contains:
1) patches (1-4) that fix the ftrace graph tracing over the function
with direct trampolines attached
2) patches (5-8) that add batch interface for ftrace direct function
register/unregister/modify
3) patches (9-27) that add support to attach BPF program to multiple
functions
The current functionality in nutshell:
- allows to create 'multi trampoline' and use it to attach single
program over multiple functions
- it's possible to attach 'multi trampoline' on top of functions
with attached trampoline
- once 'multi trampoline' is created, the functions are locked and we:
- do not allow to attach another 'multi trampoline' that intersects
partially with already attached multi trampoline
- do not allow to attach another standard trampoline on any function
from 'multi trampoline'
- allow to reuse 'multi trampoline' and attach another multi program
in it
These limitations are enforced to keep the implementation simple,
because having multi trampolines to intersect would bring more
complexity plus more ftrace direct API changes.
It'd be probably possible allowing to attach another standard
trampoline to 'multi trampoline' if needed.
v4 other changes from previous review:
- more detailed changelogs in several patches
- removed 'ip' argument assumption in verifier code,
because we now have bpf_get_func_ip helper
- moved 'multi_func' under other bools in bpf.h [Yonghong]
- used static linker in selftests [Andrii]
- added more tests
- added btf__find_by_glob_kind for simplified glob matching
instead of the previous glibc glob matching [Andrii]
- used '__ksym' instead of resolving test functions [Andrii]
- I kept the single BPF_F_MULTI_FUNC flag instead of adding
new multi prog type, because it'd be more complex
- removed superfluous BPF_PROG_TYPE_TRACING/multi_func check
from check_multi_prog_type [Yonghong]
- kept link_create.iter_info_len as BPF_LINK_CREATE_LAST_FIELD
[Yonghong]
- define FTRACE_OPS_GRAPH_STUB 0 to make code look sane [Andrii]
- removed BPF_LINK_UPDATE interface
Also available at:
https://git.kernel.org/pub/scm/linux/kernel/git/jolsa/perf.git
bpf/batch
thanks,
jirka
[1] https://lore.kernel.org/bpf/20210605111034.1810858-1-jolsa@kernel.org/
---
Jiri Olsa (25):
x86/ftrace: Remove extra orig rax move
tracing: Add trampoline/graph selftest
ftrace: Add ftrace_add_rec_direct function
ftrace: Add multi direct register/unregister interface
ftrace: Add multi direct modify interface
ftrace/samples: Add multi direct interface test module
bpf: Add support to load multi func tracing program
bpf: Add struct bpf_tramp_node layer
bpf: Factor out bpf_trampoline_init function
bpf: Factor out __bpf_trampoline_lookup function
bpf: Factor out __bpf_trampoline_put function
bpf: Change bpf_trampoline_get to return error pointer
bpf, x64: Allow to use caller address from stack
bpf: Add bpf_trampoline_multi_get/put functions
bpf: Add multi trampoline attach support
bpf, x64: Store properly return value for trampoline with multi func programs
bpf: Attach multi trampoline with ftrace_ops
libbpf: Add btf__find_by_glob_kind function
libbpf: Add support to link multi func tracing program
selftests/bpf: Add fentry multi func test
selftests/bpf: Add fexit multi func test
selftests/bpf: Add fentry/fexit multi func test
selftests/bpf: Add mixed multi func test
selftests/bpf: Add attach multi func test
selftests/bpf: Add ret_mod multi func test
Steven Rostedt (VMware) (2):
x86/ftrace: Remove fault protection code in prepare_ftrace_return
x86/ftrace: Make function graph use ftrace directly
arch/x86/Makefile | 7 +++
arch/x86/boot/compressed/Makefile | 4 ++
arch/x86/include/asm/ftrace.h | 9 +++-
arch/x86/kernel/ftrace.c | 71 +++++++++++++------------
arch/x86/kernel/ftrace_64.S | 30 +----------
arch/x86/net/bpf_jit_comp.c | 53 +++++++++++++++----
drivers/firmware/efi/libstub/Makefile | 3 ++
include/linux/bpf.h | 44 ++++++++++++++--
include/linux/ftrace.h | 22 ++++++++
include/uapi/linux/bpf.h | 12 +++++
kernel/bpf/core.c | 2 +
kernel/bpf/syscall.c | 163 +++++++++++++++++++++++++++++++++++++++++++++++++++++----
kernel/bpf/trampoline.c | 400 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------
kernel/bpf/verifier.c | 7 +--
kernel/trace/fgraph.c | 6 ++-
kernel/trace/ftrace.c | 214 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
kernel/trace/trace_selftest.c | 49 ++++++++++++++++-
samples/ftrace/Makefile | 1 +
samples/ftrace/ftrace-direct-multi.c | 52 ++++++++++++++++++
tools/include/uapi/linux/bpf.h | 12 +++++
tools/lib/bpf/bpf.c | 8 +++
tools/lib/bpf/bpf.h | 6 ++-
tools/lib/bpf/btf.c | 80 ++++++++++++++++++++++++++++
tools/lib/bpf/btf.h | 3 ++
tools/lib/bpf/libbpf.c | 72 +++++++++++++++++++++++++
tools/testing/selftests/bpf/Makefile | 8 ++-
tools/testing/selftests/bpf/prog_tests/modify_return.c | 114 ++++++++++++++++++++++++++++++++++++++--
tools/testing/selftests/bpf/prog_tests/multi_attach_check_test.c | 115 ++++++++++++++++++++++++++++++++++++++++
tools/testing/selftests/bpf/prog_tests/multi_fentry_fexit_test.c | 32 ++++++++++++
tools/testing/selftests/bpf/prog_tests/multi_fentry_test.c | 30 +++++++++++
tools/testing/selftests/bpf/prog_tests/multi_fexit_test.c | 31 +++++++++++
tools/testing/selftests/bpf/prog_tests/multi_mixed_test.c | 34 ++++++++++++
tools/testing/selftests/bpf/progs/multi_attach_check.c | 36 +++++++++++++
tools/testing/selftests/bpf/progs/multi_attach_check_extra1.c | 12 +++++
tools/testing/selftests/bpf/progs/multi_attach_check_extra2.c | 12 +++++
tools/testing/selftests/bpf/progs/multi_check.c | 85 ++++++++++++++++++++++++++++++
tools/testing/selftests/bpf/progs/multi_fentry.c | 17 ++++++
tools/testing/selftests/bpf/progs/multi_fentry_fexit.c | 28 ++++++++++
tools/testing/selftests/bpf/progs/multi_fexit.c | 20 +++++++
tools/testing/selftests/bpf/progs/multi_mixed.c | 43 +++++++++++++++
tools/testing/selftests/bpf/progs/multi_modify_return.c | 17 ++++++
41 files changed, 1799 insertions(+), 165 deletions(-)
create mode 100644 samples/ftrace/ftrace-direct-multi.c
create mode 100644 tools/testing/selftests/bpf/prog_tests/multi_attach_check_test.c
create mode 100644 tools/testing/selftests/bpf/prog_tests/multi_fentry_fexit_test.c
create mode 100644 tools/testing/selftests/bpf/prog_tests/multi_fentry_test.c
create mode 100644 tools/testing/selftests/bpf/prog_tests/multi_fexit_test.c
create mode 100644 tools/testing/selftests/bpf/prog_tests/multi_mixed_test.c
create mode 100644 tools/testing/selftests/bpf/progs/multi_attach_check.c
create mode 100644 tools/testing/selftests/bpf/progs/multi_attach_check_extra1.c
create mode 100644 tools/testing/selftests/bpf/progs/multi_attach_check_extra2.c
create mode 100644 tools/testing/selftests/bpf/progs/multi_check.c
create mode 100644 tools/testing/selftests/bpf/progs/multi_fentry.c
create mode 100644 tools/testing/selftests/bpf/progs/multi_fentry_fexit.c
create mode 100644 tools/testing/selftests/bpf/progs/multi_fexit.c
create mode 100644 tools/testing/selftests/bpf/progs/multi_mixed.c
create mode 100644 tools/testing/selftests/bpf/progs/multi_modify_return.c
From: Jiri Olsa <hidden> Date: 2021-08-26 19:39:40
From: "Steven Rostedt (VMware)" <rostedt@goodmis.org>
Removing the fault protection code when writing return_hooker
to stack. As Steven noted:
That protection was there from the beginning due to being "paranoid",
considering ftrace was bricking network cards. But that protection
would not have even protected against that.
From: Jiri Olsa <hidden> Date: 2021-08-26 19:39:46
From: "Steven Rostedt (VMware)" <rostedt@goodmis.org>
We don't need special hook for graph tracer entry point,
but instead we can use graph_ops::func function to install
the return_hooker.
This moves the graph tracing setup _before_ the direct
trampoline prepares the stack, so the return_hooker will
be called when the direct trampoline is finished.
This simplifies the code, because we don't need to take into
account the direct trampoline setup when preparing the graph
tracer hooker and we can allow function graph tracer on entries
registered with direct trampoline.
Signed-off-by: Steven Rostedt (VMware) <rostedt@goodmis.org>
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
arch/x86/include/asm/ftrace.h | 9 +++++++--
arch/x86/kernel/ftrace.c | 37 ++++++++++++++++++++++++++++++++---
arch/x86/kernel/ftrace_64.S | 29 +--------------------------
include/linux/ftrace.h | 6 ++++++
kernel/trace/fgraph.c | 6 ++++--
5 files changed, 52 insertions(+), 35 deletions(-)
@@ -65,8 +72,6 @@ struct dyn_arch_ftrace {/* No extra data needed for x86 */};-#define FTRACE_GRAPH_TRAMP_ADDR FTRACE_GRAPH_ADDR-#endif /* CONFIG_DYNAMIC_FTRACE */#endif /* __ASSEMBLY__ */#endif /* CONFIG_FUNCTION_TRACER */
@@ -115,6 +115,7 @@ int function_graph_enter(unsigned long ret, unsigned long func,{structftrace_graph_enttrace;+#ifndef CONFIG_HAVE_DYNAMIC_FTRACE_WITH_ARGS/**Skipgraphtracingifthereturnlocationisservedbydirecttrampoline,*sincecallsequenceandreturnaddressesareunpredictableanyway.
@@ -124,6 +125,7 @@ int function_graph_enter(unsigned long ret, unsigned long func,if(ftrace_direct_func_count&&ftrace_find_rec_direct(ret-MCOUNT_INSN_SIZE))return-EBUSY;+#endiftrace.func=func;trace.depth=++current->curr_ret_depth;
@@ -333,10 +335,10 @@ unsigned long ftrace_graph_ret_addr(struct task_struct *task, int *idx,#endif /* HAVE_FUNCTION_GRAPH_RET_ADDR_PTR */staticstructftrace_opsgraph_ops={-.func=ftrace_stub,+.func=ftrace_graph_func,.flags=FTRACE_OPS_FL_INITIALIZED|FTRACE_OPS_FL_PID|-FTRACE_OPS_FL_STUB,+FTRACE_OPS_GRAPH_STUB,#ifdef FTRACE_GRAPH_TRAMP_ADDR.trampoline=FTRACE_GRAPH_TRAMP_ADDR,/* trampoline_size is only needed for dynamically allocated tramps */
From: Jiri Olsa <hidden> Date: 2021-08-26 19:39:54
Adding selftest for checking that direct trampoline can
co-exist together with graph tracer on same function.
This is supported for CONFIG_HAVE_DYNAMIC_FTRACE_WITH_ARGS
config option, which is defined only for x86_64 for now.
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
kernel/trace/trace_selftest.c | 49 ++++++++++++++++++++++++++++++++++-
1 file changed, 48 insertions(+), 1 deletion(-)
@@ -808,8 +811,52 @@ trace_selftest_startup_function_graph(struct tracer *trace,gotoout;}-/* Don't test dynamic tracing, the function tracer already did */+#ifdef CONFIG_HAVE_DYNAMIC_FTRACE_WITH_ARGS+tracing_reset_online_cpus(&tr->array_buffer);+set_graph_array(tr);+/*+*Somearchs*cough*PowerPC*cough*addcharacterstothe+*startofthefunctionnames.Wesimplyputa'*'to+*accommodatethem.+*/+func_name="*"__stringify(DYN_FTRACE_TEST_NAME);+ftrace_set_global_filter(func_name,strlen(func_name),1);++/*+*Registerdirectfunctiontogetherwithgraphtracer+*andmakesurewegetgraphtrace.+*/+ret=register_ftrace_direct((unsignedlong)DYN_FTRACE_TEST_NAME,+(unsignedlong)trace_direct_tramp);+if(ret)+gotoout;++ret=register_ftrace_graph(&fgraph_ops);+if(ret){+warn_failed_init_tracer(trace,ret);+gotoout;+}++DYN_FTRACE_TEST_NAME();++count=0;++tracing_stop();+/* check the trace buffer */+ret=trace_test_buffer(&tr->array_buffer,&count);++unregister_ftrace_graph(&fgraph_ops);++tracing_start();++if(!ret&&!count){+ret=-1;+gotoout;+}+#endif++/* Don't test dynamic tracing, the function tracer already did */out:/* Stop it if we failed */if(ret)
From: Jiri Olsa <hidden> Date: 2021-08-26 19:40:02
Factor out the code that adds (ip, addr) tuple to direct_functions
hash in new ftrace_add_rec_direct function. It will be used in
following patches.
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
kernel/trace/ftrace.c | 60 ++++++++++++++++++++++++++-----------------
1 file changed, 36 insertions(+), 24 deletions(-)
@@ -2394,6 +2394,39 @@ unsigned long ftrace_find_rec_direct(unsigned long ip)returnentry->direct;}+staticstructftrace_func_entry*+ftrace_add_rec_direct(unsignedlongip,unsignedlongaddr,+structftrace_hash**free_hash)+{+structftrace_func_entry*entry;++if(ftrace_hash_empty(direct_functions)||+direct_functions->count>2*(1<<direct_functions->size_bits)){+structftrace_hash*new_hash;+intsize=ftrace_hash_empty(direct_functions)?0:+direct_functions->count+1;++if(size<32)+size=32;++new_hash=dup_hash(direct_functions,size);+if(!new_hash)+returnNULL;++*free_hash=direct_functions;+direct_functions=new_hash;+}++entry=kmalloc(sizeof(*entry),GFP_KERNEL);+if(!entry)+returnNULL;++entry->ip=ip;+entry->direct=addr;+__add_hash_entry(direct_functions,entry);+returnentry;+}+staticvoidcall_direct_funcs(unsignedlongip,unsignedlongpip,structftrace_ops*ops,structftrace_regs*fregs){
@@ -5110,27 +5143,6 @@ int register_ftrace_direct(unsigned long ip, unsigned long addr)}ret=-ENOMEM;-if(ftrace_hash_empty(direct_functions)||-direct_functions->count>2*(1<<direct_functions->size_bits)){-structftrace_hash*new_hash;-intsize=ftrace_hash_empty(direct_functions)?0:-direct_functions->count+1;--if(size<32)-size=32;--new_hash=dup_hash(direct_functions,size);-if(!new_hash)-gotoout_unlock;--free_hash=direct_functions;-direct_functions=new_hash;-}--entry=kmalloc(sizeof(*entry),GFP_KERNEL);-if(!entry)-gotoout_unlock;-direct=ftrace_find_direct_func(addr);if(!direct){direct=ftrace_alloc_direct_func(addr);
@@ -5140,9 +5152,9 @@ int register_ftrace_direct(unsigned long ip, unsigned long addr)}}-entry->ip=ip;-entry->direct=addr;-__add_hash_entry(direct_functions,entry);+entry=ftrace_add_rec_direct(ip,addr,&free_hash);+if(!entry)+gotoout_unlock;ret=ftrace_set_filter_ip(&direct_ops,ip,0,0);if(ret)
From: Jiri Olsa <hidden> Date: 2021-08-26 19:40:05
Adding interface to register multiple direct functions
within single call. Adding following functions:
register_ftrace_direct_multi(struct ftrace_ops *ops, unsigned long addr)
unregister_ftrace_direct_multi(struct ftrace_ops *ops)
The register_ftrace_direct_multi registers direct function (addr)
with all functions in ops filter. The ops filter can be updated
before with ftrace_set_filter_ip calls.
All requested functions must not have direct function currently
registered, otherwise register_ftrace_direct_multi will fail.
The unregister_ftrace_direct_multi unregisters ops related direct
functions.
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
include/linux/ftrace.h | 10 ++++
kernel/trace/ftrace.c | 111 +++++++++++++++++++++++++++++++++++++++++
2 files changed, 121 insertions(+)
@@ -5407,6 +5407,117 @@ int modify_ftrace_direct(unsigned long ip,returnret;}EXPORT_SYMBOL_GPL(modify_ftrace_direct);++#define MULTI_FLAGS (FTRACE_OPS_FL_IPMODIFY | FTRACE_OPS_FL_DIRECT | \+FTRACE_OPS_FL_SAVE_REGS)++staticintcheck_direct_multi(structftrace_ops*ops)+{+if(!(ops->flags&FTRACE_OPS_FL_INITIALIZED))+return-EINVAL;+if((ops->flags&MULTI_FLAGS)!=MULTI_FLAGS)+return-EINVAL;+return0;+}++intregister_ftrace_direct_multi(structftrace_ops*ops,unsignedlongaddr)+{+structftrace_hash*hash,*free_hash=NULL;+structftrace_func_entry*entry,*new;+interr=-EBUSY,size,i;++if(ops->func||ops->trampoline)+return-EINVAL;+if(!(ops->flags&FTRACE_OPS_FL_INITIALIZED))+return-EINVAL;+if(ops->flags&FTRACE_OPS_FL_ENABLED)+return-EINVAL;++hash=ops->func_hash->filter_hash;+if(ftrace_hash_empty(hash))+return-EINVAL;++mutex_lock(&direct_mutex);++/* Make sure requested entries are not already registered.. */+size=1<<hash->size_bits;+for(i=0;i<size;i++){+hlist_for_each_entry(entry,&hash->buckets[i],hlist){+if(ftrace_find_rec_direct(entry->ip))+gotoout_unlock;+}+}++/* ... and insert them to direct_functions hash. */+err=-ENOMEM;+for(i=0;i<size;i++){+hlist_for_each_entry(entry,&hash->buckets[i],hlist){+new=ftrace_add_rec_direct(entry->ip,addr,&free_hash);+if(!new)+gotoout_remove;+entry->direct=addr;+}+}++ops->func=call_direct_funcs;+ops->flags=MULTI_FLAGS;+ops->trampoline=FTRACE_REGS_ADDR;++err=register_ftrace_function(ops);++out_remove:+if(err){+for(i=0;i<size;i++){+hlist_for_each_entry(entry,&hash->buckets[i],hlist){+new=__ftrace_lookup_ip(direct_functions,entry->ip);+if(new){+remove_hash_entry(direct_functions,new);+kfree(new);+}+}+}+}++out_unlock:+mutex_unlock(&direct_mutex);++if(free_hash){+synchronize_rcu_tasks();+free_ftrace_hash(free_hash);+}+returnerr;+}+EXPORT_SYMBOL_GPL(register_ftrace_direct_multi);++intunregister_ftrace_direct_multi(structftrace_ops*ops)+{+structftrace_hash*hash=ops->func_hash->filter_hash;+structftrace_func_entry*entry,*new;+interr,size,i;++if(check_direct_multi(ops))+return-EINVAL;+if(!(ops->flags&FTRACE_OPS_FL_ENABLED))+return-EINVAL;++mutex_lock(&direct_mutex);+err=unregister_ftrace_function(ops);++size=1<<hash->size_bits;+for(i=0;i<size;i++){+hlist_for_each_entry(entry,&hash->buckets[i],hlist){+new=__ftrace_lookup_ip(direct_functions,entry->ip);+if(new){+remove_hash_entry(direct_functions,new);+kfree(new);+}+}+}++mutex_unlock(&direct_mutex);+returnerr;+}+EXPORT_SYMBOL_GPL(unregister_ftrace_direct_multi);#endif /* CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS *//**
From: Jiri Olsa <hidden> Date: 2021-08-26 19:40:11
Adding interface to modify registered direct function
for ftrace_ops. Adding following function:
modify_ftrace_direct_multi(struct ftrace_ops *ops, unsigned long addr)
The function changes the currently registered direct
function for all attached functions.
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
include/linux/ftrace.h | 6 ++++++
kernel/trace/ftrace.c | 43 ++++++++++++++++++++++++++++++++++++++++++
2 files changed, 49 insertions(+)
From: Jiri Olsa <hidden> Date: 2021-08-26 19:40:19
Adding simple module that uses multi direct interface:
register_ftrace_direct_multi
unregister_ftrace_direct_multi
The init function registers trampoline for 2 functions,
and exit function unregisters them.
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
samples/ftrace/Makefile | 1 +
samples/ftrace/ftrace-direct-multi.c | 52 ++++++++++++++++++++++++++++
2 files changed, 53 insertions(+)
create mode 100644 samples/ftrace/ftrace-direct-multi.c
From: Jiri Olsa <hidden> Date: 2021-08-26 19:40:28
Adding support to load tracing program with new BPF_F_MULTI_FUNC flag,
that allows the program to be loaded without specific function to be
attached to.
Such program will be allowed to be attached to multiple functions
in following patches.
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
include/linux/bpf.h | 1 +
include/uapi/linux/bpf.h | 7 +++++++
kernel/bpf/syscall.c | 35 +++++++++++++++++++++++++++++-----
kernel/bpf/verifier.c | 3 ++-
tools/include/uapi/linux/bpf.h | 7 +++++++
5 files changed, 47 insertions(+), 6 deletions(-)
@@ -1110,6 +1110,13 @@ enum bpf_link_type {*/#define BPF_F_SLEEPABLE (1U << 4)+/* If BPF_F_MULTI_FUNC is used in BPF_PROG_LOAD command, the verifier does+*notexpectBTFIDfortheprogram,insteaditassumesit'sfunction+*with6u64arguments.Notrampolineiscreatedfortheprogram.Such+*programcanbeattachedtomultiplefunctions.+*/+#define BPF_F_MULTI_FUNC (1U << 5)+/* When BPF ldimm64's insn[0].src_reg != 0 then this can have*thefollowingextensions:*
@@ -2155,6 +2165,16 @@ static bool is_perfmon_prog_type(enum bpf_prog_type prog_type)}}+#define DEFINE_BPF_MULTI_FUNC(args...) \+externintbpf_multi_func(args);\+int__initbpf_multi_func(args){return0;}++DEFINE_BPF_MULTI_FUNC(unsignedlonga1,unsignedlonga2,+unsignedlonga3,unsignedlonga4,+unsignedlonga5,unsignedlonga6)++BTF_ID_LIST_SINGLE(bpf_multi_func_btf_id,func,bpf_multi_func)+/* last field in 'union bpf_attr' used by this command */#define BPF_PROG_LOAD_LAST_FIELD fd_array
@@ -2205,6 +2227,8 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr)if(is_perfmon_prog_type(type)&&!perfmon_capable())return-EPERM;+multi_func=attr->prog_flags&BPF_F_MULTI_FUNC;+/* attach_prog_fd/attach_btf_obj_fd can specify fd of either bpf_prog*orbtf,weneedtocheckwhichoneitis*/
@@ -2223,7 +2247,7 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr)return-ENOTSUPP;}}-}elseif(attr->attach_btf_id){+}elseif(attr->attach_btf_id||multi_func){/* fall back to vmlinux BTF, if BTF type ID is specified */attach_btf=bpf_get_btf_vmlinux();if(IS_ERR(attach_btf))
@@ -1110,6 +1110,13 @@ enum bpf_link_type {*/#define BPF_F_SLEEPABLE (1U << 4)+/* If BPF_F_MULTI_FUNC is used in BPF_PROG_LOAD command, the verifier does+*notexpectBTFIDfortheprogram,insteaditassumesit'sfunction+*with6u64arguments.Notrampolineiscreatedfortheprogram.Such+*programcanbeattachedtomultiplefunctions.+*/+#define BPF_F_MULTI_FUNC (1U << 5)+/* When BPF ldimm64's insn[0].src_reg != 0 then this can have*thefollowingextensions:*
From: Jiri Olsa <hidden> Date: 2021-08-26 19:40:37
Currently each trampoline holds a list of programs that
are attached to it. With multi func attach support we need
a way for a single program to be connected to multiple
trampolines.
Adding struct bpf_tramp_node object that holds bpf_prog
pointer, so it can be resolved directly. We can now
have multiple struct bpf_tramp_node being attached to
different trampolines pointing to single bpf_prog.
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
include/linux/bpf.h | 15 ++++++++++-----
kernel/bpf/core.c | 1 +
kernel/bpf/syscall.c | 4 ++--
kernel/bpf/trampoline.c | 22 ++++++++++++----------
4 files changed, 25 insertions(+), 17 deletions(-)
@@ -866,7 +871,7 @@ struct bpf_prog_aux {boolsleepable;booltail_call_reachable;boolmulti_func;-structhlist_nodetramp_hlist;+structbpf_tramp_nodetramp_node;/* BTF_KIND_FUNC_PROTO for valid attach_btf_id */conststructbtf_type*attach_func_proto;/* function name for valid attach_btf_id */
From: Jiri Olsa <hidden> Date: 2021-08-26 19:40:55
Separating out bpf_trampoline_init function, so it can
be used from other places in following patches.
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
kernel/bpf/trampoline.c | 21 +++++++++++++--------
1 file changed, 13 insertions(+), 8 deletions(-)
From: Jiri Olsa <hidden> Date: 2021-08-26 19:40:57
Separating out __bpf_trampoline_lookup function, so it can
be used from other places in following patches.
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
kernel/bpf/trampoline.c | 26 ++++++++++++++++++++------
1 file changed, 20 insertions(+), 6 deletions(-)
From: Jiri Olsa <hidden> Date: 2021-08-26 19:40:58
Separating out __bpf_trampoline_put function, so it can
be used from other places in following patches.
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
kernel/bpf/trampoline.c | 21 +++++++++++++--------
1 file changed, 13 insertions(+), 8 deletions(-)
@@ -522,18 +522,16 @@ struct bpf_trampoline *bpf_trampoline_get(u64 key,returntr;}-voidbpf_trampoline_put(structbpf_trampoline*tr)+staticvoid__bpf_trampoline_put(structbpf_trampoline*tr){-if(!tr)-return;-mutex_lock(&trampoline_mutex);+lockdep_assert_held(&trampoline_mutex);if(!refcount_dec_and_test(&tr->refcnt))-gotoout;+return;WARN_ON_ONCE(mutex_is_locked(&tr->mutex));if(WARN_ON_ONCE(!hlist_empty(&tr->progs_hlist[BPF_TRAMP_FENTRY])))-gotoout;+return;if(WARN_ON_ONCE(!hlist_empty(&tr->progs_hlist[BPF_TRAMP_FEXIT])))-gotoout;+return;/* This code will be executed even when the last bpf_tramp_image*isalive.Allprogsaredetachedfromthetrampolineandthe*trampolineimageispatchedwithjmpintoepiloguetoskip
From: Jiri Olsa <hidden> Date: 2021-08-26 19:41:01
Changing bpf_trampoline_get to return error pointer,
so we can return other than ENOMEM error in following
changes.
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
kernel/bpf/syscall.c | 4 ++--
kernel/bpf/trampoline.c | 8 +++++---
kernel/bpf/verifier.c | 4 ++--
3 files changed, 9 insertions(+), 7 deletions(-)
From: Jiri Olsa <hidden> Date: 2021-08-26 19:41:09
Currently we call the original function by using the absolute address
given at the JIT generation. That's not usable when having trampoline
attached to multiple functions. In this case we need to take the
return address from the stack.
Adding support to retrieve the original function address from the stack
by adding new BPF_TRAMP_F_ORIG_STACK flag for arch_prepare_bpf_trampoline
function.
Basically we take the return address of the 'fentry' call:
function + 0: call fentry # stores 'function + 5' address on stack
function + 5: ...
The 'function + 5' address will be used as the address for the
original function to call.
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
arch/x86/net/bpf_jit_comp.c | 13 +++++++++----
include/linux/bpf.h | 5 +++++
2 files changed, 14 insertions(+), 4 deletions(-)
@@ -2024,10 +2024,15 @@ int arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *image, void *iif(flags&BPF_TRAMP_F_CALL_ORIG){restore_regs(m,&prog,nr_args,stack_size);-/* call original function */-if(emit_call(&prog,orig_call,prog)){-ret=-EINVAL;-gotocleanup;+if(flags&BPF_TRAMP_F_ORIG_STACK){+emit_ldx(&prog,BPF_DW,BPF_REG_0,BPF_REG_FP,8);+EMIT2(0xff,0xd0);/* call *rax */+}else{+/* call original function */+if(emit_call(&prog,orig_call,prog)){+ret=-EINVAL;+gotocleanup;+}}/* remember return value in a stack for bpf prog to access */emit_stx(&prog,BPF_DW,BPF_REG_FP,BPF_REG_0,-8);
@@ -584,6 +584,11 @@ struct btf_func_model {*/#define BPF_TRAMP_F_IP_ARG BIT(3)+/* Get original function from stack instead of from provided direct address.+*Makessenseforfexitprogramsonly.+*/+#define BPF_TRAMP_F_ORIG_STACK BIT(4)+/* Each call __bpf_prog_enter + call bpf_func + call __bpf_prog_exit is ~50*bytesonx86.PickanumbertofitintoBPF_IMAGE_SIZE/2*/
From: Jiri Olsa <hidden> Date: 2021-08-26 19:41:11
Adding struct bpf_trampoline_multi object and API to allocate
and free it.
The multi bpf trampoline is defined by BTF ids that represents
functions that the trampoline will be attached to.
By calling bpf_trampoline_multi_get you'll allocate new or get
existing bpf_trampoline_multi object with following rules:
- multi trampolines BTF ids can't intersect
- multi trampoline can attach to functions that have standard
program attached
- standard programs can't attach to functions that have multi
trampoline attached
The multi trampoline contains pointers to all 'nested' standard
trampolines and 'main' standard trampoline object (with key == 0)
that represents the rest of the functions.
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
include/linux/bpf.h | 15 ++++
kernel/bpf/trampoline.c | 179 ++++++++++++++++++++++++++++++++++++++++
2 files changed, 194 insertions(+)
@@ -10,6 +10,9 @@#include<linux/rcupdate_trace.h>#include<linux/rcupdate_wait.h>#include<linux/module.h>+#include<linux/bsearch.h>+#include<linux/bpf_verifier.h>+#include<linux/sort.h>/* dummy _ops. The verifier will operate on target program's ops. */conststructbpf_verifier_opsbpf_extension_verifier_ops={
@@ -553,6 +586,152 @@ void bpf_trampoline_put(struct bpf_trampoline *tr)mutex_unlock(&trampoline_mutex);}+staticvoidbpf_func_model_nargs(structbtf_func_model*m,intnr_args)+{+inti;++for(i=0;i<nr_args;i++)+m->arg_size[i]=8;+m->ret_size=8;+m->nr_args=nr_args;+}++staticstructbpf_trampoline*lookup_trampoline(structbpf_prog*prog,u32id)+{+u64key=bpf_trampoline_compute_key(NULL,prog->aux->attach_btf,id);++return__bpf_trampoline_lookup(key);+}++structbpf_trampoline_multi*bpf_trampoline_multi_get(structbpf_prog*prog,+u32*ids,u32ids_cnt)+{+inti,j,tr_cnt=0,err=0;+structbpf_trampoline_multi*multi;+structbpf_trampoline*tr;+u8nr_args=0;+size_tsize;++/* Sort user provided BTF ids, so we can use memcpy+*andbsearchbelow.+*/+sort(ids,ids_cnt,sizeof(u32),btf_ids_cmp,NULL);++mutex_lock(&trampoline_mutex);+/* Check if the requested multi trampoline already exists. */+list_for_each_entry(multi,&trampoline_multi,list){+if(ids_cnt==multi->ids_cnt&&!memcmp(ids,multi->ids,ids_cnt)){+refcount_inc(&multi->main.refcnt);+kfree(ids);+gotoout;+}+for(i=0;i<ids_cnt;i++){+if(bsearch(&ids[i],multi->ids,multi->ids_cnt,+sizeof(u32),btf_ids_cmp)){+multi=ERR_PTR(-EINVAL);+gotoout;+}+}+}++/* Check if any of the requested functions have already standard+*trampolineattached.+*/+for(i=0;i<ids_cnt;i++){+tr=lookup_trampoline(prog,ids[i]);+if(!tr)+continue;+if(tr->multi.tr){+multi=ERR_PTR(-EBUSY);+gotoout;+}+tr_cnt++;+}++/* Create new multi trampoline ... */+size=sizeof(*multi)+tr_cnt*sizeof(multi->tr[0]);+multi=kzalloc(size,GFP_KERNEL);+if(!multi){+multi=ERR_PTR(-ENOMEM);+gotoout;+}++bpf_trampoline_init(&multi->main,0);+multi->tr_cnt=tr_cnt;+multi->ids=ids;+multi->ids_cnt=ids_cnt;+list_add_tail(&multi->list,&trampoline_multi);++for(i=0;i<ids_cnt;i++){+structbpf_attach_target_infotgt_info={};++tr=lookup_trampoline(prog,ids[i]);+if(tr)+continue;++err=bpf_check_attach_target(NULL,prog,NULL,ids[i],&tgt_info);+if(err)+gotoout_free;++err=-EINVAL;+if(!is_ftrace_location((void*)tgt_info.tgt_addr))+gotoout_free;++if(nr_args<tgt_info.fmodel.nr_args)+nr_args=tgt_info.fmodel.nr_args;+}++bpf_func_model_nargs(&multi->main.func.model,nr_args);++/* ... and attach already existing standard trampolines. */+for(i=0,j=0;i<ids_cnt&&j<tr_cnt;i++){+tr=lookup_trampoline(prog,ids[i]);+if(tr){+refcount_inc(&tr->refcnt);+tr->multi.tr=&multi->main;+multi->tr[j++]=tr;+}+}++out_free:+if(err){+list_del(&multi->list);+kfree(multi);+multi=ERR_PTR(err);+}+out:+mutex_unlock(&trampoline_mutex);+returnmulti;+}++voidbpf_trampoline_multi_put(structbpf_trampoline_multi*multi)+{+inti;++if(!multi)+return;++mutex_lock(&trampoline_mutex);+if(!refcount_dec_and_test(&multi->main.refcnt))+gotoout;++if(WARN_ON_ONCE(!hlist_empty(&multi->main.progs_hlist[BPF_TRAMP_FENTRY])))+gotoout;+if(WARN_ON_ONCE(!hlist_empty(&multi->main.progs_hlist[BPF_TRAMP_FEXIT])))+gotoout;++list_del(&multi->list);++for(i=0;i<multi->tr_cnt;i++){+multi->tr[i]->multi.tr=NULL;+__bpf_trampoline_put(multi->tr[i]);+}+kfree(multi->ids);+kfree(multi);+out:+mutex_unlock(&trampoline_mutex);+}+#define NO_START_TIME 1staticu64notracebpf_prog_start_time(void){
From: Jiri Olsa <hidden> Date: 2021-08-26 19:41:19
Adding new multi trampoline link (BPF_LINK_TYPE_TRACING_MULTI)
as an interface to attach program to multiple functions.
The link_create bpf_attr interface already has 'bpf_prog' file
descriptor, that defines the program to be attached. It must be
loaded with BPF_F_MULTI_FUNC flag.
Adding new multi_btf_ids/multi_btf_ids_cnt link_create bpf_attr
fields that provides BTF ids.
The new link gets multi trampoline (via bpf_trampoline_multi_get)
and links the provided program with embedded trampolines and the
'main' trampoline with new multi link/unlink functions:
int bpf_trampoline_multi_link_prog(struct bpf_prog *prog,
struct bpf_trampoline_multi *tr);
int bpf_trampoline_multi_unlink_prog(struct bpf_prog *prog,
struct bpf_trampoline_multi *tr);
If embedded trampoline contains fexit programs, we need to switch
its model to the multi trampoline model (because of the final 'ret'
argument). We keep the count of attached multi func programs for each
trampoline, so we can tell when to switch the model.
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
include/linux/bpf.h | 5 ++
include/uapi/linux/bpf.h | 5 ++
kernel/bpf/core.c | 1 +
kernel/bpf/syscall.c | 120 +++++++++++++++++++++++++++++++++
kernel/bpf/trampoline.c | 87 ++++++++++++++++++++++--
tools/include/uapi/linux/bpf.h | 5 ++
6 files changed, 219 insertions(+), 4 deletions(-)
@@ -892,6 +895,8 @@ struct bpf_prog_aux {booltail_call_reachable;boolmulti_func;structbpf_tramp_nodetramp_node;+structbpf_tramp_node*multi_node;+structmutexmulti_node_mutex;/* BTF_KIND_FUNC_PROTO for valid attach_btf_id */conststructbtf_type*attach_func_proto;/* function name for valid attach_btf_id */
From: Jiri Olsa <hidden> Date: 2021-08-26 19:41:25
When we have multi func program attached, the trampoline
switched to the function model of the multi func program.
This breaks already attached standard programs, for example
when we attach following program:
SEC("fexit/bpf_fentry_test2")
int BPF_PROG(test1, int a, __u64 b, int ret)
the trampoline pushes on stack args 'a' and 'b' and return
value 'ret'.
When following multi func program is attached to bpf_fentry_test2:
SEC("fexit.multi/bpf_fentry_test*")
int BPF_PROG(test2, __u64 a, __u64 b, __u64 c, __u64 d,
__u64 e, __u64 f, int ret)
the trampoline takes this program model and pushes all 6 args
and return value on stack.
But we still have the original 'test1' program attached, that
expects 'ret' value where there's 'c' argument now:
test1(a, b, c)
To fix that we simply overwrite 'c' argument with 'ret' value,
so test1 is called as expected and test2 gets called as:
test2(a, b, ret, d, e, f, ret)
which is ok, because 'c' is not defined for bpf_fentry_test2
anyway.
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
arch/x86/net/bpf_jit_comp.c | 40 ++++++++++++++++++++++++++++++-------
include/linux/bpf.h | 1 +
kernel/bpf/trampoline.c | 1 +
3 files changed, 35 insertions(+), 7 deletions(-)
@@ -1780,9 +1780,14 @@ static int invoke_bpf_prog(const struct btf_func_model *m, u8 **pprog,/* BPF_TRAMP_MODIFY_RETURN trampolines can modify the return*ofthepreviouscallwhichisthenpassedonthestackto*thenextBPFprogram.+*Storethereturnvaluealsotooriginalargs'endincase+*wehavemultifuncprogramsintrampoline.*/-if(mod_ret)+if(mod_ret){emit_stx(&prog,BPF_DW,BPF_REG_FP,BPF_REG_0,-8);+if(args_off)+emit_stx(&prog,BPF_DW,BPF_REG_FP,BPF_REG_0,-args_off);+}/* replace 2 nops with JE insn, since jmp target is known */jmp_insn[0]=X86_JE;
@@ -1853,8 +1858,15 @@ static int invoke_bpf_mod_ret(const struct btf_func_model *m, u8 **pprog,*/emit_mov_imm32(&prog,false,BPF_REG_0,0);emit_stx(&prog,BPF_DW,BPF_REG_FP,BPF_REG_0,-8);++/* Store the return value also to original args' end in case+*wehavemultifuncprogramsintrampoline.+*/+if(args_off)+emit_stx(&prog,BPF_DW,BPF_REG_FP,BPF_REG_0,-args_off);+for(i=0;i<tp->nr_progs;i++){-if(invoke_bpf_prog(m,&prog,tp->progs[i],stack_size,true))+if(invoke_bpf_prog(m,&prog,tp->progs[i],stack_size,true,args_off))return-EINVAL;/* mod_ret prog stored return value into [rbp - 8]. Emit:
@@ -1958,6 +1970,13 @@ int arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *image, void *i(flags&BPF_TRAMP_F_SKIP_FRAME))return-EINVAL;+/* if m->nr_args_orig != 0, then we have multi prog model and+*weneedtoalsostorereturnvalueattheendofstandard+*trampoline'sarguments+*/+if(m->nr_args_orig&&m->nr_args>m->nr_args_orig)+args_off=(m->nr_args-m->nr_args_orig)*8+8;+if(flags&BPF_TRAMP_F_CALL_ORIG)stack_size+=8;/* room for return value of orig_call */
@@ -2036,6 +2055,13 @@ int arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *image, void *i}/* remember return value in a stack for bpf prog to access */emit_stx(&prog,BPF_DW,BPF_REG_FP,BPF_REG_0,-8);++/* store return value also to original args' end in case we have+*multifuncprogramsintrampoline+*/+if(args_off)+emit_stx(&prog,BPF_DW,BPF_REG_FP,BPF_REG_0,-args_off);+im->ip_after_call=prog;memcpy(prog,x86_nops[5],X86_PATCH_SIZE);prog+=X86_PATCH_SIZE;
@@ -563,6 +563,7 @@ struct btf_func_model {u8ret_size;u8nr_args;u8arg_size[MAX_BPF_FUNC_ARGS];+u8nr_args_orig;};/* Restore arguments before returning from trampoline to let original function
From: Jiri Olsa <hidden> Date: 2021-08-26 19:41:28
Adding struct ftrace_ops object to bpf_trampoline_multi
struct and setting it up with all the requested function
addresses.
Adding is_multi_trampoline(tr) hooks to installing functions
to actually install multiple bpf trampoline via ftrace_ops.
I had to add -DCC_USING_FENTRY to several places because
arch/x86/include/asm/ftrace.h would fail the compilation
if it's not defined. Perhaps there's a better way.
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
arch/x86/Makefile | 7 +++++
arch/x86/boot/compressed/Makefile | 4 +++
drivers/firmware/efi/libstub/Makefile | 3 +++
include/linux/bpf.h | 2 ++
kernel/bpf/trampoline.c | 37 +++++++++++++++++++++++++++
5 files changed, 53 insertions(+)
@@ -34,6 +34,9 @@ REALMODE_CFLAGS += -fno-stack-protectorREALMODE_CFLAGS+=$(call__cc-option,$(CC),$(REALMODE_CFLAGS),-Wno-address-of-packed-member)REALMODE_CFLAGS+=$(call__cc-option,$(CC),$(REALMODE_CFLAGS),$(cc_stack_align4))REALMODE_CFLAGS+=$(CLANG_FLAGS)+ifdef CONFIG_DYNAMIC_FTRACE+REALMODE_CFLAGS+=-DCC_USING_FENTRY+endifexportREALMODE_CFLAGS# BITS is used as extension for files which are available in a 32 bit
@@ -54,6 +57,10 @@ KBUILD_CFLAGS += $(call cc-option,-mno-avx,)# Intel CET isn't enabled in the kernelKBUILD_CFLAGS+=$(callcc-option,-fcf-protection=none)+ifdef CONFIG_DYNAMIC_FTRACE+KBUILD_CFLAGS+=-DCC_USING_FENTRY+endif+ifeq ($(CONFIG_X86_32),y)BITS:=32UTS_MACHINE:=i386
@@ -49,6 +49,10 @@ KBUILD_CFLAGS += $(call as-option,-Wa$(comma)-mrelax-relocations=no)KBUILD_CFLAGS+=-include$(srctree)/include/linux/hidden.hKBUILD_CFLAGS+=$(CLANG_FLAGS)+ifdef CONFIG_DYNAMIC_FTRACE+KBUILD_CFLAGS+=-DCC_USING_FENTRY+endif+# sev.c indirectly inludes inat-table.h which is generated during# compilation and stored in $(objtree). Add the directory to the includes so# that the compiler finds it even with out-of-tree builds (make O=/some/path).
@@ -15,6 +15,9 @@ cflags-$(CONFIG_X86) += -m$(BITS) -D__KERNEL__ \$(callcc-disable-warning,gnu)\-fno-asynchronous-unwind-tables\$(CLANG_FLAGS)+ifdef CONFIG_DYNAMIC_FTRACE+cflags-$(CONFIG_X86)+=-DCC_USING_FENTRY+endif# arm64 uses the full KBUILD_CFLAGS so it's necessary to explicitly# disable the stackleak plugin
From: Jiri Olsa <hidden> Date: 2021-08-26 19:41:35
Adding btf__find_by_glob_kind function that returns array of
BTF ids that match given kind and allow/deny patterns.
int btf__find_by_glob_kind(const struct btf *btf, __u32 kind,
const char *allow_pattern,
const char *deny_pattern,
__u32 **__ids);
The __ids array is allocated and needs to be manually freed.
At the moment the supported pattern is '*' at the beginning or
the end of the pattern.
Kindly borrowed from retsnoop.
Suggested-by: Andrii Nakryiko <redacted>
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
tools/lib/bpf/btf.c | 80 +++++++++++++++++++++++++++++++++++++++++++++
tools/lib/bpf/btf.h | 3 ++
2 files changed, 83 insertions(+)
@@ -711,6 +711,86 @@ __s32 btf__find_by_name_kind(const struct btf *btf, const char *type_name,returnlibbpf_err(-ENOENT);}+/* 'borrowed' from retsnoop */+staticboolglob_matches(constchar*glob,constchar*s)+{+intn=strlen(glob);++if(n==1&&glob[0]=='*')+returntrue;++if(glob[0]=='*'&&glob[n-1]=='*'){+constchar*subs;+/* substring match */++/* this is hacky, but we don't want to allocate for no good reason */+((char*)glob)[n-1]='\0';+subs=strstr(s,glob+1);+((char*)glob)[n-1]='*';++returnsubs!=NULL;+}elseif(glob[0]=='*'){+size_tnn=strlen(s);+/* suffix match */++/* too short for a given suffix */+if(nn<n-1)+returnfalse;++returnstrcmp(s+nn-(n-1),glob+1)==0;+}elseif(glob[n-1]=='*'){+/* prefix match */+returnstrncmp(s,glob,n-1)==0;+}else{+/* exact match */+returnstrcmp(glob,s)==0;+}+}++intbtf__find_by_glob_kind(conststructbtf*btf,__u32kind,+constchar*allow_pattern,constchar*deny_pattern,+__u32**__ids)+{+__u32i,nr_types=btf__get_nr_types(btf);+intcnt=0,alloc=0;+__u32*ids=NULL;++for(i=1;i<=nr_types;i++){+conststructbtf_type*t=btf__type_by_id(btf,i);+boolmatch=false;+constchar*name;+__u32*p;++if(btf_kind(t)!=kind)+continue;+name=btf__name_by_offset(btf,t->name_off);+if(!name)+continue;++if(allow_pattern&&glob_matches(allow_pattern,name))+match=true;+if(deny_pattern&&!glob_matches(deny_pattern,name))+match=true;+if(!match)+continue;++if(cnt==alloc){+alloc=max(100,alloc*3/2);+p=realloc(ids,alloc*sizeof(__u32));+if(!p){+free(ids);+return-ENOMEM;+}+ids=p;+}+ids[cnt]=i;+cnt++;+}++*__ids=ids;+returncnt?:-ENOENT;+}+staticboolbtf_is_modifiable(conststructbtf*btf){return(void*)btf->hdr!=btf->raw_data;
From: Jiri Olsa <hidden> Date: 2021-08-26 19:41:40
Adding support to link multi func tracing program
through link_create interface.
Adding special types for multi func programs:
fentry.multi
fexit.multi
so you can define multi func programs like:
SEC("fentry.multi/bpf_fentry_test*")
int BPF_PROG(test1, __u64 a, __u64 b, __u64 c, __u64 d, __u64 e, __u64 f)
that defines test1 to be attached to bpf_fentry_test* functions.
The test1 program is loaded with BPF_F_MULTI_FUNC flag.
If functions are not specified the program needs to be attached
manually.
Adding new btf_ids/btf_ids_cnt fields to bpf_link_create_opts,
that define functions to attach the program to.
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
tools/lib/bpf/bpf.c | 8 +++++
tools/lib/bpf/bpf.h | 6 +++-
tools/lib/bpf/libbpf.c | 72 ++++++++++++++++++++++++++++++++++++++++++
3 files changed, 85 insertions(+), 1 deletion(-)
@@ -713,12 +713,20 @@ int bpf_link_create(int prog_fd, int target_fd,if(!OPTS_ZEROED(opts,perf_event))returnlibbpf_err(-EINVAL);break;+caseBPF_TRACE_FENTRY:+caseBPF_TRACE_FEXIT:+attr.link_create.multi_btf_ids=(__u64)OPTS_GET(opts,multi.btf_ids,0);+attr.link_create.multi_btf_ids_cnt=OPTS_GET(opts,multi.btf_ids_cnt,0);+if(!OPTS_ZEROED(opts,multi))+returnlibbpf_err(-EINVAL);+break;default:if(!OPTS_ZEROED(opts,flags))returnlibbpf_err(-EINVAL);break;}proceed:+fd=sys_bpf(BPF_LINK_CREATE,&attr,sizeof(attr));returnlibbpf_err_errno(fd);}
From: Jiri Olsa <hidden> Date: 2021-08-26 19:41:45
Adding selftest for fentry multi func test that attaches
to bpf_fentry_test* functions and checks argument values
based on the processed function.
We need to cast to real arguments types in multi_arg_check,
because the checked value can be shorter than u64.
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
tools/testing/selftests/bpf/Makefile | 4 +-
.../bpf/prog_tests/multi_fentry_test.c | 30 +++++++++
.../testing/selftests/bpf/progs/multi_check.c | 63 +++++++++++++++++++
.../selftests/bpf/progs/multi_fentry.c | 17 +++++
4 files changed, 113 insertions(+), 1 deletion(-)
create mode 100644 tools/testing/selftests/bpf/prog_tests/multi_fentry_test.c
create mode 100644 tools/testing/selftests/bpf/progs/multi_check.c
create mode 100644 tools/testing/selftests/bpf/progs/multi_fentry.c
From: Jiri Olsa <hidden> Date: 2021-08-26 19:42:10
Adding selftest to check attaching rules for multi func programs.
- attach 2 programs:
fentry/bpf_fentry_test1
fexit/bpf_fentry_test2
- check that we can attach multi func program on top of them:
fentry.multi/bpf_fentry_test*
- check that we cannot attach another multi funct program
that does not cover the same BTF ids (one less):
fentry.multi/bpf_fentry_test[1-7]
fexit.multi/bpf_fentry_test[1-7]
- check that we can no longer attach standard trampoline
programs (below) on top of attached multi func program:
fentry/bpf_fentry_test1
fexit/bpf_fentry_test3
Because the supported wildcards do not allow us to
match just limited set of bpf_fentry_test*, adding
extra code to look it up in kernel's BTF.
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
.../bpf/prog_tests/multi_attach_check_test.c | 115 ++++++++++++++++++
.../selftests/bpf/progs/multi_attach_check.c | 36 ++++++
.../bpf/progs/multi_attach_check_extra1.c | 12 ++
.../bpf/progs/multi_attach_check_extra2.c | 12 ++
4 files changed, 175 insertions(+)
create mode 100644 tools/testing/selftests/bpf/prog_tests/multi_attach_check_test.c
create mode 100644 tools/testing/selftests/bpf/progs/multi_attach_check.c
create mode 100644 tools/testing/selftests/bpf/progs/multi_attach_check_extra1.c
create mode 100644 tools/testing/selftests/bpf/progs/multi_attach_check_extra2.c
@@ -0,0 +1,115 @@+// SPDX-License-Identifier: GPL-2.0+#include<test_progs.h>+#include<linux/btf_ids.h>+#include"multi_attach_check.skel.h"+#include"multi_attach_check_extra1.skel.h"+#include"multi_attach_check_extra2.skel.h"+#include<bpf/btf.h>++static__u32btf_ids[7];++staticintload_btf_ids(void)+{+__u32i,nr_types,cnt;+structbtf*btf;++btf=btf__load_vmlinux_btf();+if(!ASSERT_OK_PTR(btf,"btf__load_vmlinux_btf"))+return-1;++nr_types=btf__get_nr_types(btf);++for(i=1,cnt=0;i<=nr_types&&cnt<7;i++){+conststructbtf_type*t=btf__type_by_id(btf,i);+constchar*name;++if(!btf_is_func(t))+continue;++name=btf__name_by_offset(btf,t->name_off);+if(!name)+continue;+if(strncmp(name,"bpf_fentry_test",sizeof("bpf_fentry_test")-1))+continue;++btf_ids[cnt]=i;+cnt++;+}++btf__free(btf);+returnASSERT_EQ(cnt,7,"bpf_fentry_test_cnt")?0:-1;+}++voidtest_multi_attach_check_test(void)+{+structbpf_link*link1=NULL,*link2=NULL,*link3=NULL;+DECLARE_LIBBPF_OPTS(bpf_link_create_opts,opts);+structmulti_attach_check_extra1*skel_extra1=NULL;+structmulti_attach_check_extra2*skel_extra2=NULL;+structmulti_attach_check*skel;+intlink_fd,prog_fd;++/* Load/attach standard trampolines and on top of it multi+*funcprogram.Itshouldsucceed.+*/+skel=multi_attach_check__open_and_load();+if(!ASSERT_OK_PTR(skel,"multi_attach_check__load"))+return;++link1=bpf_program__attach(skel->progs.test1);+if(!ASSERT_OK_PTR(link1,"multi_attach_check__test1_attach"))+gotocleanup;++link2=bpf_program__attach(skel->progs.test2);+if(!ASSERT_OK_PTR(link2,"multi_attach_check__test2_attach"))+gotocleanup;++link3=bpf_program__attach(skel->progs.test3);+if(!ASSERT_OK_PTR(link3,"multi_attach_check__test3_attach"))+gotocleanup;++if(!ASSERT_OK(load_btf_ids(),"load_btf_ids"))+gotocleanup;++/* There's 8 bpf_fentry_test* functions, get BTF ids for 7 of them+*andtrytoload/linkmultifuncprogramwiththem.Itshouldfail+*bothforfentry.multi...+*/+opts.multi.btf_ids=btf_ids;+opts.multi.btf_ids_cnt=7;++prog_fd=bpf_program__fd(skel->progs.test4);++link_fd=bpf_link_create(prog_fd,0,BPF_TRACE_FENTRY,&opts);+if(!ASSERT_LT(link_fd,0,"bpf_link_create"))+gotocleanup;++close(link_fd);++/* ... and fexit.multi */+prog_fd=bpf_program__fd(skel->progs.test5);++link_fd=bpf_link_create(prog_fd,0,BPF_TRACE_FEXIT,&opts);+if(!ASSERT_LT(link_fd,0,"bpf_link_create"))+gotocleanup;++close(link_fd);++/* Try to load/attach extra programs on top of multi func programs,+*itshouldfailforbothfentry...+*/+skel_extra1=multi_attach_check_extra1__open_and_load();+if(!ASSERT_ERR_PTR(skel_extra1,"multi_attach_check_extra1__load"))+multi_attach_check_extra1__destroy(skel_extra1);++/* ... and fexit */+skel_extra2=multi_attach_check_extra2__open_and_load();+if(!ASSERT_ERR_PTR(skel_extra2,"multi_attach_check_extra2__load"))+multi_attach_check_extra2__destroy(skel_extra2);++cleanup:+bpf_link__destroy(link1);+bpf_link__destroy(link2);+bpf_link__destroy(link3);+multi_attach_check__destroy(skel);+}
From: Jiri Olsa <hidden> Date: 2021-08-26 19:42:17
Adding extra test to existing modify_return test to
test this with multi func program attached on top
of the modify return program.
Because the supported wildcards do not allow us to
match both bpf_fentry_test* and bpf_modify_return_test,
adding extra code to look it up in kernel's BTF.
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
.../selftests/bpf/prog_tests/modify_return.c | 114 +++++++++++++++++-
.../selftests/bpf/progs/multi_modify_return.c | 17 +++
2 files changed, 128 insertions(+), 3 deletions(-)
create mode 100644 tools/testing/selftests/bpf/progs/multi_modify_return.c
On Thu, Aug 26, 2021 at 09:38:55PM +0200, Jiri Olsa wrote:
hi,
sending new version of batch attach support, previous post
is in here [1].
The previous post could not assign multi trampoline on top
of regular trampolines. This patchset is trying to address
that, plus it has other fixes from last post.
This patchset contains:
1) patches (1-4) that fix the ftrace graph tracing over the function
with direct trampolines attached
2) patches (5-8) that add batch interface for ftrace direct function
register/unregister/modify
3) patches (9-27) that add support to attach BPF program to multiple
functions
I did a quick look and it looks ok, but probably will require another respin.
In the mean would be great to land the first 8 patches for the upcoming merge
window.
Jiri,
can you respin them quickly addressing build bot issues and maybe
Steven can apply them into his tracing tree for the merge window?
Then during the next release cycle we will only iterate on bpf bits in the
later patches.
Thoughts?
From: Jiri Olsa <hidden> Date: 2021-08-30 08:02:54
On Sun, Aug 29, 2021 at 10:04:25AM -0700, Alexei Starovoitov wrote:
On Thu, Aug 26, 2021 at 09:38:55PM +0200, Jiri Olsa wrote:
quoted
hi,
sending new version of batch attach support, previous post
is in here [1].
The previous post could not assign multi trampoline on top
of regular trampolines. This patchset is trying to address
that, plus it has other fixes from last post.
This patchset contains:
1) patches (1-4) that fix the ftrace graph tracing over the function
with direct trampolines attached
2) patches (5-8) that add batch interface for ftrace direct function
register/unregister/modify
3) patches (9-27) that add support to attach BPF program to multiple
functions
I did a quick look and it looks ok, but probably will require another respin.
In the mean would be great to land the first 8 patches for the upcoming merge
window.
Jiri,
can you respin them quickly addressing build bot issues and maybe
Steven can apply them into his tracing tree for the merge window?
Then during the next release cycle we will only iterate on bpf bits in the
later patches.
Thoughts?
On Thu, Aug 26, 2021 at 12:40 PM Jiri Olsa [off-list ref] wrote:
Adding support to load tracing program with new BPF_F_MULTI_FUNC flag,
that allows the program to be loaded without specific function to be
attached to.
Are there any benefits to using a new load flag vs having separate
expected attach types like FENTRY_MULTI/FEXIT_MULTI? I find load flags
a bigger pain to work with compared to expected attach type (and
expected attach type should be more apparent in BPF link info, bpftool
output, etc).
Such program will be allowed to be attached to multiple functions
in following patches.
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
include/linux/bpf.h | 1 +
include/uapi/linux/bpf.h | 7 +++++++
kernel/bpf/syscall.c | 35 +++++++++++++++++++++++++++++-----
kernel/bpf/verifier.c | 3 ++-
tools/include/uapi/linux/bpf.h | 7 +++++++
5 files changed, 47 insertions(+), 6 deletions(-)
On Thu, Aug 26, 2021 at 12:41 PM Jiri Olsa [off-list ref] wrote:
Adding new multi trampoline link (BPF_LINK_TYPE_TRACING_MULTI)
as an interface to attach program to multiple functions.
The link_create bpf_attr interface already has 'bpf_prog' file
descriptor, that defines the program to be attached. It must be
loaded with BPF_F_MULTI_FUNC flag.
Adding new multi_btf_ids/multi_btf_ids_cnt link_create bpf_attr
fields that provides BTF ids.
The new link gets multi trampoline (via bpf_trampoline_multi_get)
and links the provided program with embedded trampolines and the
'main' trampoline with new multi link/unlink functions:
int bpf_trampoline_multi_link_prog(struct bpf_prog *prog,
struct bpf_trampoline_multi *tr);
int bpf_trampoline_multi_unlink_prog(struct bpf_prog *prog,
struct bpf_trampoline_multi *tr);
If embedded trampoline contains fexit programs, we need to switch
its model to the multi trampoline model (because of the final 'ret'
argument). We keep the count of attached multi func programs for each
trampoline, so we can tell when to switch the model.
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
include/linux/bpf.h | 5 ++
include/uapi/linux/bpf.h | 5 ++
kernel/bpf/core.c | 1 +
kernel/bpf/syscall.c | 120 +++++++++++++++++++++++++++++++++
kernel/bpf/trampoline.c | 87 ++++++++++++++++++++++--
tools/include/uapi/linux/bpf.h | 5 ++
6 files changed, 219 insertions(+), 4 deletions(-)
On Thu, Aug 26, 2021 at 12:41 PM Jiri Olsa [off-list ref] wrote:
When we have multi func program attached, the trampoline
switched to the function model of the multi func program.
This breaks already attached standard programs, for example
when we attach following program:
SEC("fexit/bpf_fentry_test2")
int BPF_PROG(test1, int a, __u64 b, int ret)
the trampoline pushes on stack args 'a' and 'b' and return
value 'ret'.
When following multi func program is attached to bpf_fentry_test2:
SEC("fexit.multi/bpf_fentry_test*")
int BPF_PROG(test2, __u64 a, __u64 b, __u64 c, __u64 d,
__u64 e, __u64 f, int ret)
the trampoline takes this program model and pushes all 6 args
and return value on stack.
But we still have the original 'test1' program attached, that
expects 'ret' value where there's 'c' argument now:
test1(a, b, c)
To fix that we simply overwrite 'c' argument with 'ret' value,
so test1 is called as expected and test2 gets called as:
test2(a, b, ret, d, e, f, ret)
which is ok, because 'c' is not defined for bpf_fentry_test2
anyway.
What if we change the order on the stack to be the return value first,
followed by input arguments. That would get us a bit closer to
unifying multi-trampoline and the normal one, right? BPF verifier
should be able to rewrite access to the last argument (i.e., return
value) for fexit programs to actually be at offset 0, and shift all
other arguments by 8 bytes. For fentry, if that helps to keep things
more aligned, we'd just skip the first 8 bytes on the stack and store
all the input arguments in the same offsets. So BPF verifier rewriting
logic stays consistent (except offset 0 will be disallowed).
Basically, I'm thinking how we can make normal and multi trampolines
more interoperable to remove those limitations that two
multi-trampolines can't be attached to the same function, which seems
like a pretty annoying limitation which will be easy to hit in
practice. Alexei previously proposed (as an optimization) to group all
to-be-attached functions into groups by number of arguments, so that
we can have up to 6 different trampolines tailored to actual functions
being attached. So that we don't save unnecessary extra input
arguments saving, which will be even more important once we allow more
than 6 arguments in the future.
With such logic, we should be able to split all the functions into
multiple underlying trampolines, so it seems like it should be
possible to also allow multiple multi-fentry programs to be attached
to the same function by having a separate bpf_trampoline just for
those functions. It will be just an extension of the above "just 6
trampolines" strategy to "as much as we need trampolines".
It's just a vague idea, sorry, I don't understand all the code yet.
But the limitation outlined in one of the previous patches seems very
limiting and unpleasant. I can totally see that some 24/7 running BPF
tracing app uses multi-fentry for tracing a small subset of kernel
functions non-stop, and then someone is trying to use bpftrace or
retsnoop to trace overlapping set of functions. And it immediately
fails. Very frustrating.
On Tue, Aug 31, 2021 at 4:36 PM Andrii Nakryiko
[off-list ref] wrote:
On Thu, Aug 26, 2021 at 12:41 PM Jiri Olsa [off-list ref] wrote:
quoted
Adding new multi trampoline link (BPF_LINK_TYPE_TRACING_MULTI)
as an interface to attach program to multiple functions.
The link_create bpf_attr interface already has 'bpf_prog' file
descriptor, that defines the program to be attached. It must be
loaded with BPF_F_MULTI_FUNC flag.
Adding new multi_btf_ids/multi_btf_ids_cnt link_create bpf_attr
fields that provides BTF ids.
The new link gets multi trampoline (via bpf_trampoline_multi_get)
and links the provided program with embedded trampolines and the
'main' trampoline with new multi link/unlink functions:
int bpf_trampoline_multi_link_prog(struct bpf_prog *prog,
struct bpf_trampoline_multi *tr);
int bpf_trampoline_multi_unlink_prog(struct bpf_prog *prog,
struct bpf_trampoline_multi *tr);
If embedded trampoline contains fexit programs, we need to switch
its model to the multi trampoline model (because of the final 'ret'
argument). We keep the count of attached multi func programs for each
trampoline, so we can tell when to switch the model.
Related to my comments on the next patch, if we switch the order of
return value and always reserve 6 slots for input args, regardless of
the actual number of function input args, that should make this
upgrade logic unnecessary, right?
On Thu, Aug 26, 2021 at 12:41 PM Jiri Olsa [off-list ref] wrote:
quoted hunk
Adding btf__find_by_glob_kind function that returns array of
BTF ids that match given kind and allow/deny patterns.
int btf__find_by_glob_kind(const struct btf *btf, __u32 kind,
const char *allow_pattern,
const char *deny_pattern,
__u32 **__ids);
The __ids array is allocated and needs to be manually freed.
At the moment the supported pattern is '*' at the beginning or
the end of the pattern.
Kindly borrowed from retsnoop.
Suggested-by: Andrii Nakryiko <redacted>
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
tools/lib/bpf/btf.c | 80 +++++++++++++++++++++++++++++++++++++++++++++
tools/lib/bpf/btf.h | 3 ++
2 files changed, 83 insertions(+)
@@ -711,6 +711,86 @@ __s32 btf__find_by_name_kind(const struct btf *btf, const char *type_name,returnlibbpf_err(-ENOENT);}+/* 'borrowed' from retsnoop */+staticboolglob_matches(constchar*glob,constchar*s)+{+intn=strlen(glob);++if(n==1&&glob[0]=='*')+returntrue;++if(glob[0]=='*'&&glob[n-1]=='*'){+constchar*subs;+/* substring match */++/* this is hacky, but we don't want to allocate for no good reason */+((char*)glob)[n-1]='\0';+subs=strstr(s,glob+1);+((char*)glob)[n-1]='*';++returnsubs!=NULL;+}elseif(glob[0]=='*'){+size_tnn=strlen(s);+/* suffix match */++/* too short for a given suffix */+if(nn<n-1)+returnfalse;++returnstrcmp(s+nn-(n-1),glob+1)==0;+}elseif(glob[n-1]=='*'){+/* prefix match */+returnstrncmp(s,glob,n-1)==0;+}else{+/* exact match */+returnstrcmp(glob,s)==0;+}+}++intbtf__find_by_glob_kind(conststructbtf*btf,__u32kind,+constchar*allow_pattern,constchar*deny_pattern,+__u32**__ids)+{+__u32i,nr_types=btf__get_nr_types(btf);+intcnt=0,alloc=0;+__u32*ids=NULL;++for(i=1;i<=nr_types;i++){+conststructbtf_type*t=btf__type_by_id(btf,i);+boolmatch=false;+constchar*name;+__u32*p;++if(btf_kind(t)!=kind)+continue;+name=btf__name_by_offset(btf,t->name_off);+if(!name)+continue;++if(allow_pattern&&glob_matches(allow_pattern,name))+match=true;+if(deny_pattern&&!glob_matches(deny_pattern,name))+match=true;
this is wrong, if it matches both deny and allow patterns, you'll
still pass it through. Drop the match flag, just check deny first and
`continue` if matches.
From: Jiri Olsa <hidden> Date: 2021-09-01 11:32:51
On Tue, Aug 31, 2021 at 04:17:33PM -0700, Andrii Nakryiko wrote:
On Thu, Aug 26, 2021 at 12:40 PM Jiri Olsa [off-list ref] wrote:
quoted
Adding support to load tracing program with new BPF_F_MULTI_FUNC flag,
that allows the program to be loaded without specific function to be
attached to.
Are there any benefits to using a new load flag vs having separate
expected attach types like FENTRY_MULTI/FEXIT_MULTI? I find load flags
a bigger pain to work with compared to expected attach type (and
expected attach type should be more apparent in BPF link info, bpftool
output, etc).
it means more of the additional code, with the flag we just reuse
BPF_TRACE_FENTRY/BPF_TRACE_FEXIT related code because we use
current trampoline paths
I recall trying that approach while back, but ended up with bigger
changes that seemed unnecessary, I can dig it up to get more
details
jirka
quoted
Such program will be allowed to be attached to multiple functions
in following patches.
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
include/linux/bpf.h | 1 +
include/uapi/linux/bpf.h | 7 +++++++
kernel/bpf/syscall.c | 35 +++++++++++++++++++++++++++++-----
kernel/bpf/verifier.c | 3 ++-
tools/include/uapi/linux/bpf.h | 7 +++++++
5 files changed, 47 insertions(+), 6 deletions(-)
From: Jiri Olsa <hidden> Date: 2021-09-01 11:33:42
On Tue, Aug 31, 2021 at 05:10:52PM -0700, Andrii Nakryiko wrote:
On Thu, Aug 26, 2021 at 12:41 PM Jiri Olsa [off-list ref] wrote:
quoted
Adding btf__find_by_glob_kind function that returns array of
BTF ids that match given kind and allow/deny patterns.
int btf__find_by_glob_kind(const struct btf *btf, __u32 kind,
const char *allow_pattern,
const char *deny_pattern,
__u32 **__ids);
The __ids array is allocated and needs to be manually freed.
At the moment the supported pattern is '*' at the beginning or
the end of the pattern.
Kindly borrowed from retsnoop.
Suggested-by: Andrii Nakryiko <redacted>
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
tools/lib/bpf/btf.c | 80 +++++++++++++++++++++++++++++++++++++++++++++
tools/lib/bpf/btf.h | 3 ++
2 files changed, 83 insertions(+)
@@ -711,6 +711,86 @@ __s32 btf__find_by_name_kind(const struct btf *btf, const char *type_name,returnlibbpf_err(-ENOENT);}+/* 'borrowed' from retsnoop */+staticboolglob_matches(constchar*glob,constchar*s)+{+intn=strlen(glob);++if(n==1&&glob[0]=='*')+returntrue;++if(glob[0]=='*'&&glob[n-1]=='*'){+constchar*subs;+/* substring match */++/* this is hacky, but we don't want to allocate for no good reason */+((char*)glob)[n-1]='\0';+subs=strstr(s,glob+1);+((char*)glob)[n-1]='*';++returnsubs!=NULL;+}elseif(glob[0]=='*'){+size_tnn=strlen(s);+/* suffix match */++/* too short for a given suffix */+if(nn<n-1)+returnfalse;++returnstrcmp(s+nn-(n-1),glob+1)==0;+}elseif(glob[n-1]=='*'){+/* prefix match */+returnstrncmp(s,glob,n-1)==0;+}else{+/* exact match */+returnstrcmp(glob,s)==0;+}+}++intbtf__find_by_glob_kind(conststructbtf*btf,__u32kind,+constchar*allow_pattern,constchar*deny_pattern,+__u32**__ids)+{+__u32i,nr_types=btf__get_nr_types(btf);+intcnt=0,alloc=0;+__u32*ids=NULL;++for(i=1;i<=nr_types;i++){+conststructbtf_type*t=btf__type_by_id(btf,i);+boolmatch=false;+constchar*name;+__u32*p;++if(btf_kind(t)!=kind)+continue;+name=btf__name_by_offset(btf,t->name_off);+if(!name)+continue;++if(allow_pattern&&glob_matches(allow_pattern,name))+match=true;+if(deny_pattern&&!glob_matches(deny_pattern,name))+match=true;
this is wrong, if it matches both deny and allow patterns, you'll
still pass it through. Drop the match flag, just check deny first and
`continue` if matches.
From: Jiri Olsa <hidden> Date: 2021-09-01 11:39:47
On Tue, Aug 31, 2021 at 04:36:22PM -0700, Andrii Nakryiko wrote:
On Thu, Aug 26, 2021 at 12:41 PM Jiri Olsa [off-list ref] wrote:
quoted
Adding new multi trampoline link (BPF_LINK_TYPE_TRACING_MULTI)
as an interface to attach program to multiple functions.
The link_create bpf_attr interface already has 'bpf_prog' file
descriptor, that defines the program to be attached. It must be
loaded with BPF_F_MULTI_FUNC flag.
Adding new multi_btf_ids/multi_btf_ids_cnt link_create bpf_attr
fields that provides BTF ids.
The new link gets multi trampoline (via bpf_trampoline_multi_get)
and links the provided program with embedded trampolines and the
'main' trampoline with new multi link/unlink functions:
int bpf_trampoline_multi_link_prog(struct bpf_prog *prog,
struct bpf_trampoline_multi *tr);
int bpf_trampoline_multi_unlink_prog(struct bpf_prog *prog,
struct bpf_trampoline_multi *tr);
If embedded trampoline contains fexit programs, we need to switch
its model to the multi trampoline model (because of the final 'ret'
argument). We keep the count of attached multi func programs for each
trampoline, so we can tell when to switch the model.
Signed-off-by: Jiri Olsa <jolsa@kernel.org>
---
include/linux/bpf.h | 5 ++
include/uapi/linux/bpf.h | 5 ++
kernel/bpf/core.c | 1 +
kernel/bpf/syscall.c | 120 +++++++++++++++++++++++++++++++++
kernel/bpf/trampoline.c | 87 ++++++++++++++++++++++--
tools/include/uapi/linux/bpf.h | 5 ++
6 files changed, 219 insertions(+), 4 deletions(-)
From: Jiri Olsa <hidden> Date: 2021-09-01 15:15:24
On Tue, Aug 31, 2021 at 04:51:18PM -0700, Andrii Nakryiko wrote:
On Thu, Aug 26, 2021 at 12:41 PM Jiri Olsa [off-list ref] wrote:
quoted
When we have multi func program attached, the trampoline
switched to the function model of the multi func program.
This breaks already attached standard programs, for example
when we attach following program:
SEC("fexit/bpf_fentry_test2")
int BPF_PROG(test1, int a, __u64 b, int ret)
the trampoline pushes on stack args 'a' and 'b' and return
value 'ret'.
When following multi func program is attached to bpf_fentry_test2:
SEC("fexit.multi/bpf_fentry_test*")
int BPF_PROG(test2, __u64 a, __u64 b, __u64 c, __u64 d,
__u64 e, __u64 f, int ret)
the trampoline takes this program model and pushes all 6 args
and return value on stack.
But we still have the original 'test1' program attached, that
expects 'ret' value where there's 'c' argument now:
test1(a, b, c)
To fix that we simply overwrite 'c' argument with 'ret' value,
so test1 is called as expected and test2 gets called as:
test2(a, b, ret, d, e, f, ret)
which is ok, because 'c' is not defined for bpf_fentry_test2
anyway.
What if we change the order on the stack to be the return value first,
followed by input arguments. That would get us a bit closer to
unifying multi-trampoline and the normal one, right? BPF verifier
should be able to rewrite access to the last argument (i.e., return
value) for fexit programs to actually be at offset 0, and shift all
other arguments by 8 bytes. For fentry, if that helps to keep things
more aligned, we'd just skip the first 8 bytes on the stack and store
all the input arguments in the same offsets. So BPF verifier rewriting
logic stays consistent (except offset 0 will be disallowed).
nice idea, with this in place we could cut that args re-arranging code
Basically, I'm thinking how we can make normal and multi trampolines
more interoperable to remove those limitations that two
multi-trampolines can't be attached to the same function, which seems
like a pretty annoying limitation which will be easy to hit in
practice. Alexei previously proposed (as an optimization) to group all
to-be-attached functions into groups by number of arguments, so that
we can have up to 6 different trampolines tailored to actual functions
being attached. So that we don't save unnecessary extra input
arguments saving, which will be even more important once we allow more
than 6 arguments in the future.
With such logic, we should be able to split all the functions into
multiple underlying trampolines, so it seems like it should be
possible to also allow multiple multi-fentry programs to be attached
to the same function by having a separate bpf_trampoline just for
those functions. It will be just an extension of the above "just 6
trampolines" strategy to "as much as we need trampolines".
I'm probably missing something here.. say we have 2 functions with single
argument:
foo1(int a)
foo2(int b)
then having 2 programs:
A - attaching to foo1
B - attaching to foo2
then you need to have 2 different trampolines instead of single 'generic-1-argument-trampoline'
It's just a vague idea, sorry, I don't understand all the code yet.
But the limitation outlined in one of the previous patches seems very
limiting and unpleasant. I can totally see that some 24/7 running BPF
tracing app uses multi-fentry for tracing a small subset of kernel
functions non-stop, and then someone is trying to use bpftrace or
retsnoop to trace overlapping set of functions. And it immediately
fails. Very frustrating.
so the current approach is to some extent driven by the direct ftrace
batch API:
you have ftrace_ops object and set it up with functions you want
to change with calling:
ftrace_set_filter_ip(ops, ip1);
ftrace_set_filter_ip(ops, ip2);
...
and then register trampoline with those functions:
register_ftrace_direct_multi(ops, tramp_addr);
and with this call being the expensive one (it does the actual work
and sync waiting), my objective was to call it just once for update
now with 2 intersecting multi trampolines we end up with 3 functions
sets:
A - functions for first multi trampoline
B - functions for second multi trampoline
C - intersection of them
each set needs different trampoline:
tramp A - calls program for first multi trampoline
tramp B - calls program for second multi trampoline
tramp C - calls both programs
so we need to call register_ftrace_direct_multi 3 times
if we allow also standard trampolines being attached, it makes
it even more complicated and ultimatelly gets broken to
1-function/1-trampoline pairs, ending up with attach speed
that we have now
...
I have test code for ftrace direct interface that would
allow to register/change separate function/addr pairs,
so in one call you can change multiple ips each to
different tramp addresss
but even with that, I ended up with lot of new complexity
on bpf side keeping track of multi trampolines intersections,
so I thought I'd start with something limited and simpler
perhaps I should move back to that approach and see how bad
it ends ;-)
or this could be next step on top of current work, that should
get simpler with the args re-arranging you proposed
jirka
On Wed, Sep 1, 2021 at 8:15 AM Jiri Olsa [off-list ref] wrote:
On Tue, Aug 31, 2021 at 04:51:18PM -0700, Andrii Nakryiko wrote:
quoted
On Thu, Aug 26, 2021 at 12:41 PM Jiri Olsa [off-list ref] wrote:
quoted
When we have multi func program attached, the trampoline
switched to the function model of the multi func program.
This breaks already attached standard programs, for example
when we attach following program:
SEC("fexit/bpf_fentry_test2")
int BPF_PROG(test1, int a, __u64 b, int ret)
the trampoline pushes on stack args 'a' and 'b' and return
value 'ret'.
When following multi func program is attached to bpf_fentry_test2:
SEC("fexit.multi/bpf_fentry_test*")
int BPF_PROG(test2, __u64 a, __u64 b, __u64 c, __u64 d,
__u64 e, __u64 f, int ret)
the trampoline takes this program model and pushes all 6 args
and return value on stack.
But we still have the original 'test1' program attached, that
expects 'ret' value where there's 'c' argument now:
test1(a, b, c)
To fix that we simply overwrite 'c' argument with 'ret' value,
so test1 is called as expected and test2 gets called as:
test2(a, b, ret, d, e, f, ret)
which is ok, because 'c' is not defined for bpf_fentry_test2
anyway.
What if we change the order on the stack to be the return value first,
followed by input arguments. That would get us a bit closer to
unifying multi-trampoline and the normal one, right? BPF verifier
should be able to rewrite access to the last argument (i.e., return
value) for fexit programs to actually be at offset 0, and shift all
other arguments by 8 bytes. For fentry, if that helps to keep things
more aligned, we'd just skip the first 8 bytes on the stack and store
all the input arguments in the same offsets. So BPF verifier rewriting
logic stays consistent (except offset 0 will be disallowed).
nice idea, with this in place we could cut that args re-arranging code
quoted
Basically, I'm thinking how we can make normal and multi trampolines
more interoperable to remove those limitations that two
multi-trampolines can't be attached to the same function, which seems
like a pretty annoying limitation which will be easy to hit in
practice. Alexei previously proposed (as an optimization) to group all
to-be-attached functions into groups by number of arguments, so that
we can have up to 6 different trampolines tailored to actual functions
being attached. So that we don't save unnecessary extra input
arguments saving, which will be even more important once we allow more
than 6 arguments in the future.
With such logic, we should be able to split all the functions into
multiple underlying trampolines, so it seems like it should be
possible to also allow multiple multi-fentry programs to be attached
to the same function by having a separate bpf_trampoline just for
those functions. It will be just an extension of the above "just 6
trampolines" strategy to "as much as we need trampolines".
I'm probably missing something here.. say we have 2 functions with single
argument:
foo1(int a)
foo2(int b)
then having 2 programs:
A - attaching to foo1
B - attaching to foo2
then you need to have 2 different trampolines instead of single 'generic-1-argument-trampoline'
right, you have two different BPF progs attached to two different
functions. You have to have 2 trampolines, not sure what's
confusing?..
quoted
It's just a vague idea, sorry, I don't understand all the code yet.
But the limitation outlined in one of the previous patches seems very
limiting and unpleasant. I can totally see that some 24/7 running BPF
tracing app uses multi-fentry for tracing a small subset of kernel
functions non-stop, and then someone is trying to use bpftrace or
retsnoop to trace overlapping set of functions. And it immediately
fails. Very frustrating.
so the current approach is to some extent driven by the direct ftrace
batch API:
you have ftrace_ops object and set it up with functions you want
to change with calling:
ftrace_set_filter_ip(ops, ip1);
ftrace_set_filter_ip(ops, ip2);
...
and then register trampoline with those functions:
register_ftrace_direct_multi(ops, tramp_addr);
and with this call being the expensive one (it does the actual work
and sync waiting), my objective was to call it just once for update
now with 2 intersecting multi trampolines we end up with 3 functions
sets:
A - functions for first multi trampoline
B - functions for second multi trampoline
C - intersection of them
each set needs different trampoline:
tramp A - calls program for first multi trampoline
tramp B - calls program for second multi trampoline
tramp C - calls both programs
so we need to call register_ftrace_direct_multi 3 times
Yes, that's the minimal amount of trampolines you need. Calling
register_ftrace_direct_multi() three times is not that bad at all,
compared to calling it 1000s of times. If you are worried about 1 vs 3
calls, I think you are over-optimizing here. I'd rather take no
restrictions on what can be attached to what and in which sequences
but taking 3ms vs having obscure (for uninitiated users) restrictions,
but in some cases allowing attachment to happen in 1ms.
The goal with multi-attach is to make it decently fast when attaching
to a lot functions, but if attachment speed is fast enough, then such
small performance differences don't matter anymore.
if we allow also standard trampolines being attached, it makes
it even more complicated and ultimatelly gets broken to
1-function/1-trampoline pairs, ending up with attach speed
that we have now
So let's make sure that we are on the same page. Let me write out an example.
Let's say we have 5 kernel functions: a, b, c, d, e. Say a, b, c all
have 1 input args, and d and e have 2.
Now let's say we attach just normal fentry program A to function a.
Also we attach normal fexit program E to func e.
We'll have A attached to a with trampoline T1. We'll also have E
attached to e with trampoline T2. Right?
And now we try to attach generic fentry (fentry.multi in your
terminology) prog X to all 5 of them. If A and E weren't attached,
we'd need two generic trampolines, one for a, b, c (because 1 input
argument) and another for d,e (because 2 input arguments). But because
we already have A and B attached, we'll end up needing 4:
T1 (1 arg) for func a calling progs A and X
T2 (2 args) for func e calling progs E and X
T3 (1 arg) for func b and c calling X
T4 (2 args) for func d calling X
We can't have less than that and satisfy all the constraints. But 4 is
not that bad. If the example has 1000s of functions, you'd still need
between 4 and 8 trampolines (if we had 3, 4, 5, and 6 input args for
kernel functions). That's way less than 1000s of trampolines needed
today. And it's still fast enough on the attachment.
The good thing with what we discussed with making current trampoline
co-exist with generic (multi) fentry/fexit, is that we'll still have
just one trampoline, saving exactly as many input arguments as
attached function(s) have. So at least we don't have to maintain two
separate pieces of logic for that. Then the only added complexity
would be breaking up all to-be-attached kernel functions into groups,
as described in the example.
It sounds a bit more complicated in writing than it will be in
practice, probably. I think the critical part is unification of
trampoline to work with fentry/fexit and fentry.multi/fexit.multi
simultaneously, which seems like you agreed above is achievable.
...
I have test code for ftrace direct interface that would
allow to register/change separate function/addr pairs,
so in one call you can change multiple ips each to
different tramp addresss
but even with that, I ended up with lot of new complexity
on bpf side keeping track of multi trampolines intersections,
so I thought I'd start with something limited and simpler
perhaps I should move back to that approach and see how bad
it ends ;-)
or this could be next step on top of current work, that should
get simpler with the args re-arranging you proposed
jirka
From: Jiri Olsa <hidden> Date: 2021-09-02 12:57:19
On Wed, Sep 01, 2021 at 08:56:19PM -0700, Andrii Nakryiko wrote:
On Wed, Sep 1, 2021 at 8:15 AM Jiri Olsa [off-list ref] wrote:
quoted
On Tue, Aug 31, 2021 at 04:51:18PM -0700, Andrii Nakryiko wrote:
quoted
On Thu, Aug 26, 2021 at 12:41 PM Jiri Olsa [off-list ref] wrote:
quoted
When we have multi func program attached, the trampoline
switched to the function model of the multi func program.
This breaks already attached standard programs, for example
when we attach following program:
SEC("fexit/bpf_fentry_test2")
int BPF_PROG(test1, int a, __u64 b, int ret)
the trampoline pushes on stack args 'a' and 'b' and return
value 'ret'.
When following multi func program is attached to bpf_fentry_test2:
SEC("fexit.multi/bpf_fentry_test*")
int BPF_PROG(test2, __u64 a, __u64 b, __u64 c, __u64 d,
__u64 e, __u64 f, int ret)
the trampoline takes this program model and pushes all 6 args
and return value on stack.
But we still have the original 'test1' program attached, that
expects 'ret' value where there's 'c' argument now:
test1(a, b, c)
To fix that we simply overwrite 'c' argument with 'ret' value,
so test1 is called as expected and test2 gets called as:
test2(a, b, ret, d, e, f, ret)
which is ok, because 'c' is not defined for bpf_fentry_test2
anyway.
What if we change the order on the stack to be the return value first,
followed by input arguments. That would get us a bit closer to
unifying multi-trampoline and the normal one, right? BPF verifier
should be able to rewrite access to the last argument (i.e., return
value) for fexit programs to actually be at offset 0, and shift all
other arguments by 8 bytes. For fentry, if that helps to keep things
more aligned, we'd just skip the first 8 bytes on the stack and store
all the input arguments in the same offsets. So BPF verifier rewriting
logic stays consistent (except offset 0 will be disallowed).
nice idea, with this in place we could cut that args re-arranging code
quoted
Basically, I'm thinking how we can make normal and multi trampolines
more interoperable to remove those limitations that two
multi-trampolines can't be attached to the same function, which seems
like a pretty annoying limitation which will be easy to hit in
practice. Alexei previously proposed (as an optimization) to group all
to-be-attached functions into groups by number of arguments, so that
we can have up to 6 different trampolines tailored to actual functions
being attached. So that we don't save unnecessary extra input
arguments saving, which will be even more important once we allow more
than 6 arguments in the future.
With such logic, we should be able to split all the functions into
multiple underlying trampolines, so it seems like it should be
possible to also allow multiple multi-fentry programs to be attached
to the same function by having a separate bpf_trampoline just for
those functions. It will be just an extension of the above "just 6
trampolines" strategy to "as much as we need trampolines".
I'm probably missing something here.. say we have 2 functions with single
argument:
foo1(int a)
foo2(int b)
then having 2 programs:
A - attaching to foo1
B - attaching to foo2
then you need to have 2 different trampolines instead of single 'generic-1-argument-trampoline'
right, you have two different BPF progs attached to two different
functions. You have to have 2 trampolines, not sure what's
confusing?..
I misunderstood the statement above:
quoted
quoted
practice. Alexei previously proposed (as an optimization) to group all
to-be-attached functions into groups by number of arguments, so that
we can have up to 6 different trampolines tailored to actual functions
being attached. So that we don't save unnecessary extra input
you meant just functions to be attached at that moment, not all, ok
quoted
quoted
It's just a vague idea, sorry, I don't understand all the code yet.
But the limitation outlined in one of the previous patches seems very
limiting and unpleasant. I can totally see that some 24/7 running BPF
tracing app uses multi-fentry for tracing a small subset of kernel
functions non-stop, and then someone is trying to use bpftrace or
retsnoop to trace overlapping set of functions. And it immediately
fails. Very frustrating.
so the current approach is to some extent driven by the direct ftrace
batch API:
you have ftrace_ops object and set it up with functions you want
to change with calling:
ftrace_set_filter_ip(ops, ip1);
ftrace_set_filter_ip(ops, ip2);
...
and then register trampoline with those functions:
register_ftrace_direct_multi(ops, tramp_addr);
and with this call being the expensive one (it does the actual work
and sync waiting), my objective was to call it just once for update
now with 2 intersecting multi trampolines we end up with 3 functions
sets:
A - functions for first multi trampoline
B - functions for second multi trampoline
C - intersection of them
each set needs different trampoline:
tramp A - calls program for first multi trampoline
tramp B - calls program for second multi trampoline
tramp C - calls both programs
so we need to call register_ftrace_direct_multi 3 times
Yes, that's the minimal amount of trampolines you need. Calling
register_ftrace_direct_multi() three times is not that bad at all,
compared to calling it 1000s of times. If you are worried about 1 vs 3
calls, I think you are over-optimizing here. I'd rather take no
restrictions on what can be attached to what and in which sequences
but taking 3ms vs having obscure (for uninitiated users) restrictions,
but in some cases allowing attachment to happen in 1ms.
The goal with multi-attach is to make it decently fast when attaching
to a lot functions, but if attachment speed is fast enough, then such
small performance differences don't matter anymore.
true, I might have been focused on the worst possible case here ;-)
quoted
if we allow also standard trampolines being attached, it makes
it even more complicated and ultimatelly gets broken to
1-function/1-trampoline pairs, ending up with attach speed
that we have now
So let's make sure that we are on the same page. Let me write out an example.
Let's say we have 5 kernel functions: a, b, c, d, e. Say a, b, c all
have 1 input args, and d and e have 2.
Now let's say we attach just normal fentry program A to function a.
Also we attach normal fexit program E to func e.
We'll have A attached to a with trampoline T1. We'll also have E
attached to e with trampoline T2. Right?
And now we try to attach generic fentry (fentry.multi in your
terminology) prog X to all 5 of them. If A and E weren't attached,
we'd need two generic trampolines, one for a, b, c (because 1 input
argument) and another for d,e (because 2 input arguments). But because
we already have A and B attached, we'll end up needing 4:
T1 (1 arg) for func a calling progs A and X
T2 (2 args) for func e calling progs E and X
T3 (1 arg) for func b and c calling X
T4 (2 args) for func d calling X
so current code would group T3/T4 together, but if we keep
them separated, then we won't need to use new model and
cut off some of the code, ok
together with that args shifting we could endup with almost
untouched trampoline generation code ;-)
We can't have less than that and satisfy all the constraints. But 4 is
not that bad. If the example has 1000s of functions, you'd still need
between 4 and 8 trampolines (if we had 3, 4, 5, and 6 input args for
kernel functions). That's way less than 1000s of trampolines needed
today. And it's still fast enough on the attachment.
The good thing with what we discussed with making current trampoline
co-exist with generic (multi) fentry/fexit, is that we'll still have
just one trampoline, saving exactly as many input arguments as
attached function(s) have. So at least we don't have to maintain two
separate pieces of logic for that. Then the only added complexity
would be breaking up all to-be-attached kernel functions into groups,
as described in the example.
It sounds a bit more complicated in writing than it will be in
practice, probably. I think the critical part is unification of
trampoline to work with fentry/fexit and fentry.multi/fexit.multi
simultaneously, which seems like you agreed above is achievable.
ok, I haven't considered this way, but I think it's doable
thanks,
jirka
On Thu, Sep 2, 2021 at 5:57 AM Jiri Olsa [off-list ref] wrote:
On Wed, Sep 01, 2021 at 08:56:19PM -0700, Andrii Nakryiko wrote:
quoted
On Wed, Sep 1, 2021 at 8:15 AM Jiri Olsa [off-list ref] wrote:
quoted
On Tue, Aug 31, 2021 at 04:51:18PM -0700, Andrii Nakryiko wrote:
quoted
On Thu, Aug 26, 2021 at 12:41 PM Jiri Olsa [off-list ref] wrote:
quoted
When we have multi func program attached, the trampoline
switched to the function model of the multi func program.
This breaks already attached standard programs, for example
when we attach following program:
SEC("fexit/bpf_fentry_test2")
int BPF_PROG(test1, int a, __u64 b, int ret)
the trampoline pushes on stack args 'a' and 'b' and return
value 'ret'.
When following multi func program is attached to bpf_fentry_test2:
SEC("fexit.multi/bpf_fentry_test*")
int BPF_PROG(test2, __u64 a, __u64 b, __u64 c, __u64 d,
__u64 e, __u64 f, int ret)
the trampoline takes this program model and pushes all 6 args
and return value on stack.
But we still have the original 'test1' program attached, that
expects 'ret' value where there's 'c' argument now:
test1(a, b, c)
To fix that we simply overwrite 'c' argument with 'ret' value,
so test1 is called as expected and test2 gets called as:
test2(a, b, ret, d, e, f, ret)
which is ok, because 'c' is not defined for bpf_fentry_test2
anyway.
What if we change the order on the stack to be the return value first,
followed by input arguments. That would get us a bit closer to
unifying multi-trampoline and the normal one, right? BPF verifier
should be able to rewrite access to the last argument (i.e., return
value) for fexit programs to actually be at offset 0, and shift all
other arguments by 8 bytes. For fentry, if that helps to keep things
more aligned, we'd just skip the first 8 bytes on the stack and store
all the input arguments in the same offsets. So BPF verifier rewriting
logic stays consistent (except offset 0 will be disallowed).
nice idea, with this in place we could cut that args re-arranging code
quoted
Basically, I'm thinking how we can make normal and multi trampolines
more interoperable to remove those limitations that two
multi-trampolines can't be attached to the same function, which seems
like a pretty annoying limitation which will be easy to hit in
practice. Alexei previously proposed (as an optimization) to group all
to-be-attached functions into groups by number of arguments, so that
we can have up to 6 different trampolines tailored to actual functions
being attached. So that we don't save unnecessary extra input
arguments saving, which will be even more important once we allow more
than 6 arguments in the future.
With such logic, we should be able to split all the functions into
multiple underlying trampolines, so it seems like it should be
possible to also allow multiple multi-fentry programs to be attached
to the same function by having a separate bpf_trampoline just for
those functions. It will be just an extension of the above "just 6
trampolines" strategy to "as much as we need trampolines".
I'm probably missing something here.. say we have 2 functions with single
argument:
foo1(int a)
foo2(int b)
then having 2 programs:
A - attaching to foo1
B - attaching to foo2
then you need to have 2 different trampolines instead of single 'generic-1-argument-trampoline'
right, you have two different BPF progs attached to two different
functions. You have to have 2 trampolines, not sure what's
confusing?..
I misunderstood the statement above:
quoted
quoted
quoted
practice. Alexei previously proposed (as an optimization) to group all
to-be-attached functions into groups by number of arguments, so that
we can have up to 6 different trampolines tailored to actual functions
being attached. So that we don't save unnecessary extra input
you meant just functions to be attached at that moment, not all, ok
quoted
quoted
quoted
It's just a vague idea, sorry, I don't understand all the code yet.
But the limitation outlined in one of the previous patches seems very
limiting and unpleasant. I can totally see that some 24/7 running BPF
tracing app uses multi-fentry for tracing a small subset of kernel
functions non-stop, and then someone is trying to use bpftrace or
retsnoop to trace overlapping set of functions. And it immediately
fails. Very frustrating.
so the current approach is to some extent driven by the direct ftrace
batch API:
you have ftrace_ops object and set it up with functions you want
to change with calling:
ftrace_set_filter_ip(ops, ip1);
ftrace_set_filter_ip(ops, ip2);
...
and then register trampoline with those functions:
register_ftrace_direct_multi(ops, tramp_addr);
and with this call being the expensive one (it does the actual work
and sync waiting), my objective was to call it just once for update
now with 2 intersecting multi trampolines we end up with 3 functions
sets:
A - functions for first multi trampoline
B - functions for second multi trampoline
C - intersection of them
each set needs different trampoline:
tramp A - calls program for first multi trampoline
tramp B - calls program for second multi trampoline
tramp C - calls both programs
so we need to call register_ftrace_direct_multi 3 times
Yes, that's the minimal amount of trampolines you need. Calling
register_ftrace_direct_multi() three times is not that bad at all,
compared to calling it 1000s of times. If you are worried about 1 vs 3
calls, I think you are over-optimizing here. I'd rather take no
restrictions on what can be attached to what and in which sequences
but taking 3ms vs having obscure (for uninitiated users) restrictions,
but in some cases allowing attachment to happen in 1ms.
The goal with multi-attach is to make it decently fast when attaching
to a lot functions, but if attachment speed is fast enough, then such
small performance differences don't matter anymore.
true, I might have been focused on the worst possible case here ;-)
quoted
quoted
if we allow also standard trampolines being attached, it makes
it even more complicated and ultimatelly gets broken to
1-function/1-trampoline pairs, ending up with attach speed
that we have now
So let's make sure that we are on the same page. Let me write out an example.
Let's say we have 5 kernel functions: a, b, c, d, e. Say a, b, c all
have 1 input args, and d and e have 2.
Now let's say we attach just normal fentry program A to function a.
Also we attach normal fexit program E to func e.
We'll have A attached to a with trampoline T1. We'll also have E
attached to e with trampoline T2. Right?
And now we try to attach generic fentry (fentry.multi in your
terminology) prog X to all 5 of them. If A and E weren't attached,
we'd need two generic trampolines, one for a, b, c (because 1 input
argument) and another for d,e (because 2 input arguments). But because
we already have A and B attached, we'll end up needing 4:
T1 (1 arg) for func a calling progs A and X
T2 (2 args) for func e calling progs E and X
T3 (1 arg) for func b and c calling X
T4 (2 args) for func d calling X
so current code would group T3/T4 together, but if we keep
them separated, then we won't need to use new model and
cut off some of the code, ok
together with that args shifting we could endup with almost
untouched trampoline generation code ;-)
exactly, and thus remove those limitations you've described
quoted
We can't have less than that and satisfy all the constraints. But 4 is
not that bad. If the example has 1000s of functions, you'd still need
between 4 and 8 trampolines (if we had 3, 4, 5, and 6 input args for
kernel functions). That's way less than 1000s of trampolines needed
today. And it's still fast enough on the attachment.
The good thing with what we discussed with making current trampoline
co-exist with generic (multi) fentry/fexit, is that we'll still have
just one trampoline, saving exactly as many input arguments as
attached function(s) have. So at least we don't have to maintain two
separate pieces of logic for that. Then the only added complexity
would be breaking up all to-be-attached kernel functions into groups,
as described in the example.
It sounds a bit more complicated in writing than it will be in
practice, probably. I think the critical part is unification of
trampoline to work with fentry/fexit and fentry.multi/fexit.multi
simultaneously, which seems like you agreed above is achievable.
ok, I haven't considered this way, but I think it's doable
On Thu, Sep 02, 2021 at 02:57:11PM +0200, Jiri Olsa wrote:
quoted
Let's say we have 5 kernel functions: a, b, c, d, e. Say a, b, c all
have 1 input args, and d and e have 2.
Now let's say we attach just normal fentry program A to function a.
Also we attach normal fexit program E to func e.
We'll have A attached to a with trampoline T1. We'll also have E
attached to e with trampoline T2. Right?
And now we try to attach generic fentry (fentry.multi in your
terminology) prog X to all 5 of them. If A and E weren't attached,
we'd need two generic trampolines, one for a, b, c (because 1 input
argument) and another for d,e (because 2 input arguments). But because
we already have A and B attached, we'll end up needing 4:
T1 (1 arg) for func a calling progs A and X
T2 (2 args) for func e calling progs E and X
T3 (1 arg) for func b and c calling X
T4 (2 args) for func d calling X
so current code would group T3/T4 together, but if we keep
them separated, then we won't need to use new model and
cut off some of the code, ok
We've brainstormed this idea further with Andrii.
(thankfully we could do it in-person now ;) which saved a ton of time)
It seems the following should work:
5 kernel functions: a(int), b(long), c(void*), d(int, int), e(long, long).
fentry prog A is attached to 'a'.
fexit prog E is attached to 'e'.
multi-prog X wants to attach to all of them.
It can be achieved with 4 trampolines.
The trampolines called from funcs 'a' and 'e' can be patched to
call A+X and E+X programs correspondingly.
The multi program X needs to be able to access return values
and arguments of all functions it was attached to.
We can achieve that by always generating a trampoline (both multi and normal)
with extra constant stored in the stack. This constant is the number of
arguments served by this trampoline.
The trampoline 'a' will store nr_args=1.
The tramopline 'e' will store nr_args=2.
We need two multi trampolines.
The multi tramopline X1 that will serve 'b' and 'c' and store nr_args=1
and multi-tramopline X2 that will serve 'd' and store nr_args=2
into hidden stack location (like ctx[-2]).
The multi prog X can look like:
int BPF_PROG(x, __u64 arg1, __u64 arg2, __u64 ret)
in such case it will read correct args and ret when called from 'd' and 'e'
and only correct arg1 when called from 'a', 'b', 'c'.
To always correctly access arguments and the return value
the program can use two new helpers: bpf_arg(ctx, N) and bpf_ret_value(ctx).
Both will be fully inlined helpers similar to bpf_get_func_ip().
u64 bpf_arg(ctx, int n)
{
u64 nr_args = ctx[-2]; /* that's the place where _all_ trampoline will store nr_args */
if (n > nr_args)
return 0;
return ctx[n];
}
u64 bpf_ret_value(ctx)
{
u64 nr_args = ctx[-2];
return ctx[nr_args];
}
These helpers will be the only recommended way to access args and ret value
in multi progs.
The nice advantage is that normal fentry/fexit progs can use them too.
We can rearrange ctx[-1] /* func_ip */ and ctx[-2] /* nr_args */
if it makes things easier.
If multi prog knows that it is attaching to 100 kernel functions
and all of them have 2 arguments it can still do
int BPF_PROG(x, __u64 arg1, __u64 arg2, __u64 ret)
{ // access arg1, arg2, ret directly
and it will work correctly.
We can make it really strict in the verifier and disallow such
direct access to args from the multi prog and only allow
access via bpf_arg/bpf_ret_value helpers, but I think it's overkill.
Reading garbage values from stack isn't great, but it's not a safety issue.
It means that the verifier will allow something like 16 u64-s args
in multi program. It cannot allow large number, since ctx[1024]
might become a safety issue, while ctx[4] could be a garbage
or a valid value depending on the call site.
Thoughts?
From: Jiri Olsa <hidden> Date: 2021-09-03 09:50:21
On Thu, Sep 02, 2021 at 02:55:38PM -0700, Alexei Starovoitov wrote:
On Thu, Sep 02, 2021 at 02:57:11PM +0200, Jiri Olsa wrote:
quoted
quoted
Let's say we have 5 kernel functions: a, b, c, d, e. Say a, b, c all
have 1 input args, and d and e have 2.
Now let's say we attach just normal fentry program A to function a.
Also we attach normal fexit program E to func e.
We'll have A attached to a with trampoline T1. We'll also have E
attached to e with trampoline T2. Right?
And now we try to attach generic fentry (fentry.multi in your
terminology) prog X to all 5 of them. If A and E weren't attached,
we'd need two generic trampolines, one for a, b, c (because 1 input
argument) and another for d,e (because 2 input arguments). But because
we already have A and B attached, we'll end up needing 4:
T1 (1 arg) for func a calling progs A and X
T2 (2 args) for func e calling progs E and X
T3 (1 arg) for func b and c calling X
T4 (2 args) for func d calling X
so current code would group T3/T4 together, but if we keep
them separated, then we won't need to use new model and
cut off some of the code, ok
We've brainstormed this idea further with Andrii.
(thankfully we could do it in-person now ;) which saved a ton of time)
It seems the following should work:
5 kernel functions: a(int), b(long), c(void*), d(int, int), e(long, long).
fentry prog A is attached to 'a'.
fexit prog E is attached to 'e'.
multi-prog X wants to attach to all of them.
It can be achieved with 4 trampolines.
The trampolines called from funcs 'a' and 'e' can be patched to
call A+X and E+X programs correspondingly.
The multi program X needs to be able to access return values
and arguments of all functions it was attached to.
We can achieve that by always generating a trampoline (both multi and normal)
with extra constant stored in the stack. This constant is the number of
arguments served by this trampoline.
The trampoline 'a' will store nr_args=1.
The tramopline 'e' will store nr_args=2.
We need two multi trampolines.
The multi tramopline X1 that will serve 'b' and 'c' and store nr_args=1
and multi-tramopline X2 that will serve 'd' and store nr_args=2
into hidden stack location (like ctx[-2]).
The multi prog X can look like:
int BPF_PROG(x, __u64 arg1, __u64 arg2, __u64 ret)
in such case it will read correct args and ret when called from 'd' and 'e'
and only correct arg1 when called from 'a', 'b', 'c'.
To always correctly access arguments and the return value
the program can use two new helpers: bpf_arg(ctx, N) and bpf_ret_value(ctx).
Both will be fully inlined helpers similar to bpf_get_func_ip().
u64 bpf_arg(ctx, int n)
{
u64 nr_args = ctx[-2]; /* that's the place where _all_ trampoline will store nr_args */
if (n > nr_args)
return 0;
return ctx[n];
}
u64 bpf_ret_value(ctx)
{
u64 nr_args = ctx[-2];
return ctx[nr_args];
}
ok, this is much better then rewiring args access in verifier
These helpers will be the only recommended way to access args and ret value
in multi progs.
The nice advantage is that normal fentry/fexit progs can use them too.
We can rearrange ctx[-1] /* func_ip */ and ctx[-2] /* nr_args */
if it makes things easier.
so nr_args will be there all the time, while func_ip is optional
at the moment (based on get_func_ip helper presence in program),
so we can either switch that:
func_ip in ctx[-2]
nr_args in ctx[-1]
or make func_ip not optional to avoid confusion
I think pushing func_ip to ctx-2 is ok
If multi prog knows that it is attaching to 100 kernel functions
and all of them have 2 arguments it can still do
int BPF_PROG(x, __u64 arg1, __u64 arg2, __u64 ret)
{ // access arg1, arg2, ret directly
and it will work correctly.
ok, it's user's decision, because at load time we don't know the
functions it will be attached to, so verifier can't do anything
We can make it really strict in the verifier and disallow such
direct access to args from the multi prog and only allow
access via bpf_arg/bpf_ret_value helpers, but I think it's overkill.
Reading garbage values from stack isn't great, but it's not a safety issue.
we could also check it in attach time and forbid to attach if there
are attach functions with different nr_args and program does not use
arg helpers
It means that the verifier will allow something like 16 u64-s args
in multi program. It cannot allow large number, since ctx[1024]
might become a safety issue, while ctx[4] could be a garbage
or a valid value depending on the call site.
Thoughts?