mbox series

[RFC,bpf-next,0/3] Execution context callbacks

Message ID cover.1657576063.git.delyank@fb.com (mailing list archive)
Headers show
Series Execution context callbacks | expand

Message

Delyan Kratunov July 11, 2022, 9:48 p.m. UTC
BPF developers are sometimes faced with surprising limitations of the execution context
their code runs in. NMI is particularly problematic though userspace data access as a whole
has come up as well (e.g. build id not being available).

This series adds bpf_delayed_work_submit which takes a callback function and a context pointer
and is able to execute the callback from (initially) a hardirq context.

This is an RFC to answer a few questions on direction:

1. Naming is intentionally bad and something I'd like to bikeshed a bit.
"bpf_(defer|submit)_work" was my first instinct but that has workqueue connotations in the kernel.

2. The callback arguments need to be in a map. We can currently express helper arguments taking a
pointer to a map value but not a pointer to _within_ a map value. Should we add a new argument
type or should we just pass the map value pointer to the callback?

3. A lot of the map handling code is verbatim from bpf_timer. This feels icky but I'm not sure if it
justifies a refactor quite yet. Opinions welcome.

4. This functionality is implemented as a single helper call (no matching bpf_delayed_work_init). In practice,
this means that we can't implement the map->usercnt check that bpf_timer_start performs to ensure the
map is referenced from userspace. However, given that a) we wait for pending work before releasing the
bpf_prog, b) the map will be in the bpf_prog's used_maps, and c) the map free path does not need to release
any external resources, and d) the bpf_delayed_work items bump the prog refcnt, I think we can keep this mechanism
a single call.

I'd like to get this right from the start, so do let me know if I'm missing potential execution
contexts that we can't really wait to drain from the bpf_prog free path.

5. This mechanism generalizes to other contexts (e.g., sleepable context on the way back to userspace
a-la set_thread_flag(TIF_UPROBE)), by means of adding the bpf_delayed_work items to other llist_heads.
E.g., we can keep the llist_heads in task_local_storage or in per-cpu structures. I can't think of
anything that requires a more complicated approach (or reserved space in the structs) but do let me
know if I'm wrong.

6. Lastly, the llist approach was dictated by the NMI constraints. RCU lists are out because they need
to synchronize_rcu when splicing from one head to another.

Thanks,
Delyan

Delyan Kratunov (3):
  bpf: allow maps to hold bpf_delayed_work fields
  bpf: add delayed_work mechanism
  selftests: delayed_work tests

 include/linux/bpf.h                           |  22 ++-
 include/linux/btf.h                           |   1 +
 include/uapi/linux/bpf.h                      |  36 +++++
 kernel/bpf/btf.c                              |  21 +++
 kernel/bpf/core.c                             |   8 ++
 kernel/bpf/helpers.c                          |  92 ++++++++++++
 kernel/bpf/syscall.c                          |  24 +++-
 kernel/bpf/verifier.c                         | 132 +++++++++++++++++-
 scripts/bpf_doc.py                            |   2 +
 tools/include/uapi/linux/bpf.h                |  35 +++++
 .../selftests/bpf/prog_tests/delayed_work.c   |  29 ++++
 .../selftests/bpf/progs/delayed_irqwork.c     |  59 ++++++++
 12 files changed, 457 insertions(+), 4 deletions(-)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/delayed_work.c
 create mode 100644 tools/testing/selftests/bpf/progs/delayed_irqwork.c

--
2.36.1

Comments

Stanislav Fomichev July 12, 2022, 6:07 p.m. UTC | #1
On 07/11, Delyan Kratunov wrote:
> BPF developers are sometimes faced with surprising limitations of the  
> execution context
> their code runs in. NMI is particularly problematic though userspace data  
> access as a whole
> has come up as well (e.g. build id not being available).

> This series adds bpf_delayed_work_submit which takes a callback function  
> and a context pointer
> and is able to execute the callback from (initially) a hardirq context.

> This is an RFC to answer a few questions on direction:

> 1. Naming is intentionally bad and something I'd like to bikeshed a bit.
> "bpf_(defer|submit)_work" was my first instinct but that has workqueue  
> connotations in the kernel.

> 2. The callback arguments need to be in a map. We can currently express  
> helper arguments taking a
> pointer to a map value but not a pointer to _within_ a map value. Should  
> we add a new argument
> type or should we just pass the map value pointer to the callback?

Passing map value pointer (as you do in the selftest) seems fine; do
you think we need more flexibility here?

> 3. A lot of the map handling code is verbatim from bpf_timer. This feels  
> icky but I'm not sure if it
> justifies a refactor quite yet. Opinions welcome.

+1, it does seem very close to a timer with expiry time == 0.

I don't know what's the exact usecase you're trying to solve exactly, but
have you though of maybe initially supporting something like:

bpf_timer_init(&timer, map, SOME_NEW_DEFERRED_NMI_ONLY_FLAG);
bpf_timer_set_callback(&timer, cg);
bpf_timer_start(&timer, 0, 0);

If you init a timer with that special flag, I'm assuming you can have
special cases in the existing helpers to simulate the delayed work?
Then, the verifier changes should be minimal it seems.

OTOH, having a separate set of helpers seems more clear API-wise :-/

> 4. This functionality is implemented as a single helper call (no matching  
> bpf_delayed_work_init). In practice,
> this means that we can't implement the map->usercnt check that  
> bpf_timer_start performs to ensure the
> map is referenced from userspace. However, given that a) we wait for  
> pending work before releasing the
> bpf_prog, b) the map will be in the bpf_prog's used_maps, and c) the map  
> free path does not need to release
> any external resources, and d) the bpf_delayed_work items bump the prog  
> refcnt, I think we can keep this mechanism
> a single call.

> I'd like to get this right from the start, so do let me know if I'm  
> missing potential execution
> contexts that we can't really wait to drain from the bpf_prog free path.

> 5. This mechanism generalizes to other contexts (e.g., sleepable context  
> on the way back to userspace
> a-la set_thread_flag(TIF_UPROBE)), by means of adding the  
> bpf_delayed_work items to other llist_heads.
> E.g., we can keep the llist_heads in task_local_storage or in per-cpu  
> structures. I can't think of
> anything that requires a more complicated approach (or reserved space in  
> the structs) but do let me
> know if I'm wrong.

> 6. Lastly, the llist approach was dictated by the NMI constraints. RCU  
> lists are out because they need
> to synchronize_rcu when splicing from one head to another.

> Thanks,
> Delyan

> Delyan Kratunov (3):
>    bpf: allow maps to hold bpf_delayed_work fields
>    bpf: add delayed_work mechanism
>    selftests: delayed_work tests

>   include/linux/bpf.h                           |  22 ++-
>   include/linux/btf.h                           |   1 +
>   include/uapi/linux/bpf.h                      |  36 +++++
>   kernel/bpf/btf.c                              |  21 +++
>   kernel/bpf/core.c                             |   8 ++
>   kernel/bpf/helpers.c                          |  92 ++++++++++++
>   kernel/bpf/syscall.c                          |  24 +++-
>   kernel/bpf/verifier.c                         | 132 +++++++++++++++++-
>   scripts/bpf_doc.py                            |   2 +
>   tools/include/uapi/linux/bpf.h                |  35 +++++
>   .../selftests/bpf/prog_tests/delayed_work.c   |  29 ++++
>   .../selftests/bpf/progs/delayed_irqwork.c     |  59 ++++++++
>   12 files changed, 457 insertions(+), 4 deletions(-)
>   create mode 100644 tools/testing/selftests/bpf/prog_tests/delayed_work.c
>   create mode 100644 tools/testing/selftests/bpf/progs/delayed_irqwork.c

> --
> 2.36.1
Delyan Kratunov July 12, 2022, 6:42 p.m. UTC | #2
Thanks for taking a look, Stanislav!

On Tue, 2022-07-12 at 11:07 -0700, sdf@google.com wrote:
> *snip*
> > 2. The callback arguments need to be in a map. We can currently express  
> > helper arguments taking a
> > pointer to a map value but not a pointer to _within_ a map value. Should  
> > we add a new argument
> > type or should we just pass the map value pointer to the callback?
> 
> Passing map value pointer (as you do in the selftest) seems fine; do
> you think we need more flexibility here?

I think it makes a cleaner and more familiar API - the pointer to my data that I give
to the submission function is the one I get in the callback. Requiring it to be a map
value is a little bit quirky (it's not really my data it's pointing to!). I don't
know if it's a lot of work in the verifier to iron out this quirk but if it's
reasonable, I'd be happy to make the developer experience a little more predictable.

> > 3. A lot of the map handling code is verbatim from bpf_timer. This feels  
> > icky but I'm not sure if it
> > justifies a refactor quite yet. Opinions welcome.
> 
> +1, it does seem very close to a timer with expiry time == 0.
> 
> I don't know what's the exact usecase you're trying to solve exactly,

The primary motivating examples are 1) GFP_ATOMIC usage is not safe in NMI aiui, so
switching allocations to hardirq helps and 2) copy_from_user in tracing programs (nmi
or softirq when using software clocks). The latter shows up in insidious ways like
build id not being reliable when retrieving stack traces ([1] is a thread from a
while ago about it).

> but have you though of maybe initially supporting something like:
> 
> bpf_timer_init(&timer, map, SOME_NEW_DEFERRED_NMI_ONLY_FLAG);
> bpf_timer_set_callback(&timer, cg);
> bpf_timer_start(&timer, 0, 0);
> 
> If you init a timer with that special flag, I'm assuming you can have
> special cases in the existing helpers to simulate the delayed work?

Potentially but I have some reservations about drawing this equivalence.

> Then, the verifier changes should be minimal it seems.
> 
> OTOH, having a separate set of helpers seems more clear API-wise :-/

The primary way this differs from timers is that timers already specify an execution
context - the callback will be called from a softirq. 

It doesn't make sense to me to have some "timers" (but only 0-delay, super-special
timers) run in hardirq or, more confusingly, user context. At that point, there's
little in the API to express these differences, (e.g., bpf_copy_from_user_task is
accessible in *this* callback) and the verifier work will be far more challenging (if
at all possible since the init and the set_callback would be split).

I think it's worth thinking about how to unify the handling of timer-like map value
members but I don't think it's worth it trying to shoehorn this functionality into
existing infra.

> *snip*

  [1]: https://lore.kernel.org/bpf/CA+khW7gh=vO8m-_SVnwWwj7kv+EDeUPcuWFqebf2Zmi9T_oEAQ@mail.gmail.com/
Stanislav Fomichev July 12, 2022, 10:51 p.m. UTC | #3
On 07/12, Delyan Kratunov wrote:
> Thanks for taking a look, Stanislav!

> On Tue, 2022-07-12 at 11:07 -0700, sdf@google.com wrote:
> > *snip*
> > > 2. The callback arguments need to be in a map. We can currently  
> express
> > > helper arguments taking a
> > > pointer to a map value but not a pointer to _within_ a map value.  
> Should
> > > we add a new argument
> > > type or should we just pass the map value pointer to the callback?
> >
> > Passing map value pointer (as you do in the selftest) seems fine; do
> > you think we need more flexibility here?

> I think it makes a cleaner and more familiar API - the pointer to my data  
> that I give
> to the submission function is the one I get in the callback. Requiring it  
> to be a map
> value is a little bit quirky (it's not really my data it's pointing to!).  
> I don't
> know if it's a lot of work in the verifier to iron out this quirk but if  
> it's
> reasonable, I'd be happy to make the developer experience a little more  
> predictable.

> > > 3. A lot of the map handling code is verbatim from bpf_timer. This  
> feels
> > > icky but I'm not sure if it
> > > justifies a refactor quite yet. Opinions welcome.
> >
> > +1, it does seem very close to a timer with expiry time == 0.
> >
> > I don't know what's the exact usecase you're trying to solve exactly,

> The primary motivating examples are 1) GFP_ATOMIC usage is not safe in  
> NMI aiui, so
> switching allocations to hardirq helps and 2) copy_from_user in tracing  
> programs (nmi
> or softirq when using software clocks). The latter shows up in insidious  
> ways like
> build id not being reliable when retrieving stack traces ([1] is a thread  
> from a
> while ago about it).

> > but have you though of maybe initially supporting something like:
> >
> > bpf_timer_init(&timer, map, SOME_NEW_DEFERRED_NMI_ONLY_FLAG);
> > bpf_timer_set_callback(&timer, cg);
> > bpf_timer_start(&timer, 0, 0);
> >
> > If you init a timer with that special flag, I'm assuming you can have
> > special cases in the existing helpers to simulate the delayed work?

> Potentially but I have some reservations about drawing this equivalence.

> > Then, the verifier changes should be minimal it seems.
> >
> > OTOH, having a separate set of helpers seems more clear API-wise :-/

> The primary way this differs from timers is that timers already specify  
> an execution
> context - the callback will be called from a softirq.�

> It doesn't make sense to me to have some "timers" (but only 0-delay,  
> super-special
> timers) run in hardirq or, more confusingly, user context. At that point,  
> there's
> little in the API to express these differences, (e.g.,  
> bpf_copy_from_user_task is
> accessible in *this* callback) and the verifier work will be far more  
> challenging (if
> at all possible since the init and the set_callback would be split).

> I think it's worth thinking about how to unify the handling of timer-like  
> map value
> members but I don't think it's worth it trying to shoehorn this  
> functionality into
> existing infra.

> > *snip*

>    [1]:  
> https://lore.kernel.org/bpf/CA+khW7gh=vO8m-_SVnwWwj7kv+EDeUPcuWFqebf2Zmi9T_oEAQ@mail.gmail.com/


All valid points. I'm assuming Alexei will take a closer look at this
eventually since I don't have a ton of context about timers :-(
Alexei Starovoitov July 15, 2022, 1:51 a.m. UTC | #4
On Tue, Jul 12, 2022 at 06:42:52PM +0000, Delyan Kratunov wrote:
> 
> > but have you though of maybe initially supporting something like:
> > 
> > bpf_timer_init(&timer, map, SOME_NEW_DEFERRED_NMI_ONLY_FLAG);
> > bpf_timer_set_callback(&timer, cg);
> > bpf_timer_start(&timer, 0, 0);
> > 
> > If you init a timer with that special flag, I'm assuming you can have
> > special cases in the existing helpers to simulate the delayed work?
> 
> Potentially but I have some reservations about drawing this equivalence.

hrtimer api has various: flags. soft vs hard irq, pinned and not.
So the suggestion to treat irq_work callback as special timer flag
actually fits well.

bpf_timer_init + set_callback + start can be a static inline function
named bpf_work_submit() in bpf_helpers.h
(or some new file that will mark the beginning libc-bpf library).
Reusing struct bpf_timer and adding zero-delay callback could probably be
easier for users to learn and consume.

Separately:
+struct bpf_delayed_work {
+       __u64 :64;
+       __u64 :64;
+       __u64 :64;
+       __u64 :64;
+       __u64 :64;
+} __attribute__((aligned(8)));
is not extensible.
It would be better to add indirection to allow kernel side to grow
independently from amount of space consumed in a map value.

Can you think of a way to make irq_work/sleepable callback independent of maps?
Assume bpf_mem_alloc is already available and NMI prog can allocate a typed object.
The usage could be:
struct my_work {
  int a;
  struct task_struct __kptr_ref *t;
};
void my_cb(struct my_work *w);

struct my_work *w = bpf_mem_alloc(allocator, bpf_core_type_id_local(*w));
w->t = ..;
bpf_submit_work(w, my_cb, SLEEPABLE | IRQ_WORK);

Am I day dreaming? :)
Delyan Kratunov July 15, 2022, 6:28 p.m. UTC | #5
On Thu, 2022-07-14 at 18:51 -0700, Alexei Starovoitov wrote:
> On Tue, Jul 12, 2022 at 06:42:52PM +0000, Delyan Kratunov wrote:
> > 
> > > but have you though of maybe initially supporting something like:
> > > 
> > > bpf_timer_init(&timer, map, SOME_NEW_DEFERRED_NMI_ONLY_FLAG);
> > > bpf_timer_set_callback(&timer, cg);
> > > bpf_timer_start(&timer, 0, 0);
> > > 
> > > If you init a timer with that special flag, I'm assuming you can have
> > > special cases in the existing helpers to simulate the delayed work?
> > 
> > Potentially but I have some reservations about drawing this equivalence.
> 
> hrtimer api has various: flags. soft vs hard irq, pinned and not.
> So the suggestion to treat irq_work callback as special timer flag
> actually fits well.
> 
> bpf_timer_init + set_callback + start can be a static inline function
> named bpf_work_submit() in bpf_helpers.h
> (or some new file that will mark the beginning libc-bpf library).
> Reusing struct bpf_timer and adding zero-delay callback could probably be
> easier for users to learn and consume.

To clarify, we're talking about 1) making bpf_timer nmi-safe for _some_ but not all
combinations of parameters and 2) adding new flags to specify an execution context?
It's achievable but it's hard to see how it's the superior solution here.

> 
> Separately:
> +struct bpf_delayed_work {
> +       __u64 :64;
> +       __u64 :64;
> +       __u64 :64;
> +       __u64 :64;
> +       __u64 :64;
> +} __attribute__((aligned(8)));
> is not extensible.
> It would be better to add indirection to allow kernel side to grow
> independently from amount of space consumed in a map value.

Fair point, I was wondering what to do with it - storing just a pointer sounds
reasonable.

> Can you think of a way to make irq_work/sleepable callback independent of maps?
> Assume bpf_mem_alloc is already available and NMI prog can allocate a typed object.
> The usage could be:
> struct my_work {
>   int a;
>   struct task_struct __kptr_ref *t;
> };
> void my_cb(struct my_work *w);
> 
> struct my_work *w = bpf_mem_alloc(allocator, bpf_core_type_id_local(*w));
> w->t = ..;
> bpf_submit_work(w, my_cb, SLEEPABLE | IRQ_WORK);
> 
> Am I day dreaming? :)

Nothing wrong with dreaming of a better future :) 

(I'm assuming you're thinking of bpf_mem_alloc being fronted by the allocator you
recently sent to the list.)

On a first pass, here are my concerns:

A program and its maps can guarantee a certain amount of storage for work items.
Sizing that storage is difficult but it is yours alone to use. The freelist allocator
can be transiently drained by other programs and starve you of this utility. This is
a new failure mode, so it's worth talking about.

With a generic allocator mechanism, we'll have a hard time enforcing the can't-load-
or-store-into-special-fields logic. I like that guardrail and I'm not sure how we'd
achieve the same guarantees. (In your snippet, we don't have the llist_node on the
work item - do we wrap my_work into something else internally? That would hide the
fields that need protecting at the expense of an extra bpf_mem_alloc allocation.)

Managing the storage returned from bpf_mem_alloc is of course also a concern. We'd
need to treat bpf_submit_work as "releasing" it (really, taking ownership). This path
means more lifecycle analysis in the verifier and explicit and implicit free()s.

I'm not opposed to it overall - the developer experience is very familiar - but I am
primarily worried that allocator failures will be in the same category of issues as
the hash map collisions for stacks. If you want reliability, you just don't use that
type of map - what's the alternative in this hypothetical bpf_mem_alloc future?

-- Delyan
Alexei Starovoitov July 19, 2022, 7:02 p.m. UTC | #6
On Fri, Jul 15, 2022 at 06:28:20PM +0000, Delyan Kratunov wrote:
> On Thu, 2022-07-14 at 18:51 -0700, Alexei Starovoitov wrote:
> > On Tue, Jul 12, 2022 at 06:42:52PM +0000, Delyan Kratunov wrote:
> > > 
> > > > but have you though of maybe initially supporting something like:
> > > > 
> > > > bpf_timer_init(&timer, map, SOME_NEW_DEFERRED_NMI_ONLY_FLAG);
> > > > bpf_timer_set_callback(&timer, cg);
> > > > bpf_timer_start(&timer, 0, 0);
> > > > 
> > > > If you init a timer with that special flag, I'm assuming you can have
> > > > special cases in the existing helpers to simulate the delayed work?
> > > 
> > > Potentially but I have some reservations about drawing this equivalence.
> > 
> > hrtimer api has various: flags. soft vs hard irq, pinned and not.
> > So the suggestion to treat irq_work callback as special timer flag
> > actually fits well.
> > 
> > bpf_timer_init + set_callback + start can be a static inline function
> > named bpf_work_submit() in bpf_helpers.h
> > (or some new file that will mark the beginning libc-bpf library).
> > Reusing struct bpf_timer and adding zero-delay callback could probably be
> > easier for users to learn and consume.
> 
> To clarify, we're talking about 1) making bpf_timer nmi-safe for _some_ but not all
> combinations of parameters and 2) adding new flags to specify an execution context?
> It's achievable but it's hard to see how it's the superior solution here.
> 
> > 
> > Separately:
> > +struct bpf_delayed_work {
> > +       __u64 :64;
> > +       __u64 :64;
> > +       __u64 :64;
> > +       __u64 :64;
> > +       __u64 :64;
> > +} __attribute__((aligned(8)));
> > is not extensible.
> > It would be better to add indirection to allow kernel side to grow
> > independently from amount of space consumed in a map value.
> 
> Fair point, I was wondering what to do with it - storing just a pointer sounds
> reasonable.
> 
> > Can you think of a way to make irq_work/sleepable callback independent of maps?
> > Assume bpf_mem_alloc is already available and NMI prog can allocate a typed object.
> > The usage could be:
> > struct my_work {
> >   int a;
> >   struct task_struct __kptr_ref *t;
> > };
> > void my_cb(struct my_work *w);
> > 
> > struct my_work *w = bpf_mem_alloc(allocator, bpf_core_type_id_local(*w));
> > w->t = ..;
> > bpf_submit_work(w, my_cb, SLEEPABLE | IRQ_WORK);
> > 
> > Am I day dreaming? :)
> 
> Nothing wrong with dreaming of a better future :) 
> 
> (I'm assuming you're thinking of bpf_mem_alloc being fronted by the allocator you
> recently sent to the list.)
> 
> On a first pass, here are my concerns:
> 
> A program and its maps can guarantee a certain amount of storage for work items.
> Sizing that storage is difficult but it is yours alone to use. The freelist allocator
> can be transiently drained by other programs and starve you of this utility. This is
> a new failure mode, so it's worth talking about.

That would be the issue only when progs deliberately share the allocator.
In this stmt:
struct my_work *w = bpf_mem_alloc(allocator, bpf_core_type_id_local(*w));
The 'allocator' can be unique for each prog or shared across few progs in the same .c file.
I wasn't planning to support one global allocator.
Just like one global hash map doesn't quite make sense.
The user has to create an allocator first, get it connected with memcg,
and use the explicit one in their bpf progs/maps.

> With a generic allocator mechanism, we'll have a hard time enforcing the can't-load-
> or-store-into-special-fields logic. I like that guardrail and I'm not sure how we'd
> achieve the same guarantees. (In your snippet, we don't have the llist_node on the
> work item - do we wrap my_work into something else internally? That would hide the
> fields that need protecting at the expense of an extra bpf_mem_alloc allocation.)

bpf_mem_alloc will return referenced PTR_TO_BTF_ID.
Every field in this structure is typed. So it's trivial for the verifier to make
some of them read only or not accesible at all.
'struct my_work' can have an explicit struct bpf_delayed_work field. Example:
struct my_work {
  struct bpf_delayed_work work; // not accessible by prog
  int a; // scalar read/write
  struct task_struct __kptr_ref *t;  // kptr semantics
};

> Managing the storage returned from bpf_mem_alloc is of course also a concern. We'd
> need to treat bpf_submit_work as "releasing" it (really, taking ownership). This path
> means more lifecycle analysis in the verifier and explicit and implicit free()s.

What is the actual concern?
bpf_submit_work will have clear "release" semantics. The verifier already supports it.
The 'my_cb' callback will receive reference PTR_TO_BTF_ID as well and would
have to release it with bpf_mem_free(ma, w).
Here is more complete proposal:

struct {
        __uint(type, BPF_MEM_ALLOC);
} allocator SEC(".maps");

struct my_work {
  struct bpf_delayed_work work;
  int a;
  struct task_struct __kptr_ref *t;
};

void my_cb(struct my_work *w)
{
  // access w
  bpf_mem_free(&allocator, w);
}

void bpf_prog(...)
{
  struct my_work *w = bpf_mem_alloc(&allocator, bpf_core_type_id_local(*w));
  w->t = ..;
  bpf_submit_work(w, my_cb, USE_IRQ_WORK);
}

> I'm not opposed to it overall - the developer experience is very familiar - but I am
> primarily worried that allocator failures will be in the same category of issues as
> the hash map collisions for stacks. If you want reliability, you just don't use that
> type of map - what's the alternative in this hypothetical bpf_mem_alloc future?

Reliability of allocation is certianly necessary.
bpf_mem_alloc will have an ability to _synchronously_ preallocate into freelist
from sleepable context, so bpf prog will have full control of that free list.
Delyan Kratunov July 19, 2022, 10:12 p.m. UTC | #7
On Tue, 2022-07-19 at 12:02 -0700, Alexei Starovoitov wrote:
> On Fri, Jul 15, 2022 at 06:28:20PM +0000, Delyan Kratunov wrote:
> > On Thu, 2022-07-14 at 18:51 -0700, Alexei Starovoitov wrote:
> > > On Tue, Jul 12, 2022 at 06:42:52PM +0000, Delyan Kratunov wrote:
> > > > 
> > > > > but have you though of maybe initially supporting something like:
> > > > > 
> > > > > bpf_timer_init(&timer, map, SOME_NEW_DEFERRED_NMI_ONLY_FLAG);
> > > > > bpf_timer_set_callback(&timer, cg);
> > > > > bpf_timer_start(&timer, 0, 0);
> > > > > 
> > > > > If you init a timer with that special flag, I'm assuming you can have
> > > > > special cases in the existing helpers to simulate the delayed work?
> > > > 
> > > > Potentially but I have some reservations about drawing this equivalence.
> > > 
> > > hrtimer api has various: flags. soft vs hard irq, pinned and not.
> > > So the suggestion to treat irq_work callback as special timer flag
> > > actually fits well.
> > > 
> > > bpf_timer_init + set_callback + start can be a static inline function
> > > named bpf_work_submit() in bpf_helpers.h
> > > (or some new file that will mark the beginning libc-bpf library).
> > > Reusing struct bpf_timer and adding zero-delay callback could probably be
> > > easier for users to learn and consume.
> > 
> > To clarify, we're talking about 1) making bpf_timer nmi-safe for _some_ but not all
> > combinations of parameters and 2) adding new flags to specify an execution context?
> > It's achievable but it's hard to see how it's the superior solution here.
> > 
> > > 
> > > Separately:
> > > +struct bpf_delayed_work {
> > > +       __u64 :64;
> > > +       __u64 :64;
> > > +       __u64 :64;
> > > +       __u64 :64;
> > > +       __u64 :64;
> > > +} __attribute__((aligned(8)));
> > > is not extensible.
> > > It would be better to add indirection to allow kernel side to grow
> > > independently from amount of space consumed in a map value.
> > 
> > Fair point, I was wondering what to do with it - storing just a pointer sounds
> > reasonable.
> > 
> > > Can you think of a way to make irq_work/sleepable callback independent of maps?
> > > Assume bpf_mem_alloc is already available and NMI prog can allocate a typed object.
> > > The usage could be:
> > > struct my_work {
> > >   int a;
> > >   struct task_struct __kptr_ref *t;
> > > };
> > > void my_cb(struct my_work *w);
> > > 
> > > struct my_work *w = bpf_mem_alloc(allocator, bpf_core_type_id_local(*w));
> > > w->t = ..;
> > > bpf_submit_work(w, my_cb, SLEEPABLE | IRQ_WORK);
> > > 
> > > Am I day dreaming? :)
> > 
> > Nothing wrong with dreaming of a better future :) 
> > 
> > (I'm assuming you're thinking of bpf_mem_alloc being fronted by the allocator you
> > recently sent to the list.)
> > 
> > On a first pass, here are my concerns:
> > 
> > A program and its maps can guarantee a certain amount of storage for work items.
> > Sizing that storage is difficult but it is yours alone to use. The freelist allocator
> > can be transiently drained by other programs and starve you of this utility. This is
> > a new failure mode, so it's worth talking about.
> 
> That would be the issue only when progs deliberately share the allocator.
> In this stmt:
> struct my_work *w = bpf_mem_alloc(allocator, bpf_core_type_id_local(*w));
> The 'allocator' can be unique for each prog or shared across few progs in the same .c file.
> I wasn't planning to support one global allocator.
> Just like one global hash map doesn't quite make sense.
> The user has to create an allocator first, get it connected with memcg,
> and use the explicit one in their bpf progs/maps.
> 
> > With a generic allocator mechanism, we'll have a hard time enforcing the can't-load-
> > or-store-into-special-fields logic. I like that guardrail and I'm not sure how we'd
> > achieve the same guarantees. (In your snippet, we don't have the llist_node on the
> > work item - do we wrap my_work into something else internally? That would hide the
> > fields that need protecting at the expense of an extra bpf_mem_alloc allocation.)
> 
> bpf_mem_alloc will return referenced PTR_TO_BTF_ID.
> Every field in this structure is typed. So it's trivial for the verifier to make
> some of them read only or not accesible at all.
> 'struct my_work' can have an explicit struct bpf_delayed_work field. Example:
> struct my_work {
>   struct bpf_delayed_work work; // not accessible by prog
>   int a; // scalar read/write
>   struct task_struct __kptr_ref *t;  // kptr semantics
> };

Sure, anything is possible, it's just more complexity and these checks are not
exactly easy to follow right now. 

Alternatively, we could do the classic allocator thing and allocate accounting space
before the pointer we return. Some magic flag could then expand the space enough to
use for submit_work. Some allocations would be bumped to a higher bucket but that's
okay because it would be conststent overhead for those allocation sites.

> 
> > Managing the storage returned from bpf_mem_alloc is of course also a concern. We'd
> > need to treat bpf_submit_work as "releasing" it (really, taking ownership). This path
> > means more lifecycle analysis in the verifier and explicit and implicit free()s.
> 
> What is the actual concern?
> bpf_submit_work will have clear "release" semantics. The verifier already supports it.
> The 'my_cb' callback will receive reference PTR_TO_BTF_ID as well and would
> have to release it with bpf_mem_free(ma, w).
> Here is more complete proposal:
> 
> struct {
>         __uint(type, BPF_MEM_ALLOC);
> } allocator SEC(".maps");

I like this, so long as we pre-allocate enough to submit more sleepable work
immediately - the first work item the program submits could then prefill more items.

For an even better experience, it would be great if we could specify in the map
definition the number of items of size X we'll need. If we give that lever to the
developer, they can then use it so they never have to orchestrate sleepable work to
call bpf_mem_prealloc explicitly.

> 
> struct my_work {
>   struct bpf_delayed_work work;
>   int a;
>   struct task_struct __kptr_ref *t;
> };
> 
> void my_cb(struct my_work *w)
> {
>   // access w
>   bpf_mem_free(&allocator, w);
> }
> 
> void bpf_prog(...)
> {
>   struct my_work *w = bpf_mem_alloc(&allocator, bpf_core_type_id_local(*w));
>   w->t = ..;
>   bpf_submit_work(w, my_cb, USE_IRQ_WORK);
> }
> 
> > I'm not opposed to it overall - the developer experience is very familiar - but I am
> > primarily worried that allocator failures will be in the same category of issues as
> > the hash map collisions for stacks. If you want reliability, you just don't use that
> > type of map - what's the alternative in this hypothetical bpf_mem_alloc future?
> 
> Reliability of allocation is certianly necessary.
> bpf_mem_alloc will have an ability to _synchronously_ preallocate into freelist
> from sleepable context, so bpf prog will have full control of that free list.

I think having the map initialized and prefilled on load and having sleepable work
from the first version of this mechanism becomes a requirement of this design. Having
the prefill requirements (number of items and size) on the map definition removes the
requirement to have sleepable work from day one.

How do you want to sequence this? Do you plan to do the work to expose bpf_mem_alloc
to programs as part of the initial series or as a later followup? 

-- Delyan
Alexei Starovoitov July 20, 2022, 12:54 a.m. UTC | #8
On Tue, Jul 19, 2022 at 10:12:57PM +0000, Delyan Kratunov wrote:
> On Tue, 2022-07-19 at 12:02 -0700, Alexei Starovoitov wrote:
> > On Fri, Jul 15, 2022 at 06:28:20PM +0000, Delyan Kratunov wrote:
> > > On Thu, 2022-07-14 at 18:51 -0700, Alexei Starovoitov wrote:
> > > > On Tue, Jul 12, 2022 at 06:42:52PM +0000, Delyan Kratunov wrote:
> > > > > 
> > > > > > but have you though of maybe initially supporting something like:
> > > > > > 
> > > > > > bpf_timer_init(&timer, map, SOME_NEW_DEFERRED_NMI_ONLY_FLAG);
> > > > > > bpf_timer_set_callback(&timer, cg);
> > > > > > bpf_timer_start(&timer, 0, 0);
> > > > > > 
> > > > > > If you init a timer with that special flag, I'm assuming you can have
> > > > > > special cases in the existing helpers to simulate the delayed work?
> > > > > 
> > > > > Potentially but I have some reservations about drawing this equivalence.
> > > > 
> > > > hrtimer api has various: flags. soft vs hard irq, pinned and not.
> > > > So the suggestion to treat irq_work callback as special timer flag
> > > > actually fits well.
> > > > 
> > > > bpf_timer_init + set_callback + start can be a static inline function
> > > > named bpf_work_submit() in bpf_helpers.h
> > > > (or some new file that will mark the beginning libc-bpf library).
> > > > Reusing struct bpf_timer and adding zero-delay callback could probably be
> > > > easier for users to learn and consume.
> > > 
> > > To clarify, we're talking about 1) making bpf_timer nmi-safe for _some_ but not all
> > > combinations of parameters and 2) adding new flags to specify an execution context?
> > > It's achievable but it's hard to see how it's the superior solution here.
> > > 
> > > > 
> > > > Separately:
> > > > +struct bpf_delayed_work {
> > > > +       __u64 :64;
> > > > +       __u64 :64;
> > > > +       __u64 :64;
> > > > +       __u64 :64;
> > > > +       __u64 :64;
> > > > +} __attribute__((aligned(8)));
> > > > is not extensible.
> > > > It would be better to add indirection to allow kernel side to grow
> > > > independently from amount of space consumed in a map value.
> > > 
> > > Fair point, I was wondering what to do with it - storing just a pointer sounds
> > > reasonable.
> > > 
> > > > Can you think of a way to make irq_work/sleepable callback independent of maps?
> > > > Assume bpf_mem_alloc is already available and NMI prog can allocate a typed object.
> > > > The usage could be:
> > > > struct my_work {
> > > >   int a;
> > > >   struct task_struct __kptr_ref *t;
> > > > };
> > > > void my_cb(struct my_work *w);
> > > > 
> > > > struct my_work *w = bpf_mem_alloc(allocator, bpf_core_type_id_local(*w));
> > > > w->t = ..;
> > > > bpf_submit_work(w, my_cb, SLEEPABLE | IRQ_WORK);
> > > > 
> > > > Am I day dreaming? :)
> > > 
> > > Nothing wrong with dreaming of a better future :) 
> > > 
> > > (I'm assuming you're thinking of bpf_mem_alloc being fronted by the allocator you
> > > recently sent to the list.)
> > > 
> > > On a first pass, here are my concerns:
> > > 
> > > A program and its maps can guarantee a certain amount of storage for work items.
> > > Sizing that storage is difficult but it is yours alone to use. The freelist allocator
> > > can be transiently drained by other programs and starve you of this utility. This is
> > > a new failure mode, so it's worth talking about.
> > 
> > That would be the issue only when progs deliberately share the allocator.
> > In this stmt:
> > struct my_work *w = bpf_mem_alloc(allocator, bpf_core_type_id_local(*w));
> > The 'allocator' can be unique for each prog or shared across few progs in the same .c file.
> > I wasn't planning to support one global allocator.
> > Just like one global hash map doesn't quite make sense.
> > The user has to create an allocator first, get it connected with memcg,
> > and use the explicit one in their bpf progs/maps.
> > 
> > > With a generic allocator mechanism, we'll have a hard time enforcing the can't-load-
> > > or-store-into-special-fields logic. I like that guardrail and I'm not sure how we'd
> > > achieve the same guarantees. (In your snippet, we don't have the llist_node on the
> > > work item - do we wrap my_work into something else internally? That would hide the
> > > fields that need protecting at the expense of an extra bpf_mem_alloc allocation.)
> > 
> > bpf_mem_alloc will return referenced PTR_TO_BTF_ID.
> > Every field in this structure is typed. So it's trivial for the verifier to make
> > some of them read only or not accesible at all.
> > 'struct my_work' can have an explicit struct bpf_delayed_work field. Example:
> > struct my_work {
> >   struct bpf_delayed_work work; // not accessible by prog
> >   int a; // scalar read/write
> >   struct task_struct __kptr_ref *t;  // kptr semantics
> > };
> 
> Sure, anything is possible, it's just more complexity and these checks are not
> exactly easy to follow right now. 
> 
> Alternatively, we could do the classic allocator thing and allocate accounting space
> before the pointer we return. Some magic flag could then expand the space enough to
> use for submit_work. Some allocations would be bumped to a higher bucket but that's
> okay because it would be conststent overhead for those allocation sites.

Technically we can, but that would be a departure from what we already do.
bpf_spin_lock, bpf_timer, __kptr are normal part of struct-s with different access
restrictions. 'struct bpf_delayed_work' shouldn't be any different.

Another approach would be to let bpf prog allocate 'struct my_work' without
any special fields. Then use nmi-safe allocator inside bpf_submit_work, hide
it completely from bpf side and auto-free after callback is done.
But extra alloc is a performance hit and overall it will be an unusual hack.

May be we can allow bpf_submit_work() to work with referenced ptr_to_btf_id
like above and with normal map value similar to what you've implemented?
We would need to somehow make sure that container_of() operation to cast from
&work either to allocated ptr_to_btf_id or to map value works in both cases.
That would be the most flexible solution and will resemble kernel programming
style the best.

> > 
> > > Managing the storage returned from bpf_mem_alloc is of course also a concern. We'd
> > > need to treat bpf_submit_work as "releasing" it (really, taking ownership). This path
> > > means more lifecycle analysis in the verifier and explicit and implicit free()s.
> > 
> > What is the actual concern?
> > bpf_submit_work will have clear "release" semantics. The verifier already supports it.
> > The 'my_cb' callback will receive reference PTR_TO_BTF_ID as well and would
> > have to release it with bpf_mem_free(ma, w).
> > Here is more complete proposal:
> > 
> > struct {
> >         __uint(type, BPF_MEM_ALLOC);
> > } allocator SEC(".maps");
> 
> I like this, so long as we pre-allocate enough to submit more sleepable work
> immediately - the first work item the program submits could then prefill more items.
> 
> For an even better experience, it would be great if we could specify in the map
> definition the number of items of size X we'll need. If we give that lever to the
> developer, they can then use it so they never have to orchestrate sleepable work to
> call bpf_mem_prealloc explicitly.

Agree. That's the idea. Will work on it.

> 
> > 
> > struct my_work {
> >   struct bpf_delayed_work work;
> >   int a;
> >   struct task_struct __kptr_ref *t;
> > };
> > 
> > void my_cb(struct my_work *w)
> > {
> >   // access w
> >   bpf_mem_free(&allocator, w);
> > }
> > 
> > void bpf_prog(...)
> > {
> >   struct my_work *w = bpf_mem_alloc(&allocator, bpf_core_type_id_local(*w));
> >   w->t = ..;
> >   bpf_submit_work(w, my_cb, USE_IRQ_WORK);
> > }
> > 
> > > I'm not opposed to it overall - the developer experience is very familiar - but I am
> > > primarily worried that allocator failures will be in the same category of issues as
> > > the hash map collisions for stacks. If you want reliability, you just don't use that
> > > type of map - what's the alternative in this hypothetical bpf_mem_alloc future?
> > 
> > Reliability of allocation is certianly necessary.
> > bpf_mem_alloc will have an ability to _synchronously_ preallocate into freelist
> > from sleepable context, so bpf prog will have full control of that free list.
> 
> I think having the map initialized and prefilled on load and having sleepable work
> from the first version of this mechanism becomes a requirement of this design. Having
> the prefill requirements (number of items and size) on the map definition removes the
> requirement to have sleepable work from day one.

I'm not sure why 'sleepable' is a requirement. irq_work will be able to do
synchronous prefill with GFP_NOWAIT. sleepable callback will be able to do
synchronous prefill with GFP_KERNEL. There is a difference, of course,
but it's not a blocker.

> How do you want to sequence this? Do you plan to do the work to expose bpf_mem_alloc
> to programs as part of the initial series or as a later followup? 

Currently thinking as a follow up.
If you have cycles maybe you can help ?
bpf_mem_alloc/free internals are tested and usable already. prefill is not implemented yet.
But the work to do bpf_mem_alloc helper and to expose allocator as a special kind of map
can start already.