bpf: Introduce BPF timers.
Subsystems (9)
v7 cover bpf: Introduce BPF timers.
From: Alexei Starovoitov <[email protected]>
The first request to support timers in bpf was made in 2013 before sys_bpf syscall was added. That use case was periodic sampling. It was address with attaching bpf programs to perf_events. Then during XDP development the timers were requested to do garbage collection and health checks. They were worked around by implementing timers in user space and triggering progs with BPF_PROG_RUN command. The user space timers and perf_event+bpf timers are not armed by the bpf program. They're done asynchronously vs program execution. The XDP program cannot send a packet and arm the timer at the same time. The tracing prog cannot record an event and arm the timer right away. This large class of use cases remained unaddressed. The jiffy based and hrtimer based timers are essential part of the kernel development and with this patch set the hrtimer based timers will be available to bpf programs.
TLDR: bpf timers is a wrapper of hrtimers with all the extra safety added to make sure bpf progs cannot crash the kernel.
v6->v7:
- address Andrii's comments and add his Acks.
v5->v6:
- address code review feedback from Martin and add his Acks.
- add usercnt > 0 check to bpf_timer_init and remove timers_cancel_and_free second loop in map_free callbacks.
- add cond_resched_rcu.
v4->v5:
- Martin noticed the following issues:
. prog could be reallocated bpf_patch_insn_data().
Fixed by passing 'aux' into bpf_timer_set_callback, since 'aux' is stable during insn patching.
. Added missing rcu_read_lock.
. Removed redundant record_map.
- Discovered few bugs with stress testing:
. One cpu does htab_free_prealloced_timers->bpf_timer_cancel_and_free->hrtimer_cancel while another is trying to do something with the timer like bpf_timer_start/set_callback. Those ops try to acquire bpf_spin_lock that is already taken by bpf_timer_cancel_and_free, so both cpus spin forever. The same problem existed in bpf_timer_cancel(). One bpf prog on one cpu might call bpf_timer_cancel and wait, while another cpu is in the timer callback that tries to do bpf_timer_*() helper on the same timer. The fix is to do drop_prog_refcnt() and unlock. And only then hrtimer_cancel. Because of this had to add callback_fn != NULL check to bpf_timer_cb(). Also removed redundant bpf_prog_inc/put from bpf_timer_cb() and replaced with rcu_dereference_check similar to recent rcu_read_lock-removal from drivers. bpf_timer_cb is in softirq.
. Managed to hit refcnt==0 while doing bpf_prog_put from bpf_timer_cancel_and_free(). That exposed the issue that bpf_prog_put wasn't ready to be called from irq context. Fixed similar to bpf_map_put which is irq ready.
- Refactored BPF_CALL_1(bpf_spin_lock) into __bpf_spin_lock_irqsave() to make the main logic more clear, since Martin and Yonghong brought up this concern.
v3->v4:
1.
Split callback_fn from bpf_timer_start into bpf_timer_set_callback as suggested by Martin. That makes bpf timer api match one to one to kernel hrtimer api and provides greater flexibility.
2.
Martin also discovered the following issue with uref approach:
bpftool prog load xdp_timer.o /sys/fs/bpf/xdp_timer type xdp bpftool net attach xdpgeneric pinned /sys/fs/bpf/xdp_timer dev lo rm /sys/fs/bpf/xdp_timer
nc -6 ::1 8888
bpftool net detach xdpgeneric dev lo
The timer callback stays active in the kernel though the prog was detached and map usercnt == 0.
It happened because 'bpftool prog load' pinned the prog only. The map usercnt went to zero. Subsequent attach and runs didn't affect map usercnt. The timer was able to start and bpf_prog_inc itself. When the prog was detached the prog stayed active.
To address this issue added
if (!atomic64_read(&(t->map->usercnt))) return -EPERM;
to the first patch.
Which means that timers are allowed only in the maps that are held by user space with open file descriptor or maps pinned in bpffs. 3.
Discovered that timers in inner maps were broken.
The inner map pointers are dynamic. Therefore changed bpf_timer_init() to accept explicit map pointer supplied by the program instead of hidden map pointer supplied by the verifier.
To make sure that pointer to a timer actually belongs to that map added the verifier check in patch 3.
4.
Addressed Yonghong's feedback. Improved comments and added dynamic in_nmi() check.
Added Acks.
v2->v3:
The v2 approach attempted to bump bpf_prog refcnt when bpf_timer_start is called to make sure callback code doesn't disappear when timer is active and drop refcnt when timer cb is done. That led to a ton of race conditions between callback running and concurrent bpf_timer_init/start/cancel on another cpu, and concurrent bpf_map_update/delete_elem, and map destroy.
Then v2.5 approach skipped prog refcnt altogether. Instead it remembered all timers that bpf prog armed in a link list and canceled them when prog refcnt went to zero. The race conditions disappeared, but timers in map-in-map could not be supported cleanly, since timers in inner maps have inner map's life time and don't match prog's life time.
This v3 approach makes timers to be owned by maps. It allows timers in inner maps to be supported from the start. This apporach relies on "user refcnt" scheme used in prog_array that stores bpf programs for bpf_tail_call. The bpf_timer_start() increments prog refcnt, but unlike 1st approach the timer callback does decrement the refcnt. The ops->map_release_uref is responsible for cancelling the timers and dropping prog refcnt when user space reference to a map is dropped. That addressed all the races and simplified locking.
Andrii presented a use case where specifying callback_fn in bpf_timer_init() is inconvenient vs specifying in bpf_timer_start(). The bpf_timer_init() typically is called outside for timer callback, while bpf_timer_start() most likely will be called from the callback.timer_cb() { ... bpf_timer_start(timer_cb); ...} looks like recursion and as infinite loop to the verifier. The verifier had to be made smarter to recognize such async callbacks. Patches 7,8,9 addressed that.
Patch 1 and 2 refactoring.
Patch 3 implements bpf timer helpers and locking.
Patch 4 implements map side of bpf timer support.
Patch 5 prevent pointer mismatch in bpf_timer_init.
Patch 6 adds support for BTF in inner maps.
Patch 7 teaches check_cfg() pass to understand async callbacks. Patch 8 teaches do_check() pass to understand async callbacks. Patch 9 teaches check_max_stack_depth() pass to understand async callbacks. Patches 10 and 11 are the tests.
v1->v2:
- Addressed great feedback from Andrii and Toke.
- Fixed race between parallel bpf_timer_*() ops.
- Fixed deadlock between timer callback and LRU eviction or bpf_map_delete/update.
- Disallowed mmap and global timers.
- Allow spin_lock and bpf_timer in an element.
- Fixed memory leaks due to map destruction and LRU eviction.
- A ton more tests.
Alexei Starovoitov (11):
bpf: Prepare bpf_prog_put() to be called from irq context.
bpf: Factor out bpf_spin_lock into helpers.
bpf: Introduce bpf timers.
bpf: Add map side support for bpf timers.
bpf: Prevent pointer mismatch in bpf_timer_init.
bpf: Remember BTF of inner maps.
bpf: Relax verifier recursion check.
bpf: Implement verifier support for validation of async callbacks.
bpf: Teach stack depth check about async callbacks. selftests/bpf: Add bpf_timer test.
selftests/bpf: Add a test with bpf_timer in inner map.
include/linux/bpf.h | 47 ++- include/linux/bpf_verifier.h | 19 +- include/linux/btf.h | 1 + include/uapi/linux/bpf.h | 73 ++++ kernel/bpf/arraymap.c | 21 ++ kernel/bpf/btf.c | 77 +++- kernel/bpf/hashtab.c | 105 +++++- kernel/bpf/helpers.c | 340 +++++++++++++++++- kernel/bpf/local_storage.c | 4 +- kernel/bpf/map_in_map.c | 8 + kernel/bpf/syscall.c | 53 ++- kernel/bpf/verifier.c | 307 +++++++++++++++- kernel/trace/bpf_trace.c | 2 +- scripts/bpf_doc.py | 2 + tools/include/uapi/linux/bpf.h | 73 ++++ .../testing/selftests/bpf/prog_tests/timer.c | 55 +++ .../selftests/bpf/prog_tests/timer_mim.c | 69 ++++ tools/testing/selftests/bpf/progs/timer.c | 297 +++++++++++++++ tools/testing/selftests/bpf/progs/timer_mim.c | 88 +++++ .../selftests/bpf/progs/timer_mim_reject.c | 74 ++++ 20 files changed, 1651 insertions(+), 64 deletions(-) create mode 100644 tools/testing/selftests/bpf/prog_tests/timer.c create mode 100644 tools/testing/selftests/bpf/prog_tests/timer_mim.c create mode 100644 tools/testing/selftests/bpf/progs/timer.c create mode 100644 tools/testing/selftests/bpf/progs/timer_mim.c create mode 100644 tools/testing/selftests/bpf/progs/timer_mim_reject.c
Signature · 1 line
2.30.2
PATCH v7 1/11 bpf: Prepare bpf_prog_put() to be called from irq context.
From: Alexei Starovoitov <[email protected]>
Currently bpf_prog_put() is called from the task context only. With addition of bpf timers the timer related helpers will start calling bpf_prog_put() from irq-saved region and in rare cases might drop the refcnt to zero.
To address this case, first, convert bpf_prog_free_id() to be irq-save (this is similar to bpf_map_free_id), and, second, defer non irq appropriate calls into work queue.
For example:bpf_audit_prog() is calling kmalloc and wake_up_interruptible, bpf_prog_kallsyms_del_all()->bpf_ksym_del()->spin_unlock_bh(). They are not safe with irqs disabled.
--- kernel/bpf/syscall.c | 32 ++++++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 6 deletions(-)
kernel/bpf/syscall.c +26 -6
@@ -1699,6 +1699,8 @@ static int bpf_prog_alloc_id(struct bpf_prog *prog)void bpf_prog_free_id (struct bpf_prog *prog,bool do_idr_lock) { +unsigned long flags; +/* cBPF to eBPF migrations are currently not in the idr store. * Offloaded programs are removed from the store when their device * disappears - even if someone grabs an fd to them they are unusable,
@@ -1708,7 +1710,7 @@ void bpf_prog_free_id(struct bpf_prog *prog, bool do_idr_lock)return ;if (do_idr_lock) -spin_lock_bh (&prog_idr_lock); +spin_lock_irqsave (&prog_idr_lock, flags);else __acquire (&prog_idr_lock);
@@ -1716,7 +1718,7 @@ void bpf_prog_free_id(struct bpf_prog *prog, bool do_idr_lock) prog->aux->id =0 ;if (do_idr_lock) -spin_unlock_bh (&prog_idr_lock); +spin_unlock_irqrestore (&prog_idr_lock, flags);else __release (&prog_idr_lock); }
@@ -1752,14 +1754,32 @@ static void __bpf_prog_put_noref(struct bpf_prog *prog, bool deferred) } } +static void bpf_prog_put_deferred (struct work_struct *work) +{ +struct bpf_prog_aux *aux; +struct bpf_prog *prog; + + aux = container_of(work, struct bpf_prog_aux, work); + prog = aux->prog; +perf_event_bpf_event (prog,PERF_BPF_EVENT_PROG_UNLOAD ,0 ); +bpf_audit_prog (prog,BPF_AUDIT_UNLOAD ); +__bpf_prog_put_noref (prog, true); +} +static void __bpf_prog_put (struct bpf_prog *prog,bool do_idr_lock) { -if (atomic64_dec_and_test (&prog->aux->refcnt)) { -perf_event_bpf_event (prog,PERF_BPF_EVENT_PROG_UNLOAD ,0 ); -bpf_audit_prog (prog,BPF_AUDIT_UNLOAD ); +struct bpf_prog_aux *aux = prog->aux; + +if (atomic64_dec_and_test (&aux->refcnt)) {/* bpf_prog_free_id() must be called first */ bpf_prog_free_id (prog, do_idr_lock); -__bpf_prog_put_noref (prog, true); + +if (in_irq () ||irqs_disabled ()) { +INIT_WORK (&aux->work, bpf_prog_put_deferred); +schedule_work (&aux->work); + }else { +bpf_prog_put_deferred (&aux->work); + } } }
Signature · 1 line
2.30.2
PATCH v7 2/11 bpf: Factor out bpf_spin_lock into helpers.
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
Move ____bpf_spin_lock/unlock into helpers to make it more clear that quadruple underscore bpf_spin_lock/unlock are irqsave/restore variants.
--- kernel/bpf/helpers.c | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-)
kernel/bpf/helpers.c +14 -4
@@ -289,13 +289,18 @@ static inline void __bpf_spin_unlock(struct bpf_spin_lock *lock) static DEFINE_PER_CPU(unsigned long, irqsave_flags); -notrace BPF_CALL_1 (bpf_spin_lock ,struct bpf_spin_lock *,lock ) +static inline void __bpf_spin_lock_irqsave (struct bpf_spin_lock *lock) {unsigned long flags;local_irq_save (flags);__bpf_spin_lock (lock);__this_cpu_write (irqsave_flags, flags); +} + +notrace BPF_CALL_1 (bpf_spin_lock ,struct bpf_spin_lock *,lock ) +{ +__bpf_spin_lock_irqsave (lock);return 0 ; }
@@ -306,13 +311,18 @@ const struct bpf_func_proto bpf_spin_lock_proto = { .arg1_type = ARG_PTR_TO_SPIN_LOCK, }; -notrace BPF_CALL_1 (bpf_spin_unlock ,struct bpf_spin_lock *,lock ) +static inline void __bpf_spin_unlock_irqrestore (struct bpf_spin_lock *lock) {unsigned long flags; flags =__this_cpu_read (irqsave_flags);__bpf_spin_unlock (lock);local_irq_restore (flags); +} + +notrace BPF_CALL_1 (bpf_spin_unlock ,struct bpf_spin_lock *,lock ) +{ +__bpf_spin_unlock_irqrestore (lock);return 0 ; }
@@ -333,9 +343,9 @@ void copy_map_value_locked(struct bpf_map *map, void *dst, void *src,else lock = dst + map->spin_lock_off;preempt_disable (); -____bpf_spin_lock (lock); +__bpf_spin_lock_irqsave (lock);copy_map_value (map, dst, src); -____bpf_spin_unlock (lock); +__bpf_spin_unlock_irqrestore (lock);preempt_enable (); }
Signature · 1 line
2.30.2
PATCH v7 3/11 bpf: Introduce bpf timers.
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
Introduce 'struct bpf_timer { __u64 :64; __u64 :64; };' that can be embedded in hash/array/lru maps as a regular field and helpers to operate on it:
// Initialize the timer.
// First 4 bits of 'flags' specify clockid.
// Only CLOCK_MONOTONIC, CLOCK_REALTIME, CLOCK_BOOTTIME are allowed. long bpf_timer_init(struct bpf_timer *timer, struct bpf_map *map, int flags);
// Configure the timer to call 'callback_fn' static function. long bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
// Arm the timer to expire 'nsec' nanoseconds from the current time. long bpf_timer_start(struct bpf_timer *timer, u64 nsec, u64 flags);
// Cancel the timer and wait for callback_fn to finish if it was running. long bpf_timer_cancel(struct bpf_timer *timer);
Here is how BPF program might look like:
struct map_elem {
int counter;
struct bpf_timer timer;
};struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, 1000);
__type(key, int);
__type(value, struct map_elem);
} hmap SEC(".maps");static int timer_cb(void *map, int *key, struct map_elem *val); /* val points to particular map element that contains bpf_timer. */
SEC("fentry/bpf_fentry_test1")
int BPF_PROG(test1, int a)
{
struct map_elem *val;
int key = 0;
val = bpf_map_lookup_elem(&hmap, &key);
if (val) {
bpf_timer_init(&val->timer, &hmap, CLOCK_REALTIME);
bpf_timer_set_callback(&val->timer, timer_cb);
bpf_timer_start(&val->timer, 1000 /* call timer_cb2 in 1 usec */, 0);
}
}This patch adds helper implementations that rely on hrtimers to call bpf functions as timers expire.
The following patches add necessary safety checks.
Only programs with CAP_BPF are allowed to use bpf_timer.
The amount of timers used by the program is constrained by the memcg recorded at map creation time.
The bpf_timer_init() helper needs explicit 'map' argument because inner maps are dynamic and not known at load time. While the bpf_timer_set_callback() is receiving hidden 'aux->prog' argument supplied by the verifier.
The prog pointer is needed to do refcnting of bpf program to make sure that program doesn't get freed while the timer is armed. This approach relies on "user refcnt" scheme used in prog_array that stores bpf programs for bpf_tail_call. The bpf_timer_set_callback() will increment the prog refcnt which is paired with bpf_timer_cancel() that will drop the prog refcnt. The ops->map_release_uref is responsible for cancelling the timers and dropping prog refcnt when user space reference to a map reaches zero.
This uref approach is done to make sure that Ctrl-C of user space process will not leave timers running forever unless the user space explicitly pinned a map that contained timers in bpffs.
bpf_timer_init() and bpf_timer_set_callback() will return -EPERM if map doesn't have user references (is not held by open file descriptor from user space and not pinned in bpffs).
The bpf_map_delete_elem() and bpf_map_update_elem() operations cancel and free the timer if given map element had it allocated. "bpftool map update" command can be used to cancel timers.
The 'struct bpf_timer' is explicitly __attribute__((aligned(8))) because '__u64 :64' has 1 byte alignment of 8 byte padding.
--- include/linux/bpf.h | 3 + include/uapi/linux/bpf.h | 73 ++++++++ kernel/bpf/helpers.c | 324 +++++++++++++++++++++++++++++++++ kernel/bpf/verifier.c | 109 +++++++++++ kernel/trace/bpf_trace.c | 2 +- scripts/bpf_doc.py | 2 + tools/include/uapi/linux/bpf.h | 73 ++++++++ 7 files changed, 585 insertions(+), 1 deletion(-)
include/linux/bpf.h +3 -0
@@ -168,6 +168,7 @@ struct bpf_map {u32 max_entries;u32 map_flags;int spin_lock_off;/* >=0 valid offset, <0 error */ +int timer_off;/* >=0 valid offset, <0 error */ u32 id;int numa_node;u32 btf_key_type_id;
@@ -221,6 +222,7 @@ static inline void copy_map_value(struct bpf_map *map, void *dst, void *src) }void copy_map_value_locked (struct bpf_map *map,void *dst,void *src,bool lock_src); +void bpf_timer_cancel_and_free (void *timer);int bpf_obj_name_cpy (char *dst,const char *src,unsigned int size);struct bpf_offload_dev ;
@@ -314,6 +316,7 @@ enum bpf_arg_type {ARG_PTR_TO_FUNC ,/* pointer to a bpf program function */ ARG_PTR_TO_STACK_OR_NULL ,/* pointer to stack or NULL */ ARG_PTR_TO_CONST_STR ,/* pointer to a null terminated read-only string */ +ARG_PTR_TO_TIMER ,/* pointer to bpf_timer */ __BPF_ARG_TYPE_MAX, };
include/uapi/linux/bpf.h +73 -0
91 lines not on this page · raw message
kernel/bpf/helpers.c +324 -0
336 lines not on this page · raw message
kernel/bpf/verifier.c +109 -0
157 lines not on this page · raw message
kernel/trace/bpf_trace.c +1 -1
@@ -1059,7 +1059,7 @@ bpf_tracing_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)case BPF_FUNC_snprintf:return &bpf_snprintf_proto;default : -return NULL ; +return bpf_base_func_proto (func_id); } }
scripts/bpf_doc.py +2 -0
@@ -547,6 +547,7 @@ COMMANDS 'struct inode', 'struct socket', 'struct file', + 'struct bpf_timer', ] known_types = { '...',
@@ -594,6 +595,7 @@ COMMANDS 'struct inode', 'struct socket', 'struct file', + 'struct bpf_timer', } mapped_types = { 'u8': '__u8',
tools/include/uapi/linux/bpf.h +73 -0
91 lines not on this page · raw message
Signature · 1 line
2.30.2
PATCH v7 4/11 bpf: Add map side support for bpf timers.
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
Restrict bpf timers to array, hash (both preallocated and kmalloced), and lru map types. The per-cpu maps with timers don't make sense, since 'struct bpf_timer' is a part of map value. bpf timers in per-cpu maps would mean that the number of timers depends on number of possible cpus and timers would not be accessible from all cpus. lpm map support can be added in the future. The timers in inner maps are supported.
The bpf_map_update/delete_elem() helpers and sys_bpf commands cancel and free bpf_timer in a given map element.
Similar to 'struct bpf_spin_lock' BTF is required and it is used to validate that map element indeed contains 'struct bpf_timer'.
Make check_and_init_map_value() init both bpf_spin_lock and bpf_timer when map element data is reused in preallocated htab and lru maps.
Teach copy_map_value() to support both bpf_spin_lock and bpf_timer in a single map element. There could be one of each, but not more than one. Due to 'one bpf_timer in one element' restriction do not support timers in global data, since global data is a map of single element, but from bpf program side it's seen as many global variables and restriction of single global timer would be odd. The sys_bpf map_freeze and sys_mmap syscalls are not allowed on maps with timers, since user space could have corrupted mmap element and crashed the kernel. The maps with timers cannot be readonly. Due to these restrictions search for bpf_timer in datasec BTF in case it was placed in the global data to report clear error.
The previous patch allowed 'struct bpf_timer' as a first field in a map element only. Relax this restriction.
Refactor lru map to s/bpf_lru_push_free/htab_lru_push_free/ to cancel and free the timer when lru map deletes an element as a part of it eviction algorithm.
Make sure that bpf program cannot access 'struct bpf_timer' via direct load/store. The timer operation are done through helpers only.
This is similar to 'struct bpf_spin_lock'.
--- include/linux/bpf.h | 44 ++++++++++++---- include/linux/btf.h | 1 + kernel/bpf/arraymap.c | 21 ++++++++ kernel/bpf/btf.c | 77 ++++++++++++++++++++++----- kernel/bpf/hashtab.c | 105 ++++++++++++++++++++++++++++++++----- kernel/bpf/local_storage.c | 4 +- kernel/bpf/map_in_map.c | 2 + kernel/bpf/syscall.c | 21 ++++++-- kernel/bpf/verifier.c | 30 +++++++++-- 9 files changed, 259 insertions(+), 46 deletions(-)
include/linux/bpf.h +33 -11
@@ -198,24 +198,46 @@ static inline bool map_value_has_spin_lock(const struct bpf_map *map)return map->spin_lock_off >=0 ; } -static inline void check_and_init_map_lock (struct bpf_map *map,void *dst) +static inline bool map_value_has_timer (const struct bpf_map *map) { -if (likely (!map_value_has_spin_lock (map))) -return ; - *(struct bpf_spin_lock *)(dst + map->spin_lock_off) = - (struct bpf_spin_lock ){}; +return map->timer_off >=0 ; } -/* copy everything but bpf_spin_lock */ +static inline void check_and_init_map_value (struct bpf_map *map,void *dst) +{ +if (unlikely (map_value_has_spin_lock (map))) + *(struct bpf_spin_lock *)(dst + map->spin_lock_off) = + (struct bpf_spin_lock ){}; +if (unlikely (map_value_has_timer (map))) + *(struct bpf_timer *)(dst + map->timer_off) = + (struct bpf_timer ){}; +} + +/* copy everything but bpf_spin_lock and bpf_timer. There could be one of each. */ static inline void copy_map_value (struct bpf_map *map,void *dst,void *src) { +u32 s_off =0 , s_sz =0 , t_off =0 , t_sz =0 ; +if (unlikely (map_value_has_spin_lock (map))) { -u32 off = map->spin_lock_off; + s_off = map->spin_lock_off; + s_sz =sizeof (struct bpf_spin_lock ); + }else if (unlikely (map_value_has_timer (map))) { + t_off = map->timer_off; + t_sz =sizeof (struct bpf_timer ); + } -memcpy (dst, src, off); -memcpy (dst + off +sizeof (struct bpf_spin_lock ), - src + off +sizeof (struct bpf_spin_lock ), - map->value_size - off -sizeof (struct bpf_spin_lock )); +if (unlikely (s_sz || t_sz)) { +if (s_off < t_off || !s_sz) { +swap (s_off, t_off); +swap (s_sz, t_sz); + } +memcpy (dst, src, t_off); +memcpy (dst + t_off + t_sz, + src + t_off + t_sz, + s_off - t_off - t_sz); +memcpy (dst + s_off + s_sz, + src + s_off + s_sz, + map->value_size - s_off - s_sz); }else {memcpy (dst, src, map->value_size); }
include/linux/btf.h +1 -0
@@ -99,6 +99,7 @@ bool btf_member_is_reg_int(const struct btf *btf, const struct btf_type *s,const struct btf_member *m, u32 expected_offset, u32 expected_size);int btf_find_spin_lock (const struct btf *btf,const struct btf_type *t); +int btf_find_timer (const struct btf *btf,const struct btf_type *t);bool btf_type_is_void (const struct btf_type *t);s32 btf_find_by_name_kind (const struct btf *btf,const char *name,u8 kind); const struct btf_type *btf_type_skip_modifiers(const struct btf *btf,
kernel/bpf/arraymap.c +21 -0
@@ -287,6 +287,12 @@ static int array_map_get_next_key(struct bpf_map *map, void *key, void *next_keyreturn 0 ; } +static void check_and_free_timer_in_array (struct bpf_array *arr,void *val) +{ +if (unlikely (map_value_has_timer (&arr->map))) +bpf_timer_cancel_and_free (val + arr->map.timer_off); +} +/* Called from syscall or from eBPF program */ static int array_map_update_elem (struct bpf_map *map,void *key,void *value,u64 map_flags)
@@ -321,6 +327,7 @@ static int array_map_update_elem(struct bpf_map *map, void *key, void *value,copy_map_value_locked (map, val, value, false); elsecopy_map_value (map ,val ,value ); +check_and_free_timer_in_array (array, val); }return 0 ; }
@@ -374,6 +381,19 @@ static void *array_map_vmalloc_addr(struct bpf_array *array)return (void *)round_down ((unsigned long )array,PAGE_SIZE ); } +static void array_map_free_timers (struct bpf_map *map) +{ + struct bpf_array *array = container_of(map, struct bpf_array, map); +int i; + +if (likely (!map_value_has_timer (map))) +return ; + +for (i =0 ; i < array->map.max_entries; i++) +bpf_timer_cancel_and_free (array->value + array->elem_size * i + + map->timer_off); +} +/* Called when map->refcnt goes to zero, either from workqueue or from syscall */ static void array_map_free (struct bpf_map *map) {
@@ -668,6 +688,7 @@ const struct bpf_map_ops array_map_ops = { .map_alloc = array_map_alloc, .map_free = array_map_free, .map_get_next_key = array_map_get_next_key, + .map_release_uref = array_map_free_timers, .map_lookup_elem = array_map_lookup_elem, .map_update_elem = array_map_update_elem, .map_delete_elem = array_map_delete_elem,
kernel/bpf/btf.c +63 -14
106 lines not on this page · raw message
kernel/bpf/hashtab.c +93 -12
227 lines not on this page · raw message
kernel/bpf/local_storage.c +2 -2
@@ -173,7 +173,7 @@ static int cgroup_storage_update_elem(struct bpf_map *map, void *key,return -ENOMEM ;memcpy (&new->data[0 ], value, map->value_size); -check_and_init_map_lock (map, new->data); +check_and_init_map_value (map, new->data); new =xchg (&storage->buf, new);kfree_rcu (new, rcu);
@@ -509,7 +509,7 @@ struct bpf_cgroup_storage *bpf_cgroup_storage_alloc(struct bpf_prog *prog, map->numa_node);if (!storage->buf) goto enomem; -check_and_init_map_lock (map, storage->buf->data); +check_and_init_map_value (map, storage->buf->data); }else { storage->percpu_buf =bpf_map_alloc_percpu (map, size,8 , gfp);if (!storage->percpu_buf)
kernel/bpf/map_in_map.c +2 -0
@@ -50,6 +50,7 @@ struct bpf_map *bpf_map_meta_alloc(int inner_map_ufd) inner_map_meta->map_flags = inner_map->map_flags; inner_map_meta->max_entries = inner_map->max_entries; inner_map_meta->spin_lock_off = inner_map->spin_lock_off; + inner_map_meta->timer_off = inner_map->timer_off;/* Misc members not needed in bpf_map_meta_equal() check. */ inner_map_meta->ops = inner_map->ops;
@@ -75,6 +76,7 @@ bool bpf_map_meta_equal(const struct bpf_map *meta0,return meta0->map_type == meta1->map_type && meta0->key_size == meta1->key_size && meta0->value_size == meta1->value_size && + meta0->timer_off == meta1->timer_off && meta0->map_flags == meta1->map_flags; }
kernel/bpf/syscall.c +17 -4
@@ -260,8 +260,8 @@ static int bpf_map_copy_value(struct bpf_map *map, void *key, void *value,copy_map_value_locked (map, value, ptr, true); elsecopy_map_value (map ,value ,ptr ); -/* mask lock, since value wasn't zero inited */ -check_and_init_map_lock (map, value); +/* mask lock and timer, since value wasn't zero inited */ +check_and_init_map_value (map, value); }rcu_read_unlock (); }
@@ -623,7 +623,8 @@ static int bpf_map_mmap(struct file *filp, struct vm_area_struct *vma)struct bpf_map *map = filp->private_data;int err; -if (!map->ops->map_mmap ||map_value_has_spin_lock (map)) +if (!map->ops->map_mmap ||map_value_has_spin_lock (map) || +map_value_has_timer (map))return -ENOTSUPP ;if (!(vma->vm_flags &VM_SHARED ))
@@ -793,6 +794,16 @@ static int map_check_btf(struct bpf_map *map, const struct btf *btf, } } + map->timer_off =btf_find_timer (btf, value_type); +if (map_value_has_timer (map)) { +if (map->map_flags &BPF_F_RDONLY_PROG ) +return -EACCES ; +if (map->map_type !=BPF_MAP_TYPE_HASH && + map->map_type !=BPF_MAP_TYPE_LRU_HASH && + map->map_type !=BPF_MAP_TYPE_ARRAY ) +return -EOPNOTSUPP ; + } +if (map->ops->map_check_btf) ret = map->ops->map_check_btf (map, btf, key_type, value_type);
@@ -844,6 +855,7 @@ static int map_create(union bpf_attr *attr)mutex_init (&map->freeze_mutex); map->spin_lock_off = -EINVAL ; + map->timer_off = -EINVAL ; if (attr->btf_key_type_id || attr->btf_value_type_id ||/* Even the map's value is a kernel's struct, * the bpf_prog.o must have BTF to begin with
@@ -1591,7 +1603,8 @@ static int map_freeze(const union bpf_attr *attr)if (IS_ERR (map))return PTR_ERR (map); -if (map->map_type ==BPF_MAP_TYPE_STRUCT_OPS ) { +if (map->map_type ==BPF_MAP_TYPE_STRUCT_OPS || +map_value_has_timer (map)) {fdput (f);return -ENOTSUPP ; }
kernel/bpf/verifier.c +27 -3
@@ -3241,6 +3241,15 @@ static int check_map_access(struct bpf_verifier_env *env, u32 regno,return -EACCES ; } } +if (map_value_has_timer (map)) { +u32 t = map->timer_off; + +if (reg->smin_value + off < t +sizeof (struct bpf_timer ) && + t < reg->umax_value + off + size) { +verbose (env,"bpf_timer cannot be accessed directly by load/store\n" ); +return -EACCES ; + } + }return err; }
@@ -4675,9 +4684,24 @@ static int process_timer_func(struct bpf_verifier_env *env, int regno, map->name);return -EINVAL ; } -if (val) { -/* This restriction will be removed in the next patch */ -verbose (env,"bpf_timer field can only be first in the map value element\n" ); +if (!map_value_has_timer (map)) { +if (map->timer_off == -E2BIG ) +verbose (env, +"map '%s' has more than one 'struct bpf_timer'\n" , + map->name); +else if (map->timer_off == -ENOENT ) +verbose (env, +"map '%s' doesn't have 'struct bpf_timer'\n" , + map->name); +else +verbose (env, +"map '%s' is not a struct type or bpf_timer is mangled\n" , + map->name); +return -EINVAL ; + } +if (map->timer_off != val + reg->off) { +verbose (env,"off %lld doesn't point to 'struct bpf_timer' that is at %d\n" , + val + reg->off, map->timer_off);return -EINVAL ; }if (meta->map_ptr) {
Signature · 1 line
2.30.2
PATCH v7 5/11 bpf: Prevent pointer mismatch in bpf_timer_init.
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
bpf_timer_init() arguments are:
1. pointer to a timer (which is embedded in map element).
2. pointer to a map.
Make sure that pointer to a timer actually belongs to that map.
Use map_uid (which is unique id of inner map) to reject:inner_map1 = bpf_map_lookup_elem(outer_map, key1) inner_map2 = bpf_map_lookup_elem(outer_map, key2)
if (inner_map1 && inner_map2) {
timer = bpf_map_lookup_elem(inner_map1);
if (timer)
// mismatch would have been allowed
bpf_timer_init(timer, inner_map2);
}--- include/linux/bpf_verifier.h | 9 ++++++++- kernel/bpf/verifier.c | 31 ++++++++++++++++++++++++++++--- 2 files changed, 36 insertions(+), 4 deletions(-)
include/linux/bpf_verifier.h +8 -1
@@ -53,7 +53,14 @@ struct bpf_reg_state {/* valid when type == CONST_PTR_TO_MAP | PTR_TO_MAP_VALUE | * PTR_TO_MAP_VALUE_OR_NULL */ -struct bpf_map *map_ptr; +struct { +struct bpf_map *map_ptr; +/* To distinguish map lookups from outer map +* the map_uid is non-zero for registers +* pointing to inner maps. +*/ +u32 map_uid; + };/* for PTR_TO_BTF_ID */ struct {
kernel/bpf/verifier.c +28 -3
@@ -255,6 +255,7 @@ struct bpf_call_arg_meta {int mem_size;u64 msize_max_value;int ref_obj_id; +int map_uid;int func_id;struct btf *btf;u32 btf_id;
@@ -1135,6 +1136,10 @@ static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)if (map->inner_map_meta) { reg->type =CONST_PTR_TO_MAP ; reg->map_ptr = map->inner_map_meta; +/* transfer reg's id which is unique for every map_lookup_elem +* as UID of the inner map. +*/ + reg->map_uid = reg->id; }else if (map->map_type ==BPF_MAP_TYPE_XSKMAP ) { reg->type =PTR_TO_XDP_SOCK ; } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
@@ -4708,6 +4713,7 @@ static int process_timer_func(struct bpf_verifier_env *env, int regno,verbose (env,"verifier bug. Two map pointers in a timer helper\n" );return -EFAULT ; } + meta->map_uid = reg->map_uid; meta->map_ptr = map;return 0 ; }
@@ -5006,11 +5012,29 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 arg,if (arg_type ==ARG_CONST_MAP_PTR ) {/* bpf_map_xxx(map_ptr) call: remember that map_ptr */ -if (meta->map_ptr && meta->map_ptr != reg->map_ptr) { -verbose (env,"Map pointer doesn't match bpf_timer.\n" ); -return -EINVAL ; +if (meta->map_ptr) { +/* Use map_uid (which is unique id of inner map) to reject: +* inner_map1 = bpf_map_lookup_elem(outer_map, key1) +* inner_map2 = bpf_map_lookup_elem(outer_map, key2) +* if (inner_map1 && inner_map2) { +* timer = bpf_map_lookup_elem(inner_map1); +* if (timer) +* // mismatch would have been allowed +* bpf_timer_init(timer, inner_map2); +* } +* +* Comparing map_ptr is enough to distinguish normal and outer maps. +*/ +if (meta->map_ptr != reg->map_ptr || + meta->map_uid != reg->map_uid) { +verbose (env, +"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n" , + meta->map_uid, reg->map_uid); +return -EINVAL ; + } } meta->map_ptr = reg->map_ptr; + meta->map_uid = reg->map_uid; }else if (arg_type ==ARG_PTR_TO_MAP_KEY ) {/* bpf_map_xxx(..., map_ptr, ..., key) call: * check that [key, key + map->key_size) are within
@@ -6204,6 +6228,7 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insnreturn -EINVAL ; } regs[BPF_REG_0 ].map_ptr = meta.map_ptr; + regs[BPF_REG_0 ].map_uid = meta.map_uid;if (fn->ret_type ==RET_PTR_TO_MAP_VALUE ) { regs[BPF_REG_0 ].type =PTR_TO_MAP_VALUE ;if (map_value_has_spin_lock (meta.map_ptr))
Signature · 1 line
2.30.2
PATCH v7 6/11 bpf: Remember BTF of inner maps.
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
BTF is required for 'struct bpf_timer' to be recognized inside map value. The bpf timers are supported inside inner maps.
Remember 'struct btf *' in inner_map_meta to make it available to the verifier in the sequence:
struct bpf_map *inner_map = bpf_map_lookup_elem(&outer_map, ...); if (inner_map)
timer = bpf_map_lookup_elem(&inner_map, ...);
--- kernel/bpf/map_in_map.c | 6 ++++++ 1 file changed, 6 insertions(+)
kernel/bpf/map_in_map.c +6 -0
@@ -3,6 +3,7 @@*/ #include <linux/slab.h> #include <linux/bpf.h> +#include <linux/btf.h> #include "map_in_map.h"
@@ -51,6 +52,10 @@ struct bpf_map *bpf_map_meta_alloc(int inner_map_ufd) inner_map_meta->max_entries = inner_map->max_entries; inner_map_meta->spin_lock_off = inner_map->spin_lock_off; inner_map_meta->timer_off = inner_map->timer_off; +if (inner_map->btf) { +btf_get (inner_map->btf); + inner_map_meta->btf = inner_map->btf; + }/* Misc members not needed in bpf_map_meta_equal() check. */ inner_map_meta->ops = inner_map->ops;
@@ -66,6 +71,7 @@ struct bpf_map *bpf_map_meta_alloc(int inner_map_ufd)void bpf_map_meta_free (struct bpf_map *map_meta) { +btf_put (map_meta->btf);kfree (map_meta); }
Signature · 1 line
2.30.2
PATCH v7 7/11 bpf: Relax verifier recursion check.
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
In the following bpf subprogram:
static int timer_cb(void *map, void *key, void *value)
{
bpf_timer_set_callback(.., timer_cb);
}the 'timer_cb' is a pointer to a function. ld_imm64 insn is used to carry this pointer. bpf_pseudo_func() returns true for such ld_imm64 insn.
Unlike bpf_for_each_map_elem() the bpf_timer_set_callback() is asynchronous. Relax control flow check to allow such "recursion" that is seen as an infinite loop by check_cfg(). The distinction between bpf_for_each_map_elem() the bpf_timer_set_callback() is done in the follow up patch.
--- kernel/bpf/verifier.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
kernel/bpf/verifier.c +6 -2
@@ -9463,8 +9463,12 @@ static int visit_func_call_insn(int t, int insn_cnt,init_explored_state (env, t +1 );if (visit_callee) {init_explored_state (env, t); - ret =push_insn (t, t + insns[t].imm +1 ,BRANCH , - env, false); + ret =push_insn (t, t + insns[t].imm +1 ,BRANCH , env, +/* It's ok to allow recursion from CFG point of +* view. __check_func_call() will do the actual +* check. +*/ +bpf_pseudo_func (insns + t)); }return ret; }
Signature · 1 line
2.30.2
PATCH v7 8/11 bpf: Implement verifier support for validation of async callbacks.
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
bpf_for_each_map_elem() and bpf_timer_set_callback() helpers are relying on PTR_TO_FUNC infra in the verifier to validate addresses to subprograms and pass them into the helpers as function callbacks.
In case of bpf_for_each_map_elem() the callback is invoked synchronously and the verifier treats it as a normal subprogram call by adding another bpf_func_state and new frame in __check_func_call(). bpf_timer_set_callback() doesn't invoke the callback directly. The subprogram will be called asynchronously from bpf_timer_cb(). Teach the verifier to validate such async callbacks as special kind of jump by pushing verifier state into stack and let pop_stack() process it.
Special care needs to be taken during state pruning.
The call insn doing bpf_timer_set_callback has to be a prune_point. Otherwise short timer callbacks might not have prune points in front of bpf_timer_set_callback() which means is_state_visited() will be called after this call insn is processed in __check_func_call(). Which means that another async_cb state will be pushed to be walked later and the verifier will eventually hit BPF_COMPLEXITY_LIMIT_JMP_SEQ limit.
Since push_async_cb() looks like another push_stack() branch the infinite loop detection will trigger false positive. To recognize this case mark such states as in_async_callback_fn.
To distinguish infinite loop in async callback vs the same callback called with different arguments for different map and timer add async_entry_cnt to bpf_func_state.
Enforce return zero from async callbacks.
--- include/linux/bpf_verifier.h | 9 ++- kernel/bpf/helpers.c | 8 +-- kernel/bpf/verifier.c | 123 ++++++++++++++++++++++++++++++++++- 3 files changed, 131 insertions(+), 9 deletions(-)
include/linux/bpf_verifier.h +8 -1
@@ -208,12 +208,19 @@ struct bpf_func_state {* zero == main subprog */ u32 subprogno; +/* Every bpf_timer_start will increment async_entry_cnt. +* It's used to distinguish: +* void foo(void) { for(;;); } +* void foo(void) { bpf_timer_set_callback(,foo); } +*/ +u32 async_entry_cnt; +bool in_callback_fn; +bool in_async_callback_fn;/* The following fields should be last. See copy_func_state() */ int acquired_refs;struct bpf_reference_state *refs;int allocated_stack; -bool in_callback_fn;struct bpf_stack_state *stack; };
kernel/bpf/helpers.c +3 -5
@@ -1043,7 +1043,6 @@ static enum hrtimer_restart bpf_timer_cb(struct hrtimer *hrtimer)void *callback_fn;void *key;u32 idx; -int ret; callback_fn =rcu_dereference_check (t->callback_fn,rcu_read_lock_bh_held ());if (!callback_fn)
@@ -1066,10 +1065,9 @@ static enum hrtimer_restart bpf_timer_cb(struct hrtimer *hrtimer) key = value -round_up (map->key_size,8 ); } - ret =BPF_CAST_CALL (callback_fn)((u64 )(long )map, - (u64 )(long )key, - (u64 )(long )value,0 ,0 ); -WARN_ON (ret !=0 );/* Next patch moves this check into the verifier */ +BPF_CAST_CALL (callback_fn)((u64 )(long )map, (u64 )(long )key, + (u64 )(long )value,0 ,0 ); +/* The verifier checked that return value is zero. */ this_cpu_write (hrtimer_running,NULL ); out:
kernel/bpf/verifier.c +120 -3
172 lines not on this page · raw message
Signature · 1 line
2.30.2
Re: [PATCH v7 bpf-next 08/11] bpf: Implement verifier support for validation of async callbacks.
I ran into a problem due to this patch. Specifically, the test in the __check_func_call() function is flaweed because it can actually mis-interpret a regular BPF-to-BPF pseudo-call as a callback call.
Consider the conditional in the code:
if (insn->code == (BPF_JMP | BPF_CALL) &&
insn->imm == BPF_FUNC_timer_set_callback) {The BPF_FUNC_timer_set_callback has value 170. This means that if you have a BPF program that contains a pseudo-call with an instruction delta of 170, this conditional will be found to be true by the verifier, and it will interpret the pseudo-call as a callback. This leads to a mess with the verification of the program because it makes the wrong assumptions about the nature of this call.
As far as I can see, the solution is simple. Include an explicit check to ensure that src_reg is not a pseudo-call. I.e. make the conditional:
if (insn->code == (BPF_JMP | BPF_CALL) &&
insn->src_reg != BPF_PSEUDO_CALL &&
insn->imm == BPF_FUNC_timer_set_callback) {It is of course a pretty rare case that this would go wrong, but since my code makes extensive use of BPF-to-BPF pseudo-calls, it was only a matter of time before I would run into a call with instruction delta 170.
Kris
Quoted 274 lines · Alexei Starovoitov
From: Alexei Starovoitov <[email protected]>
bpf_for_each_map_elem()andbpf_timer_set_callback()helpers are relying onPTR_TO_FUNCinfra in the verifier to validate addresses to subprograms and pass them into the helpers as function callbacks.
In case ofbpf_for_each_map_elem()the callback is invoked synchronously and the verifier treats it as a normal subprogram call by adding anotherbpf_func_stateand new frame in__check_func_call().bpf_timer_set_callback()doesn't invoke the callback directly. The subprogram will be called asynchronously frombpf_timer_cb(). Teach the verifier to validate such async callbacks as special kind of jump by pushing verifier state into stack and letpop_stack()process it.Special care needs to be taken during state pruning.
The call insn doingbpf_timer_set_callbackhas to be aprune_point. Otherwise short timer callbacks might not have prune points in front ofbpf_timer_set_callback()which meansis_state_visited()will be called after this call insn is processed in__check_func_call(). Which means that anotherasync_cbstate will be pushed to be walked later and the verifier will eventually hitBPF_COMPLEXITY_LIMIT_JMP_SEQlimit.
Sincepush_async_cb()looks like anotherpush_stack()branch the infinite loop detection will trigger false positive. To recognize this case mark such states asin_async_callback_fn.
To distinguish infinite loop in async callback vs the same callback called with different arguments for different map and timer addasync_entry_cnttobpf_func_state.Enforce return zero from async callbacks.
Signed-off-by Alexei Starovoitov <[email protected]>Acked-by Andrii Nakryiko <[email protected]>--- include/linux/bpf_verifier.h | 9 ++- kernel/bpf/helpers.c | 8 +-- kernel/bpf/verifier.c | 123 ++++++++++++++++++++++++++++++++++- 3 files changed, 131 insertions(+), 9 deletions(-)include/linux/bpf_verifier.h +8
-1@@ -208,12 +208,19 @@ struct bpf_func_state {* zero == main subprog */ u32 subprogno; +/* Every bpf_timer_start will increment async_entry_cnt. +* It's used to distinguish: +* void foo(void) { for(;;); } +* void foo(void) { bpf_timer_set_callback(,foo); } +*/ +u32 async_entry_cnt; +bool in_callback_fn; +bool in_async_callback_fn;/* The following fields should be last. See copy_func_state() */ int acquired_refs;struct bpf_reference_state *refs;int allocated_stack; -bool in_callback_fn;struct bpf_stack_state *stack; };kernel/bpf/helpers.c +3
-5@@ -1043,7 +1043,6 @@ static enum hrtimer_restart bpf_timer_cb(struct hrtimer *hrtimer)void *callback_fn;void *key;u32 idx; -int ret; callback_fn =rcu_dereference_check (t->callback_fn,rcu_read_lock_bh_held ());if (!callback_fn)@@ -1066,10 +1065,9 @@ static enum hrtimer_restart bpf_timer_cb(struct hrtimer *hrtimer) key = value -round_up (map->key_size,8 ); } - ret =BPF_CAST_CALL (callback_fn)((u64 )(long )map, - (u64 )(long )key, - (u64 )(long )value,0 ,0 ); -WARN_ON (ret !=0 );/* Next patch moves this check into the verifier */ +BPF_CAST_CALL (callback_fn)((u64 )(long )map, (u64 )(long )key, + (u64 )(long )value,0 ,0 ); +/* The verifier checked that return value is zero. */ this_cpu_write (hrtimer_running,NULL ); out:kernel/bpf/verifier.c +120
-3@@ -735,6 +735,10 @@ static void print_verifier_state(struct bpf_verifier_env *env,if (state->refs[i].id)verbose (env,",%d" , state->refs[i].id); } +if (state->in_callback_fn) +verbose (env," cb" ); +if (state->in_async_callback_fn) +verbose (env," async_cb" );verbose (env,"\n" ); }@@ -1527,6 +1531,54 @@ static void init_func_state(struct bpf_verifier_env *env,init_reg_state (env, state); } +/* Similar to push_stack(), but for async callbacks */ +static struct bpf_verifier_state *push_async_cb (struct bpf_verifier_env *env, +int insn_idx,int prev_insn_idx, +int subprog) +{ +struct bpf_verifier_stack_elem *elem; +struct bpf_func_state *frame; + + elem =kzalloc (sizeof (struct bpf_verifier_stack_elem ),GFP_KERNEL ); +if (!elem) + goto err; + + elem->insn_idx = insn_idx; + elem->prev_insn_idx = prev_insn_idx; + elem->next = env->head; + elem->log_pos = env->log.len_used; + env->head = elem; + env->stack_size++; +if (env->stack_size >BPF_COMPLEXITY_LIMIT_JMP_SEQ ) { +verbose (env, +"The sequence of %d jumps is too complex for async cb.\n" , + env->stack_size); + goto err; + } +/* Unlike push_stack() do not copy_verifier_state(). +* The caller state doesn't matter. +* This is async callback. It starts in a fresh stack. +* Initialize it similar to do_check_common(). +*/ + elem->st.branches =1 ; + frame =kzalloc (sizeof (*frame),GFP_KERNEL ); +if (!frame) + goto err; +init_func_state (env, frame, +BPF_MAIN_FUNC /* callsite */ , +0 /* frameno within this callchain */ , + subprog/* subprog number within this prog */ ); + elem->st.frame[0 ] = frame; +return &elem->st; +err: +free_verifier_state (env->cur_state, true); + env->cur_state =NULL ; +/* pop all elements and return */ +while (!pop_stack (env,NULL ,NULL , false)); +return NULL ; +} + +enum reg_arg_type {SRC_OP ,/* register is used as source operand */ DST_OP ,/* register is used as destination operand */ @@ -5704,6 +5756,30 @@ static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn } } +if (insn->code == (BPF_JMP |BPF_CALL ) && + insn->imm == BPF_FUNC_timer_set_callback) { +struct bpf_verifier_state *async_cb; + +/* there is no real recursion here. timer callbacks are async */ + async_cb =push_async_cb (env, env->subprog_info[subprog].start, + *insn_idx, subprog); +if (!async_cb) +return -EFAULT ; + callee = async_cb->frame[0 ]; + callee->async_entry_cnt = caller->async_entry_cnt +1 ; + +/* Convert bpf_timer_set_callback() args into timer callback args */ + err =set_callee_state_cb (env, caller, callee, *insn_idx); +if (err) +return err; + +clear_caller_saved_regs (env, caller->regs); +mark_reg_unknown (env, caller->regs,BPF_REG_0 ); + caller->regs[BPF_REG_0 ].subreg_def =DEF_NOT_SUBREG ; +/* continue with next insn after call */ +return 0 ; + } + callee =kzalloc (sizeof (*callee),GFP_KERNEL );if (!callee)return -ENOMEM ;@@ -5856,6 +5932,7 @@ static int set_timer_callback_state(struct bpf_verifier_env *env,/* unused */ __mark_reg_not_init (env, &callee->regs[BPF_REG_4 ]);__mark_reg_not_init (env, &callee->regs[BPF_REG_5 ]); + callee->in_async_callback_fn = true;return 0 ; }@@ -9224,7 +9301,8 @@ static int check_return_code(struct bpf_verifier_env *env)struct tnum range =tnum_range (0 ,1 );enum bpf_prog_type prog_type =resolve_prog_type (env->prog);int err; -const bool is_subprog = env->cur_state->frame[0 ]->subprogno; +struct bpf_func_state *frame = env->cur_state->frame[0 ]; +const bool is_subprog = frame->subprogno;/* LSM and struct_ops func-ptr's return type could be "void" */ if (!is_subprog &&@@ -9249,6 +9327,22 @@ static int check_return_code(struct bpf_verifier_env *env) } reg =cur_regs (env) +BPF_REG_0 ; + +if (frame->in_async_callback_fn) { +/* enforce return zero from async callbacks like timer */ +if (reg->type !=SCALAR_VALUE ) { +verbose (env,"In async callback the register R0 is not a known value (%s)\n" , + reg_type_str[reg->type]); +return -EINVAL ; + } + +if (!tnum_in (tnum_const (0 ), reg->var_off)) { +verbose_invalid_scalar (env, reg, &range,"async callback" ,"R0" ); +return -EINVAL ; + } +return 0 ; + } +if (is_subprog) {if (reg->type !=SCALAR_VALUE ) { verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",@@ -9496,6 +9590,13 @@ static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)return DONE_EXPLORING ;case BPF_CALL : +if (insns[t].imm == BPF_FUNC_timer_set_callback) +/* Mark this call insn to trigger is_state_visited() check +* before call itself is processed by __check_func_call(). +* Otherwise new async state will be pushed for further +* exploration. +*/ +init_explored_state (env, t);return visit_func_call_insn (t, insn_cnt, insns, env, insns[t].src_reg ==BPF_PSEUDO_CALL );@@ -10503,9 +10604,25 @@ static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) states_cnt++;if (sl->state.insn_idx != insn_idx) goto next; +if (sl->state.branches) { -if (states_maybe_looping (&sl->state, cur) && -states_equal (env, &sl->state, cur)) { +struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; + +if (frame->in_async_callback_fn && + frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { +/* Different async_entry_cnt means that the verifier is +* processing another entry into async callback. +* Seeing the same state is not an indication of infinite +* loop or infinite recursion. +* But finding the same state doesn't mean that it's safe +* to stop processing the current state. The previous state +* hasn't yet reached bpf_exit, since state.branches > 0. +* Checking in_async_callback_fn alone is not enough either. +* Since the verifier still needs to catch infinite loops +* inside async callbacks. +*/ + }else if (states_maybe_looping (&sl->state, cur) && +states_equal (env, &sl->state, cur)) {verbose_linfo (env, insn_idx,"; " );verbose (env,"infinite loop detected at insn %d\n" , insn_idx);return -EINVAL ;Signature · 1 line
2.30.2
Re: [PATCH v7 bpf-next 08/11] bpf: Implement verifier support for validation of async callbacks.
Quoted 20 lines · Kris Van Hees
I ran into a problem due to this patch. Specifically, the test in the
__check_func_call()function is flaweed because it can actually mis-interpret a regular BPF-to-BPF pseudo-call as a callback call.Consider the conditional in the code:
if (insn->code == (BPF_JMP | BPF_CALL) && insn->imm == BPF_FUNC_timer_set_callback) {The
BPF_FUNC_timer_set_callbackhas value 170. This means that if you have a BPF program that contains a pseudo-call with an instruction delta of 170, this conditional will be found to be true by the verifier, and it will interpret the pseudo-call as a callback. This leads to a mess with the verification of the program because it makes the wrong assumptions about the nature of this call.As far as I can see, the solution is simple. Include an explicit check to ensure that
src_regis not a pseudo-call. I.e. make the conditional:
Quoted 7 lines
if (insn->code == (BPF_JMP | BPF_CALL) && insn->src_reg != BPF_PSEUDO_CALL && insn->imm == BPF_FUNC_timer_set_callback) {It is of course a pretty rare case that this would go wrong, but since my code makes extensive use of BPF-to-BPF pseudo-calls, it was only a matter of time before I would run into a call with instruction delta 170.
Great catch. All makes sense.
Could you please submit an official patch ? Checking for insn->src_reg == 0 is probably better, since src_reg can be BPF_PSEUDO_KFUNC_CALL as well though __check_func_call is not called for it.
PATCH v7 9/11 bpf: Teach stack depth check about async callbacks.
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
Teach max stack depth checking algorithm about async callbacks that don't increase bpf program stack size.
Also add sanity check that bpf_tail_call didn't sneak into async cb. It's impossible, since PTR_TO_CTX is not available in async cb, hence the program cannot contain bpf_tail_call(ctx,...);
--- include/linux/bpf_verifier.h | 1 + kernel/bpf/verifier.c | 18 +++++++++++++++--- 2 files changed, 16 insertions(+), 3 deletions(-)
include/linux/bpf_verifier.h +1 -0
@@ -406,6 +406,7 @@ struct bpf_subprog_info {bool has_tail_call;bool tail_call_reachable;bool has_ld_abs; +bool is_async_cb; };/* single container for all structs
kernel/bpf/verifier.c +15 -3
@@ -3709,6 +3709,8 @@ static int check_max_stack_depth(struct bpf_verifier_env *env) continue_func: subprog_end = subprog[idx +1 ].start;for (; i < subprog_end; i++) { +int next_insn; +if (!bpf_pseudo_call (insn + i) && !bpf_pseudo_func (insn + i))continue ;/* remember insn and function to return to */
@@ -3716,13 +3718,22 @@ static int check_max_stack_depth(struct bpf_verifier_env *env) ret_prog[frame] = idx;/* find the callee */ - i = i + insn[i].imm +1 ; - idx =find_subprog (env, i); + next_insn = i + insn[i].imm +1 ; + idx =find_subprog (env, next_insn);if (idx <0 ) {WARN_ONCE (1 ,"verifier bug. No program starts at insn %d\n" , - i); + next_insn);return -EFAULT ; } +if (subprog[idx].is_async_cb) { +if (subprog[idx].has_tail_call) { +verbose (env,"verifier bug. subprog has tail_call and async cb\n" ); +return -EFAULT ; + } +/* async callbacks don't increase bpf prog stack size */ +continue ; + } + i = next_insn;if (subprog[idx].has_tail_call) tail_call_reachable = true;
@@ -5761,6 +5772,7 @@ static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insnstruct bpf_verifier_state *async_cb;/* there is no real recursion here. timer callbacks are async */ + env->subprog_info[subprog].is_async_cb = true; async_cb =push_async_cb (env, env->subprog_info[subprog].start, *insn_idx, subprog);if (!async_cb)
Signature · 1 line
2.30.2
PATCH v7 10/11 selftests/bpf: Add bpf_timer test.
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
Add bpf_timer test that creates timers in preallocated and non-preallocated hash, in array and in lru maps.
Let array timer expire once and then re-arm it for 35 seconds. Arm lru timer into the same callback.
Then arm and re-arm hash timers 10 times each.
At the last invocation of prealloc hash timer cancel the array timer. Force timer free via LRU eviction and direct bpf_map_delete_elem.
--- .../testing/selftests/bpf/prog_tests/timer.c | 55 ++++ tools/testing/selftests/bpf/progs/timer.c | 297 ++++++++++++++++++ 2 files changed, 352 insertions(+) create mode 100644 tools/testing/selftests/bpf/prog_tests/timer.c create mode 100644 tools/testing/selftests/bpf/progs/timer.c
tools/testing/selftests/bpf/prog_tests/timer.c new file +55 -0
@@ -0,0 +1,55 @@ +// SPDX-License-Identifier: GPL-2.0 +/* Copyright (c) 2021 Facebook */ +#include <test_progs.h> +#include "timer.skel.h" + +static int timer (struct timer *timer_skel) +{ +int err, prog_fd; +__u32 duration =0 , retval; + + err =timer__attach (timer_skel); +if (!ASSERT_OK (err,"timer_attach" )) +return err; + +ASSERT_EQ (timer_skel->data->callback_check,52 ,"callback_check1" ); +ASSERT_EQ (timer_skel->data->callback2_check,52 ,"callback2_check1" ); + + prog_fd =bpf_program__fd (timer_skel->progs.test1); + err =bpf_prog_test_run (prog_fd,1 ,NULL ,0 , +NULL ,NULL , &retval, &duration); +ASSERT_OK (err,"test_run" ); +ASSERT_EQ (retval,0 ,"test_run" ); +timer__detach (timer_skel); + +usleep (50 );/* 10 usecs should be enough, but give it extra */ +/* check that timer_cb1() was executed 10+10 times */ +ASSERT_EQ (timer_skel->data->callback_check,42 ,"callback_check2" ); +ASSERT_EQ (timer_skel->data->callback2_check,42 ,"callback2_check2" ); + +/* check that timer_cb2() was executed twice */ +ASSERT_EQ (timer_skel->bss->bss_data,10 ,"bss_data" ); + +/* check that there were no errors in timer execution */ +ASSERT_EQ (timer_skel->bss->err,0 ,"err" ); + +/* check that code paths completed */ +ASSERT_EQ (timer_skel->bss->ok,1 |2 |4 ,"ok" ); + +return 0 ; +} + +void test_timer (void ) +{ +struct timer *timer_skel =NULL ; +int err; + + timer_skel =timer__open_and_load (); +if (!ASSERT_OK_PTR (timer_skel,"timer_skel_load" )) + goto cleanup; + + err =timer (timer_skel); +ASSERT_OK (err,"timer" ); +cleanup: +timer__destroy (timer_skel); +}
tools/testing/selftests/bpf/progs/timer.c new file +297 -0
297 lines not on this page · raw message
Signature · 1 line
2.30.2
PATCH v7 11/11 selftests/bpf: Add a test with bpf_timer in inner map.
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
Check that map-in-map supports bpf timers.
Check that indirect "recursion" of timer callbacks works:timer_cb1() { bpf_timer_set_callback(timer_cb2); } timer_cb2() { bpf_timer_set_callback(timer_cb1); }
Check that
bpf_map_release
htab_free_prealloced_timers
bpf_timer_cancel_and_free
hrtimer_cancel
works while timer cb is running.
"while true; do ./test_progs -t timer_mim; done"
is a great stress test. It caught missing timer cancel in htab->extra_elems.
timer_mim_reject.c is a negative test that checks
that timer<->map mismatch is prevented.
--- .../selftests/bpf/prog_tests/timer_mim.c | 69 +++++++++++++++ tools/testing/selftests/bpf/progs/timer_mim.c | 88 +++++++++++++++++++ .../selftests/bpf/progs/timer_mim_reject.c | 74 ++++++++++++++++ 3 files changed, 231 insertions(+) create mode 100644 tools/testing/selftests/bpf/prog_tests/timer_mim.c create mode 100644 tools/testing/selftests/bpf/progs/timer_mim.c create mode 100644 tools/testing/selftests/bpf/progs/timer_mim_reject.c
tools/testing/selftests/bpf/prog_tests/timer_mim.c new file +69 -0
@@ -0,0 +1,69 @@ +// SPDX-License-Identifier: GPL-2.0 +/* Copyright (c) 2021 Facebook */ +#include <test_progs.h> +#include "timer_mim.skel.h" +#include "timer_mim_reject.skel.h" + +static int timer_mim (struct timer_mim *timer_skel) +{ +__u32 duration =0 , retval; +__u64 cnt1, cnt2; +int err, prog_fd, key1 =1 ; + + err =timer_mim__attach (timer_skel); +if (!ASSERT_OK (err,"timer_attach" )) +return err; + + prog_fd =bpf_program__fd (timer_skel->progs.test1); + err =bpf_prog_test_run (prog_fd,1 ,NULL ,0 , +NULL ,NULL , &retval, &duration); +ASSERT_OK (err,"test_run" ); +ASSERT_EQ (retval,0 ,"test_run" ); +timer_mim__detach (timer_skel); + +/* check that timer_cb[12] are incrementing 'cnt' */ + cnt1 =READ_ONCE (timer_skel->bss->cnt); +usleep (200 );/* 100 times more than interval */ + cnt2 =READ_ONCE (timer_skel->bss->cnt); +ASSERT_GT (cnt2, cnt1,"cnt" ); + +ASSERT_EQ (timer_skel->bss->err,0 ,"err" ); +/* check that code paths completed */ +ASSERT_EQ (timer_skel->bss->ok,1 |2 ,"ok" ); + +close (bpf_map__fd (timer_skel->maps.inner_htab)); + err =bpf_map_delete_elem (bpf_map__fd (timer_skel->maps.outer_arr), &key1); +ASSERT_EQ (err,0 ,"delete inner map" ); + +/* check that timer_cb[12] are no longer running */ + cnt1 =READ_ONCE (timer_skel->bss->cnt); +usleep (200 ); + cnt2 =READ_ONCE (timer_skel->bss->cnt); +ASSERT_EQ (cnt2, cnt1,"cnt" ); + +return 0 ; +} + +void test_timer_mim (void ) +{ +struct timer_mim_reject *timer_reject_skel =NULL ; +libbpf_print_fn_t old_print_fn =NULL ; +struct timer_mim *timer_skel =NULL ; +int err; + + old_print_fn =libbpf_set_print (NULL ); + timer_reject_skel =timer_mim_reject__open_and_load (); +libbpf_set_print (old_print_fn); +if (!ASSERT_ERR_PTR (timer_reject_skel,"timer_reject_skel_load" )) + goto cleanup; + + timer_skel =timer_mim__open_and_load (); +if (!ASSERT_OK_PTR (timer_skel,"timer_skel_load" )) + goto cleanup; + + err =timer_mim (timer_skel); +ASSERT_OK (err,"timer_mim" ); +cleanup: +timer_mim__destroy (timer_skel); +timer_mim_reject__destroy (timer_reject_skel); +}
tools/testing/selftests/bpf/progs/timer_mim.c new file +88 -0
88 lines not on this page · raw message
tools/testing/selftests/bpf/progs/timer_mim_reject.c new file +74 -0
74 lines not on this page · raw message
Signature · 1 line
2.30.2
This series was applied to bpf/bpf-next.git (refs/heads/master):
Hello:
This series was applied to bpf/bpf-next.git (refs/heads/master):
Quoted 15 lines · On Wed, 14 Jul 2021 17:54:06 -0700 you wrote:
From: Alexei Starovoitov <[email protected]>
The first request to support timers in bpf was made in 2013 before
sys_bpfsyscall was added. That use case was periodic sampling. It was address with attaching bpf programs toperf_events. Then during XDP development the timers were requested to do garbage collection and health checks. They were worked around by implementing timers in user space and triggering progs withBPF_PROG_RUNcommand. The user space timers and perf_event+bpf timers are not armed by the bpf program. They're done asynchronously vs program execution. The XDP program cannot send a packet and arm the timer at the same time. The tracing prog cannot record an event and arm the timer right away. This large class of use cases remained unaddressed. The jiffy based and hrtimer based timers are essential part of the kernel development and with this patch set the hrtimer based timers will be available to bpf programs.
Quoted 1 line
[...]
Here is the summary with links:
- [v7,bpf-next,01/11] bpf: Prepare bpf_prog_put() to be called from irq context.
https://git.kernel.org/bpf/bpf-next/c/d809e134be7a - [v7,bpf-next,02/11] bpf: Factor out bpf_spin_lock into helpers. https://git.kernel.org/bpf/bpf-next/c/c1b3fed319d3 - [v7,bpf-next,03/11] bpf: Introduce bpf timers. https://git.kernel.org/bpf/bpf-next/c/b00628b1c7d5 - [v7,bpf-next,04/11] bpf: Add map side support for bpf timers. https://git.kernel.org/bpf/bpf-next/c/68134668c17f - [v7,bpf-next,05/11] bpf: Prevent pointer mismatch in bpf_timer_init. https://git.kernel.org/bpf/bpf-next/c/3e8ce29850f1 - [v7,bpf-next,06/11] bpf: Remember BTF of inner maps. https://git.kernel.org/bpf/bpf-next/c/40ec00abf1cc - [v7,bpf-next,07/11] bpf: Relax verifier recursion check. https://git.kernel.org/bpf/bpf-next/c/86fc6ee6e246 - [v7,bpf-next,08/11] bpf: Implement verifier support for validation of async callbacks. https://git.kernel.org/bpf/bpf-next/c/bfc6bb74e4f1 - [v7,bpf-next,09/11] bpf: Teach stack depth check about async callbacks. https://git.kernel.org/bpf/bpf-next/c/7ddc80a476c2 - [v7,bpf-next,10/11] selftests/bpf: Add bpf_timer test. https://git.kernel.org/bpf/bpf-next/c/3540f7c6b96a - [v7,bpf-next,11/11] selftests/bpf: Add a test with bpf_timer in inner map. https://git.kernel.org/bpf/bpf-next/c/61f71e746c72
You are awesome, thank you!
--
Deet-doot-dot, I am a bot.
https://korg.docs.kernel.org/patchwork/pwbot.html