bpf: Add bpf_loop helper
authorJoanne Koong <joannekoong@fb.com>
Tue, 30 Nov 2021 03:06:19 +0000 (19:06 -0800)
committerAlexei Starovoitov <ast@kernel.org>
Tue, 30 Nov 2021 18:56:28 +0000 (10:56 -0800)
commite6f2dd0f80674e9d5960337b3e9c2a242441b326
tree7d12129dc88e27c9c92dfde465d517c033741b34
parent88691e9e1ef59fa917b2bc2df47d550e7635e73c
bpf: Add bpf_loop helper

This patch adds the kernel-side and API changes for a new helper
function, bpf_loop:

long bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
u64 flags);

where long (*callback_fn)(u32 index, void *ctx);

bpf_loop invokes the "callback_fn" **nr_loops** times or until the
callback_fn returns 1. The callback_fn can only return 0 or 1, and
this is enforced by the verifier. The callback_fn index is zero-indexed.

A few things to please note:
~ The "u64 flags" parameter is currently unused but is included in
case a future use case for it arises.
~ In the kernel-side implementation of bpf_loop (kernel/bpf/bpf_iter.c),
bpf_callback_t is used as the callback function cast.
~ A program can have nested bpf_loop calls but the program must
still adhere to the verifier constraint of its stack depth (the stack depth
cannot exceed MAX_BPF_STACK))
~ Recursive callback_fns do not pass the verifier, due to the call stack
for these being too deep.
~ The next patch will include the tests and benchmark

Signed-off-by: Joanne Koong <joannekoong@fb.com>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Acked-by: Andrii Nakryiko <andrii@kernel.org>
Link: https://lore.kernel.org/bpf/20211130030622.4131246-2-joannekoong@fb.com
include/linux/bpf.h
include/uapi/linux/bpf.h
kernel/bpf/bpf_iter.c
kernel/bpf/helpers.c
kernel/bpf/verifier.c
tools/include/uapi/linux/bpf.h