Re: [PATCH bpf-next 2/3] bpf: selftests: Add bpf_assert_if() and bpf_assert_with_if() macros

From: Alexei Starovoitov
Date: Thu Dec 14 2023 - 21:46:45 EST


On Thu, Dec 14, 2023 at 2:56 PM Daniel Xu <dxu@xxxxxxxxx> wrote:
>
> These macros are a temporary stop-gap until bpf exceptions support
> unwinding acquired entities. Basically these macros act as if they take
> a callback which only get executed if the assertion fails.
>
> Signed-off-by: Daniel Xu <dxu@xxxxxxxxx>
> ---
> .../testing/selftests/bpf/bpf_experimental.h | 22 +++++++++++++++++++
> 1 file changed, 22 insertions(+)
>
> diff --git a/tools/testing/selftests/bpf/bpf_experimental.h b/tools/testing/selftests/bpf/bpf_experimental.h
> index 1386baf9ae4a..d63f415bef26 100644
> --- a/tools/testing/selftests/bpf/bpf_experimental.h
> +++ b/tools/testing/selftests/bpf/bpf_experimental.h
> @@ -263,6 +263,17 @@ extern void bpf_throw(u64 cookie) __ksym;
> */
> #define bpf_assert(cond) if (!(cond)) bpf_throw(0);
>
> +/* Description
> + * Assert that a conditional expression is true. If false, runs code in the
> + * body before throwing.
> + * Returns
> + * Void.
> + * Throws
> + * An exception with the value zero when the assertion fails.
> + */
> +#define bpf_assert_if(cond) \
> + for (int ___i = 0, ___j = !!(cond); !(___j) && !___i; bpf_throw(0), ___i++)

Kumar,

Is this approach reliable?
I suspect the compiler can still optimize it.
I feel it will be annoying to clean up if folks start using it now,
since there won't be a drop in replacement.
Every such bpf_assert_if() would need to be manually patched.

If 2nd part of exception is far, how about we add an equivalent
of __bpf_assert() macroses with conditional ops in asm,
but with extra 'asm volatile goto' that can be used to construct
release of resources.

bpf_do_assert_eq(var1, 0) { bpf_spin_unlock(...); }
bpf_do_assert_lt(var2, 0) { bpf_spin_unlock(...); }